@runtypelabs/persona 4.26.0 → 4.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/approval-ui.d.cts +6 -0
  2. package/dist/approval-ui.d.ts +6 -0
  3. package/dist/artifacts-ui.d.cts +6 -0
  4. package/dist/artifacts-ui.d.ts +6 -0
  5. package/dist/chunk-GKPCIQPB.js +1 -0
  6. package/dist/{client-history-YPEG45Q4.js → client-history-GOZWBDA5.js} +1 -1
  7. package/dist/client-history.js +1 -1
  8. package/dist/codegen.cjs +1 -1
  9. package/dist/codegen.js +1 -1
  10. package/dist/context-mentions.d.cts +6 -0
  11. package/dist/context-mentions.d.ts +6 -0
  12. package/dist/event-stream-view.d.cts +6 -0
  13. package/dist/event-stream-view.d.ts +6 -0
  14. package/dist/forms-ui.d.cts +6 -0
  15. package/dist/forms-ui.d.ts +6 -0
  16. package/dist/index.cjs +7 -7
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +6 -0
  19. package/dist/index.d.ts +6 -0
  20. package/dist/index.global.js +1 -1
  21. package/dist/index.global.js.map +1 -1
  22. package/dist/index.js +7 -7
  23. package/dist/index.js.map +1 -1
  24. package/dist/session-reconnect.d.cts +6 -0
  25. package/dist/session-reconnect.d.ts +6 -0
  26. package/dist/smart-dom-reader.d.cts +6 -0
  27. package/dist/smart-dom-reader.d.ts +6 -0
  28. package/dist/theme-editor-preview.cjs +14 -14
  29. package/dist/theme-editor-preview.d.cts +6 -0
  30. package/dist/theme-editor-preview.d.ts +6 -0
  31. package/dist/theme-editor-preview.js +5 -5
  32. package/dist/theme-editor.d.cts +6 -0
  33. package/dist/theme-editor.d.ts +6 -0
  34. package/dist/voice-runtime-XLU6YK2N.js +17 -0
  35. package/dist/voice-runtime.cjs +3 -3
  36. package/dist/voice-runtime.d.cts +6 -0
  37. package/dist/voice-runtime.d.ts +6 -0
  38. package/dist/voice-runtime.js +3 -3
  39. package/package.json +1 -1
  40. package/src/approval-paused-tool-settle.test.ts +108 -4
  41. package/src/session.ts +51 -10
  42. package/src/session.voice.test.ts +1 -0
  43. package/src/types.ts +6 -0
  44. package/src/voice/runtype-voice-provider.ts +19 -9
  45. package/src/voice/voice-delegation.ts +1 -1
  46. package/src/voice/voice.test.ts +81 -2
  47. package/dist/chunk-QPPJUSZH.js +0 -1
  48. package/dist/voice-runtime-UOQOFAFY.js +0 -17
@@ -4,12 +4,12 @@
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()=>{}}},Bl=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},QC=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},JC=()=>{let e=AL();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)}},ZC=()=>{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,xa.parse)(n,xa.STR|xa.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?KC(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=KC(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ew=()=>{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 Ls,eg,Dl,Sa,ML,TL,nw,ow,EL,kL,LL,PL,IL,tg,ng,rw,og,sw,HL,RL,tw,iw,Mi,rg,Aa,Ol,WL,BL,DL,aw,OL,_L,NL,lw,FL,VL,Ti,cw,No,$L,Ma,Ps,UL,zL,pp,dw,pw,sg,qL,jL,uw,Ei,ig,Is,up,fp=ie(()=>{"use strict";Ls=require("partial-json");Ye();eg="ask_user_question",Dl=8,Sa="data-persona-ask-sheet-for",ML="Other",TL="Other\u2026",nw="Type your own answer here",ow="Send",EL="Next",kL="Back",LL="Submit all",PL="Skip",IL=3,tg="data-ask-current-index",ng="data-ask-question-count",rw="data-ask-answers",og="data-ask-grouped",sw="data-ask-layout",HL=e=>e.layout==="pills"?"pills":"rows",RL=e=>e.getAttribute(sw)==="pills"?"pills":"rows",tw=!1,iw=e=>e.replace(/["\\]/g,"\\$&"),Mi=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===eg,rg=e=>e?.features?.askUserQuestion??{},Aa=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,Ls.parse)(r,Ls.STR|Ls.OBJ|Ls.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ol=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Dl&&!tw&&(tw=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Dl}.`)),t.slice(0,Dl)},WL=e=>Ol(e)[0]??null,BL=(e,t)=>Ol(e)[t]??null,DL=(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))},aw=(e,t,n)=>{if(e!=="rows")return null;let o=C("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=C("span","persona-ask-row-check");o.appendChild(r)}else{let r=C("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},OL=(e,t,n,o)=>{let s=C("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=C("span","persona-ask-row-content"),l=C("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let d=C("span","persona-ask-row-description");d.textContent=e.description,i.appendChild(d)}s.appendChild(i);let c=aw(n,o,t);c&&s.appendChild(c)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},_L=e=>{let n=C("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},NL=(e,t,n,o)=>{let s=C("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(p=>p&&typeof p.label=="string"&&p.label.length>0);if(c.length===0&&!n){for(let p=0;p<IL;p++)s.appendChild(_L(o));return s}if(c.forEach((p,f)=>{s.appendChild(OL(p,f,o,i))}),e?.allowFreeText!==!1){let p=o==="rows"?ML:TL;if(o==="rows"){let f=C("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(c.length)),f.setAttribute("data-ask-other-row","true");let m=C("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??nw,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??p),m.appendChild(g),f.appendChild(m);let h=aw(o,i,c.length);h&&f.appendChild(h),s.appendChild(f)}else{let f=C("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??p,s.appendChild(f)}}return s},lw=(e,t)=>{let o=C("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??nw,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=C("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??ow,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},FL=e=>{let t=C("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=C("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??ow,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},VL=(e,t,n)=>{let o=C("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=C("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??kL,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=C("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=C("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??PL,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=C("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let c=e===t-1;return l.textContent=c?n.submitAllLabel??LL:n.nextLabel??EL,l.setAttribute("data-ask-user-action",c?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ti=e=>{let t=e.getAttribute(rw);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cw=(e,t)=>{e.setAttribute(rw,JSON.stringify(t))},No=e=>{let t=Number(e.getAttribute(tg)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},$L=(e,t)=>{e.setAttribute(tg,String(Math.max(0,Math.floor(t))))},Ma=e=>{let t=Number(e.getAttribute(ng)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ps=e=>e.getAttribute(og)==="true",UL=(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},zL=(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)))},pp=(e,t)=>{let{payload:n}=Aa(t),o=Ol(n),r=Ti(e),s={},i=new Set;return o.forEach((l,c)=>{let d=typeof l?.question=="string"?l.question:"";d&&(i.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),i.add(d),Object.prototype.hasOwnProperty.call(r,c)&&(s[d]=r[c]))}),s},dw=e=>{let t=Ti(e),n=No(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 d=c.getAttribute("data-option-label")??"",p=r.has(d);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});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="")},pw=e=>{if(!Ps(e))return;let t=Ti(e),n=No(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}},sg=(e,t,n)=>{let o=rg(n),r=RL(e),{payload:s,complete:i}=Aa(t),l=Ps(e),c=No(e),d=Ma(e),p=l?BL(s,c):WL(s),f=!!p?.multiSelect,m=e.querySelector('[data-ask-step-inline="true"]');m&&(m.textContent=l?`${c+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let S=typeof p?.question=="string"?p.question:"";h.textContent=S,h.classList.toggle("persona-ask-question-skeleton",!S&&!i)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let S=NL(p,o,i,r);b.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(lw(o,r))}let x=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!x?e.appendChild(FL(o)):(!f||l)&&x&&x.remove(),e.setAttribute("data-multi-select",f?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=VL(c,d,o);A?A.replaceWith(S):e.appendChild(S)}else A&&A.remove();dw(e),pw(e)},qL=(e,t,n)=>{let o=rg(t),r=HL(o),s=e.toolCall.id,i=Ol(n),l=Math.max(1,i.length),c=l>1,d=UL(e,i),p=c?zL(e,l):0,f=C("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sa,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(ng,String(l)),f.setAttribute(tg,String(p)),f.setAttribute(og,c?"true":"false"),f.setAttribute(sw,r),cw(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),DL(f,o);let m=C("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=C("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",m.appendChild(g);let h=C("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",m.appendChild(h),f.appendChild(m);let x=C("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 x.setAttribute("data-ask-pill-list","true"),x.setAttribute("role","group"),f.appendChild(x),r!=="rows"&&f.appendChild(lw(o,r)),sg(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},jL=(e,t,n)=>{let{payload:o}=Aa(t),r=Math.max(1,Ol(o).length);r>Ma(e)&&(e.setAttribute(ng,String(r)),r>1&&!Ps(e)&&e.setAttribute(og,"true")),sg(e,t,n)},uw=(e,t,n)=>{if(!n||!Mi(e)||rg(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sa}]`).forEach(d=>{d.getAttribute(Sa)!==r&&d.remove()});let i=n.querySelector(`[${Sa}="${iw(r)}"]`);if(i){jL(i,e,t);return}let{payload:l}=Aa(e),c=qL(e,t,l);n.appendChild(c)},Ei=(e,t)=>{if(!e)return;let n=t?`[${Sa}="${iw(t)}"]`:`[${Sa}]`;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)})},ig=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),Is=(e,t)=>{let n=Ti(e),o=No(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,cw(e,n),dw(e),pw(e)},up=(e,t,n,o)=>{let r=Ma(e),s=Math.max(0,Math.min(r-1,o));$L(e,s),sg(e,t,n)}});var Yr,KL,mw,gw,_l,GL,hw,fw,YL,Hs,Nl=ie(()=>{"use strict";Yr="suggest_replies",KL={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},mw={name:Yr,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:KL,origin:"sdk",annotations:{readOnlyHint:!0}},gw=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_l=e=>e.variant==="tool"&&e.toolCall?.name===Yr,GL=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},hw=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!_l(n))continue;let o=GL(n.toolCall?.args);return o.length>0?o:null}return null},fw=new Set,YL=(e,t,n)=>{let o=`${e}:${t}:${n}`;fw.has(o)||(fw.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Hs=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&&YL(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 XL,QL,Fl,ag=ie(()=>{"use strict";fp();Nl();XL={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Dl,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},QL={name:eg,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:XL,origin:"sdk",annotations:{readOnlyHint:!0}},Fl=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(QL),Hs(e).expose&&t.push(mw),t}});var Cn,Jn,Ta,mp,nr=ie(()=>{"use strict";Cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Jn=1e5,Ta=Jn+1,mp="https://api.runtype.com"});async function yw(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=(d,p)=>fetch(`${e.clientApiBase()}${d}`,{method:"POST",headers:o,body:JSON.stringify({...p,...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 d=await c.clone().json().catch(()=>null);if(!d||d.error==="Not Found")return s(i)}return c}async function bw(e,t,n,o){let r=e.isClientTokenMode(),s=r?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||mp}/resume`,i,l=null;if(r){let p=await e.initSession();i=p.sessionId,p.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 d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0,...o?.after?{after:o.after}:{}};if(i&&(d.sessionId=i),r&&i){let p=[...Fl(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:f,commit:m}=await e.sendWithClientToolsDiff(i,p,g=>{let h={...d,...g};return e.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(s,{method:"POST",headers:c,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return f.ok&&m(),f}return fetch(s,{method:"POST",headers:c,body:JSON.stringify(d),signal:o?.signal})}var vw=ie(()=>{"use strict";ag();nr()});var xw={};En(xw,{preferFinalStructuredContent:()=>ww,resolveApproval:()=>yw,resumeFlow:()=>bw,streamResponse:()=>eP});function JL(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 ww(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=Cw(n);if(!Cw(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=Bl(e);return Bl(t)!==null&&i===null?t:e}async function ZL(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=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return o.current=f,r(f),f},d=p=>o.current?o.current:c(p);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 p=d(l.partId);l.partId!==void 0&&!p.partId&&(p.partId=l.partId),p.content+=l.text,r(p)}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 eP(e,t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",c=Date.now(),d=0,p=()=>c+d++,f=j=>{let R=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,K=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,ee=j.tools?j.tools.map(X=>({...X,chunks:X.chunks?[...X.chunks]:void 0})):void 0;return{...j,reasoning:R,toolCall:K,tools:ee}},m=j=>{if(j.role!=="assistant"||j.variant)return!0;let R=Array.isArray(j.contentParts)&&j.contentParts.length>0,K=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||R||K||!!j.stopReason},g=j=>{m(j)&&n({type:"message",message:f(j)})},h=null,b=null,x={current:null},A={current:null},S=null,E="",k=new Map,D=new Map,$=new Map,J=new Map,T=new Map,W=o,P=!1,v=()=>{if(h)return h;let j,R="",K=S;return!P&&W?(j=W,P=!0,R=r??""):W&&K?j=`${W}_${K}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:j,role:"assistant",content:R,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(h),h},w=j=>{let R=J.get(j);if(R)return R;let K={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:j,status:"streaming",chunks:[]}};return J.set(j,K),g(K),K},L=new Set,I=new Map,Y=new Set,_=new Map,q=j=>{if(!j)return!1;let R=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return R==="emit_artifact_markdown"||R==="emit_artifact_component"},Z=j=>{let R=T.get(j);if(R)return R;let K={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:j,status:"pending"}};return T.set(j,K),g(K),K},ne=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let R=Number(j);if(!Number.isNaN(R)&&Number.isFinite(R))return R;let K=Date.parse(j);if(!Number.isNaN(K))return K}return Date.now()},te=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},re=new Map,pe=new Map,xe=(j,R)=>{let K=te(R),ee=pe.get(j.id),X=ww(ee,K);j.rawContent=X;let le=re.get(j.id),Me=qe=>{let nt=j.content??"";qe.trim()!==""&&(nt.trim().length===0||qe.startsWith(nt)||qe.trimStart().startsWith(nt.trim()))&&(j.content=qe)},Le=()=>{if(le){let qe=le.close?.();qe instanceof Promise&&qe.catch(()=>{})}re.delete(j.id),pe.delete(j.id),j.streaming=!1,g(j)};if(!le){Me(K),Le();return}let Ne=Bl(X);if(Ne!==null&&Ne.trim()!==""){Me(Ne),Le();return}let lt=qe=>{let nt=typeof qe=="string"?qe:qe?.text??null;if(nt!==null&&nt.trim()!=="")return nt;let Ut=le.getExtractedText();return Ut!==null&&Ut.trim()!==""?Ut:K},At;try{At=le.processChunk(X)}catch{Me(K),Le();return}if(At instanceof Promise){At.then(qe=>{Me(lt(qe)),Le()}).catch(()=>{Me(K),Le()});return}Me(lt(At)),Le()},Se=null,se=(j,R,K,ee)=>{j.rawContent=R,re.has(j.id)||re.set(j.id,e.createStreamParser());let X=re.get(j.id),le=R.trim().startsWith("{")||R.trim().startsWith("[");if(le&&pe.set(j.id,R),X.__isPlainTextParser===!0){j.content=ee!==void 0?R:j.content+K,pe.delete(j.id),re.delete(j.id),j.rawContent=void 0,g(j);return}let Le=X.processChunk(R);if(Le instanceof Promise)Le.then(Ne=>{let lt=typeof Ne=="string"?Ne:Ne?.text??null;lt!==null&&lt.trim()!==""?(j.content=lt,g(j)):!le&&!R.trim().startsWith("<")&&(j.content=ee!==void 0?R:j.content+K,pe.delete(j.id),re.delete(j.id),j.rawContent=void 0,g(j))}).catch(()=>{j.content=ee!==void 0?R:j.content+K,pe.delete(j.id),re.delete(j.id),j.rawContent=void 0,g(j)});else{let Ne=typeof Le=="string"?Le:Le?.text??null;Ne!==null&&Ne.trim()!==""?(j.content=Ne,g(j)):!le&&!R.trim().startsWith("<")&&(j.content=ee!==void 0?R:j.content+K,pe.delete(j.id),re.delete(j.id),j.rawContent=void 0,g(j))}},N=(j,R)=>{let K=R??j.content;if(K==null||K===""){j.streaming=!1,g(j);return}let X=pe.get(j.id)??te(K);j.rawContent=X;let le=re.get(j.id),Me=null,Le=!1;if(le&&(Me=le.getExtractedText(),Me===null&&(Me=Bl(X)),Me===null)){let Ne=le.processChunk(X);Ne instanceof Promise?(Le=!0,Ne.then(lt=>{let At=typeof lt=="string"?lt:lt?.text??null;At!==null&&(j.content=At,j.streaming=!1,re.delete(j.id),pe.delete(j.id),g(j))}).catch(()=>{})):Me=typeof Ne=="string"?Ne:Ne?.text??null}if(!Le){Me!==null&&Me.trim()!==""?j.content=Me:pe.has(j.id)||(j.content=te(K));let Ne=re.get(j.id);if(Ne){let lt=Ne.close?.();lt instanceof Promise&&lt.catch(()=>{}),re.delete(j.id)}pe.delete(j.id),j.streaming=!1,g(j)}},Ee=(j,R,K)=>{let ee=D.get(j);if(ee)return ee;let X={id:`nested-${R}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...K?{variant:K}:{},...K==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:R}};return D.set(j,X),g(X),X},de=[],Ge,Pt=new Map,St=0,ut="agent",tt=!1,gt=null,Pe=null,Fe=e.config().iterationDisplay??"separate";for(Ge=()=>{for(let j=0;j<de.length;j++){let R=de[j];if(!tt&&ut!=="flow"&&typeof R.stepType=="string"&&(ut="flow"),R.type==="reasoning_start"){let K=typeof R.id=="string"?R.id:null,ee=typeof R.parentToolCallId=="string"&&R.parentToolCallId?R.parentToolCallId:null;if(K&&ee){k.set(K,ee),Ee(K,ee,"reasoning");continue}let X=R.id,le=w(X);le.reasoning=le.reasoning??{id:X,status:"streaming",chunks:[]},le.reasoning.startedAt=le.reasoning.startedAt??Date.now(),le.reasoning.completedAt=void 0,le.reasoning.durationMs=void 0,(R.scope==="loop"||R.scope==="turn")&&(le.reasoning.scope=R.scope),le.streaming=!0,le.reasoning.status="streaming",g(le)}else if(R.type==="reasoning_delta"){let K=typeof R.id=="string"?R.id:null;if(K&&k.has(K)&&D.has(K)){let le=D.get(K),Me=R.delta;Me&&le.reasoning&&(le.reasoning.chunks.push(String(Me)),g(le));continue}let ee=R.id,X=w(ee);X.reasoning=X.reasoning??{id:ee,status:"streaming",chunks:[]},X.reasoning.startedAt=X.reasoning.startedAt??Date.now(),R.delta&&X.reasoning.chunks.push(R.delta),X.reasoning.status="streaming",X.streaming=!0,g(X)}else if(R.type==="reasoning_complete"){let K=typeof R.id=="string"?R.id:null;if(K&&k.has(K)&&D.has(K)){let Me=D.get(K);if(Me.reasoning){let Le=typeof R.text=="string"?R.text:"";Le&&Me.reasoning.chunks.length===0&&Me.reasoning.chunks.push(Le),Me.reasoning.status="complete",Me.streaming=!1,g(Me)}k.delete(K),D.delete(K);continue}let ee=R.id,X=typeof R.text=="string"?R.text:"";!J.get(ee)&&(X||R.scope==="loop")&&w(ee);let le=J.get(ee);if(le?.reasoning){(R.scope==="loop"||R.scope==="turn")&&(le.reasoning.scope=R.scope),X&&le.reasoning.chunks.length===0&&le.reasoning.chunks.push(X),le.reasoning.status="complete",le.reasoning.completedAt=Date.now();let Me=le.reasoning.startedAt??Date.now();le.reasoning.durationMs=Math.max(0,(le.reasoning.completedAt??Date.now())-Me),le.streaming=!1,g(le)}}else if(R.type==="tool_start"){h&&(h.streaming=!1,g(h),h=null),typeof R.iteration=="number"&&(St=R.iteration);let K=R.toolCallId,ee=R.toolName;if(q(ee)){L.add(K);continue}let X=Z(K),le=X.toolCall??{id:K,status:"pending"};le.name=ee??le.name,le.status="running",le.success=void 0,le.error=void 0,le.duration=void 0,R.parameters!==void 0&&(le.args=R.parameters),le.startedAt=le.startedAt??ne(R.startedAt),le.completedAt=void 0,le.durationMs=void 0,X.toolCall=le,X.streaming=!0,R.executionId&&(X.agentMetadata={executionId:R.executionId,iteration:R.iteration}),g(X)}else if(R.type==="tool_output_delta"){let K=R.toolCallId;if(L.has(K))continue;let ee=Z(K),X=ee.toolCall??{id:K,status:"running"};X.startedAt=X.startedAt??Date.now();let le=R.delta;le&&(X.chunks=X.chunks??[],X.chunks.push(String(le))),X.status="running",ee.toolCall=X,ee.streaming=!0,R.executionId&&(ee.agentMetadata=ee.agentMetadata??{executionId:R.executionId,iteration:St}),g(ee)}else if(R.type==="tool_complete"){let K=R.toolCallId;if(L.has(K)){L.delete(K);continue}let ee=Z(K),X=ee.toolCall??{id:K,status:"running"};X.status="complete",R.result!==void 0&&(X.result=R.result),X.name=R.toolName??X.name,X.success=R.success,X.error=R.error,X.completedAt=Date.now();let le=R.executionTime;if(typeof le=="number")X.durationMs=le,X.duration=le;else{let Me=X.startedAt??Date.now();X.durationMs=Math.max(0,(X.completedAt??Date.now())-Me)}ee.toolCall=X,ee.streaming=!1,R.executionId&&(ee.agentMetadata=ee.agentMetadata??{executionId:R.executionId,iteration:R.iteration??St}),g(ee)}else if(R.type==="await"&&R.toolName){let K=typeof R.toolCallId=="string"&&R.toolCallId.length>0?R.toolCallId:void 0,ee=K??R.toolId??`local-${p()}`,X=Z(ee),le=R.toolName,Me=R.origin==="webmcp"&&!Ca(le)?`webmcp:${le}`:le,Le=Ca(Me),Ne=X.toolCall??{id:ee,status:"pending"};Ne.name=Me,Ne.args=R.parameters,Ne.status=Le?"running":"complete",Ne.chunks=Ne.chunks??[],Ne.startedAt=Ne.startedAt??ne(R.awaitedAt),Le?(Ne.completedAt=void 0,Ne.duration=void 0,Ne.durationMs=void 0):Ne.completedAt=Ne.completedAt??Ne.startedAt,X.toolCall=Ne,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:R.executionId??X.agentMetadata?.executionId,awaitingLocalTool:!0,...K?{webMcpToolCallId:K}:{}},g(X)}else if(R.type==="text_start"){let K=typeof R.id=="string"?R.id:null,ee=typeof R.parentToolCallId=="string"&&R.parentToolCallId?R.parentToolCallId:null;if(K&&ee){k.set(K,ee);continue}let X=h;X&&(ut==="flow"?(N(X),Se=X):(X.streaming=!1,g(X)),h=null),S=typeof R.id=="string"?R.id:S,E=""}else if(R.type==="text_delta"){let K=typeof R.id=="string"?R.id:null,ee=K?k.get(K):void 0;if(K&&ee){let Me=typeof R.delta=="string"?R.delta:"",Le=($.get(K)??"")+Me;if($.set(K,Le),Le.trim()==="")continue;let Ne=Ee(K,ee);Ne.agentMetadata={...Ne.agentMetadata,executionId:R.executionId,parentToolId:ee},se(Ne,Le,Me,void 0);continue}if(S=typeof R.id=="string"?R.id:S,ut==="flow"){let Me=typeof R.delta=="string"?R.delta:"";if(E+=Me,E.trim()==="")continue;let Le=v();Le.agentMetadata={executionId:R.executionId,iteration:St},se(Le,E,Me,void 0),b=Le;continue}let X=typeof R.delta=="string"?R.delta:"";E+=X;let le=v();le.agentMetadata={executionId:R.executionId,iteration:St,turnId:gt??void 0,agentName:Pe?.agentName},se(le,E,X,void 0),b=le}else if(R.type==="text_complete"){let K=typeof R.id=="string"?R.id:null;if(K&&k.has(K)){let X=D.get(K);X&&N(X),k.delete(K),$.delete(K),D.delete(K);continue}let ee=h;ee&&(ut==="flow"?(N(ee),Se=ee):((ee.content??"")===""&&typeof R.text=="string"&&(ee.content=R.text),ee.streaming=!1,g(ee)),h=null),S=null,E=""}else if(R.type==="step_complete"){if(R.stepType==="tool")continue;if(R.success===!1){let K=R.error||"Step failed";n({type:"error",error:new Error(K)});let ee=h;ee&&ee.streaming&&(ee.streaming=!1,g(ee)),n({type:"status",status:"idle"});continue}{let K=Se;Se=null;let ee=R.stopReason,le=(R.result&&typeof R.result=="object"?R.result:null)?.response;if(K)ee&&(K.stopReason=ee),le!=null?xe(K,le):K.streaming!==!1&&(re.delete(K.id),pe.delete(K.id),K.streaming=!1,g(K));else{let Me=le!=null&&le!=="";if(Me||ee){let Le=v();ee&&(Le.stopReason=ee),Me?N(Le,le):(Le.streaming=!1,g(Le))}}continue}}else if(R.type==="execution_start")ut=R.kind==="flow"?"flow":"agent",tt=!0,ut==="agent"&&(Pe={executionId:R.executionId,agentId:R.agentId??"virtual",agentName:R.agentName??""});else if(R.type==="turn_start"){let K=typeof R.iteration=="number"?R.iteration:St;if(K!==St){if(Fe==="separate"&&K>1){let ee=h;ee&&(ee.streaming=!1,g(ee),h=null)}St=K}gt=typeof R.id=="string"?R.id:null,b=null}else if(R.type==="tool_input_delta"){let K=R.toolCallId;if(K){let ee=T.get(K);ee?.toolCall&&(ee.toolCall.chunks=ee.toolCall.chunks??[],ee.toolCall.chunks.push(R.delta??""),g(ee))}}else if(R.type==="tool_input_complete"){if(L.has(R.toolCallId))continue;let K=Z(R.toolCallId),ee=K.toolCall;ee.args=R.parameters,ee.name=R.toolName??ee.name,g(K)}else if(R.type==="turn_complete"){let K=R.stopReason,ee=h??b;if(K&&ee!==null){let X=R.id;(!X||ee.agentMetadata?.turnId===X)&&(ee.stopReason=K,g(ee))}gt===R.id&&(gt=null)}else if(R.type==="media_start"){let K=String(R.id);Pt.set(K,{mediaType:typeof R.mediaType=="string"?R.mediaType:void 0,toolCallId:R.toolCallId,parts:[]})}else if(R.type==="media_delta"){let K=Pt.get(String(R.id));K&&typeof R.delta=="string"&&K.parts.push(R.delta)}else if(R.type==="media_complete"){let K=String(R.id),ee=Pt.get(K);Pt.delete(K);let X=(typeof R.mediaType=="string"?R.mediaType:void 0)??ee?.mediaType??"application/octet-stream",le=typeof R.data=="string"?R.data:void 0,Me=typeof R.url=="string"?R.url:ee&&ee.parts.length>0?ee.parts.join(""):void 0,Le=null;if(le)Le={type:"media",data:le,mediaType:X};else if(Me){let qe=X.toLowerCase();Le={type:qe==="image"||qe.startsWith("image/")?"image-url":"file-url",url:Me,mediaType:X}}let Ne=R.toolCallId??ee?.toolCallId,lt=Le?[Le]:[],At=[];for(let qe of lt){if(!qe||typeof qe!="object")continue;let nt=qe,Ut=typeof nt.type=="string"?nt.type:void 0,tn=typeof nt.mediaType=="string"?nt.mediaType.toLowerCase():"",Q=null,He="";if(Ut==="media"){let _e=typeof nt.data=="string"?nt.data:void 0;if(!_e)continue;He=tn.length>0?tn:"application/octet-stream",Q=`data:${He};base64,${_e}`}else if(Ut==="image-url"){let _e=typeof nt.url=="string"?nt.url:void 0;if(!_e)continue;He=tn,Q=_e}else if(Ut==="file-url"){let _e=typeof nt.url=="string"?nt.url:void 0;if(!_e)continue;He=tn,Q=_e}else continue;if(Q)if(Ut==="image-url"||He.startsWith("image/"))At.push({type:"image",image:Q,...He.includes("/")?{mimeType:He}:{}});else if(He.startsWith("audio/"))At.push({type:"audio",audio:Q,mimeType:He});else if(He.startsWith("video/"))At.push({type:"video",video:Q,mimeType:He});else{let _e=He||"application/octet-stream";At.push({type:"file",data:Q,mimeType:_e,filename:JL(_e)})}}if(At.length>0){let qe=p(),nt=Ne,tn={id:`agent-media-${typeof nt=="string"&&nt.length>0?`${nt}-${qe}`:String(qe)}`,role:"assistant",content:"",contentParts:At,createdAt:new Date().toISOString(),streaming:!1,sequence:qe,agentMetadata:{executionId:R.executionId,iteration:St}};g(tn);let Q=h;Q&&(Q.streaming=!1,g(Q)),h=null,x.current=null}}else if(R.type==="execution_complete"){let K=h;K&&(R.kind==="flow"&&K.streaming!==!1?N(K):(K.streaming=!1,g(K)),h=null),S=null,E="",Se=null,n({type:"status",status:"idle",terminal:!0})}else if(R.type==="execution_error"){let K=typeof R.error=="string"?R.error:R.error?.message??"Execution error";n({type:"error",error:new Error(K)})}else if(R.type!=="ping"){if(R.type==="approval_start"){let K=R.approvalId??`approval-${p()}`,ee={id:`approval-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:K,status:"pending",agentId:Pe?.agentId??"virtual",executionId:R.executionId??Pe?.executionId??"",toolName:R.toolName??"",toolType:R.toolType,description:R.description??`Execute ${R.toolName??"tool"}`,...typeof R.reason=="string"&&R.reason?{reason:R.reason}:{},parameters:R.parameters,...typeof R.toolCallId=="string"&&R.toolCallId?{toolCallId:R.toolCallId}:{}}};g(ee)}else if(R.type==="approval_complete"){let K=R.approvalId;if(K){let X={id:`approval-${K}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:K,status:R.decision??"approved",agentId:Pe?.agentId??"virtual",executionId:R.executionId??Pe?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};g(X)}}else if(R.type==="artifact_start"||R.type==="artifact_delta"||R.type==="artifact_update"||R.type==="artifact_complete"){if(R.type==="artifact_start"){let K=R.artifactType,ee=String(R.id),X=typeof R.title=="string"?R.title:void 0,le=R.file,Me;if(le&&typeof le=="object"&&!Array.isArray(le)&&typeof le.path=="string"&&typeof le.mimeType=="string"&&(Me={path:le.path,mimeType:le.mimeType,...typeof le.language=="string"?{language:le.language}:{}}),n({type:"artifact_start",id:ee,artifactType:K,title:X,component:typeof R.component=="string"?R.component:void 0,...Me?{file:Me}:{}}),_.set(ee,{markdown:"",title:X,file:Me}),!Y.has(ee)){Y.add(ee);let Le=ks(e.config().features?.artifacts,{artifactType:K,...Me?{file:Me}:{}}),Ne=typeof R.component=="string"?R.component:void 0,lt={id:`artifact-ref-${ee}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Il(Le,{artifactId:ee,title:X,artifactType:K,status:"streaming",...Me?{file:Me}:{},...Ne?{component:Ne}:{}})};I.set(ee,lt),g(lt)}}else if(R.type==="artifact_delta"){let K=String(R.id),ee=typeof R.delta=="string"?R.delta:String(R.delta??"");n({type:"artifact_delta",id:K,artDelta:ee});let X=_.get(K);X&&(X.markdown+=ee)}else if(R.type==="artifact_update"){let K=R.props&&typeof R.props=="object"&&!Array.isArray(R.props)?R.props:{};n({type:"artifact_update",id:String(R.id),props:K,component:typeof R.component=="string"?R.component:void 0});let ee=_.get(String(R.id));ee&&(ee.props={...ee.props??{},...K})}else if(R.type==="artifact_complete"){let K=String(R.id);n({type:"artifact_complete",id:K});let ee=I.get(K);if(ee){ee.streaming=!1;try{let X=JSON.parse(ee.rawContent??"{}");if(X.props){X.props.status="complete";let le=_.get(K);le?.markdown&&(X.props.markdown=le.markdown),le?.file&&(X.props.file=le.file),X.component==="PersonaArtifactInline"&&le?.props&&Object.keys(le.props).length>0&&(X.props.componentProps=le.props)}ee.rawContent=JSON.stringify(X)}catch{}_.delete(K),g(ee),I.delete(K)}}}else if(R.type==="error"&&R.recoverable===!1&&R.error!=null&&R.error!==""){let K=typeof R.error=="string"?R.error:R.error?.message!=null?String(R.error.message):"Execution error";n({type:"error",error:new Error(K)});let ee=h;ee&&ee.streaming&&(ee.streaming=!1,g(ee)),n({type:"status",status:"idle"})}}}de.length=0};;){let{done:j,value:R}=await s.read();if(j)break;l+=i.decode(R,{stream:!0});let K=l.split(`
5
5
 
6
6
  `);l=K.pop()??"";for(let ee of K){let X=ee.split(`
7
- `),le="message",Me="",Le=null;for(let nt of X)nt.startsWith("event:")?le=nt.replace("event:","").trim():nt.startsWith("data:")?Me+=nt.replace("data:","").trim():nt.startsWith("id:")&&(Le=nt.slice(3).trim());let Ne=()=>{Le!==null&&Le!==""&&n({type:"cursor",id:Le})};if(!Me){Ne();continue}let lt;try{lt=JSON.parse(Me)}catch(nt){n({type:"error",error:nt instanceof Error?nt:new Error("Failed to parse chat stream payload")});continue}let At=lt!==null&&typeof lt=="object"&&!Array.isArray(lt)?lt:null,qe=le!=="message"?le:typeof At?.type=="string"?At.type:"message";if(e.onSSEEvent?.(qe,lt),e.parseSSEEvent){x.current=h;let nt=await ZL(e,lt,n,x,g,p,A);if(x.current&&x.current!==h&&(h=x.current),nt){Ne();continue}}At&&(de.push({...At,type:qe}),Ge()),Ne()}}Ge()}var Cw,Sw=ie(()=>{"use strict";Ai();Hl();Gr();vw();Cw=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var Mw,oP,gp,yp,rP,hp,sP,iP,aP,or,lP,cP,dP,pP,Tw=ie(()=>{"use strict";Mw="webmcp:",oP=e=>e.startsWith(Mw)?e.slice(Mw.length):e,gp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},yp=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#t=3e4}#e;#t;#n=!1;#o=null;#c=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#p()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let t=this.#p();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return gp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#i(r.name)).map(r=>{let s=sP(r.annotations);return{name:r.name,description:r.description,parametersSchema:iP(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#s(),this.config.enabled!==!0)return or("WebMCP is not enabled on this widget.");let r=this.#p();if(!r){let h=typeof document<"u"&&!!document.modelContext;return or(h?"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=oP(t),i;try{i=await r.getTools()}catch(h){let b=h instanceof Error?h.message:String(h);return or(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(h=>h.name===s);if(!l)return or(`WebMCP tool not registered on this page: ${s}`);if(!this.#i(s))return or(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return or("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),d={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#g(d))return or("User declined the tool call.");if(o?.aborted)return or("Aborted by cancel()");let p=new AbortController,f=!1,m=setTimeout(()=>{f=!0,p.abort()},this.#t),g=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",g,{once:!0}));try{let h=await r.executeTool(l,dP(n),{signal:p.signal});return aP(h)}catch(h){if(f)return or(`WebMCP tool '${s}' timed out after ${this.#t}ms`);if(o?.aborted)return or("Aborted by cancel()");let b=h instanceof Error?h.message:String(h);return or(b)}finally{clearTimeout(m),o&&o.removeEventListener("abort",g)}}#s(){return this.config.enabled!==!0?Promise.resolve():(this.#o||(this.#o=this.#f()),this.#o)}async#f(){try{if(this.#p()){this.#n=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#n=!0}catch(t){gp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#n=!1}}#p(){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.#c||(this.#c=!0,gp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async#g(t){let n=this.#e??lP;try{return await n(t)}catch(o){return gp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#i(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>rP(t,o))}},rP=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},hp={type:"object",properties:{}},sP=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},iP=e=>{if(e===void 0||e==="")return{...hp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...hp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...hp}}catch{return{...hp}}},aP=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:pP(t)}]}},or=e=>({isError:!0,content:[{type:"text",text:e}]}),lP=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=cP(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
7
+ `),le="message",Me="",Le=null;for(let nt of X)nt.startsWith("event:")?le=nt.replace("event:","").trim():nt.startsWith("data:")?Me+=nt.replace("data:","").trim():nt.startsWith("id:")&&(Le=nt.slice(3).trim());let Ne=()=>{Le!==null&&Le!==""&&n({type:"cursor",id:Le})};if(!Me){Ne();continue}let lt;try{lt=JSON.parse(Me)}catch(nt){n({type:"error",error:nt instanceof Error?nt:new Error("Failed to parse chat stream payload")});continue}let At=lt!==null&&typeof lt=="object"&&!Array.isArray(lt)?lt:null,qe=le!=="message"?le:typeof At?.type=="string"?At.type:"message";if(e.onSSEEvent?.(qe,lt),e.parseSSEEvent){x.current=h;let nt=await ZL(e,lt,n,x,g,p,A);if(x.current&&x.current!==h&&(h=x.current),nt){Ne();continue}}At&&(de.push({...At,type:qe}),Ge()),Ne()}}Ge()}var Cw,Sw=ie(()=>{"use strict";Ai();Hl();Gr();vw();Cw=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<")});var Mw,oP,gp,yp,rP,hp,sP,iP,aP,or,lP,cP,dP,pP,Tw=ie(()=>{"use strict";Mw="webmcp:",oP=e=>e.startsWith(Mw)?e.slice(Mw.length):e,gp={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},yp=class{constructor(t,n){this.config=t;this.#r=n,this.#e=t.onConfirm??null,this.#t=3e4}#e;#t;#n=!1;#o=null;#i=!1;#r;setConfirmHandler(t){this.#e=t}isOperational(){return this.config.enabled!==!0||!this.#n?!1:this.#c()!==null}async snapshotForDispatch(){if(await this.#s(),this.config.enabled!==!0)return[];let t=this.#c();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return gp.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}this.#r.recordToolDisplayTitles(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.#p(r.name)).map(r=>{let s=sP(r.annotations);return{name:r.name,description:r.description,parametersSchema:iP(r.inputSchema),origin:"webmcp",...o?{pageOrigin:o}:{},...s?{annotations:s}:{},...s?.untrustedContentHint===!0?{untrustedContentHint:!0}:{}}})}async executeToolCall(t,n,o){if(await this.#s(),this.config.enabled!==!0)return or("WebMCP is not enabled on this widget.");let r=this.#c();if(!r){let h=typeof document<"u"&&!!document.modelContext;return or(h?"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=oP(t),i;try{i=await r.getTools()}catch(h){let b=h instanceof Error?h.message:String(h);return or(`Failed to read WebMCP registry: ${b}`)}this.#r.recordToolDisplayTitles(i);let l=i.find(h=>h.name===s);if(!l)return or(`WebMCP tool not registered on this page: ${s}`);if(!this.#p(s))return or(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return or("Aborted by cancel()");let c=this.#r.getToolDisplayTitle(s),d={toolName:s,args:n,description:l.description,...c?{title:c}:{},reason:"gate"};if(!await this.#f(d))return or("User declined the tool call.");if(o?.aborted)return or("Aborted by cancel()");let p=new AbortController,f=!1,m=setTimeout(()=>{f=!0,p.abort()},this.#t),g=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",g,{once:!0}));try{let h=await r.executeTool(l,dP(n),{signal:p.signal});return aP(h)}catch(h){if(f)return or(`WebMCP tool '${s}' timed out after ${this.#t}ms`);if(o?.aborted)return or("Aborted by cancel()");let b=h instanceof Error?h.message:String(h);return or(b)}finally{clearTimeout(m),o&&o.removeEventListener("abort",g)}}#s(){return this.config.enabled!==!0?Promise.resolve():(this.#o||(this.#o=this.#g()),this.#o)}async#g(){try{if(this.#c()){this.#n=!0;return}(await this.#r.loadPolyfill()).initializeWebMCPPolyfill(),this.#n=!0}catch(t){gp.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.#n=!1}}#c(){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.#i||(this.#i=!0,gp.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async#f(t){let n=this.#e??lP;try{return await n(t)}catch(o){return gp.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}#p(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>rP(t,o))}},rP=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},hp={type:"object",properties:{}},sP=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},iP=e=>{if(e===void 0||e==="")return{...hp};if(typeof e=="object")return e!==null&&!Array.isArray(e)?e:{...hp};try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{...hp}}catch{return{...hp}}},aP=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:pP(t)}]}},or=e=>({isError:!0,content:[{type:"text",text:e}]}),lP=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=cP(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
8
8
 
9
9
  Arguments:
10
10
  ${t}`:"")+(e.description?`
11
11
 
12
- ${e.description}`:"");return window.confirm(n)},cP=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},dP=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},pP=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}}});var Ew={};En(Ew,{WebMcpBridge:()=>yp});var kw=ie(()=>{"use strict";Tw()});var Ww,Rw=ie(()=>{Ww="4.26.0"});var br,vp=ie(()=>{"use strict";Rw();br=Ww});var Uw={};En(Uw,{deleteAllConversations:()=>kP,deleteConversation:()=>EP,finalizeDisplayProjections:()=>TP,getConversation:()=>MP,historyErrorFor:()=>$w,listConversations:()=>AP,readErrorCode:()=>dg,recoverFromUnauthorized:()=>Vw,resetVisitor:()=>LP});function vP(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 CP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function wP(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 xP(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",Ow);return r}async function dg(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Vw(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",_w);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",Nw);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",Fw);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 $w(e,t,n){let o=await dg(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",Ow);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",_w)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",Nw):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Fw):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function SP(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 ka(e,t,n){pg(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;CP(e,n.scope)==="verified-user"&&(s=await wP(e,r,o),s&&(r=await xP(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,d=await e.readVisitorToken();if(!d&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(vP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":br,...d?{"X-Visitor-Token":d}:{},...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(p.status===401&&!l){l=!0,r=await Vw(e,await dg(e,p),s,o);continue}if(!p.ok)throw await $w(e,p,o);let f=p.headers.get("X-History-Identity-Status"),m=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return SP(e,f,s!==null,o),m}}function pg(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 AP(e,t){let n=await ka(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(Dw),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function MP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Dw(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 TP(e,t,n){pg(e);let o=0;for(let c of n){let d=c.displayContent.length;if(d>Bw)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${Bw} character limit`);o+=d}if(o>cg)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${cg} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ka(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=cg,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 EP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function kP(e,t){let n=await ka(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 LP(e){pg(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ka(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Bw,cg,Dw,Ow,_w,Nw,Fw,zw=ie(()=>{"use strict";vp();Bw=32768,cg=49152,Dw=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:""}},Ow="The identity proof was not admitted; account history is unavailable",_w="The identity proof was rejected",Nw="The request carried no visitor credential",Fw="The stored visitor belongs to a different signed-in user"});function qw(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Cp(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function vr(e){return{type:"text",text:e}}function jw(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}function HP(e){return Kw.includes(e)||e.startsWith("image/")}function wp(e){return HP(e.type)}function Gw(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function Yw(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;wp(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 Xw(e,t=Qr,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 RP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qw(e,t){let n=RP(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var La,Kw,IP,Qr,Rs=ie(()=>{"use strict";La="[Image]";Kw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],IP=["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"],Qr=[...Kw,...IP]});function Jw(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function xp(e){return typeof e=="string"?e:void 0}function DP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?vr(t.text):null;case"image":return typeof t.image=="string"?jw(t.image,{mimeType:xp(t.mimeType),alt:xp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Gw(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...xp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...xp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function OP(e,t){let n=Jw(t),o=e.map(i=>Jw(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,d=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,f=p!==null&&n!==null?Math.min(p,n):p??n;for(let m=0;m<c;m+=1)r[s+m]=f!==null?f-(c-m):d!==null?d+m+1:BP+m;s=l+1}return r.map(i=>new Date(i).toISOString())}function Zw(e,t){let n=OP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!WP.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(DP).filter(p=>p!==null),d=qw(c);o.push({id:r.id,role:i,content:d||(Cp(c)?La:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Vl(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 WP,BP,Sp=ie(()=>{"use strict";Rs();WP=["user","assistant","system"],BP=0});function Ap(e){return e instanceof Li}var Li,zl=ie(()=>{"use strict";Li=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var ox,rx=ie(()=>{"use strict";fp();ox=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(p,f,m)=>{let g=f.trim();if(!g||!o.current)return;let h=p.getAttribute("data-tool-call-id")??"",b=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:h,answer:g,answers:m.structured,values:m.values??(m.source==="multi"?g.split(", "):[g]),isFreeText:b,source:m.source},bubbles:!0,composed:!0})),Ei(n,h);let x=o.current.getMessages().find(A=>A.toolCall?.id===h);x?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(x,m.structured??g):o.current.sendMessage(g)},s=p=>{let f=o.current;if(!f)return;let m=p.getAttribute("data-tool-call-id")??"",g=f.getMessages().find(h=>h.toolCall?.id===m);g&&f.persistAskUserQuestionProgress(g,{answers:pp(p,g),currentIndex:No(p)})},i=p=>Object.entries(p).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),l=p=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=No(p),m=Ma(p);if(f>=m-1)return;let g=o.current?.getMessages().find(h=>h.toolCall?.id===p.getAttribute("data-tool-call-id"));g&&(up(p,g,e.config(),f+1),s(p))};return{click:p=>{let m=p.target.closest("[data-ask-user-action]");if(!m)return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;let h=m.getAttribute("data-ask-user-action");if(p.preventDefault(),p.stopPropagation(),h==="dismiss"){let b=g.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b);let x=o.current?.getMessages().find(A=>A.toolCall?.id===b);x?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(x),o.current?.resolveAskUserQuestion(x,"(dismissed)"));return}if(h==="pick"){let b=m.getAttribute("data-option-label");if(!b)return;let x=g.getAttribute("data-multi-select")==="true",A=Ps(g);if(A&&x){let S=Ti(g)[No(g)],E=new Set(Array.isArray(S)?S:[]);E.has(b)?E.delete(b):E.add(b),Is(g,Array.from(E)),s(g);return}if(A){Is(g,b),s(g),l(g);return}if(x){let S=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",S?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!S);let E=g.querySelector('[data-ask-user-action="submit-multi"]');E&&(E.disabled=ig(g).length===0);return}r(g,b,{source:"pick",values:[b]});return}if(h==="submit-multi"){let b=ig(g);if(b.length===0)return;r(g,b.join(", "),{source:"multi",values:b});return}if(h==="open-free-text"){let b=g.querySelector('[data-ask-free-text-row="true"]');b&&(b.classList.remove("persona-hidden"),b.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(h==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(h==="submit-free-text"){let x=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!x.trim())return;if(Ps(g)){Is(g,x.trim()),s(g),l(g);return}r(g,x,{source:"free-text"});return}if(h==="next"||h==="back"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",x=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!x)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(S){let D=Ti(g)[No(g)];(typeof D!="string"||D!==S)&&Is(g,S)}let E=h==="next"?1:-1,k=No(g)+E;up(g,x,e.config(),k),s(g);return}if(h==="submit-all"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",x=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!x)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";S&&Is(g,S);let E=pp(g,x);o.current.persistAskUserQuestionProgress(x,{answers:E,currentIndex:No(g)});let k=i(E);r(g,k||"(submitted)",{source:"submit-all",structured:E});return}if(h==="skip"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",x=o.current.getMessages().find($=>$.toolCall?.id===b);if(!x)return;let A=Ps(g),S=No(g),E=Ma(g),k=S>=E-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b),x.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(x),o.current.resolveAskUserQuestion(x,"(dismissed)"));return}Is(g,"");let D=g.querySelector('[data-ask-free-text-input="true"]');if(D&&(D.value=""),k){let $=pp(g,x),J=i($);r(g,J||"(skipped)",{source:"submit-all",structured:$});return}up(g,x,e.config(),S+1),s(g);return}},keydown:p=>{if(p.key!=="Enter")return;let m=p.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;p.preventDefault();let h=m.value;if(h.trim()){if(Ps(g)){Is(g,h.trim()),s(g),l(g);return}r(g,h,{source:"free-text"})}}}}});function VP(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
12
+ ${e.description}`:"");return window.confirm(n)},cP=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},dP=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},pP=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}}});var Ew={};En(Ew,{WebMcpBridge:()=>yp});var kw=ie(()=>{"use strict";Tw()});var Ww,Rw=ie(()=>{Ww="4.26.1"});var br,vp=ie(()=>{"use strict";Rw();br=Ww});var Uw={};En(Uw,{deleteAllConversations:()=>kP,deleteConversation:()=>EP,finalizeDisplayProjections:()=>TP,getConversation:()=>MP,historyErrorFor:()=>$w,listConversations:()=>AP,readErrorCode:()=>dg,recoverFromUnauthorized:()=>Vw,resetVisitor:()=>LP});function vP(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 CP(e,t){if(t)return t;let n=e.config.features?.history?.scope;return n||(e.config.getIdentityProof?"verified-user":"browser")}async function wP(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 xP(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",Ow);return r}async function dg(e,t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async function Vw(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",_w);if(r.includes("visitor token required"))throw new e.HistoryClientError("visitor_token_missing",Nw);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",Fw);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 $w(e,t,n){let o=await dg(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",Ow);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",_w)):r.includes("visitor token required")?new e.HistoryClientError("visitor_token_missing",Nw):r.includes("visitor_identity_mismatch")?new e.HistoryClientError("visitor_identity_mismatch",Fw):new e.HistoryClientError("unauthorized",o||"History request was not authorized")}return new e.HistoryClientError("request_failed",o||`History request failed (${t.status})`)}function SP(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 ka(e,t,n){pg(e);let o=n.trackIdentity!==!1,r=await e.initSession(),s=null;CP(e,n.scope)==="verified-user"&&(s=await wP(e,r,o),s&&(r=await xP(e,r,s,o)));let i=e.historyInternals.visitorStore,l=!1;for(;;){let c=i?.revision()??0,d=await e.readVisitorToken();if(!d&&!n.visitorTokenOptional)throw new e.HistoryClientError("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(vP(e,t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":br,...d?{"X-Visitor-Token":d}:{},...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(p.status===401&&!l){l=!0,r=await Vw(e,await dg(e,p),s,o);continue}if(!p.ok)throw await $w(e,p,o);let f=p.headers.get("X-History-Identity-Status"),m=await p.json().catch(()=>{});if(i&&i.revision()!==c)throw new e.HistoryClientError("credential_changed","The visitor credential changed while the request was in flight");return SP(e,f,s!==null,o),m}}function pg(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 AP(e,t){let n=await ka(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(Dw),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async function MP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Dw(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 TP(e,t,n){pg(e);let o=0;for(let c of n){let d=c.displayContent.length;if(d>Bw)throw new e.HistoryClientError("payload_too_large",`displayContent exceeds the ${Bw} character limit`);o+=d}if(o>cg)throw new e.HistoryClientError("payload_too_large",`Display projection batch exceeds the ${cg} character limit`);await e.initSession();let r=e.historyInternals.visitorStore,s=r?.revision()??0,i=await ka(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=cg,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 EP(e,t,n){let o=await ka(e,`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async function kP(e,t){let n=await ka(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 LP(e){pg(e),e.setHistoryIdentityStatus({state:"resetting"});try{await ka(e,"visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Bw,cg,Dw,Ow,_w,Nw,Fw,zw=ie(()=>{"use strict";vp();Bw=32768,cg=49152,Dw=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:""}},Ow="The identity proof was not admitted; account history is unavailable",_w="The identity proof was rejected",Nw="The request carried no visitor credential",Fw="The stored visitor belongs to a different signed-in user"});function qw(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Cp(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function vr(e){return{type:"text",text:e}}function jw(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}function HP(e){return Kw.includes(e)||e.startsWith("image/")}function wp(e){return HP(e.type)}function Gw(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function Yw(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;wp(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 Xw(e,t=Qr,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 RP(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qw(e,t){let n=RP(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var La,Kw,IP,Qr,Rs=ie(()=>{"use strict";La="[Image]";Kw=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],IP=["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"],Qr=[...Kw,...IP]});function Jw(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function xp(e){return typeof e=="string"?e:void 0}function DP(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?vr(t.text):null;case"image":return typeof t.image=="string"?jw(t.image,{mimeType:xp(t.mimeType),alt:xp(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Gw(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...xp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...xp(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function OP(e,t){let n=Jw(t),o=e.map(i=>Jw(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,d=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,f=p!==null&&n!==null?Math.min(p,n):p??n;for(let m=0;m<c;m+=1)r[s+m]=f!==null?f-(c-m):d!==null?d+m+1:BP+m;s=l+1}return r.map(i=>new Date(i).toISOString())}function Zw(e,t){let n=OP(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!WP.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(DP).filter(p=>p!==null),d=qw(c);o.push({id:r.id,role:i,content:d||(Cp(c)?La:""),createdAt:l,...c.length>0&&{contentParts:c}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function Vl(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 WP,BP,Sp=ie(()=>{"use strict";Rs();WP=["user","assistant","system"],BP=0});function Ap(e){return e instanceof Li}var Li,zl=ie(()=>{"use strict";Li=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var ox,rx=ie(()=>{"use strict";fp();ox=e=>{let{mount:t,overlay:n,sessionRef:o}=e,r=(p,f,m)=>{let g=f.trim();if(!g||!o.current)return;let h=p.getAttribute("data-tool-call-id")??"",b=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:h,answer:g,answers:m.structured,values:m.values??(m.source==="multi"?g.split(", "):[g]),isFreeText:b,source:m.source},bubbles:!0,composed:!0})),Ei(n,h);let x=o.current.getMessages().find(A=>A.toolCall?.id===h);x?.agentMetadata?.awaitingLocalTool?o.current.resolveAskUserQuestion(x,m.structured??g):o.current.sendMessage(g)},s=p=>{let f=o.current;if(!f)return;let m=p.getAttribute("data-tool-call-id")??"",g=f.getMessages().find(h=>h.toolCall?.id===m);g&&f.persistAskUserQuestionProgress(g,{answers:pp(p,g),currentIndex:No(p)})},i=p=>Object.entries(p).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),l=p=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=No(p),m=Ma(p);if(f>=m-1)return;let g=o.current?.getMessages().find(h=>h.toolCall?.id===p.getAttribute("data-tool-call-id"));g&&(up(p,g,e.config(),f+1),s(p))};return{click:p=>{let m=p.target.closest("[data-ask-user-action]");if(!m)return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;let h=m.getAttribute("data-ask-user-action");if(p.preventDefault(),p.stopPropagation(),h==="dismiss"){let b=g.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b);let x=o.current?.getMessages().find(A=>A.toolCall?.id===b);x?.agentMetadata?.awaitingLocalTool&&(o.current?.markAskUserQuestionResolved(x),o.current?.resolveAskUserQuestion(x,"(dismissed)"));return}if(h==="pick"){let b=m.getAttribute("data-option-label");if(!b)return;let x=g.getAttribute("data-multi-select")==="true",A=Ps(g);if(A&&x){let S=Ti(g)[No(g)],E=new Set(Array.isArray(S)?S:[]);E.has(b)?E.delete(b):E.add(b),Is(g,Array.from(E)),s(g);return}if(A){Is(g,b),s(g),l(g);return}if(x){let S=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",S?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!S);let E=g.querySelector('[data-ask-user-action="submit-multi"]');E&&(E.disabled=ig(g).length===0);return}r(g,b,{source:"pick",values:[b]});return}if(h==="submit-multi"){let b=ig(g);if(b.length===0)return;r(g,b.join(", "),{source:"multi",values:b});return}if(h==="open-free-text"){let b=g.querySelector('[data-ask-free-text-row="true"]');b&&(b.classList.remove("persona-hidden"),b.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(h==="focus-free-text"){g.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(h==="submit-free-text"){let x=g.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!x.trim())return;if(Ps(g)){Is(g,x.trim()),s(g),l(g);return}r(g,x,{source:"free-text"});return}if(h==="next"||h==="back"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",x=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!x)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(S){let D=Ti(g)[No(g)];(typeof D!="string"||D!==S)&&Is(g,S)}let E=h==="next"?1:-1,k=No(g)+E;up(g,x,e.config(),k),s(g);return}if(h==="submit-all"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",x=o.current.getMessages().find(D=>D.toolCall?.id===b);if(!x)return;let S=g.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";S&&Is(g,S);let E=pp(g,x);o.current.persistAskUserQuestionProgress(x,{answers:E,currentIndex:No(g)});let k=i(E);r(g,k||"(submitted)",{source:"submit-all",structured:E});return}if(h==="skip"){if(!o.current)return;let b=g.getAttribute("data-tool-call-id")??"",x=o.current.getMessages().find($=>$.toolCall?.id===b);if(!x)return;let A=Ps(g),S=No(g),E=Ma(g),k=S>=E-1;if(!A){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:b},bubbles:!0,composed:!0})),Ei(n,b),x.agentMetadata?.awaitingLocalTool&&(o.current.markAskUserQuestionResolved(x),o.current.resolveAskUserQuestion(x,"(dismissed)"));return}Is(g,"");let D=g.querySelector('[data-ask-free-text-input="true"]');if(D&&(D.value=""),k){let $=pp(g,x),J=i($);r(g,J||"(skipped)",{source:"submit-all",structured:$});return}up(g,x,e.config(),S+1),s(g);return}},keydown:p=>{if(p.key!=="Enter")return;let m=p.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let g=m.closest("[data-persona-ask-sheet-for]");if(!g)return;p.preventDefault();let h=m.value;if(h.trim()){if(Ps(g)){Is(g,h.trim()),s(g),l(g);return}r(g,h,{source:"free-text"})}}}}});function VP(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
13
13
  `:o===""||sx.test(o)}function $P(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 VP(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
14
14
  `||i==="\uFFFC"||!r&&sx.test(i))return null;s--}return null}function ql(e,t,n){for(let o of n){let r=$P(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function ix(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function ax(e,t,n){return{value:e.slice(0,t.triggerIndex)+e.slice(n),caret:t.triggerIndex}}var sx,Mp=ie(()=>{"use strict";sx=/\s/});function Tp(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 mg=ie(()=>{"use strict"});function px(e){e.delayMs!==void 0&&(lx=kp(e.delayMs)),e.skipDelayMs!==void 0&&(cx=kp(e.skipDelayMs))}function ux(e){Ep.get(e)?.hide()}function $n(e){Ep.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=UP,viewportPadding:l=zP}=e,c=()=>t.ownerDocument,d=()=>c().defaultView??window,p=null,f=null,m=null,g=null,h,b=!1,x=!1,A=!1,S=()=>(typeof o=="function"?o():o).trim(),E=()=>(typeof r=="function"?r():r??"").trim(),k=()=>kp(e.delayMs??lx),D=()=>kp(e.skipDelayMs??cx),$=()=>{h!==void 0&&(d().clearTimeout(h),h=void 0)},J=()=>{$();let ne=p!==null;g?.(),g=null,p?.remove(),p=null,f=null,m=null,ne&&jP(D())},T=()=>{if(!p)return;let ne=c(),te=d(),re=t.getBoundingClientRect(),pe=p.getBoundingClientRect(),xe=ne.documentElement.clientWidth||te.innerWidth,Se=ne.documentElement.clientHeight||te.innerHeight,se=xe-l-pe.width,N=re.left+re.width/2-pe.width/2,Ee=hg(N,l,se),de=re.top-l,Ge=Se-l-re.bottom,Pt=pe.height+i,St=de>=Pt||de>=Ge?"top":"bottom",ut=St==="top"?re.top-i-pe.height:re.bottom+i,tt=Se-l-pe.height,gt=hg(ut,l,tt),Pe=re.left+re.width/2,Fe=Math.max(gg,pe.width-gg),j=hg(Pe-Ee,gg,Fe);p.dataset.placement=St,p.style.left=`${Ee}px`,p.style.top=`${gt}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${j}px`)},W=()=>{if(A||!s||p||!t.isConnected||KP(t))return;let ne=S(),te=GP(t);if(!ne||!te)return;let re=c(),pe=d();p=re.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ta);let xe=pe.getComputedStyle?.(t);if(xe){for(let Pt of YP){let St=xe.getPropertyValue(Pt).trim();St&&p.style.setProperty(Pt,St)}xe.fontFamily&&(p.style.fontFamily=xe.fontFamily)}f=re.createElement("span"),f.className="persona-control-tooltip__label",f.textContent=ne,p.appendChild(f);let Se=E();Se&&(m=re.createElement("span"),m.className="persona-control-tooltip__hint",m.textContent=Se,p.appendChild(m));let se=re.createElement("span");se.className="persona-control-tooltip__arrow",p.appendChild(se),te.appendChild(p),T(),p.dataset.state="open";let N=()=>{if(!t.isConnected){J();return}f&&(f.textContent=S()),m&&(m.textContent=E()),T()};pe.addEventListener("scroll",N,!0),pe.addEventListener("resize",N);let Ee=t.getRootNode(),de=fx(Ee)?Ee:re.documentElement,Ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||J()});Ge?.observe(de,{childList:!0,subtree:!0}),g=()=>{pe.removeEventListener("scroll",N,!0),pe.removeEventListener("resize",N),Ge?.disconnect()}},P=ne=>{if(!(A||p)){if($(),ne||k()<=0||qP()){W();return}h=d().setTimeout(()=>{h=void 0,W()},k())}},v=()=>{b||x?P(x):J()},w=()=>{let ne=d();(!ne.matchMedia||!ne.matchMedia("(hover: none)").matches)&&(b=!0,v())},L=()=>{b=!1,v()},I=()=>{try{x=t.matches(":focus-visible")}catch{x=!0}v()},Y=()=>{x=!1,v()},_=()=>{b=!1,x=!1,J()},q=ne=>{ne.key==="Escape"&&_()};n.addEventListener("mouseenter",w),n.addEventListener("mouseleave",L),t.addEventListener("focus",I),t.addEventListener("blur",Y),t.addEventListener("keydown",q),t.addEventListener("click",_);let Z={get isOpen(){return p!==null},show:W,hide:J,reposition:T,destroy:()=>{A||(A=!0,J(),n.removeEventListener("mouseenter",w),n.removeEventListener("mouseleave",L),t.removeEventListener("focus",I),t.removeEventListener("blur",Y),t.removeEventListener("keydown",q),t.removeEventListener("click",_),Ep.delete(t))}};return Ep.set(t,Z),Z}var UP,zP,gg,lx,cx,dx,kp,qP,jP,Ep,yg,KP,fx,GP,hg,YP,Pa=ie(()=>{"use strict";nr();$d();UP=8,zP=8,gg=10,lx=200,cx=300,dx=0,kp=e=>Math.max(0,e);qP=()=>Date.now()<dx,jP=e=>{dx=e>0?Date.now()+e:0},Ep=new WeakMap,yg="data-persona-tooltip-suppressed",KP=e=>typeof e.closest=="function"&&e.closest(`[${yg}]`)!==null;fx=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,GP=e=>{let t=e.getRootNode?.();return fx(t)?t:e.ownerDocument.body},hg=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),YP=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"]});function bg(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 Lp(e,t){return typeof e!="number"||!Number.isFinite(e)?t:e>0?e:t}function mx(e,t){e.style.maxHeight=`${t*bg(e)}px`,e.style.overflowY="auto"}function jl(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 gx(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function hx(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||!gx(t)}function XP(e){return(e.submitKey??"enter")!=="enter"||gx(e)?"enter":"send"}function Pp(e,t){e.setAttribute("enterkeyhint",XP(t))}function Ip(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 vg(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 Hp=ie(()=>{"use strict"});var Ao,rr,wg,vo,Rp,Wp,JP,xg,Bp,Ia,Dp,Op,_p,Ws=ie(()=>{"use strict";jm();Ye();ln();er();Rs();Pa();Hp();Ao="persona-composer-control",rr="persona-composer-control--glyph",wg=40,vo=24,Rp=(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)}},Wp=(e,t)=>{let n=C("textarea");n.setAttribute("data-persona-composer-input",""),n.placeholder=e?.copy?.inputPlaceholder??Fm,n.dir="auto",Pp(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:jl(n)}),Ip(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=Lp(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 d=parseFloat(l);if(Number.isFinite(d)&&d>0)return d}let c=o*bg(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}},JP="[data-persona-glyph-stack]",xg=(e,t,n="send")=>{let o=F("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},Bp=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",d=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,f=t.size,m=parseFloat(f??"")||wg,g=t.backgroundColor,h=t.textColor,b=C("div","persona-send-button-wrapper"),x=F("button",{className:Jt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?`persona-flex persona-items-center persona-justify-center ${Ao}`:"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!h&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":"","data-persona-send-mode":"send"},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?h||"var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))":h||void 0,backgroundColor:n&&g||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,S=null,E=null;if(n){let $=parseFloat(t.iconSize??"")||Math.round(m*.5),J=t.iconStrokeWidth??2,T=h?.trim()||"currentColor";if(r&&(A=Re(r,$,T,J)),S=Re(s,$,T,J),!t.iconSize)for(let W of[A,S])W&&(W.style.width=`var(--persona-components-composer-sendIconSize, ${$}px)`,W.style.height=`var(--persona-components-composer-sendIconSize, ${$}px)`);A&&S?(E=xg(A,S),x.appendChild(E)):A?x.appendChild(A):(x.textContent=o,S=null)}else x.textContent=c;x.setAttribute("aria-label",i),b.appendChild(x),$n({anchor:x,trigger:b,text:()=>x.getAttribute("aria-label")??"",enabled:p});let k="send";return{button:x,wrapper:b,setMode:$=>{if($===k)return;k=$;let J=$==="stop"?l:i;x.setAttribute("aria-label",J),x.setAttribute("data-persona-send-mode",$),n?(x.querySelector(JP)??E)?.setAttribute("data-mode",$):x.textContent=$==="stop"?d:c},glyphStack:E}},Ia=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,d=parseFloat(c??"")||vo,p=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,m=C("div","persona-send-button-wrapper"),g=F("button",{className:Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ao,!c&&rr),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:f||"var(--persona-text, #111827)",backgroundColor:p||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}}),b=Re(l,d,f||"currentColor",1.5);b?g.appendChild(b):g.textContent="\u{1F3A4}",m.appendChild(g);let x=t.tooltipText??"Start voice recognition",A=t.showTooltip??!1;return $n({anchor:g,trigger:m,text:()=>g.getAttribute("aria-label")??x,enabled:A}),{button:g,wrapper:m}},Dp=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=C("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=C("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=(t.allowedTypes??Qr).join(","),o.multiple=(t.maxFiles??4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",s=C("div","persona-send-button-wrapper"),i=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ao} ${rr}`,attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{fontSize:"18px",lineHeight:"1"}}),l=Re(r,vo,"currentColor",1.5);l?i.appendChild(l):i.textContent="\u{1F4CE}",i.addEventListener("click",d=>{d.preventDefault(),o.click()}),s.appendChild(i);let c=t.buttonTooltipText??"Attach file";return $n({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=C("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status",""),xi(o,t,"idle");let r=t.idleText??"Online";if(t.idleLink){let s=C("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},_p=()=>F("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}})});function Np(e){let{config:t,onOpen:n}=e,o=t.buttonIconName??"plus",r=t.buttonTooltipText??"Add context",s=C("div","persona-send-button-wrapper"),i=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Ao} ${rr}`,attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":r,"aria-haspopup":"listbox","aria-expanded":"false"},style:{fontSize:"18px",lineHeight:"1"}}),l=Re(o,vo,"currentColor",1.5);return l?i.appendChild(l):i.textContent="+",i.addEventListener("click",c=>{c.preventDefault(),c.stopPropagation(),n()}),s.appendChild(i),$n({anchor:i,trigger:s,text:()=>i.getAttribute("aria-label")??r}),{button:i,wrapper:s}}var Sg=ie(()=>{"use strict";Ye();ln();Pa();Ws()});var yx,Ag,Fp,Vp=ie(()=>{"use strict";yx=null,Ag=e=>{yx=e},Fp=(e,t,n,o)=>yx?.(e,t,n,o)??null});function vx(e){let{ref:t,config:n,onRemove:o}=e;if(n.renderMentionChip){let g="resolving",h,b=n.renderMentionChip({ref:t,status:g,payload:h,remove:o});return{get el(){return b},setStatus:(A,S)=>{if(A===g&&S===h)return;g=A,h=S;let E=n.renderMentionChip({ref:t,status:g,payload:h,remove:o});b.replaceWith(E),b=E}}}let r=t.iconName??n.chipIconName??"at-sign",s=F("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:t.label}}),i=C("span","persona-mention-chip-icon"),l=g=>{i.replaceChildren();let h=Fp(g,13,"currentColor",2);h&&i.appendChild(h)};l(r);let c=C("span","persona-mention-chip-spinner"),d=F("span",{className:"persona-mention-chip-label",text:t.label}),p=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${t.label} context`}}),f=Je(bx.X,11,"currentColor",2.5);return f?p.appendChild(f):p.textContent="\xD7",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(c),s.appendChild(d),s.appendChild(p),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="resolving"?(c.parentNode!==s&&s.insertBefore(c,d),i.parentNode===s&&i.remove(),s.setAttribute("title",t.label)):(c.parentNode===s&&c.remove(),i.parentNode!==s&&s.insertBefore(i,d),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${t.label} to context`)):(l(r),s.setAttribute("title",t.label)))}}}var bx,Cx=ie(()=>{"use strict";Ye();bx=require("lucide");io();Vp()});function Ha(e){e.style.display=e.childElementCount>0?"flex":"none"}function Tg(e){let t=e.querySelector(Mg);if(t)return t;let n=F("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 Mg,$p=ie(()=>{"use strict";Ye();Mg="[data-persona-composer-chip-row]"});function ZP(e){let t=0;for(let n of e.split(`
15
15
  `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>t&&(t=o[1].length)}return t}function Kl(e,t){let n="`".repeat(Math.max(3,ZP(t)+1));return`${n}${e}
@@ -19,7 +19,7 @@ ${n}`}function eI(e,t,n){return t.includes("</document_content>")?Kl(e,t):`<docu
19
19
  <document_content>
20
20
  ${t}
21
21
  </document_content>
22
- </document>`}function wx(e,t,n="fenced"){if(typeof n=="function")try{return n(e,t)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Kl(e.label,e.text)}return n==="document"?eI(e.label,e.text,t):Kl(e.label,e.text)}var Eg=ie(()=>{"use strict"});function Up(e,t){return{sourceId:e.id,itemId:t.id,label:t.label,iconName:t.iconName,color:t.color}}var xx,zp,kg=ie(()=>{"use strict";Cx();$p();Eg();xx=(e,t)=>`${e}\0${t}`,zp=class{constructor(t){this.mentions=[];this.#e=t,this.#s()}#e;get#t(){return this.#e.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(t,n,o=""){let r=xx(t.id,n.id);if(this.mentions.some(l=>l.key===r))return this.#n(t,n,"duplicate");if(this.atLimit())return this.#n(t,n,"limit");let s=Up(t,n),i={key:r,source:t,item:n,ref:s,status:"resolving",args:o};return i.chip=vx({ref:s,config:this.#e.mentionConfig,onRemove:()=>this.remove(r)}),i.chip.el.setAttribute("data-persona-chip-enter",""),i.chip.el.addEventListener("animationend",()=>i.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.#e.contextRow.appendChild(i.chip.el),this.#o(i),this.#s(),!0}atLimit(){return this.mentions.length>=this.#t}admit(t,n){return this.atLimit()?this.#n(t,n,"limit"):!0}track(t,n,o,r="",s){let i={key:t,source:n,item:o,ref:Up(n,o),status:"resolving",args:r,reportStatus:s};this.#o(i)}#n(t,n,o){return this.#e.mentionConfig.onMentionRejected?.(n,o),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:o}),!1}#o(t){this.mentions.push(t),t.source.resolveOn==="submit"?(t.status="ready",t.chip?.setStatus("ready"),t.reportStatus?.("resolved")):t.resolvePromise=this.#r(t),this.#e.announce(`Added ${t.ref.label} to context`)}#c(t,n,o=this.#e.getComposerText()){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:o,args:n,signal:t}}async#r(t){let n=new AbortController;t.abort=n;try{let o=await t.source.resolve(t.item,this.#c(n.signal,t.args));if(n.signal.aborted)return;t.payload=o,t.status="ready",t.chip?.setStatus("ready",o),t.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;t.status="error",t.chip?.setStatus("error"),t.reportStatus?.("error"),(this.#e.announceError??this.#e.announce)(`Couldn't attach ${t.ref.label} to context`),this.#e.mentionConfig.onMentionResolveError?.(t.item,o),this.#e.emit?.("resolve-error",{sourceId:t.source.id,itemId:t.item.id})}}remove(t){let n=this.mentions.findIndex(r=>r.key===t);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.#s(),this.#e.announce(`Removed ${o.ref.label} from context`)}getRefs(){return this.mentions.map(t=>t.ref)}removeLast(){let t=this.mentions[this.mentions.length-1];return t?(this.remove(t.key),!0):!1}clear(){for(let t of this.mentions)t.abort?.abort(),t.chip?.el.remove();this.mentions.length=0,this.#s()}collectForSubmit(){let t=[...this.mentions],n=t.map(s=>s.ref),o=this.#e.getComposerText();for(let s of t)s.chip?.el.remove();return this.mentions.length=0,this.#s(),{refs:n,finalize:async()=>{let s=await Promise.all(t.map(async p=>{try{return p.source.resolveOn==="submit"?await p.source.resolve(p.item,this.#c(new AbortController().signal,p.args,o)):(p.resolvePromise&&await p.resolvePromise,p.payload??null)}catch(f){try{this.#e.mentionConfig.onMentionResolveError?.(p.item,f)}catch(m){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",m)}return this.#e.emit?.("resolve-error",{sourceId:p.source.id,itemId:p.item.id}),null}})),i=[],l=[],c={},d=new Set;for(let p=0;p<t.length;p++){let f=t[p],m=s[p];if(!m)continue;let g=xx(f.source.id,f.item.id);if(!d.has(g)){if(d.add(g),m.llmAppend&&m.llmAppend.trim())try{i.push(wx({label:f.ref.label,text:m.llmAppend,ref:f.ref,item:f.item},i.length,this.#e.mentionConfig.llmFormat))}catch(h){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",h)}m.contentParts?.length&&l.push(...m.contentParts),m.context&&((c[f.source.id]??={})[f.item.id]=m.context)}}return{blocks:i,contentParts:l,context:c}}}}#s(){Ha(this.#e.contextRow)}}});function Sx(e){let t=e.getRootNode?.();return t&&Ax(t)||t&&jp(t)?t:e.ownerDocument??document}function qp(e,t,n){let o=jp(e)?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(jp(e)?e:e.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",t),i.textContent=n,o.appendChild(i)}function Kp(e,t,n){if(jp(e)||Ax(e)){qp(e,t,n);return}let o=e;if(o.isConnected){qp(Sx(o),t,n);return}let r=o.ownerDocument??document;qp(r,t,n),queueMicrotask(()=>{let s=Sx(o);s!==r&&qp(s,t,n)})}function tI(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Bs(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:d,onDismiss:p}=e,f=e.container??tI(t),m=!1,g=null,h=()=>{if(!m)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let S=n.getBoundingClientRect(),E=l?.()??null,k=E!=null?A.top+E:A.top,D=o==="top-start"||o==="top-end"?k-r-S.height:A.bottom+r,J=o==="bottom-end"||o==="top-end"?A.right-S.width:A.left,T=i?.()??null;if(T!=null){let W=Math.max(A.left,A.right-S.width);J=Math.min(Math.max(A.left+T,A.left),W)}n.style.top=`${D}px`,n.style.left=`${J}px`},b=()=>{m&&(m=!1,g&&(g(),g=null),n.remove())},x=()=>{if(m)return;m=!0,c!=null&&(n.style.zIndex=String(c)),f.appendChild(n),h();let A=(t.ownerDocument??document).defaultView??window,S=t.ownerDocument??document,E=()=>{if(!t.isConnected){b(),p?.("anchor-removed");return}h()},k=$=>{let J=typeof $.composedPath=="function"?$.composedPath():[];J.includes(n)||J.includes(t)||(b(),p?.("outside"))},D=A.setTimeout(()=>{S.addEventListener("pointerdown",k,!0)},0);A.addEventListener("scroll",E,!0),A.addEventListener("resize",E),g=()=>{A.clearTimeout(D),S.removeEventListener("pointerdown",k,!0),A.removeEventListener("scroll",E,!0),A.removeEventListener("resize",E)},d?.()};return{get isOpen(){return m},open:x,close:b,toggle:()=>m?b():x(),reposition:h,destroy:b}}function Mx(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var jp,Ax,Ra=ie(()=>{"use strict";jp=e=>e.nodeType===Node.DOCUMENT_NODE,Ax=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host!==void 0});var Tx,Ex=ie(()=>{"use strict";Tx=`
22
+ </document>`}function wx(e,t,n="fenced"){if(typeof n=="function")try{return n(e,t)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Kl(e.label,e.text)}return n==="document"?eI(e.label,e.text,t):Kl(e.label,e.text)}var Eg=ie(()=>{"use strict"});function Up(e,t){return{sourceId:e.id,itemId:t.id,label:t.label,iconName:t.iconName,color:t.color}}var xx,zp,kg=ie(()=>{"use strict";Cx();$p();Eg();xx=(e,t)=>`${e}\0${t}`,zp=class{constructor(t){this.mentions=[];this.#e=t,this.#s()}#e;get#t(){return this.#e.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(t,n,o=""){let r=xx(t.id,n.id);if(this.mentions.some(l=>l.key===r))return this.#n(t,n,"duplicate");if(this.atLimit())return this.#n(t,n,"limit");let s=Up(t,n),i={key:r,source:t,item:n,ref:s,status:"resolving",args:o};return i.chip=vx({ref:s,config:this.#e.mentionConfig,onRemove:()=>this.remove(r)}),i.chip.el.setAttribute("data-persona-chip-enter",""),i.chip.el.addEventListener("animationend",()=>i.chip?.el.removeAttribute("data-persona-chip-enter"),{once:!0}),this.#e.contextRow.appendChild(i.chip.el),this.#o(i),this.#s(),!0}atLimit(){return this.mentions.length>=this.#t}admit(t,n){return this.atLimit()?this.#n(t,n,"limit"):!0}track(t,n,o,r="",s){let i={key:t,source:n,item:o,ref:Up(n,o),status:"resolving",args:r,reportStatus:s};this.#o(i)}#n(t,n,o){return this.#e.mentionConfig.onMentionRejected?.(n,o),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:o}),!1}#o(t){this.mentions.push(t),t.source.resolveOn==="submit"?(t.status="ready",t.chip?.setStatus("ready"),t.reportStatus?.("resolved")):t.resolvePromise=this.#r(t),this.#e.announce(`Added ${t.ref.label} to context`)}#i(t,n,o=this.#e.getComposerText()){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:o,args:n,signal:t}}async#r(t){let n=new AbortController;t.abort=n;try{let o=await t.source.resolve(t.item,this.#i(n.signal,t.args));if(n.signal.aborted)return;t.payload=o,t.status="ready",t.chip?.setStatus("ready",o),t.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;t.status="error",t.chip?.setStatus("error"),t.reportStatus?.("error"),(this.#e.announceError??this.#e.announce)(`Couldn't attach ${t.ref.label} to context`),this.#e.mentionConfig.onMentionResolveError?.(t.item,o),this.#e.emit?.("resolve-error",{sourceId:t.source.id,itemId:t.item.id})}}remove(t){let n=this.mentions.findIndex(r=>r.key===t);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.#s(),this.#e.announce(`Removed ${o.ref.label} from context`)}getRefs(){return this.mentions.map(t=>t.ref)}removeLast(){let t=this.mentions[this.mentions.length-1];return t?(this.remove(t.key),!0):!1}clear(){for(let t of this.mentions)t.abort?.abort(),t.chip?.el.remove();this.mentions.length=0,this.#s()}collectForSubmit(){let t=[...this.mentions],n=t.map(s=>s.ref),o=this.#e.getComposerText();for(let s of t)s.chip?.el.remove();return this.mentions.length=0,this.#s(),{refs:n,finalize:async()=>{let s=await Promise.all(t.map(async p=>{try{return p.source.resolveOn==="submit"?await p.source.resolve(p.item,this.#i(new AbortController().signal,p.args,o)):(p.resolvePromise&&await p.resolvePromise,p.payload??null)}catch(f){try{this.#e.mentionConfig.onMentionResolveError?.(p.item,f)}catch(m){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",m)}return this.#e.emit?.("resolve-error",{sourceId:p.source.id,itemId:p.item.id}),null}})),i=[],l=[],c={},d=new Set;for(let p=0;p<t.length;p++){let f=t[p],m=s[p];if(!m)continue;let g=xx(f.source.id,f.item.id);if(!d.has(g)){if(d.add(g),m.llmAppend&&m.llmAppend.trim())try{i.push(wx({label:f.ref.label,text:m.llmAppend,ref:f.ref,item:f.item},i.length,this.#e.mentionConfig.llmFormat))}catch(h){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",h)}m.contentParts?.length&&l.push(...m.contentParts),m.context&&((c[f.source.id]??={})[f.item.id]=m.context)}}return{blocks:i,contentParts:l,context:c}}}}#s(){Ha(this.#e.contextRow)}}});function Sx(e){let t=e.getRootNode?.();return t&&Ax(t)||t&&jp(t)?t:e.ownerDocument??document}function qp(e,t,n){let o=jp(e)?e.head:e,r=t.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(jp(e)?e:e.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",t),i.textContent=n,o.appendChild(i)}function Kp(e,t,n){if(jp(e)||Ax(e)){qp(e,t,n);return}let o=e;if(o.isConnected){qp(Sx(o),t,n);return}let r=o.ownerDocument??document;qp(r,t,n),queueMicrotask(()=>{let s=Sx(o);s!==r&&qp(s,t,n)})}function tI(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Bs(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:c=2147483e3,onOpen:d,onDismiss:p}=e,f=e.container??tI(t),m=!1,g=null,h=()=>{if(!m)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`),i&&(n.style.maxWidth=`${A.width}px`);let S=n.getBoundingClientRect(),E=l?.()??null,k=E!=null?A.top+E:A.top,D=o==="top-start"||o==="top-end"?k-r-S.height:A.bottom+r,J=o==="bottom-end"||o==="top-end"?A.right-S.width:A.left,T=i?.()??null;if(T!=null){let W=Math.max(A.left,A.right-S.width);J=Math.min(Math.max(A.left+T,A.left),W)}n.style.top=`${D}px`,n.style.left=`${J}px`},b=()=>{m&&(m=!1,g&&(g(),g=null),n.remove())},x=()=>{if(m)return;m=!0,c!=null&&(n.style.zIndex=String(c)),f.appendChild(n),h();let A=(t.ownerDocument??document).defaultView??window,S=t.ownerDocument??document,E=()=>{if(!t.isConnected){b(),p?.("anchor-removed");return}h()},k=$=>{let J=typeof $.composedPath=="function"?$.composedPath():[];J.includes(n)||J.includes(t)||(b(),p?.("outside"))},D=A.setTimeout(()=>{S.addEventListener("pointerdown",k,!0)},0);A.addEventListener("scroll",E,!0),A.addEventListener("resize",E),g=()=>{A.clearTimeout(D),S.removeEventListener("pointerdown",k,!0),A.removeEventListener("scroll",E,!0),A.removeEventListener("resize",E)},d?.()};return{get isOpen(){return m},open:x,close:b,toggle:()=>m?b():x(),reposition:h,destroy:b}}function Mx(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var jp,Ax,Ra=ie(()=>{"use strict";jp=e=>e.nodeType===Node.DOCUMENT_NODE,Ax=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&e.host!==void 0});var Tx,Ex=ie(()=>{"use strict";Tx=`
23
23
  .persona-mention-menu {
24
24
  box-sizing: border-box;
25
25
  display: flex;
@@ -177,30 +177,30 @@ ${t}
177
177
  min-height: 36px;
178
178
  }
179
179
  }
180
- `});function Gp(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}var kx=ie(()=>{"use strict"});function Ix(e){let{config:t,listboxId:n}=e,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=C("span","persona-mention-search-icon"),i=Je(Px.Search,15,"currentColor",2);i&&s.appendChild(i);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":t.searchPlaceholder??"Search context",placeholder:t.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>e.onSearchInput?.(l.value)),l.addEventListener("keydown",P=>e.onSearchKeydown?.(P));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let d=[],p=[],f=-1,m=new Map,g=(P,v)=>`${P}\0${v}`,h=P=>`${n}-opt-${P}`,b=P=>`${n}-grp-${P}`,x=(P,v)=>{let w=d[P];w&&(v?w.setAttribute("data-active","true"):w.removeAttribute("data-active"),w.setAttribute("aria-selected",v?"true":"false"),p[P]?.(v))},A=(P,v=!0)=>{f>=0&&f!==P&&x(f,!1),f=P;let w=d[P];w?(x(P,!0),v&&w.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",w.id),l.setAttribute("aria-activedescendant",w.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},S=(P,v)=>{let w=b(v),L=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":w}});return L.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:w},text:P})),L},E=()=>{let P=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),v=C("span","persona-mention-option-icon");P.appendChild(v);let w="",L=C("span","persona-mention-option-text"),I=C("span","persona-mention-option-labelline"),Y=C("span","persona-mention-option-label");I.appendChild(Y),L.appendChild(I),P.appendChild(L);let _=null,q=null,Z={el:P,index:0,update:(ne,te,re)=>{Z.index=te,P.id=h(te),P.setAttribute("aria-setsize",String(re)),P.setAttribute("aria-posinset",String(te+1)),P.removeAttribute("data-active"),P.setAttribute("aria-selected","false");let pe=ne.iconName??t.chipIconName??"at-sign";if(pe!==w){w=pe;let Se=nI(pe,15,2);v.replaceChildren(...Se?[Se]:[])}Y.textContent!==ne.label&&(Y.textContent=ne.label);let xe=ne.commandArgsPlaceholder?`\u2039${ne.commandArgsPlaceholder}\u203A`:null;xe?(_||(_=C("span","persona-mention-option-arghint"),I.appendChild(_)),_.textContent!==xe&&(_.textContent=xe)):_&&(_.remove(),_=null),ne.description?(q||(q=C("span","persona-mention-option-desc"),L.appendChild(q)),q.textContent!==ne.description&&(q.textContent=ne.description)):q&&(q.remove(),q=null)}};return P.addEventListener("mousedown",ne=>{ne.button===0&&(ne.preventDefault(),e.onSelectIndex(Z.index))}),P.addEventListener("mouseenter",()=>e.onHoverIndex(Z.index)),Z},k=(P,v,w,L,I)=>{let Y=F("div",{className:"persona-mention-option",attrs:{role:"option",id:h(L),"aria-selected":"false","aria-setsize":String(I),"aria-posinset":String(L+1)}}),_=q=>{Y.replaceChildren(t.renderMentionItem({item:P,source:v,query:w,active:q,index:L}))};return _(!1),Y.addEventListener("mousedown",q=>{q.button===0&&(q.preventDefault(),e.onSelectIndex(L))}),Y.addEventListener("mouseenter",()=>e.onHoverIndex(L)),{el:Y,paint:_}},D=P=>{let v=F("div",{className:"persona-mention-status persona-mention-error"});if(v.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${P.label}`})),e.onRetry){let w=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});w.addEventListener("mousedown",L=>L.preventDefault()),w.addEventListener("click",L=>{L.preventDefault(),e.onRetry(P.id)}),v.appendChild(w)}return v};return{el:o,render:P=>{c.replaceChildren(),d=[],p=[],f=-1;let v=new Set,w=0,L=0,I=0,Y=0,_=0,q=P.groups.reduce((Z,ne)=>ne.status==="ready"?Z+ne.items.length:Z,0);for(let Z of P.groups)if(Z.status==="loading"){I++;let ne=S(Z.source.label,_++);ne.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(ne)}else if(Z.status==="error"){Y++;let ne=S(Z.source.label,_++);ne.appendChild(D(Z.source)),c.appendChild(ne)}else if(Z.status==="ready"&&Z.items.length>0){let ne=new Map;for(let re of Z.items){let pe=re.group??Z.source.label,xe=ne.get(pe);xe?xe.push(re):ne.set(pe,[re])}let te=Array.from(ne.entries());te.forEach(([re,pe],xe)=>{let Se=S(re,_++);for(let se of pe){let N=w++,Ee;if(t.renderMentionItem){let de=k(se,Z.source,P.query,N,q);Ee=de.el,p.push(de.paint)}else{let de=g(Z.source.id,se.id),Ge=v.has(de)?void 0:m.get(de);Ge||(Ge=E(),v.has(de)||m.set(de,Ge)),v.add(de),Ge.update(se,N,q),Ee=Ge.el,p.push(null)}d.push(Ee),Se.appendChild(Ee),L++}Z.truncated&&xe===te.length-1&&Se.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Se)})}for(let Z of m.keys())v.has(Z)||m.delete(Z);L===0&&I===0&&Y===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),d.length>0?A(Math.min(Math.max(0,P.activeIndex),d.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:A,destroy:()=>{c.replaceChildren(),d=[],m.clear(),o.remove()},showSearch:(P,v)=>{l.value=P,v&&(l.placeholder=v),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var Px,Lx,nI,Hx=ie(()=>{"use strict";Ye();Px=require("lucide");io();Vp();Lx=new Map,nI=(e,t,n)=>{let o=`${e}|${t}|${n}`,r=Lx.get(o);return r===void 0&&(r=Fp(e,t,"currentColor",n),Lx.set(o,r)),r?r.cloneNode(!0):null}});var oI,rI,Yp,Rx=ie(()=>{"use strict";Ra();Ex();Mp();mg();kx();Hx();kg();oI=e=>!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function",rI=0,Yp=class{#e;#t;#n;#o;#c;#r;#s;#f=null;#p=null;#g=!1;#i="";#a=null;#u=0;#L=null;#b=!1;#w=null;#d=[];#l=[];#m=0;#h=null;#C=null;#v=new Set;#y=new Set;#A=-1;#E=null;#x=null;constructor(t){this.#e=t;let n=t.mentionConfig,o=Tp(n),r=o.filter(i=>i.sources.length>0);this.#t=r.length>0?r:[o[0]],this.#n=this.#t[0],this.#o=n.maxItemsPerGroup??6,this.#c=n.searchDebounceMs??150,this.#s=`persona-mention-listbox-${++rI}`,this.#r=t.mentionConfig.renderMentionMenu?this.#S():Ix({config:t.mentionConfig,listboxId:this.#s,onSelectIndex:i=>this.#R(i),onHoverIndex:i=>this.#F(i,!1),onRetry:i=>this.#le(i),onSearchInput:i=>this.#H(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=t.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.#s)}get input(){return this.#e.composerInput}#S(){let t=document.createElement("div");t.setAttribute("data-persona-mention-menu",""),t.setAttribute("role","listbox"),t.id=this.#s;let n=()=>{let o=this.#e.mentionConfig.renderMentionMenu({query:this.#i,groups:this.#d.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.#d.map(r=>[r.source.id,r.status])),activeIndex:this.#u,select:r=>{let s=this.#d.find(i=>i.items.includes(r));s&&this.#se(s.source,r)},close:()=>this.close()});t.replaceChildren(o)};return{el:t,render:n,setActiveIndex:n,destroy:()=>t.remove()}}isOpen(){return this.#g}openFromButton(t){let n=t&&this.#t.find(i=>i.trigger===t)||this.#t[0],o=this.input.getSelection().start,r=ql(this.input.getLogicalText(),o,[n]);if(r){this.#b=!1,this.#a=r.match,this.#g?(this.#U(n),this.#H(r.match.query)):this.#q(r.match.query,n),this.input.focus();return}let s=this.#w;this.#b=!0,this.#w=n.trigger,this.#a=null,this.#g?(s&&s!==n.trigger&&this.#e.onPickerOpenChange?.(!1,s,this.#s),this.#U(n),this.#H("")):this.#q("",n),this.#r.showSearch?this.#r.showSearch("",n.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,n.trigger,this.#s)}onInput(){let t=this.input.getSelection().start,n=ql(this.input.getLogicalText(),t,this.#t);if(!n){this.#g&&this.close();return}if(this.#k(n.channel,n.match.query)){this.#a=null,this.#g&&this.close(!1);return}this.#a=n.match,this.#g?(this.#U(n.channel),this.#x!==n.match.triggerIndex&&this.#M(),this.#H(n.match.query)):this.#q(n.match.query,n.channel)}#U(t){t!==this.#n&&(this.#n=t,this.#d=[],this.#u=0)}#q(t,n){if(this.#g=!0,this.#n=n,this.#d=[],this.#u=0,this.#A=-1,!this.#f){let o=this.#N();if(this.#f=Bs({anchor:this.#e.anchor,content:this.#r.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.#e.popoverContainer,horizontalOffset:o?()=>this.#E?.x??null:void 0,verticalOffset:o?()=>this.#E?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.#e.anchor.getBoundingClientRect().width;this.#r.el.style.minWidth=`${Math.min(220,r)}px`}}this.#M(),this.#f.open(),Kp(this.#r.el,"persona-mention-menu",Tx),this.#j(),this.#e.emit?.("opened",{trigger:n.trigger}),this.#H(t)}#j(){typeof ResizeObserver>"u"||this.#p||(this.#p=new ResizeObserver(()=>{this.#g&&(this.#M(),this.#f?.reposition())}),this.#p.observe(this.#e.anchor))}#B(){this.#p?.disconnect(),this.#p=null}#N(){return this.#V()&&!!this.input.getLogicalRangeRect}#M(){let t=this.#a,n=this.input.getLogicalRangeRect;if(this.#x=t?.triggerIndex??null,this.#E=null,!t||!n)return;let o=n(t.triggerIndex,t.triggerIndex+1);if(!o)return;let r=this.#e.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.#E={x:l?null:o.left-r.left,y:s}}close(t=!0){this.#g&&(this.#g=!1,this.#B(),this.#C&&clearTimeout(this.#C),this.#h?.abort(),this.#m++,this.#f?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.#b&&(this.#b=!1,this.#r.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#w??this.#n.trigger,this.#s),this.#w=null,t&&this.input.focus()))}#H(t){this.#i=t,this.#u=0,this.#L=null;let n=++this.#m;this.#y.clear(),this.#h?.abort(),this.#h=new AbortController;for(let o of this.#n.sources)this.#v.has(o.id)?this.#D(o.id,"loading"):(this.#y.add(o.id),this.#K(o,n));this.#P(),this.#C&&clearTimeout(this.#C),this.#C=setTimeout(()=>{if(n===this.#m)for(let o of this.#n.sources)this.#v.has(o.id)&&!this.#y.has(o.id)&&this.#K(o,n)},this.#c)}#K(t,n){let o={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#h.signal},r;try{r=t.search(this.#i,o)}catch{this.#D(t.id,"error"),this.#P();return}oI(r)?(this.#v.add(t.id),this.#D(t.id,"loading"),r.then(s=>{n===this.#m&&(this.#z(t.id,s),this.#P())}).catch(()=>{n===this.#m&&(this.#D(t.id,"error"),this.#P())})):this.#z(t.id,r)}#Q(t){let n=this.#d.find(o=>o.source.id===t.id);if(!n){n={source:t,items:[],status:"loading",truncated:!1};let o=this.#n.sources;this.#d.push(n),this.#d.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}#D(t,n){let o=this.#n.sources.find(r=>r.id===t);o&&(this.#Q(o).status=n)}#z(t,n){let o=this.#n.sources.find(s=>s.id===t);if(!o)return;let r=this.#Q(o);r.truncated=n.length>this.#o,r.items=n.slice(0,this.#o),r.status=r.items.length===0?"empty":"ready"}#O(t){return JSON.stringify([t.source.id,t.item.id])}#ne(){this.#l=[];for(let t of this.#d)if(t.status==="ready")for(let n of t.items)this.#l.push({source:t.source,item:n});if(this.#L){let t=this.#l.findIndex(n=>this.#O(n)===this.#L);this.#u=t>=0?t:Math.min(this.#u,Math.max(0,this.#l.length-1))}else this.#u>=this.#l.length&&(this.#u=Math.max(0,this.#l.length-1))}#J(){return{query:this.#i,groups:this.#d,activeIndex:this.#u}}#P(){this.#ne(),this.#r.render(this.#J()),this.#oe(),this.#f?.reposition();let t=this.#d.some(n=>n.status==="loading");this.#l.length===0&&t||this.#l.length!==this.#A&&(this.#A=this.#l.length,this.#e.announce(this.#l.length===0?"No matches":this.#l.length===1?"1 result":`${this.#l.length} results`),this.#e.emit?.("searched",{query:this.#i,results:this.#l.length}))}#F(t,n=!0){t<0||t>=this.#l.length||(this.#u=t,this.#L=this.#O(this.#l[t]),this.#r.setActiveIndex(t,n),this.#oe())}#oe(){this.#g&&!this.#b&&this.#u>=0&&this.#u<this.#l.length?this.input.element.setAttribute("aria-activedescendant",`${this.#s}-opt-${this.#u}`):this.input.element.removeAttribute("aria-activedescendant")}#le(t){let n=this.#n.sources.find(o=>o.id===t);!n||!this.#h||(this.#D(t,"loading"),this.#P(),this.#K(n,this.#m),this.#P())}handleKeydown(t){if(!this.#g)return!1;switch(t.key){case"ArrowDown":return this.#l.length===0||(t.preventDefault(),this.#F((this.#u+1)%this.#l.length)),!0;case"ArrowUp":return this.#l.length===0||(t.preventDefault(),this.#F((this.#u-1+this.#l.length)%this.#l.length)),!0;case"Home":return this.#l.length===0||(t.preventDefault(),this.#F(0)),!0;case"End":return this.#l.length===0||(t.preventDefault(),this.#F(this.#l.length-1)),!0;case"Enter":case"Tab":return this.#l.length===0?(this.close(),!1):(t.preventDefault(),this.#R(this.#u),!0);case"Escape":return t.preventDefault(),this.close(),!0;case"Backspace":return this.#i.length===0&&this.close(),!1;default:return!1}}#R(t){let n=this.#l[t];n&&this.#se(n.source,n.item)}#re(t){return Gp(t).args}#G(t){return t.command==="server"||t.commandArgsPlaceholder!=null}#se(t,n){let o=n.command;if(this.#G(n)){this.#W(t,n);return}if(o==="action"){let s=this.#re(this.#i);this.#de(),this.close(),this.#Z(n,s),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.#re(this.#i),i=this.#$();this.close(),this.#me(t,n,s,i),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"prompt",args:s});return}if(this.#V()){this.#_(t,n);return}this.#e.onSelect(t,n,"")&&(this.#de(),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}#V(){return this.#e.mentionConfig.display==="inline"&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#_(t,n){if(this.#e.admitMention&&!this.#e.admitMention(t,n)){this.close(),this.input.focus();return}let o=Up(t,n),r=this.#a?this.input.insertMentionAtTrigger(o,this.#a):this.input.insertMentionAtSelection?.(o)??null;r?(this.#e.onInsertMention(r,t,n,""),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})):(this.#e.mentionConfig.onMentionRejected?.(n,"stale"),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:"stale"})),this.#a=null,this.close(),this.input.focus()}#W(t,n){let o=`${this.#n.trigger}${n.label} `,r=this.input.getSelection().start,s=this.#a?this.#a.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.#a=null,this.close(),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}#k(t,n){let{name:o}=Gp(n);return!o||n.length<=o.length?!1:t.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.#G(s)})}#Y(t){for(let n of this.#t){if(!n.trigger)continue;let o=n.position==="anywhere"?[t]:n.position==="line-start"?t.split(`
180
+ `});function Gp(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}var kx=ie(()=>{"use strict"});function Ix(e){let{config:t,listboxId:n}=e,o=F("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=F("div",{className:"persona-mention-search",style:{display:"none"}}),s=C("span","persona-mention-search-icon"),i=Je(Px.Search,15,"currentColor",2);i&&s.appendChild(i);let l=F("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":t.searchPlaceholder??"Search context",placeholder:t.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>e.onSearchInput?.(l.value)),l.addEventListener("keydown",P=>e.onSearchKeydown?.(P));let c=F("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,c);let d=[],p=[],f=-1,m=new Map,g=(P,v)=>`${P}\0${v}`,h=P=>`${n}-opt-${P}`,b=P=>`${n}-grp-${P}`,x=(P,v)=>{let w=d[P];w&&(v?w.setAttribute("data-active","true"):w.removeAttribute("data-active"),w.setAttribute("aria-selected",v?"true":"false"),p[P]?.(v))},A=(P,v=!0)=>{f>=0&&f!==P&&x(f,!1),f=P;let w=d[P];w?(x(P,!0),v&&w.scrollIntoView?.({block:"nearest"}),c.setAttribute("aria-activedescendant",w.id),l.setAttribute("aria-activedescendant",w.id)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},S=(P,v)=>{let w=b(v),L=F("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":w}});return L.appendChild(F("div",{className:"persona-mention-group-header",attrs:{id:w},text:P})),L},E=()=>{let P=F("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),v=C("span","persona-mention-option-icon");P.appendChild(v);let w="",L=C("span","persona-mention-option-text"),I=C("span","persona-mention-option-labelline"),Y=C("span","persona-mention-option-label");I.appendChild(Y),L.appendChild(I),P.appendChild(L);let _=null,q=null,Z={el:P,index:0,update:(ne,te,re)=>{Z.index=te,P.id=h(te),P.setAttribute("aria-setsize",String(re)),P.setAttribute("aria-posinset",String(te+1)),P.removeAttribute("data-active"),P.setAttribute("aria-selected","false");let pe=ne.iconName??t.chipIconName??"at-sign";if(pe!==w){w=pe;let Se=nI(pe,15,2);v.replaceChildren(...Se?[Se]:[])}Y.textContent!==ne.label&&(Y.textContent=ne.label);let xe=ne.commandArgsPlaceholder?`\u2039${ne.commandArgsPlaceholder}\u203A`:null;xe?(_||(_=C("span","persona-mention-option-arghint"),I.appendChild(_)),_.textContent!==xe&&(_.textContent=xe)):_&&(_.remove(),_=null),ne.description?(q||(q=C("span","persona-mention-option-desc"),L.appendChild(q)),q.textContent!==ne.description&&(q.textContent=ne.description)):q&&(q.remove(),q=null)}};return P.addEventListener("mousedown",ne=>{ne.button===0&&(ne.preventDefault(),e.onSelectIndex(Z.index))}),P.addEventListener("mouseenter",()=>e.onHoverIndex(Z.index)),Z},k=(P,v,w,L,I)=>{let Y=F("div",{className:"persona-mention-option",attrs:{role:"option",id:h(L),"aria-selected":"false","aria-setsize":String(I),"aria-posinset":String(L+1)}}),_=q=>{Y.replaceChildren(t.renderMentionItem({item:P,source:v,query:w,active:q,index:L}))};return _(!1),Y.addEventListener("mousedown",q=>{q.button===0&&(q.preventDefault(),e.onSelectIndex(L))}),Y.addEventListener("mouseenter",()=>e.onHoverIndex(L)),{el:Y,paint:_}},D=P=>{let v=F("div",{className:"persona-mention-status persona-mention-error"});if(v.appendChild(F("span",{className:"persona-mention-error-text",text:`Couldn't load ${P.label}`})),e.onRetry){let w=F("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});w.addEventListener("mousedown",L=>L.preventDefault()),w.addEventListener("click",L=>{L.preventDefault(),e.onRetry(P.id)}),v.appendChild(w)}return v};return{el:o,render:P=>{c.replaceChildren(),d=[],p=[],f=-1;let v=new Set,w=0,L=0,I=0,Y=0,_=0,q=P.groups.reduce((Z,ne)=>ne.status==="ready"?Z+ne.items.length:Z,0);for(let Z of P.groups)if(Z.status==="loading"){I++;let ne=S(Z.source.label,_++);ne.appendChild(F("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),c.appendChild(ne)}else if(Z.status==="error"){Y++;let ne=S(Z.source.label,_++);ne.appendChild(D(Z.source)),c.appendChild(ne)}else if(Z.status==="ready"&&Z.items.length>0){let ne=new Map;for(let re of Z.items){let pe=re.group??Z.source.label,xe=ne.get(pe);xe?xe.push(re):ne.set(pe,[re])}let te=Array.from(ne.entries());te.forEach(([re,pe],xe)=>{let Se=S(re,_++);for(let se of pe){let N=w++,Ee;if(t.renderMentionItem){let de=k(se,Z.source,P.query,N,q);Ee=de.el,p.push(de.paint)}else{let de=g(Z.source.id,se.id),Ge=v.has(de)?void 0:m.get(de);Ge||(Ge=E(),v.has(de)||m.set(de,Ge)),v.add(de),Ge.update(se,N,q),Ee=Ge.el,p.push(null)}d.push(Ee),Se.appendChild(Ee),L++}Z.truncated&&xe===te.length-1&&Se.appendChild(F("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),c.appendChild(Se)})}for(let Z of m.keys())v.has(Z)||m.delete(Z);L===0&&I===0&&Y===0&&c.appendChild(F("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),d.length>0?A(Math.min(Math.max(0,P.activeIndex),d.length-1)):(c.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:A,destroy:()=>{c.replaceChildren(),d=[],m.clear(),o.remove()},showSearch:(P,v)=>{l.value=P,v&&(l.placeholder=v),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var Px,Lx,nI,Hx=ie(()=>{"use strict";Ye();Px=require("lucide");io();Vp();Lx=new Map,nI=(e,t,n)=>{let o=`${e}|${t}|${n}`,r=Lx.get(o);return r===void 0&&(r=Fp(e,t,"currentColor",n),Lx.set(o,r)),r?r.cloneNode(!0):null}});var oI,rI,Yp,Rx=ie(()=>{"use strict";Ra();Ex();Mp();mg();kx();Hx();kg();oI=e=>!!e&&(typeof e=="object"||typeof e=="function")&&typeof e.then=="function",rI=0,Yp=class{#e;#t;#n;#o;#i;#r;#s;#g=null;#c=null;#f=!1;#p="";#l=null;#a=0;#S=null;#b=!1;#w=null;#y=[];#d=[];#u=0;#m=null;#h=null;#x=new Set;#A=new Set;#C=-1;#v=null;#P=null;constructor(t){this.#e=t;let n=t.mentionConfig,o=Tp(n),r=o.filter(i=>i.sources.length>0);this.#t=r.length>0?r:[o[0]],this.#n=this.#t[0],this.#o=n.maxItemsPerGroup??6,this.#i=n.searchDebounceMs??150,this.#s=`persona-mention-listbox-${++rI}`,this.#r=t.mentionConfig.renderMentionMenu?this.#k():Ix({config:t.mentionConfig,listboxId:this.#s,onSelectIndex:i=>this.#B(i),onHoverIndex:i=>this.#R(i,!1),onRetry:i=>this.#le(i),onSearchInput:i=>this.#O(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=t.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.#s)}get input(){return this.#e.composerInput}#k(){let t=document.createElement("div");t.setAttribute("data-persona-mention-menu",""),t.setAttribute("role","listbox"),t.id=this.#s;let n=()=>{let o=this.#e.mentionConfig.renderMentionMenu({query:this.#p,groups:this.#y.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.#y.map(r=>[r.source.id,r.status])),activeIndex:this.#a,select:r=>{let s=this.#y.find(i=>i.items.includes(r));s&&this.#oe(s.source,r)},close:()=>this.close()});t.replaceChildren(o)};return{el:t,render:n,setActiveIndex:n,destroy:()=>t.remove()}}isOpen(){return this.#f}openFromButton(t){let n=t&&this.#t.find(i=>i.trigger===t)||this.#t[0],o=this.input.getSelection().start,r=ql(this.input.getLogicalText(),o,[n]);if(r){this.#b=!1,this.#l=r.match,this.#f?(this.#M(n),this.#O(r.match.query)):this.#I(r.match.query,n),this.input.focus();return}let s=this.#w;this.#b=!0,this.#w=n.trigger,this.#l=null,this.#f?(s&&s!==n.trigger&&this.#e.onPickerOpenChange?.(!1,s,this.#s),this.#M(n),this.#O("")):this.#I("",n),this.#r.showSearch?this.#r.showSearch("",n.searchPlaceholder):this.input.focus(),this.#e.onPickerOpenChange?.(!0,n.trigger,this.#s)}onInput(){let t=this.input.getSelection().start,n=ql(this.input.getLogicalText(),t,this.#t);if(!n){this.#f&&this.close();return}if(this.#D(n.channel,n.match.query)){this.#l=null,this.#f&&this.close(!1);return}this.#l=n.match,this.#f?(this.#M(n.channel),this.#P!==n.match.triggerIndex&&this.#T(),this.#O(n.match.query)):this.#I(n.match.query,n.channel)}#M(t){t!==this.#n&&(this.#n=t,this.#y=[],this.#a=0)}#I(t,n){if(this.#f=!0,this.#n=n,this.#y=[],this.#a=0,this.#C=-1,!this.#g){let o=this.#V();if(this.#g=Bs({anchor:this.#e.anchor,content:this.#r.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.#e.popoverContainer,horizontalOffset:o?()=>this.#v?.x??null:void 0,verticalOffset:o?()=>this.#v?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.#e.anchor.getBoundingClientRect().width;this.#r.el.style.minWidth=`${Math.min(220,r)}px`}}this.#T(),this.#g.open(),Kp(this.#r.el,"persona-mention-menu",Tx),this.#X(),this.#e.emit?.("opened",{trigger:n.trigger}),this.#O(t)}#X(){typeof ResizeObserver>"u"||this.#c||(this.#c=new ResizeObserver(()=>{this.#f&&(this.#T(),this.#g?.reposition())}),this.#c.observe(this.#e.anchor))}#z(){this.#c?.disconnect(),this.#c=null}#V(){return this.#ne()&&!!this.input.getLogicalRangeRect}#T(){let t=this.#l,n=this.input.getLogicalRangeRect;if(this.#P=t?.triggerIndex??null,this.#v=null,!t||!n)return;let o=n(t.triggerIndex,t.triggerIndex+1);if(!o)return;let r=this.#e.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.#v={x:l?null:o.left-r.left,y:s}}close(t=!0){this.#f&&(this.#f=!1,this.#z(),this.#h&&clearTimeout(this.#h),this.#m?.abort(),this.#u++,this.#g?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.#b&&(this.#b=!1,this.#r.hideSearch?.(),this.#e.onPickerOpenChange?.(!1,this.#w??this.#n.trigger,this.#s),this.#w=null,t&&this.input.focus()))}#O(t){this.#p=t,this.#a=0,this.#S=null;let n=++this.#u;this.#A.clear(),this.#m?.abort(),this.#m=new AbortController;for(let o of this.#n.sources)this.#x.has(o.id)?this.#j(o.id,"loading"):(this.#A.add(o.id),this.#W(o,n));this.#q(),this.#h&&clearTimeout(this.#h),this.#h=setTimeout(()=>{if(n===this.#u)for(let o of this.#n.sources)this.#x.has(o.id)&&!this.#A.has(o.id)&&this.#W(o,n)},this.#i)}#W(t,n){let o={messages:this.#e.getMessages(),config:this.#e.getConfig(),signal:this.#m.signal},r;try{r=t.search(this.#p,o)}catch{this.#j(t.id,"error"),this.#q();return}oI(r)?(this.#x.add(t.id),this.#j(t.id,"loading"),r.then(s=>{n===this.#u&&(this.#ee(t.id,s),this.#q())}).catch(()=>{n===this.#u&&(this.#j(t.id,"error"),this.#q())})):this.#ee(t.id,r)}#$(t){let n=this.#y.find(o=>o.source.id===t.id);if(!n){n={source:t,items:[],status:"loading",truncated:!1};let o=this.#n.sources;this.#y.push(n),this.#y.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}#j(t,n){let o=this.#n.sources.find(r=>r.id===t);o&&(this.#$(o).status=n)}#ee(t,n){let o=this.#n.sources.find(s=>s.id===t);if(!o)return;let r=this.#$(o);r.truncated=n.length>this.#o,r.items=n.slice(0,this.#o),r.status=r.items.length===0?"empty":"ready"}#_(t){return JSON.stringify([t.source.id,t.item.id])}#Q(){this.#d=[];for(let t of this.#y)if(t.status==="ready")for(let n of t.items)this.#d.push({source:t.source,item:n});if(this.#S){let t=this.#d.findIndex(n=>this.#_(n)===this.#S);this.#a=t>=0?t:Math.min(this.#a,Math.max(0,this.#d.length-1))}else this.#a>=this.#d.length&&(this.#a=Math.max(0,this.#d.length-1))}#te(){return{query:this.#p,groups:this.#y,activeIndex:this.#a}}#q(){this.#Q(),this.#r.render(this.#te()),this.#U(),this.#g?.reposition();let t=this.#y.some(n=>n.status==="loading");this.#d.length===0&&t||this.#d.length!==this.#C&&(this.#C=this.#d.length,this.#e.announce(this.#d.length===0?"No matches":this.#d.length===1?"1 result":`${this.#d.length} results`),this.#e.emit?.("searched",{query:this.#p,results:this.#d.length}))}#R(t,n=!0){t<0||t>=this.#d.length||(this.#a=t,this.#S=this.#_(this.#d[t]),this.#r.setActiveIndex(t,n),this.#U())}#U(){this.#f&&!this.#b&&this.#a>=0&&this.#a<this.#d.length?this.input.element.setAttribute("aria-activedescendant",`${this.#s}-opt-${this.#a}`):this.input.element.removeAttribute("aria-activedescendant")}#le(t){let n=this.#n.sources.find(o=>o.id===t);!n||!this.#m||(this.#j(t,"loading"),this.#q(),this.#W(n,this.#u),this.#q())}handleKeydown(t){if(!this.#f)return!1;switch(t.key){case"ArrowDown":return this.#d.length===0||(t.preventDefault(),this.#R((this.#a+1)%this.#d.length)),!0;case"ArrowUp":return this.#d.length===0||(t.preventDefault(),this.#R((this.#a-1+this.#d.length)%this.#d.length)),!0;case"Home":return this.#d.length===0||(t.preventDefault(),this.#R(0)),!0;case"End":return this.#d.length===0||(t.preventDefault(),this.#R(this.#d.length-1)),!0;case"Enter":case"Tab":return this.#d.length===0?(this.close(),!1):(t.preventDefault(),this.#B(this.#a),!0);case"Escape":return t.preventDefault(),this.close(),!0;case"Backspace":return this.#p.length===0&&this.close(),!1;default:return!1}}#B(t){let n=this.#d[t];n&&this.#oe(n.source,n.item)}#ce(t){return Gp(t).args}#J(t){return t.command==="server"||t.commandArgsPlaceholder!=null}#oe(t,n){let o=n.command;if(this.#J(n)){this.#K(t,n);return}if(o==="action"){let s=this.#ce(this.#p);this.#se(),this.close(),this.#F(n,s),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.#ce(this.#p),i=this.#G();this.close(),this.#ve(t,n,s,i),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:"prompt",args:s});return}if(this.#ne()){this.#re(t,n);return}this.#e.onSelect(t,n,"")&&(this.#se(),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}#ne(){return this.#e.mentionConfig.display==="inline"&&!!this.#e.onInsertMention&&!!this.input.insertMentionAtTrigger}#re(t,n){if(this.#e.admitMention&&!this.#e.admitMention(t,n)){this.close(),this.input.focus();return}let o=Up(t,n),r=this.#l?this.input.insertMentionAtTrigger(o,this.#l):this.input.insertMentionAtSelection?.(o)??null;r?(this.#e.onInsertMention(r,t,n,""),this.#e.emit?.("selected",{sourceId:t.id,itemId:n.id,label:n.label})):(this.#e.mentionConfig.onMentionRejected?.(n,"stale"),this.#e.emit?.("rejected",{sourceId:t.id,itemId:n.id,reason:"stale"})),this.#l=null,this.close(),this.input.focus()}#K(t,n){let o=`${this.#n.trigger}${n.label} `,r=this.input.getSelection().start,s=this.#l?this.#l.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.#l=null,this.close(),this.#e.emit?.("command",{sourceId:t.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}#D(t,n){let{name:o}=Gp(n);return!o||n.length<=o.length?!1:t.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.#J(s)})}#N(t){for(let n of this.#t){if(!n.trigger)continue;let o=n.position==="anywhere"?[t]:n.position==="line-start"?t.split(`
181
181
  `):[t.split(`
182
- `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Gp(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.#G(c))return{source:l,item:c,args:i}}}}return null}async dispatchInlineCommand(t){let n=this.#Y(t);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.#e.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.#Z(r,s),{kind:"action"};if(i==="prompt"){let c;try{c=await o.resolve(r,this.#ce(s,t))}catch(d){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",d),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??t}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.#ce(s,t)),d={};return c.context&&(d[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:d}}}}}#ce(t,n){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:n,args:t,signal:new AbortController().signal}}#Z(t,n){if(t.action)try{Promise.resolve(t.action({args:n,config:this.#e.getConfig(),messages:this.#e.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}#$(){return this.#a?{value:this.input.getValue(),start:this.#a.triggerIndex,end:this.input.getSelection().start}:null}async#me(t,n,o,r){let s=this.input,i;try{i=await t.resolve(n,{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}#de(){if(!this.#a)return;let t=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.#a.triggerIndex,t,"");else{let n=ax(this.input.getValue(),this.#a,t);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.#a=null}destroy(){this.#B(),this.#C&&clearTimeout(this.#C),this.#h?.abort(),this.#f?.destroy(),this.#r.destroy();let t=this.input.element;t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-controls"),t.removeAttribute("aria-activedescendant")}}});function Gl(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Wx(e){let t=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:e,getValue:()=>e.value,getLogicalText:()=>e.value,getSelection:()=>({start:e.selectionStart??0,end:e.selectionEnd??0}),setSelection:(n,o=n)=>{e.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{e.value=n,e.setSelectionRange(o,o)},setValue:n=>{e.value=n,e.setSelectionRange(n.length,n.length),t(),e.focus()},submit:()=>Gl(e.form),dispatchInput:t,focus:()=>e.focus()}}var Xp=ie(()=>{"use strict"});function Lg(e,t){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",e),n.setAttribute("aria-atomic","true"),n.setAttribute("role",e==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=t.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,sI),document.body.appendChild(n)):t.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var sI,Bx=ie(()=>{"use strict";sI={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function Dx(e){let t=e.composerInput??Wx(e.textarea),n=Lg("polite",e.liveRegionHost),o=Lg("assertive",e.liveRegionHost),r=d=>n.announce(d),s=d=>o.announce(d),i=new zp({mentionConfig:e.mentionConfig,contextRow:e.contextRow,getMessages:e.getMessages,getConfig:e.getConfig,getComposerText:()=>t.getValue(),announce:r,announceError:s,emit:e.emit}),l=()=>new Yp({mentionConfig:e.mentionConfig,composerInput:t,anchor:e.anchor,getMessages:e.getMessages,getConfig:e.getConfig,onSelect:(d,p,f)=>i.add(d,p,f),onInsertMention:(d,p,f,m)=>i.track(d,p,f,m,g=>t.setMentionStatus?.(d,g)),admitMention:(d,p)=>i.admit(d,p),announce:r,popoverContainer:e.popoverContainer,onPickerOpenChange:e.onPickerOpenChange,emit:e.emit}),c=l();return{openMenu:d=>c.openFromButton(d),isMenuOpen:()=>c.isOpen(),handleInput:()=>c.onInput(),handleKeydown:d=>c.handleKeydown(d),hasMentions:()=>i.hasMentions(),getMentionRefs:()=>i.getRefs(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:d=>c.dispatchInlineCommand(d),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:d=>i.remove(d),rebindComposer:d=>{d!==t&&(c.destroy(),t=d,c=l())},clear:()=>i.clear(),destroy:()=>{c.destroy(),i.clear(),n.destroy(),o.destroy()}}}var Ox=ie(()=>{"use strict";kg();Rx();Xp();Bx();Vp()});var _x={};En(_x,{mountContextMentions:()=>Dx,setMentionIconRenderer:()=>Ag});var Nx=ie(()=>{"use strict";Ox()});var kN,iI,Qp,Pg=ie(()=>{"use strict";Bn();({setLoader:kN,load:iI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Nx(),_x))})),Qp=iI});function Hg(e){return e.kind==="text"?e.value.length:1}function Rg(e){let t=[],n=r=>{let s=t[t.length-1];s&&s.kind==="text"?s.value+=r:t.push({kind:"text",value:r})};(e.length===0||e[0].kind!=="text")&&t.push({kind:"text",value:""});for(let r of e){if(r.kind==="text"){n(r.value);continue}let s=t[t.length-1];(!s||s.kind!=="text")&&t.push({kind:"text",value:""}),t.push({kind:"mention",id:r.id,ref:r.ref}),t.push({kind:"text",value:""})}let o=t[t.length-1];return(!o||o.kind!=="text")&&t.push({kind:"text",value:""}),t}function Fx(){return{blocks:[{kind:"text",value:""}]}}function Wg(e){return{blocks:[{kind:"text",value:e}]}}function Bg(e){return e.blocks.map(t=>t.kind==="text"?t.value:`${aI}${t.ref.label}`).join("")}function Zp(e){return e.blocks.map(t=>t.kind==="text"?t.value:"\uFFFC").join("")}function eu(e){return e.blocks.reduce((t,n)=>t+Hg(n),0)}function lI(e){let t=[];for(let n of e.blocks)n.kind==="mention"&&t.push({id:n.id,ref:n.ref});return t}function Jp(e,t){let n=[],o=[],r=0;for(let s of e){let i=Hg(s),l=r+i;if(l<=t)n.push(s);else if(r>=t)o.push(s);else if(s.kind==="text"){let c=t-r;c>0&&n.push({kind:"text",value:s.value.slice(0,c)}),c<i&&o.push({kind:"text",value:s.value.slice(c)})}else o.push(s);r=l}return{left:n,right:o}}function Dg(e,t,n,o){let r=Jp(e.blocks,t.start).left,s=Jp(e.blocks,t.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",c=l!==" "&&l!==" "&&l!==`
182
+ `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Gp(r.slice(n.trigger.length));if(s)for(let l of n.sources){let c=l.matchCommand?.(s);if(c&&this.#J(c))return{source:l,item:c,args:i}}}}return null}async dispatchInlineCommand(t){let n=this.#N(t);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.#e.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.#F(r,s),{kind:"action"};if(i==="prompt"){let c;try{c=await o.resolve(r,this.#L(s,t))}catch(d){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",d),null}return{kind:"prompt",sendText:c.insertText??c.llmAppend??t}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let c=await o.resolve(r,this.#L(s,t)),d={};return c.context&&(d[o.id]={[r.id]:c.context}),{blocks:[],contentParts:c.contentParts??[],context:d}}}}}#L(t,n){return{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:n,args:t,signal:new AbortController().signal}}#F(t,n){if(t.action)try{Promise.resolve(t.action({args:n,config:this.#e.getConfig(),messages:this.#e.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}#G(){return this.#l?{value:this.input.getValue(),start:this.#l.triggerIndex,end:this.input.getSelection().start}:null}async#ve(t,n,o,r){let s=this.input,i;try{i=await t.resolve(n,{messages:this.#e.getMessages(),config:this.#e.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(c){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",c);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}#se(){if(!this.#l)return;let t=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.#l.triggerIndex,t,"");else{let n=ax(this.input.getValue(),this.#l,t);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.#l=null}destroy(){this.#z(),this.#h&&clearTimeout(this.#h),this.#m?.abort(),this.#g?.destroy(),this.#r.destroy();let t=this.input.element;t.removeAttribute("aria-haspopup"),t.removeAttribute("aria-controls"),t.removeAttribute("aria-activedescendant")}}});function Gl(e){e&&(typeof e.requestSubmit=="function"?e.requestSubmit():e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Wx(e){let t=()=>{e.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:e,getValue:()=>e.value,getLogicalText:()=>e.value,getSelection:()=>({start:e.selectionStart??0,end:e.selectionEnd??0}),setSelection:(n,o=n)=>{e.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{e.value=n,e.setSelectionRange(o,o)},setValue:n=>{e.value=n,e.setSelectionRange(n.length,n.length),t(),e.focus()},submit:()=>Gl(e.form),dispatchInput:t,focus:()=>e.focus()}}var Xp=ie(()=>{"use strict"});function Lg(e,t){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",e),n.setAttribute("aria-atomic","true"),n.setAttribute("role",e==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=t.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,sI),document.body.appendChild(n)):t.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var sI,Bx=ie(()=>{"use strict";sI={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function Dx(e){let t=e.composerInput??Wx(e.textarea),n=Lg("polite",e.liveRegionHost),o=Lg("assertive",e.liveRegionHost),r=d=>n.announce(d),s=d=>o.announce(d),i=new zp({mentionConfig:e.mentionConfig,contextRow:e.contextRow,getMessages:e.getMessages,getConfig:e.getConfig,getComposerText:()=>t.getValue(),announce:r,announceError:s,emit:e.emit}),l=()=>new Yp({mentionConfig:e.mentionConfig,composerInput:t,anchor:e.anchor,getMessages:e.getMessages,getConfig:e.getConfig,onSelect:(d,p,f)=>i.add(d,p,f),onInsertMention:(d,p,f,m)=>i.track(d,p,f,m,g=>t.setMentionStatus?.(d,g)),admitMention:(d,p)=>i.admit(d,p),announce:r,popoverContainer:e.popoverContainer,onPickerOpenChange:e.onPickerOpenChange,emit:e.emit}),c=l();return{openMenu:d=>c.openFromButton(d),isMenuOpen:()=>c.isOpen(),handleInput:()=>c.onInput(),handleKeydown:d=>c.handleKeydown(d),hasMentions:()=>i.hasMentions(),getMentionRefs:()=>i.getRefs(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:d=>c.dispatchInlineCommand(d),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:d=>i.remove(d),rebindComposer:d=>{d!==t&&(c.destroy(),t=d,c=l())},clear:()=>i.clear(),destroy:()=>{c.destroy(),i.clear(),n.destroy(),o.destroy()}}}var Ox=ie(()=>{"use strict";kg();Rx();Xp();Bx();Vp()});var _x={};En(_x,{mountContextMentions:()=>Dx,setMentionIconRenderer:()=>Ag});var Nx=ie(()=>{"use strict";Ox()});var kN,iI,Qp,Pg=ie(()=>{"use strict";Bn();({setLoader:kN,load:iI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Nx(),_x))})),Qp=iI});function Hg(e){return e.kind==="text"?e.value.length:1}function Rg(e){let t=[],n=r=>{let s=t[t.length-1];s&&s.kind==="text"?s.value+=r:t.push({kind:"text",value:r})};(e.length===0||e[0].kind!=="text")&&t.push({kind:"text",value:""});for(let r of e){if(r.kind==="text"){n(r.value);continue}let s=t[t.length-1];(!s||s.kind!=="text")&&t.push({kind:"text",value:""}),t.push({kind:"mention",id:r.id,ref:r.ref}),t.push({kind:"text",value:""})}let o=t[t.length-1];return(!o||o.kind!=="text")&&t.push({kind:"text",value:""}),t}function Fx(){return{blocks:[{kind:"text",value:""}]}}function Wg(e){return{blocks:[{kind:"text",value:e}]}}function Bg(e){return e.blocks.map(t=>t.kind==="text"?t.value:`${aI}${t.ref.label}`).join("")}function Zp(e){return e.blocks.map(t=>t.kind==="text"?t.value:"\uFFFC").join("")}function eu(e){return e.blocks.reduce((t,n)=>t+Hg(n),0)}function lI(e){let t=[];for(let n of e.blocks)n.kind==="mention"&&t.push({id:n.id,ref:n.ref});return t}function Jp(e,t){let n=[],o=[],r=0;for(let s of e){let i=Hg(s),l=r+i;if(l<=t)n.push(s);else if(r>=t)o.push(s);else if(s.kind==="text"){let c=t-r;c>0&&n.push({kind:"text",value:s.value.slice(0,c)}),c<i&&o.push({kind:"text",value:s.value.slice(c)})}else o.push(s);r=l}return{left:n,right:o}}function Dg(e,t,n,o){let r=Jp(e.blocks,t.start).left,s=Jp(e.blocks,t.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",c=l!==" "&&l!==" "&&l!==`
183
183
  `,d=Rg([...r,{kind:"mention",id:o,ref:n},...c?[{kind:"text",value:" "}]:[],...s]),p=t.start+1+(l===`
184
184
  `?0:1);return{doc:{blocks:d},caret:p}}function Vx(e,t){let n=0,o=0,r=!1;for(let i of e.blocks)i.kind==="mention"&&i.id===t&&(n=o,r=!0),o+=Hg(i);return r?{doc:{blocks:Rg(e.blocks.filter(i=>!(i.kind==="mention"&&i.id===t)))},caret:n}:{doc:e,caret:o}}function tu(e,t,n,o){let r=eu(e),s=Math.max(0,Math.min(t,n,r)),i=Math.min(r,Math.max(t,n,0)),l=Jp(e.blocks,s).left,c=Jp(e.blocks,i).right;return{doc:{blocks:Rg([...l,{kind:"text",value:o},...c])},caret:s+o.length}}function $x(e){let t=[];for(let n of e.blocks)n.kind==="text"?n.value.length>0&&t.push({kind:"text",text:n.value}):t.push({kind:"mention",ref:n.ref});return{content:Bg(e),contextMentions:lI(e).map(n=>n.ref),contentSegments:t}}var aI,Og=ie(()=>{"use strict";Mp();aI="@"});function Jl(e){return e.nodeType===1&&e.hasAttribute(Ql)}function qx(e){return e.nodeType===1&&e.tagName==="BR"}function nu(e){return e.nodeType===3?e.data.length:Jl(e)||qx(e)?1:e.textContent?.length??0}function Ux(e,t,n){let o=0;for(let r of Array.from(e.childNodes)){if(r===t)return r.nodeType===3?o+n:o+(n>0?nu(r):0);if(r.contains(t))return Jl(r)?o+1:o+dI(r,t,n);o+=nu(r)}if(t===e){let r=0,s=Array.from(e.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=nu(s[i]);return r}return o}function dI(e,t,n){let o=0,r=s=>{if(s===t)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let i of Array.from(s.childNodes))if(r(i))return!0;return!1};return r(e),o}function Xl(e,t){let n=0,o=Array.from(e.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=nu(s);if(t<=n+i)return s.nodeType===3?{node:s,offset:t-n}:{node:e,offset:t<=n?r:r+1};n+=i}return{node:e,offset:o.length}}function pI(e,t){let n=[];for(let o of Array.from(e.childNodes))if(Jl(o)){let r=o.getAttribute(Ql),s=t.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(qx(o))n.push({kind:"text",value:zx});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function jx(e){let t=e.renderToken,n=new Map,o=e.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.setAttribute("dir","auto"),o.classList.add("persona-composer-contenteditable"),e.placeholder!=null&&o.setAttribute("data-placeholder",e.placeholder);let r=!1,s=0,i=()=>pI(o,n),l=T=>{o.replaceChildren();for(let W of T.blocks)if(W.kind==="text")W.value.length>0&&o.appendChild(document.createTextNode(W.value));else{n.set(W.id,W.ref);let P=t(W.ref);P.setAttribute("contenteditable","false"),P.setAttribute(Ql,W.id),o.appendChild(P)}},c=()=>{let W=o.getRootNode().activeElement;return W===o||W!=null&&o.contains(W)},d=(T,W)=>{if(s=T,!W?.focus&&!c())return;let P=typeof window<"u"?window.getSelection():null;if(!P)return;let v=Xl(o,T);try{let w=document.createRange();w.setStart(v.node,v.offset),w.collapse(!0),P.removeAllRanges(),P.addRange(w)}catch{}},p=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},f=()=>{let T={start:s,end:s},W=typeof window<"u"?window.getSelection():null;if(!W||W.rangeCount===0)return T;let P=W.getRangeAt(0);if(!o.contains(P.startContainer))return T;let v=Ux(o,P.startContainer,P.startOffset),w=P.collapsed?v:Ux(o,P.endContainer,P.endOffset);return{start:Math.min(v,w),end:Math.max(v,w)}},m=()=>{let T=new Set;for(let W of Array.from(o.childNodes))Jl(W)&&T.add(W.getAttribute(Ql));for(let W of Array.from(n.keys()))T.has(W)||(n.delete(W),e.onMentionRemoved?.(W))},g=()=>{r||n.size!==0&&m()},h=()=>{r=!0},b=()=>{r=!1,m()},x=T=>{T.preventDefault();let W=T.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,W);else{let{start:P,end:v}=f(),w=tu(i(),P,v,W);l(w.doc),d(w.caret,{focus:!0}),m()}p()},A=T=>{if(r)return;let W=T.inputType;if(W==="insertParagraph"){T.preventDefault();let{start:Z,end:ne}=f(),te=tu(i(),Z,ne,zx);l(te.doc),d(te.caret,{focus:!0}),n.size>0&&m(),p();return}if(W!=="deleteContentBackward"&&W!=="deleteContentForward"||n.size===0)return;let{start:P,end:v}=f();if(P!==v)return;let w=i(),L=Zp(w),I=W==="deleteContentBackward"?P-1:P;if(I<0||I>=L.length||L[I]!=="\uFFFC")return;let Y=0,_=null;for(let Z of w.blocks){let ne=Z.kind==="text"?Z.value.length:1;if(Z.kind==="mention"&&I>=Y&&I<Y+ne){_=Z.id;break}Y+=ne}if(!_)return;T.preventDefault();let q=Vx(w,_);l(q.doc),d(q.caret,{focus:!0}),m(),p()},S=(T,W)=>{l(Wg(T)),d(W)},E=(T,W)=>{if(!Number.isFinite(T)||!Number.isFinite(W)||W<=T)return null;try{let P=Xl(o,T),v=Xl(o,W),w=document.createRange();w.setStart(P.node,P.offset),w.setEnd(v.node,v.offset);let L=w.getBoundingClientRect();return L.width===0&&L.height===0?null:L}catch{return null}},k=(T,W,P)=>{let v=tu(i(),T,W,P);l(v.doc),d(v.caret,{focus:!0})},D=(T,W)=>{let P=i(),v=Zp(P),w=W.triggerIndex,L=W.triggerIndex+1+W.query.length;if(w<0||L>v.length||v.slice(w+1,L)!==W.query)return null;let I=e.generateId(),Y=Dg(P,{start:w,end:L},T,I);return l(Y.doc),d(Y.caret,{focus:!0}),e.onMentionInserted?.(I,T),p(),I},$=T=>{let W=i(),P=f(),w=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:P.start,end:P.end}:{start:eu(W),end:eu(W)},L=e.generateId(),I=Dg(W,w,T,L);return l(I.doc),d(I.caret,{focus:!0}),e.onMentionInserted?.(L,T),p(),L},J=(T,W)=>{for(let P of Array.from(o.childNodes))if(Jl(P)&&P.getAttribute(Ql)===T){let v=W==="error";if(P.classList.toggle(cI,v),v){P.hasAttribute(Yl)||(P.setAttribute(Yl,P.getAttribute("aria-label")??""),P.setAttribute(_g,P.getAttribute("title")??""));let w=n.get(T)?.label??"";P.setAttribute("title",`${w}: failed to attach context`),P.setAttribute("aria-label",`${w}, failed to attach context`)}else if(P.hasAttribute(Yl)){let w=P.getAttribute(Yl),L=P.getAttribute(_g);w?P.setAttribute("aria-label",w):P.removeAttribute("aria-label"),L?P.setAttribute("title",L):P.removeAttribute("title"),P.removeAttribute(Yl),P.removeAttribute(_g)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",h),o.addEventListener("compositionend",b),o.addEventListener("paste",x),o.addEventListener("beforeinput",A),l(Fx()),{element:o,getValue:()=>Bg(i()),getLogicalText:()=>Zp(i()),getDocument:i,getSelection:f,setSelection:(T,W=T)=>{let P=typeof window<"u"?window.getSelection():null;if(P)try{let v=Xl(o,T),w=Xl(o,W),L=document.createRange();L.setStart(v.node,v.offset),L.setEnd(w.node,w.offset),P.removeAllRanges(),P.addRange(L)}catch{}},setValueWithCaret:S,getLogicalRangeRect:E,setValue:T=>{l(Wg(T)),o.focus(),d(T.length,{focus:!0}),p()},replaceLogicalRange:k,insertMentionAtTrigger:D,insertMentionAtSelection:$,setMentionStatus:J,submit:()=>Gl(o.closest("form")),dispatchInput:p,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",h),o.removeEventListener("compositionend",b),o.removeEventListener("paste",x),o.removeEventListener("beforeinput",A)}}}var cI,Ql,Yl,_g,zx,Kx=ie(()=>{"use strict";Og();Xp();cI="persona-mention-token-error",Ql="data-mention-id",Yl="data-mention-prev-label",_g="data-mention-prev-title",zx=`
185
185
  `});function mI(e,t){t.className=`${e.className} persona-composer-contenteditable`.trim();for(let r=0;r<e.style.length;r++){let s=e.style.item(r);s!=="height"&&t.style.setProperty(s,e.style.getPropertyValue(s),e.style.getPropertyPriority(s))}let n=e.getAttribute("placeholder");n&&(t.setAttribute("data-placeholder",n),t.setAttribute("aria-placeholder",n));let o=e.getAttribute("aria-label")??n;o&&t.setAttribute("aria-label",o)}function gI(e,t,n){Object.defineProperty(e,"value",{configurable:!0,get:()=>t.getValue(),set:o=>{t.setValueWithCaret(o,o.length),t.dispatchInput()}}),Object.defineProperty(e,"placeholder",{configurable:!0,get:()=>e.getAttribute("data-placeholder")??"",set:o=>{o?(e.setAttribute("data-placeholder",o),e.setAttribute("aria-placeholder",o),n||e.setAttribute("aria-label",o)):(e.removeAttribute("data-placeholder"),e.removeAttribute("aria-placeholder"),n||e.removeAttribute("aria-label"))}}),Object.defineProperty(e,"selectionStart",{configurable:!0,get:()=>t.getSelection().start}),Object.defineProperty(e,"selectionEnd",{configurable:!0,get:()=>t.getSelection().end}),e.setSelectionRange=(o,r)=>t.setSelection(o??0,r??o??0)}function Gx(e){let{textarea:t}=e,n={generateId:fI,renderToken:e.renderToken,onMentionRemoved:e.onMentionRemoved,placeholder:t.getAttribute("placeholder")??void 0},o=jx(n),r=o.element,s=t.getAttribute("aria-label")!=null;mI(t,r),gI(r,o,s),r.getInlineMessageFields=()=>$x(o.getDocument?.()??{blocks:[]});let i=t.selectionStart??t.value.length;return o.setValueWithCaret(t.value,i),{input:o,element:r,destroy:o.destroy}}var uI,fI,Yx=ie(()=>{"use strict";Kx();Og();uI=0,fI=()=>`pmention-${++uI}`});var Xx={};En(Xx,{mountInlineComposer:()=>Gx});var Qx=ie(()=>{"use strict";Yx()});var FN,hI,ou,Ng=ie(()=>{"use strict";Bn();({setLoader:FN,load:hI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Qx(),Xx)),resetOnSetLoader:!0})),ou=hI});function Zl(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=F("span",{className:Jt("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=Re(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=C("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(F("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}var Fg=ie(()=>{"use strict";Ye();ln()});function Jx(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:o,createMentionButton:r}=e.deps??yI,s=e.config.contextMentions;if(!s?.enabled)return null;let i=Tp(s).filter(T=>T.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(T=>T.sources.some(W=>typeof W.matchCommand=="function")),c=T=>l.some(W=>W.trigger?W.position==="line-start"?T.split(`
186
186
  `).some(v=>v.startsWith(W.trigger)):(W.position==="anywhere"?T:T.split(`
187
- `)[0]).startsWith(W.trigger):!1),d=(T,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:W}))}catch{}},p=!e.chipRow,f=e.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),m=null,g=null,h=e.textarea,b=null,x=null,A=null,S=null,E=()=>{if(m)return Promise.resolve(m);if(g)return g;let T=t().then(W=>(W.setMentionIconRenderer(o),m=W.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:b??void 0,anchor:e.anchor,contextRow:f,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:J,emit:d}),m)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),g===T&&(g=null),null));return g=T,T},k=()=>{n().then(T=>{let W=T.mountInlineComposer({textarea:e.textarea,renderToken:v=>Zl(v,{render:s.renderMentionToken}),onMentionRemoved:v=>m?.untrackMention(v)});b=W.input,x=W.destroy;let P=h;P.replaceWith(W.element),h=W.element,S={next:W.element,prev:P},A?.(W.element,P),m?m.rebindComposer(W.input):g&&g.then(v=>v?.rebindComposer(W.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};s.display==="inline"&&k();let D=[],$=new Map;for(let T of i){if(!T.showButton)continue;let W=r({config:{...s,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{E().then(P=>P?.openMenu(T.trigger))}});D.push(W),$.set(T.trigger,W.button)}let J=(T,W,P)=>{let v=$.get(W);v&&(v.setAttribute("aria-expanded",T?"true":"false"),T?v.setAttribute("aria-controls",P):v.removeAttribute("aria-controls"))};return{affordanceButtons:D.map(T=>T.wrapper),contextRow:f,handleInput:T=>{if(m){m.handleInput();return}if(!ix(T))return;let W=h,P=W.selectionStart??0;ql(W.value,P,i)&&E().then(v=>v?.handleInput())},handleKeydown:T=>{if(m?.isMenuOpen())return m.handleKeydown(T);if(T.key==="Backspace"&&m?.hasMentions()&&!S){let W=h,P=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||P)&&m.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>m?.isMenuOpen()??!1,hasMentions:()=>m?.hasMentions()??!1,getMentionRefs:()=>m?.getMentionRefs()??[],collectForSubmit:()=>m?.collectForSubmit()??null,takeInlineCommand:async T=>c(T)?(m??await E())?.dispatchInlineCommand(T)??null:null,clear:()=>m?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:T=>{A=T,S&&T(S.next,S.prev)},destroy:()=>{m?.destroy(),x?.();for(let T of D)T.wrapper.remove();p&&f.remove()}}}var yI,Zx=ie(()=>{"use strict";Ye();Mp();mg();Sg();Pg();ln();Ng();Fg();yI={loadContextMentions:()=>Qp(),loadContextMentionsInline:()=>ou(),renderLucideIcon:(...e)=>Re(...e),createMentionButton:(...e)=>Np(...e)}});var eS={};En(eS,{createAskUserSheetHandlers:()=>ox,createContextMentionOrchestrator:()=>Jx});var tS=ie(()=>{"use strict";rx();Zx()});var rS={};En(rS,{resolveApproval:()=>wI,resolveAskUserQuestion:()=>xI,resolveWebMcpToolCall:()=>MI,resolveWebMcpToolCallBatch:()=>oS});async function wI(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(m=>m.id===r),d={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(d),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let p=e.s.config.approval,f=p&&typeof p=="object"?p.onDecision:void 0;try{let m;if(f?m=await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):m=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),m){let g=null;if(m instanceof Response){if(!m.ok){let h=await m.json().catch(()=>null),b=h?.message??h?.error??`Approval request failed: ${m.status}`,x=h?.code==="APPROVAL_ALREADY_RESOLVED"||m.status===404&&/no paused execution/i.test(String(h?.error)),A=e.s.messages.find(S=>S.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...d,approval:x?{...l,status:"timeout"}:t}),x&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(b)}g=m.body}else m instanceof ReadableStream&&(g=m);e.s.approvalTokens.get(r)===i&&e.s.messages.some(h=>h.id===s)&&(e.s.messages=e.s.messages.filter(h=>h.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),g?await e.s.connectStream(g,{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(m){let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function xI(e,t,n){if(e.s.messages.find(p=>p.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 p=t.toolCall?.args,f=Array.isArray(p?.questions)?p.questions:[];if(f.length===1){let m=typeof f[0]?.question=="string"?f[0].question:"";m&&(i={[m]: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,d=Array.isArray(c?.questions)?c.questions:[];if(d.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let p=i??{};d.forEach((f,m)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let h=p[g],b=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";e.appendMessage({id:`ask-user-q-${l}-${m}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${m}`,role:"user",content:b||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let p=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!p.ok){let f=await p.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${p.status}`)}p.body?await e.s.connectStream(p.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(p){let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,f||e.s.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}function SI(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 nS(e,t){return t.toolCall?.name!==Yr?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function AI(e,t){let n=SI(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 su(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 oS(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let d=c.toolCall?.name,p=c.toolCall?.id;if(!d||!p)return null;let f=`${t}:${p}`;if(e.s.webMcpInflightKeys.has(f)||e.s.webMcpResolvedKeys.has(f)||nS(e,c))return null;e.s.webMcpInflightKeys.add(f),o.push(f);let m=AI(e,c),g=c.agentMetadata?.webMcpToolCallId??d;if(d===Yr)return{dedupeKey:f,resumeKey:g,output:gw(),toolMessage:c,startedAt:m,completedAt:Date.now()};let h=e.s.client.executeWebMcpToolCall(d,c.toolCall?.args,r.signal),b;if(!h)b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{b=await h}catch(x){let A=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return A||e.s.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),su(e,c,$g(A?"Aborted by cancel()":CI(x)),m),e.s.webMcpInflightKeys.delete(f),null}return r.signal.aborted?(su(e,c,$g("Aborted by cancel()"),m),e.s.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:b,toolMessage:c,startedAt:m,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(f=>f!==null),l.length===0)return;let c={};for(let f of l)c[f.resumeKey]=f.output;let d=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!d.ok){let f=await d.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${d.status}`)}let p=l[0].dedupeKey;for(let f of l){e.s.webMcpResolvedKeys.add(f.dedupeKey);let m=f.toolMessage.toolCall?.name,g=f.toolMessage.agentMetadata?.webMcpToolCallId;su(e,f.toolMessage,f.output,f.startedAt,f.completedAt,{...m===Yr?{suggestRepliesResolved:!0}:{},...m&&g?{clientToolAnswer:{toolCallId:g,toolName:m,args:f.toolMessage.toolCall?.args,result:f.output,batch:p}}:{}})}d.body&&await e.s.connectStream(d.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 p of l)su(e,p.toolMessage,$g("Aborted by cancel()"),p.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 MI(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 TI(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)||nS(e,t)))return oS(e,n,[t])}async function TI(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 $g,CI,sS=ie(()=>{"use strict";Nl();$g=e=>({isError:!0,content:[{type:"text",text:e}]}),CI=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});var Wa,Kg=ie(()=>{"use strict";Wa=class{#e=null;#t=0;#n=[];#o=[];#c=[];#r=!1;#s=!1;#f=0;#p=!1;#g=!1;#i;#a=[];#u=0;#L=!1;#b;#w;#d;#l=null;constructor(t=24e3,n={}){this.#w=t;let o=Math.max(0,n.prebufferMs??0);this.#d=Math.round(t*o/1e3),this.#i=this.#d>0}#m(){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.#g&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#l){let r=new Uint8Array(this.#l.length+t.length);r.set(this.#l),r.set(t,this.#l.length),n=r,this.#l=null}if(n.length%2!==0&&(this.#l=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#y(n);o.length!==0&&(this.#i?(this.#a.push(o),this.#u+=o.length,clearTimeout(this.#b),this.#u>=this.#d?this.#h():this.#L&&(this.#b=setTimeout(()=>this.#h(),this.#d/this.#w*1e3))):this.#C(o))}markStreamEnd(){this.#a.length>0&&this.#h(),this.#s=!0,this.#v()}flush(){for(let t of this.#n){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#n=[],this.#f=0,this.#t=0,this.#r=!1,this.#s=!1,this.#o=[],this.#c=[],this.#l=null,this.#a=[],this.#u=0,this.#i=this.#d>0,this.#p=!1,clearTimeout(this.#b)}setContinuousMode(t){this.#L=t}isPlaying(){return this.#r}onFinished(t){this.#o.push(t)}onStarted(t){this.#c.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)}#h(){this.#i=!1;let t=this.#a;this.#a=[],this.#u=0;for(let n of t)this.#C(n)}#C(t){if(t.length===0)return;let n=this.#m(),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.#d>0&&(this.#i=!0)),r.start(this.#t),this.#t+=o.duration,this.#n.push(r),this.#f++,this.#r=!0,!this.#p){this.#p=!0;let i=this.#c.slice();this.#c=[];for(let l of i)l()}r.onended=()=>{let i=this.#n.indexOf(r);i!==-1&&(this.#n.splice(i,1),this.#f--,this.#v())}}#v(){if(this.#s&&this.#f<=0&&this.#a.length===0){this.#r=!1,this.#s=!1;let t=this.#o.slice();this.#o=[];for(let n of t)n()}}#y(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 QI(e,t){let n="Conversation so far:",o=t.slice(0,YI).trim(),r=GI-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-XI).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>dS&&(c=`${c.slice(0,dS-1)}\u2026`);let d=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(d.length+1>r)break;r-=d.length+1,s.unshift(d)}let i=s.length>0?[`${n}
187
+ `)[0]).startsWith(W.trigger):!1),d=(T,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${T}`,{detail:W}))}catch{}},p=!e.chipRow,f=e.chipRow??F("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),m=null,g=null,h=e.textarea,b=null,x=null,A=null,S=null,E=()=>{if(m)return Promise.resolve(m);if(g)return g;let T=t().then(W=>(W.setMentionIconRenderer(o),m=W.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:b??void 0,anchor:e.anchor,contextRow:f,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:J,emit:d}),m)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),g===T&&(g=null),null));return g=T,T},k=()=>{n().then(T=>{let W=T.mountInlineComposer({textarea:e.textarea,renderToken:v=>Zl(v,{render:s.renderMentionToken}),onMentionRemoved:v=>m?.untrackMention(v)});b=W.input,x=W.destroy;let P=h;P.replaceWith(W.element),h=W.element,S={next:W.element,prev:P},A?.(W.element,P),m?m.rebindComposer(W.input):g&&g.then(v=>v?.rebindComposer(W.input))}).catch(T=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",T)})};s.display==="inline"&&k();let D=[],$=new Map;for(let T of i){if(!T.showButton)continue;let W=r({config:{...s,buttonIconName:T.buttonIconName,buttonTooltipText:T.buttonTooltipText},onOpen:()=>{E().then(P=>P?.openMenu(T.trigger))}});D.push(W),$.set(T.trigger,W.button)}let J=(T,W,P)=>{let v=$.get(W);v&&(v.setAttribute("aria-expanded",T?"true":"false"),T?v.setAttribute("aria-controls",P):v.removeAttribute("aria-controls"))};return{affordanceButtons:D.map(T=>T.wrapper),contextRow:f,handleInput:T=>{if(m){m.handleInput();return}if(!ix(T))return;let W=h,P=W.selectionStart??0;ql(W.value,P,i)&&E().then(v=>v?.handleInput())},handleKeydown:T=>{if(m?.isMenuOpen())return m.handleKeydown(T);if(T.key==="Backspace"&&m?.hasMentions()&&!S){let W=h,P=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||P)&&m.removeLastChip())return T.preventDefault(),!0}return!1},isMenuOpen:()=>m?.isMenuOpen()??!1,hasMentions:()=>m?.hasMentions()??!1,getMentionRefs:()=>m?.getMentionRefs()??[],collectForSubmit:()=>m?.collectForSubmit()??null,takeInlineCommand:async T=>c(T)?(m??await E())?.dispatchInlineCommand(T)??null:null,clear:()=>m?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:T=>{A=T,S&&T(S.next,S.prev)},destroy:()=>{m?.destroy(),x?.();for(let T of D)T.wrapper.remove();p&&f.remove()}}}var yI,Zx=ie(()=>{"use strict";Ye();Mp();mg();Sg();Pg();ln();Ng();Fg();yI={loadContextMentions:()=>Qp(),loadContextMentionsInline:()=>ou(),renderLucideIcon:(...e)=>Re(...e),createMentionButton:(...e)=>Np(...e)}});var eS={};En(eS,{createAskUserSheetHandlers:()=>ox,createContextMentionOrchestrator:()=>Jx});var tS=ie(()=>{"use strict";rx();Zx()});var rS={};En(rS,{resolveApproval:()=>wI,resolveAskUserQuestion:()=>xI,resolveWebMcpToolCall:()=>MI,resolveWebMcpToolCallBatch:()=>oS});async function wI(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(m=>m.id===r),d={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(d),e.s.abortController?.abort(),e.s.abortController=new AbortController,e.setStreaming(!0);let p=e.s.config.approval,f=p&&typeof p=="object"?p.onDecision:void 0;try{let m;if(f?m=await f({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):m=await e.s.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),m){let g=null;if(m instanceof Response){if(!m.ok){let h=await m.json().catch(()=>null),b=h?.message??h?.error??`Approval request failed: ${m.status}`,x=h?.code==="APPROVAL_ALREADY_RESOLVED"||m.status===404&&/no paused execution/i.test(String(h?.error)),A=e.s.messages.find(S=>S.id===r);throw e.s.approvalTokens.get(r)===i&&A?.approval?.resolvedAt===l.resolvedAt&&(e.s.upsertMessage({...d,approval:x?{...l,status:"timeout"}:t}),x&&e.settleApprovalPausedToolCall(r),e.s.upsertMessage({id:s,role:"assistant",content:b,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})),new Error(b)}g=m.body}else m instanceof ReadableStream&&(g=m);e.s.approvalTokens.get(r)===i&&e.s.messages.some(h=>h.id===s)&&(e.s.messages=e.s.messages.filter(h=>h.id!==s),e.s.callbacks.onMessagesChanged([...e.s.messages])),g?await e.s.connectStream(g,{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(m){let g=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,g||e.s.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}finally{e.s.approvalTokens.get(r)===i&&e.s.approvalTokens.delete(r)}}async function xI(e,t,n){if(e.s.messages.find(p=>p.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 p=t.toolCall?.args,f=Array.isArray(p?.questions)?p.questions:[];if(f.length===1){let m=typeof f[0]?.question=="string"?f[0].question:"";m&&(i={[m]: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,d=Array.isArray(c?.questions)?c.questions:[];if(d.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([f,m])=>`${f}: ${Array.isArray(m)?m.join(", "):m}`).join(" | ");e.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})}else{let p=i??{};d.forEach((f,m)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let h=p[g],b=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";e.appendMessage({id:`ask-user-q-${l}-${m}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}),e.appendMessage({id:`ask-user-a-${l}-${m}`,role:"user",content:b||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()})})}try{let p=await e.s.client.resumeFlow(r,{[s]:n},{after:e.resumeAfter(r)});if(!p.ok){let f=await p.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${p.status}`)}p.body?await e.s.connectStream(p.body,{allowReentry:!0}):(e.setStreaming(!1),e.s.abortController=null)}catch(p){let f=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));e.setStreaming(!1),e.s.abortController=null,f||e.s.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}function SI(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 nS(e,t){return t.toolCall?.name!==Yr?!1:(e.s.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}function AI(e,t){let n=SI(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 su(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 oS(e,t,n){let o=[],r=new AbortController;e.s.webMcpResolveControllers.add(r),e.setStreaming(!0);let s=async c=>{let d=c.toolCall?.name,p=c.toolCall?.id;if(!d||!p)return null;let f=`${t}:${p}`;if(e.s.webMcpInflightKeys.has(f)||e.s.webMcpResolvedKeys.has(f)||nS(e,c))return null;e.s.webMcpInflightKeys.add(f),o.push(f);let m=AI(e,c),g=c.agentMetadata?.webMcpToolCallId??d;if(d===Yr)return{dedupeKey:f,resumeKey:g,output:gw(),toolMessage:c,startedAt:m,completedAt:Date.now()};let h=e.s.client.executeWebMcpToolCall(d,c.toolCall?.args,r.signal),b;if(!h)b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{b=await h}catch(x){let A=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));return A||e.s.callbacks.onError?.(x instanceof Error?x:new Error(String(x))),su(e,c,$g(A?"Aborted by cancel()":CI(x)),m),e.s.webMcpInflightKeys.delete(f),null}return r.signal.aborted?(su(e,c,$g("Aborted by cancel()"),m),e.s.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:b,toolMessage:c,startedAt:m,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(f=>f!==null),l.length===0)return;let c={};for(let f of l)c[f.resumeKey]=f.output;let d=await e.s.client.resumeFlow(t,c,{signal:r.signal,after:e.resumeAfter(t)});if(!d.ok){let f=await d.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${d.status}`)}let p=l[0].dedupeKey;for(let f of l){e.s.webMcpResolvedKeys.add(f.dedupeKey);let m=f.toolMessage.toolCall?.name,g=f.toolMessage.agentMetadata?.webMcpToolCallId;su(e,f.toolMessage,f.output,f.startedAt,f.completedAt,{...m===Yr?{suggestRepliesResolved:!0}:{},...m&&g?{clientToolAnswer:{toolCallId:g,toolName:m,args:f.toolMessage.toolCall?.args,result:f.output,batch:p}}:{}})}d.body&&await e.s.connectStream(d.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 p of l)su(e,p.toolMessage,$g("Aborted by cancel()"),p.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 MI(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 TI(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)||nS(e,t)))return oS(e,n,[t])}async function TI(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 $g,CI,sS=ie(()=>{"use strict";Nl();$g=e=>({isError:!0,content:[{type:"text",text:e}]}),CI=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t});var Wa,Kg=ie(()=>{"use strict";Wa=class{#e=null;#t=0;#n=[];#o=[];#i=[];#r=!1;#s=!1;#g=0;#c=!1;#f=!1;#p;#l=[];#a=0;#S=!1;#b;#w;#y;#d=null;constructor(t=24e3,n={}){this.#w=t;let o=Math.max(0,n.prebufferMs??0);this.#y=Math.round(t*o/1e3),this.#p=this.#y>0}#u(){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.#f&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.#d){let r=new Uint8Array(this.#d.length+t.length);r.set(this.#d),r.set(t,this.#d.length),n=r,this.#d=null}if(n.length%2!==0&&(this.#d=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.#A(n);o.length!==0&&(this.#p?(this.#l.push(o),this.#a+=o.length,clearTimeout(this.#b),this.#a>=this.#y?this.#m():this.#S&&(this.#b=setTimeout(()=>this.#m(),this.#y/this.#w*1e3))):this.#h(o))}markStreamEnd(){this.#l.length>0&&this.#m(),this.#s=!0,this.#x()}flush(){for(let t of this.#n){t.onended=null;try{t.stop(),t.disconnect()}catch{}}this.#n=[],this.#g=0,this.#t=0,this.#r=!1,this.#s=!1,this.#o=[],this.#i=[],this.#d=null,this.#l=[],this.#a=0,this.#p=this.#y>0,this.#c=!1,clearTimeout(this.#b)}setContinuousMode(t){this.#S=t}isPlaying(){return this.#r}onFinished(t){this.#o.push(t)}onStarted(t){this.#i.push(t)}pause(){this.#f=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#f=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#m(){this.#p=!1;let t=this.#l;this.#l=[],this.#a=0;for(let n of t)this.#h(n)}#h(t){if(t.length===0)return;let n=this.#u(),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.#y>0&&(this.#p=!0)),r.start(this.#t),this.#t+=o.duration,this.#n.push(r),this.#g++,this.#r=!0,!this.#c){this.#c=!0;let i=this.#i.slice();this.#i=[];for(let l of i)l()}r.onended=()=>{let i=this.#n.indexOf(r);i!==-1&&(this.#n.splice(i,1),this.#g--,this.#x())}}#x(){if(this.#s&&this.#g<=0&&this.#l.length===0){this.#r=!1,this.#s=!1;let t=this.#o.slice();this.#o=[];for(let n of t)n()}}#A(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 QI(e,t){let n="Conversation so far:",o=t.slice(0,YI).trim(),r=GI-(o?o.length+2:0)-n.length,s=[];for(let l of e.slice(-XI).reverse()){let c=l.content.replace(/\s+/g," ").trim();if(!c)continue;c.length>dS&&(c=`${c.slice(0,dS-1)}\u2026`);let d=`${l.role==="user"?"User":"Assistant"}: ${c}`;if(d.length+1>r)break;r-=d.length+1,s.unshift(d)}let i=s.length>0?[`${n}
188
188
  ${s.join(`
189
189
  `)}`]:[];return o&&i.push(o),i.join(`
190
190
 
191
- `)}function JI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===BI?new Uint8Array(e,44):new Uint8Array(e)}function pS(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 ZI(e){return pS(e).replace(/^ws/i,"http")}function eH(e){return typeof e!="number"||!Number.isFinite(e)?_I:Math.min(FI,Math.max(NI,Math.round(e)))}var Gg,II,HI,RI,WI,BI,DI,OI,_I,NI,FI,VI,$I,UI,zI,qI,jI,KI,GI,YI,XI,dS,Ba,Yg=ie(()=>{"use strict";Kg();vp();Gg=16e3,II=24e3,HI=4096,RI=Gg*2*8,WI=4,BI=1380533830,DI=3e4,OI=5e3,_I=3e4,NI=3e4,FI=6e5,VI="full-duplex-v1",$I=300,UI=2e3,zI=2e3,qI="runtype-browser-v1",jI=54e4,KI="You're talking to an AI assistant. Voice is processed by OpenAI.",GI=8e3,YI=4e3,XI=12,dS=2e3;Ba=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#t=null;this.#n=[];this.#o=null;this.#c=null;this.#r=null;this.#s=[];this.#f=0;this.#p=null;this.#g=!1;this.#i=!1;this.#a=0;this.#u=!1;this.#L=Number.NEGATIVE_INFINITY;this.#b=null;this.#w=!1;this.#d=!1;this.#l=0;this.#m=0;this.#C=!1;this.bridge=null;this.#v=!1;this.#y=new Set;this.#A=new Map;this.#E=new Set;this.#S=!1;this.#U=null;this.#q=null;this.#j=Promise.resolve();this.#B=new Set;this.#N=!1;this.#M=new Set;this.#H=new Set;this.#K=[];this.#Q=[];this.#D=[];this.#z=[];this.#O=[]}#e;#t;#n;#o;#c;#r;#s;#f;#p;#g;#i;#a;#u;#L;#b;#w;#d;#l;#m;#h;#C;#v;#y;#A;#E;#x;#S;#U;#q;#j;#B;#N;#M;#H;#K;#Q;#D;#z;#O;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#g||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.#L<DI)){this.#L=r;try{this.config?.prewarmMode==="attach"?this.#J(o,t,n):this.#ne(o,t,n)}catch{}}}#ne(t,n,o){if(typeof fetch!="function")return;let r=`${ZI(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#J(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=eH(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#le(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},d=new Promise(f=>{c=f}),p={ws:l,state:"connecting",ready:d,settle:c,openedAt:0,idleTimer:void 0};this.#b=p,l.onopen=()=>{this.#b===p&&(p.state=l.protocol==="runtype.attach"?"attached":"live",p.openedAt=Date.now(),this.#P(p,i),p.state==="attached"&&l.send('{"type":"ping"}'),p.settle())},l.onmessage=f=>{if(this.#b!==p||typeof f.data!="string")return;let m;try{m=JSON.parse(f.data)}catch{return}m.type==="attached"&&typeof m.idleMs=="number"&&this.#P(p,m.idleMs-(Date.now()-p.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#b===p&&this.#F()}}#P(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#b===t&&this.#F()},Math.max(0,n))}#F(){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#oe(){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,OI)})]),clearTimeout(n)}return this.#b!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#F(),null):(this.#b=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#le(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:qI,clientVersion:`persona/${br}`,voiceCapabilities:VI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${pS(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.#a;this.#u=!1,this.#g=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Gg,channelCount:1,echoCancellation:!0}});if(r!==this.#a){s.getTracks().forEach(f=>f.stop());return}this.#o=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Gg});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#t=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Wa(II);if(r!==this.#a){c.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.#p=c,this.#$(),this.#re(l,s,r);let d=await this.#oe();if(r!==this.#a){d?.ws.close(1e3,"client ended call");return}if(d){let{ws:f}=d;this.#e=f,this.#R(f,r),d.live||f.send('{"type":"start"}'),this.#G(f),this.#T("listening");return}let p=new WebSocket(this.#le(o,t),["runtype.bearer",n]);p.binaryType="arraybuffer",this.#e=p,p.onopen=()=>{r===this.#a&&(this.#G(p),this.#T("listening"))},this.#R(p,r)}catch(s){throw this.#ie(),this.#pe(s),this.#T("error"),s}}#R(t,n){t.onmessage=o=>this.#se(o,n),t.onerror=()=>{n===this.#a&&(this.#pe(new Error("Voice connection failed")),this.#T("error"),this.#ie())},t.onclose=o=>{if(this.#u){this.#u=!1;return}if(n===this.#a){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.#pe(new Error(`Voice connection closed${r}`)),this.#T("error")}else this.#T("idle");this.#ie()}}}getDisclosure(){let t=this.config?.disclosureText;return this.#g&&this.#w&&t!==!1?t||KI:null}async stopListening(){this.#ie(),this.#T("idle")}async disconnect(){this.#ie(),this.#T("disconnected"),this.#K=[],this.#Q=[],this.#D=[],this.#z=[],this.#O=[]}stopPlayback(){this.#Ce();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#w&&(this.#l=Date.now()+UI,t.send('{"type":"cancel"}')),this.#T("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#g}onLevel(t){this.#n.push(t)}async deactivateBargeIn(){this.#ie(),this.#T("idle")}#re(t,n,o){let r=t.createMediaStreamSource(n);this.#c=r;let s=t.createScriptProcessor(HI,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#a)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let d=i.inputBuffer.getChannelData(0),p=new Int16Array(d.length),f=0;for(let m=0;m<d.length;m++){let g=Math.max(-1,Math.min(1,d[m]));f+=g*g,p[m]=g<0?g*32768:g*32767}if(l&&c)this.#G(l),l.send(p.buffer);else for(this.#s.push(p.buffer),this.#f+=p.byteLength;this.#f>RI;)this.#f-=this.#s.shift().byteLength;if(this.#n.length>0){let m=Math.sqrt(f/d.length),g=Math.max(0,Math.min(1,m*WI));for(let h of this.#n)h(g)}},r.connect(s),s.connect(t.destination)}#G(t){for(let n of this.#s)t.send(n);this.#s=[],this.#f=0}#se(t,n){if(n!==this.#a)return;if(t.data instanceof ArrayBuffer){this.#ce(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.#p?.setContinuousMode?.(this.#w)),Array.isArray(o.capabilities)&&(this.#y=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#x=o.callId),this.#v=this.#w&&this.#y.has("client_delegation")&&!!this.bridge,this.#w&&!this.#i&&this.#T("listening"),this.#y.has("context")&&!this.#S&&(this.#S=!0,this.#U=this.#V());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#Z())break;let i=String(s);if(r==="user")o.final===!0&&this.#_(n),this.#N=!1;else if(this.#N&&!this.#M.has(i)&&(this.#H.add(i),this.#N=!1),this.#M.add(i),this.#H.has(i))break;this.#te(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#v&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#_(n);let s=o.input;this.#v&&s&&this.#Y(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.#B.has(r)&&(this.#N=!0);this.#d=o.type==="delegation_started",!this.#i&&!this.#Z()&&this.#T(this.#d?"processing":"listening");break}case"delegation_cancelled":this.#k(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#x??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#k(String(o.delegationId));break;case"audio_clear":this.#Ce(),this.#l=0,this.#T("listening");break;case"transcript_interim":this.#T("listening"),this.#te("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#T(r==="user"?"processing":"speaking"),this.#te(r,o.text??"",!0);break}case"audio_end":this.#p?this.#p.markStreamEnd():(this.#i=!1,this.#T("listening"));break;case"metrics":this.#Se({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#pe(new Error(o.error||"Voice error")),this.#T("error");break}}async#V(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return QI(t,n)}#_(t){let n=this.#U;if(!n)return;this.#U=null;let o=!1,r=n.then(s=>{let i=this.#e;o||!s||t!==this.#a||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#q={done:r,drop:()=>o=!0}}async#W(){let t=this.#q;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),zI)})]);clearTimeout(n),o&&t.drop()}#k(t,n=!1){this.#E.add(t),this.bridge?.dropDelegation?.(t,n),this.#A.get(t)?.abort()}#Y(t,n,o){let r=this.bridge,s=(i,l,c)=>{let d=this.#e;return o!==this.#a||d?.readyState!==WebSocket.OPEN||this.#E.has(t)?!1:(d.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#j=this.#j.then(async()=>{if(o!==this.#a||this.#E.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#W();let l=!!i.followUp,c=l&&this.#y.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&this.#B.add(t),!i.followUp))return;let p=new AbortController;this.#A.set(t,p),i.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,jI),readBack:c,onUpdate:f=>s("delegation_update","pending_approval",f)}).then(f=>{this.#A.delete(t),c&&f&&!p.signal.aborted&&s("delegation_result",f.status,f.text)})})}#ce(t,n){if(n!==this.#a||!this.#p||this.#Z())return;let o=JI(t);o.length!==0&&(this.#i||(this.#i=!0,this.#T("speaking")),this.#$(),this.#p.enqueue(o),this.#w&&this.#me(o.length))}#Z(){return Date.now()<this.#l}#$(){if(this.#C||!this.#p)return;this.#C=!0;let t=this.#a;this.#p.onFinished(()=>{t===this.#a&&(this.#C=!1,this.#de())})}#me(t){let n=Date.now();this.#m=Math.max(n,this.#m)+t/48,clearTimeout(this.#h),this.#h=setTimeout(()=>this.#de(),this.#m-n+$I)}#de(){this.#i=!1,this.#m=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#T(this.#d?"processing":"listening")}#Ce(){this.#p?.flush(),this.#C=!1,this.#$(),this.#i=!1,this.#m=0,clearTimeout(this.#h)}#ie(){this.#a+=1,this.#g=!1,this.#i=!1,this.#F(),this.#w=!1,this.#d=!1,this.#v=!1,this.#y=new Set;for(let t of this.#A.values())t.abort();if(this.#A.clear(),this.#E.clear(),this.#x=void 0,this.#S=!1,this.#U=null,this.#q=null,this.#j=Promise.resolve(),this.#B.clear(),this.#N=!1,this.#M.clear(),this.#H.clear(),this.#C=!1,this.#l=0,this.#m=0,clearTimeout(this.#h),this.#s=[],this.#f=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#c&&(this.#c.disconnect(),this.#c=null),this.#o&&(this.#o.getTracks().forEach(t=>t.stop()),this.#o=null),this.#t&&(this.#t.close().catch(()=>{}),this.#t=null),this.#p&&(this.#p.destroy(),this.#p=null),this.#e){this.#u=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#K.push(t)}onError(t){this.#Q.push(t)}onStatusChange(t){this.#D.push(t)}onTranscript(t){this.#z.push(t)}onMetrics(t){this.#O.push(t)}#T(t){this.#D.forEach(n=>n(t))}#pe(t){this.#Q.forEach(n=>n(t))}#te(t,n,o,r){this.#z.forEach(s=>s(t,n,o,r))}#Se(t){this.#O.forEach(n=>n(t))}}});var Ds,Xg=ie(()=>{"use strict";Ds=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#t=[];this.#n=[];this.#o=[];this.#c=!1;this.#r=typeof window<"u"?window:void 0}#e;#t;#n;#o;#c;#r;async connect(){this.#o.forEach(t=>t("connected"))}async startListening(){try{if(this.#c)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.#t.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#n.forEach(o=>o(new Error(n.error))),this.#o.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#c=!0,this.#o.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#c=!1,this.#o.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#n.forEach(n=>n(t)),this.#o.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#c=!1,this.#o.forEach(t=>t("idle"))}onResult(t){this.#t.push(t)}onError(t){this.#n.push(t)}onStatusChange(t){this.#o.push(t)}async disconnect(){await this.stopListening(),this.#o.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ba(e.runtype);case"browser":if(!Ds.isSupported())throw new Error("Browser speech recognition not supported");return new Ds(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 Qg(e){if(e?.type==="custom"&&e.custom)return nc({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return nc({type:"runtype",runtype:e.runtype});if(Ds.isSupported())return nc({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function uS(e){try{return Qg(e),!0}catch{return!1}}var fS=ie(()=>{"use strict";Yg();Xg()});var mS,lu,gS=ie(()=>{"use strict";mS=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),lu=class{constructor(t){this.host=t;this.turns=new Map;this.latestId=null;this.cancelled=new Set}apply(t,n,o,r,s,i){let l=this.host;n=n.trim();let c=this.turns.get(r);if(c||(c={},this.turns.set(r,c),this.latestId=r),t==="user"){c.userFinal=o;let d=c.userId?l.find(c.userId):void 0;if(d){let p=c.userStartMs===void 0&&s!==void 0;p&&(c.userStartMs=s),l.upsert({...d,content:n,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else{c.userStartMs=s;let p=c.assistantId?l.find(c.assistantId):void 0;c.userId=l.inject({role:"user",content:n,streaming:!1,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s)??p)}).id}}else if(!this.cancelled.has(r)){c.assistantFinal=o;let d=c.assistantId?l.find(c.assistantId):void 0;if(d){let p=c.assistantStartMs===void 0&&s!==void 0;p&&(c.assistantStartMs=s),l.upsert({...d,content:n,streaming:!o,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else n&&(c.assistantStartMs=s,c.assistantId=l.inject({role:"assistant",content:n,streaming:!o,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s))}).id);o&&c.assistantId&&l.markSpoken(c.assistantId)}this.sync()}claimUserTurn(t,n=[]){let o=n[n.length-1];for(let s of n)s!==o&&(this.turns.has(s)||this.turns.set(s,{}),this.turns.get(s).claimed=!0);let r;if(o){if(r=this.turns.get(o),r||(r={},this.turns.set(o,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:"user",content:t.trim()}).id)}else{let s=mS(t),i=[...this.turns.values()].reverse().flatMap(l=>{let c=l.userId&&!l.claimed?this.host.find(l.userId):void 0;return c?[{turn:l,text:mS(c.content)}]:[]}).filter(({text:l})=>l&&s);r=(i.find(({text:l})=>l===s)??i.find(({text:l})=>l.startsWith(s)||s.startsWith(l)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let t=this.inFlight();if(t.length===0){let n=this.awaiting();if(!n)return;t=[n]}for(let n of t)this.cancelled.add(n);this.closeReplies(t),this.sync()}fail(t){let n=this.awaiting(),o=this.inFlight();if(!n&&o.length===0)return;for(let i of o)this.turns.get(i).assistantFinal=!0;this.closeReplies(o);let r=this.host.inject({role:"assistant",content:t,streaming:!1,voiceProcessing:!1}),s=n?this.turns.get(n):void 0;s&&(s.assistantId=r.id,s.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let t=this.pending(),n=new Set;for(let o of this.turns.values())o.userId&&n.add(o.userId),o.assistantId&&(n.add(o.assistantId),this.host.markSpoken(o.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(n),t&&this.host.setStreaming(!1)}startedAfter(t){if(t===void 0)return;let n;for(let o of this.turns.values())for(let[r,s]of[[o.userId,o.userStartMs],[o.assistantId,o.assistantStartMs]])r&&s!==void 0&&s>t&&(!n||s<n.start)&&(n={start:s,id:r});return n&&this.host.find(n.id)}placeBefore(t){if(!t)return;let n=t.sequence??0,o=n-1;for(let r of this.turns.values())for(let s of[r.userId,r.assistantId]){let i=s?this.host.find(s):void 0,l=i?.sequence;i?.createdAt===t.createdAt&&l!==void 0&&l>o&&l<n&&(o=l)}return{createdAt:t.createdAt,sequence:(o+n)/2}}closeReplies(t){let n=new Set;for(let o of t){let r=this.turns.get(o)?.assistantId;r&&(n.add(r),this.host.markSpoken(r))}n.size>0&&this.host.settle(n)}inFlight(){let t=[];for(let[n,o]of this.turns)o.assistantId&&!o.assistantFinal&&!this.cancelled.has(n)&&t.push(n);return t}awaiting(){let t=this.latestId;if(!t)return null;let n=this.turns.get(t);return n?.userFinal&&!n.assistantId&&!n.claimed&&!this.cancelled.has(t)?t:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}});function Zg(e,t=0){if(e==null||e==="")return"";if(typeof e!="object")return String(e);if(t>2)return"";if(Array.isArray(e))return e.map(s=>Zg(s,t+1)).filter(Boolean).join(", ");let n=e,o=n.quantity??n.qty??n.count,r=n.name??n.item??n.product??n.title;return o!=null&&r!=null&&typeof r!="object"?`${o} ${r}`:Object.entries(n).filter(([s])=>!s.startsWith("_")).map(([s,i])=>{let l=Zg(i,t+1);return l&&(t?`${Da(s)} ${l}`:`${Da(s)}: ${l}`)}).filter(Boolean).join(t?", ":"; ")}function vS(e){let t=e.length>1?"These actions need the user's approval in the chat before they happen:":"This action needs the user's approval in the chat before it happens:",n=1e3-t.length-yS.length-2,o=e.map(r=>{let s=[Da(r.toolName)];r.description&&s.push(`(${Jg(r.description.trim(),160)})`);let i=Zg(r.parameters);return i&&s.push(`with ${i}`),r.reason&&s.push(`because: ${Jg(r.reason.trim(),160)}`),Jg(`- ${s.join(" ")}`,Math.floor(n/e.length)-1)});return`${t}
191
+ `)}function JI(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===BI?new Uint8Array(e,44):new Uint8Array(e)}function pS(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 ZI(e){return pS(e).replace(/^ws/i,"http")}function eH(e){return typeof e!="number"||!Number.isFinite(e)?_I:Math.min(FI,Math.max(NI,Math.round(e)))}var Gg,II,HI,RI,WI,BI,DI,OI,_I,NI,FI,VI,$I,UI,zI,qI,jI,KI,GI,YI,XI,dS,Ba,Yg=ie(()=>{"use strict";Kg();vp();Gg=16e3,II=24e3,HI=4096,RI=Gg*2*8,WI=4,BI=1380533830,DI=3e4,OI=5e3,_I=3e4,NI=3e4,FI=6e5,VI="full-duplex-v1",$I=300,UI=2e3,zI=2e3,qI="runtype-browser-v1",jI=54e4,KI="You're talking to an AI assistant. Voice is processed by OpenAI.",GI=8e3,YI=4e3,XI=12,dS=2e3;Ba=class{constructor(t){this.config=t;this.type="runtype";this.#e=null;this.#t=null;this.#n=[];this.#o=null;this.#i=null;this.#r=null;this.#s=[];this.#g=0;this.#c=null;this.#f=!1;this.#p=!1;this.#l=0;this.#a=!1;this.#S=Number.NEGATIVE_INFINITY;this.#b=null;this.#w=!1;this.#y=!1;this.#d=0;this.#u=0;this.#h=!1;this.bridge=null;this.#x=!1;this.#A=new Set;this.#C=new Map;this.#v=new Set;this.#k=!1;this.#M=null;this.#I=null;this.#X=Promise.resolve();this.#z=new Set;this.#V=!1;this.#T=new Set;this.#O=new Set;this.#W=[];this.#$=[];this.#j=[];this.#ee=[];this.#_=[]}#e;#t;#n;#o;#i;#r;#s;#g;#c;#f;#p;#l;#a;#S;#b;#w;#y;#d;#u;#m;#h;#x;#A;#C;#v;#P;#k;#M;#I;#X;#z;#V;#T;#O;#W;#$;#j;#ee;#_;async connect(){}setSessionBridge(t){this.bridge=t}prewarm(){if(this.#f||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.#S<DI)){this.#S=r;try{this.config?.prewarmMode==="attach"?this.#te(o,t,n):this.#Q(o,t,n)}catch{}}}#Q(t,n,o){if(typeof fetch!="function")return;let r=`${ZI(t)}/v1/client/agents/${encodeURIComponent(n)}/voice/prewarm`;fetch(r,{method:"POST",headers:{Authorization:`Bearer ${o}`},keepalive:!0}).catch(()=>{})}#te(t,n,o){let r=new URLSearchParams,s=this.config?.attachIdleMs,i=eH(s);s!==void 0&&r.set("attachIdleMs",String(i));let l=new WebSocket(this.#le(t,n,r),["runtype.bearer","runtype.attach",o]);l.binaryType="arraybuffer";let c=()=>{},d=new Promise(f=>{c=f}),p={ws:l,state:"connecting",ready:d,settle:c,openedAt:0,idleTimer:void 0};this.#b=p,l.onopen=()=>{this.#b===p&&(p.state=l.protocol==="runtype.attach"?"attached":"live",p.openedAt=Date.now(),this.#q(p,i),p.state==="attached"&&l.send('{"type":"ping"}'),p.settle())},l.onmessage=f=>{if(this.#b!==p||typeof f.data!="string")return;let m;try{m=JSON.parse(f.data)}catch{return}m.type==="attached"&&typeof m.idleMs=="number"&&this.#q(p,m.idleMs-(Date.now()-p.openedAt))},l.onerror=()=>{},l.onclose=()=>{this.#b===p&&this.#R()}}#q(t,n){clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{this.#b===t&&this.#R()},Math.max(0,n))}#R(){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#U(){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,OI)})]),clearTimeout(n)}return this.#b!==t?null:t.state==="connecting"||t.ws.readyState!==WebSocket.OPEN?(this.#R(),null):(this.#b=null,clearTimeout(t.idleTimer),{ws:t.ws,live:t.state==="live"})}#le(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:qI,clientVersion:`persona/${br}`,voiceCapabilities:VI,clientCapabilities:r.join(",")});return o?.forEach((i,l)=>s.set(l,i)),`${pS(t)}/ws/agents/${encodeURIComponent(n)}/voice?${s}`}async startListening(){if(this.#f)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.#l;this.#a=!1,this.#f=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Gg,channelCount:1,echoCancellation:!0}});if(r!==this.#l){s.getTracks().forEach(f=>f.stop());return}this.#o=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Gg});l.state==="suspended"&&await l.resume().catch(()=>{}),this.#t=l;let c=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Wa(II);if(r!==this.#l){c.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.#c=c,this.#G(),this.#ce(l,s,r);let d=await this.#U();if(r!==this.#l){d?.ws.close(1e3,"client ended call");return}if(d){let{ws:f}=d;this.#e=f,this.#B(f,r),d.live||f.send('{"type":"start"}'),this.#J(f),this.#E("listening");return}let p=new WebSocket(this.#le(o,t),["runtype.bearer",n]);p.binaryType="arraybuffer",this.#e=p,p.onopen=()=>{r===this.#l&&(this.#J(p),this.#E("listening"))},this.#B(p,r)}catch(s){throw this.#ie(),this.#de(s),this.#E("error"),s}}#B(t,n){t.onmessage=o=>this.#oe(o,n),t.onerror=()=>{n===this.#l&&(this.#de(new Error("Voice connection failed")),this.#E("error"),this.#ie())},t.onclose=o=>{if(this.#a){this.#a=!1;return}if(n===this.#l){if(o.code!==1e3){let r=o.code?` (code ${o.code})`:"";this.#de(new Error(`Voice connection closed${r}`)),this.#E("error")}else this.#E("idle");this.#ie()}}}getDisclosure(){let t=this.config?.disclosureText;return this.#f&&this.#w&&t!==!1?t||KI:null}async stopListening(){this.#ie(),this.#E("idle")}async disconnect(){this.#ie(),this.#E("disconnected"),this.#W=[],this.#$=[],this.#j=[],this.#ee=[],this.#_=[]}stopPlayback(){this.#Ce();let t=this.#e;t&&t.readyState===WebSocket.OPEN&&(this.#w&&(this.#d=Date.now()+UI,t.send('{"type":"cancel"}')),this.#E("listening"))}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.#f}onLevel(t){this.#n.push(t)}async deactivateBargeIn(){this.#ie(),this.#E("idle")}#ce(t,n,o){let r=t.createMediaStreamSource(n);this.#i=r;let s=t.createScriptProcessor(HI,1,1);this.#r=s,s.onaudioprocess=i=>{if(o!==this.#l)return;let l=this.#e,c=l?.readyState===WebSocket.OPEN;if(l&&!c&&l.readyState!==WebSocket.CONNECTING)return;let d=i.inputBuffer.getChannelData(0),p=new Int16Array(d.length),f=0;for(let m=0;m<d.length;m++){let g=Math.max(-1,Math.min(1,d[m]));f+=g*g,p[m]=g<0?g*32768:g*32767}if(l&&c)this.#J(l),l.send(p.buffer);else for(this.#s.push(p.buffer),this.#g+=p.byteLength;this.#g>RI;)this.#g-=this.#s.shift().byteLength;if(this.#n.length>0){let m=Math.sqrt(f/d.length),g=Math.max(0,Math.min(1,m*WI));for(let h of this.#n)h(g)}},r.connect(s),s.connect(t.destination)}#J(t){for(let n of this.#s)t.send(n);this.#s=[],this.#g=0}#oe(t,n){if(n!==this.#l)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.#w=o.speechMode==="speech_to_speech",this.#c?.setContinuousMode?.(this.#w)),Array.isArray(o.capabilities)&&(this.#A=new Set(o.capabilities)),typeof o.callId=="string"&&(this.#P=o.callId),this.#x=this.#w&&this.#A.has("client_delegation")&&!!this.bridge,this.#w&&!this.#p&&this.#E("listening"),this.#A.has("context")&&!this.#k&&(this.#k=!0,this.#M=this.#ne());break;case"transcript_update":{let r=o.role==="assistant"?"assistant":"user",s=o.utteranceId??o.turnId;if(!s||r==="assistant"&&this.#F())break;let i=String(s);if(r==="user")o.final===!0&&this.#re(n),this.#V=!1;else{if(this.#A.has("delegation_read_back")){let l=o.delegationId;typeof l=="string"&&this.#z.has(l)&&!this.#T.has(i)&&this.#O.add(i)}else this.#V&&!this.#T.has(i)&&(this.#O.add(i),this.#V=!1);if(this.#T.add(i),this.#O.has(i))break}this.#pe(r,o.text??"",o.final===!0,{turnId:i,...typeof o.startMs=="number"&&{startMs:o.startMs},...typeof o.endMs=="number"&&{endMs:o.endMs},...this.#x&&{caption:!0}});break}case"delegation_started":case"delegation_completed":{let r=String(o.delegationId??o.turnId);if(o.type==="delegation_started"){this.#re(n);let s=o.input;this.#x&&s&&this.#N(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.#z.has(r)&&(this.#V=!0);this.#y=o.type==="delegation_started",!this.#p&&!this.#F()&&this.#E(this.#y?"processing":"listening");break}case"delegation_cancelled":this.#D(String(o.delegationId),o.reason!=="session_ending"&&o.reason!=="provider_cancelled");break;case"warning":console.warn(`[Persona voice] ${o.code}: ${o.message??""}`,this.#P??""),o.delegationId&&(o.code==="UNKNOWN_DELEGATION"||o.code==="LATE_RESULT_LIMIT")&&this.#D(String(o.delegationId));break;case"audio_clear":this.#Ce(),this.#d=0,this.#E("listening");break;case"transcript_interim":this.#E("listening"),this.#pe("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.#E(r==="user"?"processing":"speaking"),this.#pe(r,o.text??"",!0);break}case"audio_end":this.#c?this.#c.markStreamEnd():(this.#p=!1,this.#E("listening"));break;case"metrics":this.#xe({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.#de(new Error(o.error||"Voice error")),this.#E("error");break}}async#ne(){let t=this.bridge?.getHistory()??[],n="";try{let o=this.config?.callContext;n=String((typeof o=="function"?await o():o)??"")}catch{}return QI(t,n)}#re(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.#l||i?.readyState!==WebSocket.OPEN||i.send(JSON.stringify({type:"context",text:s}))});this.#I={done:r,drop:()=>o=!0}}async#K(){let t=this.#I;if(!t)return;let n,o=await Promise.race([t.done.then(()=>!1),new Promise(r=>{n=setTimeout(()=>r(!0),zI)})]);clearTimeout(n),o&&t.drop()}#D(t,n=!1){this.#v.add(t),this.bridge?.dropDelegation?.(t,n),this.#C.get(t)?.abort()}#N(t,n,o){let r=this.bridge,s=(i,l,c)=>{let d=this.#e;return o!==this.#l||d?.readyState!==WebSocket.OPEN||this.#v.has(t)?!1:(d.send(JSON.stringify({type:i,delegationId:t,status:l,text:c})),!0)};this.#X=this.#X.then(async()=>{if(o!==this.#l||this.#v.has(t))return;let i=await r.runDelegatedTurn(n).catch(()=>({status:"failed",text:""}));await this.#K();let l=!!i.followUp,c=l&&this.#A.has("delegation_update");if(!s(c?"delegation_update":"delegation_result",l&&!c?"completed":i.status,i.text)||(i.status!=="failed"&&i.inChat!==!1&&this.#z.add(t),!i.followUp))return;let p=new AbortController;this.#C.set(t,p),i.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,jI),readBack:c,onUpdate:f=>s("delegation_update","pending_approval",f)}).then(f=>{this.#C.delete(t),c&&f&&!p.signal.aborted&&s("delegation_result",f.status,f.text)})})}#L(t,n){if(n!==this.#l||!this.#c||this.#F())return;let o=JI(t);o.length!==0&&(this.#p||(this.#p=!0,this.#E("speaking")),this.#G(),this.#c.enqueue(o),this.#w&&this.#ve(o.length))}#F(){return Date.now()<this.#d}#G(){if(this.#h||!this.#c)return;this.#h=!0;let t=this.#l;this.#c.onFinished(()=>{t===this.#l&&(this.#h=!1,this.#se())})}#ve(t){let n=Date.now();this.#u=Math.max(n,this.#u)+t/48,clearTimeout(this.#m),this.#m=setTimeout(()=>this.#se(),this.#u-n+$I)}#se(){this.#p=!1,this.#u=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#E(this.#y?"processing":"listening")}#Ce(){this.#c?.flush(),this.#h=!1,this.#G(),this.#p=!1,this.#u=0,clearTimeout(this.#m)}#ie(){this.#l+=1,this.#f=!1,this.#p=!1,this.#R(),this.#w=!1,this.#y=!1,this.#x=!1,this.#A=new Set;for(let t of this.#C.values())t.abort();if(this.#C.clear(),this.#v.clear(),this.#P=void 0,this.#k=!1,this.#M=null,this.#I=null,this.#X=Promise.resolve(),this.#z.clear(),this.#V=!1,this.#T.clear(),this.#O.clear(),this.#h=!1,this.#d=0,this.#u=0,clearTimeout(this.#m),this.#s=[],this.#g=0,this.#r&&(this.#r.onaudioprocess=null,this.#r.disconnect(),this.#r=null),this.#i&&(this.#i.disconnect(),this.#i=null),this.#o&&(this.#o.getTracks().forEach(t=>t.stop()),this.#o=null),this.#t&&(this.#t.close().catch(()=>{}),this.#t=null),this.#c&&(this.#c.destroy(),this.#c=null),this.#e){this.#a=!0;try{this.#e.close(1e3,"client ended call")}catch{}this.#e=null}}onResult(t){this.#W.push(t)}onError(t){this.#$.push(t)}onStatusChange(t){this.#j.push(t)}onTranscript(t){this.#ee.push(t)}onMetrics(t){this.#_.push(t)}#E(t){this.#j.forEach(n=>n(t))}#de(t){this.#$.forEach(n=>n(t))}#pe(t,n,o,r){this.#ee.forEach(s=>s(t,n,o,r))}#xe(t){this.#_.forEach(n=>n(t))}}});var Ds,Xg=ie(()=>{"use strict";Ds=class{constructor(t={}){this.config=t;this.type="browser";this.#e=null;this.#t=[];this.#n=[];this.#o=[];this.#i=!1;this.#r=typeof window<"u"?window:void 0}#e;#t;#n;#o;#i;#r;async connect(){this.#o.forEach(t=>t("connected"))}async startListening(){try{if(this.#i)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.#t.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=n=>{this.#n.forEach(o=>o(new Error(n.error))),this.#o.forEach(o=>o("error"))},this.#e.onstart=()=>{this.#i=!0,this.#o.forEach(n=>n("listening"))},this.#e.onend=()=>{this.#i=!1,this.#o.forEach(n=>n("idle"))},this.#e.start()}catch(t){throw this.#n.forEach(n=>n(t)),this.#o.forEach(n=>n("error")),t}}async stopListening(){this.#e&&(this.#e.stop(),this.#e=null),this.#i=!1,this.#o.forEach(t=>t("idle"))}onResult(t){this.#t.push(t)}onError(t){this.#n.push(t)}onStatusChange(t){this.#o.push(t)}async disconnect(){await this.stopListening(),this.#o.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}}});function nc(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ba(e.runtype);case"browser":if(!Ds.isSupported())throw new Error("Browser speech recognition not supported");return new Ds(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 Qg(e){if(e?.type==="custom"&&e.custom)return nc({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return nc({type:"runtype",runtype:e.runtype});if(Ds.isSupported())return nc({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function uS(e){try{return Qg(e),!0}catch{return!1}}var fS=ie(()=>{"use strict";Yg();Xg()});var mS,lu,gS=ie(()=>{"use strict";mS=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,""),lu=class{constructor(t){this.host=t;this.turns=new Map;this.latestId=null;this.cancelled=new Set}apply(t,n,o,r,s,i){let l=this.host;n=n.trim();let c=this.turns.get(r);if(c||(c={},this.turns.set(r,c),this.latestId=r),t==="user"){c.userFinal=o;let d=c.userId?l.find(c.userId):void 0;if(d){let p=c.userStartMs===void 0&&s!==void 0;p&&(c.userStartMs=s),l.upsert({...d,content:n,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else{c.userStartMs=s;let p=c.assistantId?l.find(c.assistantId):void 0;c.userId=l.inject({role:"user",content:n,streaming:!1,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s)??p)}).id}}else if(!this.cancelled.has(r)){c.assistantFinal=o;let d=c.assistantId?l.find(c.assistantId):void 0;if(d){let p=c.assistantStartMs===void 0&&s!==void 0;p&&(c.assistantStartMs=s),l.upsert({...d,content:n,streaming:!o,voiceProcessing:!o,...p&&this.placeBefore(this.startedAfter(s))})}else n&&(c.assistantStartMs=s,c.assistantId=l.inject({role:"assistant",content:n,streaming:!o,voiceProcessing:!o,voiceCaption:i,...this.placeBefore(this.startedAfter(s))}).id);o&&c.assistantId&&l.markSpoken(c.assistantId)}this.sync()}claimUserTurn(t,n=[]){let o=n[n.length-1];for(let s of n)s!==o&&(this.turns.has(s)||this.turns.set(s,{}),this.turns.get(s).claimed=!0);let r;if(o){if(r=this.turns.get(o),r||(r={},this.turns.set(o,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:"user",content:t.trim()}).id)}else{let s=mS(t),i=[...this.turns.values()].reverse().flatMap(l=>{let c=l.userId&&!l.claimed?this.host.find(l.userId):void 0;return c?[{turn:l,text:mS(c.content)}]:[]}).filter(({text:l})=>l&&s);r=(i.find(({text:l})=>l===s)??i.find(({text:l})=>l.startsWith(s)||s.startsWith(l)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let t=this.inFlight();if(t.length===0){let n=this.awaiting();if(!n)return;t=[n]}for(let n of t)this.cancelled.add(n);this.closeReplies(t),this.sync()}fail(t){let n=this.awaiting(),o=this.inFlight();if(!n&&o.length===0)return;for(let i of o)this.turns.get(i).assistantFinal=!0;this.closeReplies(o);let r=this.host.inject({role:"assistant",content:t,streaming:!1,voiceProcessing:!1}),s=n?this.turns.get(n):void 0;s&&(s.assistantId=r.id,s.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let t=this.pending(),n=new Set;for(let o of this.turns.values())o.userId&&n.add(o.userId),o.assistantId&&(n.add(o.assistantId),this.host.markSpoken(o.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(n),t&&this.host.setStreaming(!1)}startedAfter(t){if(t===void 0)return;let n;for(let o of this.turns.values())for(let[r,s]of[[o.userId,o.userStartMs],[o.assistantId,o.assistantStartMs]])r&&s!==void 0&&s>t&&(!n||s<n.start)&&(n={start:s,id:r});return n&&this.host.find(n.id)}placeBefore(t){if(!t)return;let n=t.sequence??0,o=n-1;for(let r of this.turns.values())for(let s of[r.userId,r.assistantId]){let i=s?this.host.find(s):void 0,l=i?.sequence;i?.createdAt===t.createdAt&&l!==void 0&&l>o&&l<n&&(o=l)}return{createdAt:t.createdAt,sequence:(o+n)/2}}closeReplies(t){let n=new Set;for(let o of t){let r=this.turns.get(o)?.assistantId;r&&(n.add(r),this.host.markSpoken(r))}n.size>0&&this.host.settle(n)}inFlight(){let t=[];for(let[n,o]of this.turns)o.assistantId&&!o.assistantFinal&&!this.cancelled.has(n)&&t.push(n);return t}awaiting(){let t=this.latestId;if(!t)return null;let n=this.turns.get(t);return n?.userFinal&&!n.assistantId&&!n.claimed&&!this.cancelled.has(t)?t:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}});function Zg(e,t=0){if(e==null||e==="")return"";if(typeof e!="object")return String(e);if(t>2)return"";if(Array.isArray(e))return e.map(s=>Zg(s,t+1)).filter(Boolean).join(", ");let n=e,o=n.quantity??n.qty??n.count,r=n.name??n.item??n.product??n.title;return o!=null&&r!=null&&typeof r!="object"?`${o} ${r}`:Object.entries(n).filter(([s])=>!s.startsWith("_")).map(([s,i])=>{let l=Zg(i,t+1);return l&&(t?`${Da(s)} ${l}`:`${Da(s)}: ${l}`)}).filter(Boolean).join(t?", ":"; ")}function vS(e){let t=e.length>1?"These actions need the user's approval in the chat before they happen:":"This action needs the user's approval in the chat before it happens:",n=1e3-t.length-yS.length-2,o=e.map(r=>{let s=[Da(r.toolName)];r.description&&s.push(`(${Jg(r.description.trim(),160)})`);let i=Zg(r.parameters);return i&&s.push(`with ${i}`),r.reason&&s.push(`because: ${Jg(r.reason.trim(),160)}`),Jg(`- ${s.join(" ")}`,Math.floor(n/e.length)-1)});return`${t}
192
192
  ${o.join(`
193
193
  `)}
194
194
 
195
195
  ${yS}`}function CS(e){let t=null,n=null,o=()=>e.track(t??n),r=[],s=new Map,i=new Map,l=(h,b)=>{s.set(h,[...s.get(h)??[],b]),s.size>32&&s.delete(s.keys().next().value)},c=h=>e.messages().find(b=>b.id===h),d=h=>h.approvals.filter(b=>c(b)?.approval?.status==="pending"),p=h=>Da(c(h)?.approval?.toolName??""),f=(h,b,x)=>{h.outcome={status:b,text:x};for(let A of d(h))e.decide(A)},m=h=>h.flatMap(b=>e.messages().find(x=>x.id===b)??[]).filter(b=>!b.variant&&b.content.trim()).map(b=>b.content.trim()).join(`
196
196
 
197
- `),g=async h=>{do await bS();while(e.busy()&&!(h&&(e.parked()||h.failed)))};return{getHistory:()=>e.messages().flatMap(h=>(h.role==="user"||h.role==="assistant")&&!h.variant&&!h.voiceProcessing&&!h.voiceCaption&&h.content?[{role:h.role,content:h.content}]:[]),dropDelegation(h,b){i.set(h,!!b),i.size>32&&i.delete(i.keys().next().value);let x=b&&r.find(A=>A.delegationId===h);x&&!x.outcome&&f(x,"timeout","");for(let A of s.get(h)??[])A.dropped=!0,A.ids.length&&e.unspoken(A.ids)},async runDelegatedTurn({delegationId:h,userText:b,userUtteranceIds:x}){let A=r.filter(v=>d(v).length),S=A.flatMap(d);if(S.length===1&&oH(b)){let v=p(S[0]);return f(A[0],"denied",""),{status:"denied",text:`Okay, I cancelled the ${v} request. Nothing was done.`}}let E=e.parked()&&e.messages().every(v=>!cu(v)||S.includes(v.id));e.busy()&&!E&&await g();let k=new Set(e.messages().map(v=>v.id)),D=()=>e.messages().filter(v=>!k.has(v.id)&&v.variant==="approval"),$={ids:[],failed:!1};l(h,$),t=$,o();try{await e.send(b,e.claim(b,x)??void 0),await g($)}catch{$.failed=!0}finally{t=null,o()}let J=$.ids.flatMap(v=>e.messages().find(w=>w.id===v)??[]),T=m($.ids),W=$.failed?[]:D().filter(cu),P=new Set(W.map(v=>Da(v.approval.toolName)));for(let v of A){if(v.outcome)continue;for(let L of d(v).filter(I=>P.has(p(I))))v.replaced.add(L),e.decide(L);let w=p(v.approvals[0]);v.approvals.every(L=>v.replaced.has(L))?v.outcome={status:"cancelled",text:`The earlier ${w} request was replaced by the new one; it was not done.`}:E&&v.approvals.every(L=>c(L)?.approval?.status==="denied")&&(v.outcome={status:"cancelled",text:`The earlier ${w} request was replaced by the new one; it was not done.`})}if(W.length){let v=new Set(W.map(L=>L.id)),w={delegationId:h,approvals:[...v],at:Date.now(),replaced:new Set};return r.push(w),i.get(h)&&f(w,"timeout",""),T=`${T}
197
+ `),g=async h=>{do await bS();while(e.busy()&&!(h&&(e.parked()||h.failed)))};return{getHistory:()=>e.messages().flatMap(h=>(h.role==="user"||h.role==="assistant")&&!h.variant&&!h.voiceProcessing&&!h.voiceCaption&&h.content?[{role:h.role,content:h.content}]:[]),dropDelegation(h,b){i.set(h,!!b),i.size>32&&i.delete(i.keys().next().value);let x=b&&r.find(A=>A.delegationId===h);x&&!x.outcome&&f(x,"timeout","");for(let A of s.get(h)??[])A.dropped=!0,A.ids.length&&e.unspoken(A.ids)},async runDelegatedTurn({delegationId:h,userText:b,userUtteranceIds:x}){let A=r.filter(v=>d(v).length),S=A.flatMap(d);if(S.length===1&&oH(b)){let v=p(S[0]);return f(A[0],"denied",""),{status:"denied",text:`Okay, I cancelled the ${v} request. Nothing was done.`,inChat:!1}}let E=e.parked()&&e.messages().every(v=>!cu(v)||S.includes(v.id));e.busy()&&!E&&await g();let k=new Set(e.messages().map(v=>v.id)),D=()=>e.messages().filter(v=>!k.has(v.id)&&v.variant==="approval"),$={ids:[],failed:!1};l(h,$),t=$,o();try{await e.send(b,e.claim(b,x)??void 0),await g($)}catch{$.failed=!0}finally{t=null,o()}let J=$.ids.flatMap(v=>e.messages().find(w=>w.id===v)??[]),T=m($.ids),W=$.failed?[]:D().filter(cu),P=new Set(W.map(v=>Da(v.approval.toolName)));for(let v of A){if(v.outcome)continue;for(let L of d(v).filter(I=>P.has(p(I))))v.replaced.add(L),e.decide(L);let w=p(v.approvals[0]);v.approvals.every(L=>v.replaced.has(L))?v.outcome={status:"cancelled",text:`The earlier ${w} request was replaced by the new one; it was not done.`}:E&&v.approvals.every(L=>c(L)?.approval?.status==="denied")&&(v.outcome={status:"cancelled",text:`The earlier ${w} request was replaced by the new one; it was not done.`})}if(W.length){let v=new Set(W.map(L=>L.id)),w={delegationId:h,approvals:[...v],at:Date.now(),replaced:new Set};return r.push(w),i.get(h)&&f(w,"timeout",""),T=`${T}
198
198
 
199
199
  ${vS(W.map(L=>L.approval))}`.trim(),{status:"pending_approval",text:T,followUp:async({signal:L,approvalTimeoutMs:I=3e5,readBack:Y=!0,onUpdate:_})=>{let q={ids:[],failed:!1};s.delete(h),l(h,q);let Z=()=>D().filter(de=>v.has(de.id)||q.ids.includes(de.id)),ne=()=>D().filter(de=>cu(de)&&!v.has(de.id)&&!r.some(Ge=>Ge.approvals.includes(de.id))&&(q.ids.includes(de.id)||de.approval?.toolType==="webmcp"&&n===q)),te=()=>{n=q,o()};Y&&te();try{for(;!L.aborted&&!w.outcome&&(t||e.busy()||Z().some(cu));){Y&&n!==q&&!d(w).length&&te();let de=ne();if(de.length){for(let Ge of de)v.add(Ge.id),w.approvals.push(Ge.id);w.at=Date.now(),_?.(vS(de.map(Ge=>Ge.approval)))}if(Date.now()-w.at>=I&&d(w).length&&(!e.busy()||e.parked())){f(w,"timeout",`That ${p(w.approvals[0])} request expired, so nothing was done.`);break}await bS()}}finally{n===q&&(n=null,o()),r.splice(r.indexOf(w),1)}if(L.aborted)return null;if(w.outcome)return w.outcome;if(q.failed)return{status:"failed",text:`The ${p(w.approvals[0])} request didn't complete.`};let re=Z(),pe=de=>re.filter(de).map(Ge=>Da(Ge.approval.toolName)).join(", "),xe=re.some(de=>de.approval?.status==="approved"),Se=pe(de=>de.approval?.status==="denied"&&!w.replaced.has(de.id)),se=pe(de=>w.replaced.has(de.id)),N=pe(de=>de.approval?.status==="timeout"),Ee=[xe?m(q.ids):"",Se&&`The user declined the ${Se} request in the chat, so ${xe?"that part was not done":"nothing was done"}.`,se&&`The earlier ${se} request was replaced by the new one; it was not done.`,N&&`The ${N} request timed out, so it was not done.`].filter(Boolean).join(`
200
200
 
201
201
  `);return{status:xe?"completed":Se?"denied":se?"cancelled":N?"timeout":"completed",text:Ee}}}}return!$.failed&&e.parked()||J.some(v=>v.agentMetadata?.awaitingLocalTool&&!v.agentMetadata.askUserQuestionAnswered&&!v.toolCall?.name?.startsWith("webmcp:"))?{status:$.failed?"failed":"completed",text:`${T}
202
202
 
203
- ${tH}`.trim()}:{status:!$.failed&&T?"completed":"failed",text:T}}}}var tH,hS,nH,oH,yS,bS,Jg,Da,cu,wS=ie(()=>{"use strict";tH="I need your answer in the chat before I can continue.",hS="no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)",nH=new RegExp(`^(?:${hS})(?: (?:${hS}))?(?: thanks| thank you)?$`),oH=e=>nH.test(e.toLowerCase().replace(/[^a-z' ]+/g," ").replace(/\s+/g," ").trim()),yS="Briefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.",bS=()=>new Promise(e=>setTimeout(e,50)),Jg=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e,Da=e=>e.replace(/^webmcp:/,"").replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().toLowerCase();cu=e=>e.variant==="approval"&&e.approval?.status==="pending"});var xS,SS=ie(()=>{"use strict";xS=(e,t,n,o)=>{let r=e.session;try{e.keyed=n?new n({find:d=>r.messages.find(p=>p.id===d),inject:d=>r.injectMessage(d),upsert:d=>r.upsertMessage(d),settle:d=>{r.messages=r.messages.map(p=>d.has(p.id)?{...p,streaming:!1,voiceProcessing:!1}:p),r.callbacks.onMessagesChanged([...r.messages])},setStreaming:d=>{(d||!e.busy())&&e.setStreaming(d)},markSpoken:d=>{r.ttsSpokenMessageIds.add(d)}}):null,o&&t.setSessionBridge&&t.setSessionBridge(o({messages:()=>r.messages,busy:()=>e.busy(),parked:()=>r.webMcpApprovalResolvers.size>0,claim:(d,p)=>e.keyed?.claimUserTurn(d,p)??null,send:(d,p)=>r.sendMessage(d,{viaVoice:!0,voiceTurn:{userMessageId:p}}),track:d=>{e.setDelegation(d)},unspoken:d=>{for(let p of d)r.ttsSpokenMessageIds.delete(p);r.streaming||r.speakLatestAssistantMessage(d)},decide:d=>{if(r.webMcpApprovalResolvers.has(d))return r.resolveWebMcpApproval(d,"denied");let p=r.messages.find(f=>f.id===d)?.approval;p?.status==="pending"&&r.resolveApproval(p,"denied")}}));let s=e.generation(),i=()=>e.provider()===t&&s===e.generation(),c=(r.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";t.onResult(d=>{i()&&d.provider!=="runtype"&&d.text&&d.text.trim()&&r.sendMessage(d.text,{viaVoice:!0})}),t.onTranscript&&t.onTranscript((d,p,f,m)=>{if(i()){if(m?.turnId){e.keyed?.apply(d,p,f,m.turnId,m.startMs,m.caption);return}if(d==="user"){if(e.pendingUser)r.upsertMessage({id:e.pendingUser,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!f});else{let g=r.injectMessage({role:"user",content:p,streaming:!1,voiceProcessing:!f});e.pendingUser=g.id}if(f){e.turns().start(m?.turnId),e.pendingUser=null;let g=r.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});e.pendingAssistant=g.id,e.setStreaming(!0)}}else{if(!e.turns().accepts(m?.turnId))return;if(e.pendingAssistant)r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!f,voiceProcessing:!f});else{let g=r.injectMessage({role:"assistant",content:p,streaming:!f,voiceProcessing:!f});e.pendingAssistant=g.id}f&&(e.pendingAssistant&&r.ttsSpokenMessageIds.add(e.pendingAssistant),e.setStreaming(!1),e.pendingAssistant=null)}}}),t.onLevel&&t.onLevel(d=>{i()&&e.setLevel(Number.isFinite(d)?Math.max(0,Math.min(1,d)):0)}),t.onMetrics&&t.onMetrics(d=>{i()&&r.config.voiceRecognition?.onMetrics?.(d)}),t.onError(d=>{i()&&(console.error("Voice error:",d),e.pendingAssistant&&(r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),e.setStreaming(!1),e.pendingUser=null,e.pendingAssistant=null),e.keyed?.fail(c))}),t.onStatusChange(d=>{i()&&(e.setStatus(d),(d==="listening"||d==="idle"||d==="disconnected")&&e.settlePending(d!=="listening"),(d==="idle"||d==="disconnected")&&e.keyed?.settle(),r.callbacks.onVoiceStatusChanged?.(d))}),t.connect()}catch(s){console.error("Failed to setup voice:",s)}}});var AS,MS=ie(()=>{"use strict";AS=e=>{let t=c=>{if(e.original)return;let d=e.config().voiceRecognition??{};e.original={backgroundColor:c.style.backgroundColor,color:c.style.color,borderColor:c.style.borderColor,iconName:d.iconName??"mic",iconSize:parseFloat(d.iconSize??"")||e.iconFallbackPx}},n=(c,d,p)=>{let f=c.querySelector("svg");f&&f.remove();let m=e.original?.iconSize??(parseFloat(e.config().voiceRecognition?.iconSize??"")||e.iconFallbackPx),g=e.renderIcon(d,m,p,1.5);g&&c.appendChild(g)},o=c=>{c.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")};return{recording:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=d.recordingBackgroundColor,f=d.recordingIconColor,m=d.recordingBorderColor;if(o(c),c.classList.add("persona-voice-recording"),e.setMicState("recording"),c.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",c.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let g=c.querySelector("svg");g&&g.setAttribute("stroke",f)}m&&(c.style.borderColor=m),c.setAttribute("aria-label","Stop voice recognition")},processing:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=d.processingIconName??"loader",g=d.processingIconColor??f?.color??"",h=d.processingBackgroundColor??f?.backgroundColor??"",b=d.processingBorderColor??f?.borderColor??"";o(c),c.classList.add("persona-voice-processing"),e.setMicState("processing"),c.style.backgroundColor=h,c.style.borderColor=b;let x=g||"currentColor";c.style.color=x,n(c,m,x),c.setAttribute("aria-label","Processing voice input"),p==="none"&&(c.style.cursor="default")},speaking:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",g=d.speakingIconName??m,h=d.speakingIconColor??(p==="barge-in"?d.recordingIconColor??f?.color??"":f?.color??""),b=d.speakingBackgroundColor??(p==="barge-in"?d.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":f?.backgroundColor??""),x=d.speakingBorderColor??(p==="barge-in"?d.recordingBorderColor??"":f?.borderColor??"");o(c),c.classList.add("persona-voice-speaking"),e.setMicState("speaking"),c.style.backgroundColor=b,c.style.borderColor=x;let A=h||"currentColor";c.style.color=A,n(c,g,A);let S=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";c.setAttribute("aria-label",S),p==="none"&&(c.style.cursor="default"),p==="barge-in"&&c.classList.add("persona-voice-recording")},reset:()=>{let c=e.mic();if(!c)return;o(c),e.setMicState("idle");let d=e.original;d&&(c.style.backgroundColor=d.backgroundColor??"",c.style.color=d.color??"",c.style.borderColor=d.borderColor??"",n(c,d.iconName,d.color||"currentColor"),e.original=null),c.style.cursor="",c.setAttribute("aria-label","Start voice recognition")}}}});var TS={};En(TS,{BrowserVoiceProvider:()=>Ds,KeyedVoiceTranscript:()=>lu,RuntypeVoiceProvider:()=>Ba,createBestAvailableVoiceProvider:()=>Qg,createMicStateStyles:()=>AS,createVoiceProvider:()=>nc,createVoiceSessionBridge:()=>CS,isVoiceSupported:()=>uS,wireSessionVoice:()=>xS});var ES=ie(()=>{"use strict";fS();Yg();Xg();gS();wS();SS();MS()});function aH(e){return e.replace(/\/+$/,"")}async function lH(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 du,PS=ie(()=>{"use strict";Kg();du=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#t=null;this.#n=0;this.#o=t}#e;#t;#n;#o;#c(){return this.#t??=Promise.resolve(this.#o.createPlaybackEngine?this.#o.createPlaybackEngine():new Wa(24e3,{prebufferMs:this.#o.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#n;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#c();if(t!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#n&&o.onStart?.()}),r.onFinished(()=>{t===this.#n&&o.onEnd?.()});let s=`${aH(this.#o.host)}/v1/agents/${encodeURIComponent(this.#o.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#o.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#o.voice,format:"pcm"})});if(t!==this.#n)return;if(!i.ok||!i.body)throw new Error(await lH(i));let l=i.body.getReader();for(;;){let{done:c,value:d}=await l.read();if(t!==this.#n){await l.cancel().catch(()=>{});return}if(c)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.#n)return;let s=r instanceof Error?r:new Error(String(r));this.#o.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}});var pu,IS=ie(()=>{"use strict";pu=class{constructor(t,n,o={}){this.id="fallback";this.#t=t,this.#n=n,this.#o=o,this.#e=t}#e;#t;#n;#o;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.#o.onFallback?.(r),this.#e=this.#n,this.#n.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}});var HS={};En(HS,{FallbackSpeechEngine:()=>pu,RuntypeSpeechEngine:()=>du});var RS=ie(()=>{"use strict";PS();IS()});var BS={};En(BS,{createReconnectController:()=>dH});function dH(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},i=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},c=()=>{i()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},f=h=>new Promise(b=>{n=b,o=setTimeout(()=>{o=null,n=null,b()},h)}),m=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let b=!1;for(let A of e.getMessages())A.streaming&&(A.streaming=!1,b=!0);let x=e.buildErrorContent("Connection lost and the response could not be resumed.");x?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):b&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let h=e.config.reconnect?.backoffMs??cH,b=e.config.reconnect?.maxAttempts??h.length,x=e.config.reconnectStream;if(!x){e.setReconnecting(!1);return}for(;e.getResumable()&&t<b;){t+=1,e.setStatus("resuming");let A=e.getResumable(),S=A.lastEventId,E=new AbortController;e.setAbortController(E),e.emitReconnect({phase:"resuming",handle:A,attempt:t});let k=null;try{let D=await x({executionId:A.executionId,after:A.lastEventId,signal:E.signal});D&&D.ok&&D.body&&(k=D.body)}catch{k=null}if(E.signal.aborted)return;if(k){let D=e.getMessages().find(J=>J.id===A.assistantMessageId)?.content,$=typeof D=="string"?D:"";try{await e.resumeConnect(k,A.assistantMessageId,$)}catch{}if(E.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:A});return}e.getResumable().lastEventId!==S&&(t=0)}if(e.getResumable()&&t<b&&(e.setStatus("paused"),await f(h[Math.min(t-1,h.length-1)]??1e3),E.signal.aborted))return}e.getResumable()&&m()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var cH,DS=ie(()=>{"use strict";cH=[1e3,2e3,4e3,8e3,8e3]});var TA,gh,pR,Su,Au,uR,EA,Mu,dc,fR,mR,kA,Tu=ie(()=>{"use strict";TA=null,gh=()=>{if(TA!==null)return TA;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},pR="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Su=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Au=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 Su("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Su("unsupported",e),null):(n==="space"&&(o.key=" "),o)},uR=e=>pR.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),EA=(e,t)=>{let n=Au(e);if(!n)return"";let o=gh(),r=uR(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("+")},Mu=e=>EA(e,!1),dc=e=>EA(e,!0),fR=(e,t)=>t.key?.toLowerCase()===e.key&&(gh()?t.metaKey:t.ctrlKey)===e.mod&&!(gh()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,mR=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},kA=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(fR(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&mR(i))){s.preventDefault();try{l.run(s)}catch(c){Su(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Au(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Su(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",dc(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function OA(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 ku(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Zr(e,t){return xr(e)-e.scrollTop<=t}function Lu(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Pu(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 _A(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yh(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 NA(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var bh=ie(()=>{"use strict"});var pc,gR,Iu,hR,wh,VA,Pi,uc,Hu,yR,bR,vh,vR,CR,wR,fc,Ru,mc,FA,xR,Ch,SR,$A,gc,hc=ie(()=>{"use strict";pc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gR=["pre","code","a","script","style"],Iu=e=>({type:e?.type??pc.type,placeholder:e?.placeholder??pc.placeholder,speed:e?.speed??pc.speed,duration:e?.duration??pc.duration,buffer:e?.buffer??pc.buffer}),hR=[{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"}],wh=new Map;for(let e of hR)wh.set(e.name,e);VA=["wipe","glyph-cycle"],Pi=e=>{wh.set(e.name,e)},uc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:wh.get(e)??null,Hu=(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(`
203
+ ${tH}`.trim()}:{status:!$.failed&&T?"completed":"failed",text:T}}}}var tH,hS,nH,oH,yS,bS,Jg,Da,cu,wS=ie(()=>{"use strict";tH="I need your answer in the chat before I can continue.",hS="no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)",nH=new RegExp(`^(?:${hS})(?: (?:${hS}))?(?: thanks| thank you)?$`),oH=e=>nH.test(e.toLowerCase().replace(/[^a-z' ]+/g," ").replace(/\s+/g," ").trim()),yS="Briefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.",bS=()=>new Promise(e=>setTimeout(e,50)),Jg=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}\u2026`:e,Da=e=>e.replace(/^webmcp:/,"").replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[_\-.]+/g," ").trim().toLowerCase();cu=e=>e.variant==="approval"&&e.approval?.status==="pending"});var xS,SS=ie(()=>{"use strict";xS=(e,t,n,o)=>{let r=e.session;try{e.keyed=n?new n({find:d=>r.messages.find(p=>p.id===d),inject:d=>r.injectMessage(d),upsert:d=>r.upsertMessage(d),settle:d=>{r.messages=r.messages.map(p=>d.has(p.id)?{...p,streaming:!1,voiceProcessing:!1}:p),r.callbacks.onMessagesChanged([...r.messages])},setStreaming:d=>{(d||!e.busy())&&e.setStreaming(d)},markSpoken:d=>{r.ttsSpokenMessageIds.add(d)}}):null,o&&t.setSessionBridge&&t.setSessionBridge(o({messages:()=>r.messages,busy:()=>e.busy(),parked:()=>r.webMcpApprovalResolvers.size>0,claim:(d,p)=>e.keyed?.claimUserTurn(d,p)??null,send:(d,p)=>r.sendMessage(d,{viaVoice:!0,voiceTurn:{userMessageId:p}}),track:d=>{e.setDelegation(d)},unspoken:d=>{for(let p of d)r.ttsSpokenMessageIds.delete(p);r.streaming||r.speakLatestAssistantMessage(d)},decide:d=>{if(r.webMcpApprovalResolvers.has(d))return r.resolveWebMcpApproval(d,"denied");let p=r.messages.find(f=>f.id===d)?.approval;p?.status==="pending"&&r.resolveApproval(p,"denied")}}));let s=e.generation(),i=()=>e.provider()===t&&s===e.generation(),c=(r.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";t.onResult(d=>{i()&&d.provider!=="runtype"&&d.text&&d.text.trim()&&r.sendMessage(d.text,{viaVoice:!0})}),t.onTranscript&&t.onTranscript((d,p,f,m)=>{if(i()){if(m?.turnId){e.keyed?.apply(d,p,f,m.turnId,m.startMs,m.caption);return}if(d==="user"){if(e.pendingUser)r.upsertMessage({id:e.pendingUser,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!f});else{let g=r.injectMessage({role:"user",content:p,streaming:!1,voiceProcessing:!f});e.pendingUser=g.id}if(f){e.turns().start(m?.turnId),e.pendingUser=null;let g=r.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});e.pendingAssistant=g.id,e.setStreaming(!0)}}else{if(!e.turns().accepts(m?.turnId))return;if(e.pendingAssistant)r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!f,voiceProcessing:!f});else{let g=r.injectMessage({role:"assistant",content:p,streaming:!f,voiceProcessing:!f});e.pendingAssistant=g.id}f&&(e.pendingAssistant&&r.ttsSpokenMessageIds.add(e.pendingAssistant),e.setStreaming(!1),e.pendingAssistant=null)}}}),t.onLevel&&t.onLevel(d=>{i()&&e.setLevel(Number.isFinite(d)?Math.max(0,Math.min(1,d)):0)}),t.onMetrics&&t.onMetrics(d=>{i()&&r.config.voiceRecognition?.onMetrics?.(d)}),t.onError(d=>{i()&&(console.error("Voice error:",d),e.pendingAssistant&&(r.upsertMessage({id:e.pendingAssistant,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),e.setStreaming(!1),e.pendingUser=null,e.pendingAssistant=null),e.keyed?.fail(c))}),t.onStatusChange(d=>{i()&&(e.setStatus(d),(d==="listening"||d==="idle"||d==="disconnected")&&e.settlePending(d!=="listening"),(d==="idle"||d==="disconnected")&&e.keyed?.settle(),r.callbacks.onVoiceStatusChanged?.(d))}),t.connect()}catch(s){console.error("Failed to setup voice:",s)}}});var AS,MS=ie(()=>{"use strict";AS=e=>{let t=c=>{if(e.original)return;let d=e.config().voiceRecognition??{};e.original={backgroundColor:c.style.backgroundColor,color:c.style.color,borderColor:c.style.borderColor,iconName:d.iconName??"mic",iconSize:parseFloat(d.iconSize??"")||e.iconFallbackPx}},n=(c,d,p)=>{let f=c.querySelector("svg");f&&f.remove();let m=e.original?.iconSize??(parseFloat(e.config().voiceRecognition?.iconSize??"")||e.iconFallbackPx),g=e.renderIcon(d,m,p,1.5);g&&c.appendChild(g)},o=c=>{c.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")};return{recording:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=d.recordingBackgroundColor,f=d.recordingIconColor,m=d.recordingBorderColor;if(o(c),c.classList.add("persona-voice-recording"),e.setMicState("recording"),c.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",c.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let g=c.querySelector("svg");g&&g.setAttribute("stroke",f)}m&&(c.style.borderColor=m),c.setAttribute("aria-label","Stop voice recognition")},processing:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=d.processingIconName??"loader",g=d.processingIconColor??f?.color??"",h=d.processingBackgroundColor??f?.backgroundColor??"",b=d.processingBorderColor??f?.borderColor??"";o(c),c.classList.add("persona-voice-processing"),e.setMicState("processing"),c.style.backgroundColor=h,c.style.borderColor=b;let x=g||"currentColor";c.style.color=x,n(c,m,x),c.setAttribute("aria-label","Processing voice input"),p==="none"&&(c.style.cursor="default")},speaking:()=>{let c=e.mic();if(!c)return;t(c);let d=e.config().voiceRecognition??{},p=e.session().getVoiceInterruptionMode(),f=e.original,m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",g=d.speakingIconName??m,h=d.speakingIconColor??(p==="barge-in"?d.recordingIconColor??f?.color??"":f?.color??""),b=d.speakingBackgroundColor??(p==="barge-in"?d.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":f?.backgroundColor??""),x=d.speakingBorderColor??(p==="barge-in"?d.recordingBorderColor??"":f?.borderColor??"");o(c),c.classList.add("persona-voice-speaking"),e.setMicState("speaking"),c.style.backgroundColor=b,c.style.borderColor=x;let A=h||"currentColor";c.style.color=A,n(c,g,A);let S=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";c.setAttribute("aria-label",S),p==="none"&&(c.style.cursor="default"),p==="barge-in"&&c.classList.add("persona-voice-recording")},reset:()=>{let c=e.mic();if(!c)return;o(c),e.setMicState("idle");let d=e.original;d&&(c.style.backgroundColor=d.backgroundColor??"",c.style.color=d.color??"",c.style.borderColor=d.borderColor??"",n(c,d.iconName,d.color||"currentColor"),e.original=null),c.style.cursor="",c.setAttribute("aria-label","Start voice recognition")}}}});var TS={};En(TS,{BrowserVoiceProvider:()=>Ds,KeyedVoiceTranscript:()=>lu,RuntypeVoiceProvider:()=>Ba,createBestAvailableVoiceProvider:()=>Qg,createMicStateStyles:()=>AS,createVoiceProvider:()=>nc,createVoiceSessionBridge:()=>CS,isVoiceSupported:()=>uS,wireSessionVoice:()=>xS});var ES=ie(()=>{"use strict";fS();Yg();Xg();gS();wS();SS();MS()});function aH(e){return e.replace(/\/+$/,"")}async function lH(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 du,PS=ie(()=>{"use strict";Kg();du=class{constructor(t){this.id="runtype-tts";this.supportsPause=!0;this.#e=null;this.#t=null;this.#n=0;this.#o=t}#e;#t;#n;#o;#i(){return this.#t??=Promise.resolve(this.#o.createPlaybackEngine?this.#o.createPlaybackEngine():new Wa(24e3,{prebufferMs:this.#o.prebufferMs??200})).then(t=>this.#e=t)}speak(t,n){let o=++this.#n;this.#r(o,t,n)}async#r(t,n,o){try{let r=await this.#i();if(t!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.#n&&o.onStart?.()}),r.onFinished(()=>{t===this.#n&&o.onEnd?.()});let s=`${aH(this.#o.host)}/v1/agents/${encodeURIComponent(this.#o.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.#o.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.#o.voice,format:"pcm"})});if(t!==this.#n)return;if(!i.ok||!i.body)throw new Error(await lH(i));let l=i.body.getReader();for(;;){let{done:c,value:d}=await l.read();if(t!==this.#n){await l.cancel().catch(()=>{});return}if(c)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.#n)return;let s=r instanceof Error?r:new Error(String(r));this.#o.onError?.(s),o.onError?.(s)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}});var pu,IS=ie(()=>{"use strict";pu=class{constructor(t,n,o={}){this.id="fallback";this.#t=t,this.#n=n,this.#o=o,this.#e=t}#e;#t;#n;#o;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.#o.onFallback?.(r),this.#e=this.#n,this.#n.speak(t,n)}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}});var HS={};En(HS,{FallbackSpeechEngine:()=>pu,RuntypeSpeechEngine:()=>du});var RS=ie(()=>{"use strict";PS();IS()});var BS={};En(BS,{createReconnectController:()=>dH});function dH(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},i=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},c=()=>{i()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",c),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",c),r=!1)},f=h=>new Promise(b=>{n=b,o=setTimeout(()=>{o=null,n=null,b()},h)}),m=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let b=!1;for(let A of e.getMessages())A.streaming&&(A.streaming=!1,b=!0);let x=e.buildErrorContent("Connection lost and the response could not be resumed.");x?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:x,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):b&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let h=e.config.reconnect?.backoffMs??cH,b=e.config.reconnect?.maxAttempts??h.length,x=e.config.reconnectStream;if(!x){e.setReconnecting(!1);return}for(;e.getResumable()&&t<b;){t+=1,e.setStatus("resuming");let A=e.getResumable(),S=A.lastEventId,E=new AbortController;e.setAbortController(E),e.emitReconnect({phase:"resuming",handle:A,attempt:t});let k=null;try{let D=await x({executionId:A.executionId,after:A.lastEventId,signal:E.signal});D&&D.ok&&D.body&&(k=D.body)}catch{k=null}if(E.signal.aborted)return;if(k){let D=e.getMessages().find(J=>J.id===A.assistantMessageId)?.content,$=typeof D=="string"?D:"";try{await e.resumeConnect(k,A.assistantMessageId,$)}catch{}if(E.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:A});return}e.getResumable().lastEventId!==S&&(t=0)}if(e.getResumable()&&t<b&&(e.setStatus("paused"),await f(h[Math.min(t-1,h.length-1)]??1e3),E.signal.aborted))return}e.getResumable()&&m()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var cH,DS=ie(()=>{"use strict";cH=[1e3,2e3,4e3,8e3,8e3]});var TA,gh,pR,Su,Au,uR,EA,Mu,dc,fR,mR,kA,Tu=ie(()=>{"use strict";TA=null,gh=()=>{if(TA!==null)return TA;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},pR="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Su=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Au=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 Su("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Su("unsupported",e),null):(n==="space"&&(o.key=" "),o)},uR=e=>pR.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),EA=(e,t)=>{let n=Au(e);if(!n)return"";let o=gh(),r=uR(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("+")},Mu=e=>EA(e,!1),dc=e=>EA(e,!0),fR=(e,t)=>t.key?.toLowerCase()===e.key&&(gh()?t.metaKey:t.ctrlKey)===e.mod&&!(gh()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,mR=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},kA=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(fR(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&mR(i))){s.preventDefault();try{l.run(s)}catch(c){Su(`${l.id} threw on`,l.combo),console.warn(c)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Au(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,c=t.get(l);return c?(Su(`${c.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",dc(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}}});function OA(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 ku(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function xr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Zr(e,t){return xr(e)-e.scrollTop<=t}function Lu(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&c&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Pu(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 _A(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yh(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 NA(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var bh=ie(()=>{"use strict"});var pc,gR,Iu,hR,wh,VA,Pi,uc,Hu,yR,bR,vh,vR,CR,wR,fc,Ru,mc,FA,xR,Ch,SR,$A,gc,hc=ie(()=>{"use strict";pc={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gR=["pre","code","a","script","style"],Iu=e=>({type:e?.type??pc.type,placeholder:e?.placeholder??pc.placeholder,speed:e?.speed??pc.speed,duration:e?.duration??pc.duration,buffer:e?.buffer??pc.buffer}),hR=[{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"}],wh=new Map;for(let e of hR)wh.set(e.name,e);VA=["wipe","glyph-cycle"],Pi=e=>{wh.set(e.name,e)},uc=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:wh.get(e)??null,Hu=(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(`
204
204
  `);return s<0?"":e.slice(0,s)}return e},yR=(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},bR=(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},vh=/\s/,vR=(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},CR=(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(vh.test(s[l])){let c=l;for(;c<s.length&&vh.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 d=l;for(;d<s.length&&!vh.test(s[d]);)c.appendChild(yR(o,s[d],t,n.value)),n.value+=1,d+=1;i.appendChild(c),l=d}r.replaceChild(i,e)},wR=(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(bR(o,c,t,n.value)),n.value+=1));r.replaceChild(i,e)},fc=(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??gR).map(f=>f.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],c=i.nextNode();for(;c;)vR(c,s)||l.push(c),c=i.nextNode();let d={value:o?.startIndex??0},p=t==="char"?CR:wR;for(let f of l)p(f,n,d);return r.innerHTML},Ru=(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},mc=(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},FA=new WeakMap,xR=(e,t)=>{if(!e.styles)return;let n=FA.get(t);if(n||(n=new Set,FA.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)},Ch=new WeakMap,SR=(e,t)=>{if(!e.onAttach)return;let n=Ch.get(t);if(n||(n=new Map,Ch.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},$A=e=>{let t=Ch.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},gc=(e,t)=>{xR(e,t),SR(e,t)}});var AR,UA,zA,qA=ie(()=>{"use strict";hc();AR=`
205
205
  @keyframes persona-stream-wipe {
206
206
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
@@ -255,7 +255,7 @@ ${tH}`.trim()}:{status:!$.failed&&T?"completed":"failed",text:T}}}}var tH,hS,nH,
255
255
  opacity: 1 !important;
256
256
  }
257
257
  }
258
- `.trim(),yc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",TR=10,ER=120,xh=120,kR=.4,LR=50,PR=e=>{if(!e)return xh;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):xh},ZA=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=PR(t);return ER*n/xh},Sh=e=>{let t=yc[Math.floor(Math.random()*yc.length)];return e&&t===e&&(t=yc[(yc.indexOf(t)+1)%yc.length]),t},IR=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<kR&&(r.textContent=Sh())}},jA=new WeakMap,KA=25,GA=.5,HR=6,YA=.25,XA=new WeakMap,QA=new WeakMap,RR=(e,t)=>{if(!e)return KA*GA;let n=XA.get(e);XA.set(e,t);let o=QA.get(e)??KA;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-YA)+r*YA,QA.set(e,o))}return Math.max(HR,o*GA)},_a=new Map,WR=e=>e.closest("[data-message-id]")?.dataset.messageId??null,BR=e=>{e&&_a.set(e,(_a.get(e)??0)+1)},DR=e=>{if(!e)return;let t=_a.get(e)??0;t<=1?_a.delete(e):_a.set(e,t-1)},eM=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Sh();let n=WR(e);n&&(e.dataset.glyphCycleMessageId=n),BR(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=RR(o,r),i=ZA(e),l=TR*i,c=r+l;if(o){let d=jA.get(o);d!==void 0&&(c=Math.max(c,d)),jA.set(o,c+s)}OR(e,t,c)},OR=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=ZA(e),r=e.textContent??void 0,s=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,DR(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let i=Sh(r);e.textContent=i,r=i,IR(e),setTimeout(s,o)};setTimeout(s,o)},JA=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))eM(n)},_R=e=>e.nodeType===1,tM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:MR,bufferContent(e){if(e.length<LR)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(_a.get(e.id)??0)>0},onAttach(e){JA(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))_R(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?eM(r):JA(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};Pi(tM);nM=tM});var rM={};En(rM,{glyphCycle:()=>nM,wipe:()=>zA});var sM=ie(()=>{"use strict";qA();oM()});function Sc(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=C("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(Ta)):(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 h of t){if(h.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",h.id),h.destructive&&b.setAttribute("data-destructive",""),h.icon){let A=Re(h.icon,16,"currentColor",1.5);A&&b.appendChild(A)}let x=document.createElement("span");x.textContent=h.label,b.appendChild(x),b.addEventListener("click",A=>{A.stopPropagation(),f(),n(h.id)}),l.appendChild(b)}let c=null;function d(){if(!s)return;let h=o.getBoundingClientRect();l.style.top=`${h.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-h.right}px`,l.style.left="auto"):(l.style.left=`${h.left}px`,l.style.right="auto")}function p(){let h=l.classList.contains("persona-hidden");d(),l.classList.remove("persona-hidden"),h&&i?.(!0),requestAnimationFrame(()=>{let b=x=>{!l.contains(x.target)&&!o.contains(x.target)&&f()};document.addEventListener("click",b,!0),c=()=>document.removeEventListener("click",b,!0)})}function f(){let h=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,h&&i?.(!1)}function m(){l.classList.contains("persona-hidden")?p():f()}function g(){f(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:f,toggle:m,destroy:g}}var Ph=ie(()=>{"use strict";Ye();ln();nr()});function Ln(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,d=C("button",Jt(!i&&"persona-icon-btn",s));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=Re(t,o??16,"currentColor",r??2);if(p&&d.appendChild(p),l&&d.addEventListener("click",l),c)for(let[f,m]of Object.entries(c))d.setAttribute(f,m);return d}function Hi(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,i&&(d+=" "+i);let p=C("button",d);if(p.type="button",p.setAttribute("aria-label",n),t){let m=Re(t,s??14,"currentColor",2);m&&p.appendChild(m)}let f=C("span");if(f.textContent=n,p.appendChild(f),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Bu(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=C("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let f;p.icon?f=Ln({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),o(p.id)}}):(f=C("button","persona-icon-btn"+(p.className?" "+p.className:"")),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{i=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:f}),s.appendChild(f)}function d(p){i=p,c()}return{element:s,setSelected:d}}function dM(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:d,chevronLabel:p="More options",chevronIconSize:f,className:m,primaryClassName:g,chevronClassName:h}=e,b=C("div","persona-split-btn"+(m?" "+m:"")),x={label:t,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},A=r&&n?Ln({...x,icon:n,size:o??14}):Hi({...x,icon:n,iconSize:o??14}),S=Ln({icon:"chevron-down",label:p,size:f??14,className:"persona-split-btn-chevron"+(h?" "+h:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});b.append(A,S);let E=null,k=()=>{if(E)return E;let D=(typeof d=="function"?d():d)??void 0;return E=Sc({items:s,onSelect:i,anchor:b,position:c,portal:D,onOpenChange:$=>{S.setAttribute("aria-expanded",$?"true":"false")}}),D||b.appendChild(E.element),E};return b.isConnected?k():requestAnimationFrame(()=>{E||k()}),S.addEventListener("click",D=>{D.stopPropagation(),k().toggle()}),{element:b,primaryButton:A,chevronButton:S,openMenu:()=>k().show(),closeMenu:()=>E?.hide(),toggleMenu:()=>k().toggle(),destroy:()=>{E?.destroy(),b.remove()}}}function pM(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,d=C("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=C("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let f=Re(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),c&&(d.style.borderRadius=c.borderRadius??"10px",d.style.padding=c.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=c.background??"",d.style.borderColor=c.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let m=Sc({items:o,onSelect:h=>{d.setAttribute("aria-expanded","false"),r(h)},anchor:d,position:s,portal:i});i||d.appendChild(m.element);let g=()=>d.getAttribute("data-persona-menu-locked")==="true";return d.addEventListener("click",h=>{if(h.stopPropagation(),g())return;let b=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),m.toggle()}),d.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d.click())}),{element:d,setLabel:h=>{p.textContent=h,d.setAttribute("aria-label",h)},open:()=>{d.setAttribute("aria-expanded","true"),m.show()},close:()=>{d.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let h=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),d.remove()}}}var Ri=ie(()=>{"use strict";Ye();ln();Ph()});var Fs,zu=ie(()=>{"use strict";Ye();Fs=(e,t,n)=>{let o=n;for(let r of t){let s=C("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o}});var $M,Xh,qu,ju=ie(()=>{"use strict";$M=()=>{},Xh=e=>{$M=e.webMcpToolTitle},qu=e=>$M(e)});var $o,Bi,UM,zM,qM,Qh,Jh,Zh=ie(()=>{"use strict";Ye();Gr();ju();$o=require("lucide");io();Ai();Bi=e=>{let n=(e.startsWith(Kr)?e.slice(Kr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},UM=e=>e?.approval!==!1?e?.approval:void 0,zM=(e,t,n)=>{let o=UM(n)?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},qM=(e,t,n)=>{let o=UM(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=Je(t?$o.ChevronUp:$o.ChevronDown,14,"currentColor",2);i&&s.appendChild(i)}},Qh=(e,t,n,o=new Map)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let i=zM(e,o,n);qM(r,i,n),s.style.display=i?"":"none"},Jh=(e,t,n=new Map)=>{let o=e.approval,r=t?.approval!==!1?t?.approval:void 0,s=o?.status==="pending",i=C("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",i.style.borderColor=r?.borderColor??"var(--persona-approval-border)",i.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return i;let l=C("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=C("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let d=o.status==="denied"?$o.ShieldX:o.status==="timeout"?$o.ShieldAlert:$o.ShieldCheck,p=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",f=Je(d,20,p,2);f&&c.appendChild(f);let m=C("div","persona-flex-1 persona-min-w-0"),g=C("div","persona-flex persona-items-center persona-gap-2"),h=C("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(h.style.color=r.titleColor),h.textContent=r?.title??"Approval Required",g.appendChild(h),!s){let T=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");T.setAttribute("data-approval-status",o.status),o.status==="approved"?(T.style.backgroundColor="var(--persona-palette-colors-success-100)",T.style.color="var(--persona-palette-colors-success-700)",T.textContent="Approved"):o.status==="denied"?(T.style.backgroundColor="var(--persona-palette-colors-error-100)",T.style.color="var(--persona-palette-colors-error-700)",T.textContent="Denied"):o.status==="timeout"&&(T.style.backgroundColor="var(--persona-palette-colors-warning-100)",T.style.color="var(--persona-palette-colors-warning-700)",T.textContent="Timeout"),g.appendChild(T)}m.appendChild(g);let x=o.toolType==="webmcp"||o.toolName.startsWith(Kr)?qu(o.toolName):void 0,A=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...x?{displayTitle:x}:{},...o.reason?{reason:o.reason}:{}}),S=!o.toolName,E=A||(S?o.description:`The assistant wants to use \u201C${x??Bi(o.toolName)}\u201D.`),k=C("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=E,m.appendChild(k),o.reason){let T=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");T.setAttribute("data-approval-reason","true"),r?.reasonColor?T.style.color=r.reasonColor:r?.descriptionColor&&(T.style.color=r.descriptionColor);let W=C("span","persona-font-medium");W.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,T.appendChild(W),T.appendChild(document.createTextNode(o.reason)),m.appendChild(T)}let D=r?.detailsDisplay??"collapsed",$=!!o.description&&!S,J=$||!!o.parameters;if(D!=="hidden"&&J){let T=zM(e.id,n,t),W=C("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(W.style.color=r.descriptionColor);let P=C("span");P.setAttribute("data-approval-details-label","true");let v=C("span","persona-inline-flex persona-items-center");v.setAttribute("data-approval-details-chevron","true"),W.append(P,v),qM(W,T,t),m.appendChild(W);let w=C("div");if(w.setAttribute("data-approval-details","true"),w.style.display=T?"":"none",$){let L=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(L.style.color=r.descriptionColor),L.textContent=o.description,w.appendChild(L)}if(o.parameters){let L=C("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(L.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(L.style.color=r.parameterTextColor),L.style.fontSize="0.75rem",L.style.lineHeight="1rem",L.textContent=tr(o.parameters),w.appendChild(L)}m.appendChild(w)}if(s){let T=C("div","persona-flex persona-gap-2 persona-mt-2");T.setAttribute("data-approval-buttons","true");let W=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",W.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",W.setAttribute("data-approval-action","approve");let P=Je($o.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);P&&(P.style.marginRight="4px",W.appendChild(P));let v=document.createTextNode(r?.approveLabel??"Approve");W.appendChild(v);let w=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");w.type="button",w.style.backgroundColor=r?.denyButtonColor??"transparent",w.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",w.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,w.setAttribute("data-approval-action","deny");let L=Je($o.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);L&&(L.style.marginRight="4px",w.appendChild(L));let I=document.createTextNode(r?.denyLabel??"Deny");w.appendChild(I),T.append(W,w),m.appendChild(T)}return l.append(c,m),i.appendChild(l),i}});var Oi,NW,jM,Di,FW,VW,ey,$W,UW,zW,ty,KM=ie(()=>{"use strict";Ye();ju();Oi=require("lucide");io();Gr();Ai();Ra();Zh();NW=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),jM=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Di=(e,t)=>{jM(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},FW=e=>e?.approval!==!1?e?.approval:void 0,VW=(e,t,n)=>{let o=n?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},ey=e=>{let t=C("span","persona-approval-kbd");return t.textContent=e,t},$W=(e,t)=>{let n=C("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Kr)?qu(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let i=r??Bi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=i,n.appendChild(c),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},UW=e=>{let t=C("div","persona-approval-resolved"),n=Je(Oi.Ban,15,"currentColor",2);n&&t.appendChild(n);let o=C("span","persona-approval-resolved-name");return o.textContent=e.toolName?Bi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},zW=(e,t,n,o,r,s,i,l,c=!1)=>{let d=C("div","persona-approval-card persona-shadow-sm");d.id=`bubble-${n.id}`,d.setAttribute("data-message-id",n.id),d.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(d.style.background=r.backgroundColor),r?.borderColor&&(d.style.borderColor=r.borderColor),r?.shadow!==void 0&&(d.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",f=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden"&&!c,g=f||m,h=g&&VW(n.id,t,r),b=r?.showDetailsLabel??"Show details",x=r?.hideDetailsLabel??"Hide details",A=C("button","persona-approval-head");A.type="button",g?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",h?"true":"false"),A.setAttribute("aria-label",h?x:b)):A.setAttribute("data-static","true");let S=C("span","persona-approval-logo"),E=Je(Oi.ShieldCheck,16,"currentColor",2);E&&S.appendChild(E),A.appendChild(S);let k=$W(o,r);if(g){let P=C("span","persona-approval-toggle");P.setAttribute("aria-hidden","true");let v=Je(Oi.ChevronDown,14,"currentColor",2);v&&P.appendChild(v),k.append(" "),k.appendChild(P)}A.appendChild(k),d.appendChild(A);let D=C("div","persona-approval-body");if(g){let P=C("div","persona-approval-details");if(P.setAttribute("data-role","params"),P.hidden=!h,f){let v=C("p","persona-approval-desc");r?.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=o.description,P.appendChild(v)}if(m){let v=C("pre","persona-approval-params");r?.parameterBackgroundColor&&(v.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(v.style.color=r.parameterTextColor),v.textContent=tr(o.parameters),P.appendChild(v)}D.appendChild(P)}if(c){let P=C("div","persona-approval-call");P.setAttribute("data-role","raw-call");let v=C("code","persona-approval-tool-name");if(v.textContent=o.toolName,P.appendChild(v),o.parameters!=null){let w=C("pre","persona-approval-params");r?.parameterBackgroundColor&&(w.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(w.style.color=r.parameterTextColor),w.textContent=tr(o.parameters),P.appendChild(w)}D.appendChild(P)}if(o.reason){let P=C("p","persona-approval-reason");r?.reasonColor?P.style.color=r.reasonColor:r?.descriptionColor&&(P.style.color=r.descriptionColor);let v=C("span","persona-approval-reason-label");v.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,P.append(v,document.createTextNode(o.reason)),D.appendChild(P)}let $=C("div","persona-approval-actions"),J=null,T=P=>{r?.approveButtonColor&&(P.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(P.style.color=r.approveButtonTextColor)},W=C("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r?.denyButtonColor&&(W.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append(r?.denyLabel??"Deny"),l){let P=C("div","persona-approval-split"),v=C("button","persona-approval-primary");v.type="button",v.setAttribute("data-action","always"),T(v),v.append(r?.approveLabel??"Always allow",ey("\u23CE"));let w=C("button","persona-approval-caret");w.type="button",w.setAttribute("data-action","toggle-menu"),w.setAttribute("aria-label","More options"),T(w);let L=Je(Oi.ChevronDown,15,"currentColor",2);L&&w.appendChild(L),P.append(v,w),$.append(P,W),W.append(ey("Esc"));let I=C("div","persona-approval-menu"),Y=C("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",ey("\u2318\u23CE")),I.appendChild(Y),J=Bs({anchor:P,content:I,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(n.id,J),Y.addEventListener("click",()=>{Di(e,n.id),s()})}else{let P=C("button","persona-approval-primary persona-approval-primary--solo");P.type="button",P.setAttribute("data-action","allow"),T(P),P.append(r?.approveLabel??"Allow"),$.append(P,W)}return D.appendChild($),d.appendChild(D),d.addEventListener("click",P=>{let v=P.target instanceof Element?P.target.closest("[data-action]"):null;if(!v)return;let w=v.getAttribute("data-action");if(w==="toggle-params"){let L=d.querySelector('[data-role="params"]');if(L){let I=L.hidden;L.hidden=!I,A.setAttribute("aria-expanded",I?"true":"false"),A.setAttribute("aria-label",I?x:b),t.set(n.id,I)}return}if(w==="toggle-menu"){J?.toggle();return}if(w==="always"){Di(e,n.id),s({remember:!0});return}if(w==="allow"){Di(e,n.id),s();return}if(w==="deny"){Di(e,n.id),i();return}}),d},ty=(e=new Map)=>{let t=NW();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:i,config:l})=>{let c=r?.approval;if(!c)return null;let d=FW(l);if(c.status!=="pending"){if(Di(t,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return UW(c)}jM(t,r.id);let p=!!l?.clientToken,f=d?.enableAlwaysAllow===!0,m=zW(t,e,r,c,d,s,i,f,p);if(f){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=h=>{Mx(h)||r.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Di(t,r.id),h.key==="Escape"?i():h.metaKey||h.ctrlKey?s():s({remember:!0})))};t.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Di(t,r);t.latestPendingApprovalId=null}}}});var GM=ie(()=>{"use strict";Zh();KM();ju()});var YM={};En(YM,{createApprovalBubble:()=>Jh,createBuiltInApprovalPlugin:()=>ty,humanizeToolName:()=>Bi,initApprovalUi:()=>Xh,updateApprovalDetailsUI:()=>Qh});var XM=ie(()=>{"use strict";GM()});function za(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}function ZM(e,t){if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n]}function XW(e,t){return(t&&ZM(e,t))??ZM(e,es)??KW}function QW(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function JW(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ZW(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function eB(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function tB(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function nB(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function oB(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function rB(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function sB(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=C("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=C("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function ny(e,t,n,o,r,s,i,l){let c=r.has(e.id),d=C("div","persona-border-b persona-border-persona-divider persona-text-xs");za(d,o.classNames?.eventRow);let p=i.find(m=>m.renderEventStreamRow);if(p?.renderEventStreamRow&&l){let m=p.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>s(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(f()),d;function f(){let m=C("div",""),g=C("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let h=C("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=Je(c?qn.ChevronDown:qn.ChevronRight,"14px","currentColor",2);b&&h.appendChild(b);let x=C("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=o.timestampFormat??"relative";x.textContent=A==="relative"?JW(e.timestamp,n):ZW(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=C("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let E=XW(e.type,o.badgeColors),k=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=QW(E.text),k.textContent=e.type;let D=o.descriptionFields??GW,$=eB(e.payload,D),J=null;$&&(J=C("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),J.textContent=$);let T=C("div","persona-flex-1 persona-min-w-0"),W=C("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),P=Je(qn.Clipboard,"12px","currentColor",1.5);return P&&W.appendChild(P),W.addEventListener("click",async v=>{v.stopPropagation(),await tB(nB(e)),W.innerHTML="";let w=Je(qn.Check,"12px","currentColor",1.5);w&&W.appendChild(w),setTimeout(()=>{W.innerHTML="";let L=Je(qn.Clipboard,"12px","currentColor",1.5);L&&W.appendChild(L)},1500)}),g.appendChild(h),g.appendChild(x),S&&g.appendChild(S),g.appendChild(k),J&&g.appendChild(J),g.appendChild(T),g.appendChild(W),m.appendChild(g),c&&m.appendChild(sB(e,i,l)),m}}function oy(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=e,l=e.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,d=c?.enabled!==!1,p=c?.iconName??"arrow-down",f=c?.label??"",m=r?.features?.eventStream??{},g=s.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>h().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return h();function h(){let b=m.classNames,x=C("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");za(x,b?.panel);let A=[],S="",E="",k=null,D=[],$={},J=0,T=ku(),W=0,P=0,v=!1,w=null,L=!1,I=0,Y=new Set,_=new Map,q="",Z="",ne=null,te,re,pe,xe,Se=null,se=null,N=null;function Ee(){let Te=C("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ie=C("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(za(Ie,b?.headerBar),i){se=C("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),se.style.cursor="help",Se=C("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Se.textContent="-- tok/s",N=C("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),N.style.display="none",N.style.pointerEvents="none";let gn=se,Zn=N,ss=()=>{if(!Zn.textContent)return;let qs=gn.getBoundingClientRect(),no=Te.getBoundingClientRect();Zn.style.left=`${qs.left-no.left}px`,Zn.style.top=`${qs.bottom-no.top+4}px`,Zn.style.display="block"},jn=()=>{Zn.style.display="none"};se.addEventListener("mouseenter",ss),se.addEventListener("mouseleave",jn),se.appendChild(Se)}let je=C("div","persona-flex-1");te=C("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let It=C("option","");It.value="",It.textContent="All events (0)",te.appendChild(It),re=C("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),re.type="button",re.title="Copy All";let nn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);nn&&re.appendChild(nn);let _t=C("span","persona-event-copy-all persona-text-xs");_t.textContent="Copy All",re.appendChild(_t),se&&Ie.appendChild(se),Ie.appendChild(je),Ie.appendChild(te),Ie.appendChild(re);let ft=C("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");za(ft,b?.searchBar);let Ht=Je(qn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Ct=C("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ht&&Ct.appendChild(Ht),pe=C("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),za(pe,b?.searchInput),pe.type="text",pe.placeholder="Search event payloads...",xe=C("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),xe.type="button",xe.style.display="none";let Kt=Je(qn.X,"12px","currentColor",2);return Kt&&xe.appendChild(Kt),ft.appendChild(Ct),ft.appendChild(pe),ft.appendChild(xe),Te.appendChild(Ie),Te.appendChild(ft),N&&Te.appendChild(N),Te}let de,Ge=s.find(Te=>Te.renderEventStreamToolbar);Ge?.renderEventStreamToolbar&&r?de=Ge.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ee(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Ie=>{S=Ie,X(),Le()},onSearchChange:Ie=>{E=Ie,X(),Le()}})??Ee():de=Ee();let Pt=C("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Pt.style.display="none";function St(){if(!i||!Se||!se)return;let Te=i(),Ie=oB(Te);Se.textContent=Ie;let je=rB(Te);N&&(N.textContent=je,je||(N.style.display="none")),se.setAttribute("aria-label",je?`Throughput: ${Ie}, ${je}`:`Throughput: ${Ie}`)}let ut=C("div","persona-flex-1 persona-min-h-0 persona-relative"),tt=C("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");tt.style.height="100%";let gt=C("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");za(gt,b?.scrollIndicator),gt.style.display="none",gt.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let Pe=l(p,"14px","currentColor",2);Pe&&gt.appendChild(Pe);let Fe=C("span","");Fe.textContent=f,gt.appendChild(Fe);let j=C("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");j.style.display="none",ut.appendChild(tt),ut.appendChild(j),ut.appendChild(gt),x.setAttribute("tabindex","0"),x.appendChild(de),x.appendChild(Pt),x.appendChild(ut);function R(){let Te=t.getAll(),Ie={};for(let ft of Te)Ie[ft.type]=(Ie[ft.type]||0)+1;let je=Object.keys(Ie).sort(),It=je.length!==D.length||!je.every((ft,Ht)=>ft===D[Ht]),wn=!It&&je.some(ft=>Ie[ft]!==$[ft]),nn=Te.length!==Object.values($).reduce((ft,Ht)=>ft+Ht,0);if(!It&&!wn&&!nn||(D=je,$=Ie,!te))return;let _t=te.value;if(te.options[0].textContent=`All events (${Te.length})`,It){for(;te.options.length>1;)te.remove(1);for(let ft of je){let Ht=C("option","");Ht.value=ft,Ht.textContent=`${ft} (${Ie[ft]||0})`,te.appendChild(Ht)}_t&&je.includes(_t)?te.value=_t:_t&&(te.value="",S="")}else for(let ft=1;ft<te.options.length;ft++){let Ht=te.options[ft];Ht.textContent=`${Ht.value} (${Ie[Ht.value]||0})`}}function K(){let Te=t.getAll();if(S&&(Te=Te.filter(Ie=>Ie.type===S)),E){let Ie=E.toLowerCase();Te=Te.filter(je=>je.type.toLowerCase().includes(Ie)||je.payload.toLowerCase().includes(Ie))}return Te}function ee(){return S!==""||E!==""}function X(){J=0,W=0,T.resume(),gt.style.display="none"}function le(Te){Y.has(Te)?Y.delete(Te):Y.add(Te),ne=Te;let Ie=tt.scrollTop,je=T.isFollowing();L=!0,T.pause(),Le(),tt.scrollTop=Ie,je&&T.resume(),L=!1}function Me(){return Zr(tt,50)}function Le(){P=Date.now(),v=!1,St(),R();let Te=t.getEvictedCount();Te>0?(Pt.textContent=`${Te.toLocaleString()} older events truncated`,Pt.style.display=""):Pt.style.display="none",A=K();let Ie=A.length,je=t.getSize()>0;Ie===0&&je&&ee()?(j.textContent=E?`No events matching '${E}'`:"No events matching filter",j.style.display="",tt.style.display="none"):(j.style.display="none",tt.style.display=""),re&&(re.title=ee()?`Copy Filtered (${Ie})`:"Copy All"),d&&!T.isFollowing()&&Ie>J&&(W+=Ie-J,Fe.textContent=f?`${f}${W>0?` (${W})`:""}`:"",gt.style.display=""),J=Ie;let It=t.getAll(),wn=It.length>0?It[0].timestamp:0,nn=new Set(A.map(Ht=>Ht.id));for(let Ht of Y)nn.has(Ht)||Y.delete(Ht);let _t=S!==q||E!==Z,ft=_.size===0&&A.length>0;if(_t||ft||A.length===0){tt.innerHTML="",_.clear();let Ht=document.createDocumentFragment();for(let Ct=0;Ct<A.length;Ct++){let Kt=ny(A[Ct],Ct,wn,m,Y,le,s,r);_.set(A[Ct].id,Kt),Ht.appendChild(Kt)}tt.appendChild(Ht),q=S,Z=E,ne=null}else{if(ne!==null){let Ct=_.get(ne);if(Ct&&Ct.parentNode===tt){let Kt=A.findIndex(gn=>gn.id===ne);if(Kt>=0){let gn=ny(A[Kt],Kt,wn,m,Y,le,s,r);tt.insertBefore(gn,Ct),Ct.remove(),_.set(ne,gn)}}ne=null}let Ht=new Set(A.map(Ct=>Ct.id));for(let[Ct,Kt]of _)Ht.has(Ct)||(Kt.remove(),_.delete(Ct));for(let Ct=0;Ct<A.length;Ct++){let Kt=A[Ct];if(!_.has(Kt.id)){let gn=ny(Kt,Ct,wn,m,Y,le,s,r);_.set(Kt.id,gn),tt.appendChild(gn)}}}T.isFollowing()&&(tt.scrollTop=tt.scrollHeight)}function Ne(){if(Date.now()-P>=YW){w!==null&&(cancelAnimationFrame(w),w=null),Le();return}v||(v=!0,w=requestAnimationFrame(()=>{w=null,Le()}))}let lt=(Te,Ie)=>{if(!re)return;re.innerHTML="";let je=Je(Te,"12px","currentColor",1.5);je&&re.appendChild(je);let It=C("span","persona-text-xs");It.textContent="Copy All",re.appendChild(It),setTimeout(()=>{re.innerHTML="";let wn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);wn&&re.appendChild(wn);let nn=C("span","persona-text-xs");nn.textContent="Copy All",re.appendChild(nn),re.disabled=!1},Ie)},At=async()=>{if(re){re.disabled=!0;try{let Te;ee()?Te=A:n?(Te=await n(),Te.length===0&&(Te=t.getAll())):Te=t.getAll();let Ie=Te.map(je=>{try{return JSON.parse(je.payload)}catch{return je.payload}});await navigator.clipboard.writeText(JSON.stringify(Ie,null,2)),lt(qn.Check,1500)}catch{lt(qn.X,1500)}}},qe=()=>{te&&(S=te.value,X(),Le())},nt=()=>{!pe||!xe||(xe.style.display=pe.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{E=pe.value,X(),Le()},150))},Ut=()=>{!pe||!xe||(pe.value="",E="",xe.style.display="none",k&&clearTimeout(k),X(),Le())},tn=()=>{if(L)return;let Te=tt.scrollTop,{action:Ie,nextLastScrollTop:je}=Lu({following:T.isFollowing(),currentScrollTop:Te,lastScrollTop:I,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});I=je,Ie==="resume"?(T.resume(),W=0,gt.style.display="none"):Ie==="pause"&&(T.pause(),d&&(Fe.textContent=f,gt.style.display=""))},Q=Te=>{let Ie=Pu({following:T.isFollowing(),deltaY:Te.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Ie==="pause"?(T.pause(),d&&(Fe.textContent=f,gt.style.display="")):Ie==="resume"&&(T.resume(),W=0,gt.style.display="none")},He=()=>{d&&(tt.scrollTop=tt.scrollHeight,T.resume(),W=0,gt.style.display="none")},_e=Te=>{let Ie=Te.target;if(!Ie||Ie.closest("button"))return;let je=Ie.closest("[data-event-id]");if(!je)return;let It=je.getAttribute("data-event-id");It&&le(It)},ht=Te=>{if((Te.metaKey||Te.ctrlKey)&&Te.key==="f"){Te.preventDefault(),pe?.focus(),pe?.select();return}Te.key==="Escape"&&(pe&&document.activeElement===pe?(Ut(),pe.blur(),x.focus()):o&&o())};re&&re.addEventListener("click",At),te&&te.addEventListener("change",qe),pe&&pe.addEventListener("input",nt),xe&&xe.addEventListener("click",Ut),tt.addEventListener("scroll",tn),tt.addEventListener("wheel",Q,{passive:!0}),tt.addEventListener("click",_e),gt.addEventListener("click",He),x.addEventListener("keydown",ht);function yt(){k&&clearTimeout(k),w!==null&&(cancelAnimationFrame(w),w=null),v=!1,_.clear(),re&&re.removeEventListener("click",At),te&&te.removeEventListener("change",qe),pe&&pe.removeEventListener("input",nt),xe&&xe.removeEventListener("click",Ut),tt.removeEventListener("scroll",tn),tt.removeEventListener("wheel",Q),tt.removeEventListener("click",_e),gt.removeEventListener("click",He),x.removeEventListener("keydown",ht)}return{element:x,update:Ne,destroy:yt}}}var qn,es,KW,GW,YW,eT=ie(()=>{"use strict";Ye();qn=require("lucide");io();bh();es={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};es.execution_error=es.error;es.execution_=es.flow_;es.turn_=es.agent_;es.text_=es.agent_;KW={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},GW=["flowName","stepName","reasoningText","text","name","tool","toolName"],YW=100});var Ec,tT=ie(()=>{"use strict";Ec=class{#e;#t=0;#n=0;#o=0;#c=new Set;#r;#s;constructor(t=2e3,n=null){this.#r=t,this.#e=new Array(t),this.#s=n}push(t){this.#e[this.#t]=t,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#o++,this.#c.add(t.type),this.#s?.put(t)}getAll(){return this.#n===0?[]:this.#n<this.#r?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#r),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#s)return 0;let t=await this.#s.getAll();if(t.length===0)return 0;let n=t.length>this.#r?t.slice(t.length-this.#r):t;for(let o of n)this.#e[this.#t]=o,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#c.add(o.type);return this.#o=t.length,n.length}getAllFromStore(){return this.#s?this.#s.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.#n}getTotalCaptured(){return this.#o}getEvictedCount(){return this.#o-this.#n}clear(){this.#e=new Array(this.#r),this.#t=0,this.#n=0,this.#o=0,this.#c.clear(),this.#s?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#o=0,this.#c.clear(),this.#s?.destroy()}getEventTypes(){return Array.from(this.#c)}}});var kc,nT=ie(()=>{"use strict";kc=class{#e=null;#t=[];#n=!1;#o=!1;#c;#r;constructor(t="persona-event-stream",n="events"){this.#c=t,this.#r=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.#c,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.#r)||r.createObjectStore(this.#r,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.#e=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.#e||this.#o||(this.#t.push(t),this.#n||(this.#n=!0,queueMicrotask(()=>this.#s())))}putBatch(t){if(!(!this.#e||this.#o||t.length===0))try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.#e){t([]);return}try{let i=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.#e){t(0);return}try{let s=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.#e){t();return}this.#t=[];try{let s=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.#e&&(this.#e.close(),this.#e=null)}destroy(){return this.#o=!0,this.#t=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.#c);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}#s(){if(this.#n=!1,!this.#e||this.#o||this.#t.length===0)return;let t=this.#t;this.#t=[];try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}}});function ry(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ku(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function lB(e,t){return typeof t.type=="string"?t.type:e}function rT(e){let t=oT(e,"tokens")??oT(e,"totalTokens");return t?iT(t.output):void 0}function cB(e){return iT(e.durationMs)}function dB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var iB,aB,sT,iT,oT,Lc,aT=ie(()=>{"use strict";iB=new Set(["step_start","turn_start"]),aB=new Set(["step_complete","turn_complete"]),sT=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iT=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,oT=(e,t)=>{let n=e[t];return sT(n)?n:void 0};Lc=class{#e={status:"idle"};#t=null;constructor(t=dB){this.now=t}getMetric(){let t=this.#t;if(t&&this.#e.status==="running"&&t.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.#e,durationMs:n,tokensPerSecond:Ku(this.#e.outputTokens,n)}}return this.#e}reset(){this.#t=null,this.#e={status:"idle"}}#n(t){this.#t={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.#e={status:"running"}}processEvent(t,n){if(!sT(n)){t==="execution_error"&&this.#t&&(this.#t=null,this.#e={status:"error"});return}let o=lB(t,n),r=this.now();if(o==="execution_start"){this.#n(r);return}if(iB.has(o)){this.#t||this.#n(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.#t||this.#n(r);let i=this.#t;i.firstDeltaAt??=r,i.visibleCharCount+=s.length;let l=i.exactOutputTokens+ry(i.visibleCharCount),c=r-i.firstDeltaAt;this.#e={status:"running",tokensPerSecond:Ku(l,c),outputTokens:l,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(aB.has(o)){if(!this.#t)return;let s=this.#t,i=rT(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+ry(s.visibleCharCount),d=this.#o(s,n,r);this.#e={status:"running",tokensPerSecond:Ku(c,d),outputTokens:c,durationMs:d,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.#t)return;let s=this.#t,i=rT(n),l=i??s.exactOutputTokens+ry(s.visibleCharCount),c=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.#o(s,n,r);this.#e={status:"complete",tokensPerSecond:Ku(l,d),outputTokens:l,durationMs:d,source:c},this.#t=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:"error"}}}#o(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:cB(n)??o-t.startedAt}}});var lT=ie(()=>{"use strict";eT();tT();nT();aT()});var cT={};En(cT,{EventStreamBuffer:()=>Ec,EventStreamStore:()=>kc,ThroughputTracker:()=>Lc,createEventStreamView:()=>oy});var dT=ie(()=>{"use strict";lT()});var iy,sr,Pc=ie(()=>{"use strict";iy=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},sr=new iy});function Sr(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function pT(e){let t=Sr(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Gu(e){if(typeof e!="string")return"";let t=e.indexOf(`
258
+ `.trim(),yc="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",TR=10,ER=120,xh=120,kR=.4,LR=50,PR=e=>{if(!e)return xh;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):xh},ZA=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=PR(t);return ER*n/xh},Sh=e=>{let t=yc[Math.floor(Math.random()*yc.length)];return e&&t===e&&(t=yc[(yc.indexOf(t)+1)%yc.length]),t},IR=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<kR&&(r.textContent=Sh())}},jA=new WeakMap,KA=25,GA=.5,HR=6,YA=.25,XA=new WeakMap,QA=new WeakMap,RR=(e,t)=>{if(!e)return KA*GA;let n=XA.get(e);XA.set(e,t);let o=QA.get(e)??KA;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-YA)+r*YA,QA.set(e,o))}return Math.max(HR,o*GA)},_a=new Map,WR=e=>e.closest("[data-message-id]")?.dataset.messageId??null,BR=e=>{e&&_a.set(e,(_a.get(e)??0)+1)},DR=e=>{if(!e)return;let t=_a.get(e)??0;t<=1?_a.delete(e):_a.set(e,t-1)},eM=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Sh();let n=WR(e);n&&(e.dataset.glyphCycleMessageId=n),BR(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),s=RR(o,r),i=ZA(e),l=TR*i,c=r+l;if(o){let d=jA.get(o);d!==void 0&&(c=Math.max(c,d)),jA.set(o,c+s)}OR(e,t,c)},OR=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=ZA(e),r=e.textContent??void 0,s=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,DR(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let i=Sh(r);e.textContent=i,r=i,IR(e),setTimeout(s,o)};setTimeout(s,o)},JA=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))eM(n)},_R=e=>e.nodeType===1,tM={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:MR,bufferContent(e){if(e.length<LR)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(_a.get(e.id)??0)>0},onAttach(e){JA(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))_R(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?eM(r):JA(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};Pi(tM);nM=tM});var rM={};En(rM,{glyphCycle:()=>nM,wipe:()=>zA});var sM=ie(()=>{"use strict";qA();oM()});function Sc(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=C("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(Ta)):(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 h of t){if(h.dividerBefore){let A=document.createElement("hr");l.appendChild(A)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",h.id),h.destructive&&b.setAttribute("data-destructive",""),h.icon){let A=Re(h.icon,16,"currentColor",1.5);A&&b.appendChild(A)}let x=document.createElement("span");x.textContent=h.label,b.appendChild(x),b.addEventListener("click",A=>{A.stopPropagation(),f(),n(h.id)}),l.appendChild(b)}let c=null;function d(){if(!s)return;let h=o.getBoundingClientRect();l.style.top=`${h.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-h.right}px`,l.style.left="auto"):(l.style.left=`${h.left}px`,l.style.right="auto")}function p(){let h=l.classList.contains("persona-hidden");d(),l.classList.remove("persona-hidden"),h&&i?.(!0),requestAnimationFrame(()=>{let b=x=>{!l.contains(x.target)&&!o.contains(x.target)&&f()};document.addEventListener("click",b,!0),c=()=>document.removeEventListener("click",b,!0)})}function f(){let h=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),c?.(),c=null,h&&i?.(!1)}function m(){l.classList.contains("persona-hidden")?p():f()}function g(){f(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:f,toggle:m,destroy:g}}var Ph=ie(()=>{"use strict";Ye();ln();nr()});function Ln(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,chromeless:i,onClick:l,aria:c}=e,d=C("button",Jt(!i&&"persona-icon-btn",s));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=Re(t,o??16,"currentColor",r??2);if(p&&d.appendChild(p),l&&d.addEventListener("click",l),c)for(let[f,m]of Object.entries(c))d.setAttribute(f,m);return d}function Hi(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,i&&(d+=" "+i);let p=C("button",d);if(p.type="button",p.setAttribute("aria-label",n),t){let m=Re(t,s??14,"currentColor",2);m&&p.appendChild(m)}let f=C("span");if(f.textContent=n,p.appendChild(f),l&&p.addEventListener("click",l),c)for(let[m,g]of Object.entries(c))p.setAttribute(m,g);return p}function Bu(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=C("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function c(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let f;p.icon?f=Ln({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,c(),o(p.id)}}):(f=C("button","persona-icon-btn"+(p.className?" "+p.className:"")),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{i=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:f}),s.appendChild(f)}function d(p){i=p,c()}return{element:s,setSelected:d}}function dM(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:c="bottom-left",portal:d,chevronLabel:p="More options",chevronIconSize:f,className:m,primaryClassName:g,chevronClassName:h}=e,b=C("div","persona-split-btn"+(m?" "+m:"")),x={label:t,className:"persona-split-btn-primary"+(g?" "+g:""),onClick:l},A=r&&n?Ln({...x,icon:n,size:o??14}):Hi({...x,icon:n,iconSize:o??14}),S=Ln({icon:"chevron-down",label:p,size:f??14,className:"persona-split-btn-chevron"+(h?" "+h:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});b.append(A,S);let E=null,k=()=>{if(E)return E;let D=(typeof d=="function"?d():d)??void 0;return E=Sc({items:s,onSelect:i,anchor:b,position:c,portal:D,onOpenChange:$=>{S.setAttribute("aria-expanded",$?"true":"false")}}),D||b.appendChild(E.element),E};return b.isConnected?k():requestAnimationFrame(()=>{E||k()}),S.addEventListener("click",D=>{D.stopPropagation(),k().toggle()}),{element:b,primaryButton:A,chevronButton:S,openMenu:()=>k().show(),closeMenu:()=>E?.hide(),toggleMenu:()=>k().toggle(),destroy:()=>{E?.destroy(),b.remove()}}}function pM(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:c}=e,d=C("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=C("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let f=Re(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),c&&(d.style.borderRadius=c.borderRadius??"10px",d.style.padding=c.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=c.background??"",d.style.borderColor=c.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let m=Sc({items:o,onSelect:h=>{d.setAttribute("aria-expanded","false"),r(h)},anchor:d,position:s,portal:i});i||d.appendChild(m.element);let g=()=>d.getAttribute("data-persona-menu-locked")==="true";return d.addEventListener("click",h=>{if(h.stopPropagation(),g())return;let b=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),m.toggle()}),d.addEventListener("keydown",h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),d.click())}),{element:d,setLabel:h=>{p.textContent=h,d.setAttribute("aria-label",h)},open:()=>{d.setAttribute("aria-expanded","true"),m.show()},close:()=>{d.setAttribute("aria-expanded","false"),m.hide()},toggle:()=>{let h=!m.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",h?"false":"true"),m.toggle()},destroy:()=>{m.destroy(),d.remove()}}}var Ri=ie(()=>{"use strict";Ye();ln();Ph()});var Fs,zu=ie(()=>{"use strict";Ye();Fs=(e,t,n)=>{let o=n;for(let r of t){let s=C("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o}});var $M,Xh,qu,ju=ie(()=>{"use strict";$M=()=>{},Xh=e=>{$M=e.webMcpToolTitle},qu=e=>$M(e)});var $o,Bi,UM,zM,qM,Qh,Jh,Zh=ie(()=>{"use strict";Ye();Gr();ju();$o=require("lucide");io();Ai();Bi=e=>{let n=(e.startsWith(Kr)?e.slice(Kr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},UM=e=>e?.approval!==!1?e?.approval:void 0,zM=(e,t,n)=>{let o=UM(n)?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},qM=(e,t,n)=>{let o=UM(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=Je(t?$o.ChevronUp:$o.ChevronDown,14,"currentColor",2);i&&s.appendChild(i)}},Qh=(e,t,n,o=new Map)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!r||!s)return;let i=zM(e,o,n);qM(r,i,n),s.style.display=i?"":"none"},Jh=(e,t,n=new Map)=>{let o=e.approval,r=t?.approval!==!1?t?.approval:void 0,s=o?.status==="pending",i=C("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.style.backgroundColor=r?.backgroundColor??"var(--persona-approval-bg)",i.style.borderColor=r?.borderColor??"var(--persona-approval-border)",i.style.boxShadow=r?.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow)",!o)return i;let l=C("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),c=C("div","persona-flex-shrink-0 persona-mt-0.5");c.setAttribute("data-approval-icon","true");let d=o.status==="denied"?$o.ShieldX:o.status==="timeout"?$o.ShieldAlert:$o.ShieldCheck,p=o.status==="approved"?"var(--persona-feedback-success, var(--persona-palette-colors-success-600))":o.status==="denied"?"var(--persona-feedback-error, var(--persona-palette-colors-error-600))":o.status==="timeout"?"var(--persona-feedback-warning, var(--persona-palette-colors-warning-600))":r?.titleColor??"currentColor",f=Je(d,20,p,2);f&&c.appendChild(f);let m=C("div","persona-flex-1 persona-min-w-0"),g=C("div","persona-flex persona-items-center persona-gap-2"),h=C("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r?.titleColor&&(h.style.color=r.titleColor),h.textContent=r?.title??"Approval Required",g.appendChild(h),!s){let T=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");T.setAttribute("data-approval-status",o.status),o.status==="approved"?(T.style.backgroundColor="var(--persona-palette-colors-success-100)",T.style.color="var(--persona-palette-colors-success-700)",T.textContent="Approved"):o.status==="denied"?(T.style.backgroundColor="var(--persona-palette-colors-error-100)",T.style.color="var(--persona-palette-colors-error-700)",T.textContent="Denied"):o.status==="timeout"&&(T.style.backgroundColor="var(--persona-palette-colors-warning-100)",T.style.color="var(--persona-palette-colors-warning-700)",T.textContent="Timeout"),g.appendChild(T)}m.appendChild(g);let x=o.toolType==="webmcp"||o.toolName.startsWith(Kr)?qu(o.toolName):void 0,A=r?.formatDescription?.({toolName:o.toolName,toolType:o.toolType,description:o.description,parameters:o.parameters,...x?{displayTitle:x}:{},...o.reason?{reason:o.reason}:{}}),S=!o.toolName,E=A||(S?o.description:`The assistant wants to use \u201C${x??Bi(o.toolName)}\u201D.`),k=C("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r?.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=E,m.appendChild(k),o.reason){let T=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");T.setAttribute("data-approval-reason","true"),r?.reasonColor?T.style.color=r.reasonColor:r?.descriptionColor&&(T.style.color=r.descriptionColor);let W=C("span","persona-font-medium");W.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,T.appendChild(W),T.appendChild(document.createTextNode(o.reason)),m.appendChild(T)}let D=r?.detailsDisplay??"collapsed",$=!!o.description&&!S,J=$||!!o.parameters;if(D!=="hidden"&&J){let T=zM(e.id,n,t),W=C("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");W.type="button",W.setAttribute("data-expand-header","true"),W.setAttribute("data-bubble-type","approval"),r?.descriptionColor&&(W.style.color=r.descriptionColor);let P=C("span");P.setAttribute("data-approval-details-label","true");let v=C("span","persona-inline-flex persona-items-center");v.setAttribute("data-approval-details-chevron","true"),W.append(P,v),qM(W,T,t),m.appendChild(W);let w=C("div");if(w.setAttribute("data-approval-details","true"),w.style.display=T?"":"none",$){let L=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r?.descriptionColor&&(L.style.color=r.descriptionColor),L.textContent=o.description,w.appendChild(L)}if(o.parameters){let L=C("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r?.parameterBackgroundColor&&(L.style.backgroundColor=r.parameterBackgroundColor),r?.parameterTextColor&&(L.style.color=r.parameterTextColor),L.style.fontSize="0.75rem",L.style.lineHeight="1rem",L.textContent=tr(o.parameters),w.appendChild(L)}m.appendChild(w)}if(s){let T=C("div","persona-flex persona-gap-2 persona-mt-2");T.setAttribute("data-approval-buttons","true");let W=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");W.type="button",W.style.backgroundColor=r?.approveButtonColor??"var(--persona-approval-approve-bg)",W.style.color=r?.approveButtonTextColor??"var(--persona-button-primary-fg)",W.setAttribute("data-approval-action","approve");let P=Je($o.ShieldCheck,14,r?.approveButtonTextColor??"var(--persona-button-primary-fg)",2);P&&(P.style.marginRight="4px",W.appendChild(P));let v=document.createTextNode(r?.approveLabel??"Approve");W.appendChild(v);let w=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");w.type="button",w.style.backgroundColor=r?.denyButtonColor??"transparent",w.style.color=r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",w.style.border=`1px solid ${r?.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200)"}`,w.setAttribute("data-approval-action","deny");let L=Je($o.ShieldX,14,r?.denyButtonTextColor??"var(--persona-feedback-error, var(--persona-palette-colors-error-600))",2);L&&(L.style.marginRight="4px",w.appendChild(L));let I=document.createTextNode(r?.denyLabel??"Deny");w.appendChild(I),T.append(W,w),m.appendChild(T)}return l.append(c,m),i.appendChild(l),i}});var Oi,NW,jM,Di,FW,VW,ey,$W,UW,zW,ty,KM=ie(()=>{"use strict";Ye();ju();Oi=require("lucide");io();Gr();Ai();Ra();Zh();NW=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),jM=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Di=(e,t)=>{jM(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},FW=e=>e?.approval!==!1?e?.approval:void 0,VW=(e,t,n)=>{let o=n?.detailsDisplay??"collapsed";return t.get(e)??o==="expanded"},ey=e=>{let t=C("span","persona-approval-kbd");return t.textContent=e,t},$W=(e,t)=>{let n=C("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Kr)?qu(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let i=r??Bi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=i,n.appendChild(c),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},UW=e=>{let t=C("div","persona-approval-resolved"),n=Je(Oi.Ban,15,"currentColor",2);n&&t.appendChild(n);let o=C("span","persona-approval-resolved-name");return o.textContent=e.toolName?Bi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},zW=(e,t,n,o,r,s,i,l,c=!1)=>{let d=C("div","persona-approval-card persona-shadow-sm");d.id=`bubble-${n.id}`,d.setAttribute("data-message-id",n.id),d.setAttribute("data-bubble-type","approval"),r?.backgroundColor&&(d.style.background=r.backgroundColor),r?.borderColor&&(d.style.borderColor=r.borderColor),r?.shadow!==void 0&&(d.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let p=r?.detailsDisplay??"collapsed",f=!!o.description&&p!=="hidden",m=o.parameters!=null&&p!=="hidden"&&!c,g=f||m,h=g&&VW(n.id,t,r),b=r?.showDetailsLabel??"Show details",x=r?.hideDetailsLabel??"Hide details",A=C("button","persona-approval-head");A.type="button",g?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",h?"true":"false"),A.setAttribute("aria-label",h?x:b)):A.setAttribute("data-static","true");let S=C("span","persona-approval-logo"),E=Je(Oi.ShieldCheck,16,"currentColor",2);E&&S.appendChild(E),A.appendChild(S);let k=$W(o,r);if(g){let P=C("span","persona-approval-toggle");P.setAttribute("aria-hidden","true");let v=Je(Oi.ChevronDown,14,"currentColor",2);v&&P.appendChild(v),k.append(" "),k.appendChild(P)}A.appendChild(k),d.appendChild(A);let D=C("div","persona-approval-body");if(g){let P=C("div","persona-approval-details");if(P.setAttribute("data-role","params"),P.hidden=!h,f){let v=C("p","persona-approval-desc");r?.descriptionColor&&(v.style.color=r.descriptionColor),v.textContent=o.description,P.appendChild(v)}if(m){let v=C("pre","persona-approval-params");r?.parameterBackgroundColor&&(v.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(v.style.color=r.parameterTextColor),v.textContent=tr(o.parameters),P.appendChild(v)}D.appendChild(P)}if(c){let P=C("div","persona-approval-call");P.setAttribute("data-role","raw-call");let v=C("code","persona-approval-tool-name");if(v.textContent=o.toolName,P.appendChild(v),o.parameters!=null){let w=C("pre","persona-approval-params");r?.parameterBackgroundColor&&(w.style.background=r.parameterBackgroundColor),r?.parameterTextColor&&(w.style.color=r.parameterTextColor),w.textContent=tr(o.parameters),P.appendChild(w)}D.appendChild(P)}if(o.reason){let P=C("p","persona-approval-reason");r?.reasonColor?P.style.color=r.reasonColor:r?.descriptionColor&&(P.style.color=r.descriptionColor);let v=C("span","persona-approval-reason-label");v.textContent=`${r?.reasonLabel??"Agent's stated reason:"} `,P.append(v,document.createTextNode(o.reason)),D.appendChild(P)}let $=C("div","persona-approval-actions"),J=null,T=P=>{r?.approveButtonColor&&(P.style.background=r.approveButtonColor),r?.approveButtonTextColor&&(P.style.color=r.approveButtonTextColor)},W=C("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),r?.denyButtonColor&&(W.style.background=r.denyButtonColor),r?.denyButtonTextColor&&(W.style.color=r.denyButtonTextColor),W.append(r?.denyLabel??"Deny"),l){let P=C("div","persona-approval-split"),v=C("button","persona-approval-primary");v.type="button",v.setAttribute("data-action","always"),T(v),v.append(r?.approveLabel??"Always allow",ey("\u23CE"));let w=C("button","persona-approval-caret");w.type="button",w.setAttribute("data-action","toggle-menu"),w.setAttribute("aria-label","More options"),T(w);let L=Je(Oi.ChevronDown,15,"currentColor",2);L&&w.appendChild(L),P.append(v,w),$.append(P,W),W.append(ey("Esc"));let I=C("div","persona-approval-menu"),Y=C("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",ey("\u2318\u23CE")),I.appendChild(Y),J=Bs({anchor:P,content:I,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(n.id,J),Y.addEventListener("click",()=>{Di(e,n.id),s()})}else{let P=C("button","persona-approval-primary persona-approval-primary--solo");P.type="button",P.setAttribute("data-action","allow"),T(P),P.append(r?.approveLabel??"Allow"),$.append(P,W)}return D.appendChild($),d.appendChild(D),d.addEventListener("click",P=>{let v=P.target instanceof Element?P.target.closest("[data-action]"):null;if(!v)return;let w=v.getAttribute("data-action");if(w==="toggle-params"){let L=d.querySelector('[data-role="params"]');if(L){let I=L.hidden;L.hidden=!I,A.setAttribute("aria-expanded",I?"true":"false"),A.setAttribute("aria-label",I?x:b),t.set(n.id,I)}return}if(w==="toggle-menu"){J?.toggle();return}if(w==="always"){Di(e,n.id),s({remember:!0});return}if(w==="allow"){Di(e,n.id),s();return}if(w==="deny"){Di(e,n.id),i();return}}),d},ty=(e=new Map)=>{let t=NW();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:s,deny:i,config:l})=>{let c=r?.approval;if(!c)return null;let d=FW(l);if(c.status!=="pending"){if(Di(t,r.id),c.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return UW(c)}jM(t,r.id);let p=!!l?.clientToken,f=d?.enableAlwaysAllow===!0,m=zW(t,e,r,c,d,s,i,f,p);if(f){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=h=>{Mx(h)||r.id===t.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Di(t,r.id),h.key==="Escape"?i():h.metaKey||h.ctrlKey?s():s({remember:!0})))};t.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return m}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Di(t,r);t.latestPendingApprovalId=null}}}});var GM=ie(()=>{"use strict";Zh();KM();ju()});var YM={};En(YM,{createApprovalBubble:()=>Jh,createBuiltInApprovalPlugin:()=>ty,humanizeToolName:()=>Bi,initApprovalUi:()=>Xh,updateApprovalDetailsUI:()=>Qh});var XM=ie(()=>{"use strict";GM()});function za(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}function ZM(e,t){if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n]}function XW(e,t){return(t&&ZM(e,t))??ZM(e,es)??KW}function QW(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function JW(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ZW(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function eB(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function tB(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function nB(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function oB(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function rB(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function sB(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=C("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=C("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,l.appendChild(c),l}}function ny(e,t,n,o,r,s,i,l){let c=r.has(e.id),d=C("div","persona-border-b persona-border-persona-divider persona-text-xs");za(d,o.classNames?.eventRow);let p=i.find(m=>m.renderEventStreamRow);if(p?.renderEventStreamRow&&l){let m=p.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>s(e.id)});if(m)return d.appendChild(m),d}return d.appendChild(f()),d;function f(){let m=C("div",""),g=C("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let h=C("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=Je(c?qn.ChevronDown:qn.ChevronRight,"14px","currentColor",2);b&&h.appendChild(b);let x=C("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=o.timestampFormat??"relative";x.textContent=A==="relative"?JW(e.timestamp,n):ZW(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=C("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let E=XW(e.type,o.badgeColors),k=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=QW(E.text),k.textContent=e.type;let D=o.descriptionFields??GW,$=eB(e.payload,D),J=null;$&&(J=C("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),J.textContent=$);let T=C("div","persona-flex-1 persona-min-w-0"),W=C("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),P=Je(qn.Clipboard,"12px","currentColor",1.5);return P&&W.appendChild(P),W.addEventListener("click",async v=>{v.stopPropagation(),await tB(nB(e)),W.innerHTML="";let w=Je(qn.Check,"12px","currentColor",1.5);w&&W.appendChild(w),setTimeout(()=>{W.innerHTML="";let L=Je(qn.Clipboard,"12px","currentColor",1.5);L&&W.appendChild(L)},1500)}),g.appendChild(h),g.appendChild(x),S&&g.appendChild(S),g.appendChild(k),J&&g.appendChild(J),g.appendChild(T),g.appendChild(W),m.appendChild(g),c&&m.appendChild(sB(e,i,l)),m}}function oy(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=e,l=e.renderIconByName??(()=>null),c=r?.features?.scrollToBottom,d=c?.enabled!==!1,p=c?.iconName??"arrow-down",f=c?.label??"",m=r?.features?.eventStream??{},g=s.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>h().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return h();function h(){let b=m.classNames,x=C("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");za(x,b?.panel);let A=[],S="",E="",k=null,D=[],$={},J=0,T=ku(),W=0,P=0,v=!1,w=null,L=!1,I=0,Y=new Set,_=new Map,q="",Z="",ne=null,te,re,pe,xe,Se=null,se=null,N=null;function Ee(){let Te=C("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Ie=C("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(za(Ie,b?.headerBar),i){se=C("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),se.style.cursor="help",Se=C("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Se.textContent="-- tok/s",N=C("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),N.style.display="none",N.style.pointerEvents="none";let gn=se,Zn=N,ss=()=>{if(!Zn.textContent)return;let qs=gn.getBoundingClientRect(),no=Te.getBoundingClientRect();Zn.style.left=`${qs.left-no.left}px`,Zn.style.top=`${qs.bottom-no.top+4}px`,Zn.style.display="block"},jn=()=>{Zn.style.display="none"};se.addEventListener("mouseenter",ss),se.addEventListener("mouseleave",jn),se.appendChild(Se)}let je=C("div","persona-flex-1");te=C("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let It=C("option","");It.value="",It.textContent="All events (0)",te.appendChild(It),re=C("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),re.type="button",re.title="Copy All";let nn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);nn&&re.appendChild(nn);let _t=C("span","persona-event-copy-all persona-text-xs");_t.textContent="Copy All",re.appendChild(_t),se&&Ie.appendChild(se),Ie.appendChild(je),Ie.appendChild(te),Ie.appendChild(re);let ft=C("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");za(ft,b?.searchBar);let Ht=Je(qn.Search,"14px","var(--persona-muted, #9ca3af)",1.5),Ct=C("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ht&&Ct.appendChild(Ht),pe=C("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),za(pe,b?.searchInput),pe.type="text",pe.placeholder="Search event payloads...",xe=C("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),xe.type="button",xe.style.display="none";let Kt=Je(qn.X,"12px","currentColor",2);return Kt&&xe.appendChild(Kt),ft.appendChild(Ct),ft.appendChild(pe),ft.appendChild(xe),Te.appendChild(Ie),Te.appendChild(ft),N&&Te.appendChild(N),Te}let de,Ge=s.find(Te=>Te.renderEventStreamToolbar);Ge?.renderEventStreamToolbar&&r?de=Ge.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ee(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Ie=>{S=Ie,X(),Le()},onSearchChange:Ie=>{E=Ie,X(),Le()}})??Ee():de=Ee();let Pt=C("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Pt.style.display="none";function St(){if(!i||!Se||!se)return;let Te=i(),Ie=oB(Te);Se.textContent=Ie;let je=rB(Te);N&&(N.textContent=je,je||(N.style.display="none")),se.setAttribute("aria-label",je?`Throughput: ${Ie}, ${je}`:`Throughput: ${Ie}`)}let ut=C("div","persona-flex-1 persona-min-h-0 persona-relative"),tt=C("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");tt.style.height="100%";let gt=C("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");za(gt,b?.scrollIndicator),gt.style.display="none",gt.setAttribute("data-persona-scroll-to-bottom-has-label",f?"true":"false");let Pe=l(p,"14px","currentColor",2);Pe&&gt.appendChild(Pe);let Fe=C("span","");Fe.textContent=f,gt.appendChild(Fe);let j=C("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");j.style.display="none",ut.appendChild(tt),ut.appendChild(j),ut.appendChild(gt),x.setAttribute("tabindex","0"),x.appendChild(de),x.appendChild(Pt),x.appendChild(ut);function R(){let Te=t.getAll(),Ie={};for(let ft of Te)Ie[ft.type]=(Ie[ft.type]||0)+1;let je=Object.keys(Ie).sort(),It=je.length!==D.length||!je.every((ft,Ht)=>ft===D[Ht]),wn=!It&&je.some(ft=>Ie[ft]!==$[ft]),nn=Te.length!==Object.values($).reduce((ft,Ht)=>ft+Ht,0);if(!It&&!wn&&!nn||(D=je,$=Ie,!te))return;let _t=te.value;if(te.options[0].textContent=`All events (${Te.length})`,It){for(;te.options.length>1;)te.remove(1);for(let ft of je){let Ht=C("option","");Ht.value=ft,Ht.textContent=`${ft} (${Ie[ft]||0})`,te.appendChild(Ht)}_t&&je.includes(_t)?te.value=_t:_t&&(te.value="",S="")}else for(let ft=1;ft<te.options.length;ft++){let Ht=te.options[ft];Ht.textContent=`${Ht.value} (${Ie[Ht.value]||0})`}}function K(){let Te=t.getAll();if(S&&(Te=Te.filter(Ie=>Ie.type===S)),E){let Ie=E.toLowerCase();Te=Te.filter(je=>je.type.toLowerCase().includes(Ie)||je.payload.toLowerCase().includes(Ie))}return Te}function ee(){return S!==""||E!==""}function X(){J=0,W=0,T.resume(),gt.style.display="none"}function le(Te){Y.has(Te)?Y.delete(Te):Y.add(Te),ne=Te;let Ie=tt.scrollTop,je=T.isFollowing();L=!0,T.pause(),Le(),tt.scrollTop=Ie,je&&T.resume(),L=!1}function Me(){return Zr(tt,50)}function Le(){P=Date.now(),v=!1,St(),R();let Te=t.getEvictedCount();Te>0?(Pt.textContent=`${Te.toLocaleString()} older events truncated`,Pt.style.display=""):Pt.style.display="none",A=K();let Ie=A.length,je=t.getSize()>0;Ie===0&&je&&ee()?(j.textContent=E?`No events matching '${E}'`:"No events matching filter",j.style.display="",tt.style.display="none"):(j.style.display="none",tt.style.display=""),re&&(re.title=ee()?`Copy Filtered (${Ie})`:"Copy All"),d&&!T.isFollowing()&&Ie>J&&(W+=Ie-J,Fe.textContent=f?`${f}${W>0?` (${W})`:""}`:"",gt.style.display=""),J=Ie;let It=t.getAll(),wn=It.length>0?It[0].timestamp:0,nn=new Set(A.map(Ht=>Ht.id));for(let Ht of Y)nn.has(Ht)||Y.delete(Ht);let _t=S!==q||E!==Z,ft=_.size===0&&A.length>0;if(_t||ft||A.length===0){tt.innerHTML="",_.clear();let Ht=document.createDocumentFragment();for(let Ct=0;Ct<A.length;Ct++){let Kt=ny(A[Ct],Ct,wn,m,Y,le,s,r);_.set(A[Ct].id,Kt),Ht.appendChild(Kt)}tt.appendChild(Ht),q=S,Z=E,ne=null}else{if(ne!==null){let Ct=_.get(ne);if(Ct&&Ct.parentNode===tt){let Kt=A.findIndex(gn=>gn.id===ne);if(Kt>=0){let gn=ny(A[Kt],Kt,wn,m,Y,le,s,r);tt.insertBefore(gn,Ct),Ct.remove(),_.set(ne,gn)}}ne=null}let Ht=new Set(A.map(Ct=>Ct.id));for(let[Ct,Kt]of _)Ht.has(Ct)||(Kt.remove(),_.delete(Ct));for(let Ct=0;Ct<A.length;Ct++){let Kt=A[Ct];if(!_.has(Kt.id)){let gn=ny(Kt,Ct,wn,m,Y,le,s,r);_.set(Kt.id,gn),tt.appendChild(gn)}}}T.isFollowing()&&(tt.scrollTop=tt.scrollHeight)}function Ne(){if(Date.now()-P>=YW){w!==null&&(cancelAnimationFrame(w),w=null),Le();return}v||(v=!0,w=requestAnimationFrame(()=>{w=null,Le()}))}let lt=(Te,Ie)=>{if(!re)return;re.innerHTML="";let je=Je(Te,"12px","currentColor",1.5);je&&re.appendChild(je);let It=C("span","persona-text-xs");It.textContent="Copy All",re.appendChild(It),setTimeout(()=>{re.innerHTML="";let wn=Je(qn.ClipboardCopy,"12px","currentColor",1.5);wn&&re.appendChild(wn);let nn=C("span","persona-text-xs");nn.textContent="Copy All",re.appendChild(nn),re.disabled=!1},Ie)},At=async()=>{if(re){re.disabled=!0;try{let Te;ee()?Te=A:n?(Te=await n(),Te.length===0&&(Te=t.getAll())):Te=t.getAll();let Ie=Te.map(je=>{try{return JSON.parse(je.payload)}catch{return je.payload}});await navigator.clipboard.writeText(JSON.stringify(Ie,null,2)),lt(qn.Check,1500)}catch{lt(qn.X,1500)}}},qe=()=>{te&&(S=te.value,X(),Le())},nt=()=>{!pe||!xe||(xe.style.display=pe.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{E=pe.value,X(),Le()},150))},Ut=()=>{!pe||!xe||(pe.value="",E="",xe.style.display="none",k&&clearTimeout(k),X(),Le())},tn=()=>{if(L)return;let Te=tt.scrollTop,{action:Ie,nextLastScrollTop:je}=Lu({following:T.isFollowing(),currentScrollTop:Te,lastScrollTop:I,nearBottom:Me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});I=je,Ie==="resume"?(T.resume(),W=0,gt.style.display="none"):Ie==="pause"&&(T.pause(),d&&(Fe.textContent=f,gt.style.display=""))},Q=Te=>{let Ie=Pu({following:T.isFollowing(),deltaY:Te.deltaY,nearBottom:Me(),resumeWhenNearBottom:!0});Ie==="pause"?(T.pause(),d&&(Fe.textContent=f,gt.style.display="")):Ie==="resume"&&(T.resume(),W=0,gt.style.display="none")},He=()=>{d&&(tt.scrollTop=tt.scrollHeight,T.resume(),W=0,gt.style.display="none")},_e=Te=>{let Ie=Te.target;if(!Ie||Ie.closest("button"))return;let je=Ie.closest("[data-event-id]");if(!je)return;let It=je.getAttribute("data-event-id");It&&le(It)},ht=Te=>{if((Te.metaKey||Te.ctrlKey)&&Te.key==="f"){Te.preventDefault(),pe?.focus(),pe?.select();return}Te.key==="Escape"&&(pe&&document.activeElement===pe?(Ut(),pe.blur(),x.focus()):o&&o())};re&&re.addEventListener("click",At),te&&te.addEventListener("change",qe),pe&&pe.addEventListener("input",nt),xe&&xe.addEventListener("click",Ut),tt.addEventListener("scroll",tn),tt.addEventListener("wheel",Q,{passive:!0}),tt.addEventListener("click",_e),gt.addEventListener("click",He),x.addEventListener("keydown",ht);function yt(){k&&clearTimeout(k),w!==null&&(cancelAnimationFrame(w),w=null),v=!1,_.clear(),re&&re.removeEventListener("click",At),te&&te.removeEventListener("change",qe),pe&&pe.removeEventListener("input",nt),xe&&xe.removeEventListener("click",Ut),tt.removeEventListener("scroll",tn),tt.removeEventListener("wheel",Q),tt.removeEventListener("click",_e),gt.removeEventListener("click",He),x.removeEventListener("keydown",ht)}return{element:x,update:Ne,destroy:yt}}}var qn,es,KW,GW,YW,eT=ie(()=>{"use strict";Ye();qn=require("lucide");io();bh();es={flow_:{bg:"var(--persona-event-badge-flow-bg, #dcfce7)",text:"var(--persona-event-badge-flow-fg, #15803d)"},step_:{bg:"var(--persona-event-badge-step-bg, #f5f5f5)",text:"var(--persona-event-badge-step-fg, #0a0a0a)"},reasoning_:{bg:"var(--persona-event-badge-reasoning-bg, #fef9c3)",text:"var(--persona-event-badge-reasoning-fg, #a16207)"},tool_:{bg:"var(--persona-event-badge-tool-bg, #f3e8ff)",text:"var(--persona-event-badge-tool-fg, #6b21a8)"},agent_:{bg:"var(--persona-event-badge-agent-bg, #ccfbf1)",text:"var(--persona-event-badge-agent-fg, #115e59)"},error:{bg:"var(--persona-event-badge-error-bg, #fee2e2)",text:"var(--persona-event-badge-error-fg, #b91c1c)"}};es.execution_error=es.error;es.execution_=es.flow_;es.turn_=es.agent_;es.text_=es.agent_;KW={bg:"var(--persona-event-badge-default-bg, #f3f4f6)",text:"var(--persona-event-badge-default-fg, #4b5563)"},GW=["flowName","stepName","reasoningText","text","name","tool","toolName"],YW=100});var Ec,tT=ie(()=>{"use strict";Ec=class{#e;#t=0;#n=0;#o=0;#i=new Set;#r;#s;constructor(t=2e3,n=null){this.#r=t,this.#e=new Array(t),this.#s=n}push(t){this.#e[this.#t]=t,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#o++,this.#i.add(t.type),this.#s?.put(t)}getAll(){return this.#n===0?[]:this.#n<this.#r?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#r),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#s)return 0;let t=await this.#s.getAll();if(t.length===0)return 0;let n=t.length>this.#r?t.slice(t.length-this.#r):t;for(let o of n)this.#e[this.#t]=o,this.#t=(this.#t+1)%this.#r,this.#n<this.#r&&this.#n++,this.#i.add(o.type);return this.#o=t.length,n.length}getAllFromStore(){return this.#s?this.#s.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.#n}getTotalCaptured(){return this.#o}getEvictedCount(){return this.#o-this.#n}clear(){this.#e=new Array(this.#r),this.#t=0,this.#n=0,this.#o=0,this.#i.clear(),this.#s?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#o=0,this.#i.clear(),this.#s?.destroy()}getEventTypes(){return Array.from(this.#i)}}});var kc,nT=ie(()=>{"use strict";kc=class{#e=null;#t=[];#n=!1;#o=!1;#i;#r;constructor(t="persona-event-stream",n="events"){this.#i=t,this.#r=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.#i,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.#r)||r.createObjectStore(this.#r,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.#e=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.#e||this.#o||(this.#t.push(t),this.#n||(this.#n=!0,queueMicrotask(()=>this.#s())))}putBatch(t){if(!(!this.#e||this.#o||t.length===0))try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.#e){t([]);return}try{let i=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.#e){t(0);return}try{let s=this.#e.transaction(this.#r,"readonly").objectStore(this.#r).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.#e){t();return}this.#t=[];try{let s=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.#e&&(this.#e.close(),this.#e=null)}destroy(){return this.#o=!0,this.#t=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.#i);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}#s(){if(this.#n=!1,!this.#e||this.#o||this.#t.length===0)return;let t=this.#t;this.#t=[];try{let o=this.#e.transaction(this.#r,"readwrite").objectStore(this.#r);for(let r of t)o.put(r)}catch{}}}});function ry(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ku(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function lB(e,t){return typeof t.type=="string"?t.type:e}function rT(e){let t=oT(e,"tokens")??oT(e,"totalTokens");return t?iT(t.output):void 0}function cB(e){return iT(e.durationMs)}function dB(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var iB,aB,sT,iT,oT,Lc,aT=ie(()=>{"use strict";iB=new Set(["step_start","turn_start"]),aB=new Set(["step_complete","turn_complete"]),sT=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),iT=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,oT=(e,t)=>{let n=e[t];return sT(n)?n:void 0};Lc=class{#e={status:"idle"};#t=null;constructor(t=dB){this.now=t}getMetric(){let t=this.#t;if(t&&this.#e.status==="running"&&t.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.#e,durationMs:n,tokensPerSecond:Ku(this.#e.outputTokens,n)}}return this.#e}reset(){this.#t=null,this.#e={status:"idle"}}#n(t){this.#t={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.#e={status:"running"}}processEvent(t,n){if(!sT(n)){t==="execution_error"&&this.#t&&(this.#t=null,this.#e={status:"error"});return}let o=lB(t,n),r=this.now();if(o==="execution_start"){this.#n(r);return}if(iB.has(o)){this.#t||this.#n(r);return}if(o==="text_delta"){let s=typeof n.delta=="string"?n.delta:"";if(!s)return;this.#t||this.#n(r);let i=this.#t;i.firstDeltaAt??=r,i.visibleCharCount+=s.length;let l=i.exactOutputTokens+ry(i.visibleCharCount),c=r-i.firstDeltaAt;this.#e={status:"running",tokensPerSecond:Ku(l,c),outputTokens:l,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(aB.has(o)){if(!this.#t)return;let s=this.#t,i=rT(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,c=s.exactOutputTokens+ry(s.visibleCharCount),d=this.#o(s,n,r);this.#e={status:"running",tokensPerSecond:Ku(c,d),outputTokens:c,durationMs:d,source:l?"usage":"estimate"};return}if(o==="execution_complete"){if(!this.#t)return;let s=this.#t,i=rT(n),l=i??s.exactOutputTokens+ry(s.visibleCharCount),c=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.#o(s,n,r);this.#e={status:"complete",tokensPerSecond:Ku(l,d),outputTokens:l,durationMs:d,source:c},this.#t=null;return}if(o==="execution_error"||o==="error"&&n.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:"error"}}}#o(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:cB(n)??o-t.startedAt}}});var lT=ie(()=>{"use strict";eT();tT();nT();aT()});var cT={};En(cT,{EventStreamBuffer:()=>Ec,EventStreamStore:()=>kc,ThroughputTracker:()=>Lc,createEventStreamView:()=>oy});var dT=ie(()=>{"use strict";lT()});var iy,sr,Pc=ie(()=>{"use strict";iy=class{constructor(){this.components=new Map;this.#e=new Map}#e;register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.#e.set(t,o):this.#e.delete(t)}unregister(t){this.components.delete(t),this.#e.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.#e.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.#e.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},sr=new iy});function Sr(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function pT(e){let t=Sr(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Gu(e){if(typeof e!="string")return"";let t=e.indexOf(`
259
259
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
260
260
  `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function _i(e){let t=pT(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Vs(e){switch(_i(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=pT(e.path);return t?t.toUpperCase():"File"}}}function Ic(e){let t=e.markdown??"";return e.file?{filename:Sr(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Gu(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}function Hc(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e.filename,o.click(),URL.revokeObjectURL(n)}var Ni=ie(()=>{"use strict"});function qa(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Yu+(n?" persona-artifact-doc-copy-btn":"");o=C("button",r)}else{let r="persona-icon-btn "+Yu+(n?" persona-artifact-doc-icon-btn":"");o=C("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=C("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Hi({icon:e.icon,label:e.label,className:Yu+(n?" persona-artifact-doc-copy-btn":"")}):o=Ln({icon:e.icon,label:e.label,className:Yu+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Rc(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}var Yu,Xu=ie(()=>{"use strict";Ri();Ye();Yu="persona-artifact-custom-action-btn"});function uT(e){let t=document.createElementNS(ay,"svg");t.setAttribute("class",Jt("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(ay,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(ay,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var ay,fT=ie(()=>{"use strict";Ye();ay="http://www.w3.org/2000/svg"});function mT(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Fs(e,t,0)}var gT=ie(()=>{"use strict";zu()});function ja(e){e&&cy.delete(e)}function uB(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Vs(t):e.artifactType==="component"?"Component":"Document"}function Ka(e,t,n){let o=uB(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=e.id,l=cy.get(i);e.status!=="complete"&&l===void 0&&(l=bT(),cy.set(i,l));let c=l===void 0?0:Math.max(0,bT()-l),d=e.artifactType==="component",p=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:p.length,m=d||p===""?0:p.split(`
261
261
  `).length,g=e.artifactType==="markdown"?e.file:void 0,h={artifactId:i,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:f,lines:m,elapsedMs:c,content:()=>d?"":p,surface:n};try{let b=s(h);return typeof b=="string"?{label:b}:b&&typeof b=="object"&&typeof b.label=="string"?{label:b.label,detail:typeof b.detail=="string"?b.detail:void 0}:{label:r}}catch{return{label:r}}}function fB(e){e.className=ly,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Fi(e,t,n){let o=e.querySelector(`:scope > .${ly}`);o||(o=C("span",ly),e.appendChild(o)),o.getAttribute(yT)!==t.label&&(fB(o),mT(o,t.label,n),o.setAttribute(yT,t.label));let r=e.querySelector(`:scope > .${hT}`),s=t.detail;s?(r||(r=C("span",hT),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var ly,hT,yT,cy,bT,Qu=ie(()=>{"use strict";Ye();Ni();gT();ly="persona-artifact-status-label",hT="persona-artifact-status-detail",yT="data-artifact-status-label",cy=new Map,bT=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()});function hB(e,t){let n=(e||"").trim().toLowerCase();if(n&&Ju[n])return Ju[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Ju[r])return Ju[r]}}return null}function Zu(e,t){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:e.slice(r,i)})};for(;o<e.length;){let i=!1;for(let l of t){l.re.lastIndex=o;let c=l.re.exec(e);if(c&&c.index===o&&c[0].length>0){s(o);let d=l.map?l.map(c[0]):l.type;n.push({type:d,value:c[0]}),o+=c[0].length,r=o,i=!0;break}}i||(o+=1)}return s(e.length),n}function vT(e){return Zu(e,bB)}function CB(e){let t=Zu(e,vB);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}function CT(e){let t=Zu(e,wB),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<t.length&&t[i].value.trim()==="";)i+=1;let l=t[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}function SB(e){let t=[],n=(s,i)=>{i&&t.push({type:s,value:i})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let i=e.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let i=e.indexOf(">",r),l=i===-1?o:i+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let i=e.indexOf(">",r),l=i===-1?o:i+1,c=e.slice(r,l);for(let p of Zu(c,xB))t.push(p);r=l;let d=/^<\s*(script|style)\b/i.exec(c);if(d&&!/\/>\s*$/.test(c)){let p=d[1].toLowerCase(),m=new RegExp("</\\s*"+p+"\\s*>","i").exec(e.slice(r)),g=m?r+m.index:o,h=e.slice(r,g),b=p==="script"?vT(h):CT(h);for(let x of b)t.push(x);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let i=s===-1?o:s;n("plain",e.slice(r,i)),r=i}}return t}function AB(e,t){switch(t){case"html":return SB(e);case"css":return CT(e);case"js":return vT(e);case"json":return CB(e)}}function MB(e){let t=CC(),n=C("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=mB[r];if(i){let l=C("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
@@ -1162,17 +1162,17 @@ ${tH}`.trim()}:{status:!$.failed&&T?"completed":"failed",text:T}}}}var tH,hS,nH,
1162
1162
 
1163
1163
  ${B.description}`)},fn=async B=>await Gs({host:qi(),title:o.deleteConversationConfirmTitle,description:o.deleteConversationConfirm,confirmLabel:o.deleteConversationConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await Gc(B),"deleted"):"cancelled",Ys=async()=>{let B=D()==="verified-user";return await Gs({host:qi(),title:o.clearHistoryConfirmTitle,description:B?o.clearHistoryVerifiedConfirm:o.clearHistoryConfirm,confirmLabel:o.clearHistoryConfirmLabel,cancelLabel:o.confirmCancelLabel})?(await el(),"cleared"):"cancelled"},nl=async()=>{if(!await Gs({host:qi(),title:o.resetIdentityConfirmTitle,description:o.resetIdentityConfirm,confirmLabel:o.resetIdentityConfirmLabel,cancelLabel:o.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:G}=await tl();return{outcome:"reset",remoteRevocationConfirmed:G}},Mn=C("button","persona-history-earlier");Mn.type="button",Mn.textContent=o.showEarlierMessagesLabel,Mn.setAttribute("data-persona-history-earlier",""),Object.assign(Mn.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 xn=()=>{if(!(S()&&!!e.historySessionState.nextMessageCursor&&!!e.session.getActiveConversationId())){Mn.remove();return}Mn.textContent=o.showEarlierMessagesLabel,Mn.parentNode!==e.body&&e.body.insertBefore(Mn,e.body.firstChild)};Mn.addEventListener("click",()=>{let B=e.session.getActiveConversationId(),G=e.historySessionState.nextMessageCursor;if(!B||!G||Mn.disabled)return;Mn.disabled=!0;let me=e.body.scrollHeight,ke=e.body.scrollTop;e.session.loadOlderMessages(B,G,{scope:D()}).then(()=>{e.body.scrollTop=ke+(e.body.scrollHeight-me),e.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Mn.disabled=!1,xn()})});let zo=()=>{let B=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 B.button.addEventListener("click",G=>{if(!(!S()||E())){if(e.historyVisible){Kn();return}mt({invoker:B.button,keyboard:G.detail===0})}}),B},as=()=>{if(!S()){f?.remove(),p=null,f=null;return}if(f&&!f.isConnected&&(p=null,f=null),!p&&e.header){let ke=zo();p=ke.button,f=ke.wrapper;let Xe=e.panelElements.clearChatButtonWrapper||e.panelElements.closeButtonWrapper;Xe?.parentNode&&e.header.contains(Xe)?Xe.parentNode.insertBefore(f,Xe):e.header.appendChild(f)}if(!p||!f)return;let B=jn()||e.historyVisible&&e.historyPresentation==="rail";if(f.style.display=B?"none":"",B){document.activeElement===p&&Vt();return}let G=E();p.disabled=G,p.setAttribute("aria-disabled",G?"true":"false");let me=G?o.openHistoryBusyLabel:o.openHistoryLabel;p.setAttribute("aria-label",me),(e.config.features?.history?.presentation??"panel")==="panel"?(p.removeAttribute("aria-expanded"),p.removeAttribute("aria-controls")):(p.setAttribute("aria-expanded",e.historyVisible?"true":"false"),p.setAttribute("aria-controls",A))},Er=!1,Xs=()=>{let B=e.panelElements.clearChatButton;if(B){if(S()){Er||(h=B.getAttribute("aria-label")??"",Er=!0),B.setAttribute("aria-label",o.newConversationLabel),B.removeAttribute("title");return}Er&&(Er=!1,h&&B.setAttribute("aria-label",h))}},go=()=>{o=Py(e.config.features?.history?.copy),as(),uo(),Xs(),xn()};return e.historyChromeSync=go,w(),go(),e.destroyCallbacks.push(()=>{b?.(),x?.(),g+=1,zi(),i?.dispose(),i?.view.destroy(),i=null}),{historyAvailable:S,historyScope:k,installHistoryProvider:w,syncHistoryChromeImpl:go,syncHistoryPresentation:mo,syncEarlierMessagesPill:xn,openHistory:mt,closeHistory:Kn,openHistoryConversation:Gn,startNewConversation:Uo,updateHistoryConversation:Ks,deleteHistoryConversation:Gc,requestDeleteConversation:fn,clearConversationHistory:el,resetHistoryIdentity:tl,railCollapseShortcut:It,railCollapsible:j,railTriggerApplies:jn,railOverlayMode:At,toggleRailCollapsed:je,toggleRailPinned:()=>Ie(),get historyProvider(){return r},get historySurface(){return i},get railShell(){return St},get railHost(){return ut},get railColumn(){return tt}}}});var H1={};En(H1,{createThemePreview:()=>s0});module.exports=Fk(H1);var tp=require("lucide");io();er();Ye();ln();Ye();var Yd=require("lucide");io();var tL=["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"],nL="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",oL="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",rL=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Xd=(e,t)=>{let n=C("div",["persona-message-bubble",e,...tL].join(" "));return n.id=`bubble-${t}`,n.setAttribute("data-message-id",t),n},Qd=e=>{let t=C("button",e.expandable?nL:oL);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},zm=(e,t,n)=>{e.innerHTML="";let o=Je(t?Yd.ChevronUp:Yd.ChevronDown,16,n,2);o?e.appendChild(o):e.textContent=t?"Hide":"Show"},ba=(e,t,n)=>{if(!n.expandable)return e.append(t),null;let o=C("div","persona-flex persona-items-center");zm(o,n.expanded,n.iconColor);let r=C("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},Jd=e=>{let t=C("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?.();rL(t,n)||(t.textContent=e.previewText),t.style.display=""}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),t},Zd=e=>{e.header.setAttribute("aria-expanded",e.expanded?"true":"false"),e.toggleIcon&&zm(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"},ep=(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&&zm(c,o,n.iconColor),s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")};function np(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return{...e,features:{...e?.features,[n]:{...t==="tool"?zr:wi,...e?.future?.v5Defaults===!0?Ci.features?.[n]:{},...e?.features?.[n]}}}}function Es(e,t){let n=t==="tool"?"toolCallDisplay":"reasoningDisplay";return e?.features?.[n]?.variant??(e?.future?.v5Defaults?"row":"card")}function Pl(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 qr(e,t,n,o){if(Es(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 d=C("span","persona-activity-icon");d.dataset.activityIcon=c;let p={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},f=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,m=f?Re(f,16,"currentColor",2):c==="pending"?Je(tp.Circle,16,"currentColor",2):c==="awaiting-approval"?Je(tp.Clock,16,"currentColor",2):Re(p[c],16,"currentColor",2);m&&d.appendChild(m),r.querySelector(".persona-reasoning-header-icon")?.remove();let g=o==="tool"?"toolCallDisplay":"reasoningDisplay",h=n.features?.[g]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((h==="always"||h==="active"&&c!=="done")&&r.prepend(d),o==="tool"&&s){let S=C("span","persona-activity-duration");i&&s.startedAt&&S.setAttribute("data-tool-elapsed",String(s.startedAt));let E=(o==="tool"?t.toolCall?.duration:void 0)??s.durationMs??(s.completedAt!==void 0&&s.startedAt!==void 0?s.completedAt-s.startedAt:void 0);S.textContent=E===void 0?"":Pl(E),r.appendChild(S)}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 AC(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,d={}){let p=l==="tool"?i.toolCall:i.reasoning;if(!(!p||n.has(i.id))&&(!t.has(i.id)&&p.status!=="complete"&&p.chunks?.some(Boolean)&&(t.add(i.id),d.autoExpand!==!1&&c.add(i.id)),t.has(i.id)&&p.status==="complete"&&!o.has(i.id))){if(o.add(i.id),d.autoCollapseDelay===!1)return;r.set(i.id,setTimeout(()=>{r.delete(i.id),c.delete(i.id),e(i.id,l)},d.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 MC(e,t,n,o){let r=C("div","");r.id=`bubble-${e.id}`,r.dataset.messageId=e.id;let s=C("button","");s.type="button",s.dataset.expandHeader="true",s.dataset.bubbleType="tool",s.setAttribute("aria-expanded",String(n));let i=C("div","");typeof o=="string"?i.textContent=o:i.appendChild(o),ba(s,i,{expandable:!0,expanded:n,iconColor:t.toolCall?.toggleTextColor||t.toolCall?.headerTextColor||"currentColor",metaGap:!0});let l=C("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),qr(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}}jm();function TC(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 ao(e){return e?.type==="runtype"||e?.type==="custom"}var iL=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function EC(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:iL()}catch{return!1}}sp();Xm();var WC=/^\s*\|?[\s:|-]*-[\s:|-]*$/,BC=e=>e.includes("|"),DC=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())},fL=e=>`| ${e.join(" | ")} |`,mL=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,gL=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),OC=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
1164
1164
  `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!BC(r)||WC.test(r)||!WC.test(s))continue;let i=DC(r).length;if(i<1)continue;let l=mL(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let c=o+2;for(;c<t.length;c++){let d=t[c];if(d.trim()===""||!BC(d))break;let p=fL(gL(DC(d),i));t[c]!==p&&(t[c]=p,n=!0)}o=c-1}return n?t.join(`
1165
- `):e};var _C="var(--persona-md-table-scroll-fade, 24px)",NC=new WeakSet;function VC(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 FC(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":_C),e.style.setProperty("--persona-fade-r",r<=1?"0px":_C)}function Qm(e){NC.has(e)||(NC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&FC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(FC)}Si();Bn();var{setLoader:$O,load:tP,provide:UO,getSync:nP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Sw(),xw))});var ki=tP;var Aw=nP;Ai();Bn();var{setLoader:GO,load:uP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(kw(),Ew))});var Lw=uP;var fP="agent_",mP="flow_";function Pw(e){return e.startsWith(fP)?{kind:"agentId",agentId:e}:e.startsWith(mP)?{kind:"flowId",flowId:e}:null}function Iw(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 d=Pw(l);if(d)return d;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=Pw(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 bp(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Hw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}ag();var gP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),hP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=gP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:hP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},lg=(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 d=yP(c);if(d){let f=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(f===void 0||f!==i)&&l(),o.length===0&&(s=c.createdAt,i=f),o.some(m=>m.toolCallId===d.call.toolCallId)||(o.push(d.call),r.push(d.result));continue}let p=t(c);p&&(l(),n.push(p))}return l(),n};Gr();vp();Bn();var{setLoader:r_,load:PP,provide:s_}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(zw(),Uw))});var Xr=PP;Sp();nr();var _P="https://api.runtype.com/v1/dispatch",kn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},ex=e=>"reason"in e?e.reason:void 0,NP="The identity proof was rejected",ug=(e,t)=>e instanceof kn&&e.code===t,fg=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),tx=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),nx=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function FP(e){switch(e){case"json":return ZC;case"regex-json":return JC;case"xml":return ew;default:return QC}}var Ul=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#g=null;this.clientSession=null;this.#i=null;this.#a=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#u=null;this.#L=!1;this.#b=!1;this.#w=!1;this.#d=null;this.#l=new Set;this.#m=new Set;this.webMcpBridge=null;this.#h=null;this.#F=null;this.#le=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??_P,this.#t={"Content-Type":"application/json","X-Persona-Version":br,...t.headers},this.debug=!!t.debug,this.#n=t.streamParser??FP(t.parserType),this.#o=t.contextProviders??[],this.#c=t.requestMiddleware,this.#r=t.customFetch,this.#s=t.parseSSEEvent,this.#f=t.getHeaders,t.webmcp?.enabled===!0&&(this.#h=this.#v(t.webmcp))}#e;#t;#n;#o;#c;#r;#s;#f;#p;#g;#i;#a;#u;#L;#b;#w;#d;#l;#m;#h;#C;#v(t){return Lw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:zC,getToolDisplayTitle:ap,loadPolyfill:jC});return this.#C!==void 0&&o.setConfirmHandler(this.#C),this.webMcpBridge=o,o}).catch(n=>(this.#h=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#y(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#h||(this.#h=this.#v(this.config.webmcp)),this.#h)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#p=t}setWebMcpConfirmHandler(t){this.#C=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#y().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#p}isClientTokenMode(){return!!this.config.clientToken}#A(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Iw(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#A().agentId)}#E(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||mp}#x(t){return`${this.#E()}/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 kn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#E()}/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":br,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let d=await Xr();n=await d.recoverFromUnauthorized(this.#R(),await d.readErrorCode(this.#R(),c),null,!0);continue}if(!c.ok)throw await(await Xr()).historyErrorFor(this.#R(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#i||t&&new Date<t.expiresAt||this.#a===t?null:(this.#a=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.#i)return this.#i;let t=this.#i=this.#H().then(n=>this.#i!==t?this.initSession():(this.clientSession=n,this.#a=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#i===t&&(this.#i=null)});return t}#S(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#L}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#U(){if(!this.#L){this.#N({state:"unavailable",reason:"history_disabled"}),this.#L=!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.#m])t(!1)}}getHistoryIdentityStatus(){return this.#d??this.#q()}subscribeHistoryIdentityStatus(t){return this.#l.add(t),()=>{this.#l.delete(t)}}subscribeHistoryAvailability(t){return this.#m.add(t),this.#L&&t(!1),()=>{this.#m.delete(t)}}#q(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#L?{state:"unavailable",reason:"history_disabled"}:this.#j():{state:"unavailable",reason:"ineligible_mode"}}#j(){let t=this.#d;return t?.state==="browser_only"?t:this.#B()}#B(){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"}}#N(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&ex(n)===ex(t);if(this.#d=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#l])r(t)}}async#M(t){let n=this.#S()&&!t.omitVisitorFields,o=!t.omitVisitorFields,r=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,r=await this.readVisitorToken());let s=this.#A(),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 d=await fetch(this.#x("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(c),signal:t.signal});if(!d.ok){let f=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&f.error==="visitor_history_disabled"){if(this.#U(),l)throw new kn("history_disabled","Visitor history is disabled for this surface");return this.#M({...t,omitVisitorFields:!0})}throw d.status===403&&f.error==="durable_recovery_disabled"?new kn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&d.status===401&&f.error==="visitor_required"?new kn("visitor_required","Visitor credential no longer resolves"):l&&d.status===404?new kn("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${f.hint||f.error}`):d.status===403?new Error(`Origin not allowed: ${f.hint||f.error}`):new Error(f.error||"Failed to initialize session")}let p=await d.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{targetId:p.targetId}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async#H(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#S()&&!n)return this.#K(t,!1);let o=await this.readVisitorToken();if(t&&o)try{let r=await this.#M({conversationId:t,durableResume:n});return n&&r.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(r,t,!1)}catch(r){if(!ug(r,"not_found")&&!ug(r,"visitor_required")&&!ug(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#K(t,!0)}return this.#K(t,!1)}async#K(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#Q(t,n)):this.#Q(t,n)}async#Q(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#M({storedSessionId:o}),s=await this.#z(r);return this.#O(s,t,n)}async#D(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#M({storedSessionId:n,identityProof:t}),s=this.#O(r,o,!1);return this.clientSession=s,this.#i=null,this.#a=!1,this.resetClientToolsFingerprint(),s}async#z(t){if(!t.visitor?.token||this.#w||!this.#S()&&t.durableRecovery?.enabled!==!0)return t;this.#w=!0;try{return await this.#M({storedSessionId:t.sessionId})}catch{return t}finally{this.#w=!1}}#O(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}#ne(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#a=!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.#S())throw new kn("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 kn("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.#M({conversationId:t,identityProof:o});return this.#ne(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.#M({});return this.#ne(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#S()&&this.#N(this.#B())}clearClientSession(){this.clientSession=null,this.#i=null,this.#a=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#u=null}#J(){return`${this.#E()}/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.#J(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},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.#a=!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#P(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}}#F;#oe(){let t=this;return this.#F??={get config(){return t.config},headers:this.#t,getHeaders:this.#f,debug:this.debug,clientApiBase:()=>t.#E(),getClientApiUrl:n=>t.#x(n),getWebMcpBridge:()=>t.#y(),sendWithClientToolsDiff:(n,o,r,s)=>t.#V(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#le;#R(){let t=this;return this.#le??={HistoryClientError:kn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#E(),setHistoryIdentityStatus:n=>t.#N(n),browserOnlyStatus:()=>t.#j(),derivedBrowserOnly:()=>t.#B(),reinitWithProof:n=>t.#D(n),isHistoryCapable:()=>t.#S(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Xr()).listConversations(this.#R(),t)}async getConversation(t,n){return(await Xr()).getConversation(this.#R(),t,n)}async finalizeDisplayProjections(t,n){return(await Xr()).finalizeDisplayProjections(this.#R(),t,n)}async deleteConversation(t,n){return(await Xr()).deleteConversation(this.#R(),t,n)}async deleteAllConversations(t){return(await Xr()).deleteAllConversations(this.#R(),t)}async resetVisitor(){return(await Xr()).resetVisitor(this.#R())}async dispatch(t,n){return t.signal?.throwIfAborted(),ki().catch(()=>{}),this.isClientTokenMode()?this.#re(t,n):this.isAgentMode()?this.#se(t,n):this.#G(t,n)}async#re(t,n){let o=Hw();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,S=A.durableRecovery?.enabled===!0;if(S&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let E=await this.#M({...S||this.#S()?{conversationId:A.conversationId,durableResume:S}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&E.conversationId!==A.conversationId||S&&E.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#O(E,A.conversationId??null,!1),this.clientSession=l,this.#a=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let d=await this.#Z(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,f=this.#S(),m={sessionId:l.sessionId,messages:t.messages.filter(fg).map(A=>{let S=f?Vl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},g=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#V(l.sessionId,d.clientTools,async S=>{i();let E=await this.#P(t.signal);i();let k={...m,sessionId:l.sessionId,...S,...E&&{identityProof:E}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...k,...E&&{identityProof:{provider:E.provider,token:"[REDACTED]"}}}),fetch(this.#x("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(k),signal:t.signal})})},h=await g();if(i(),h.response.status===401){let A=await h.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),h=await g(),i())}let{response:b,commit:x}=h;if(!b.ok){let A=await b.json().catch(()=>({error:"Chat request failed"}));if(b.status===401&&A.error==="invalid_identity_proof"){let E=new kn("invalid_identity_proof",NP);throw s({type:"error",error:E}),E}if(b.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let E=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:E}),E}if(b.status===429){let E=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:E}),E}if(b.status===410&&A.error==="conversation_deleted"){let E=new kn("conversation_deleted","This conversation was deleted");throw s({type:"error",error:E}),E}let S=new Error(A.error||"Failed to send message");throw s({type:"error",error:S}),S}if(!b.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}x(),s({type:"status",status:"connected"});try{await this.#$(b.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 kn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#G(t,n){n({type:"status",status:"connecting"});let o=await this.#Z(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#t};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.#$(s.body,n)}finally{n({type:"status",status:"idle"})}}async#se(t,n){n({type:"status",status:"connecting"});let o=await this.#ce(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.#t};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.#$(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.#$(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){return(await ki()).resolveApproval(this.#oe(),t,n)}async#V(t,n,o,r){let s=!!(n&&n.length>0),i=s?qC(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,d=!s&&r?.emptyMeansReplace===!0&&this.#u===t,p=!1,f;for(let m=0;;m++){if(f=await o({...s&&(p||!c)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),f.status===409&&m===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#u=t:d&&(this.#u=null)}}}async resumeFlow(t,n,o){return(await ki()).resumeFlow(this.#oe(),t,n,o)}#_(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#W(t){let n={};this.#o.length&&await Promise.all(this.#o.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.#_(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#k(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}#Y(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#ce(t,n){let o=this.#A().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=lg(tx(t),d=>fg(d)&&(d.role==="user"||d.role==="assistant"||d.role==="system")&&(!d.variant||d.variant==="assistant")?nx(d):null),s=this.#k(n),i={agent:this.#Y(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...Fl(this.config),...await(await this.#y())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#W(t);return c&&(i.context=c),i}async#Z(t,n){let o=lg(tx(t),d=>fg(d)?nx(d):null),r=this.#A(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,p]of Object.entries(r.targetPayload))d!=="messages"&&(s[d]=p);let i=[...Fl(this.config),...await(await this.#y())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#W(t);l&&(s.context=l);let c=this.#k(n);if(c&&(s.composerOptions=c),this.#c)try{let d=await this.#c({payload:{...s},config:this.config});if(d&&typeof d=="object"){let p=d;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",d)}return s}async#$(t,n,o,r){let{streamResponse:s}=Aw()??await ki();return s({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#s,onSSEEvent:(i,l)=>this.#p?.(i,l)},t,n,o,r)}};zl();Bn();var{setLoader:oF,load:bI,provide:rF,getSync:vI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(tS(),eS))});var ru=bI;var Vg=vI;Ai();Bn();var{setLoader:lF,load:EI,provide:cF,getSync:kI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(sS(),rS))});var Ug=EI;var iS=kI;Nl();Rs();Hl();Rs();Eg();var LI=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function PI(e){let t=e?.text?.trim()??"";return t?Kl(LI(e),t):""}function aS(e){let t=PI(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[vr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
1165
+ `):e};var _C="var(--persona-md-table-scroll-fade, 24px)",NC=new WeakSet;function VC(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 FC(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":_C),e.style.setProperty("--persona-fade-r",r<=1?"0px":_C)}function Qm(e){NC.has(e)||(NC.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&FC(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(FC)}Si();Bn();var{setLoader:$O,load:tP,provide:UO,getSync:nP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(Sw(),xw))});var ki=tP;var Aw=nP;Ai();Bn();var{setLoader:GO,load:uP}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(kw(),Ew))});var Lw=uP;var fP="agent_",mP="flow_";function Pw(e){return e.startsWith(fP)?{kind:"agentId",agentId:e}:e.startsWith(mP)?{kind:"flowId",flowId:e}:null}function Iw(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 d=Pw(l);if(d)return d;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=Pw(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 bp(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Ea(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}function Hw(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`turn_${e}_${t}`}ag();var gP=e=>e.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),hP=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),yP=e=>{if(e.variant!=="tool")return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=gP(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:hP(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},lg=(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 d=yP(c);if(d){let f=c.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(f===void 0||f!==i)&&l(),o.length===0&&(s=c.createdAt,i=f),o.some(m=>m.toolCallId===d.call.toolCallId)||(o.push(d.call),r.push(d.result));continue}let p=t(c);p&&(l(),n.push(p))}return l(),n};Gr();vp();Bn();var{setLoader:r_,load:PP,provide:s_}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(zw(),Uw))});var Xr=PP;Sp();nr();var _P="https://api.runtype.com/v1/dispatch",kn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},ex=e=>"reason"in e?e.reason:void 0,NP="The identity proof was rejected",ug=(e,t)=>e instanceof kn&&e.code===t,fg=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),tx=e=>e.slice().sort((t,n)=>new Date(t.createdAt).getTime()-new Date(n.createdAt).getTime()),nx=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt});function FP(e){switch(e){case"json":return ZC;case"regex-json":return JC;case"xml":return ew;default:return QC}}var Ul=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.#f=null;this.clientSession=null;this.#p=null;this.#l=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#a=null;this.#S=!1;this.#b=!1;this.#w=!1;this.#y=null;this.#d=new Set;this.#u=new Set;this.webMcpBridge=null;this.#m=null;this.#R=null;this.#le=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??_P,this.#t={"Content-Type":"application/json","X-Persona-Version":br,...t.headers},this.debug=!!t.debug,this.#n=t.streamParser??FP(t.parserType),this.#o=t.contextProviders??[],this.#i=t.requestMiddleware,this.#r=t.customFetch,this.#s=t.parseSSEEvent,this.#g=t.getHeaders,t.webmcp?.enabled===!0&&(this.#m=this.#x(t.webmcp))}#e;#t;#n;#o;#i;#r;#s;#g;#c;#f;#p;#l;#a;#S;#b;#w;#y;#d;#u;#m;#h;#x(t){return Lw().then(n=>{let o=new n.WebMcpBridge(t,{recordToolDisplayTitles:zC,getToolDisplayTitle:ap,loadPolyfill:jC});return this.#h!==void 0&&o.setConfirmHandler(this.#h),this.webMcpBridge=o,o}).catch(n=>(this.#m=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#A(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#m||(this.#m=this.#x(this.config.webmcp)),this.#m)}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.#c=t}setWebMcpConfirmHandler(t){this.#h=t,this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.config.webmcp?.enabled!==!0?null:this.#A().then(r=>r?r.executeToolCall(t,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#C(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Iw(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.#C().agentId)}#v(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||mp}#P(t){return`${this.#v()}/v1/client/${t}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(t){let n=await this.initSession(),o=!1;for(;;){let r=n.conversationId,s=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!r||!s)throw new kn("visitor_token_missing","Durable recovery is not enabled for this client session");let i=`${this.#v()}/v1/client/conversations/${encodeURIComponent(r)}/executions/${encodeURIComponent(t.executionId)}/events`,l=new URLSearchParams({sessionId:n.sessionId,after:t.after}),c=await fetch(`${i}?${l}`,{method:"GET",headers:{"X-Persona-Version":br,"X-Visitor-Token":s},signal:t.signal});if(c.status===401&&!o){o=!0;let d=await Xr();n=await d.recoverFromUnauthorized(this.#B(),await d.readErrorCode(this.#B(),c),null,!0);continue}if(!c.ok)throw await(await Xr()).historyErrorFor(this.#B(),c,!0);return c}}async warmSession(){let t=this.clientSession;return!this.isClientTokenMode()||this.#p||t&&new Date<t.expiresAt||this.#l===t?null:(this.#l=t,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#p)return this.#p;let t=this.#p=this.#O().then(n=>this.#p!==t?this.initSession():(this.clientSession=n,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===t&&(this.#p=null)});return t}#k(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#S}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}#M(){if(!this.#S){this.#V({state:"unavailable",reason:"history_disabled"}),this.#S=!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.#u])t(!1)}}getHistoryIdentityStatus(){return this.#y??this.#I()}subscribeHistoryIdentityStatus(t){return this.#d.add(t),()=>{this.#d.delete(t)}}subscribeHistoryAvailability(t){return this.#u.add(t),this.#S&&t(!1),()=>{this.#u.delete(t)}}#I(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#S?{state:"unavailable",reason:"history_disabled"}:this.#X():{state:"unavailable",reason:"ineligible_mode"}}#X(){let t=this.#y;return t?.state==="browser_only"?t:this.#z()}#z(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#V(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&ex(n)===ex(t);if(this.#y=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.#d])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.#C(),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 d=await fetch(this.#P("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(c),signal:t.signal});if(!d.ok){let f=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&f.error==="visitor_history_disabled"){if(this.#M(),l)throw new kn("history_disabled","Visitor history is disabled for this surface");return this.#T({...t,omitVisitorFields:!0})}throw d.status===403&&f.error==="durable_recovery_disabled"?new kn("history_disabled","Durable recovery is disabled for this surface"):(n||t.durableResume)&&d.status===401&&f.error==="visitor_required"?new kn("visitor_required","Visitor credential no longer resolves"):l&&d.status===404?new kn("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${f.hint||f.error}`):d.status===403?new Error(`Origin not allowed: ${f.hint||f.error}`):new Error(f.error||"Failed to initialize session")}let p=await d.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId?{targetId:p.targetId}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.durableRecovery?{durableRecovery:p.durableRecovery}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async#O(){await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#k()&&!n)return this.#W(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.#_(r,t,!1)}catch(r){if(!ug(r,"not_found")&&!ug(r,"visitor_required")&&!ug(r,"history_disabled"))throw r;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(t,!0)}return this.#W(t,!1)}async#W(t,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#$(t,n)):this.#$(t,n)}async#$(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.#T({storedSessionId:o}),s=await this.#ee(r);return this.#_(s,t,n)}async#j(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.#T({storedSessionId:n,identityProof:t}),s=this.#_(r,o,!1);return this.clientSession=s,this.#p=null,this.#l=!1,this.resetClientToolsFingerprint(),s}async#ee(t){if(!t.visitor?.token||this.#w||!this.#k()&&t.durableRecovery?.enabled!==!0)return t;this.#w=!0;try{return await this.#T({storedSessionId:t.sessionId})}catch{return t}finally{this.#w=!1}}#_(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}#Q(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.#l=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#k())throw new kn("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 kn("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.#Q(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.#Q(t)}handleExternalCredentialChange(){this.clearClientSession(),this.#k()&&this.#V(this.#z())}clearClientSession(){this.clientSession=null,this.#p=null,this.#l=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#a=null}#te(){return`${this.#v()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.#te(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.#l=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async#q(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}}#R;#U(){let t=this;return this.#R??={get config(){return t.config},headers:this.#t,getHeaders:this.#g,debug:this.debug,clientApiBase:()=>t.#v(),getClientApiUrl:n=>t.#P(n),getWebMcpBridge:()=>t.#A(),sendWithClientToolsDiff:(n,o,r,s)=>t.#ne(n,o,r,s),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}#le;#B(){let t=this;return this.#le??={HistoryClientError:kn,get config(){return t.config},get historyInternals(){return t.historyInternals},get clientSession(){return t.clientSession},clientApiBase:()=>t.#v(),setHistoryIdentityStatus:n=>t.#V(n),browserOnlyStatus:()=>t.#X(),derivedBrowserOnly:()=>t.#z(),reinitWithProof:n=>t.#j(n),isHistoryCapable:()=>t.#k(),clearClientSession:()=>t.clearClientSession(),initSession:()=>t.initSession(),readVisitorToken:()=>t.readVisitorToken(),isClientTokenMode:()=>t.isClientTokenMode()}}async listConversations(t){return(await Xr()).listConversations(this.#B(),t)}async getConversation(t,n){return(await Xr()).getConversation(this.#B(),t,n)}async finalizeDisplayProjections(t,n){return(await Xr()).finalizeDisplayProjections(this.#B(),t,n)}async deleteConversation(t,n){return(await Xr()).deleteConversation(this.#B(),t,n)}async deleteAllConversations(t){return(await Xr()).deleteAllConversations(this.#B(),t)}async resetVisitor(){return(await Xr()).resetVisitor(this.#B())}async dispatch(t,n){return t.signal?.throwIfAborted(),ki().catch(()=>{}),this.isClientTokenMode()?this.#ce(t,n):this.isAgentMode()?this.#oe(t,n):this.#J(t,n)}async#ce(t,n){let o=Hw();this.#f=o;let r=()=>this.#f===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,S=A.durableRecovery?.enabled===!0;if(S&&(!A.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");i();let E=await this.#T({...S||this.#k()?{conversationId:A.conversationId,durableResume:S}:{storedSessionId:A.sessionId},signal:t.signal});if(i(),A.conversationId&&E.conversationId!==A.conversationId||S&&E.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");l=this.#_(E,A.conversationId??null,!1),this.clientSession=l,this.#l=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await c();let d=await this.#F(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([A])=>A!=="sessionId"&&A!=="session_id")):void 0,f=this.#k(),m={sessionId:l.sessionId,messages:t.messages.filter(fg).map(A=>{let S=f?Vl(A):void 0;return{id:A.id,role:A.role,content:A.contentParts??A.llmContent??A.rawContent??A.content,...S!==void 0&&{displayContent:S}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:o,...t.interrupt&&{submitMode:"interrupt"}},g=async()=>{i();let A=l.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return i(),this.#ne(l.sessionId,d.clientTools,async S=>{i();let E=await this.#q(t.signal);i();let k={...m,sessionId:l.sessionId,...S,...E&&{identityProof:E}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...k,...E&&{identityProof:{provider:E.provider,token:"[REDACTED]"}}}),fetch(this.#P("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":br,...A?{"X-Visitor-Token":A}:{}},body:JSON.stringify(k),signal:t.signal})})},h=await g();if(i(),h.response.status===401){let A=await h.response.clone().json().catch(()=>null);i(),A?.error==="Session not found or expired"&&(await c(),h=await g(),i())}let{response:b,commit:x}=h;if(!b.ok){let A=await b.json().catch(()=>({error:"Chat request failed"}));if(b.status===401&&A.error==="invalid_identity_proof"){let E=new kn("invalid_identity_proof",NP);throw s({type:"error",error:E}),E}if(b.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let E=new Error("Session expired. Please refresh to continue.");throw s({type:"error",error:E}),E}if(b.status===429){let E=new Error(A.hint||"Message limit reached for this session.");throw s({type:"error",error:E}),E}if(b.status===410&&A.error==="conversation_deleted"){let E=new kn("conversation_deleted","This conversation was deleted");throw s({type:"error",error:E}),E}let S=new Error(A.error||"Failed to send message");throw s({type:"error",error:S}),S}if(!b.body){let A=new Error("No response body received");throw s({type:"error",error:A}),A}x(),s({type:"status",status:"connected"});try{await this.#G(b.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 kn)&&!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&s({type:"error",error:l}),l}}async#J(t,n){n({type:"status",status:"connecting"});let o=await this.#F(t.messages,t.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.#t};if(this.#g)try{let i=await this.#g();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#oe(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.#t};if(this.#g)try{let i=await this.#g();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 ki()).resolveApproval(this.#U(),t,n)}async#ne(t,n,o,r){let s=!!(n&&n.length>0),i=s?qC(n):void 0,l=this.clientToolsFingerprintSessionId===t,c=s&&l&&this.lastSentClientToolsFingerprint===i,d=!s&&r?.emptyMeansReplace===!0&&this.#a===t,p=!1,f;for(let m=0;;m++){if(f=await o({...s&&(p||!c)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),f.status===409&&m===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.#a=t:d&&(this.#a=null)}}}async resumeFlow(t,n,o){return(await ki()).resumeFlow(this.#U(),t,n,o)}#re(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#K(t){let n={};this.#o.length&&await Promise.all(this.#o.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.#re(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#D(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}#N(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.#C().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let r=lg(tx(t),d=>fg(d)&&(d.role==="user"||d.role==="assistant"||d.role==="system")&&(!d.variant||d.variant==="assistant")?nx(d):null),s=this.#D(n),i={agent:this.#N(this.config.agent??{agentId:o},s),messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};s&&(i.composerOptions=s);let l=[...Fl(this.config),...await(await this.#A())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#K(t);return c&&(i.context=c),i}async#F(t,n){let o=lg(tx(t),d=>fg(d)?nx(d):null),r=this.#C(),s={messages:o,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,p]of Object.entries(r.targetPayload))d!=="messages"&&(s[d]=p);let i=[...Fl(this.config),...await(await this.#A())?.snapshotForDispatch()??[]];i.length>0&&(s.clientTools=i);let l=await this.#K(t);l&&(s.context=l);let c=this.#D(n);if(c&&(s.composerOptions=c),this.#i)try{let d=await this.#i({payload:{...s},config:this.config});if(d&&typeof d=="object"){let p=d;return s.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=s.clientTools),p}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",d)}return s}async#G(t,n,o,r){let{streamResponse:s}=Aw()??await ki();return s({config:()=>this.config,createStreamParser:this.#n,parseSSEEvent:this.#s,onSSEEvent:(i,l)=>this.#c?.(i,l)},t,n,o,r)}};zl();Bn();var{setLoader:oF,load:bI,provide:rF,getSync:vI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(tS(),eS))});var ru=bI;var Vg=vI;Ai();Bn();var{setLoader:lF,load:EI,provide:cF,getSync:kI}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(sS(),rS))});var Ug=EI;var iS=kI;Nl();Rs();Hl();Rs();Eg();var LI=e=>e.sourceLabel?`quoted-text source=${e.sourceLabel}`:"quoted-text";function PI(e){let t=e?.text?.trim()??"";return t?Kl(LI(e),t):""}function aS(e){let t=PI(e.quote);return t?e.contentParts&&e.contentParts.length>0?{contentParts:[vr(t),...e.contentParts]}:{llmContent:[t,e.text].filter(Boolean).join(`
1166
1166
 
1167
- `)}:{}}function iu(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function lS(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 zg(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 cS(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 zg(e,n.id)?n.id:null}return null}function qg(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}zl();Sp();function jg(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 ec=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):jg(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 au=class{#e=null;#t=null;#n="idle";#o=new Set;#c=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#t===t?this.#n:"idle"}activeMessageId(){return this.#t}onChange(t){return this.#o.add(t),()=>this.#o.delete(t)}toggle(t,n){if(this.#t===t){if(this.#n==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#s(t,"paused")):this.stop();return}if(this.#n==="paused"){this.#e?.resume(),this.#s(t,"playing");return}if(this.#n==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#c;this.#e?.stop(),this.#s(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#c)return;if(!r){this.#s(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#c&&this.#s(t,"playing")},onEnd:()=>{o===this.#c&&this.#s(null,"idle")},onError:()=>{o===this.#c&&this.#s(null,"idle")}})}catch{o===this.#c&&this.#s(null,"idle")}}stop(){this.#c++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(t,n){this.#t=n==="idle"?null:t,this.#n=n;for(let o of this.#o)o(this.#t,this.#n)}};var tc=class{#e;#t=!1;start(t){this.#e=t,this.#t=!1}cancel(){this.#t=!0}accepts(t){return!this.#t&&(!t||!this.#e||t===this.#e)}};Bn();var{setLoader:_F,load:rH,getSync:sH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(ES(),TS))});var oc=rH,kS=sH;function eh(e){if(!e)return"";let t=iH(e);return LS(t!==null?t:e)}function iH(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 LS(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
1167
+ `)}:{}}function iu(e,t=140){let n=e.replace(/\s+/g," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function lS(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 zg(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 cS(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 zg(e,n.id)?n.id:null}return null}function qg(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}zl();Sp();function jg(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 ec=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):jg(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 au=class{#e=null;#t=null;#n="idle";#o=new Set;#i=0;#r;constructor(t){this.#r=t}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(t){return this.#t===t?this.#n:"idle"}activeMessageId(){return this.#t}onChange(t){return this.#o.add(t),()=>this.#o.delete(t)}toggle(t,n){if(this.#t===t){if(this.#n==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#s(t,"paused")):this.stop();return}if(this.#n==="paused"){this.#e?.resume(),this.#s(t,"playing");return}if(this.#n==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.#i;this.#e?.stop(),this.#s(t,"loading");try{if(!this.#e){let r=await this.#r();if(o!==this.#i)return;if(!r){this.#s(null,"idle");return}this.#e=r}this.#e.speak(n,{onStart:()=>{o===this.#i&&this.#s(t,"playing")},onEnd:()=>{o===this.#i&&this.#s(null,"idle")},onError:()=>{o===this.#i&&this.#s(null,"idle")}})}catch{o===this.#i&&this.#s(null,"idle")}}stop(){this.#i++,this.#e?.stop(),this.#s(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#o.clear()}#s(t,n){this.#t=n==="idle"?null:t,this.#n=n;for(let o of this.#o)o(this.#t,this.#n)}};var tc=class{#e;#t=!1;start(t){this.#e=t,this.#t=!1}cancel(){this.#t=!0}accepts(t){return!this.#t&&(!t||!this.#e||t===this.#e)}};Bn();var{setLoader:_F,load:rH,getSync:sH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(ES(),TS))});var oc=rH,kS=sH;function eh(e){if(!e)return"";let t=iH(e);return LS(t!==null?t:e)}function iH(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 LS(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
1168
1168
  `),t=t.replace(/\n{2,}/g,`
1169
1169
  `),t.trim()}var WS=null;var th=()=>WS?WS():Promise.resolve().then(()=>(RS(),HS));Bn();var{setLoader:GF,load:pH}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(DS(),BS))});var OS=pH;var uH=["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 fH(e,t){return uH.some(n=>e[n]!==t[n])}var Cr=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function nh(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}
1170
1170
 
1171
- _Details: ${n.message}_`:o}var _S=e=>Ca(e)||e===Yr,uu=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.#n=null;this.#o=!1;this.#c=null;this.#r=null;this.#s=null;this.artifacts=new Map;this.#f=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#g=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#i=null;this.#a=null;this.#u=0;this.#L=0;this.#b=!1;this.#w="disconnected";this.#d=null;this.#l=null;this.#m=null;this.#h=0;this.#C=!1;this.#v=null;this.#y=!1;this.#A=null;this.#E=new Map;this.#x=null;this.#S=new Map;this.#U=null;this.#q=null;this.#j=!1;this.#B=null;this.#N=null;this.#M=!1;this.#H=null;this.#D=null;this.#z=null;this.#O=new tc;this.#ne=Promise.resolve();this.#J=null;this.#P=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new au(()=>this.#F());this.#Xe=null;this.#ue=0;this.handleEvent=t=>{let n=this.#P;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.#Oe(t.message.id),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#n=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Ug().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(Ca(o.name)||o.name===Yr&&Hs(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.#Ee();return}if(this.#ee(t.status),t.status==="connecting")this.#I(!0);else if(t.status==="idle"||t.status==="error"){this.#De()||this.#xe(),this.webMcpResolveControllers.size===0&&(this.#I(!1),this.abortController=null,this.#ze(),this.#$e());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.#ee("error"),this.#xe(),this.webMcpResolveControllers.size===0&&(this.#I(!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.#se(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#X()})),this.messages=this.#fe(this.messages),this.client=new Ul(t,this.historyInternals),this.#ke(),this.#We();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#f=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#ye(),this.callbacks.onStatusChanged(this.status),this.#Q(),this.#K()}#e;#t;#n;#o;#c;#r;#s;#f;#p;#g;#i;#a;#u;#L;#b;#w;#d;#l;#m;#h;#C;#v;#y;#A;#E;#x;#S;#U;#q;#j;#B;#N;#M;#H;#K(){this.config.voiceRecognition?.provider&&oc().catch(()=>{})}#Q(){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||th().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 EC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#b}getVoiceStatus(){return this.#w}getVoiceDisclosure(){return this.#i?.getDisclosure?.()??null}getVoiceLevel(){return this.#i?.onLevel?this.#L:null}getVoiceInterruptionMode(){return this.#i?.getInterruptionMode?this.#i.getInterruptionMode():"none"}stopVoicePlayback(){this.#i?.stopPlayback&&(this.#O.cancel(),this.#J?.cancel(),this.#i.stopPlayback())}isBargeInActive(){return this.#i?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#i?.deactivateBargeIn&&await this.#i.deactivateBargeIn()}#D;#z;#O;#ne;#J;#P;#F(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ec.isSupported()?new ec({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 th().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(d,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):d});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.#u;this.#a=oc().then(async s=>{await o,r===this.#u&&this.#oe(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#u&&(this.#a=null)})}catch(n){console.error("Failed to setup voice:",n)}}#oe(t,n){this.#i=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#i,generation:()=>o.#u,get keyed(){return o.#J},set keyed(r){o.#J=r},get pendingUser(){return o.#D},set pendingUser(r){o.#D=r},get pendingAssistant(){return o.#z},set pendingAssistant(r){o.#z=r},turns:()=>o.#O,busy:()=>o.#le(),setStreaming:r=>o.#I(r),setDelegation:r=>{o.#P=r},setLevel:r=>{o.#L=r},setStatus:r=>{o.#w=r,o.#b=r==="listening"},settlePending:r=>o.#re(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#i&&this.#a&&await this.#a,!this.#i){console.error("Voice not configured");return}if(this.#b)await this.#i.stopListening();else{this.stopSpeaking();try{await this.#i.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!ao(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#u,n=()=>{let o=this.#i;!o?.prewarm||t!==this.#u||this.#b||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#i&&this.#a){this.#a.then(n,()=>{});return}n()}#le(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#o||this.status==="resuming"}cleanupVoice(){let t=this.#i!==null;if(this.#u++,this.#a=null,this.#i){let n=this.#i;this.#i=null,this.#ne=this.#R(n)}this.#b=!1,this.#w="disconnected",this.#re(!0),this.#J?.settle(),this.#J=null,this.#O=new tc,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#R(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#re(t){let n=t?this.#D:null,o=this.#z;!n&&!o||(o&&this.#O.cancel(),t&&(this.#D=null),this.#z=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.#I(!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.#q=this.historyInternals.getStoredConversationRevision?.()??null,this.#j=!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.#G(t,n)}#G(t,n=!this.messages.length){if(this.#C||!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.#X()};this.#ae(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.#ke()}destroy(){this.cleanupVoice(),this.#B?.(),this.#B=null,this.#N=null}#se(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Se(o),n?.(o)}}}get#V(){return this.historyInternals.historyProvider??null}#_(){let t=this.#V;if(!t)throw new Cr("history_unavailable","No conversation history provider is installed");return t}#W(t){let n=this.#_(),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 Li("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#d,conversationRevision:this.#l,nextMessageCursor:this.#m,recovery:this.#v,sendBlocked:this.#y}}getActiveConversationId(){return this.#d}#k(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#Y(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#A;t&&await t.catch(()=>{});let n=this.#x;n&&await n.catch(()=>{})}#ce(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Cr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#_().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#W(t?.scope)})}async openConversation(t,n){let o=this.#_();this.#ce();let r=this.#W(n?.scope);await this.awaitHistorySettled();let s=++this.#h,i=await o.getPage(t,{context:r});if(s!==this.#h)throw new Cr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#h)throw l.discard(),new Cr("superseded","A later selection won");this.#C=!0;try{await this.#ie(l)}finally{this.#C=!1}this.#d=l.conversationId||t,this.#l=l.conversationRevision||i.conversationRevision||null,this.#m=i.nextCursor,this.#v=null,this.#y=!1,this.#pe();for(let c of i.messages)this.#S.set(c.id,c.content);return this.#T(),this.hydrateMessages(i.messages),this.#k(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#_(),s=this.#W(o?.scope),i=n??this.#m;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#E.get(l);if(c)return c;let d=this.#Z(r,t,i,s).finally(()=>{this.#E.delete(l)});return this.#E.set(l,d),d}async#Z(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.#fe(l.map(c=>this.#ve(c))),this.#m=i.nextCursor;for(let c of i.messages)this.#S.set(c.id,c.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#k(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.#_(),o=this.#W(t?.scope);await this.awaitHistorySettled();let r=++this.#h,s=await n.prepareStartNew({context:o});if(r!==this.#h)throw s.discard(),new Cr("superseded","A later action won");await this.#$(s)}async#$(t){this.#te(),await this.#ie(t),this.#d=t.conversationId||null,this.#l=t.conversationRevision||null,this.#m=null,this.#v=null,this.#y=!1,this.#T(),this.#k()}async deleteConversation(t,n){let o=this.#_(),r=this.#W(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#d&&await this.#me(r)}async updateConversation(t,n,o){let r=this.#_();if(!r.update)throw new Cr("history_unavailable","This history provider cannot update conversations");let s=this.#W(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#V?.update=="function"}async clearConversationHistory(t){let n=this.#_(),o=this.#W(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#me(o),r}async resetHistoryDevice(){let t=this.#_();if(!t.resetDevice)throw new Cr("history_unavailable","This history provider cannot reset the device");this.#h+=1,this.#x=null;try{return await t.resetDevice()}finally{this.#te(),this.#d=null,this.#l=null,this.#m=null,this.#v=null,this.#y=!1,this.#k()}}async#me(t){this.#h+=1,this.#x=null,this.#te(),this.#d=null,this.#l=null,this.#m=null,this.#y=!0,this.#v=null,this.#k(),await this.#de(t)}async#de(t){let n=this.#V;if(!n){this.#y=!1,this.#k();return}try{let o=await n.prepareStartNew({context:t});await this.#$(o)}catch{this.#y=!0,this.#v="new_conversation_required",this.#k(),this.#Y("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#Ce(){if(!(this.#v!=="new_conversation_required"||!this.#V)&&(this.#v=null,await this.#de(this.#W()),this.#v==="new_conversation_required"))throw new Cr("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.#l=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#C||this.#G(t)}#T(){this.#d?this.config.setStoredConversationId?.(this.#d):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#l),this.historyInternals.setStoredMessageCursor?.(this.#m)}#pe(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#S.clear(),this.#ge(null)}#te(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.messages=[],this.#pe(),this.#E.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#I(!1),this.#ee("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Se(t){this.#h+=1,this.#x=null,this.#y=!0,this.#te(),this.#d=t.conversationId,this.#l=null,this.#m=null,this.#v=null,this.#k(),this.#Y("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#A=Promise.resolve().then(()=>{this.#y=!1,this.#A=null,this.#k()})}#ke(){let t=this.historyInternals.visitorStore??null;t!==this.#N&&(this.#B?.(),this.#B=null,this.#N=t,t&&(this.#B=t.subscribe(n=>this.#_e(n))))}#_e(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#h+=1,this.#x=null,this.#M=!0,this.#H=null;let n=this.messages.length>0;n||this.#d!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#te():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#E.clear(),this.#ge(null)),this.#d=null,this.#l=null,this.#m=null,this.#v=null,this.#k(),n&&this.#Y("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#Ne(){return this.#M?(this.#H||(this.#H=this.#Fe().finally(()=>{this.#H=null})),this.#H):Promise.resolve()}async#Fe(){if(!this.isClientTokenMode()){this.#M=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#M=!1}catch{}}reconcileBootConversation(t){let n=this.#V,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#d;if(!n||!o)return Promise.resolve();let r=this.#W(t?.scope);this.#y=!0,this.#k();let s=this.#Ve(n,o,r).finally(()=>{this.#y=this.#v!==null,this.#A===s&&(this.#A=null),this.#k()});return this.#A=s,s}async#Ve(t,n,o){this.#d=n;let r=this.clientSession?.conversationRevision??this.#l??null,s=this.#j?this.#q:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#j=!1,this.#m=this.historyInternals.getStoredMessageCursor?.()??this.#m,await this.replayPendingProjections(),r&&s&&r===s){this.#l=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(f=>f.id)),c=this.messages.some(f=>l.has(f.id)),d=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(f=>this.#ve(f));else{let f=this.#t?this.#n:null,m=this.messages.filter(g=>l.has(g.id)||g.id===f?!0:d!==void 0&&g.createdAt<d);p=$l(m,i.messages).map(g=>this.#ve(g))}this.#m=i.nextCursor,this.#l=i.conversationRevision||r||null,this.#S.clear();for(let f of i.messages)this.#S.set(f.id,f.content);this.#T(),this.messages=this.#fe(p),this.callbacks.onMessagesChanged([...this.messages])}#Ae(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ge(t){this.#U=t,this.historyInternals.setPendingDisplayProjections?.(t)}#Le(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Pe(t){if(this.#Ae())for(let n of t){let o=Vl(n);o!==void 0&&this.#S.set(n.id,o)}}#$e(){if(!this.#Ae())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=Vl(o);r!==void 0&&this.#S.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#ge({conversationId:t,messageIds:n.map(o=>o.id)}),this.#Ie(t,n))}#Ie(t,n){let r=(this.#x??Promise.resolve()).catch(()=>{}).then(()=>this.#He(t,n,!1)).finally(()=>{this.#x===r&&(this.#x=null)});this.#x=r}async#He(t,n,o){if(this.#d!==t)return;let r=n.filter(s=>this.#S.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.#S.set(i.id,i.displayContent);this.#d===t&&s&&(this.#l=s),this.#Me(t,n)}catch(s){if(!o&&this.#Ue(s)){await this.#He(t,r,!0);return}if(s instanceof kn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Me(t,n);return}this.#Y("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#Ue(t){return t instanceof kn?t.code==="request_failed":t instanceof Error}#Me(t,n){let o=this.#Le();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#ge(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#Ae())return;let t=this.#Le();if(!t)return;if(this.#d&&t.conversationId!==this.#d){this.#ge(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.#ge(null);return}this.#Ie(t.conversationId,n),await this.#x?.catch(()=>{})}#ze(){this.#d&&(this.#l=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Re(){await this.awaitHistorySettled(),await this.#Ne(),this.#v==="new_conversation_required"&&await this.#Ce()}static#qe(t){return t instanceof kn&&t.code==="conversation_deleted"}async#je(t,n,o,r,s){this.#Pe(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.#Pe([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.#x=null,this.#te(),this.#d=null,this.#l=null,this.#m=null,this.#C=!0;try{let r=this.#V;if(r){let s=await r.prepareStartNew({context:this.#W()});await this.#$(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#y=!0,this.#v="new_conversation_required",this.#k(),this.#Y("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#C=!1}return this.#ae(o),this.#I(!0),this.#Y("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=TC(this.config,o),s=fH(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&ao(o.voiceRecognition.provider)&&this.setupVoice());let i=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!s){this.client.updateConfig(o),i&&this.#Be();return}this.#he(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ul(this.config,this.historyInternals),i&&this.#Be(),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:d=!1,voiceProcessing:p,voiceCaption:f,rawContent:m}=t,h={id:i??(n==="user"?bp():n==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#X(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...f&&{voiceCaption:f},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}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:d,sequence:p,streaming:f=!1,voiceProcessing:m,rawContent:g}=o,b={id:c??(r==="user"?bp():r==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:p??this.#X(),streaming:f,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...m!==void 0&&{voiceProcessing:m},...g!==void 0&&{rawContent:g}};n.push(b)}return this.messages=this.#fe([...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,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...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(`
1171
+ _Details: ${n.message}_`:o}var _S=e=>Ca(e)||e===Yr,uu=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.#n=Date.now();this.clientSession=null;this.agentExecution=null;this.#o=null;this.#i=null;this.#r=!1;this.#s=null;this.#g=null;this.#c=null;this.artifacts=new Map;this.#f=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.#p=0;this.webMcpApprovalResolvers=new Map;this.#l=0;this.approvalTokens=new Map;this.webMcpAwaitBatches=new Map;this.#a=null;this.#S=null;this.#b=0;this.#w=0;this.#y=!1;this.#d="disconnected";this.#u=null;this.#m=null;this.#h=null;this.#x=0;this.#A=!1;this.#C=null;this.#v=!1;this.#P=null;this.#k=new Map;this.#M=null;this.#I=new Map;this.#X=null;this.#z=null;this.#V=!1;this.#T=null;this.#O=null;this.#W=!1;this.#$=null;this.#_=null;this.#Q=null;this.#te=new tc;this.#q=Promise.resolve();this.#R=null;this.#U=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new au(()=>this.#le());this.#Ze=null;this.#ue=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.#t),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.#i=t.message.id),(t.message.variant==="approval"||t.message.agentMetadata?.awaitingLocalTool===!0)&&Ug().catch(()=>{});let o=t.message.toolCall,r=!!o?.name&&(Ca(o.name)||o.name===Yr&&Hs(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.#ke();return}if(this.#Z(t.status),t.status==="connecting")this.#H(!0);else if(t.status==="idle"||t.status==="error"){this.#_e()||this.#Ae(),this.webMcpResolveControllers.size===0&&(this.#H(!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.#H(!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.#re(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.#Y()})),this.messages=this.#fe(this.messages),this.client=new Ul(t,this.historyInternals),this.#Pe(),this.#De();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.#f=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#ye(),this.callbacks.onStatusChanged(this.status),this.#ee(),this.#j()}#e;#t;#n;#o;#i;#r;#s;#g;#c;#f;#p;#l;#a;#S;#b;#w;#y;#d;#u;#m;#h;#x;#A;#C;#v;#P;#k;#M;#I;#X;#z;#V;#T;#O;#W;#$;#j(){this.config.voiceRecognition?.provider&&oc().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||th().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 EC(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#y}getVoiceStatus(){return this.#d}getVoiceDisclosure(){return this.#a?.getDisclosure?.()??null}getVoiceLevel(){return this.#a?.onLevel?this.#w:null}getVoiceInterruptionMode(){return this.#a?.getInterruptionMode?this.#a.getInterruptionMode():"none"}stopVoicePlayback(){this.#a?.stopPlayback&&(this.#te.cancel(),this.#R?.cancel(),this.#a.stopPlayback())}isBargeInActive(){return this.#a?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#a?.deactivateBargeIn&&await this.#a.deactivateBargeIn()}#_;#Q;#te;#q;#R;#U;#le(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=ec.isSupported()?new ec({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 th().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:c})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new c(d,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):d});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.#q,r=++this.#b;this.#S=oc().then(async s=>{await o,r===this.#b&&this.#B(s,s.createVoiceProvider(n))}).catch(s=>{console.error("Failed to setup voice:",s)}).finally(()=>{r===this.#b&&(this.#S=null)})}catch(n){console.error("Failed to setup voice:",n)}}#B(t,n){this.#a=n;let o=this;t.wireSessionVoice({session:this,provider:()=>o.#a,generation:()=>o.#b,get keyed(){return o.#R},set keyed(r){o.#R=r},get pendingUser(){return o.#_},set pendingUser(r){o.#_=r},get pendingAssistant(){return o.#Q},set pendingAssistant(r){o.#Q=r},turns:()=>o.#te,busy:()=>o.#ce(),setStreaming:r=>o.#H(r),setDelegation:r=>{o.#U=r},setLevel:r=>{o.#w=r},setStatus:r=>{o.#d=r,o.#y=r==="listening"},settlePending:r=>o.#oe(r)},n,t.KeyedVoiceTranscript,t.createVoiceSessionBridge)}async toggleVoice(){if(!this.#a&&this.#S&&await this.#S,!this.#a){console.error("Voice not configured");return}if(this.#y)await this.#a.stopListening();else{this.stopSpeaking();try{await this.#a.startListening()}catch(t){console.error("Failed to start voice:",t)}}}prewarmVoice(){if(!ao(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let t=this.#b,n=()=>{let o=this.#a;!o?.prewarm||t!==this.#b||this.#y||this.isBargeInActive()||Promise.resolve().then(()=>o.prewarm?.()).catch(()=>{})};if(!this.#a&&this.#S){this.#S.then(n,()=>{});return}n()}#ce(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#r||this.status==="resuming"}cleanupVoice(){let t=this.#a!==null;if(this.#b++,this.#S=null,this.#a){let n=this.#a;this.#a=null,this.#q=this.#J(n)}this.#y=!1,this.#d="disconnected",this.#oe(!0),this.#R?.settle(),this.#R=null,this.#te=new tc,t&&this.callbacks.onVoiceStatusChanged?.("disconnected")}async#J(t){try{await t.disconnect()}catch(n){console.error("Failed to disconnect voice:",n)}}#oe(t){let n=t?this.#_:null,o=this.#Q;!n&&!o||(o&&this.#te.cancel(),t&&(this.#_=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.#H(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine,prewarmMode:t.runtype?.prewarmMode,attachIdleMs:t.runtype?.attachIdleMs,clientDelegation:t.runtype?.clientDelegation,callContext:t.runtype?.callContext,approvalTimeoutMs:t.runtype?.approvalTimeoutMs,disclosureText:t.runtype?.disclosureText}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#z=this.historyInternals.getStoredConversationRevision?.()??null,this.#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.#A||!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.#Y()};this.#ae(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.#re(t),this.client.setHistoryInternals(this.historyInternals),this.#Pe()}destroy(){this.cleanupVoice(),this.#T?.(),this.#T=null,this.#O=null}#re(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.#Fe(o),n?.(o)}}}get#K(){return this.historyInternals.historyProvider??null}#D(){let t=this.#K;if(!t)throw new Cr("history_unavailable","No conversation history provider is installed");return t}#N(t){let n=this.#D(),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 Li("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.#u,conversationRevision:this.#m,nextMessageCursor:this.#h,recovery:this.#C,sendBlocked:this.#v}}getActiveConversationId(){return this.#u}#L(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#F(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.#P;t&&await t.catch(()=>{});let n=this.#M;n&&await n.catch(()=>{})}#G(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new Cr("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.#D().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.#N(t?.scope)})}async openConversation(t,n){let o=this.#D();this.#G();let r=this.#N(n?.scope);await this.awaitHistorySettled();let s=++this.#x,i=await o.getPage(t,{context:r});if(s!==this.#x)throw new Cr("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.#x)throw l.discard(),new Cr("superseded","A later selection won");this.#A=!0;try{await this.#de(l)}finally{this.#A=!1}this.#u=l.conversationId||t,this.#m=l.conversationRevision||i.conversationRevision||null,this.#h=i.nextCursor,this.#C=null,this.#v=!1,this.#xe();for(let c of i.messages)this.#I.set(c.id,c.content);return this.#pe(),this.hydrateMessages(i.messages),this.#L(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.#D(),s=this.#N(o?.scope),i=n??this.#h;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,c=this.#k.get(l);if(c)return c;let d=this.#ve(r,t,i,s).finally(()=>{this.#k.delete(l)});return this.#k.set(l,d),d}async#ve(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.#u&&this.#u!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=$l(this.messages,i.messages);this.messages=this.#fe(l.map(c=>this.#we(c))),this.#h=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.#D(),o=this.#N(t?.scope);await this.awaitHistorySettled();let r=++this.#x,s=await n.prepareStartNew({context:o});if(r!==this.#x)throw s.discard(),new Cr("superseded","A later action won");await this.#se(s)}async#se(t){this.#me(),await this.#de(t),this.#u=t.conversationId||null,this.#m=t.conversationRevision||null,this.#h=null,this.#C=null,this.#v=!1,this.#pe(),this.#L()}async deleteConversation(t,n){let o=this.#D(),r=this.#N(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.#u&&await this.#Ce(r)}async updateConversation(t,n,o){let r=this.#D();if(!r.update)throw new Cr("history_unavailable","This history provider cannot update conversations");let s=this.#N(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.#K?.update=="function"}async clearConversationHistory(t){let n=this.#D(),o=this.#N(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.#Ce(o),r}async resetHistoryDevice(){let t=this.#D();if(!t.resetDevice)throw new Cr("history_unavailable","This history provider cannot reset the device");this.#x+=1,this.#M=null;try{return await t.resetDevice()}finally{this.#me(),this.#u=null,this.#m=null,this.#h=null,this.#C=null,this.#v=!1,this.#L()}}async#Ce(t){this.#x+=1,this.#M=null,this.#me(),this.#u=null,this.#m=null,this.#h=null,this.#v=!0,this.#C=null,this.#L(),await this.#ie(t)}async#ie(t){let n=this.#K;if(!n){this.#v=!1,this.#L();return}try{let o=await n.prepareStartNew({context:t});await this.#se(o)}catch{this.#v=!0,this.#C="new_conversation_required",this.#L(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async#E(){if(!(this.#C!=="new_conversation_required"||!this.#K)&&(this.#C=null,await this.#ie(this.#N()),this.#C==="new_conversation_required"))throw new Cr("new_conversation_required","A new conversation is required before sending")}async#de(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.#u=t.conversationId,this.#m=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.#A||this.#ne(t)}#pe(){this.#u?this.config.setStoredConversationId?.(this.#u):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#m),this.historyInternals.setStoredMessageCursor?.(this.#h)}#xe(){this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#Ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#I.clear(),this.#ge(null)}#me(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.messages=[],this.#xe(),this.#k.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.#H(!1),this.#Z("idle"),this.callbacks.onMessagesChanged([...this.messages])}#Fe(t){this.#x+=1,this.#M=null,this.#v=!0,this.#me(),this.#u=t.conversationId,this.#m=null,this.#h=null,this.#C=null,this.#L(),this.#F("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.#P=Promise.resolve().then(()=>{this.#v=!1,this.#P=null,this.#L()})}#Pe(){let t=this.historyInternals.visitorStore??null;t!==this.#O&&(this.#T?.(),this.#T=null,this.#O=t,t&&(this.#T=t.subscribe(n=>this.#Ve(n))))}#Ve(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.#x+=1,this.#M=null,this.#W=!0,this.#$=null;let n=this.messages.length>0;n||this.#u!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#me():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#k.clear(),this.#ge(null)),this.#u=null,this.#m=null,this.#h=null,this.#C=null,this.#L(),n&&this.#F("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}#$e(){return this.#W?(this.#$||(this.#$=this.#Ue().finally(()=>{this.#$=null})),this.#$):Promise.resolve()}async#Ue(){if(!this.isClientTokenMode()){this.#W=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.#W=!1}catch{}}reconcileBootConversation(t){let n=this.#K,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#u;if(!n||!o)return Promise.resolve();let r=this.#N(t?.scope);this.#v=!0,this.#L();let s=this.#ze(n,o,r).finally(()=>{this.#v=this.#C!==null,this.#P===s&&(this.#P=null),this.#L()});return this.#P=s,s}async#ze(t,n,o){this.#u=n;let r=this.clientSession?.conversationRevision??this.#m??null,s=this.#V?this.#z:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#V=!1,this.#h=this.historyInternals.getStoredMessageCursor?.()??this.#h,await this.replayPendingProjections(),r&&s&&r===s){this.#m=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(f=>f.id)),c=this.messages.some(f=>l.has(f.id)),d=i.messages[0]?.createdAt,p;if(!c)p=i.messages.map(f=>this.#we(f));else{let f=this.#o?this.#i:null,m=this.messages.filter(g=>l.has(g.id)||g.id===f?!0:d!==void 0&&g.createdAt<d);p=$l(m,i.messages).map(g=>this.#we(g))}this.#h=i.nextCursor,this.#m=i.conversationRevision||r||null,this.#I.clear();for(let f of i.messages)this.#I.set(f.id,f.content);this.#pe(),this.messages=this.#fe(p),this.callbacks.onMessagesChanged([...this.messages])}#Me(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#ge(t){this.#X=t,this.historyInternals.setPendingDisplayProjections?.(t)}#Ie(){return this.historyInternals.getPendingDisplayProjections?.()??this.#X}#He(t){if(this.#Me())for(let n of t){let o=Vl(n);o!==void 0&&this.#I.set(n.id,o)}}#qe(){if(!this.#Me())return;let t=this.#u;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=Vl(o);r!==void 0&&this.#I.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.#ge({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.#u!==t)return;let r=n.filter(s=>this.#I.get(s.id)!==s.displayContent);if(r.length===0){this.#Te(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.#u===t&&s&&(this.#m=s),this.#Te(t,n)}catch(s){if(!o&&this.#je(s)){await this.#We(t,r,!0);return}if(s instanceof kn&&(s.code==="not_found"||s.code==="conversation_deleted")){this.#Te(t,n);return}this.#F("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}#je(t){return t instanceof kn?t.code==="request_failed":t instanceof Error}#Te(t,n){let o=this.#Ie();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.#ge(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.#Me())return;let t=this.#Ie();if(!t)return;if(this.#u&&t.conversationId!==this.#u){this.#ge(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.#ge(null);return}this.#Re(t.conversationId,n),await this.#M?.catch(()=>{})}#Ke(){this.#u&&(this.#m=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Be(){await this.awaitHistorySettled(),await this.#$e(),this.#C==="new_conversation_required"&&await this.#E()}static#Ge(t){return t instanceof kn&&t.code==="conversation_deleted"}async#Ye(t,n,o,r,s){this.#He(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.#He([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.#x+=1,this.#M=null,this.#me(),this.#u=null,this.#m=null,this.#h=null,this.#A=!0;try{let r=this.#K;if(r){let s=await r.prepareStartNew({context:this.#N()});await this.#se(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.#v=!0,this.#C="new_conversation_required",this.#L(),this.#F("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.#A=!1}return this.#ae(o),this.#H(!0),this.#F("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=TC(this.config,o),s=fH(this.config,o);this.config=o,r&&(this.cleanupVoice(),o.voiceRecognition?.enabled===!0&&ao(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.#he(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let l=this.client.getSSEEventCallback();this.client=new Ul(this.config,this.historyInternals),i&&this.#Oe(),this.#De(),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:d=!1,voiceProcessing:p,voiceCaption:f,rawContent:m}=t,h={id:i??(n==="user"?bp():n==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:c??this.#Y(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...f&&{voiceCaption:f},...m!==void 0&&{rawContent:m}};return this.upsertMessage(h),h}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:d,sequence:p,streaming:f=!1,voiceProcessing:m,rawContent:g}=o,b={id:c??(r==="user"?bp():r==="assistant"?Ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:p??this.#Y(),streaming:f,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...m!==void 0&&{voiceProcessing:m},...g!==void 0&&{rawContent:g}};n.push(b)}return this.messages=this.#fe([...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,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...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(`
1172
1172
 
1173
1173
  `),i=[s,n].filter(Boolean).join(`
1174
1174
 
1175
- `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let d=[];s&&d.push(vr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(c){let d=[];i&&d.push(vr(i)),d.push(...r.contentParts),t.contentParts=d}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.#P&&!n?.voiceTurn&&(this.#P.failed=!0,this.#P=null),(this.#A||this.#x||this.#y||this.#M)&&await this.#Re(),this.stopSpeaking(),this.abortController?.abort(),this.#he(),this.#ue++,this.#be();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(g=>g.id===s&&g.role==="user"):void 0,l=i?.id??bp(),c=Ea();this.#n=null;let d=n?.contentParts&&Cp(n.contentParts)?La:"",p={id:l,role:"user",content:o||d,createdAt:new Date().toISOString(),sequence:this.#X(),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.#ae(p),this.#I(!0);let f=new AbortController;if(this.abortController=f,n?.mentions){let g=this.messages.find(h=>h.id===l)??p;if(await this.#Ge(g,o,n.mentions.finalize),f.signal.aborted||this.abortController!==f)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let g=this.messages.find(b=>b.id===l)??p,h=aS({quote:n.quote,text:g.llmContent??g.content,contentParts:g.contentParts});h.contentParts&&(g.contentParts=h.contentParts),h.llmContent!==void 0&&(g.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(g.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let m=i?[...this.messages.filter(g=>g!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#je(m,f,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(g){if(this.status==="resuming"||this.#o)return;this.#P&&(this.#P.failed=!0);let h=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));if(!h){let b=nh(g,this.config.errorMessage);if(b){let x={id:c,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.#X()};this.#ae(x)}}this.#ee("idle"),this.#I(!1),this.abortController=null,h||(g instanceof Error?this.callbacks.onError?.(g):this.callbacks.onError?.(new Error(String(g))))}}resubmitFrom(t,n){let o=lS(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 d=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}},p=s?this.#Ye(s.options):r.composerOptions,f=s?s.contentSegments:r.contentSegments,m=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...f?.length?{contentSegments:[...f]}:{},...p?{composerOptions:p}:{},...m?{quote:m}:{},...d&&Object.keys(d).length>0?{replayFields:d}:{},viaVoice:g===!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.#A||this.#x||this.#y||this.#M)&&await this.#Re(),this.abortController?.abort(),this.#be();let t=Ea();this.#n=null,this.#I(!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.#o)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=nh(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#X()};this.#ae(l)}}this.#ee("idle"),this.#I(!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.#n=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.#I(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.#o)return;this.#ee("error"),this.webMcpResolveControllers.size===0&&(this.#I(!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.#g}`,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;#ue;#we(t){let n=this.#Xe??={s:this,setStreaming:s=>this.#I(s),appendMessage:s=>this.#ae(s),nextSequence:()=>this.#X(),settleApprovalPausedToolCall:s=>this.#Oe(s),resumeAfter:s=>this.#t?.executionId===s?this.#t.lastEventId:void 0},o=iS();if(o)return t(o,n);let r=this.#ue;return Ug().then(s=>r===this.#ue?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.#p;queueMicrotask(()=>{s===this.#p&&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.#p;queueMicrotask(()=>{if(t===this.#p)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))}#he(){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.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#I(!1),this.#ee("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.messages=[],this.agentExecution=null,this.#Te(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#I(!1),this.#ee("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#f}selectArtifact(t){this.#f=t,this.#ye()}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.#f=n,this.#ye(),t.transcript!==!1&&this.#et(o),o}#et(t){let n=`artifact-ref-${t.id}`,o=ks(this.config.features?.artifacts,t),r=Il(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})}#Be(){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=ks(this.config.features?.artifacts,n),s=Il(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.#f===null||(this.artifacts.clear(),this.#f=null,this.#ye())}#ye(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#f})}#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.#f=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.#ye()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#fe(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#X()}))),this.#I(!1),this.#ee("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.#f=n,this.#ye()}#nt(t){let n=this.agentExecution?.executionId;if(!n||!this.#n||this.agentExecution?.status!=="running")return;let o=this.#t===null;this.#t={executionId:n,lastEventId:t,assistantMessageId:this.#n,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.#De()}#De(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#Ee(){this.#o||!this.#t||typeof this.config.reconnectStream!="function"||(this.#o=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#t}),this.#I(!0),this.#ee("resuming"),this.#rt().then(t=>{this.#o&&this.#t&&t.begin()}))}#rt(){return this.#c?Promise.resolve(this.#c):(this.#r||(this.#r=OS().then(({createReconnectController:t})=>{let n=t(this.#st());return this.#c=n,n}),this.#r.catch(()=>{this.#r=null})),this.#r)}#st(){let t=this;return{get config(){return t.config},getResumable:()=>t.#t,clearResumable:()=>t.#xe(),getStatus:()=>t.status,setStatus:n=>t.#ee(n),setStreaming:n=>t.#I(n),setReconnecting:n=>{t.#o=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.#ae(n),nextSequence:()=>t.#X(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>nh(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#o){this.#c?.wake();return}this.#Ee()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#o)return;let n=this.#it();n||(n=Ea(),this.#ae({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#X()})),this.#n=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.#Ee()}#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}#be(){this.#o=!1,this.#c?.teardown(),this.#xe()}#xe(){this.#s&&(clearTimeout(this.#s),this.#s=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.#s&&(clearTimeout(this.#s),this.#s=null),n(this.#t);return}this.#s||(this.#s=setTimeout(()=>{this.#s=null,this.config.onExecutionState?.(this.#t)},500))}}getResumableHandle(){return this.#t}#ee(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#I(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=eh(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return jg(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=eh(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()}#Oe(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})}#ae(t){let n=this.#ve(t);this.messages=this.#fe([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#ve(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#ae(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 f=r.approval,m=n.approval;i.approval={...f,...m,executionId:m.executionId||f.executionId,toolName:m.toolName||f.toolName,description:m.description||f.description,toolType:m.toolType??f.toolType,reason:m.reason??f.reason,parameters:m.parameters??f.parameters,toolCallId:m.toolCallId??f.toolCallId}}let c=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(c&&_S(c)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let f=`${d}:${p}`,m=this.webMcpInflightKeys.has(f),g=this.webMcpResolvedKeys.has(f),h=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&_S(h)&&r.toolCall?.status==="complete";(m||g||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#fe(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#ve(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#X()}}#X(){return this.#e++}#fe(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)})}};Ye();var Fo=require("lucide");io();ln();Rs();var mH={add:e=>Yw(e)},gH=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,fu={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function hH(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yH(e){return e==="application/pdf"?Fo.FileText:e.startsWith("text/")?Fo.FileText:e.includes("word")?Fo.FileText:e.includes("excel")||e.includes("spreadsheet")?Fo.FileSpreadsheet:e==="application/json"?Fo.FileCode:Fo.File}var rc=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#n=!1;this.config={allowedTypes:t.allowedTypes??fu.allowedTypes,maxFileSize:t.maxFileSize??fu.maxFileSize,maxFiles:t.maxFiles??fu.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#t;#n;#o(){return typeof this.config.adapter?.add=="function"}#c(){return this.#o()?this.config.adapter:mH}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#g(n)}this.#u()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:fu.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.#n)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=Xw(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:hH(),file:o,previewUrl:wp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#o()?"uploading":"processing",progress:this.#o()?0:void 0};this.attachments.push(s),this.#g(s),n.push(s)}this.#u(),this.#p(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#t.set(t.id,n);let o=()=>this.#n||n.signal.aborted||this.#t.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#c().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=gH(s),this.#i(t),this.#p())}});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.#i(t),this.#p()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#n||(n.status=this.#o()?"uploading":"processing",n.progress=this.#o()?0:void 0,n.error=void 0,this.#i(n),this.#p(),this.#r(n))}#s(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.#s(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.#u(),this.#p()}#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.#s(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#u(),this.#p()}destroy(){if(!this.#n){this.#n=!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}}#p(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#g(t){if(!this.#e)return;let n=wp(t.file),o=C("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 p=C("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",o.appendChild(p)}else{let p=C("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let f=yH(t.file.type),m=Je(f,20,"var(--persona-muted, #6b7280)",1.5);m&&p.appendChild(m);let g=C("span");g.textContent=Qw(t.file.type,t.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",p.appendChild(g),o.appendChild(p)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=C("div","persona-attachment-progress");s.appendChild(C("div","persona-attachment-progress__bar"));let i=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=Re("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=C("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 d=Je(Fo.X,10,"var(--persona-text-inverse, #ffffff)",2);d?c.appendChild(d):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#a(o,t)}#i(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#a(n,t)}#a(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)}%`:""}}#u(){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 NS=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),bH=(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 FS(){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 p=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(f=>Object.freeze({...f}))),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:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let p=l();for(let f of[...t])try{f(p)}catch(m){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",m)}},d=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,d())},setAttachments:p=>{bH(e.attachments,p)||(e.attachments=[...p],d())},setMentionRefs:p=>{NS(e.mentionRefs,p)||(e.mentionRefs=[...p],d())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,d())},setActiveModeIds:p=>{NS(e.activeModeIds,p)||(e.activeModeIds=[...p],d())},setQuote:p=>{let f=e.quote;f?.text===p?.text&&f?.messageId===p?.messageId&&f?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,d())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,d())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,d())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,d())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,d())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,d())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Ye();var Co=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},VS=(e,t)=>{let n=C("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function $S(e,t={}){let n=Co(e,"[data-persona-composer-form]"),o=Co(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:Co(e,"[data-persona-composer-header]"),body:Co(e,"[data-persona-composer-body]"),actionsStart:Co(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Co(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Co(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Co(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Co(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=VS("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=(x,A,S,E,k)=>{if(A)return A;s.add(x);let D=VS(S,E);return k.appendChild(D),D},d=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),f=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),m=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),g=[],h=(x,A)=>x.target===A.target&&x.type===A.type&&x.handler===A.handler,b=Co(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:d,actionsEnd:p,suggestions:f,status:m,attachmentInput:b,attachmentPreviews:Co(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Co(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Co(e,"[data-persona-composer-submit]")??void 0,micButton:Co(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,A,S,E)=>{x.addEventListener(A,S,E),g.push({target:x,type:A,handler:S,options:E})},removeListener:(x,A,S,E)=>{x.removeEventListener(A,S,E),g=g.filter(k=>!h(k,{target:x,type:A,handler:S}))},destroy:()=>{for(let x of g)x.target.removeEventListener(x.type,x.handler,x.options);g=[]}}}Ye();ln();Pa();Ws();Ra();Ye();ln();Ws();var vH='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',CH=["--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"],oh="data-persona-menu-focus",wH=new Set(["ArrowDown","ArrowUp","Home","End"]);function US(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(vH)??e}var xH=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function zS(e){let t=e.label,n=!1,o=C("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Ao} ${rr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let I=e.getButtonSize?.()??"";r.style.width=I,r.style.height=I,r.style.minWidth=I,r.style.minHeight=I,r.style.lineHeight="1",r.replaceChildren();let Y=Re("plus",vo,"currentColor",1.5);Y?r.appendChild(Y):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],d=-1,p=!1,f=()=>{let Y=s.getRootNode().activeElement;return Y instanceof HTMLElement?Y:null},m=()=>{let I=f();for(let Y of c){let _=!!I&&US(Y)===I;Y.toggleAttribute(oh,_&&p)}},g=()=>c.filter(I=>I.isConnected||s.contains(I)).map(US).filter(I=>!xH(I)),h=(I,Y)=>{I.forEach((_,q)=>{_.setAttribute("tabindex",q===Y?"0":"-1")})},b=I=>{let Y=g();if(Y.length===0)return;let _=(I%Y.length+Y.length)%Y.length;d=_,h(Y,_),Y[_].focus(),m()},x=()=>o.ownerDocument??document,A=null,S=null,E=null,k=()=>{A&&(x().removeEventListener("focusin",A,!0),A=null)},D=()=>{S&&(s.removeEventListener("focusin",S),S=null),E&&(s.removeEventListener("pointerdown",E,!0),E=null)},$=null,J=()=>($||($=Bs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),k()}})),$),T=()=>$?.isOpen===!0,W=(I=!1)=>{if(T()){$?.close(),r.setAttribute("aria-expanded","false"),k(),D(),d=-1,p=!1;for(let Y of c)Y.removeAttribute(oh);I&&r.focus()}},P=(I=0,Y=!1)=>{if(n||T())return;p=Y,Rp(r,s,CH),J().open(),r.setAttribute("aria-expanded","true");let _=g();h(_,-1),b(I<0?_.length-1:I),A=q=>{let Z=typeof q.composedPath=="function"?q.composedPath():[];Z.includes(s)||Z.includes(o)||W()},x().addEventListener("focusin",A,!0),S=()=>m(),s.addEventListener("focusin",S),E=()=>{p=!1},s.addEventListener("pointerdown",E,!0)},v=I=>{I.preventDefault(),I.stopPropagation(),T()?W(!0):P(0)},w=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),p=!0,T()?b(0):P(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),p=!0,T()?b(-1):P(-1,!0))},L=I=>{switch(wH.has(I.key)&&(p=!0),I.key){case"ArrowDown":I.preventDefault(),b(d+1);return;case"ArrowUp":I.preventDefault(),b(d-1);return;case"Home":I.preventDefault(),b(0);return;case"End":I.preventDefault(),b(g().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),W(!0);return;case"Tab":W(!0);return;default:}};return r.addEventListener("click",v),r.addEventListener("keydown",w),s.addEventListener("keydown",L),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let _ of c)I.includes(_)||_.removeAttribute(oh);if(c=[...I],!T())return;let Y=g();h(Y,Math.min(d,Y.length-1)),m()},isOpen:T,open:()=>P(0),close:W,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:i,destroy:()=>{n=!0,k(),D(),r.removeEventListener("click",v),r.removeEventListener("keydown",w),s.removeEventListener("keydown",L),$?.destroy(),$=null,o.remove(),s.remove(),c=[]}}}var wr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},qS="data-persona-composer-action",rh="data-persona-composer-disable-when-streaming",SH="core:overflow",AH=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function MH(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=C("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 sh(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 jS=(e,t)=>{!e||typeof console>"u"||console.warn(t)},TH=(e,t)=>t.includes(":")?t:`${e}:${t}`;function EH(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){jS(t,`[Persona] composer action "${l.id}" is already contributed by ${KS(c)}; the ${KS(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,d)=>{let p=d?TH(d,l.id):l.id,f=l.order??wr.custom;l.placement==="end"&&f>=wr.send&&(jS(t,`[Persona] composer action "${p}" ordered at ${f} would render after send; clamped to ${wr.send-1}.`),f=wr.send-1),s({id:p,placement:l.placement,presentation:l.presentation??"bar",order:f,sequence:r++,source:c,pluginId:d,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(d){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,d);continue}for(let d of c??[])i(d,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var KS=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",GS=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,kH=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function LH(e,t){if(!e||e==="always")return!0;let n=kH(t);return e==="when-text"?n:!n}var Os=e=>e.kind==="custom",ih=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,PH=e=>{let t=ih(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},IH='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function HH(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(IH)||o.childNodes.forEach(n)};return n(e),t.trim()}var RH=e=>HH(e).length===0;function YS(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(v,w)=>{let L=v.button;if(!L)return;L.setAttribute("role","menuitem"),L.setAttribute("tabindex","-1"),L.className="persona-composer-overflow-menu__item";for(let _ of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])L.style[_]="";L.style.lineHeight="1",w.tooltipText?L.setAttribute("title",w.tooltipText):L.removeAttribute("title"),L.replaceChildren();let I=C("span","persona-composer-overflow-menu__icon");if(w.iconName){let _=Re(w.iconName,16,"currentColor",1.5);_&&I.appendChild(_)}let Y=C("span","persona-composer-overflow-menu__label");Y.textContent=w.shortLabel??w.label,L.append(I,Y)},i=(v,w)=>{let L=v.button;if(!L)return;if(L.setAttribute("aria-label",w.label),w.pressed===void 0?L.removeAttribute("aria-pressed"):L.setAttribute("aria-pressed",w.pressed?"true":"false"),L.toggleAttribute(rh,w.disableWhenStreaming===!0),v.mode==="menu"){v.tooltip?.destroy(),v.tooltip=void 0,s(v,w);return}L.removeAttribute("role"),L.removeAttribute("tabindex"),L.removeAttribute("title");let I=r(),Y=!!w.shortLabel;if(L.className=Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Ao,rr,Y&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),L.style.width=I&&!Y?I:"",L.style.height=I??"",L.style.minWidth=I&&!Y?I:"",L.style.minHeight=I??"",L.style.fontSize=Y?"":"18px",L.style.lineHeight="1",L.style.color=w.iconColor??"",L.style.backgroundColor=w.backgroundColor??"",L.replaceChildren(),w.iconName){let _=Re(w.iconName,vo,"currentColor",1.5);_&&L.appendChild(_)}if(Y){let _=C("span","persona-composer-action-button__label");_.textContent=w.shortLabel,L.appendChild(_)}else L.firstChild||(L.textContent=w.label);v.tooltip?.destroy(),v.tooltip=$n({anchor:L,trigger:v.element,text:()=>w.tooltipText??w.label,enabled:!!w.tooltipText})},l=(v,w)=>{let L=v.action,I=F("button",{attrs:{type:"button"}}),Y=I;if(w==="bar"){let Z=C("div","persona-send-button-wrapper");Z.appendChild(I),Y=Z}Y.setAttribute(qS,v.id);let _={resolved:v,element:Y,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:w},q=Z=>{if(Z.preventDefault(),Z.stopPropagation(),_.busy||I.disabled)return;let ne=_.resolved.action;_.mode==="menu"&&g?.close(!0);let te;try{te=ne.onSelect(e.actionContext,Z)}catch(re){e.reportError(re,{actionId:_.resolved.id});return}!te||typeof te.then!="function"||(_.busy=!0,I.setAttribute("aria-busy","true"),te.catch(re=>{e.reportError(re,{actionId:_.resolved.id})}).finally(()=>{_.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",q),_.detach=()=>I.removeEventListener("click",q),i(_,L),_},c=v=>{let w=v.action,L;try{L=w.render({...e.actionContext,id:v.id,action:w})}catch(I){return e.reportError(I,{actionId:v.id}),null}return L?.element?(L.element.setAttribute(qS,v.id),L.element.toggleAttribute(rh,w.disableWhenStreaming===!0),{resolved:v,element:L.element,owned:!0,managed:!0,destroy:L.destroy,busy:!1,visible:!0,mode:"bar"}):null},d=(v,w)=>{if(v.builtIn){let I=v.builtIn.element;return I?{resolved:v,element:I,owned:!1,managed:v.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let L=v.action;return L?Os(L)?c(v):l(v,w):null},p=v=>{if(v.detach?.(),v.tooltip?.destroy(),v.detachMenuSlot?.(),v.detachMenuSlot=void 0,v.menuLabel?.remove(),v.menuLabel=void 0,v.menuSlot?.remove(),v.menuSlot=void 0,v.owned){try{v.destroy?.()}catch(w){e.reportError(w,{actionId:v.resolved.id})}v.element.remove()}},f=(v,w)=>{for(let L=0;L<w.length;L++){let I=w[L];if(!I.managed)continue;let Y=null;for(let _=L+1;_<w.length;_++){let q=w[_];if(!q.managed&&q.element.parentElement===v){Y=q.element;break}}Y?(I.element.parentElement!==v||I.element.nextSibling!==Y)&&v.insertBefore(I.element,Y):v.lastChild!==I.element&&v.appendChild(I.element)}},m=(v,w)=>{if(v.button){v.button.disabled=w;return}if(!v.owned)return;let L=v.element;L.toggleAttribute("data-disabled",w),L.setAttribute("aria-disabled",w?"true":"false");let I=L instanceof HTMLButtonElement||L instanceof HTMLSelectElement||L instanceof HTMLInputElement||L instanceof HTMLTextAreaElement?L:L.querySelector("button, select, input, textarea");I&&(I.disabled=w)},g=null,h=null,b=null,x=0,A=()=>{let v=e.getOverflow?.();return v?.enabled===!0?v:void 0},S=()=>(g?g.setLabel(e.getOverflowLabel?.()??"More actions"):g=zS({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),E=v=>{h!==v&&(b?.disconnect(),h=v,x=sh(v),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(w=>{let I=w[w.length-1]?.contentRect?.width??sh(v);I!==x&&(x=I,W())}),b.observe(v)))},k=(v,w)=>{let L=MH(v.collapseAutoActionsBelow,w);if(L===null)return!1;let I=x||sh(w);return I>0&&I<L},D=(v,w,L)=>{if(!w)return"bar";if(v.resolved.builtIn){let Y=AH(v.resolved.id);return Y&&w.includeBuiltIns?.includes(Y)?"menu":"bar"}let I=v.resolved.presentation;return I==="overflow"||I==="auto"&&L?"menu":"bar"},$=v=>{let w=v.menuSlot;if(!w)return;if(!RH(v.element)){v.menuLabel?.remove(),v.menuLabel=void 0;return}let L=PH(v.element);if(!L){v.menuLabel?.remove(),v.menuLabel=void 0;return}v.menuLabel||(v.menuLabel=C("span","persona-composer-overflow-menu__label")),v.menuLabel.textContent!==L&&(v.menuLabel.textContent=L),v.menuLabel.parentElement!==w&&w.appendChild(v.menuLabel)},J=(v,w)=>{if(v.mode===w)return v;let L=v.resolved.action;if(L&&!Os(L)){p(v),t.delete(v.resolved.id);let I=l(v.resolved,w);return t.set(v.resolved.id,I),I}if(w==="menu"){let I=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[yg]:""}});I.appendChild(v.element),ux(ih(v.element)),v.menuSlot=I;let Y=_=>{let q=ih(v.element);if(q.disabled)return;let Z=_.target===q||q.contains(_.target);g?.close(!0),Z||q.click()};I.addEventListener("click",Y,!0),v.detachMenuSlot=()=>I.removeEventListener("click",Y,!0),v.managed=!0,$(v)}else v.detachMenuSlot?.(),v.detachMenuSlot=void 0,v.menuLabel?.remove(),v.menuLabel=void 0,v.menuSlot?.remove(),v.menuSlot=void 0;return v.mode=w,v},T=(v,w)=>{let L=w.map(I=>I.menuSlot??I.element);for(L.forEach((I,Y)=>{let _=v.children[Y];_!==I&&(_?v.insertBefore(I,_):v.appendChild(I))});v.children.length>L.length;)v.lastElementChild?.remove()},W=()=>{if(o)return;let v=e.getBindings();if(!v)return;let w=e.getState(),L=w.phase==="streaming",I=A();I&&E(v.footer);let Y=I?k(I,v.footer):!1,_={start:[],end:[]},q=[];for(let Z of n){let ne=t.get(Z.id);if(!ne)continue;let te=Z.action,re=te?GS(te.visible,w,!0)&&LH(te.visibility,w):!0;if(ne.visible!==re&&(ne.visible=re,!re&&ne.managed&&(ne.menuSlot??ne.element).remove()),!!re){if(ne=J(ne,D(ne,I,Y)),te){let pe=GS(te.disabled,w,!1)||te.disableWhenStreaming===!0&&L;m(ne,pe),!Os(te)&&te.pressed!==void 0&&ne.button?.setAttribute("aria-pressed",te.pressed?"true":"false")}ne.mode==="menu"?($(ne),q.push(ne)):_[Z.placement].push(ne)}}if(q.length>0){let Z=S();T(Z.panel,q),Z.setItems(q.map(pe=>pe.menuSlot??pe.element)),Z.applyButtonSize();let ne=Number.isFinite(I?.order)?I?.order:wr.overflow,te=_.start.findIndex(pe=>pe.resolved.order>ne),re={resolved:{id:SH,placement:"start",presentation:"bar",order:ne,sequence:-1,source:"core"},element:Z.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};_.start.splice(te<0?_.start.length:te,0,re)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));f(v.actionsStart,_.start),f(v.actionsEnd,_.end)};return{resolve:()=>{if(o)return;let v=EH(e.collect()),w=new Set(v.map(L=>L.id));for(let[L,I]of t)w.has(L)||(p(I),t.delete(L));for(let L of v){let I=t.get(L.id);if(!I){let Z=d(L,"bar");Z&&t.set(L.id,Z);continue}let Y=I.resolved.action,_=L.action;if(!!Y!=!!_||Y&&_&&Os(Y)!==Os(_)||Y&&_&&Os(Y)&&Os(_)&&Y.render!==_.render){p(I),t.delete(L.id);let Z=d(L,I.mode);Z&&t.set(L.id,Z);continue}I.resolved=L,L.builtIn?(I.managed=L.builtIn.managed===!0||I.mode==="menu",L.builtIn.element&&I.mode==="bar"&&(I.element=L.builtIn.element)):_&&!Os(_)?i(I,_):_&&I.element.toggleAttribute(rh,_.disableWhenStreaming===!0)}n=v,W()},sync:W,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,b?.disconnect(),b=null,h=null;for(let v of t.values())p(v);t.clear(),g?.destroy(),g=null,n=[]}}}}Ra();Ye();ln();Ws();var WH="core:model",BH=700,XS=16,DH=["--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"],QS=()=>{let e=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function JS(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let d=e.getSelectedModelId();return c.find(p=>p.id===d)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),d="",p=()=>{let b=e.getModels(),x=b.map(A=>`${A.id}:${A.label}`).join("|");x!==d&&(d=x,c.replaceChildren(...b.map(A=>{let S=F("option",{attrs:{value:A.id}});return S.textContent=A.label,S}))),c.value=r(b)?.id??""};p(),o=p;let f=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",f);let m=b=>b.stopPropagation();c.addEventListener("click",m);let{wrapper:g,chevron:h}=QS();return g.append(c,h),{element:g,destroy:()=>{o===p&&(o=null),c.removeEventListener("change",f),c.removeEventListener("click",m)}}},i=()=>{let c=F("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),d=C("span","persona-composer-model-picker-label"),p=C("span","persona-composer-model-picker-suffix");c.append(d,p);let f=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),m=new Map,g="",h=null,b=()=>h?.isOpen===!0,x=(w=!1)=>{b()&&(h?.close(),c.setAttribute("aria-expanded","false"),w&&c.focus())},A=w=>{let L=[...m.values()];if(L.length===0)return;let I=(w%L.length+L.length)%L.length;L[I].focus()},S=w=>{if(b())return;h||(h=Bs({anchor:c,content:f,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Rp(c,f,DH),h.open(),c.setAttribute("aria-expanded","true");let I=[...m.keys()].indexOf(r(e.getModels())?.id??"");A(w??(I>=0?I:0))},E=w=>{x(!0),e.onSelect(w)},k=w=>{w.preventDefault(),w.stopPropagation();let L=w.currentTarget.getAttribute("data-persona-model-option");L&&E(L)},D=w=>{let L=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":w.id}});if(w.icon){let Z=Re(w.icon,XS,"currentColor",1.5);if(Z){let ne=C("span","persona-composer-model-option-icon");ne.appendChild(Z),L.appendChild(ne)}}let I=C("span","persona-composer-model-option-body"),Y=C("span","persona-composer-model-option-label");if(Y.textContent=w.label,I.appendChild(Y),w.description){let Z=C("span","persona-composer-model-option-description");Z.textContent=w.description,I.appendChild(Z)}L.appendChild(I);let _=C("span","persona-composer-model-option-check");_.setAttribute("aria-hidden","true");let q=Re("check",XS,"currentColor",2);return q&&_.appendChild(q),L.appendChild(_),L.addEventListener("click",k),L},$=()=>{let w=e.getModels(),L=w.map(_=>`${_.id}:${_.label}:${_.icon??""}:${_.description??""}`).join("|");if(L!==g){g=L;for(let _ of m.values())_.removeEventListener("click",k);m.clear(),f.replaceChildren(...w.map(_=>{let q=D(_);return m.set(_.id,q),q}))}let I=r(w);for(let[_,q]of m)q.setAttribute("aria-selected",String(_===I?.id));d.textContent=I?.label??"";let Y=e.getSuffix?.()??"";p.textContent=Y,c.setAttribute("aria-label",[t,[I?.label,Y].filter(Boolean).join(" ")].filter(Boolean).join(": "))};$(),o=$;let J=w=>{w.preventDefault(),w.stopPropagation(),b()?x(!0):S()},T=w=>{if(w.key==="ArrowDown"){w.preventDefault(),b()?A(0):S(0);return}w.key==="ArrowUp"&&(w.preventDefault(),b()?A(-1):S(-1))},W=w=>{let L=[...m.values()],I=L.indexOf(w.target?.closest?.(".persona-composer-model-option"));switch(w.key){case"ArrowDown":w.preventDefault(),A(I+1);return;case"ArrowUp":w.preventDefault(),A(I-1);return;case"Home":w.preventDefault(),A(0);return;case"End":w.preventDefault(),A(L.length-1);return;case"Escape":w.preventDefault(),w.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};c.addEventListener("click",J),c.addEventListener("keydown",T),f.addEventListener("keydown",W);let{wrapper:P,chevron:v}=QS();return P.append(c,v),{element:P,destroy:()=>{o===$&&(o=null),c.removeEventListener("click",J),c.removeEventListener("keydown",T),f.removeEventListener("keydown",W);for(let w of m.values())w.removeEventListener("click",k);m.clear(),h?.destroy(),h=null,f.remove()}}};return{action:{id:WH,kind:"custom",placement:"end",order:BH,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ye();ln();$p();var OH=":scope > [data-persona-composer-mode]";function ZS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=d=>{let p=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":d.id}});if(d.iconName){let h=C("span","persona-mention-chip-icon"),b=Re(d.iconName,12,"currentColor",1.5);b&&h.appendChild(b),p.appendChild(h)}let f=C("span","persona-mention-chip-label");f.textContent=d.shortLabel??d.label,p.appendChild(f);let m=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${d.label}`}}),g=Re("x",12,"currentColor",2);return g?m.appendChild(g):m.textContent="\xD7",m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),e.onRemove(d.id)}),p.appendChild(m),p},i=()=>Array.from(t.querySelectorAll(OH)),l=d=>{d.setAttribute("data-persona-chip-exit",""),d.setAttribute("aria-hidden","true"),d.style.pointerEvents="none";let p=()=>{d.remove(),Ha(t)},f=t.ownerDocument.defaultView,m=typeof f?.getComputedStyle=="function"?f.getComputedStyle(d).animationName:"";if(!m||m==="none"){p();return}d.addEventListener("animationend",p,{once:!0}),d.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let d of i())d.remove()};return{element:t,render:(d,p)=>{if(o)return;let f=p.filter(b=>d.includes(b.id)),m=f.map(b=>`${b.id}:${b.shortLabel??b.label}`).join("|");if(m===n)return;n=m;let g=new Map;for(let b of i()){let x=b.getAttribute("data-persona-composer-mode");x&&f.some(S=>S.id===x)&&!b.hasAttribute("data-persona-chip-exit")?g.set(x,b):b.hasAttribute("data-persona-chip-exit")||l(b)}let h=t.firstChild;for(let b of f){let x=g.get(b.id);x||(x=s(b),r.has(b.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(b.id),x!==h&&t.insertBefore(x,h),h=x.nextSibling}Ha(t)},destroy:()=>{o=!0,c(),Ha(t)}}}Ye();ln();var eA=e=>`core:mode:${e}`;var ah=e=>Math.min(300+e,499),tA=e=>`core:mode-group:${e}`;function mu(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function _H(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function nA(e,t){return e?.length?e.filter(n=>!mu(n.groupId,t)&&!_H(n.groupId,t)):[]}var NH=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function oA(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(NH(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 gu(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function rA(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function sA(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var FH=16;function iA(e){let t=null;return{action:{id:tA(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=d=>{d.preventDefault(),d.stopPropagation();let f=d.currentTarget.getAttribute("data-persona-composer-mode");!f||e.getActiveIds().includes(f)&&e.getGroup()?.selection==="single"||e.onSelect(f)},l=d=>{let p=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":d.id,"aria-label":d.label}});if(d.iconName){let m=Re(d.iconName,FH,"currentColor",1.5);m&&p.appendChild(m)}let f=C("span","persona-composer-segmented-label");return f.textContent=d.shortLabel??d.label,p.appendChild(f),p.addEventListener("click",i),p},c=()=>{let d=e.getGroup();d?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",d.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let p=e.getModes(),f=p.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(f!==s){s=f;for(let h of r.values())h.removeEventListener("click",i);r.clear();let g=p.map(h=>{let b=l(h);return r.set(h.id,b),b});o.replaceChildren(...g)}let m=e.getActiveIds();for(let[g,h]of r)h.setAttribute("aria-pressed",String(m.includes(g)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let d of r.values())d.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}$p();Ye();ln();function aA(e){let t=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=C("span","persona-composer-quote-bar"),l=C("div","persona-composer-quote-content");if(s.sourceLabel){let f=C("div","persona-composer-quote-source");f.textContent=s.sourceLabel,l.appendChild(f)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=iu(s.text),l.appendChild(c);let d=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=Re("x",12,"currentColor",2);p?d.appendChild(p):d.textContent="\xD7",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,d)};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()}}}Ye();ln();function lA(e){let t=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,d)=>{let p=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),f=Re(i,12,"currentColor",2);return f?p.appendChild(f):p.textContent=l,p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),d()}),p},s=i=>{let l=iu(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(p=>p.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=C("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=F("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()}}}Ye();function cA(e){let t=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=F("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=C("div","persona-message-edit-actions"),s=(l,c,d,p)=>{let f=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[d]:""},text:l});return f.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),p()}),f},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 dA(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 pA(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 uA(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 fA(e){return e.wrapped||e.text.includes(`
1175
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,c=r.contentParts.length>0;if(l){let d=[];s&&d.push(vr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(c){let d=[];i&&d.push(vr(i)),d.push(...r.contentParts),t.contentParts=d}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.#P||this.#M||this.#v||this.#W)&&await this.#Be(),this.stopSpeaking(),this.abortController?.abort(),this.#he(),this.#ue++,this.#be();let s=n?.voiceTurn?.userMessageId,i=s?this.messages.find(g=>g.id===s&&g.role==="user"):void 0,l=i?.id??bp(),c=Ea();this.#i=null;let d=n?.contentParts&&Cp(n.contentParts)?La:"",p={id:l,role:"user",content:o||d,createdAt:new Date().toISOString(),sequence:this.#Y(),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.#ae(p),this.#H(!0);let f=new AbortController;if(this.abortController=f,n?.mentions){let g=this.messages.find(h=>h.id===l)??p;if(await this.#Qe(g,o,n.mentions.finalize),f.signal.aborted||this.abortController!==f)return;this.callbacks.onMessagesChanged([...this.messages])}if(n?.quote&&!n.replayFields){let g=this.messages.find(b=>b.id===l)??p,h=aS({quote:n.quote,text:g.llmContent??g.content,contentParts:g.contentParts});h.contentParts&&(g.contentParts=h.contentParts),h.llmContent!==void 0&&(g.llmContent=h.llmContent),(h.contentParts||h.llmContent!==void 0)&&(g.quote={...n.quote},this.callbacks.onMessagesChanged([...this.messages]))}let m=i?[...this.messages.filter(g=>g!==i),{...i,createdAt:new Date().toISOString()}]:[...this.messages];try{await this.#Ye(m,f,c,l,{composerOptions:n?.composerOptions,interrupt:n?.interrupt})}catch(g){if(this.status==="resuming"||this.#r)return;this.#U&&(this.#U.failed=!0);let h=g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"));if(!h){let b=nh(g,this.config.errorMessage);if(b){let x={id:c,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.#Y()};this.#ae(x)}}this.#Z("idle"),this.#H(!1),this.abortController=null,h||(g instanceof Error?this.callbacks.onError?.(g):this.callbacks.onError?.(new Error(String(g))))}}resubmitFrom(t,n){let o=lS(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 d=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}},p=s?this.#Je(s.options):r.composerOptions,f=s?s.contentSegments:r.contentSegments,m=s?s.options?.quote:void 0,g=s?s.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,o.start),this.sendMessage(i??"",{...l?.length?{contentParts:[...l]}:{},...f?.length?{contentSegments:[...f]}:{},...p?{composerOptions:p}:{},...m?{quote:m}:{},...d&&Object.keys(d).length>0?{replayFields:d}:{},viaVoice:g===!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.#P||this.#M||this.#v||this.#W)&&await this.#Be(),this.abortController?.abort(),this.#be();let t=Ea();this.#i=null,this.#H(!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=nh(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.#Y()};this.#ae(l)}}this.#Z("idle"),this.#H(!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.#i=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.#H(!0);let s={};try{await this.client.processStream(t,i=>{let l=this.#t;this.#t=s;try{this.handleEvent(i)}finally{this.#t=l}},n?.assistantMessageId,n?.seedContent),this.#Le(s)}catch(i){if(this.status==="resuming"||this.#r){this.#pt(s);return}this.#Le(s),this.#Z("error"),this.webMcpResolveControllers.size===0&&(this.#H(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}#De(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.#l}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}#Ze;#ue;#Se(t){let n=this.#Ze??={s:this,setStreaming:s=>this.#H(s),appendMessage:s=>this.#ae(s),nextSequence:()=>this.#Y(),settleApprovalPausedToolCall:s=>this.#Ne(s),resumeAfter:s=>this.#o?.executionId===s?this.#o.lastEventId:void 0},o=iS();if(o)return t(o,n);let r=this.#ue;return Ug().then(s=>r===this.#ue?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.#p;queueMicrotask(()=>{s===this.#p&&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.#p;queueMicrotask(()=>{if(t===this.#p)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))}#he(){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.#p++}cancel(){this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#H(!1),this.#Z("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.messages=[],this.agentExecution=null,this.#Ee(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H(!1),this.#Z("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.#f}selectArtifact(t){this.#f=t,this.#ye()}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.#f=n,this.#ye(),t.transcript!==!1&&this.#ot(o),o}#ot(t){let n=`artifact-ref-${t.id}`,o=ks(this.config.features?.artifacts,t),r=Il(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=ks(this.config.features?.artifacts,n),s=Il(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.#f===null||(this.artifacts.clear(),this.#f=null,this.#ye())}#ye(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#f})}#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.#f=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.#ye()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.#be(),this.#he(),this.#ue++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.#fe(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.#Y()}))),this.#H(!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.#f=n,this.#ye()}#st(t){let n=this.agentExecution?.executionId;if(!n||!this.#i||this.agentExecution?.status!=="running")return;let o=this.#o===null;this.#o={executionId:n,lastEventId:t,assistantMessageId:this.#i,status:"running"},this.#dt(o)}#it(){return this.#o!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#_e()}#_e(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}#ke(){this.#r||!this.#o||typeof this.config.reconnectStream!="function"||(this.#r=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.#o}),this.#H(!0),this.#Z("resuming"),this.#at().then(t=>{this.#r&&this.#o&&t.begin()}))}#at(){return this.#s?Promise.resolve(this.#s):(this.#g||(this.#g=OS().then(({createReconnectController:t})=>{let n=t(this.#lt());return this.#s=n,n}),this.#g.catch(()=>{this.#g=null})),this.#g)}#lt(){let t=this;return{get config(){return t.config},getResumable:()=>t.#o,clearResumable:()=>t.#Ae(),getStatus:()=>t.status,setStatus:n=>t.#Z(n),setStreaming:n=>t.#H(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.#ae(n),nextSequence:()=>t.#Y(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>nh(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.#r){this.#s?.wake();return}this.#ke()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.#r)return;let n=this.#ct();n||(n=Ea(),this.#ae({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.#Y()})),this.#i=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.#o={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.#ke()}#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}#be(){this.#r=!1,this.#s?.teardown(),this.#Ae()}#Ae(){this.#c&&(clearTimeout(this.#c),this.#c=null);let t=this.#o!==null;this.#o=null,t&&this.config.onExecutionState?.(null)}#dt(t){let n=this.config.onExecutionState;if(n){if(t){this.#c&&(clearTimeout(this.#c),this.#c=null),n(this.#o);return}this.#c||(this.#c=setTimeout(()=>{this.#c=null,this.config.onExecutionState?.(this.#o)},500))}}getResumableHandle(){return this.#o}#Z(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}#H(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&(this.#Le(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=eh(r.content);s.trim()&&this.readAloud.play(r.id,{text:s,voice:n.voice,rate:n.rate,pitch:n.pitch})}static pickBestVoice(t){return jg(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=eh(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()}#Le(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})}#ae(t){let n=this.#we(t);this.messages=this.#fe([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.#we(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.#ae(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 f=r.approval,m=n.approval;i.approval={...f,...m,executionId:m.executionId||f.executionId,toolName:m.toolName||f.toolName,description:m.description||f.description,toolType:m.toolType??f.toolType,reason:m.reason??f.reason,parameters:m.parameters??f.parameters,toolCallId:m.toolCallId??f.toolCallId}}let c=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(c&&_S(c)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let f=`${d}:${p}`,m=this.webMcpInflightKeys.has(f),g=this.webMcpResolvedKeys.has(f),h=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&h!==void 0&&_S(h)&&r.toolCall?.status==="complete";(m||g||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.#fe(this.messages),this.callbacks.onMessagesChanged([...this.messages])}#we(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.#Y()}}#Y(){return this.#n++}#fe(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)})}};Ye();var Fo=require("lucide");io();ln();Rs();var mH={add:e=>Yw(e)},gH=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,fu={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function hH(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yH(e){return e==="application/pdf"?Fo.FileText:e.startsWith("text/")?Fo.FileText:e.includes("word")?Fo.FileText:e.includes("excel")||e.includes("spreadsheet")?Fo.FileSpreadsheet:e==="application/json"?Fo.FileCode:Fo.File}var rc=class e{constructor(t={}){this.attachments=[];this.#e=null;this.#t=new Map;this.#n=!1;this.config={allowedTypes:t.allowedTypes??fu.allowedTypes,maxFileSize:t.maxFileSize??fu.maxFileSize,maxFiles:t.maxFiles??fu.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange,adapter:t.adapter}}#e;#t;#n;#o(){return typeof this.config.adapter?.add=="function"}#i(){return this.#o()?this.config.adapter:mH}setPreviewsContainer(t){this.#e=t}remountPreviews(t){if(this.#e=t,t){t.innerHTML="";for(let n of this.attachments)this.#f(n)}this.#a()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:fu.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.#n)return;let n=[];for(let o of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(o,"count");continue}let r=Xw(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:hH(),file:o,previewUrl:wp(o)?URL.createObjectURL(o):null,contentPart:null,status:this.#o()?"uploading":"processing",progress:this.#o()?0:void 0};this.attachments.push(s),this.#f(s),n.push(s)}this.#a(),this.#c(),await Promise.all(n.map(o=>this.#r(o)))}async#r(t){let n=new AbortController;this.#t.set(t.id,n);let o=()=>this.#n||n.signal.aborted||this.#t.get(t.id)!==n||!this.attachments.includes(t);try{let r=await this.#i().add(t.file,{signal:n.signal,onProgress:s=>{o()||t.status!=="uploading"||(t.progress=gH(s),this.#p(t),this.#c())}});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.#p(t),this.#c()}retryAttachment(t){let n=this.attachments.find(o=>o.id===t);!n||n.status!=="error"||this.#n||(n.status=this.#o()?"uploading":"processing",n.progress=this.#o()?0:void 0,n.error=void 0,this.#p(n),this.#c(),this.#r(n))}#s(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.#s(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.#g(o.contentPart),this.#a(),this.#c()}#g(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.#s(t.id),t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.#t.clear(),this.#e&&(this.#e.innerHTML=""),this.#a(),this.#c()}destroy(){if(!this.#n){this.#n=!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}}#c(){this.#n||this.config.onAttachmentsChange?.(this.getAttachments())}#f(t){if(!this.#e)return;let n=wp(t.file),o=C("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 p=C("img");p.src=t.previewUrl,p.alt=t.file.name,p.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",p.style.width="48px",p.style.height="48px",p.style.objectFit="cover",p.style.borderRadius="8px",o.appendChild(p)}else{let p=C("div");p.style.width="48px",p.style.height="48px",p.style.borderRadius="8px",p.style.backgroundColor="var(--persona-container, #f3f4f6)",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.display="flex",p.style.flexDirection="column",p.style.alignItems="center",p.style.justifyContent="center",p.style.gap="2px",p.style.overflow="hidden";let f=yH(t.file.type),m=Je(f,20,"var(--persona-muted, #6b7280)",1.5);m&&p.appendChild(m);let g=C("span");g.textContent=Qw(t.file.type,t.file.name),g.style.fontSize="8px",g.style.fontWeight="600",g.style.color="var(--persona-muted, #6b7280)",g.style.textTransform="uppercase",g.style.lineHeight="1",p.appendChild(g),o.appendChild(p)}let r=F("div",{className:"persona-attachment-status",attrs:{"data-persona-attachment-status":""}}),s=C("div","persona-attachment-progress");s.appendChild(C("div","persona-attachment-progress__bar"));let i=F("button",{className:"persona-attachment-retry",attrs:{type:"button","aria-label":"Retry upload"}}),l=Re("rotate-cw",12,"var(--persona-text-inverse, #ffffff)",2);l?i.appendChild(l):i.textContent="\u21BB",i.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.retryAttachment(t.id)}),r.append(s,i),o.appendChild(r);let c=C("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 d=Je(Fo.X,10,"var(--persona-text-inverse, #ffffff)",2);d?c.appendChild(d):(c.textContent="\xD7",c.style.color="var(--persona-text-inverse, #ffffff)",c.style.fontSize="14px",c.style.lineHeight="1"),c.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(c),this.#e.appendChild(o),this.#l(o,t)}#p(t){let n=this.#e?.querySelector(`[data-attachment-id="${t.id}"]`);n&&this.#l(n,t)}#l(t,n){t.dataset.status=n.status;let o=n.status!=="ready"&&n.status!=="error";t.setAttribute("aria-busy",o?"true":"false"),t.title=n.status==="error"?`${n.file.name}: ${n.error??"Upload failed"}`:n.file.name;let r=t.querySelector(".persona-attachment-progress__bar");if(r){let s=n.progress;r.style.width=typeof s=="number"?`${Math.round(s*100)}%`:""}}#a(){this.#e&&(this.#e.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n,adapter:t?.adapter})}};var NS=(e,t)=>e.length===t.length&&e.every((n,o)=>n===t[o]),bH=(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 FS(){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 p=s();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(f=>Object.freeze({...f}))),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:p,inputDisabled:e.inputDisabled,sendDisabled:p!=="idle"||e.sendDisabled||e.inputDisabled})},l=()=>(n||(n=i()),n),c=()=>{if(o=!1,r||t.size===0)return;let p=l();for(let f of[...t])try{f(p)}catch(m){typeof console<"u"&&console.error("[AgentWidget] composer state listener failed:",m)}},d=()=>{n=null,!(r||o)&&(o=!0,queueMicrotask(c))};return{getState:l,subscribe:p=>(t.add(p),()=>t.delete(p)),setText:p=>{e.text!==p&&(e.text=p,d())},setAttachments:p=>{bH(e.attachments,p)||(e.attachments=[...p],d())},setMentionRefs:p=>{NS(e.mentionRefs,p)||(e.mentionRefs=[...p],d())},setSelectedModelId:p=>{e.selectedModelId!==p&&(e.selectedModelId=p,d())},setActiveModeIds:p=>{NS(e.activeModeIds,p)||(e.activeModeIds=[...p],d())},setQuote:p=>{let f=e.quote;f?.text===p?.text&&f?.messageId===p?.messageId&&f?.sourceLabel===p?.sourceLabel||(e.quote=p?{...p}:void 0,d())},setPendingSubmission:p=>{e.pendingSubmission!==p&&(e.pendingSubmission=p,d())},setPreparing:p=>{e.preparing!==p&&(e.preparing=p,d())},setStreaming:p=>{e.streaming!==p&&(e.streaming=p,d())},setInputDisabled:p=>{e.inputDisabled!==p&&(e.inputDisabled=p,d())},setSendDisabled:p=>{e.sendDisabled!==p&&(e.sendDisabled=p,d())},flush:()=>{o&&c()},destroy:()=>{r=!0,o=!1,t.clear()}}}Ye();var Co=(e,...t)=>{for(let n of t){let o=e.querySelector(n);if(o)return o}return null},VS=(e,t)=>{let n=C("div",e);return n.setAttribute(t,""),n.setAttribute("data-persona-composer-synthesized",""),n.style.display="contents",n};function $S(e,t={}){let n=Co(e,"[data-persona-composer-form]"),o=Co(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:Co(e,"[data-persona-composer-header]"),body:Co(e,"[data-persona-composer-body]"),actionsStart:Co(e,"[data-persona-composer-actions-start]",".persona-widget-composer__left-actions"),actionsEnd:Co(e,"[data-persona-composer-actions-end]",".persona-widget-composer__right-actions"),actionsRow:Co(e,"[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between"),suggestions:Co(e,"[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2"),status:Co(e,"[data-persona-composer-status]")},s=new Set,i=r.header;i||(s.add("header"),i=VS("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=(x,A,S,E,k)=>{if(A)return A;s.add(x);let D=VS(S,E);return k.appendChild(D),D},d=c("actionsStart",r.actionsStart,"persona-widget-composer__left-actions","data-persona-composer-actions-start",n),p=c("actionsEnd",r.actionsEnd,"persona-widget-composer__right-actions","data-persona-composer-actions-end",n),f=c("suggestions",r.suggestions,"persona-widget-composer__suggestions","data-persona-composer-suggestions",e),m=c("status",r.status,"persona-widget-composer__status","data-persona-composer-status",e),g=[],h=(x,A)=>x.target===A.target&&x.type===A.type&&x.handler===A.handler,b=Co(e,"[data-persona-composer-attachment-input]",'input[type="file"]')??void 0;return{footer:e,form:n,input:o,header:i,body:l,actionsStart:d,actionsEnd:p,suggestions:f,status:m,attachmentInput:b,attachmentPreviews:Co(e,"[data-persona-composer-attachment-previews]",".persona-attachment-previews")??void 0,attachmentButton:Co(e,"[data-persona-composer-attachment-button]",".persona-attachment-button")??void 0,sendButton:Co(e,"[data-persona-composer-submit]")??void 0,micButton:Co(e,"[data-persona-composer-mic]")??void 0,synthesized:s,found:r,addListener:(x,A,S,E)=>{x.addEventListener(A,S,E),g.push({target:x,type:A,handler:S,options:E})},removeListener:(x,A,S,E)=>{x.removeEventListener(A,S,E),g=g.filter(k=>!h(k,{target:x,type:A,handler:S}))},destroy:()=>{for(let x of g)x.target.removeEventListener(x.type,x.handler,x.options);g=[]}}}Ye();ln();Pa();Ws();Ra();Ye();ln();Ws();var vH='button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',CH=["--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"],oh="data-persona-menu-focus",wH=new Set(["ArrowDown","ArrowUp","Home","End"]);function US(e){return e.getAttribute("role")==="menuitem"?e:e.querySelector(vH)??e}var xH=e=>e.disabled===!0||e.getAttribute("aria-disabled")==="true";function zS(e){let t=e.label,n=!1,o=C("div","persona-send-button-wrapper"),r=F("button",{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center persona-cursor-pointer persona-composer-action-button persona-composer-overflow-trigger ${Ao} ${rr}`,attrs:{type:"button","aria-haspopup":"menu","aria-expanded":"false","data-persona-composer-overflow-trigger":""}});o.appendChild(r);let s=F("div",{className:"persona-composer-overflow-menu",attrs:{role:"menu",tabindex:"-1","data-persona-composer-overflow-menu":""}}),i=()=>{let I=e.getButtonSize?.()??"";r.style.width=I,r.style.height=I,r.style.minWidth=I,r.style.minHeight=I,r.style.lineHeight="1",r.replaceChildren();let Y=Re("plus",vo,"currentColor",1.5);Y?r.appendChild(Y):r.textContent="+"},l=()=>{r.setAttribute("aria-label",t),r.setAttribute("title",t),s.setAttribute("aria-label",t)};l(),i();let c=[],d=-1,p=!1,f=()=>{let Y=s.getRootNode().activeElement;return Y instanceof HTMLElement?Y:null},m=()=>{let I=f();for(let Y of c){let _=!!I&&US(Y)===I;Y.toggleAttribute(oh,_&&p)}},g=()=>c.filter(I=>I.isConnected||s.contains(I)).map(US).filter(I=>!xH(I)),h=(I,Y)=>{I.forEach((_,q)=>{_.setAttribute("tabindex",q===Y?"0":"-1")})},b=I=>{let Y=g();if(Y.length===0)return;let _=(I%Y.length+Y.length)%Y.length;d=_,h(Y,_),Y[_].focus(),m()},x=()=>o.ownerDocument??document,A=null,S=null,E=null,k=()=>{A&&(x().removeEventListener("focusin",A,!0),A=null)},D=()=>{S&&(s.removeEventListener("focusin",S),S=null),E&&(s.removeEventListener("pointerdown",E,!0),E=null)},$=null,J=()=>($||($=Bs({anchor:r,content:s,placement:"top-start",offset:6,onDismiss:()=>{r.setAttribute("aria-expanded","false"),k()}})),$),T=()=>$?.isOpen===!0,W=(I=!1)=>{if(T()){$?.close(),r.setAttribute("aria-expanded","false"),k(),D(),d=-1,p=!1;for(let Y of c)Y.removeAttribute(oh);I&&r.focus()}},P=(I=0,Y=!1)=>{if(n||T())return;p=Y,Rp(r,s,CH),J().open(),r.setAttribute("aria-expanded","true");let _=g();h(_,-1),b(I<0?_.length-1:I),A=q=>{let Z=typeof q.composedPath=="function"?q.composedPath():[];Z.includes(s)||Z.includes(o)||W()},x().addEventListener("focusin",A,!0),S=()=>m(),s.addEventListener("focusin",S),E=()=>{p=!1},s.addEventListener("pointerdown",E,!0)},v=I=>{I.preventDefault(),I.stopPropagation(),T()?W(!0):P(0)},w=I=>{if(I.key==="ArrowDown"||I.key==="Enter"||I.key===" "){I.preventDefault(),p=!0,T()?b(0):P(0,!0);return}I.key==="ArrowUp"&&(I.preventDefault(),p=!0,T()?b(-1):P(-1,!0))},L=I=>{switch(wH.has(I.key)&&(p=!0),I.key){case"ArrowDown":I.preventDefault(),b(d+1);return;case"ArrowUp":I.preventDefault(),b(d-1);return;case"Home":I.preventDefault(),b(0);return;case"End":I.preventDefault(),b(g().length-1);return;case"Escape":I.preventDefault(),I.stopPropagation(),W(!0);return;case"Tab":W(!0);return;default:}};return r.addEventListener("click",v),r.addEventListener("keydown",w),s.addEventListener("keydown",L),{trigger:o,triggerButton:r,panel:s,setItems:I=>{for(let _ of c)I.includes(_)||_.removeAttribute(oh);if(c=[...I],!T())return;let Y=g();h(Y,Math.min(d,Y.length-1)),m()},isOpen:T,open:()=>P(0),close:W,setLabel:I=>{I!==t&&(t=I,l())},applyButtonSize:i,destroy:()=>{n=!0,k(),D(),r.removeEventListener("click",v),r.removeEventListener("keydown",w),s.removeEventListener("keydown",L),$?.destroy(),$=null,o.remove(),s.remove(),c=[]}}}var wr={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500},qS="data-persona-composer-action",rh="data-persona-composer-disable-when-streaming",SH="core:overflow",AH=e=>e==="core:attachment"?"attachments":e.startsWith("core:mention")?"mentions":null;function MH(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=C("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 sh(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 jS=(e,t)=>{!e||typeof console>"u"||console.warn(t)},TH=(e,t)=>t.includes(":")?t:`${e}:${t}`;function EH(e){let{debug:t}=e,n=[],o=new Map,r=0,s=l=>{let c=o.get(l.id);if(c){jS(t,`[Persona] composer action "${l.id}" is already contributed by ${KS(c)}; the ${KS(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,d)=>{let p=d?TH(d,l.id):l.id,f=l.order??wr.custom;l.placement==="end"&&f>=wr.send&&(jS(t,`[Persona] composer action "${p}" ordered at ${f} would render after send; clamped to ${wr.send-1}.`),f=wr.send-1),s({id:p,placement:l.placement,presentation:l.presentation??"bar",order:f,sequence:r++,source:c,pluginId:d,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(d){typeof console<"u"&&console.error(`[Persona] plugin "${l.id}" contributeComposerActions failed:`,d);continue}for(let d of c??[])i(d,"plugin",l.id)}return n.sort((l,c)=>l.order===c.order?l.sequence-c.sequence:l.order-c.order)}var KS=e=>e.source==="plugin"?`plugin "${e.pluginId}"`:e.source==="config"?"composer.actions":"a core built-in",GS=(e,t,n)=>e===void 0?n:typeof e=="function"?e(t)===!0:e===!0,kH=e=>e.phase==="streaming"||e.text.trim().length>0||e.attachments.length>0;function LH(e,t){if(!e||e==="always")return!0;let n=kH(t);return e==="when-text"?n:!n}var Os=e=>e.kind==="custom",ih=e=>e instanceof HTMLButtonElement?e:e.querySelector("button")??e,PH=e=>{let t=ih(e);return t.getAttribute("aria-label")?.trim()||t.getAttribute("title")?.trim()||""},IH='.persona-control-tooltip, [role="tooltip"], .persona-sr-only, [hidden], [aria-hidden="true"]';function HH(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(IH)||o.childNodes.forEach(n)};return n(e),t.trim()}var RH=e=>HH(e).length===0;function YS(e){let t=new Map,n=[],o=!1,r=()=>e.getButtonSize?.(),s=(v,w)=>{let L=v.button;if(!L)return;L.setAttribute("role","menuitem"),L.setAttribute("tabindex","-1"),L.className="persona-composer-overflow-menu__item";for(let _ of["width","height","minWidth","minHeight","fontSize","color","backgroundColor"])L.style[_]="";L.style.lineHeight="1",w.tooltipText?L.setAttribute("title",w.tooltipText):L.removeAttribute("title"),L.replaceChildren();let I=C("span","persona-composer-overflow-menu__icon");if(w.iconName){let _=Re(w.iconName,16,"currentColor",1.5);_&&I.appendChild(_)}let Y=C("span","persona-composer-overflow-menu__label");Y.textContent=w.shortLabel??w.label,L.append(I,Y)},i=(v,w)=>{let L=v.button;if(!L)return;if(L.setAttribute("aria-label",w.label),w.pressed===void 0?L.removeAttribute("aria-pressed"):L.setAttribute("aria-pressed",w.pressed?"true":"false"),L.toggleAttribute(rh,w.disableWhenStreaming===!0),v.mode==="menu"){v.tooltip?.destroy(),v.tooltip=void 0,s(v,w);return}L.removeAttribute("role"),L.removeAttribute("tabindex"),L.removeAttribute("title");let I=r(),Y=!!w.shortLabel;if(L.className=Jt("persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-action-button",Ao,rr,Y&&"persona-composer-action-button--text persona-gap-1 persona-text-sm"),L.style.width=I&&!Y?I:"",L.style.height=I??"",L.style.minWidth=I&&!Y?I:"",L.style.minHeight=I??"",L.style.fontSize=Y?"":"18px",L.style.lineHeight="1",L.style.color=w.iconColor??"",L.style.backgroundColor=w.backgroundColor??"",L.replaceChildren(),w.iconName){let _=Re(w.iconName,vo,"currentColor",1.5);_&&L.appendChild(_)}if(Y){let _=C("span","persona-composer-action-button__label");_.textContent=w.shortLabel,L.appendChild(_)}else L.firstChild||(L.textContent=w.label);v.tooltip?.destroy(),v.tooltip=$n({anchor:L,trigger:v.element,text:()=>w.tooltipText??w.label,enabled:!!w.tooltipText})},l=(v,w)=>{let L=v.action,I=F("button",{attrs:{type:"button"}}),Y=I;if(w==="bar"){let Z=C("div","persona-send-button-wrapper");Z.appendChild(I),Y=Z}Y.setAttribute(qS,v.id);let _={resolved:v,element:Y,button:I,owned:!0,managed:!0,busy:!1,visible:!0,mode:w},q=Z=>{if(Z.preventDefault(),Z.stopPropagation(),_.busy||I.disabled)return;let ne=_.resolved.action;_.mode==="menu"&&g?.close(!0);let te;try{te=ne.onSelect(e.actionContext,Z)}catch(re){e.reportError(re,{actionId:_.resolved.id});return}!te||typeof te.then!="function"||(_.busy=!0,I.setAttribute("aria-busy","true"),te.catch(re=>{e.reportError(re,{actionId:_.resolved.id})}).finally(()=>{_.busy=!1,I.removeAttribute("aria-busy")}))};return I.addEventListener("click",q),_.detach=()=>I.removeEventListener("click",q),i(_,L),_},c=v=>{let w=v.action,L;try{L=w.render({...e.actionContext,id:v.id,action:w})}catch(I){return e.reportError(I,{actionId:v.id}),null}return L?.element?(L.element.setAttribute(qS,v.id),L.element.toggleAttribute(rh,w.disableWhenStreaming===!0),{resolved:v,element:L.element,owned:!0,managed:!0,destroy:L.destroy,busy:!1,visible:!0,mode:"bar"}):null},d=(v,w)=>{if(v.builtIn){let I=v.builtIn.element;return I?{resolved:v,element:I,owned:!1,managed:v.builtIn.managed===!0,busy:!1,visible:!0,mode:"bar"}:null}let L=v.action;return L?Os(L)?c(v):l(v,w):null},p=v=>{if(v.detach?.(),v.tooltip?.destroy(),v.detachMenuSlot?.(),v.detachMenuSlot=void 0,v.menuLabel?.remove(),v.menuLabel=void 0,v.menuSlot?.remove(),v.menuSlot=void 0,v.owned){try{v.destroy?.()}catch(w){e.reportError(w,{actionId:v.resolved.id})}v.element.remove()}},f=(v,w)=>{for(let L=0;L<w.length;L++){let I=w[L];if(!I.managed)continue;let Y=null;for(let _=L+1;_<w.length;_++){let q=w[_];if(!q.managed&&q.element.parentElement===v){Y=q.element;break}}Y?(I.element.parentElement!==v||I.element.nextSibling!==Y)&&v.insertBefore(I.element,Y):v.lastChild!==I.element&&v.appendChild(I.element)}},m=(v,w)=>{if(v.button){v.button.disabled=w;return}if(!v.owned)return;let L=v.element;L.toggleAttribute("data-disabled",w),L.setAttribute("aria-disabled",w?"true":"false");let I=L instanceof HTMLButtonElement||L instanceof HTMLSelectElement||L instanceof HTMLInputElement||L instanceof HTMLTextAreaElement?L:L.querySelector("button, select, input, textarea");I&&(I.disabled=w)},g=null,h=null,b=null,x=0,A=()=>{let v=e.getOverflow?.();return v?.enabled===!0?v:void 0},S=()=>(g?g.setLabel(e.getOverflowLabel?.()??"More actions"):g=zS({label:e.getOverflowLabel?.()??"More actions",getButtonSize:r}),g),E=v=>{h!==v&&(b?.disconnect(),h=v,x=sh(v),!(typeof ResizeObserver>"u")&&(b=new ResizeObserver(w=>{let I=w[w.length-1]?.contentRect?.width??sh(v);I!==x&&(x=I,W())}),b.observe(v)))},k=(v,w)=>{let L=MH(v.collapseAutoActionsBelow,w);if(L===null)return!1;let I=x||sh(w);return I>0&&I<L},D=(v,w,L)=>{if(!w)return"bar";if(v.resolved.builtIn){let Y=AH(v.resolved.id);return Y&&w.includeBuiltIns?.includes(Y)?"menu":"bar"}let I=v.resolved.presentation;return I==="overflow"||I==="auto"&&L?"menu":"bar"},$=v=>{let w=v.menuSlot;if(!w)return;if(!RH(v.element)){v.menuLabel?.remove(),v.menuLabel=void 0;return}let L=PH(v.element);if(!L){v.menuLabel?.remove(),v.menuLabel=void 0;return}v.menuLabel||(v.menuLabel=C("span","persona-composer-overflow-menu__label")),v.menuLabel.textContent!==L&&(v.menuLabel.textContent=L),v.menuLabel.parentElement!==w&&w.appendChild(v.menuLabel)},J=(v,w)=>{if(v.mode===w)return v;let L=v.resolved.action;if(L&&!Os(L)){p(v),t.delete(v.resolved.id);let I=l(v.resolved,w);return t.set(v.resolved.id,I),I}if(w==="menu"){let I=F("div",{className:"persona-composer-overflow-menu__slot",attrs:{role:"none",[yg]:""}});I.appendChild(v.element),ux(ih(v.element)),v.menuSlot=I;let Y=_=>{let q=ih(v.element);if(q.disabled)return;let Z=_.target===q||q.contains(_.target);g?.close(!0),Z||q.click()};I.addEventListener("click",Y,!0),v.detachMenuSlot=()=>I.removeEventListener("click",Y,!0),v.managed=!0,$(v)}else v.detachMenuSlot?.(),v.detachMenuSlot=void 0,v.menuLabel?.remove(),v.menuLabel=void 0,v.menuSlot?.remove(),v.menuSlot=void 0;return v.mode=w,v},T=(v,w)=>{let L=w.map(I=>I.menuSlot??I.element);for(L.forEach((I,Y)=>{let _=v.children[Y];_!==I&&(_?v.insertBefore(I,_):v.appendChild(I))});v.children.length>L.length;)v.lastElementChild?.remove()},W=()=>{if(o)return;let v=e.getBindings();if(!v)return;let w=e.getState(),L=w.phase==="streaming",I=A();I&&E(v.footer);let Y=I?k(I,v.footer):!1,_={start:[],end:[]},q=[];for(let Z of n){let ne=t.get(Z.id);if(!ne)continue;let te=Z.action,re=te?GS(te.visible,w,!0)&&LH(te.visibility,w):!0;if(ne.visible!==re&&(ne.visible=re,!re&&ne.managed&&(ne.menuSlot??ne.element).remove()),!!re){if(ne=J(ne,D(ne,I,Y)),te){let pe=GS(te.disabled,w,!1)||te.disableWhenStreaming===!0&&L;m(ne,pe),!Os(te)&&te.pressed!==void 0&&ne.button?.setAttribute("aria-pressed",te.pressed?"true":"false")}ne.mode==="menu"?($(ne),q.push(ne)):_[Z.placement].push(ne)}}if(q.length>0){let Z=S();T(Z.panel,q),Z.setItems(q.map(pe=>pe.menuSlot??pe.element)),Z.applyButtonSize();let ne=Number.isFinite(I?.order)?I?.order:wr.overflow,te=_.start.findIndex(pe=>pe.resolved.order>ne),re={resolved:{id:SH,placement:"start",presentation:"bar",order:ne,sequence:-1,source:"core"},element:Z.trigger,owned:!1,managed:!0,busy:!1,visible:!0,mode:"bar"};_.start.splice(te<0?_.start.length:te,0,re)}else g&&(g.close(),g.trigger.remove(),g.setItems([]));f(v.actionsStart,_.start),f(v.actionsEnd,_.end)};return{resolve:()=>{if(o)return;let v=EH(e.collect()),w=new Set(v.map(L=>L.id));for(let[L,I]of t)w.has(L)||(p(I),t.delete(L));for(let L of v){let I=t.get(L.id);if(!I){let Z=d(L,"bar");Z&&t.set(L.id,Z);continue}let Y=I.resolved.action,_=L.action;if(!!Y!=!!_||Y&&_&&Os(Y)!==Os(_)||Y&&_&&Os(Y)&&Os(_)&&Y.render!==_.render){p(I),t.delete(L.id);let Z=d(L,I.mode);Z&&t.set(L.id,Z);continue}I.resolved=L,L.builtIn?(I.managed=L.builtIn.managed===!0||I.mode==="menu",L.builtIn.element&&I.mode==="bar"&&(I.element=L.builtIn.element)):_&&!Os(_)?i(I,_):_&&I.element.toggleAttribute(rh,_.disableWhenStreaming===!0)}n=v,W()},sync:W,getResolved:()=>n,getOverflowMenu:()=>g,destroy:()=>{if(!o){o=!0,b?.disconnect(),b=null,h=null;for(let v of t.values())p(v);t.clear(),g?.destroy(),g=null,n=[]}}}}Ra();Ye();ln();Ws();var WH="core:model",BH=700,XS=16,DH=["--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"],QS=()=>{let e=F("span",{className:"persona-composer-model-picker-wrapper",attrs:{"data-persona-composer-model-picker-wrapper":""}}),t=F("span",{className:"persona-composer-model-picker-chevron",attrs:{"aria-hidden":"true"}});return{wrapper:e,chevron:t}};function JS(e){let t=e.label??"Model",n=e.presentation??"native",o=null,r=c=>{let d=e.getSelectedModelId();return c.find(p=>p.id===d)??c[0]},s=()=>{let c=F("select",{className:"persona-composer-model-picker",attrs:{"aria-label":t,"data-persona-composer-model-picker":""}}),d="",p=()=>{let b=e.getModels(),x=b.map(A=>`${A.id}:${A.label}`).join("|");x!==d&&(d=x,c.replaceChildren(...b.map(A=>{let S=F("option",{attrs:{value:A.id}});return S.textContent=A.label,S}))),c.value=r(b)?.id??""};p(),o=p;let f=()=>{c.value&&e.onSelect(c.value)};c.addEventListener("change",f);let m=b=>b.stopPropagation();c.addEventListener("click",m);let{wrapper:g,chevron:h}=QS();return g.append(c,h),{element:g,destroy:()=>{o===p&&(o=null),c.removeEventListener("change",f),c.removeEventListener("click",m)}}},i=()=>{let c=F("button",{className:"persona-composer-model-picker persona-composer-model-picker-trigger",attrs:{type:"button","aria-haspopup":"listbox","aria-expanded":"false","data-persona-composer-model-picker":"popover"}}),d=C("span","persona-composer-model-picker-label"),p=C("span","persona-composer-model-picker-suffix");c.append(d,p);let f=F("div",{className:"persona-composer-model-menu",attrs:{role:"listbox",tabindex:"-1","aria-label":t,"data-persona-composer-model-menu":""}}),m=new Map,g="",h=null,b=()=>h?.isOpen===!0,x=(w=!1)=>{b()&&(h?.close(),c.setAttribute("aria-expanded","false"),w&&c.focus())},A=w=>{let L=[...m.values()];if(L.length===0)return;let I=(w%L.length+L.length)%L.length;L[I].focus()},S=w=>{if(b())return;h||(h=Bs({anchor:c,content:f,placement:"top-start",offset:6,onDismiss:()=>c.setAttribute("aria-expanded","false")})),Rp(c,f,DH),h.open(),c.setAttribute("aria-expanded","true");let I=[...m.keys()].indexOf(r(e.getModels())?.id??"");A(w??(I>=0?I:0))},E=w=>{x(!0),e.onSelect(w)},k=w=>{w.preventDefault(),w.stopPropagation();let L=w.currentTarget.getAttribute("data-persona-model-option");L&&E(L)},D=w=>{let L=F("button",{className:"persona-composer-model-option",attrs:{type:"button",role:"option",tabindex:"-1","aria-selected":"false","data-persona-model-option":w.id}});if(w.icon){let Z=Re(w.icon,XS,"currentColor",1.5);if(Z){let ne=C("span","persona-composer-model-option-icon");ne.appendChild(Z),L.appendChild(ne)}}let I=C("span","persona-composer-model-option-body"),Y=C("span","persona-composer-model-option-label");if(Y.textContent=w.label,I.appendChild(Y),w.description){let Z=C("span","persona-composer-model-option-description");Z.textContent=w.description,I.appendChild(Z)}L.appendChild(I);let _=C("span","persona-composer-model-option-check");_.setAttribute("aria-hidden","true");let q=Re("check",XS,"currentColor",2);return q&&_.appendChild(q),L.appendChild(_),L.addEventListener("click",k),L},$=()=>{let w=e.getModels(),L=w.map(_=>`${_.id}:${_.label}:${_.icon??""}:${_.description??""}`).join("|");if(L!==g){g=L;for(let _ of m.values())_.removeEventListener("click",k);m.clear(),f.replaceChildren(...w.map(_=>{let q=D(_);return m.set(_.id,q),q}))}let I=r(w);for(let[_,q]of m)q.setAttribute("aria-selected",String(_===I?.id));d.textContent=I?.label??"";let Y=e.getSuffix?.()??"";p.textContent=Y,c.setAttribute("aria-label",[t,[I?.label,Y].filter(Boolean).join(" ")].filter(Boolean).join(": "))};$(),o=$;let J=w=>{w.preventDefault(),w.stopPropagation(),b()?x(!0):S()},T=w=>{if(w.key==="ArrowDown"){w.preventDefault(),b()?A(0):S(0);return}w.key==="ArrowUp"&&(w.preventDefault(),b()?A(-1):S(-1))},W=w=>{let L=[...m.values()],I=L.indexOf(w.target?.closest?.(".persona-composer-model-option"));switch(w.key){case"ArrowDown":w.preventDefault(),A(I+1);return;case"ArrowUp":w.preventDefault(),A(I-1);return;case"Home":w.preventDefault(),A(0);return;case"End":w.preventDefault(),A(L.length-1);return;case"Escape":w.preventDefault(),w.stopPropagation(),x(!0);return;case"Tab":x(!0);return;default:}};c.addEventListener("click",J),c.addEventListener("keydown",T),f.addEventListener("keydown",W);let{wrapper:P,chevron:v}=QS();return P.append(c,v),{element:P,destroy:()=>{o===$&&(o=null),c.removeEventListener("click",J),c.removeEventListener("keydown",T),f.removeEventListener("keydown",W);for(let w of m.values())w.removeEventListener("click",k);m.clear(),h?.destroy(),h=null,f.remove()}}};return{action:{id:WH,kind:"custom",placement:"end",order:BH,presentation:n==="popover"?"bar":"auto",label:t,render:()=>n==="popover"?i():s()},repaint:()=>o?.()}}Ye();ln();$p();var OH=":scope > [data-persona-composer-mode]";function ZS(e){let t=e.row,n="",o=!1,r=new Set(e.initialIds??[]),s=d=>{let p=F("span",{className:"persona-mention-chip persona-composer-mode-chip",attrs:{"data-persona-composer-mode":d.id}});if(d.iconName){let h=C("span","persona-mention-chip-icon"),b=Re(d.iconName,12,"currentColor",1.5);b&&h.appendChild(b),p.appendChild(h)}let f=C("span","persona-mention-chip-label");f.textContent=d.shortLabel??d.label,p.appendChild(f);let m=F("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${d.label}`}}),g=Re("x",12,"currentColor",2);return g?m.appendChild(g):m.textContent="\xD7",m.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),e.onRemove(d.id)}),p.appendChild(m),p},i=()=>Array.from(t.querySelectorAll(OH)),l=d=>{d.setAttribute("data-persona-chip-exit",""),d.setAttribute("aria-hidden","true"),d.style.pointerEvents="none";let p=()=>{d.remove(),Ha(t)},f=t.ownerDocument.defaultView,m=typeof f?.getComputedStyle=="function"?f.getComputedStyle(d).animationName:"";if(!m||m==="none"){p();return}d.addEventListener("animationend",p,{once:!0}),d.addEventListener("animationcancel",p,{once:!0})},c=()=>{for(let d of i())d.remove()};return{element:t,render:(d,p)=>{if(o)return;let f=p.filter(b=>d.includes(b.id)),m=f.map(b=>`${b.id}:${b.shortLabel??b.label}`).join("|");if(m===n)return;n=m;let g=new Map;for(let b of i()){let x=b.getAttribute("data-persona-composer-mode");x&&f.some(S=>S.id===x)&&!b.hasAttribute("data-persona-chip-exit")?g.set(x,b):b.hasAttribute("data-persona-chip-exit")||l(b)}let h=t.firstChild;for(let b of f){let x=g.get(b.id);x||(x=s(b),r.has(b.id)||(x.setAttribute("data-persona-chip-enter",""),x.addEventListener("animationend",()=>x?.removeAttribute("data-persona-chip-enter"),{once:!0}))),r.delete(b.id),x!==h&&t.insertBefore(x,h),h=x.nextSibling}Ha(t)},destroy:()=>{o=!0,c(),Ha(t)}}}Ye();ln();var eA=e=>`core:mode:${e}`;var ah=e=>Math.min(300+e,499),tA=e=>`core:mode-group:${e}`;function mu(e,t){return e?t?.find(n=>n.id===e)?.presentation==="segmented":!1}function _H(e,t){return e?t?.find(n=>n.id===e)?.chipVisibility==="hidden":!1}function nA(e,t){return e?.length?e.filter(n=>!mu(n.groupId,t)&&!_H(n.groupId,t)):[]}var NH=(e,t)=>e.groupId?t?.find(n=>n.id===e.groupId)?.selection??null:null;function oA(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(NH(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 gu(e,t){return t?.length?t.filter(n=>e.includes(n.id)).map(n=>n.id):[]}function rA(e,t){return t?.length?t.filter(n=>e.includes(n.id)&&(n.persistence??"sticky")!=="once").map(n=>n.id):[]}function sA(e,t){if(!(!t?.length||e.length===0))return t.find(n=>e.includes(n.id)&&n.placeholder)?.placeholder}var FH=16;function iA(e){let t=null;return{action:{id:tA(e.groupId),kind:"custom",placement:"start",presentation:"bar",label:e.getGroup()?.label??e.groupId,render:()=>{let o=F("div",{className:"persona-composer-segmented",attrs:{"data-persona-composer-mode-group":e.groupId}}),r=new Map,s="",i=d=>{d.preventDefault(),d.stopPropagation();let f=d.currentTarget.getAttribute("data-persona-composer-mode");!f||e.getActiveIds().includes(f)&&e.getGroup()?.selection==="single"||e.onSelect(f)},l=d=>{let p=F("button",{className:"persona-composer-segmented-item",attrs:{type:"button","data-persona-composer-mode":d.id,"aria-label":d.label}});if(d.iconName){let m=Re(d.iconName,FH,"currentColor",1.5);m&&p.appendChild(m)}let f=C("span","persona-composer-segmented-label");return f.textContent=d.shortLabel??d.label,p.appendChild(f),p.addEventListener("click",i),p},c=()=>{let d=e.getGroup();d?.label?(o.setAttribute("role","group"),o.setAttribute("aria-label",d.label)):(o.removeAttribute("role"),o.removeAttribute("aria-label"));let p=e.getModes(),f=p.map(g=>`${g.id}:${g.shortLabel??g.label}:${g.iconName??""}`).join("|");if(f!==s){s=f;for(let h of r.values())h.removeEventListener("click",i);r.clear();let g=p.map(h=>{let b=l(h);return r.set(h.id,b),b});o.replaceChildren(...g)}let m=e.getActiveIds();for(let[g,h]of r)h.setAttribute("aria-pressed",String(m.includes(g)))};return c(),t=c,{element:o,destroy:()=>{t===c&&(t=null);for(let d of r.values())d.removeEventListener("click",i);r.clear()}}}},repaint:()=>t?.()}}$p();Ye();ln();function aA(e){let t=F("div",{className:"persona-composer-quote",attrs:{"data-persona-composer-quote":""}});t.style.display="none";let n="",o=!1,r=s=>{let i=C("span","persona-composer-quote-bar"),l=C("div","persona-composer-quote-content");if(s.sourceLabel){let f=C("div","persona-composer-quote-source");f.textContent=s.sourceLabel,l.appendChild(f)}let c=F("div",{className:"persona-composer-quote-text",attrs:{"data-persona-composer-quote-text":""}});c.textContent=iu(s.text),l.appendChild(c);let d=F("button",{className:"persona-composer-quote-dismiss",attrs:{type:"button","aria-label":e.dismissLabel??"Remove quote","data-persona-composer-quote-dismiss":""}}),p=Re("x",12,"currentColor",2);p?d.appendChild(p):d.textContent="\xD7",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),e.onDismiss()}),t.replaceChildren(i,l,d)};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()}}}Ye();ln();function lA(e){let t=F("div",{className:"persona-composer-pending",attrs:{"data-persona-composer-pending":""}});t.style.display="none";let n,o=!1,r=(i,l,c,d)=>{let p=F("button",{className:"persona-composer-pending-action",attrs:{type:"button","aria-label":l,[c]:""}}),f=Re(i,12,"currentColor",2);return f?p.appendChild(f):p.textContent=l,p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),d()}),p},s=i=>{let l=iu(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(p=>p.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=C("span","persona-composer-pending-badge");l.textContent=e.label??"Sends next";let c=F("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()}}}Ye();function cA(e){let t=F("div",{className:"persona-message-edit",attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":""}}),n=F("textarea",{className:"persona-message-edit-input",attrs:{rows:"1",dir:"auto","aria-label":"Edit message","data-persona-message-edit-input":""}});n.value=e.initialText;let o=()=>{n.style.height="auto",n.style.height=`${n.scrollHeight}px`};n.addEventListener("input",o);let r=C("div","persona-message-edit-actions"),s=(l,c,d,p)=>{let f=F("button",{className:`persona-message-edit-button ${c}`,attrs:{type:"button",[d]:""},text:l});return f.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),p()}),f},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 dA(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 pA(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 uA(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 fA(e){return e.wrapped||e.text.includes(`
1176
1176
  `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function mA(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function gA(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}Xp();Hp();function lh(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 yA(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}var VH=e=>typeof e?.then=="function";function hA(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 bA(e,t,n){let o;try{o=e(lh(t),{signal:n})}catch(r){return{status:"error",error:r}}return VH(o)?Promise.resolve(o).then(r=>n.aborted?{status:"aborted"}:hA(t,r),r=>n.aborted?{status:"aborted"}:{status:"error",error:r}):hA(t,o)}Pg();Ng();Sg();Rs();var hu=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?"circle":"pill"),yu={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"};er();er();var vu="16px",Cu="transparent",$H=(()=>{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})(),sc={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:$H,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"}},bu={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"}},Mo={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:Nm,maxWidth:"none",height:"min(640px, max(200px, calc(100vh - 64px)))",maxHeight:"none",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:vu,canvasBackground:Cu,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"}}},UH=sc.colors.gray,zH={50:"#fafafa",100:"#f5f5f5",200:"#e5e5e5",300:"#d4d4d4",400:"#a3a3a3",500:"#737373",600:"#525252",700:"#404040",800:"#262626",900:"#171717",950:"#0a0a0a"},qH={...sc,colors:{...sc.colors,gray:UH}},jH={...sc,colors:{...sc.colors,gray:zH},radius:{none:"0px",sm:"4px",md:"8px",lg:"12px",xl:"16px","2xl":"24px",full:"9999px"}};var KH=bu,GH={...bu,colors:{...bu.colors,surface:"#ffffff",background:"#ffffff",container:"semantic.colors.surface",textInverse:"#ffffff"},typography:{...bu.typography,fontSize:"14px",lineHeight:"1.5"}};var dh=Mo,YH={...Mo,launcher:yu,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:{...Mo.input,borderRadius:"palette.radius.full"},introCard:{...Mo.introCard,title:{fontSize:"22px",fontWeight:"500"}},suggestion:{chip:{...Mo.suggestion.chip,fontWeight:"400"},card:{...Mo.suggestion.card,fontWeight:"400"},list:{...Mo.suggestion.list,fontWeight:"400"}},panel:{...Mo.panel,width:"min(400px, calc(100vw - 24px))",height:"min(704px, calc(100dvh - 104px))",borderRadius:"palette.radius.xl"},header:{...Mo.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:{...Mo.message,gap:"20px",fullscreenGap:"28px",topFadeHeight:"18px",user:{...Mo.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:{...Mo.message.assistant,background:"transparent",border:"transparent",borderWidth:"0px",borderRadius:"0px",shadow:"none",padding:"0px",fontSize:"14px",lineHeight:"1.55"}},composer:{...Mo.composer,padding:"8px",fontSize:"15px",lineHeight:"1.5",controlSize:"32px",controlIconSize:"20px",sendIconSize:"18px",sendButtonRadius:"9999px",footerBorder:"none",overlayBand:"linear-gradient(to bottom, transparent, var(--persona-container) 24px)",focusBorderColor:"color-mix(in srgb, var(--persona-text) 28%, var(--persona-border))",focusRing:"1px solid color-mix(in srgb, var(--persona-text) 12%, transparent)"}};var XH=e=>Ts({future:e}),ph=e=>XH(e)==="v5"?{palette:jH,semantic:GH,components:YH}:{palette:qH,semantic:KH,components:dh};function zn(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."))?zn(e,o):o}function CA(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=zn(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 QH(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 wA(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]=wA(s,r):n[o]=r}return n}function JH(e,t){return t?wA(e,t):e}function Oa(e,t={}){let n=ph(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:JH(o.components,e?.components)},s=e?.components?.activity;for(let d of["toolBubble","reasoningBubble"])for(let p of["rowHeight","labelSize","iconSize","indent","bodySurface"])s?.[p]!==void 0&&(r.components[d][p]=s[p]);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 d=QH(r);if(!d.valid)throw new Error(`Theme validation failed: ${d.errors.map(p=>p.message).join(", ")}`)}if(t.plugins)for(let d of t.plugins)r=d.transform(r);return r}var ch=e=>e.trim()==="0"?"0px":e,vA="--persona-",ZH=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 d=c.endsWith("%"),p=parseFloat(d?c.slice(0,-1):c);return d?p/100*255:p}))}}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},eR=.179,Un=(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[vA+s],r!==void 0)break;r!==void 0&&(e[vA+n]=r)}};function xA(e){let t=CA(e),n={};for(let[N,Ee]of Object.entries(t)){let de=N.replace(/\./g,"-");n[`--persona-${de}`]=Ee.value}Un(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"],Un(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"]]),Un(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"]}`,Un(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"]??vu,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Cu,Un(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"]]),Un(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"],Un(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"],Un(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 d=n["--persona-components-history-railHeader-border"];d&&(n["--persona-history-rail-header-border"]=d);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[N,Ee]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${N}`];de&&(n[`--persona-history-overlay-${Ee}`]=de)}for(let[N,Ee]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${N}`];de&&(n[`--persona-history-menu-${Ee}`]=de)}let f=e.components?.history?.motion;if(f){let N=Ge=>{if(Ge===void 0)return;let Pt=String(Ge).trim();return/^\d+(\.\d+)?$/.test(Pt)?`${Pt}ms`:Pt},Ee=N(f.enterDurationMs);Ee!==void 0&&(n["--persona-history-enter-ms"]=Ee);let de=N(f.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),f.enterEasing&&(n["--persona-history-enter-easing"]=f.enterEasing),f.exitEasing&&(n["--persona-history-exit-easing"]=f.exitEasing)}let m=n["--persona-components-history-dangerForeground"];m&&(n["--persona-history-danger-fg"]=m),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 N of["scrim","shadow"]){let Ee=n[`--persona-components-history-confirm-${N}`];Ee&&(n[`--persona-history-confirm-${N}`]=Ee)}for(let[N,Ee]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${N}`];de&&(n[`--persona-tooltip-${Ee}`]=de)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[N,Ee]of[["background","bg"],["border","border"],["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${N}`];de&&(n[`--persona-message-action-${Ee}`]=de)}Un(n,[["intro-card-bg","components-introCard-background","=transparent"],["intro-card-radius","components-introCard-borderRadius","=1rem"]]);let g=n["--persona-components-introCard-background"],h=n["--persona-components-introCard-shadow"],b=(!g||g==="transparent"||g==="none")&&(!h||h==="none"),x=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=b&&x==="1.5rem"?"1.5rem 0":x,Un(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"]]),Un(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 S=n["--persona-components-markdown-heading-h1-fontWeight"];S&&(n["--persona-md-h1-weight"]=S);let E=n["--persona-components-markdown-heading-h2-fontSize"];E&&(n["--persona-md-h2-size"]=E);let k=n["--persona-components-markdown-heading-h2-fontWeight"];k&&(n["--persona-md-h2-weight"]=k);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),Un(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"]]),Un(n,[["md-code-block-border-radius","components-markdown-codeBlock-borderRadius","radius-md","=0.375rem"]]),Un(n,[["md-table-header-bg","components-markdown-table-headerBackground","container"],["md-table-border-color","components-markdown-table-borderColor","border"]]),Un(n,[["md-hr-color","components-markdown-hr-color","divider"]]),Un(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 $=[["container","surface"],["surface","surface"],["border","border"]];for(let[N,Ee]of $){let de=n[`--persona-components-collapsibleWidget-${N}`]??n[`--persona-${Ee}`];de!==void 0&&(n[`--persona-cw-${N}`]=de,n[`--cw-${N}`]=de)}Un(n,[["message-border","components-message-border","border"]]),Un(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 J=e.components,T=J?.iconButton;T&&(T.background&&(n["--persona-icon-btn-bg"]=T.background),T.border&&(n["--persona-icon-btn-border"]=T.border),T.color&&(n["--persona-icon-btn-color"]=T.color),T.padding&&(n["--persona-icon-btn-padding"]=T.padding),T.borderRadius&&(n["--persona-icon-btn-radius"]=T.borderRadius),T.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=T.hoverBackground),T.hoverColor&&(n["--persona-icon-btn-hover-color"]=T.hoverColor),T.activeBackground&&(n["--persona-icon-btn-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-icon-btn-active-border"]=T.activeBorder));let W=J?.labelButton;W&&(W.background&&(n["--persona-label-btn-bg"]=W.background),W.border&&(n["--persona-label-btn-border"]=W.border),W.color&&(n["--persona-label-btn-color"]=W.color),W.padding&&(n["--persona-label-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-label-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-label-btn-hover-bg"]=W.hoverBackground),W.fontSize&&(n["--persona-label-btn-font-size"]=W.fontSize),W.gap&&(n["--persona-label-btn-gap"]=W.gap));let P=J?.toggleGroup;P&&(P.gap&&(n["--persona-toggle-group-gap"]=P.gap),P.borderRadius&&(n["--persona-toggle-group-radius"]=P.borderRadius));let v=J?.artifact;if(v?.toolbar){let N=v.toolbar;N.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=N.iconHoverColor),N.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=N.iconHoverBackground),N.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=N.iconPadding),N.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=N.iconBorderRadius),N.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=N.iconBorder),N.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ch(N.toggleGroupGap)),N.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=N.toggleBorderRadius),N.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=ch(N.toggleGroupPadding)),N.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=N.toggleGroupBorder),N.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=N.toggleGroupBorderRadius),N.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=zn(e,N.toggleGroupBackground)??N.toggleGroupBackground),N.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=N.copyBackground),N.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=N.copyBorder),N.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=N.copyColor),N.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ch(N.copyBorderRadius)),N.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=N.copyPadding),N.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=N.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??N.copyMenuBackground),N.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=N.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??N.copyMenuBorder),N.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=N.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??N.copyMenuShadow),N.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=N.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??N.copyMenuBorderRadius),N.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=N.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??N.copyMenuItemHoverBackground),N.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=N.iconBackground),N.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=N.toolbarBorder)}if(v?.tab){let N=v.tab;N.background&&(n["--persona-artifact-tab-bg"]=N.background),N.activeBackground&&(n["--persona-artifact-tab-active-bg"]=N.activeBackground),N.activeBorder&&(n["--persona-artifact-tab-active-border"]=N.activeBorder),N.borderRadius&&(n["--persona-artifact-tab-radius"]=N.borderRadius),N.textColor&&(n["--persona-artifact-tab-color"]=N.textColor),N.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=N.hoverBackground),N.listBackground&&(n["--persona-artifact-tab-list-bg"]=N.listBackground),N.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=N.listBorderColor),N.listPadding&&(n["--persona-artifact-tab-list-padding"]=N.listPadding)}if(v?.pane){let N=v.pane;if(N.toolbarBackground){let Ee=zn(e,N.toolbarBackground)??N.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ee}}if(v?.card){let N=v.card;N.background&&(n["--persona-artifact-card-bg"]=N.background),N.border&&(n["--persona-artifact-card-border"]=N.border),N.borderRadius&&(n["--persona-artifact-card-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=N.hoverBackground),N.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=N.hoverBorderColor)}if(v?.inline){let N=v.inline;N.background&&(n["--persona-artifact-inline-bg"]=zn(e,N.background)??N.background),N.border&&(n["--persona-artifact-inline-border"]=N.border),N.borderRadius&&(n["--persona-artifact-inline-radius"]=N.borderRadius),N.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=zn(e,N.chromeBackground)??N.chromeBackground),N.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=zn(e,N.chromeBorder)??N.chromeBorder),N.titleColor&&(n["--persona-artifact-inline-title-color"]=zn(e,N.titleColor)??N.titleColor),N.mutedColor&&(n["--persona-artifact-inline-muted-color"]=zn(e,N.mutedColor)??N.mutedColor),N.frameHeight&&(n["--persona-artifact-inline-frame-height"]=N.frameHeight)}let w=J?.code;w&&(w.keywordColor&&(n["--persona-code-keyword-color"]=w.keywordColor),w.stringColor&&(n["--persona-code-string-color"]=w.stringColor),w.commentColor&&(n["--persona-code-comment-color"]=w.commentColor),w.numberColor&&(n["--persona-code-number-color"]=w.numberColor),w.tagColor&&(n["--persona-code-tag-color"]=w.tagColor),w.attrColor&&(n["--persona-code-attr-color"]=w.attrColor),w.propertyColor&&(n["--persona-code-property-color"]=w.propertyColor),w.lineNumberColor&&(n["--persona-code-line-number-color"]=w.lineNumberColor),w.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=w.gutterBorderColor),w.background&&(n["--persona-code-bg"]=zn(e,w.background)??w.background));let L=n["--persona-surface"],I=n["--persona-container"],Y=n["--persona-palette-colors-gray-100"]??"#f3f4f6",_=n["--persona-palette-colors-gray-200"]??"#e5e7eb",q=n["--persona-palette-colors-gray-300"]??"#d1d5db",Z=!I||I===L,ne=ZH(L??n["--persona-background"]),te=Z&&ne!==void 0&&ne<eR,re=te?"rgba(255, 255, 255, 0.08)":Y,pe=te?"rgba(255, 255, 255, 0.12)":_,xe=te?"rgba(255, 255, 255, 0.16)":q,Se=Z?re:I,se=Z?pe:I;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??Se,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??se,Z&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??xe),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??Se,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??Se,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??Se,n}Nd();var tR=e=>!!e&&"launcher"in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode==="docked"),SA=(e,t)=>{if(!t||!tR(t))return e;let n=t.theme?.components?.panel?.width,o=t.darkTheme?.components?.panel?.width;return(ac(t)==="dark"?o??n:n)!=null?e:{...e,components:{...e.components,panel:{...e.components.panel,width:Ts(t)==="v5"?"400px":"420px"}}}},nR={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"}}},ic={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)"}}}},uh=nR,oR={...uh,colors:{...uh.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"}}},rR=ic,sR={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:{...ic.components,button:{...ic.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:{...ic.components?.eventStream,badge:{...ic.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"}}}}},iR=e=>Ts({future:e})==="v5"?{palette:oR,components:sR}:{palette:uh,components:rR},AA=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},fh=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",aR=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":fh()},ac=e=>aR(e),lR=(e,t={})=>Oa(e,t),cR=(e,t={})=>{let n=iR(t.future),o=Zo(n.components,e??{})??{};return Oa({...o,palette:{...o.palette,colors:Ts(t)==="v5"?Zo(n.palette.colors,o.palette?.colors):{...n.palette.colors,...o.palette?.colors}}},{validate:!1,future:t.future})},Jr=e=>{let t=ac(e),n=AA(e?.theme),o=hu(e)==="circle"?yu:{...dh.launcher,...e?.future?.v5Defaults?{offset:"1.5rem"}:{}},r=Zo({components:{launcher:o}},n),s=AA(e?.darkTheme);return SA(t==="dark"?cR(Zo(r??{},s??{}),{future:e?.future}):lR(r,{future:e?.future}),e)},dR=e=>xA(e),lc=(e,t)=>{let n=Jr(t),o=dR(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",ac(t)),e.setAttribute("data-persona-defaults",Ts(t))},wu=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(fh())});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(fh());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())}};Nd();var rs=require("lucide");ln();io();Ye();var _s=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var xu="24px",mh=(e,t)=>t||e?.composer?.placement!=="overlay"?"block":"overlay",cc=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},MA=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight);Pa();$d();Tu();var LA=require("idiomorph"),Eu=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;LA.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 PA=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var hh={index:-1,draft:""};function IA(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 HA(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 RA(){return new Map}function WA(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function BA(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function DA(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}bh();nr();hc();Bn();var{setLoader:RV,load:NR}=Wt({fallbackImport:()=>Promise.resolve().then(()=>(sM(),rM))});var iM=NR;nr();function Ah(e,t=Jn){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 bc=0,Ns=null;function Mh(e=document){if(bc++,bc===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ns={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,bc=Math.max(0,bc-1),bc===0&&Ns)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ns.originalOverflow,n.style.position=Ns.originalPosition,n.style.top=Ns.originalTop,n.style.width=Ns.originalWidth,o.scrollTo(0,Ns.scrollY),Ns=null}}}ha();var vc={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},un=e=>(e?.launcher?.mountMode??"floating")==="docked",Cc=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Vo=e=>{let t=e?.launcher?.dock,n=Ur(e).dockWidth?t?.width:zn(Jr(e),"components.panel.width");return{side:t?.side??vc.side,width:n??vc.width,animate:t?.animate??vc.animate,reveal:t?.reveal??vc.reveal,maxHeight:t?.maxHeight??vc.maxHeight}};Ye();Ye();var lM=require("lucide");ln();io();var Th=e=>e==="followUp"?"follow-up":e,Eh=(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"}},aM=new WeakSet,FR=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,VR=e=>{FR()||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"})})},kh=e=>{let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:c,chipsConfig:d,session:p,getTextarea:f,eventTarget:m,submitPrompt:g}=e,h=o==="followUp",b=t.behavior,x=()=>{if(p.isStreaming())return;let E={suggestion:{...t},surface:o,source:r,behavior:b},k=m.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:E,bubbles:!0,composed:!0,cancelable:!0}));if(h&&m.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!k)return;for(let $ of c)if($.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let D=f();if(b==="fill"){D.value=t.prompt,D.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),D.focus();return}if(g){g(t.prompt);return}D.value="",p.sendMessage(t.prompt)},A=()=>{let E=C("button",`persona-suggestion persona-suggestion--${s}`);if(E.type="button",E.disabled=i,E.dataset.suggestionId=t.id,E.dataset.emphasis=t.emphasis,E.dataset.behavior=b,s==="chip"&&(d?.fontWeight&&(E.style.fontWeight=d.fontWeight),d?.paddingX&&(E.style.paddingLeft=d.paddingX,E.style.paddingRight=d.paddingX),d?.paddingY&&(E.style.paddingTop=d.paddingY,E.style.paddingBottom=d.paddingY)),t.icon){let D=Re(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);D&&(D.classList.add("persona-suggestion__icon"),t.iconColor&&(D.style.color=t.iconColor),E.appendChild(D))}let k=C("span","persona-suggestion__copy");if(k.appendChild(F("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&k.appendChild(F("span",{className:"persona-suggestion__description",text:t.description})),E.appendChild(k),s!=="chip"){let D=Je(lM.ArrowRight,16,"currentColor",1.8);D&&(D.classList.add("persona-suggestion__arrow"),E.appendChild(D))}return E.addEventListener("click",x),E},S=null;for(let E of c)if(E.renderSuggestion&&(S=E.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:A,select:x}),S))break;return S??=A(),S.dataset.suggestionId||=t.id,S.dataset.behavior||=b,S.dataset.emphasis||=t.emphasis,S instanceof HTMLButtonElement||S.setAttribute("aria-disabled",i?"true":"false"),S},wc=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 p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){s();return}let f=getComputedStyle(e).direction==="rtl",m=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),g=4,h=m<=g,b=m>=p-g,x=f?!b:!h,A=f?!h:!b;e.toggleAttribute("data-scroll-left",x),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:(p,f,m,g,h,b)=>{e.replaceChildren(),t.length=0,n.length=0;let x=b?.source??"config",A=b?.surface??(x==="config"?"starter":"followUp"),S=A==="followUp",E=b?.variant??"chip",k=b?.behavior??"send",D=b?.overflow??"wrap",$=b?.config??{},J=b?.plugins??[],T=typeof b?.maxItems=="number"?Math.max(0,Math.floor(b.maxItems)):void 0,W=S?"followUps":"starters";!aM.has($)&&$.debug===!0&&E!=="chip"&&$.suggestions?.[W]?.overflow!==void 0&&(aM.add($),console.info(`[persona] suggestions.${W}.overflow applies to the "chip" variant only; the "${E}" variant manages its own stacking.`));let P=_=>_.map(Eh).filter(q=>q!==null).map(q=>({...q,behavior:q.behavior??k})),v=P(p??[]);J.forEach(_=>{_.transformSuggestions&&(v=P(_.transformSuggestions({suggestions:v.map(q=>({...q})),surface:A,source:x,config:$})))});let w=T===void 0?v:v.slice(0,T);if(!w.length){e.hidden=!0,o=null,s();return}if(!S&&(g??f.getMessages()).some(q=>q.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Th(A),e.dataset.variant=E,e.dataset.overflow=D;let L=document.createDocumentFragment(),I=f.isStreaming();w.forEach((_,q)=>{let Z=kh({item:_,index:q,surface:A,source:x,variant:E,streaming:I,config:$,plugins:J,chipsConfig:h,session:f,getTextarea:()=>m,eventTarget:e,submitPrompt:b?.submitPrompt});L.appendChild(Z),n.push(Z),[...Z instanceof HTMLButtonElement?[Z]:[],...Array.from(Z.querySelectorAll("button"))].forEach(te=>{t.includes(te)||(te.disabled=I,t.push(te))})}),e.appendChild(L),i(),l();let Y=JSON.stringify({normalized:w,surface:A,variant:E,source:x});Y!==o&&(o=Y,VR(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:w.map(_=>({..._})),surface:A,source:x,variant:E},bubbles:!0,composed:!0})),S&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:w.map(_=>_.prompt)},bubbles:!0,composed:!0})))}}};var To={"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"};nr();Ye();ln();er();Ye();ln();Pa();var $R="persona-header-control",UR="persona-header-control--glyph",zR="persona-header-control--sparse",qR=20,jR={x:[1.4,1.05]},cM="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",KR="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Wu=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=jR[t]??[1,1.5],l=!o;e.classList.toggle(UR,l),e.classList.toggle(zR,l&&s!==1);let c=parseFloat(o??"")||qR,d=Re(t,`${Math.round(c*s)}px`,"currentColor",i);d?(d.style.display="block",l||(d.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(d)):r&&(e.textContent=r)},Na=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=cM,size:l,iconSize:c,color:d,backgroundColor:p,borderWidth:f,borderColor:m,borderRadius:g,paddingX:h,paddingY:b,hidden:x,extraClassName:A,attrs:S}=e,E=C("div",i),k=!!(f||m),D=F("button",{className:Jt($R,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!k&&"persona-border-none",!g&&"persona-rounded-full",A),attrs:{type:"button","aria-label":t,...S},style:{width:l,height:l,minWidth:l,minHeight:l,display:x?"none":void 0,color:d||lo.actionIconColor,backgroundColor:p,border:k?`${f||"0px"} solid ${m||"transparent"}`:void 0,borderRadius:g,paddingLeft:h,paddingRight:h,paddingTop:b,paddingBottom:b}});return r?Wu(D,r,{iconSize:c,iconText:s}):s&&(D.textContent=s),E.appendChild(D),$n({anchor:D,trigger:E,text:()=>D.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:D,wrapper:E}},Fa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=cM,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",c=i.closeButtonShowTooltip??!0,{button:d,wrapper:p}=Na({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:d,wrapper:p}},Va=(e,t={})=>{let{wrapperClassName:n=KR,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",c=i.showTooltip??!0,{button:d,wrapper:p}=Na({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:d,wrapper:p}};var lo={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)"},Lh={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)"},GR={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)"},Ii=e=>{let{config:t,showClose:n=!0}=e,o=F("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3",attrs:{"data-persona-theme-zone":"header"},style:{padding:"var(--persona-components-header-padding, 20px 24px)",minHeight:lo.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??Ll,i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,c=r.headerIconName,d=F("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(c){let D=parseFloat(s)||24,$=Re(c,D*.6,"currentColor",1);$?($.style.width=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,$.style.height=`calc(${D}px * var(--persona-components-header-iconScale, 0.6))`,d.replaceChildren($)):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let D=C("img");D.src=t.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,d.replaceChildren(D)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=C("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=F("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:lo.titleColor,...Lh}}),m=F("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:lo.subtitleColor,...GR}});p.append(f,m),l?o.append(p):o.append(d,p);let g=r.clearChat??{},h=g.enabled??!0,b=g.placement??"inline",x=null,A=null;if(h){let $=Va(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});x=$.button,A=$.wrapper,b==="top-right"&&(A.style.right="48px"),b==="inline"&&o.appendChild(A)}let S=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&b==="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:E,wrapper:k}=Fa(t,{showClose:n,wrapperClassName:S});return i!=="top-right"&&o.appendChild(k),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:m,closeButton:E,closeButtonWrapper:k,clearChatButton:x,clearChatButtonWrapper:A}},xc=(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))};Ye();Ph();Ri();Tu();var YR=e=>{let t=Ii({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 XR(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Na({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Mu(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=dc(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Sc({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 QR=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=C("div","persona-flex persona-items-center persona-justify-between");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=lo.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,d,p;if(c){let k=pM({label:i.title??"Chat Assistant",menuItems:c.menuItems,onSelect:D=>{let $=T=>{T===!1&&k.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},J=c.onSelect(D);J instanceof Promise?J.then($,()=>{}):$(J)},hover:c.hover,className:""});d=k.element,d.style.color=lo.titleColor,p=d.querySelector(".persona-combo-btn-label")??d}else{if(d=C("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=C("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=lo.titleColor,Object.assign(p.style,Lh),p.textContent=i.title??"Chat Assistant",d.appendChild(p),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let D=r.onTitleClick;d.addEventListener("click",$=>{$.target.closest("button")||D()}),d.addEventListener("keydown",$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),D())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:m,wrapper:g}=Fa(t,{showClose:n,wrapperClassName:f});o&&m.addEventListener("click",o);let h=C("div","persona-flex persona-items-center persona-gap-1");c||XR(h,r?.trailingActions,r?.onAction??s);let b=i.clearChat??{},x=null,A=null;if(b.enabled??!0){let k=b.placement??"inline",D=Va(t,{wrapperClassName:k==="top-right"?"persona-absolute persona-top-4 persona-z-50":f});x=D.button,A=D.wrapper,k==="top-right"?A.style.right="48px":h.appendChild(A)}h.appendChild(g),l.appendChild(h);let S=C("div");S.style.display="none";let E=C("span");return E.style.display="none",{header:l,iconHolder:S,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:g,clearChatButton:x,clearChatButtonWrapper:A}},uM={default:YR,minimal:QR},JR=e=>uM[e]??uM.default,Du=(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=C("div");l.style.display="none";let c=C("span"),d=C("span"),p=C("button");p.style.display="none";let f=C("div");return f.style.display="none",{header:i,iconHolder:l,headerTitle:c,headerSubtitle:d,closeButton:p,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=JR(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};Ye();Ws();var Ac=e=>{let{config:t}=e,n=F("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=_p(),r=F("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""}}),{textarea:s,attachAutoResize:i}=Wp(t);i();let l=Bp(t),c=Ia(t),d=Dp(t),p=Op(t),f=F("div",{className:"persona-widget-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});r.append(f),d&&(d.previewsContainer.style.gap="8px",f.append(d.previewsContainer),r.append(d.input)),r.append(s);let m=F("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=F("div",{className:"persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-start":""}}),h=F("div",{className:"persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2",attrs:{"data-persona-composer-actions-end":""}});return d&&g.append(d.wrapper),c&&h.append(c.wrapper),h.append(l.wrapper),m.append(g,h),r.append(m),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),t?.statusIndicator?.mode==="transient"?n.append(o,p,r):n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,header:f,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:p,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:l.setMode}};Ye();var Ou=require("lucide");io();Ws();Hp();var fM=()=>{let e=F("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=C("span","persona-pill-peek__icon"),n=Je(Ou.MessageSquare,16,"currentColor",1.5);n&&t.appendChild(n);let o=C("span","persona-pill-peek__text"),r=C("span","persona-pill-peek__caret"),s=Je(Ou.ChevronUp,16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},_u=e=>{let{config:t}=e,n=F("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=_p(),r=Op(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Wp(t,{defaultMaxLines:5});i();let l=Bp(t),c=Ia(t),d=Dp(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let p=F("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""}}),f=F("div",{className:"persona-widget-composer__left-actions persona-pill-composer__left",attrs:{"data-persona-composer-actions-start":""}});d&&f.append(d.wrapper);let m=F("div",{className:"persona-widget-composer__right-actions persona-pill-composer__right",attrs:{"data-persona-composer-actions-end":""}});c&&m.append(c.wrapper),m.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==c?.button&&b.target!==c?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),d&&p.append(d.input),p.append(f,s,m);let g=F("div",{className:"persona-pill-composer__header",attrs:{"data-persona-composer-header":""},style:{display:"contents"}});n.append(g),d&&g.append(d.previewsContainer),n.append(o,p,r);let h=p;return{footer:n,suggestions:o,composerForm:p,header:g,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:h,leftActions:f,rightActions:m,setSendButtonMode:l.setMode}};Ye();ln();Ye();Fg();Ri();ln();Rs();hc();var ZR=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}},eW=(e,t)=>{if(!e)return null;let n=ZR(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},tW=(e,t)=>{let n=C("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},nW=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Hh=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(":"))},Rh=320,bM=320,oW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),rW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),sW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),iW=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),aW=e=>{if(!e||e.length===0)return null;let t=F("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=F("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=C("span","persona-mention-chip-icon"),s=Re(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(F("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},lW=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Zl(o.ref,{readonly:!0,render:t}))}return n},mM="\uE000",gM="\uE001",cW=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=m=>`${mM}${r}:${m}${gM}`,i=t.map((m,g)=>m.kind==="text"?m.text:s(g)).join(""),l=n(i);if(!t.every((m,g)=>m.kind==="text"||l.includes(s(g)))){e.replaceChildren(lW(t,o));return}e.innerHTML=l;let d=new RegExp(`${mM}${r}:(\\d+)${gM}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let m=p.nextNode();m;m=p.nextNode())f.push(m);for(let m of f){let g=m;for(let h=d.exec(g.data);h;h=d.exec(g.data)){let b=t[Number(h[1])],x=g.splitText(h.index);x.data=x.data.slice(h[0].length),b?.kind==="mention"&&x.parentNode?.insertBefore(Zl(b.ref,{readonly:!0,render:o}),x),g=x}}},dW=(e,t,n)=>{if(e.length===0)return null;try{let o=C("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 d=C("img");d.alt=l.alt?.trim()||`Attached image ${c+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Rh}px`,d.style.maxHeight=`${bM}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,d.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),d.remove(),r===0&&i())}),d.addEventListener("load",()=>{p=!0}),nW(l.image)?(d.src=l.image,o.appendChild(d)):(p=!0,r=Math.max(0,r-1),d.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},pW=e=>{if(e.length===0)return null;try{let t=C("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Hh(o.audio))return;let r=C("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Rh}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},uW=e=>{if(e.length===0)return null;try{let t=C("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Hh(o.video))return;let r=C("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Rh}px`,r.style.maxHeight=`${bM}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}},fW=e=>{if(e.length===0)return null;try{let t=C("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Hh(o.data))return;let r=C("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}},Mc=()=>{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},mW=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Mc};if(t){let r=t(o);if(r!==null)return r}return Mc()},gW=(e,t)=>{let n=C("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=C("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},hM=(e,t,n="div")=>{let o=C(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},Tc=(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},yM={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"}},hW=(e,t,n="bubble",o)=>{if(!o)return;let r=t==="user"?"user":"assistant",s=yM[n??"bubble"]??yM.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)`)},Nu="custom:",yW=e=>`${Nu}${e}`,vM=(e,t)=>t!=="user"&&t!=="assistant"?[]:(e?.custom??[]).filter(n=>(n.roles??["assistant"]).includes(t)),bW=(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,d=(t.showEdit??!1)&&o?.canEdit===!0,p=(t.showQuote??!1)&&o?.canQuote!==!1,f=vM(t,e.role);if(!r&&!s&&!i&&!l&&!c&&!d&&!p&&f.length===0){let E=C("div");return E.style.display="none",E.id=`actions-${e.id}`,E.setAttribute("data-actions-for",e.id),E}let m=t.visibility??"hover",g=t.align??"right",h=t.layout??"pill-inside",b={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[g],x={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[h],A=C("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${b} ${x} ${m==="hover"?"persona-message-actions-hover":""}`);A.id=`actions-${e.id}`,A.setAttribute("data-actions-for",e.id);let S=(E,k,D)=>{let $=Ln({icon:E,label:k,size:14,className:"persona-message-action-btn",chromeless:!0});return $.setAttribute("data-action",D),$};r&&A.appendChild(S("copy","Copy message","copy")),l&&A.appendChild(S("volume-2","Read aloud","read-aloud")),s&&A.appendChild(S("thumbs-up","Upvote","upvote")),i&&A.appendChild(S("thumbs-down","Downvote","downvote")),c&&A.appendChild(S("refresh-cw","Regenerate response","regenerate")),d&&A.appendChild(S("pencil","Edit message","edit")),p&&A.appendChild(S("quote","Quote message","quote"));for(let E of f)A.appendChild(S(E.iconName??"ellipsis",E.label,yW(E.id)));return A},Wh=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",c=i.avatar,d=i.timestamp,p=c?.show??!1,f=d?.show??!1,m=c?.position??"left",g=d?.position??"below",h=Tc(e.role,l),b=C("div",h.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message");let x=ph(s?.widgetConfig?.future).components.message,A=s?.widgetConfig?.theme?.components?.message;hW(b,e.role,l,e.role==="user"?{...x.user,...A?.user,...s?.widgetConfig?.darkTheme?.components?.message?.user}:{...x.assistant,...A?.assistant,...s?.widgetConfig?.darkTheme?.components?.message?.assistant}),l==="flat"?(b.style.backgroundColor="transparent",b.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=oW(e),E=e.content?.trim()??"",D=S.length>0&&E===La,$=Iu(s?.widgetConfig?.features?.streamAnimation),J=s?.widgetConfig?.features?.streamAnimation?.plugins,T=e.role==="assistant"&&$.type!=="none"?uc($.type,J):null,W=e.role==="assistant"&&T?.isAnimating?.(e)===!0,P=e.role==="assistant"&&T!==null&&(!!e.streaming||W);P&&T?.bubbleClass&&b.classList.add(T.bubbleClass);let v=document.createElement("div");v.classList.add("persona-message-content"),e.streaming&&v.classList.add("persona-content-streaming"),P&&T&&(T.containerClass&&v.classList.add(T.containerClass),v.style.setProperty("--persona-stream-step",`${$.speed}ms`),v.style.setProperty("--persona-stream-duration",`${$.duration}ms`));let w=P?Hu(e.content??"",$.buffer,T,e,!!e.streaming):e.content??"",L=()=>{let se=t({text:w,message:e,streaming:!!e.streaming,raw:e.rawContent});return P&&T?.wrap==="char"?fc(se,"char",e.id,{skipTags:T.skipTags}):P&&T?.wrap==="word"?fc(se,"word",e.id,{skipTags:T.skipTags}):se},I=null;if(D?(I=document.createElement("div"),I.innerHTML=L(),I.style.display="none",v.appendChild(I)):e.contentSegments?.length?cW(v,e.contentSegments,se=>t({text:se,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):v.innerHTML=L(),P&&T?.useCaret&&!D&&E){let se=Ru(),N=v.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ee=N[N.length-1];if(Ee?.parentNode)Ee.parentNode.insertBefore(se,Ee.nextSibling);else{let de=v.lastElementChild;de?de.appendChild(se):v.appendChild(se)}}if(f&&g==="inline"&&e.createdAt){let se=hM(e,d,"span");se.classList.add("persona-timestamp-inline");let N=v.lastElementChild;N?N.appendChild(se):v.appendChild(se)}if(S.length>0){let se=dW(S,!D&&!!E,()=>{D&&I&&(I.style.display="")});se?b.appendChild(se):D&&I&&(I.style.display="")}let Y=rW(e);if(Y.length>0){let se=pW(Y);se&&b.appendChild(se)}let _=sW(e);if(_.length>0){let se=uW(_);se&&b.appendChild(se)}let q=iW(e);if(q.length>0){let se=fW(q);se&&b.appendChild(se)}let Z=e.contentSegments?.length?null:aW(e.contextMentions);if(Z&&b.appendChild(Z),b.appendChild(v),f&&g==="below"&&e.createdAt){let se=hM(e,d);se.classList.add("persona-mt-1"),b.appendChild(se)}let ne=e.role==="assistant"?eW(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let se=!!(w&&w.trim()),N=$.placeholder==="skeleton",Ee=N&&$.buffer==="line"&&se;if(se)Ee&&b.appendChild(mc());else if(N)b.appendChild(mc());else{let de=mW("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);de&&b.appendChild(de)}}ne&&e.stopReason&&!e.streaming&&(E||(v.style.display="none"),b.appendChild(tW(e.stopReason,ne)));let te=e.role==="assistant"&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&o?.enabled!==!1,re=s?.actionEligibility,pe=e.role==="user"&&!e.streaming&&o?.enabled!==!1&&(o?.showEdit===!0&&re?.canEdit===!0||o?.showQuote===!0&&re?.canQuote===!0||vM(o,"user").length>0);if((te||pe)&&o){let se=bW(e,pe?{...o,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:o,r,re);b.appendChild(se)}if(!p||e.role==="system")return b;let xe=C("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Se=gW(c,e.role);return m==="right"||m==="left"&&e.role==="user"?xe.append(b,Se):xe.append(Se,b),xe};var vW=40,CW=(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=Re(t.name,vW);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(F("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(F("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},CM=(e,t,n={})=>{let o=F("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=C("p","persona-welcome-kicker");r.hidden=!0;let s=C("h2","persona-welcome-title"),i=C("p","persona-welcome-subtitle"),l=F("div",{className:"persona-welcome-head-text"},r,s),c=F("div",{className:"persona-welcome-title-row"},o,l);return{host:F("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},c,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)},Vu=(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==="",CW(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")},wW="data-persona-welcome-plugin",wM="data-persona-welcome-overlay",Fu="persona-welcome-overlay-active",Bh=new WeakMap,Dh=(e,t,n)=>{n.setAttribute(wW,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(wM,""),e.classList.contains(Fu)||(Bh.set(e,e.scrollTop),e.classList.add(Fu),e.scrollTop=0)},Oh=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(wM),e.classList.contains(Fu)&&(e.classList.remove(Fu),e.scrollTop=Bh.get(e)??e.scrollTop,Bh.delete(e))},xM=()=>{let e=F("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},$u=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=F("div",{className:Tc("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(F("div",{className:"persona-flex"},r)),e.hidden=!1},SM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,AM=(e,t)=>{if(SM()||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 h=getComputedStyle(o);r=parseFloat(h.rowGap)||0;let b=e.previousElementSibling,x=e.nextElementSibling,S=o.getBoundingClientRect().top+(parseFloat(h.borderTopWidth)||0)+(parseFloat(h.paddingTop)||0)-o.scrollTop;s=Math.max(0,b?n.top-b.getBoundingClientRect().bottom-r:n.top-S),i=Math.max(0,x?x.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let c=getComputedStyle(e),d=parseFloat(c.paddingTop)||0,p=parseFloat(c.paddingBottom)||0,f=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${d}px`,paddingBottom:`${p}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"}),m=!1,g=()=>{m||(m=!0,e.style.overflow=l,t(f))};return f.finished.then(g).catch(g),f},MM=(e,t,n,o=260)=>{if(t<=1||SM()||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 xW="Hello \u{1F44B}",SW="I can answer questions and help you get things done here.",TM=new WeakSet,co=(e,t)=>!!e&&e[t]!==void 0,AW=(e,t)=>{!e||e.debug!==!0||!t.length||TM.has(e)||(TM.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Uu=(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=co(n,"variant")?n.variant:o?.showWelcomeCard===!1?"none":"card",l=i==="hero"&&!r&&n?.layout===void 0?"on-first-message":co(n,"dismiss")?n.dismiss:r||i==="hero"?"on-first-message":"never",c=[];co(n,"title")&&co(o,"welcomeTitle")&&c.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),co(n,"subtitle")&&co(o,"welcomeSubtitle")&&c.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),co(n,"variant")&&co(o,"showWelcomeCard")&&c.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),i==="hero"&&co(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"&&co(n,"dismiss")&&n.dismiss!=="on-first-message"&&c.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".');let d=n?.anchor??(s==="centered"&&t?"center":"bottom"),p=cc(n?.anchorComposerTop)!==null;return co(n,"anchorComposerTop")&&!p&&c.push('welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".'),d!=="center"&&(co(n,"anchorComposerTop")||co(n,"composerGap"))&&c.push('welcome.anchorComposerTop is ignored unless welcome.anchor is "center".'),AW(e,c),{title:co(n,"title")?n.title:o?.welcomeTitle??(r?"What can I help with?":xW),kicker:n?.kicker??"",subtitle:co(n,"subtitle")?n.subtitle:o?.welcomeSubtitle??(r?"":SW),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:d,anchorComposerTop:p?n.anchorComposerTop:"44%",composerGap:n?.composerGap?.trim()||xu}},EM=e=>(e??[]).some(t=>t.role==="user")?"active":"empty",Ua=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");ha();var MW="var(--persona-components-panel-maxWidth)",kM="var(--persona-components-panel-height)",TW="var(--persona-components-panel-maxHeight)",Wi=e=>{let t=Ur(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,o=e?.launcher?.heightOffset??0,r=o===0?`max(200px, ${kM})`:`max(200px, calc(${kM} - ${o}px))`;return{width:n??yC,maxWidth:n??MW,height:r,maxHeight:TW}},LM="16px",Nh="10px",Fh="14px",PM=e=>{let t=e?.launcher?.enabled??!0,n=un(e);if(Cc(e)){let d=e?.launcher?.composerBar??{},p=C("div","persona-widget-wrapper persona-fixed persona-transition");p.setAttribute("data-persona-composer-bar",""),p.dataset.state="collapsed",p.dataset.expandedSize=d.expandedSize??"anchored",p.style.zIndex=String(e?.launcher?.zIndex??Jn);let f=C("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");f.style.width="100%",p.appendChild(f);let m=C("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=d.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Jn),{wrapper:p,panel:f,pillRoot:m}}if(n){let d=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),p=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(p),{wrapper:d,panel:p}}if(!t){let d=C("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),p=C("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),f=Ur(e),g=f.launcherWidth||f.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?Wi(e).width:"100%";return d.style.width=g,p.style.width="100%",d.appendChild(p),{wrapper:d,panel:p}}let r=e?.launcher??{},s=r.position&&To[r.position]?To[r.position]:To["bottom-right"],i=C("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Jn);let l=C("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=Wi(e);return l.style.width=c.width,l.style.maxWidth=c.maxWidth,i.appendChild(l),{wrapper:i,panel:l}},Vh=e=>{let t=F("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Th(e)}});return t.hidden=!0,t},IM=(e,t)=>{let n=Vh("starter"),o=CM(e,n,{flatShadow:un(e)}),r=Uu(e);Vu(o,r),$a(t,o.host,Ua(r,e?.initialMessages));let s=xM();return $u(s,r.message,e),{welcome:o,greetingHost:s}},EW=(e,t)=>{let n=C("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}=Fa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:LM,iconSize:Nh});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 J=Va(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:LM,iconSize:Fh});i=J.button,l=J.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let c=F("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:f}=IM(e,d),{host:m,title:g,subtitle:h}=p,b=p.starterSuggestions,x=C("div","persona-widget-messages persona-flex persona-flex-col");x.style.gap="var(--persona-components-message-gap, 12px)";let A=Vh("followUp"),S=_s(e,!0);S&&(x.style.maxWidth=S,x.style.marginLeft="auto",x.style.marginRight="auto",x.style.width="100%"),d.append(m,f,x,A);let E=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}}),k=_u({config:e}),{root:D,textNode:$}=fM();return n.append(c,r,d,E),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:x,starterSuggestions:b,transcriptSuggestions:A,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,welcomeHost:m,welcomeIconHolder:p.iconHolder,greetingHost:f,introKicker:p.kicker,introTitle:g,introSubtitle:h,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:C("span"),headerTitle:C("span"),headerSubtitle:C("span"),header:c,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:D,peekTextNode:$}},HM=(e,t=!0)=>{if(Cc(e))return EW(e,t);let n=F("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?Du(e,o,{showClose:t}):Ii({config:e,showClose:t}),i=F("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:c}=IM(e,i),{host:d,title:p,subtitle:f}=l,m=l.starterSuggestions,g=C("div","persona-widget-messages persona-flex persona-flex-col");g.style.gap="var(--persona-components-message-gap, 12px)";let h=Vh("followUp"),b=_s(e,!1);b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),i.append(d,c,g,h);let x=Ac({config:e}),A=e?.layout?.showFooter!==!1;r?xc(n,s,e):(s.header.style.display="none",xc(n,s,e)),n.append(i);let S=F("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"calc(var(--persona-composer-overlay-height, 0px) + var(--persona-composer-lift, 0px))",zIndex:"20"}});return A||(x.footer.style.display="none"),n.append(x.footer),n.append(S),{container:n,body:i,messagesWrapper:g,starterSuggestions:m,transcriptSuggestions:h,composerOverlay:S,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:c,introKicker:l.kicker,introTitle:p,introSubtitle:f,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:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};Ws();Ye();ln();nr();var $h=(e,t)=>{let n=C("button");n.type="button",n.innerHTML=`
1177
1177
  <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>
1178
1178
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />