@runtypelabs/persona 4.32.0 → 4.32.2

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 (56) hide show
  1. package/dist/activity-ui.cjs +1 -1
  2. package/dist/activity-ui.js +1 -1
  3. package/dist/{chunk-BrptyKSq.js → chunk-B3l7TOOv.js} +1 -1
  4. package/dist/{chunk-CkE90FtA.js → chunk-B4ecQzeK.js} +1 -1
  5. package/dist/{chunk-CzZBmTLd.js → chunk-B9Zu-wrk.js} +1 -1
  6. package/dist/chunk-BNE40cEG.js +1 -0
  7. package/dist/{chunk-BWCo3rCm.js → chunk-B_H0l3u2.js} +1 -1
  8. package/dist/{chunk-MdlQetfC.js → chunk-BbXc58OA.js} +1 -1
  9. package/dist/{chunk-DE0cSmku.js → chunk-BpjtKnGI.js} +1 -1
  10. package/dist/{chunk-CHAwCqpk.js → chunk-CdpVP6LZ.js} +1 -1
  11. package/dist/{chunk-FEzOcZof.js → chunk-CjkechxR.js} +1 -1
  12. package/dist/{chunk-DZg9bFK6.js → chunk-D0tcIZJM.js} +1 -1
  13. package/dist/{chunk-Cb7qy0c7.js → chunk-DNdeIFJ6.js} +1 -1
  14. package/dist/{chunk-VaT6xry9.js → chunk-DTGvDx8o.js} +1 -1
  15. package/dist/{chunk-ezlpsYGk.js → chunk-DVZ8ri1z.js} +1 -1
  16. package/dist/{chunk-DhedQnek.js → chunk-DgZZqy14.js} +1 -1
  17. package/dist/{chunk-C2IbR39s.js → chunk-UWMfWW2a.js} +1 -1
  18. package/dist/client-dispatch.js +1 -1
  19. package/dist/client-history.js +1 -1
  20. package/dist/codegen.cjs +1 -1
  21. package/dist/codegen.js +1 -1
  22. package/dist/index.cjs +4 -4
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.global.js +1 -1
  25. package/dist/index.global.js.map +1 -1
  26. package/dist/index.js +4 -4
  27. package/dist/index.js.map +1 -1
  28. package/dist/install.global.js +1 -1
  29. package/dist/install.global.js.map +1 -1
  30. package/dist/launcher.global.js +2 -2
  31. package/dist/launcher.global.js.map +1 -1
  32. package/dist/theme-editor-preview.cjs +4 -4
  33. package/dist/theme-editor-preview.js +4 -4
  34. package/dist/theme-editor.cjs +1 -1
  35. package/dist/theme-editor.js +1 -1
  36. package/dist/theme-reference.cjs +1 -1
  37. package/dist/theme-reference.js +1 -1
  38. package/dist/voice-runtime.cjs +1 -1
  39. package/dist/voice-runtime.js +1 -1
  40. package/dist/widget.css +1 -1
  41. package/package.json +1 -1
  42. package/src/index-global.ts +2 -1
  43. package/src/install.test.ts +6 -5
  44. package/src/install.ts +2 -2
  45. package/src/launcher-global.ts +2 -1
  46. package/src/session.test.ts +41 -0
  47. package/src/session.ts +14 -7
  48. package/src/styles/widget.css +12 -0
  49. package/src/utils/brand.test.ts +50 -0
  50. package/src/utils/brand.ts +6 -2
  51. package/src/utils/cdn-release.test.ts +20 -0
  52. package/src/utils/cdn-release.ts +14 -0
  53. package/src/utils/tokens.ts +2 -1
  54. package/src/utils/tool-activity-summary.test.ts +8 -0
  55. package/src/utils/tool-activity-summary.ts +2 -1
  56. package/dist/chunk-DDAwu89-.js +0 -1
package/dist/index.js CHANGED
@@ -2,10 +2,10 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
2
2
  `),n=!1;for(let e=0;e<t.length-1;e++){let r=t[e],i=t[e+1];if(!Ut(r)||Ht.test(r)||!Ht.test(i))continue;let a=Wt(r).length;if(a<1)continue;let o=Kt(a);t[e+1]!==o&&(t[e+1]=o,n=!0);let s=e+2;for(;s<t.length;s++){let e=t[s];if(e.trim()===``||!Ut(e))break;let r=Gt(qt(Wt(e),a));t[s]!==r&&(t[s]=r,n=!0)}e=s-1}return n?t.join(`
3
3
  `):e}})),Xt,Zt,Qt,$t,en,tn=B((()=>{Yt(),Xt=e=>!e||/\s/.test(e),Zt=e=>!!e&&/[\p{P}\p{S}]/u.test(e),Qt=(e,t,n)=>{let r=e.slice(t,n),i=n;for(;(i=e.indexOf(r,i))!==-1;){if(e[i-1]!=="`"&&e[i+r.length]!=="`")return i+r.length;i+=r.length}return-1},$t=(e,t=!0)=>{let n=[],r=/* @__PURE__ */ new Set,i=``;for(let a=0;a<e.length;){let o=e[a];if(o===`\\`)i+=e.slice(a,a+2),a+=2;else if(o==="`"){let t=a+1;for(;e[t]==="`";)t++;let n=e.slice(a,t),r=Qt(e,a,t);if(r!==-1)i+=e.slice(a,r),a=r;else{let r=e.slice(t);i+=r?`${n}${r}${r.endsWith("`")?` `:``}${n}`:``,a=e.length}}else if(o===`<`){let t=e.indexOf(`>`,a+1);i+=e.slice(a,t<0?e.length:t+1),a=t<0?e.length:t+1}else if(t&&(o===`[`||o===`!`&&e[a+1]===`[`)){let t=o===`!`,n=a+(t?2:1),r=1,s=n;for(;s<e.length;s++)if(e[s]===`\\`)s++;else if(e[s]==="`"){let t=s+1;for(;e[t]==="`";)t++;let n=Qt(e,s,t);s=(n<0?t:n)-1}else if(e[s]===`[`&&r++,e[s]===`]`&&--r===0)break;if(s>=e.length){i+=t?``:$t(e.slice(n),!1);break}if(e[s+1]===`(`){let r=1,o=``,c=!1,l=s+2;for(;l<e.length;l++){let t=e[l];if(t===`\\`)l++;else if(o)t===o&&(o=``);else if((t===`"`||t===`'`)&&Xt(e[l-1]))o=t;else if(t===`<`&&(c=!0),t===`>`&&(c=!1),!c&&t===`(`&&r++,!c&&t===`)`&&--r===0)break}if(l>=e.length){i+=t?``:$t(e.slice(n,s),!1);break}i+=e.slice(a,l+1),a=l+1;continue}if(s===e.length-1){i+=t?``:$t(e.slice(n,s),!1);break}i+=e.slice(a,s+1),a=s+1}else if(o===`*`||o===`_`){let t=a+1;for(;e[t]===o;)t++;let s=e.slice(a,t),c=e[a-1]??``,l=e[t]??``,u=!Xt(l)&&(!Zt(l)||Xt(c)||Zt(c)),d=!Xt(c)&&(!Zt(c)||Xt(l)||Zt(l)),f=s.length;if(d&&(o!==`_`||!u||Zt(l)))for(;f&&n[n.length-1]?.marker[0]===o;){let e=n[n.length-1],t=Math.min(f,e.marker.length);f-=t,e.marker=e.marker.slice(t),e.marker||n.pop()}if(f&&s.length<=3&&u&&!d)n.push({marker:o.repeat(f)});else if(f===s.length&&t===e.length&&Xt(c)&&e.slice(e.lastIndexOf(`
4
4
  `,a)+1,a).trim()&&(n.length>0||!r.has(o))){a=t;continue}Xt(c)&&Xt(l)&&t<e.length&&r.add(o),i+=s,a=t}else i+=o,a++}let a=i.match(/\s*$/)?.[0]??``;i=i.slice(0,i.length-a.length),n.length&&(i.match(/\\+$/)?.[0].length??0)%2&&(i+=`\\`);for(let e=n.length-1;e>=0;e--)i+=n[e].marker;return i+a},en=e=>{let t=``,n=``,r=``,i=()=>{t+=Jt(n).split(/(\n\s*\n)/).map(e=>/^\n\s*\n$/.test(e)?e:$t(e)).join(``),n=``};for(let a of e.match(/[^\n]*\n|[^\n]+$/g)??[]){let e=/^(?: {0,3}> ?)* {0,3}(?:[-+*] )?(`{3,}|~{3,})(.*)/.exec(a);r?(t+=a,e&&e[1][0]===r[0]&&e[1].length>=r.length&&!e[2].trim()&&(r=``)):e?(i(),r=e[1],t+=a):/^(?: {4}|\t)/.test(a)?(i(),t+=a):n+=a}return i(),t}})),nn=/* @__PURE__ */ Vt({DOMPurify:()=>r,Marked:()=>t,stabilizeStreamingMarkdown:()=>en}),rn=B((()=>{tn()}));H();const{setLoader:an,load:on,provide:sn,getSync:cn}=V({fallbackImport:()=>Promise.resolve().then(()=>(rn(),nn))}),ln=/* @__PURE__ */ new Set,un=()=>{let e=[...ln];ln.clear();for(let t of e)try{t()}catch{}},dn=()=>{let e=cn();return e?Promise.resolve(e):on().then(e=>(un(),e))},fn=e=>cn()?()=>{}:(ln.add(e),()=>{ln.delete(e)}),pn=e=>{sn(e),un()},mn=cn;tn(),pn({Marked:e,DOMPurify:n,stabilizeStreamingMarkdown:en});const hn={"ellipsis-vertical":le,brain:h,toolbox:Ct,wrench:Nt,circle:T,database:O,terminal:R,user:kt,mail:Ie,phone:et,calendar:_,clock:re,building:g,"map-pin":Le,lock:Fe,key:Ae,"credit-card":oe,hash:we,globe:Ce,link:Me,"circle-check":E,"circle-x":te,"triangle-alert":Et,info:ke,ban:d,shield:ft,house:j,"pen-line":Ze,save:st,share:dt,funnel:xe,settings:ut,"rotate-cw":ot,"shopping-cart":ht,"shopping-bag":P,package:qe,truck:Dt,tag:yt,gift:Se,receipt:it,wallet:Mt,store:_t,"dollar-sign":se,percent:$e,play:tt,pause:Xe,"volume-x":jt,camera:y,image:Oe,film:_e,headphones:Te,"message-circle":Be,bell:f,heart:Ee,"eye-off":fe,bookmark:p,"calendar-days":v,timer:St,folder:ye,"folder-open":be,files:ge,"chart-column":b,sparkles:F,zap:Pt,sun:vt,moon:Ke,flag:ve,lightbulb:je,monitor:Ge,smartphone:gt};var gn,_n=B((()=>{gn=(e,t=24,n=`currentColor`,r=2)=>{if(!Array.isArray(e))return null;let i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);for(let[e,a]of Object.entries({width:String(t),height:String(t),viewBox:`0 0 24 24`,fill:`none`,stroke:n,"stroke-width":String(r),"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`}))i.setAttribute(e,a);for(let t of e){if(!Array.isArray(t)||t.length<2)continue;let e=t[0],n=t[1];if(!n)continue;let r=document.createElementNS(`http://www.w3.org/2000/svg`,e);for(let[e,t]of Object.entries(n))e!==`stroke`&&r.setAttribute(e,String(t));i.appendChild(r)}return i}})),vn,U,yn,W,bn=B((()=>{H(),{setLoader:vn,load:U}=V({fallbackImport:()=>import(`@runtypelabs/persona/icons-extra`)}),yn=vn,W=U})),xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,G,Pn=B((()=>{_n(),bn(),xn={activity:i,"arrow-down":a,"arrow-up":c,"arrow-up-right":l,bot:m,"chevron-down":S,"chevron-up":w,"chevron-right":ee,"chevron-left":C,check:x,clipboard:D,"clipboard-copy":ne,"code-xml":ie,copy:ae,file:pe,"file-code":me,"file-spreadsheet":he,"file-text":A,"image-plus":M,loader:Ne,"loader-circle":Pe,mic:He,paperclip:Ye,quote:rt,"refresh-cw":at,search:ct,send:lt,"shield-alert":pt,"shield-check":mt,"shield-x":N,square:I,"square-text":[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}],[`path`,{d:`M7 8h10M7 12h10M7 16h6`}]],"thumbs-down":bt,"thumbs-up":xt,upload:Ot,"volume-2":At,"voice-bars":[[`path`,{d:`M4 10v4`}],[`path`,{d:`M8 6v12`}],[`path`,{d:`M12 3v18`}],[`path`,{d:`M16 7v10`}],[`path`,{d:`M20 10v4`}]],x:z,"at-sign":u,"arrow-left":o,"arrow-right":s,"external-link":ue,ellipsis:k,menu:ze,"panel-left":Je,plus:nt,minus:We,pencil:Qe,trash:wt,"trash-2":Tt,download:ce,maximize:Re,minimize:Ue,"message-square":Ve,star:L,eye:de,history:De},Sn=/* @__PURE__ */ `brain.toolbox.wrench.circle.database.terminal.user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.ellipsis-vertical.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),Cn=new Map(Object.entries(xn)),wn=/* @__PURE__ */ new Map,Tn=!1,En=/* @__PURE__ */ new Set,Dn=e=>{let t=[...En];e&&En.clear();for(let e of t)try{e()}catch{}},On=()=>{let e=0;for(let[t,n]of wn){let r=Cn.get(n);if(!r)continue;wn.delete(t),e++;let i=gn(r);if(i)for(t.removeAttribute(`data-persona-icon-pending`);i.firstChild;)t.appendChild(i.firstChild)}return e},kn=e=>{for(let[t,n]of Object.entries(e))Cn.set(t,n);On()>0&&!Tn&&Dn(!1)},An=e=>{if(!Tn){for(let[t,n]of Object.entries(e))Cn.has(t)||Cn.set(t,n);Tn=!0,On(),Dn(!0)}},jn=()=>Tn?null:W().then(e=>An(e.EXTRA_LUCIDE_ICONS)),Mn=()=>{jn()?.catch(e=>{console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},Nn=(e,t,n)=>{let r=gn([],e,t,n);return r.setAttribute(`data-persona-icon-pending`,`true`),r},G=(e,t=24,n=`currentColor`,r=2)=>{let i=Cn.get(e);if(i)return gn(i,t,n,r);if(Sn.includes(e)){let i=Nn(t,n,r);return wn.size>=500&&wn.delete(wn.keys().next().value),wn.set(i,e),Mn(),i}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null}}));Pn(),An(hn);function Fn(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${Ln(t.join(``))}`}function In(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Ln(e){return`${In(e,0).toString(36)}.${In(e,2654435761).toString(36)}`}var Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn=B((()=>{Rn=`webmcp:`,zn=/* @__PURE__ */ new Map,Bn=e=>{zn.clear();for(let t of e){let e=t.title?.trim();e&&zn.set(t.name,e)}},Vn=e=>zn.get(Un(e)),Hn=null,Un=e=>e.startsWith(`webmcp:`)?e.slice(7):e,Wn=e=>e.startsWith(Rn),Gn=()=>Hn?Hn():import(`@mcp-b/webmcp-polyfill`)}));function K(e){return e===`card`?`collapsed`:e}function qn(e){return e.split(`;`,1)[0].trim().toLowerCase()}function Jn(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(qn(e)===t)return{mode:K(r),selector:qn(e)};let r=`${t.split(`/`,1)[0]}/*`;for(let[e,t]of n)if(qn(e)===r)return{mode:K(t),selector:r}}function Yn(e,t){let n=e?.display,r=typeof n==`string`?{default:n}:n??{};if(t.file&&r.files){if(typeof r.files==`string`)return{mode:K(r.files),matchedBy:{type:`files`}};let e=t.file.mimeType?qn(t.file.mimeType):void 0,n=e?Jn(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:`mediaType`,mediaType:e,selector:n.selector}};if(r.files.default)return{mode:K(r.files.default),matchedBy:{type:`files`}}}let i=r.byKind?.[t.artifactType];if(i)return{mode:K(i),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byKind`}};let a=r.byType?.[t.artifactType];if(a)return{mode:K(a),matchedBy:{type:`kind`,kind:t.artifactType,configuredBy:`byType`}};let o=t.presentation?.preferredMode;return o?{mode:K(o),matchedBy:{type:`preferredMode`}}:r.default?{mode:K(r.default),matchedBy:{type:`default`}}:{mode:`panel`,matchedBy:{type:`personaDefault`}}}function Xn(e,t){return Yn(e,t).mode}function Zn(e,t){return JSON.stringify({component:e===`inline`?`PersonaArtifactInline`:`PersonaArtifactCard`,props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e===`inline`&&t.component?{component:t.component}:{},...e===`inline`&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown===void 0?{}:{markdown:t.markdown}}})}var q=B((()=>{})),Qn,$n=B((()=>{Qn=(e,t)=>{let n=t?.durationMs??15e3,r=t?.chars??1200;return typeof e.durationMs==`number`?e.durationMs<n:(e.chunks??[]).join(``).length<r}})),er,tr,nr,rr,ir,ar,or,sr,cr=B((()=>{$n(),er=e=>e.replace(/\\n/g,`
5
- `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),tr=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return er(t)}catch{return t}};return{getExtractedText:()=>e,processChunk:async r=>{let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(r.length<=t)return e===null?null:{text:e,raw:r};let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},nr=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},rr=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ir=()=>tr(),ar=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=Rt(n,Lt|It);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?er(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=er(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},or=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?er(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?er(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=Rt(e,Lt|It),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},sr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}}));function lr(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=ur(t)&&ur(r)?lr(t,r):r}return n}var ur,dr=B((()=>{ur=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),fr,pr,mr,hr,gr,_r,vr,yr=B((()=>{dr(),fr=e=>{if(typeof e!=`string`)return;let t=e.trim(),n=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(t)?.[1];if(n){let e=n.length===3?[...n].map(e=>e+e).join(``):n;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let r=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!r)return;let i=r[1].trim().split(/\s*[,/]\s*|\s+/);if(i.length===4&&/^(?:1(?:\.0+)?|100%)$/.test(i[3])&&i.pop(),i.length!==3)return;let a=i.map(e=>/^\d+(?:\.\d+)?%?$/.test(e)?Number.parseFloat(e)*(e.endsWith(`%`)?2.55:1):NaN);if(!a.some(e=>!Number.isFinite(e)||e<0||e>255))return a},pr=e=>e.reduce((e,t,n)=>{let r=t/255;return e+(r<=.04045?r/12.92:((r+.055)/1.055)**2.4)*[.2126,.7152,.0722][n]},0),mr=e=>`#`+e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``),hr=(e,t,n)=>mr(e.map(e=>e+(t-e)*n)),gr=e=>pr(e)>.179?`#000000`:`#ffffff`,_r=e=>{let t=fr(e?.neutral);return t?pr(t)<.18?`dark`:`light`:void 0},vr=(e,t=`light`,n,r=!1)=>{let i={};if(!e)return i;let a=fr(e.accent);if(a){let e={};for(let[t,n]of[[50,.96],[100,.9],[200,.75],[300,.55],[400,.25]])e[t]=hr(a,255,n);e[500]=mr(a);for(let[t,n]of[[600,.15],[700,.3],[800,.45],[900,.6],[950,.75]])e[t]=hr(a,0,n);let t=gr(a);i.palette={colors:{primary:e,accent:e}},i.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},i.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:r?{background:`semantic.colors.container`,foreground:`semantic.colors.text`,iconBackground:`transparent`,iconForeground:`semantic.colors.text`}:{background:e[500],foreground:t,iconBackground:e[500],iconForeground:t},approval:{approve:{foreground:t}},message:{user:r?{background:`color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))`,text:`semantic.colors.text`}:{background:e[500],text:t}}}}let o=fr(e.neutral);if(o){let e=t===`dark`,n=e===pr(o)<.18?o:fr(hr(o,e?0:255,.9)),r=mr(n),a=hr(n,e?255:0,e?.06:.025),s=hr(n,e?255:0,e?.2:.16),c=gr(n),l={};for(let[e,t]of[[50,0],[100,.06],[200,.16],[300,.28],[400,.45],[500,.65],[600,.72],[700,.8],[800,.9],[900,.97],[950,1]])l[e]=hr(n,c===`#ffffff`?255:0,t);i.palette={...i.palette,colors:{...i.palette?.colors,gray:l}},i.semantic={...i.semantic,colors:{...i.semantic?.colors,surface:r,background:r,container:a,border:s,divider:s,text:c,textMuted:hr(n,c===`#ffffff`?255:0,.65)}},i.components={...i.components,panel:{background:r},header:{...i.components?.header,background:r,foreground:c},composer:{footerBackground:r}}}if(a){let e=fr(i.semantic?.colors?.surface)??(t===`dark`?[15,15,16]:[255,255,255]),n=mr(a),r=gr(e)===`#ffffff`?255:0;for(let t=0;t<=1;t+=.1){n=hr(a,r,t);let i=pr(fr(n)),o=pr(e);if((Math.max(i,o)+.05)/(Math.min(i,o)+.05)>=4.5)break}i.components={...i.components,markdown:{link:{foreground:n}},input:{focus:{border:n,ring:n}}}}e.font?.trim()&&(i.semantic={...i.semantic,typography:{fontFamily:e.font}});let s={none:`0px`,sm:`4px`,md:`8px`,lg:`16px`}[e.radius??`none`];e.radius&&s&&(i.palette={...i.palette,radius:{none:`0px`,sm:s,md:s,lg:s,xl:s,"2xl":s}},i.components={...i.components,input:{...i.components?.input,borderRadius:s},header:{...i.components?.header,controlBorderRadius:s}});let c={compact:[13,44,8],comfortable:[14,48,12],spacious:[15,52,16]}[e.density??`comfortable`];if(e.density&&c){let[e,t,n]=c;i.semantic={...i.semantic,typography:{...i.semantic?.typography,fontSize:`${e}px`}},i.components={...i.components,header:{...i.components?.header,minHeight:`${t}px`,padding:`${n}px 16px`,minimalPadding:`${n}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...i.components?.composer,fontSize:`${e}px`,padding:`${n}px`,gap:`${n/2}px`},message:{...i.components?.message,gap:`${n}px`,user:{...i.components?.message?.user,fontSize:`${e}px`},assistant:{fontSize:`${e}px`}}}}if(e.elevation&&[`flat`,`subtle`,`raised`].includes(e.elevation)){let t=e.elevation===`flat`,r=t?`none`:e.elevation===`subtle`?`0 2px 8px rgba(0, 0, 0, 0.08)`:`0 12px 32px rgba(0, 0, 0, 0.18)`,a=t?`1px solid var(--persona-border)`:`1px solid color-mix(in srgb, var(--persona-border) 65%, transparent)`;i.palette={...i.palette,shadows:{sm:r,md:r,lg:r,xl:r,"2xl":r}};let o=e=>{let n={};for(let[i,s]of Object.entries(e))if(i.toLowerCase().endsWith(`shadow`)){n[i]=r;let o=i===`shadow`?`border`:i.replace(/Shadow$/,`Border`);o in e&&(n[o]=typeof e[o]==`string`&&e[o].includes(`solid`)?a:t?`semantic.colors.border`:`color-mix(in srgb, var(--persona-border) 65%, transparent)`)}else if(s&&typeof s==`object`){let e=o(s);Object.keys(e).length&&(n[i]=e)}return n},s=n?o(n):{};i.components=lr(i.components,s),i.components={...i.components,panel:{...i.components?.panel,shadow:r,modes:{floating:{shadow:r,border:a},inline:{shadow:r,border:a},docked:{shadow:r,border:a},sidebar:{shadow:r,border:a},mobile:{shadow:r,border:a}}},launcher:{...i.components?.launcher,shadow:r,border:`semantic.colors.border`},composer:{...i.components?.composer,shadow:r,borderColor:`semantic.colors.border`},toolBubble:{shadow:r},reasoningBubble:{shadow:r}}}return i}}));function br(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return Or(n)?br(n,r):[r]})}function xr(e,t){let n=t.split(`.`);for(let t=0;t<n.length;t++){let r=n[t];if(!Or(e)||!Object.prototype.hasOwnProperty.call(e,r))return`absent`;if(e=e[r],e===void 0||t<n.length-1&&!Or(e))return`clear`}return`explicit`}function Sr(e,t){return e?.[Dr]??t.filter(t=>xr(e,t)===`explicit`)}function Cr(e,t){return Object.defineProperty(e,Dr,{value:t,enumerable:!0,configurable:!0}),e}function wr(e,t,n){return Cr(e,Sr(t,br(n)))}function Tr(e,t,n){let r=t[Dr];if(r)return r;let i=new Set(Sr(e,n));for(let e of n){let n=xr(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function Er(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!Or(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var Dr,Or,kr=B((()=>{Dr=Symbol.for(`persona.defaultsProvenance`),Or=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr=B((()=>{yr(),kr(),Ar=(e,t)=>t.split(` `).map(t=>`${e}.${t}`),jr=[...Ar(`launcher`,`closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY`),...Ar(`launcher.clearChat`,`size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY`),...Ar(`sendButton`,`size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY`),...Ar(`voiceRecognition`,`iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor`),...Ar(`toolCall`,`shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration`),...Ar(`approval`,`backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor`),...Ar(`features.askUserQuestion.styles`,`sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground`),...Ar(`features.artifacts.layout`,`paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize`),...Ar(`suggestionChipsConfig`,`fontWeight paddingX paddingY`)],Mr=[`voice.recording.border`,`voice.processing.icon`,`voice.processing.background`,`voice.speaking.icon`,`approval.requested.text`,`approval.approve.foreground`,`approval.deny.foreground`,`approval.deny.background`,`reasoningBubble.shadow`,`toolBubble.shadow`],Nr=[...jr,`suggestionChips`,`copy.welcomeTitle`,`copy.welcomeSubtitle`,`copy.showWelcomeCard`,`features.suggestReplies.enabled`,`features.suggestReplies.expose`,...[`theme`,`darkTheme`].flatMap(e=>Mr.map(t=>`${e}.components.${t}`))],Pr=Symbol.for(`persona.styleProvenance`),Fr=e=>e[Pr]!==void 0,Ir=(e,t)=>{for(let n of t.split(`.`)){if(typeof e!=`object`||!e)return;e=e[n]}return e},Lr=e=>{let t=e?.[Pr];if(!t)return Nr.filter(t=>xr(e,t)===`explicit`);let n=new Set(t.explicit);return Nr.forEach(r=>{Ir(e,r)!==t.values[r]&&(xr(e,r)===`explicit`?n.add(r):n.delete(r))}),[...n]},Rr=(e,t)=>(Object.defineProperty(e,Pr,{value:{explicit:t,values:Object.fromEntries(Nr.map(t=>[t,Ir(e,t)]))},enumerable:!0,configurable:!0}),e),zr=(e,t)=>Rr(e,Lr(t)),Br=(e,t)=>{if(t[Pr])return Lr(t);let n=new Set(Lr(e));for(let e of Nr){let r=xr(t,e);r===`clear`&&n.delete(e),r===`explicit`&&n.add(e)}return[...n]},Vr=(e,t)=>{let n=e?.[Pr];return!n||!Object.prototype.hasOwnProperty.call(n.values,t)||Ir(e,t)!==n.values[t]?xr(e,t)===`explicit`:n.explicit.includes(t)},Hr=(e,t)=>Vr(e,t)?Ir(e,t):void 0,Ur=(e,t,n)=>{let r=e,i=n??r?.colorScheme??_r(r?.brand)??`light`,a=i===`dark`||i===`auto`&&(typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches);return Vr(e,`theme.components.${t}`)||a&&Vr(e,`darkTheme.components.${t}`)}})),J,Y,Gr,X=B((()=>{J=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Y=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},Gr=(...e)=>e.filter(Boolean).join(` `)})),Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Z,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,Q,zi,Bi,Vi,Hi,Ui,Wi,Gi=B((()=>{Wr(),X(),Kr=`ask_user_question`,qr=`data-persona-ask-sheet-for`,Jr=`Other`,Yr=`Other…`,Xr=`Type your own answer here`,Zr=`Send`,Qr=`Next`,$r=`Back`,ei=`Submit all`,ti=`Skip`,ni=3,ri=`data-ask-current-index`,ii=`data-ask-question-count`,ai=`data-ask-answers`,oi=`data-ask-grouped`,si=`data-ask-layout`,ci=e=>e.layout===`pills`?`pills`:`rows`,li=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,ui=!1,di=e=>e.replace(/["\\]/g,`\\$&`),fi=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,pi=e=>e?.features?.askUserQuestion??{},mi=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=Rt(e,Lt|It|Ft);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},hi=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!ui&&(ui=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},gi=e=>hi(e)[0]??null,_i=(e,t)=>hi(e)[t]??null,vi={sheetBackground:`--persona-ask-sheet-bg`,sheetBorder:`--persona-ask-sheet-border`,sheetShadow:`--persona-ask-sheet-shadow`,pillBackground:`--persona-ask-pill-bg`,pillBackgroundSelected:`--persona-ask-pill-bg-selected`,pillTextColor:`--persona-ask-pill-fg`,pillTextColorSelected:`--persona-ask-pill-fg-selected`,pillBorderRadius:`--persona-ask-pill-radius`,customInputBackground:`--persona-ask-input-bg`},yi=(e,t)=>{Object.entries(vi).forEach(([n,r])=>{let i=Hr(t,`features.askUserQuestion.styles.${n}`);typeof i==`string`&&i?e.style.setProperty(r,i):e.style.removeProperty(r)})},bi=(e,t,n)=>{if(e!==`rows`)return null;let r=J(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=J(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=J(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},xi=(e,t,n,r)=>{let i=J(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=J(`span`,`persona-ask-row-content`),o=J(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=J(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=bi(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},Si=e=>{let t=J(`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 t.setAttribute(`aria-hidden`,`true`),t},Ci=(e,t,n,r)=>{let i=J(`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`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<ni;e++)i.appendChild(Si(r));return i}if(o.forEach((e,t)=>{i.appendChild(xi(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?Jr:Yr;if(r===`rows`){let n=J(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=J(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??Xr,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=bi(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=J(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},wi=(e,t)=>{let n=J(`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`);n.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??Xr,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=J(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??Zr,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},Ti=e=>{let t=J(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=J(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??Zr,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Z=(e,t,n)=>{let r=J(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=J(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??$r,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=J(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=J(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??ti,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=J(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??ei:n.nextLabel??Qr,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Ei=e=>{let t=e.getAttribute(ai);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Di=(e,t)=>{e.setAttribute(ai,JSON.stringify(t))},Oi=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ki=(e,t)=>{e.setAttribute(ri,String(Math.max(0,Math.floor(t))))},Ai=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ji=e=>e.getAttribute(oi)===`true`,Mi=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Ni=(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)))},Pi=(e,t)=>{let{payload:n}=mi(t),r=hi(n),i=Ei(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Fi=e=>{let t=Ei(e)[Oi(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},Ii=e=>{if(!ji(e))return;let t=Ei(e)[Oi(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},Li=(e,t,n)=>{let r=pi(n),i=li(e),{payload:a,complete:o}=mi(t),s=ji(e),c=Oi(e),l=Ai(e),u=s?_i(a,c):gi(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=Ci(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(wi(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(Ti(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Z(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Fi(e),Ii(e)},Ri=(e,t,n)=>{let r=pi(t),i=ci(r),a=e.toolCall.id,o=hi(n),s=Math.max(1,o.length),c=s>1,l=Mi(e,o),u=c?Ni(e,s):0,d=J(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(qr,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(ii,String(s)),d.setAttribute(ri,String(u)),d.setAttribute(oi,c?`true`:`false`),d.setAttribute(si,i),Di(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),yi(d,t);let f=J(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=J(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=J(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=J(`div`,i===`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 h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(wi(r,i)),Li(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Q=(e,t,n)=>{yi(e,n);let{payload:r}=mi(t),i=Math.max(1,hi(r).length);i>Ai(e)&&(e.setAttribute(ii,String(i)),i>1&&!ji(e)&&e.setAttribute(oi,`true`)),Li(e,t,n)},zi=(e,t)=>{let n=J(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`),yi(n,t);let r=J(`span`,`persona-ask-stub-label`),{complete:i}=mi(e);return r.textContent=i?`Awaiting your response…`:`Preparing options…`,n.appendChild(r),n},Bi=(e,t,n)=>{if(!n||!fi(e)||pi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${qr}]`).forEach(e=>{e.getAttribute(qr)!==r&&e.remove()});let i=n.querySelector(`[${qr}="${di(r)}"]`);if(i){Q(i,e,t);return}let{payload:a}=mi(e),o=Ri(e,t,a);n.appendChild(o)},Vi=(e,t)=>{if(!e)return;let n=t?`[${qr}="${di(t)}"]`:`[${qr}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Hi=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),Ui=(e,t)=>{let n=Ei(e),r=Oi(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Di(e,n),Fi(e),Ii(e)},Wi=(e,t,n,r)=>{let i=Ai(e),a=Math.max(0,Math.min(i-1,r));ki(e,a),Li(e,t,n)}})),Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra=B((()=>{Ki=`suggest_replies`,qi={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},Ji={name:Ki,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:qi,origin:`sdk`,annotations:{readOnlyHint:!0}},Yi=e=>{let t=e?.suggestions?.followUps?.maxItems,n=typeof t==`number`&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return n===4?Ji:{...Ji,parametersSchema:{...qi,properties:{suggestions:{...qi.properties.suggestions,maxItems:n,description:`1-${n} short, distinct follow-up replies, phrased in the user's voice.`}}}}},Xi=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Zi=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Qi=(e,t=4)=>{let n=e;if(typeof n==`string`)try{n=JSON.parse(n)}catch{return[]}let r=n?.suggestions;if(!Array.isArray(r))return[];let i=r.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return i.length>t?(console.warn(`[persona] suggest_replies: ${i.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),i.slice(0,t)):i},$i=(e,t=4)=>{for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role===`user`)return null;if(!Zi(r))continue;let i=Qi(r.toolCall?.args,t);return i.length>0?i:null}return null},ea=/* @__PURE__ */ new Set,ta=(e,t,n)=>{let r=`${e}:${t}:${n}`;ea.has(r)||(ea.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},na=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&ta(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),ia,aa,oa,sa=B((()=>{Gi(),ra(),ia={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,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},aa={name:Kr,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:ia,origin:`sdk`,annotations:{readOnlyHint:!0}},oa=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(aa),na(e).expose&&t.push(Yi(e)),t}})),ca,la,ua,da=B((()=>{ca={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},la=1e5,ua=100001}));async function fa(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function pa(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o,r?.assistantMessageId&&(l.assistantMessageId=r.assistantMessageId)),i&&o){let t=[...oa(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var ma=B((()=>{sa(),da()})),ha=/* @__PURE__ */ Vt({preferFinalStructuredContent:()=>_a,resolveApproval:()=>fa,resumeFlow:()=>pa,streamResponse:()=>ya});function ga(e){let t=e.toLowerCase(),n=t===`text/plain`?`txt`:t===`text/markdown`?`md`:void 0;if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function _a(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(!n)return t;if(!r)return e;let i=xa(n);if(!xa(r))return e;if(!i||r.startsWith(n))return t;let a=nr(e);return nr(t)!==null&&a===null?t:e}async function va(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function ya(e,t,n,r,i,a,o,s){let c=e.streamGeneration(),l=t.getReader();e.streamReaders.add(l);let u=!!e.config().backgroundConversations,d=()=>{u&&l.cancel().catch(()=>{})};a?.addEventListener(`abort`,d,{once:!0});let f=new TextDecoder,p=``,m=Date.now(),h=0,g=()=>m+h++,_=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),v=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?_(e.toolCall):void 0,tools:e.tools?.map(_)}),y=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},b=t=>{!a?.aborted&&c===e.streamGeneration()&&y(t)&&n({type:`message`,message:v(t)})},x=null,S=null,C={current:null},ee={current:null},w=null,T=``,E=new Map(s?.textPhases),te=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,ne=/* @__PURE__ */ new Map,re=/* @__PURE__ */ new Map,ie=/* @__PURE__ */ new Map,ae=r,oe=!1,O=o?.find(e=>e.id===r);O&&(x=v(O),x.streaming=s?.openAssistant??!0,oe=!0,w=O.agentMetadata?.textBlockId??null,T=O.rawContent??O.content,S=x,s&&!s.openAssistant&&(x=null)),s&&(w=s.textBlockId,T=s.rawText,s.nestedParents.forEach(([e,t])=>te.set(e,t)),s.nestedRaw.forEach(([e,t])=>ne.set(e,t)));for(let e of o??[]){e.variant===`tool`&&e.toolCall?.id&&ie.set(e.toolCall.id,v(e)),e.variant===`reasoning`&&e.reasoning?.id&&re.set(e.reasoning.id,v(e));let t=e.agentMetadata?.textBlockId;t&&(D.set(t,e.id===x?.id?x:v(e)),e.agentMetadata?.phase&&E.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&(te.set(t,n),ne.set(t,e.rawContent??e.content))}let se=()=>{if(x)return x;let e,t=``,n=w;return!oe&&ae?(e=ae,oe=!0,t=i??``):e=ae&&n?`${ae}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g()},b(x),x},ce=(e,t)=>{let n=re.get(e);if(n)return n;let r={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,agentMetadata:{executionId:t},sequence:g(),reasoning:{id:e,status:`streaming`,chunks:[]}};return re.set(e,r),b(r),r},k=/* @__PURE__ */ new Set,le=/* @__PURE__ */ new Map,ue=/* @__PURE__ */ new Set;for(let e of o??[])if(e.id.startsWith(`artifact-ref-`)){let t=e.id.slice(13);ue.add(t),le.set(t,v(e))}s?.artifactTools.forEach(e=>k.add(e));let de=/* @__PURE__ */ new Map;s?.artifactContent.forEach(([e,t])=>de.set(e,{...t}));let fe=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},pe=(e,t,n)=>{let r=ie.get(e),i={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(Ee||void 0)};if(r)return r.agentMetadata=i,r;let a={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,agentMetadata:i,sequence:g(),toolCall:{id:e,status:`pending`}};return ie.set(e,a),b(a),a},me=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},he=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},A=/* @__PURE__ */ new Map,ge=/* @__PURE__ */ new Map,_e=(e,t)=>{let n=he(t),r=_a(ge.get(e.id),n);e.rawContent=r;let i=A.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{let t=i?.close?.();t instanceof Promise&&t.catch(()=>{}),A.delete(e.id),ge.delete(e.id),e.streaming=!1,b(e)};if(!i){a(n),o();return}let s=nr(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ve=null,ye=o?.find(e=>e.id===s?.sealedFlowMessageId);ye&&(ve=v(ye));let be=(t,n,r)=>{t.rawContent=n,A.has(t.id)||A.set(t.id,e.createStreamParser());let i=A.get(t.id),a=/^[{[]/.test(n.trim());a&&ge.set(t.id,n);let o=()=>{t.content+=r,ge.delete(t.id),A.delete(t.id),t.rawContent=void 0,b(t)};if(i.__isPlainTextParser===!0){o();return}let s=e=>{let r=typeof e==`string`?e:e?.text??null;r!==null&&r.trim()!==``?(t.content=r,b(t)):!a&&!n.trim().startsWith(`<`)&&o()},c=i.processChunk(n);c instanceof Promise?c.then(s).catch(o):s(c)},xe=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,b(e);return}let r=ge.get(e.id)??he(n);e.rawContent=r;let i=A.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=nr(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,A.delete(e.id),ge.delete(e.id),b(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:ge.has(e.id)||(e.content=he(n));let t=A.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),A.delete(e.id)}ge.delete(e.id),e.streaming=!1,b(e)}},Se=(e,t,n,r)=>{let i=D.get(e);if(i)return i;let a={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:E.get(e)}};return D.set(e,a),b(a),a},Ce=[],we,Te=/* @__PURE__ */ new Map;s?.media.forEach(([e,t])=>Te.set(e,{...t,parts:[...t.parts]}));let Ee=s?.iteration??0,De=s?.executionKind??`agent`,j=s?.executionKindResolved??!1,Oe=s?.turnId??null,M=null,ke=e.config().iterationDisplay??`separate`;we=()=>{for(let t=0;t<Ce.length;t++){let r=Ce[t];if(!j&&De!==`flow`&&typeof r.stepType==`string`&&(De=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){te.set(e,t),Se(e,t,`reasoning`,r.executionId);continue}let n=r.id,i=ce(n,r.executionId);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,b(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&te.has(e)&&D.has(e)){let t=D.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=r.id,n=ce(t,r.executionId);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,b(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&te.has(e)&&D.has(e)){let t=D.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,b(t)}te.delete(e),D.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!re.get(t)&&(n||r.scope===`loop`)&&ce(t,r.executionId);let i=re.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,b(i)}}else if(r.type===`tool_start`){x&&=(x.streaming=!1,b(x),null),typeof r.iteration==`number`&&(Ee=r.iteration);let e=r.toolCallId,t=r.toolName;if(fe(t)){k.add(e);continue}let n=pe(e,r.executionId,r.iteration),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??me(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,b(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(k.has(e))continue;let t=pe(e,r.executionId),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,b(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(k.has(e)){k.delete(e);continue}let t=pe(e,r.executionId,r.iteration),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,b(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${g()}`,n=pe(t,r.executionId),i=r.toolName,a=r.origin===`webmcp`&&!Wn(i)?`webmcp:${i}`:i,o=Wn(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??me(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},b(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null;if(e){let t=ba(r.phase);t?E.set(e,t):E.delete(e)}let t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){te.set(e,t);continue}let n=x;n&&(De===`flow`?(xe(n),ve=n):(n.streaming=!1,b(n)),x=null),w=e??w,T=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?te.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(ne.get(e)??``)+n;if(ne.set(e,i),i.trim()===``)continue;let a=Se(e,t,void 0,r.executionId);be(a,i,n);continue}w=e??w;let n=typeof r.delta==`string`?r.delta:``;if(T+=n,De===`flow`&&T.trim()===``)continue;let i=se();i.agentMetadata={textBlockId:w??void 0,phase:E.get(w??``),executionId:r.executionId,iteration:Ee,...De===`flow`?{}:{turnId:Oe??void 0,agentName:M?.agentName}},w&&D.set(w,i),be(i,T,n),S=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;e&&E.delete(e);let t=e?D.get(e):x,n=ba(r.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&te.has(e)){let t=D.get(e);t&&xe(t),te.delete(e),ne.delete(e),D.delete(e);continue}if(e&&t!==x){t&&(t.streaming=!1,b(t));continue}let i=x;i&&(De===`flow`?(xe(i),ve=i):((i.content??``)===``&&typeof r.text==`string`&&(i.content=r.text),i.streaming=!1,b(i)),x=null),w=null,T=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),n({type:`status`,status:`idle`});continue}{let e=ve;ve=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(A.delete(e.id),ge.delete(e.id),e.streaming=!1,b(e)):_e(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=se();t&&(r.stopReason=t),e?xe(r,n):(r.streaming=!1,b(r))}}continue}}else if(r.type===`execution_start`)De=r.kind===`flow`?`flow`:`agent`,j=!0,e.config().backgroundConversations&&n({type:`status`,status:`connected`,executionId:r.executionId}),De===`agent`&&(M={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:Ee;if(e!==Ee){if(ke===`separate`&&e>1){let e=x;e&&(e.streaming=!1,b(e),x=null)}Ee=e}Oe=typeof r.id==`string`?r.id:null,S=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=ie.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),b(t))}}else if(r.type===`tool_input_complete`){if(k.has(r.toolCallId))continue;let e=pe(r.toolCallId,r.executionId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,b(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=x??S;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,b(t))}Oe===r.id&&(Oe=null)}else if(r.type===`media_start`){let e=String(r.id);Te.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=Te.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=Te.get(e);Te.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:ga(e)})}}}if(l.length>0){let e=g(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:Ee}};b(n);let i=x;i&&(i.streaming=!1,b(i)),x=null,C.current=null}}else if(r.type===`execution_complete`){let e=x;e&&(r.kind===`flow`&&e.streaming!==!1?xe(e):(e.streaming=!1,b(e)),x=null),w=null,T=``,ve=null,n({type:`status`,status:r.success===!1?`error`:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${g()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:g(),approval:{id:e,status:`pending`,agentId:M?.agentId??`virtual`,executionId:r.executionId??M?.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}:{}}};b(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:g(),approval:{id:e,status:r.decision??`approved`,agentId:M?.agentId??`virtual`,executionId:r.executionId??M?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};b(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),de.set(i,{markdown:``,title:a,file:s}),!ue.has(i)){ue.add(i);let n=Xn(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g(),rawContent:Zn(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};le.set(i,c),b(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=de.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=de.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=le.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=de.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}de.delete(e),b(t),le.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),n({type:`status`,status:`idle`})}}}Ce.length=0};try{for(;;){if(c!==e.streamGeneration())return;a?.throwIfAborted();let{done:t,value:r}=await l.read();if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),t)break;p+=f.decode(r,{stream:!0});let i=p.split(`
5
+ `).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),tr=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return er(t)}catch{return t}};return{getExtractedText:()=>e,processChunk:async r=>{let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(r.length<=t)return e===null?null:{text:e,raw:r};let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},nr=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},rr=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ir=()=>tr(),ar=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=Rt(n,Lt|It);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?er(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=er(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},or=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?er(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?er(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=Rt(e,Lt|It),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},sr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}}));function lr(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=ur(t)&&ur(r)?lr(t,r):r}return n}var ur,dr=B((()=>{ur=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),fr,pr,mr,hr,gr,_r,vr,yr=B((()=>{dr(),fr=e=>{if(typeof e!=`string`)return;let t=e.trim(),n=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(t)?.[1];if(n){let e=n.length===3?[...n].map(e=>e+e).join(``):n;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let r=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!r)return;let i=r[1].trim().split(/\s*[,/]\s*|\s+/);if(i.length===4&&/^(?:1(?:\.0+)?|100%)$/.test(i[3])&&i.pop(),i.length!==3)return;let a=i.map(e=>/^\d+(?:\.\d+)?%?$/.test(e)?Number.parseFloat(e)*(e.endsWith(`%`)?2.55:1):NaN);if(!a.some(e=>!Number.isFinite(e)||e<0||e>255))return a},pr=e=>e.reduce((e,t,n)=>{let r=t/255;return e+(r<=.04045?r/12.92:((r+.055)/1.055)**2.4)*[.2126,.7152,.0722][n]},0),mr=e=>`#`+e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``),hr=(e,t,n)=>mr(e.map(e=>e+(t-e)*n)),gr=e=>pr(e)>.179?`#000000`:`#ffffff`,_r=e=>{let t=fr(e?.neutral);return t?pr(t)<.18?`dark`:`light`:void 0},vr=(e,t=`light`,n,r=!1)=>{let i={};if(!e)return i;let a=fr(e.accent);if(a){let e={};for(let[t,n]of[[50,.96],[100,.9],[200,.75],[300,.55],[400,.25]])e[t]=hr(a,255,n);e[500]=mr(a);for(let[t,n]of[[600,.15],[700,.3],[800,.45],[900,.6],[950,.75]])e[t]=hr(a,0,n);let t=gr(a);i.palette={colors:{primary:e,accent:e}},i.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},i.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:r?{background:`semantic.colors.container`,foreground:`semantic.colors.text`,iconBackground:`transparent`,iconForeground:`semantic.colors.text`}:{background:e[500],foreground:t,iconBackground:e[500],iconForeground:t},approval:{approve:{foreground:t}},message:{user:r?{background:`color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))`,text:`semantic.colors.text`}:{background:e[500],text:t}}}}let o=fr(e.neutral);if(o){let e=t===`dark`,n=e===pr(o)<.18?o:fr(hr(o,e?0:255,.9)),r=mr(n),a=hr(n,e?255:0,e?.06:.025),s=hr(n,e?255:0,e?.2:.16),c=gr(n),l={};for(let[e,t]of[[50,0],[100,.06],[200,.16],[300,.28],[400,.45],[500,.65],[600,.72],[700,.8],[800,.9],[900,.97],[950,1]])l[e]=hr(n,c===`#ffffff`?255:0,t);i.palette={...i.palette,colors:{...i.palette?.colors,gray:l}},i.semantic={...i.semantic,colors:{...i.semantic?.colors,surface:r,background:r,container:a,border:s,divider:s,text:c,textMuted:hr(n,c===`#ffffff`?255:0,.65)}},i.components={...i.components,panel:{background:r},header:{...i.components?.header,background:r,foreground:c},composer:{footerBackground:r}}}if(a){let e=fr(i.semantic?.colors?.surface)??(t===`dark`?[15,15,16]:[255,255,255]),n=mr(a),r=gr(e)===`#ffffff`?255:0;for(let t=0;t<=1;t+=.1){n=hr(a,r,t);let i=pr(fr(n)),o=pr(e);if((Math.max(i,o)+.05)/(Math.min(i,o)+.05)>=4.5)break}i.components={...i.components,markdown:{link:{foreground:n}},input:{focus:{border:n,ring:n}}}}e.font?.trim()&&(i.semantic={...i.semantic,typography:{fontFamily:e.font}});let s={none:`0px`,sm:`4px`,md:`8px`,lg:`16px`}[e.radius??`none`];e.radius&&s&&(i.palette={...i.palette,radius:{none:`0px`,sm:s,md:s,lg:s,xl:s,"2xl":s}},i.components={...i.components,input:{...i.components?.input,borderRadius:s},header:{...i.components?.header,controlBorderRadius:s}});let c={compact:[13,44,8],comfortable:[14,48,12],spacious:[15,52,16]}[e.density??`comfortable`];if(e.density&&c){let[e,t,n]=c;i.semantic={...i.semantic,typography:{...i.semantic?.typography,fontSize:`${e}px`}},i.components={...i.components,header:{...i.components?.header,minHeight:`${t}px`,padding:`${n}px 16px`,minimalPadding:`${n}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...i.components?.composer,fontSize:`${e}px`,padding:`${n}px`,gap:`${n/2}px`},message:{...i.components?.message,gap:`${n}px`,user:{...i.components?.message?.user,fontSize:`${e}px`},assistant:{fontSize:`${e}px`}}}}if(e.elevation&&[`flat`,`subtle`,`raised`].includes(e.elevation)){let t=e.elevation===`flat`,a=t?`none`:e.elevation===`subtle`?`0 2px 8px rgba(0, 0, 0, 0.08)`:`0 12px 32px rgba(0, 0, 0, 0.18)`,o=t?`1px solid var(--persona-border)`:`1px solid color-mix(in srgb, var(--persona-border) 65%, transparent)`;i.palette={...i.palette,shadows:{sm:a,md:a,lg:a,xl:a,"2xl":a}};let s=(e,n=``)=>{let i={};if(r&&n===`message.assistant`)return i;for(let[r,c]of Object.entries(e))if(r.toLowerCase().endsWith(`shadow`)){i[r]=a;let n=r===`shadow`?`border`:r.replace(/Shadow$/,`Border`);n in e&&(i[n]=typeof e[n]==`string`&&e[n].includes(`solid`)?o:t?`semantic.colors.border`:`color-mix(in srgb, var(--persona-border) 65%, transparent)`)}else if(c&&typeof c==`object`){let e=s(c,n?`${n}.${r}`:r);Object.keys(e).length&&(i[r]=e)}return i},c=n?s(n):{};i.components=lr(i.components,c),i.components={...i.components,panel:{...i.components?.panel,shadow:a,modes:{floating:{shadow:a,border:o},inline:{shadow:a,border:o},docked:{shadow:a,border:o},sidebar:{shadow:a,border:o},mobile:{shadow:a,border:o}}},launcher:{...i.components?.launcher,shadow:a,border:`semantic.colors.border`},composer:{...i.components?.composer,shadow:a,borderColor:`semantic.colors.border`},toolBubble:{shadow:a},reasoningBubble:{shadow:a}}}return i}}));function br(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return Or(n)?br(n,r):[r]})}function xr(e,t){let n=t.split(`.`);for(let t=0;t<n.length;t++){let r=n[t];if(!Or(e)||!Object.prototype.hasOwnProperty.call(e,r))return`absent`;if(e=e[r],e===void 0||t<n.length-1&&!Or(e))return`clear`}return`explicit`}function Sr(e,t){return e?.[Dr]??t.filter(t=>xr(e,t)===`explicit`)}function Cr(e,t){return Object.defineProperty(e,Dr,{value:t,enumerable:!0,configurable:!0}),e}function wr(e,t,n){return Cr(e,Sr(t,br(n)))}function Tr(e,t,n){let r=t[Dr];if(r)return r;let i=new Set(Sr(e,n));for(let e of n){let n=xr(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function Er(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!Or(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var Dr,Or,kr=B((()=>{Dr=Symbol.for(`persona.defaultsProvenance`),Or=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr=B((()=>{yr(),kr(),Ar=(e,t)=>t.split(` `).map(t=>`${e}.${t}`),jr=[...Ar(`launcher`,`closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY`),...Ar(`launcher.clearChat`,`size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY`),...Ar(`sendButton`,`size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY`),...Ar(`voiceRecognition`,`iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor`),...Ar(`toolCall`,`shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration`),...Ar(`approval`,`backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor`),...Ar(`features.askUserQuestion.styles`,`sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground`),...Ar(`features.artifacts.layout`,`paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize`),...Ar(`suggestionChipsConfig`,`fontWeight paddingX paddingY`)],Mr=[`voice.recording.border`,`voice.processing.icon`,`voice.processing.background`,`voice.speaking.icon`,`approval.requested.text`,`approval.approve.foreground`,`approval.deny.foreground`,`approval.deny.background`,`reasoningBubble.shadow`,`toolBubble.shadow`],Nr=[...jr,`suggestionChips`,`copy.welcomeTitle`,`copy.welcomeSubtitle`,`copy.showWelcomeCard`,`features.suggestReplies.enabled`,`features.suggestReplies.expose`,...[`theme`,`darkTheme`].flatMap(e=>Mr.map(t=>`${e}.components.${t}`))],Pr=Symbol.for(`persona.styleProvenance`),Fr=e=>e[Pr]!==void 0,Ir=(e,t)=>{for(let n of t.split(`.`)){if(typeof e!=`object`||!e)return;e=e[n]}return e},Lr=e=>{let t=e?.[Pr];if(!t)return Nr.filter(t=>xr(e,t)===`explicit`);let n=new Set(t.explicit);return Nr.forEach(r=>{Ir(e,r)!==t.values[r]&&(xr(e,r)===`explicit`?n.add(r):n.delete(r))}),[...n]},Rr=(e,t)=>(Object.defineProperty(e,Pr,{value:{explicit:t,values:Object.fromEntries(Nr.map(t=>[t,Ir(e,t)]))},enumerable:!0,configurable:!0}),e),zr=(e,t)=>Rr(e,Lr(t)),Br=(e,t)=>{if(t[Pr])return Lr(t);let n=new Set(Lr(e));for(let e of Nr){let r=xr(t,e);r===`clear`&&n.delete(e),r===`explicit`&&n.add(e)}return[...n]},Vr=(e,t)=>{let n=e?.[Pr];return!n||!Object.prototype.hasOwnProperty.call(n.values,t)||Ir(e,t)!==n.values[t]?xr(e,t)===`explicit`:n.explicit.includes(t)},Hr=(e,t)=>Vr(e,t)?Ir(e,t):void 0,Ur=(e,t,n)=>{let r=e,i=n??r?.colorScheme??_r(r?.brand)??`light`,a=i===`dark`||i===`auto`&&(typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches);return Vr(e,`theme.components.${t}`)||a&&Vr(e,`darkTheme.components.${t}`)}})),J,Y,Gr,X=B((()=>{J=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Y=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},Gr=(...e)=>e.filter(Boolean).join(` `)})),Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Z,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,Q,zi,Bi,Vi,Hi,Ui,Wi,Gi=B((()=>{Wr(),X(),Kr=`ask_user_question`,qr=`data-persona-ask-sheet-for`,Jr=`Other`,Yr=`Other…`,Xr=`Type your own answer here`,Zr=`Send`,Qr=`Next`,$r=`Back`,ei=`Submit all`,ti=`Skip`,ni=3,ri=`data-ask-current-index`,ii=`data-ask-question-count`,ai=`data-ask-answers`,oi=`data-ask-grouped`,si=`data-ask-layout`,ci=e=>e.layout===`pills`?`pills`:`rows`,li=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,ui=!1,di=e=>e.replace(/["\\]/g,`\\$&`),fi=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,pi=e=>e?.features?.askUserQuestion??{},mi=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=Rt(e,Lt|It|Ft);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},hi=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!ui&&(ui=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},gi=e=>hi(e)[0]??null,_i=(e,t)=>hi(e)[t]??null,vi={sheetBackground:`--persona-ask-sheet-bg`,sheetBorder:`--persona-ask-sheet-border`,sheetShadow:`--persona-ask-sheet-shadow`,pillBackground:`--persona-ask-pill-bg`,pillBackgroundSelected:`--persona-ask-pill-bg-selected`,pillTextColor:`--persona-ask-pill-fg`,pillTextColorSelected:`--persona-ask-pill-fg-selected`,pillBorderRadius:`--persona-ask-pill-radius`,customInputBackground:`--persona-ask-input-bg`},yi=(e,t)=>{Object.entries(vi).forEach(([n,r])=>{let i=Hr(t,`features.askUserQuestion.styles.${n}`);typeof i==`string`&&i?e.style.setProperty(r,i):e.style.removeProperty(r)})},bi=(e,t,n)=>{if(e!==`rows`)return null;let r=J(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=J(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=J(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},xi=(e,t,n,r)=>{let i=J(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=J(`span`,`persona-ask-row-content`),o=J(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=J(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=bi(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},Si=e=>{let t=J(`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 t.setAttribute(`aria-hidden`,`true`),t},Ci=(e,t,n,r)=>{let i=J(`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`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<ni;e++)i.appendChild(Si(r));return i}if(o.forEach((e,t)=>{i.appendChild(xi(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?Jr:Yr;if(r===`rows`){let n=J(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=J(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??Xr,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=bi(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=J(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},wi=(e,t)=>{let n=J(`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`);n.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??Xr,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=J(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??Zr,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},Ti=e=>{let t=J(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=J(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??Zr,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Z=(e,t,n)=>{let r=J(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=J(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??$r,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=J(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=J(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??ti,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=J(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??ei:n.nextLabel??Qr,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Ei=e=>{let t=e.getAttribute(ai);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Di=(e,t)=>{e.setAttribute(ai,JSON.stringify(t))},Oi=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ki=(e,t)=>{e.setAttribute(ri,String(Math.max(0,Math.floor(t))))},Ai=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ji=e=>e.getAttribute(oi)===`true`,Mi=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Ni=(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)))},Pi=(e,t)=>{let{payload:n}=mi(t),r=hi(n),i=Ei(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Fi=e=>{let t=Ei(e)[Oi(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},Ii=e=>{if(!ji(e))return;let t=Ei(e)[Oi(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},Li=(e,t,n)=>{let r=pi(n),i=li(e),{payload:a,complete:o}=mi(t),s=ji(e),c=Oi(e),l=Ai(e),u=s?_i(a,c):gi(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=Ci(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(wi(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(Ti(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Z(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Fi(e),Ii(e)},Ri=(e,t,n)=>{let r=pi(t),i=ci(r),a=e.toolCall.id,o=hi(n),s=Math.max(1,o.length),c=s>1,l=Mi(e,o),u=c?Ni(e,s):0,d=J(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(qr,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(ii,String(s)),d.setAttribute(ri,String(u)),d.setAttribute(oi,c?`true`:`false`),d.setAttribute(si,i),Di(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),yi(d,t);let f=J(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=J(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=J(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=J(`div`,i===`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 h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(wi(r,i)),Li(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Q=(e,t,n)=>{yi(e,n);let{payload:r}=mi(t),i=Math.max(1,hi(r).length);i>Ai(e)&&(e.setAttribute(ii,String(i)),i>1&&!ji(e)&&e.setAttribute(oi,`true`)),Li(e,t,n)},zi=(e,t)=>{let n=J(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`),yi(n,t);let r=J(`span`,`persona-ask-stub-label`),{complete:i}=mi(e);return r.textContent=i?`Awaiting your response…`:`Preparing options…`,n.appendChild(r),n},Bi=(e,t,n)=>{if(!n||!fi(e)||pi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${qr}]`).forEach(e=>{e.getAttribute(qr)!==r&&e.remove()});let i=n.querySelector(`[${qr}="${di(r)}"]`);if(i){Q(i,e,t);return}let{payload:a}=mi(e),o=Ri(e,t,a);n.appendChild(o)},Vi=(e,t)=>{if(!e)return;let n=t?`[${qr}="${di(t)}"]`:`[${qr}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Hi=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),Ui=(e,t)=>{let n=Ei(e),r=Oi(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Di(e,n),Fi(e),Ii(e)},Wi=(e,t,n,r)=>{let i=Ai(e),a=Math.max(0,Math.min(i-1,r));ki(e,a),Li(e,t,n)}})),Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra=B((()=>{Ki=`suggest_replies`,qi={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},Ji={name:Ki,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:qi,origin:`sdk`,annotations:{readOnlyHint:!0}},Yi=e=>{let t=e?.suggestions?.followUps?.maxItems,n=typeof t==`number`&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return n===4?Ji:{...Ji,parametersSchema:{...qi,properties:{suggestions:{...qi.properties.suggestions,maxItems:n,description:`1-${n} short, distinct follow-up replies, phrased in the user's voice.`}}}}},Xi=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Zi=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Qi=(e,t=4)=>{let n=e;if(typeof n==`string`)try{n=JSON.parse(n)}catch{return[]}let r=n?.suggestions;if(!Array.isArray(r))return[];let i=r.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return i.length>t?(console.warn(`[persona] suggest_replies: ${i.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),i.slice(0,t)):i},$i=(e,t=4)=>{for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role===`user`)return null;if(!Zi(r))continue;let i=Qi(r.toolCall?.args,t);return i.length>0?i:null}return null},ea=/* @__PURE__ */ new Set,ta=(e,t,n)=>{let r=`${e}:${t}:${n}`;ea.has(r)||(ea.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},na=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&ta(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),ia,aa,oa,sa=B((()=>{Gi(),ra(),ia={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,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},aa={name:Kr,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:ia,origin:`sdk`,annotations:{readOnlyHint:!0}},oa=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(aa),na(e).expose&&t.push(Yi(e)),t}})),ca,la,ua,da=B((()=>{ca={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},la=1e5,ua=100001}));async function fa(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function pa(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o,r?.assistantMessageId&&(l.assistantMessageId=r.assistantMessageId)),i&&o){let t=[...oa(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var ma=B((()=>{sa(),da()})),ha=/* @__PURE__ */ Vt({preferFinalStructuredContent:()=>_a,resolveApproval:()=>fa,resumeFlow:()=>pa,streamResponse:()=>ya});function ga(e){let t=e.toLowerCase(),n=t===`text/plain`?`txt`:t===`text/markdown`?`md`:void 0;if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function _a(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(!n)return t;if(!r)return e;let i=xa(n);if(!xa(r))return e;if(!i||r.startsWith(n))return t;let a=nr(e);return nr(t)!==null&&a===null?t:e}async function va(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function ya(e,t,n,r,i,a,o,s){let c=e.streamGeneration(),l=t.getReader();e.streamReaders.add(l);let u=!!e.config().backgroundConversations,d=()=>{u&&l.cancel().catch(()=>{})};a?.addEventListener(`abort`,d,{once:!0});let f=new TextDecoder,p=``,m=Date.now(),h=0,g=()=>m+h++,_=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),v=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?_(e.toolCall):void 0,tools:e.tools?.map(_)}),y=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},b=t=>{!a?.aborted&&c===e.streamGeneration()&&y(t)&&n({type:`message`,message:v(t)})},x=null,S=null,C={current:null},ee={current:null},w=null,T=``,E=new Map(s?.textPhases),te=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,ne=/* @__PURE__ */ new Map,re=/* @__PURE__ */ new Map,ie=/* @__PURE__ */ new Map,ae=r,oe=!1,O=o?.find(e=>e.id===r);O&&(x=v(O),x.streaming=s?.openAssistant??!0,oe=!0,w=O.agentMetadata?.textBlockId??null,T=O.rawContent??O.content,S=x,s&&!s.openAssistant&&(x=null)),s&&(w=s.textBlockId,T=s.rawText,s.nestedParents.forEach(([e,t])=>te.set(e,t)),s.nestedRaw.forEach(([e,t])=>ne.set(e,t)));for(let e of o??[]){e.variant===`tool`&&e.toolCall?.id&&ie.set(e.toolCall.id,v(e)),e.variant===`reasoning`&&e.reasoning?.id&&re.set(e.reasoning.id,v(e));let t=e.agentMetadata?.textBlockId;t&&(D.set(t,e.id===x?.id?x:v(e)),e.agentMetadata?.phase&&E.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&(te.set(t,n),ne.set(t,e.rawContent??e.content))}let se=()=>{if(x)return x;let e,t=``,n=w;return!oe&&ae?(e=ae,oe=!0,t=i??``):e=ae&&n?`${ae}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g()},b(x),x},ce=(e,t)=>{let n=re.get(e);if(n)return n;let r={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,agentMetadata:{executionId:t},sequence:g(),reasoning:{id:e,status:`streaming`,chunks:[]}};return re.set(e,r),b(r),r},k=/* @__PURE__ */ new Set,le=/* @__PURE__ */ new Map,ue=/* @__PURE__ */ new Set;for(let e of o??[])if(e.id.startsWith(`artifact-ref-`)){let t=e.id.slice(13);ue.add(t),le.set(t,v(e))}s?.artifactTools.forEach(e=>k.add(e));let de=/* @__PURE__ */ new Map;s?.artifactContent.forEach(([e,t])=>de.set(e,{...t}));let fe=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},pe=(e,t,n)=>{let r=ie.get(e),i={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(Ee||void 0)};if(r)return r.agentMetadata=i,r;let a={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,agentMetadata:i,sequence:g(),toolCall:{id:e,status:`pending`}};return ie.set(e,a),b(a),a},me=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},he=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},A=/* @__PURE__ */ new Map,ge=/* @__PURE__ */ new Map,_e=(e,t)=>{let n=he(t),r=_a(ge.get(e.id),n);e.rawContent=r;let i=A.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{let t=i?.close?.();t instanceof Promise&&t.catch(()=>{}),A.delete(e.id),ge.delete(e.id),e.streaming=!1,b(e)};if(!i){a(n),o();return}let s=nr(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ve=null,ye=o?.find(e=>e.id===s?.sealedFlowMessageId);ye&&(ve=v(ye));let be=(t,n,r)=>{t.rawContent=n,A.has(t.id)||A.set(t.id,e.createStreamParser());let i=A.get(t.id),a=/^[{[]/.test(n.trim());a&&ge.set(t.id,n);let o=()=>{t.content+=r,ge.delete(t.id),A.delete(t.id),t.rawContent=void 0,b(t)};if(i.__isPlainTextParser===!0){o();return}let s=e=>{let r=typeof e==`string`?e:e?.text??null;r!==null&&r.trim()!==``?(t.content=r,b(t)):!a&&!n.trim().startsWith(`<`)&&o()},c=i.processChunk(n);c instanceof Promise?c.then(s).catch(o):s(c)},xe=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,b(e);return}let r=ge.get(e.id)??he(n);e.rawContent=r;let i=A.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=nr(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,A.delete(e.id),ge.delete(e.id),b(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:ge.has(e.id)||(e.content=he(n));let t=A.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),A.delete(e.id)}ge.delete(e.id),e.streaming=!1,b(e)}},Se=(e,t,n,r)=>{let i=D.get(e);if(i)return i;let a={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:E.get(e)}};return D.set(e,a),b(a),a},Ce=[],we,Te=/* @__PURE__ */ new Map;s?.media.forEach(([e,t])=>Te.set(e,{...t,parts:[...t.parts]}));let Ee=s?.iteration??0,De=s?.executionKind??`agent`,j=s?.executionKindResolved??!1,Oe=s?.turnId??null,M=null,ke=e.config().iterationDisplay??`separate`;we=()=>{for(let t=0;t<Ce.length;t++){let r=Ce[t];if(!j&&De!==`flow`&&typeof r.stepType==`string`&&(De=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){te.set(e,t),Se(e,t,`reasoning`,r.executionId);continue}let n=r.id,i=ce(n,r.executionId);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,b(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&te.has(e)&&D.has(e)){let t=D.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=r.id,n=ce(t,r.executionId);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,b(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&te.has(e)&&D.has(e)){let t=D.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,b(t)}te.delete(e),D.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!re.get(t)&&(n||r.scope===`loop`)&&ce(t,r.executionId);let i=re.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,b(i)}}else if(r.type===`tool_start`){x&&=(x.streaming=!1,b(x),null),typeof r.iteration==`number`&&(Ee=r.iteration);let e=r.toolCallId,t=r.toolName;if(fe(t)){k.add(e);continue}let n=pe(e,r.executionId,r.iteration),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??me(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,b(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(k.has(e))continue;let t=pe(e,r.executionId),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,b(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(k.has(e)){k.delete(e);continue}let t=pe(e,r.executionId,r.iteration),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,b(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${g()}`,n=pe(t,r.executionId),i=r.toolName,a=r.origin===`webmcp`&&!Wn(i)?`webmcp:${i}`:i,o=Wn(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??me(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},b(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null;if(e){let t=ba(r.phase);t?E.set(e,t):E.delete(e)}let t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){te.set(e,t);continue}let n=x;n&&(De===`flow`?(xe(n),ve=n):(n.streaming=!1,b(n)),x=null),w=e??w,T=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?te.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(ne.get(e)??``)+n;if(ne.set(e,i),i.trim()===``)continue;let a=Se(e,t,void 0,r.executionId);be(a,i,n);continue}w=e??w;let n=typeof r.delta==`string`?r.delta:``;if(T+=n,De===`flow`&&T.trim()===``)continue;let i=se();i.agentMetadata={textBlockId:w??void 0,phase:E.get(w??``),executionId:r.executionId,iteration:Ee,...De===`flow`?{}:{turnId:Oe??void 0,agentName:M?.agentName}},w&&D.set(w,i),be(i,T,n),S=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;e&&E.delete(e);let t=e?D.get(e):x,n=ba(r.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&te.has(e)){let t=D.get(e);t&&xe(t),te.delete(e),ne.delete(e),D.delete(e);continue}if(e&&t!==x){t&&(t.streaming=!1,b(t));continue}let i=x;i&&(De===`flow`?(xe(i),ve=i):((i.content??``)===``&&typeof r.text==`string`&&(i.content=r.text),i.streaming=!1,b(i)),x=null),w=null,T=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),n({type:`status`,status:`idle`});continue}{let e=ve;ve=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(A.delete(e.id),ge.delete(e.id),e.streaming=!1,b(e)):_e(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=se();t&&(r.stopReason=t),e?xe(r,n):(r.streaming=!1,b(r))}}continue}}else if(r.type===`execution_start`)De=r.kind===`flow`?`flow`:`agent`,j=!0,e.config().backgroundConversations&&n({type:`status`,status:`connected`,executionId:r.executionId}),De===`agent`&&(M={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:Ee;if(e!==Ee){if(ke===`separate`&&e>1){let e=x;e&&(e.streaming=!1,b(e),x=null)}Ee=e}Oe=typeof r.id==`string`?r.id:null,S=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=ie.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),b(t))}}else if(r.type===`tool_input_complete`){if(k.has(r.toolCallId))continue;let e=pe(r.toolCallId,r.executionId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,b(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=x??S;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,b(t))}Oe===r.id&&(Oe=null)}else if(r.type===`media_start`){let e=String(r.id);Te.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=Te.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=Te.get(e);Te.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:ga(e)})}}}if(l.length>0){let e=g(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:Ee}};b(n);let i=x;i&&(i.streaming=!1,b(i)),x=null,C.current=null}}else if(r.type===`execution_complete`){let e=x;e&&(r.kind===`flow`&&e.streaming!==!1?xe(e):(e.streaming=!1,b(e)),x=null),w=null,T=``,ve=null,n({type:`status`,status:r.success===!1?`error`:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${g()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:g(),approval:{id:e,status:`pending`,agentId:M?.agentId??`virtual`,executionId:r.executionId??M?.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}:{}}};b(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:g(),approval:{id:e,status:r.decision??`approved`,agentId:M?.agentId??`virtual`,executionId:r.executionId??M?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};b(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),de.set(i,{markdown:``,title:a,file:s}),!ue.has(i)){ue.add(i);let n=Xn(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g(),rawContent:Zn(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};le.set(i,c),b(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=de.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=de.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=le.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=de.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}de.delete(e),b(t),le.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),n({type:`status`,status:`idle`})}}}Ce.length=0};try{for(;;){if(c!==e.streamGeneration())return;a?.throwIfAborted();let{done:t,value:r}=await l.read();if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),t)break;p+=f.decode(r,{stream:!0});let i=p.split(`
6
6
 
7
7
  `);p=i.pop()??``;for(let t of i){if(c!==e.streamGeneration())return;a?.throwIfAborted();let r=t.split(`
8
- `),i=`message`,o=``,s=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?o+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(s=e.slice(3).trim());let l=()=>{s!==null&&s!==``&&n({type:`cursor`,id:s,...e.config().backgroundConversations?{checkpoint:{textBlockId:w,openAssistant:x!==null,sealedFlowMessageId:ve?.id??null,rawText:T,executionKind:De,executionKindResolved:j,turnId:Oe,iteration:Ee,textPhases:[...E],nestedParents:[...te],nestedRaw:[...ne],media:[...Te].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...de].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...k]}}:{}})};if(!o){l();continue}let u;try{u=JSON.parse(o)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let d=typeof u==`object`&&u&&!Array.isArray(u)?u:null,f=i===`message`?typeof d?.type==`string`?d.type:`message`:i;if(e.onSSEEvent?.(f,u),e.parseSSEEvent){C.current=x;let t=await va(e,u,n,C,b,g,ee);if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),C.current&&C.current!==x&&(x=C.current),t){l();continue}}d&&(Ce.push({...d,type:f}),we()),l()}}we()}finally{e.streamReaders.delete(l),a?.removeEventListener(`abort`,d),l.releaseLock()}}var ba,xa,Sa=B((()=>{Kn(),q(),cr(),ma(),ba=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0,xa=e=>/^[{[<]/.test(e)}));Sa(),H();const{setLoader:Ca,load:wa,provide:Ta,getSync:Ea}=V({fallbackImport:()=>Promise.resolve().then(()=>(Sa(),ha))}),Da=wa,Oa=Ta,ka=Ea;Oa(ha);var Aa=`4.32.0`,ja,Ma=B((()=>{ja=Aa})),Na=/* @__PURE__ */ Vt({deleteAllConversations:()=>$,deleteConversation:()=>qa,finalizeDisplayProjections:()=>Ka,getConversation:()=>Ga,historyErrorFor:()=>Ba,listConversations:()=>Wa,readErrorCode:()=>Ra,recoverFromUnauthorized:()=>za,resetVisitor:()=>Ja});function Pa(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Fa(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Ia(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;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 La(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);return i}async function Ra(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function za(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,eo);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,to);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Ba(e,t,n){let r=await Ra(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,eo):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,to):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function Va(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`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(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Ha(e,t,n){Ua(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Fa(e,n.scope)===`verified-user`&&(a=await Ia(e,i,r),a&&(i=await La(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Pa(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":ja,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await za(e,await Ra(e,u),a,r);continue}if(!u.ok)throw await Ba(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return Va(e,d,a!==null,r),f}}function Ua(e){if(!e.isClientTokenMode())throw 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 Wa(e,t){let n=await Ha(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(Za),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Ga(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Za(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Ka(e,t,n){Ua(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Ya)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Ya} character limit`);r+=n}if(r>Xa)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${Xa} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ha(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=Xa,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function qa(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function $(e,t){let n=await Ha(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 Ja(e){Ua(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ha(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Ya,Xa,Za,Qa,$a,eo,to,no=B((()=>{Ma(),Ya=32768,Xa=49152,Za=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:``}},Qa=`The identity proof was not admitted; account history is unavailable`,$a=`The identity proof was rejected`,eo=`The request carried no visitor credential`,to=`The stored visitor belongs to a different signed-in user`}));no(),H();const{setLoader:ro,load:io,provide:ao}=V({fallbackImport:()=>Promise.resolve().then(()=>(no(),Na))}),oo=io;ao(Na);var so,co=B((()=>{Gi(),so=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(i,a,o)=>{let s=a.trim();if(!s||!r.current)return;let c=i.getAttribute(`data-tool-call-id`)??``,l=o.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{instanceId:e.instanceId,toolUseId:c,answer:s,answers:o.structured,values:o.values??(o.source===`multi`?s.split(`, `):[s]),isFreeText:l,source:o.source},bubbles:!0,composed:!0})),Vi(n,c);let u=r.current.getMessages().find(e=>e.toolCall?.id===c);u?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(u,o.structured??s):r.current.sendMessage(s)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Pi(e,i),currentIndex:Oi(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Oi(t);if(n>=Ai(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Wi(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let i=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:i},bubbles:!0,composed:!0})),Vi(n,i);let a=r.current?.getMessages().find(e=>e.toolCall?.id===i);a?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(a),r.current?.resolveAskUserQuestion(a,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=ji(u);if(n&&t){let t=Ei(u)[Oi(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Ui(u,Array.from(n)),a(u);return}if(n){Ui(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Hi(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Hi(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(ji(u)){Ui(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Ei(u)[Oi(u)];(typeof e!=`string`||e!==i)&&Ui(u,i)}let o=d===`next`?1:-1,s=Oi(u)+o;Wi(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Ui(u,n);let a=Pi(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Oi(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=ji(u),d=Oi(u),f=d>=Ai(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:s},bubbles:!0,composed:!0})),Vi(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Ui(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Pi(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Wi(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(ji(n)?(Ui(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function lo(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
8
+ `),i=`message`,o=``,s=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?o+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(s=e.slice(3).trim());let l=()=>{s!==null&&s!==``&&n({type:`cursor`,id:s,...e.config().backgroundConversations?{checkpoint:{textBlockId:w,openAssistant:x!==null,sealedFlowMessageId:ve?.id??null,rawText:T,executionKind:De,executionKindResolved:j,turnId:Oe,iteration:Ee,textPhases:[...E],nestedParents:[...te],nestedRaw:[...ne],media:[...Te].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...de].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...k]}}:{}})};if(!o){l();continue}let u;try{u=JSON.parse(o)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let d=typeof u==`object`&&u&&!Array.isArray(u)?u:null,f=i===`message`?typeof d?.type==`string`?d.type:`message`:i;if(e.onSSEEvent?.(f,u),e.parseSSEEvent){C.current=x;let t=await va(e,u,n,C,b,g,ee);if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),C.current&&C.current!==x&&(x=C.current),t){l();continue}}d&&(Ce.push({...d,type:f}),we()),l()}}we()}finally{e.streamReaders.delete(l),a?.removeEventListener(`abort`,d),l.releaseLock()}}var ba,xa,Sa=B((()=>{Kn(),q(),cr(),ma(),ba=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0,xa=e=>/^[{[<]/.test(e)}));Sa(),H();const{setLoader:Ca,load:wa,provide:Ta,getSync:Ea}=V({fallbackImport:()=>Promise.resolve().then(()=>(Sa(),ha))}),Da=wa,Oa=Ta,ka=Ea;Oa(ha);var Aa=`4.32.2`,ja,Ma=B((()=>{ja=Aa})),Na=/* @__PURE__ */ Vt({deleteAllConversations:()=>$,deleteConversation:()=>qa,finalizeDisplayProjections:()=>Ka,getConversation:()=>Ga,historyErrorFor:()=>Ba,listConversations:()=>Wa,readErrorCode:()=>Ra,recoverFromUnauthorized:()=>za,resetVisitor:()=>Ja});function Pa(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Fa(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Ia(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;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 La(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);return i}async function Ra(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function za(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,eo);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,to);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Ba(e,t,n){let r=await Ra(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,eo):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,to):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function Va(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`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(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Ha(e,t,n){Ua(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Fa(e,n.scope)===`verified-user`&&(a=await Ia(e,i,r),a&&(i=await La(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Pa(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":ja,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await za(e,await Ra(e,u),a,r);continue}if(!u.ok)throw await Ba(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return Va(e,d,a!==null,r),f}}function Ua(e){if(!e.isClientTokenMode())throw 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 Wa(e,t){let n=await Ha(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(Za),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Ga(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Za(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Ka(e,t,n){Ua(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Ya)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Ya} character limit`);r+=n}if(r>Xa)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${Xa} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ha(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=Xa,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function qa(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function $(e,t){let n=await Ha(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 Ja(e){Ua(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ha(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Ya,Xa,Za,Qa,$a,eo,to,no=B((()=>{Ma(),Ya=32768,Xa=49152,Za=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:``}},Qa=`The identity proof was not admitted; account history is unavailable`,$a=`The identity proof was rejected`,eo=`The request carried no visitor credential`,to=`The stored visitor belongs to a different signed-in user`}));no(),H();const{setLoader:ro,load:io,provide:ao}=V({fallbackImport:()=>Promise.resolve().then(()=>(no(),Na))}),oo=io;ao(Na);var so,co=B((()=>{Gi(),so=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(i,a,o)=>{let s=a.trim();if(!s||!r.current)return;let c=i.getAttribute(`data-tool-call-id`)??``,l=o.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{instanceId:e.instanceId,toolUseId:c,answer:s,answers:o.structured,values:o.values??(o.source===`multi`?s.split(`, `):[s]),isFreeText:l,source:o.source},bubbles:!0,composed:!0})),Vi(n,c);let u=r.current.getMessages().find(e=>e.toolCall?.id===c);u?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(u,o.structured??s):r.current.sendMessage(s)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Pi(e,i),currentIndex:Oi(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Oi(t);if(n>=Ai(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Wi(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let i=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:i},bubbles:!0,composed:!0})),Vi(n,i);let a=r.current?.getMessages().find(e=>e.toolCall?.id===i);a?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(a),r.current?.resolveAskUserQuestion(a,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=ji(u);if(n&&t){let t=Ei(u)[Oi(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Ui(u,Array.from(n)),a(u);return}if(n){Ui(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Hi(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Hi(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(ji(u)){Ui(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Ei(u)[Oi(u)];(typeof e!=`string`||e!==i)&&Ui(u,i)}let o=d===`next`?1:-1,s=Oi(u)+o;Wi(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Ui(u,n);let a=Pi(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Oi(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=ji(u),d=Oi(u),f=d>=Ai(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:s},bubbles:!0,composed:!0})),Vi(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Ui(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Pi(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Wi(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(ji(n)?(Ui(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function lo(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
9
9
  `:r===``||mo.test(r)}function uo(e,t,n=`@`,r=`anywhere`,i=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let o=e[a];if(o===n)return lo(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
10
10
  `||o===``||!i&&mo.test(o))return null;a--}return null}function fo(e,t,n){for(let r of n){let n=uo(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function po(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var mo,ho=B((()=>{mo=/\s/}));function go(e){return[{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},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var _o=B((()=>{})),vo=B((()=>{})),yo=B((()=>{}));function bo(e){e.delayMs!==void 0&&(Eo=ko(e.delayMs)),e.skipDelayMs!==void 0&&(Do=ko(e.skipDelayMs))}function xo(e){Mo.get(e)?.hide()}function So(e){Mo.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=Co,viewportPadding:s=wo}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>ko(e.delayMs??Eo),x=()=>ko(e.skipDelayMs??Do),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&jo(x())},ee=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Io(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Io(v,s,y),x=r.left+r.width/2,S=Math.max(To,i.width-To),C=Io(x-m,To,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},w=()=>{if(_||!a||u||!t.isConnected||No(t))return;let e=v(),n=Fo(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(ua);let o=i.getComputedStyle?.(t);if(o){for(let e of Lo){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),ee(),u.dataset.state=`open`;let h=()=>{if(!t.isConnected){C();return}d&&(d.textContent=v()),f&&(f.textContent=y());let e=Fo(t);u&&e&&u.parentNode!==e&&e.appendChild(u),ee()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.closest(`[data-persona-root]`);g?.addEventListener(`persona:internal:host-moved`,h);let b=t.getRootNode(),x=Po(b)?b:r.documentElement,S=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});S?.observe(x,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),g?.removeEventListener(`persona:internal:host-moved`,h),S?.disconnect()}},T=e=>{_||u||(S(),e||b()<=0||Ao()?w():m=l().setTimeout(()=>{m=void 0,w()},b()))},E=()=>{h||g?T(g):C()},te=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,E())},D=()=>{h=!1,E()},ne=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}E()},re=()=>{g=!1,E()},ie=()=>{h=!1,g=!1,C()},ae=e=>{e.key===`Escape`&&ie()};n.addEventListener(`mouseenter`,te),n.addEventListener(`mouseleave`,D),t.addEventListener(`focus`,ne),t.addEventListener(`blur`,re),t.addEventListener(`keydown`,ae),t.addEventListener(`click`,ie);let oe={get isOpen(){return u!==null},show:w,hide:C,reposition:ee,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,te),n.removeEventListener(`mouseleave`,D),t.removeEventListener(`focus`,ne),t.removeEventListener(`blur`,re),t.removeEventListener(`keydown`,ae),t.removeEventListener(`click`,ie),Mo.delete(t))}};return Mo.set(t,oe),oe}var Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro=B((()=>{da(),vo(),yo(),Co=8,wo=8,To=10,Eo=400,Do=300,Oo=0,ko=e=>Math.max(0,e),Ao=()=>Date.now()<Oo,jo=e=>{Oo=e>0?Date.now()+e:0},Mo=/* @__PURE__ */ new WeakMap,No=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Po=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Fo=e=>{let t=e.getRootNode?.();return Po(t)?t:e.closest(`dialog[open]`)??e.ownerDocument.body},Io=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Lo=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),zo,Bo,Vo,Ho,Uo=B((()=>{Wr(),zo=(e,t,n,r)=>{let[i,a]=t.split(`.`);return[e?.theme,e?.darkTheme].some(e=>e?.components?.[i]?.[a]?.[n]!==void 0)?`var(--persona-components-${t.replace(`.`,`-`)}-${n}, ${r})`:r},Bo=(e,t)=>{let n=e&&Hr(e,t);return typeof n==`string`&&n?n:void 0},Vo=(e,t,n,r)=>{let i=t.startsWith(`var(`);e.classList.toggle(`persona-theme-padding`,i),e.style.padding=i?``:t,i?e.style.setProperty(`--persona-theme-padding`,t):e.style.removeProperty(`--persona-theme-padding`),n&&(e.style.paddingLeft=e.style.paddingRight=n),r&&(e.style.paddingTop=e.style.paddingBottom=r)},Ho=(e,t,n)=>{let r=t.startsWith(`var(`)&&t.includes(`--persona-components-`);e.classList.toggle(`persona-control-size`,r),r?e.style.setProperty(`--persona-control-size`,t):e.style.removeProperty(`--persona-control-size`),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=n??``}})),Wo,Go,Ko,qo=B((()=>{Wo=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Go=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Wo(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Ko=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}})),Jo,Yo,Xo,Zo,Qo=B((()=>{Jo={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,groupBoundary:`adjacent`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Yo={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Xo={layout:`row`,variant:`row`,iconVisibility:`active`,autoExpand:!1,grouped:!0,groupedMode:`collapsible`,groupAppearance:`inset`,loadingAnimation:`shimmer`},Zo={appearance:`inset`,layout:`row`,variant:`row`,iconVisibility:`active`,autoExpand:!1,loadingAnimation:`shimmer`}})),$o,es=B((()=>{$o={resolvedDisplay:`row`,primaryAction:`allow-once`,keyboardShortcuts:`focused`}})),ts,ns,rs,is,as,os,ss,cs,ls,us,ds=B((()=>{ts=Symbol(`persona.panelAliasProvenance`),ns=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),rs=(e,t)=>ns(e,t)&&e[t]!==void 0,is=e=>({launcherWidth:rs(e?.launcher,`width`),legacyLauncherWidth:rs(e,`launcherWidth`),sidebarWidth:rs(e?.launcher,`sidebarWidth`),dockWidth:rs(e?.launcher?.dock,`width`)}),as=e=>{let t=e?.[ts];return t?{...t}:is(e)},os=(e,t)=>(Object.defineProperty(e,ts,{value:t,enumerable:!0,configurable:!0}),e),ss=(e,t)=>os(e,as(t)),cs=(e,t)=>{let n=t[ts];if(n)return{...n};let r=as(e);return ns(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),ns(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(ns(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),ns(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),ns(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:ns(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)},ls=e=>e?.layout?.embedded===!0&&e.launcher?.enabled===!1&&!e.launcher.sidebarMode&&(e.launcher.mountMode??`floating`)===`floating`,us=e=>e?.layout?.showHeader??!ls(e)}));function fs(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function ps(e){let t=fs(e)===`v5`?ws:Ss;return lr(xs,t)}function ms(e,t){if(e||t)return e?t?lr(e,t):e:t}function hs(e){let t=ps(e);return e?zr(wr(ss({...t,...e,colorScheme:Sr(e,[`colorScheme`]).includes(`colorScheme`)?e.colorScheme:e.brand?void 0:t.colorScheme,...t.approval||e.approval!==void 0?{approval:e.approval!==!1&&{...t.approval||{},...e.approval}}:{},theme:ms(t.theme,e.theme),darkTheme:ms(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay,...e.features?.toolCallDisplay?.layout===void 0&&e.features?.toolCallDisplay?.variant!==void 0?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay,...e.features?.reasoningDisplay?.layout===void 0&&e.features?.reasoningDisplay?.variant!==void 0?{layout:e.features.reasoningDisplay.variant}:{}},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,ws),e):zr(wr(ss(t),void 0,ws))}var gs,_s,vs,ys,bs,xs,Ss,Cs,ws,Ts,Es=B((()=>{Qo(),dr(),es(),kr(),ds(),Wr(),vo(),gs=`min(440px, calc(100vw - 24px))`,_s=`440px`,vs=`40px`,ys=`How can I help...`,bs={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:gs,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:vs,closeButtonPaddingX:`0px`,closeButtonPaddingY:`0px`,callToActionIconName:`arrow-up-right`,callToActionIconText:``,callToActionIconSize:`32px`,callToActionIconPadding:`5px`,callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:`transparent`,clearChat:{backgroundColor:`transparent`,borderColor:`transparent`,enabled:!0,placement:`inline`,iconName:`refresh-cw`,showTooltip:!0,tooltipText:`Clear chat`,paddingX:`0px`,paddingY:`0px`},headerIconHidden:!1,border:void 0,shadow:`0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`},xs={apiUrl:`https://api.runtype.com/api/chat/dispatch`,clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:`light`,tooltip:{delayMs:400,skipDelayMs:300},launcher:bs,copy:{inputPlaceholder:ys,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``,streamingIndicator:`arrow`,scrollBehavior:`instant`,scrollDurationMs:220,transition:`none`},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:Jo,reasoningDisplay:Yo,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},Ss={},Cs={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},ws={colorScheme:`light`,errorDisplay:`block`,messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:$o,loadingIndicator:{variant:`label`},launcher:Cs,features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:`dots`,transition:`fade`,scrollBehavior:`smooth`},toolCallDisplay:Xo,reasoningDisplay:Zo},composer:{layout:`single-row`,placement:`overlay`},sendButton:{iconName:`arrow-up`},statusIndicator:{mode:`transient`},layout:{contentMaxWidth:`768px`,topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:`full`}}}},Ts=ps()}));function Ds(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Os(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function ks(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function As(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function js(e){return{type:`text`,text:e}}function Ms(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Ns(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:`image`,image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Ps(e,t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(`, `)}`}}function Fs(e){return Hs.includes(e)||e.startsWith(`image/`)}function Is(e){return Fs(e.type)}async function Ls(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Is(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Rs(e,t=Ws,n=10485760){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 zs(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Bs(e,t){let n=zs(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 Vs,Hs,Us,Ws,Gs=B((()=>{Vs=`[Image]`,Hs=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Us=[`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`],Ws=[...Hs,...Us]}));function Ks(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 r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function qs(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function Js(e,t){e.style.maxHeight=`${t*Ks(e)}px`,e.style.overflowY=`auto`}function Ys(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 Xs(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Zs(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!Xs(t)}function Qs(e){return(e.submitKey??`enter`)===`enter`?Xs(e)?`enter`:`send`:`enter`}function $s(e,t){e.setAttribute(`enterkeyhint`,Qs(t))}function ec(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function tc(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 nc=B((()=>{})),rc,ic,ac=B((()=>{rc=`persona-composer-control`,ic=`persona-composer-control--glyph`})),oc,sc,cc,lc,uc,dc,fc,pc,mc,hc,gc,_c=B((()=>{Uo(),qo(),X(),Pn(),Es(),Gs(),Ro(),nc(),ac(),ac(),oc=(e,t)=>{let n=J(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,$s(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ys(n)}),ec(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 r=qs(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*Ks(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}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:o}},sc=`[data-persona-glyph-stack]`,cc=(e,t,n=`send`)=>{let r=Y(`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`),r.append(e,t),r},lc=/* @__PURE__ */ new WeakMap,uc=(e,t,n=!0)=>{lc.set(e,t);let r=t?.sendButton??{},i=r.useIcon??!1,a=e.getAttribute(`data-persona-send-mode`)===`stop`?`stop`:`send`,o=e=>Bo(t,`sendButton.${e}`),s=(e,n)=>zo(t,`composer.send`,e,n),c=o(`size`)||r.size;e.style.fontSize=i?`18px`:``,e.style.lineHeight=i?`1`:``,e.className=Gr(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,i?`persona-flex persona-items-center persona-justify-center ${rc}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,i&&!o(`backgroundColor`)&&`persona-bg-persona-primary`,!i&&!o(`textColor`)&&`persona-text-white`),Ho(e,i?c||(s(`size`,``)?s(`size`,`var(--persona-composer-control-size, 40px)`):``):``,i?c:void 0);let l=s(`foreground`,i?`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:`#ffffff`),u=s(`background`,i?`var(--persona-button-primary-bg, var(--persona-primary, #111827))`:`var(--persona-accent, #0f0f0f)`);e.style.color=o(`textColor`)||(a===`stop`&&s(`foreground`,``)?`var(--persona-button-stop-fg, ${l})`:s(`foreground`,``)||(i?l:``)),e.style.backgroundColor=(i?o(`backgroundColor`):void 0)||(s(`background`,``)?a===`stop`?`var(--persona-button-stop-bg, ${u})`:u:``);let d=o(`borderWidth`)||(s(`borderWidth`,``)?s(`borderWidth`,r.borderWidth||`0px`):r.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderColor=o(`borderColor`)||(s(`borderColor`,``)?s(`borderColor`,r.borderColor||`transparent`):r.borderColor||``),e.style.borderRadius=s(`borderRadius`,``)?s(`borderRadius`,`var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))`):``,Vo(e,s(`padding`,i?`0`:`8px 16px`),i?void 0:o(`paddingX`)||(s(`padding`,``)?void 0:r.paddingX),i?void 0:o(`paddingY`)||(s(`padding`,``)?void 0:r.paddingY));let f=parseFloat(r.iconSize??``)||Math.round((parseFloat(r.size??``)||40)*.5);if(n){if(e.replaceChildren(),i){let t=r.iconStrokeWidth??2,n=r.iconName?G(r.iconName,f,`currentColor`,t):null,i=G(r.stopIconName??`square`,f,`currentColor`,t);n&&i?e.appendChild(cc(n,i,a)):n?e.appendChild(n):e.textContent=r.iconText??`↑`}else e.textContent=a===`stop`?t?.copy?.stopButtonLabel??`Stop`:t?.copy?.sendButtonLabel??`Send`}for(let n of Array.from(e.querySelectorAll(`svg`))){n.style.width=n.style.height=o(`iconSize`)?``:s(`iconSize`,`var(--persona-components-composer-sendIconSize, ${f}px)`);let e=t?.sendButton?.iconStrokeWidth;n.style.strokeWidth=e===void 0?s(`iconStrokeWidth`,``):String(e)}},dc=e=>{let t=e?.sendButton,n=J(`div`,`persona-send-button-wrapper`),r=Y(`button`,{attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`}});return uc(r,e),r.setAttribute(`aria-label`,t?.tooltipText??`Send message`),n.appendChild(r),So({anchor:r,trigger:n,text:()=>r.getAttribute(`aria-label`)??``,enabled:t?.showTooltip??!1}),{button:r,wrapper:n,setMode:e=>{if(r.getAttribute(`data-persona-send-mode`)===e)return;r.setAttribute(`data-persona-send-mode`,e),r.setAttribute(`aria-label`,e===`stop`?t?.stopTooltipText??`Stop generating`:t?.tooltipText??`Send message`);let n=lc.get(r);uc(r,n,!1),r.querySelector(sc)?.setAttribute(`data-mode`,e),(n?.sendButton?.useIcon??!1)||(r.textContent=e===`stop`?n?.copy?.stopButtonLabel??`Stop`:n?.copy?.sendButtonLabel??`Send`)},glyphStack:r.querySelector(sc)}},fc=(e,t,n=`idle`,r=`none`)=>{let i=t?.voiceRecognition??{},a=e=>Bo(t,`voiceRecognition.${e}`),o=(e,n)=>zo(t,`voice.control`,e,n),s=a(`iconSize`)||i.iconSize;Ho(e,s||(o(`size`,``)?o(`size`,`var(--persona-composer-control-size, 40px)`):``),s),e.classList.add(rc),e.classList.toggle(ic,!s&&!o(`size`,``)),e.style.fontSize=`18px`,e.style.lineHeight=`1`;let c=a(`iconColor`)||Bo(t,`sendButton.textColor`)||o(`foreground`,`var(--persona-text, #111827)`),l=a(`backgroundColor`)||Bo(t,`sendButton.backgroundColor`)||o(`background`,i.backgroundColor||`transparent`),u=a(`borderColor`)||o(`borderColor`,i.borderColor||`transparent`),d=a(`borderWidth`)||o(`borderWidth`,i.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderRadius=o(`borderRadius`,``)?o(`borderRadius`,`var(--persona-button-radius)`):``,Vo(e,o(`padding`,``)?o(`padding`,`0px`):``,a(`paddingX`)||(o(`padding`,``)?void 0:i.paddingX),a(`paddingY`)||(o(`padding`,``)?void 0:i.paddingY));let f=a(`recordingBackgroundColor`)||`var(--persona-voice-recording-bg, #ef4444)`,p=a(`recordingIconColor`)||`var(--persona-voice-recording-indicator, #ffffff)`,m=a(`recordingBorderColor`)||`var(--persona-consumer-voice-recording-border, ${i.recordingBorderColor||u})`,h=c,g=l,_=u,v=i.iconName??`mic`;if(n===`recording`)h=p,g=f,_=m;else if(n===`processing`)h=a(`processingIconColor`)||`var(--persona-consumer-voice-processing-icon, ${c})`,g=a(`processingBackgroundColor`)||`var(--persona-consumer-voice-processing-background, ${l})`,_=a(`processingBorderColor`)||`var(--persona-components-voice-processing-border, ${u})`,v=i.processingIconName??`loader`;else if(n===`speaking`){let e=r===`barge-in`;h=a(`speakingIconColor`)||`var(--persona-consumer-voice-speaking-icon, ${e&&a(`recordingIconColor`)||c})`,g=a(`speakingBackgroundColor`)||`var(--persona-components-voice-speaking-background, ${e?f:l})`,_=a(`speakingBorderColor`)||`var(--persona-components-voice-speaking-border, ${e?m:u})`,v=i.speakingIconName??(r===`cancel`?`square`:e?`mic`:`volume-2`)}e.style.color=h,e.style.backgroundColor=g,e.style.borderColor=_,e.setAttribute(`data-state`,n);let y=parseFloat(i.iconSize??``)||24,b=G(v,y,`currentColor`,1.5);if(e.replaceChildren(),b){let t=s||(o(`iconSize`,``)?o(`iconSize`,`var(--persona-composer-control-icon-size, 24px)`):``);b.style.width=b.style.height=t,!s&&o(`iconSize`,``)&&(b.style.flexBasis=t),b.style.strokeWidth=o(`iconStrokeWidth`,`1.5`),e.appendChild(b)}else e.textContent=`🎤`},pc=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0||t.showButton===!1)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`||t.dictation?.provider?.type===`custom`;if(!(n||r||i))return null;let a=J(`div`,`persona-send-button-wrapper`),o=Y(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control`,attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`}});fc(o,e),a.appendChild(o);let s=t.tooltipText??`Start voice recognition`;return So({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??s,enabled:t.showTooltip??!1}),{button:o,wrapper:a}},mc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=J(`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 r=J(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Ws).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=J(`div`,`persona-send-button-wrapper`),o=Y(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${rc} ${ic}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=G(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return So({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},hc=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=J(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Go(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=J(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},gc=()=>Y(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function vc(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=J(`div`,`persona-send-button-wrapper`),o=Y(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${rc} ${ic}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=G(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),So({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var yc=B((()=>{X(),Pn(),Ro(),_c()})),bc,xc,Sc,Cc=B((()=>{H(),{setLoader:bc,load:xc}=V({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),Sc=xc})),wc,Tc,Ec,Dc=B((()=>{H(),{setLoader:wc,load:Tc}=V({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),Ec=Tc}));function Oc(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Y(`span`,{className:Gr(`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 r=G(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=J(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(Y(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var kc=B((()=>{X(),Pn()}));function Ac(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??jc,a=e.config.contextMentions;if(!a?.enabled)return null;let o=go(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
11
11
  `).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
@@ -14,12 +14,12 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
14
14
 
15
15
  `)}:{}}function Zd(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Qd(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function $d(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function ef(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return $d(e,n.id)?n.id:null}return null}function tf(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}function nf(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function rf(e,t){if(!nf(e))return null;let n=e.props&&typeof e.props==`object`&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function af(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e;try{let t=rf(Rt(n,Lt|It),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function of(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}X();function sf(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Ql(n,e.component);if(!a){if(eu.includes(e.component)){cu().catch(()=>{});let e=J(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o=t.context??{message:r,config:n,signal:t.signal??new AbortController().signal,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function cf(){let e=af();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function lf(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function uf(e){let t=lf(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function df(e){let t=lf(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}function ff(e){for(let t of[`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)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var pf=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):ff(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},mf=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},hf=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};function gf(e){if(!e)return``;let t=_f(e);return vf(t===null?e:t)}function _f(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 e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function vf(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,`
16
16
  `),t=t.replace(/\n{2,}/g,`
17
- `),t.trim()}var yf,bf=B((()=>{yf=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function xf(e){return e.replace(/\/+$/,``)}async function Sf(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 Cf,wf=B((()=>{bf(),Cf=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new yf(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${xf(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Sf(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}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}}})),Tf,Ef=B((()=>{Tf=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),Df=/* @__PURE__ */ Vt({FallbackSpeechEngine:()=>Tf,RuntypeSpeechEngine:()=>Cf}),Of=B((()=>{wf(),Ef()}));const kf=()=>Promise.resolve().then(()=>(Of(),Df));H();const{setLoader:Af,load:jf}=V({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),Mf=jf;Kn(),ra(),Kc(),Gs(),q(),dd();const Nf=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Pf(e,t){return Nf.some(n=>e[n]!==t[n])}var Ff=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function If(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`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?`${r}\n\n_Details: ${n.message}_`:r}const Lf=e=>Wn(e)||e===`suggest_replies`;var Rf=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${Wc()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:/* @__PURE__ */ new Set},e)for(let t of this.messages)t.role===`assistant`&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;this.#r!==null&&clearTimeout(this.#r),this.#r=null;let n=this.#e;if(this.#e=null,n){let t=n;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#o(){if(!this.#e||this.#r!==null)return;let e=this.#e;this.#r=setTimeout(()=>{this.#r=null,this.#e===e&&(!this.#n&&(this.streaming||this.#f||this.#_t()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#n?`error`:`success`))},0)}#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.#e=null,this.#n=!1,this.#r=null,this.streaming=!1,this.#s=/* @__PURE__ */ new Map,this.abortController=null,this.#l=Date.now(),this.clientSession=null,this.agentExecution=null,this.#u=null,this.#d=null,this.#f=!1,this.#m=null,this.#h=null,this.#g=null,this.#_=null,this.#v=null,this.#y=null,this.artifacts=/* @__PURE__ */ new Map,this.#b=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#x=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#S=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#C=null,this.#w=null,this.#T=0,this.#E=0,this.#D=!1,this.#O=`disconnected`,this.#k=null,this.#A=null,this.#j=null,this.#M=0,this.#N=0,this.#P=null,this.#F=Promise.resolve(),this.#I=!1,this.#L=null,this.#R=!1,this.#z=null,this.#B=/* @__PURE__ */ new Map,this.#V=null,this.#H=/* @__PURE__ */ new Map,this.#U=null,this.#W=null,this.#G=!1,this.#K=null,this.#q=null,this.#J=!1,this.#Y=null,this.#Q=null,this.#$=null,this.#ee=new hf,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new mf(()=>this.#ie()),this.#Ze=null,this.#Qe=0,this.handleEvent=(e,t=!1)=>{if(this.#m){this.#m.push({event:e,readOnlyReplay:t});return}let n=this.#re,r=!1;if(n&&(e.type===`error`||e.type===`status`&&e.status===`error`?n.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),r=!0)),e.type===`message`){this.#e&&!t&&e.message.role===`assistant`&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||e.message.variant===`approval`&&e.message.approval?.status===`pending`)&&this.#dt(`needs-attention`),r&&n.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#s.set(e.message.id,this.#c),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#d=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&ul().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(Wn(i.name)||i.name===`suggest_replies`&&na(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&a&&!t&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#et(e.message),e.message.agentMetadata?.executionId&&(!this.agentExecution||this.agentExecution.executionId!==e.message.agentMetadata.executionId?this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0}:e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration))}else if(e.type===`cursor`)this.#p=e.checkpoint,this.#ht(e.id);else if(e.type===`status`){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#dt(`running`)),e.status===`idle`&&!e.terminal&&this.#gt()){this.#vt();return}if(e.status===`error`?this.#dt(`failed`):e.terminal&&e.status===`idle`&&this.#dt(`completed`),this.#Ot(e.status),e.status===`connecting`)this.#kt(!0);else if(e.status===`idle`||e.status===`error`){this.#_t()||this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null,this.#He(),this.#Le());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#tt()}}else e.type===`error`?(this.#dt(`failed`),this.#Ot(`error`),this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#ct(e)},this.historyInternals=this.#ue(n),this.messages=[...e.initialMessages??[]].map(e=>({...Iu(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new Rd(e,this.historyInternals),this.#Oe(),this.#Xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#b=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#st(),this.callbacks.onStatusChanged(this.status),this.#Z(),this.#X()}#X(){this.config.voiceRecognition?.provider&&mu().catch(()=>{})}#Z(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&kf().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return yu(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#O}getVoiceNotice(){return this.#C?.takeNotice?.()??null}getVoiceDisclosure(){return this.#C?.getDisclosure?.()??null}getVoiceLevel(){return this.#C?.onLevel?this.#E:null}getVoiceInterruptionMode(){return this.#C?.getInterruptionMode?this.#C.getInterruptionMode():`none`}stopVoicePlayback(){this.#C?.stopPlayback&&(this.#ee.cancel(),this.#ne?.cancel(),this.#C.stopPlayback())}isBargeInActive(){return this.#C?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#C?.deactivateBargeIn&&await this.#C.deactivateBargeIn()}#Q;#$;#ee;#te;#ne;#re;#ie(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=pf.isSupported()?new pf({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return kf().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#te,r=++this.#T;this.#w=mu().then(async e=>{await n,r===this.#T&&this.#ae(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#T&&(this.#w=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#ae(e,t){this.#C=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#C,generation:()=>n.#T,get keyed(){return n.#ne},set keyed(e){n.#ne=e},get pendingUser(){return n.#Q},set pendingUser(e){n.#Q=e},get pendingAssistant(){return n.#$},set pendingAssistant(e){n.#$=e},turns:()=>n.#ee,busy:()=>n.#oe(),setStreaming:e=>n.#kt(e),setDelegation:e=>{n.#re=e},setLevel:e=>{n.#E=e},setStatus:e=>{n.#O=e,n.#D=e===`listening`},settlePending:e=>n.#ce(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#T;if(!this.#C&&this.#w&&await this.#w,e===this.#T){if(!this.#C)console.error(`Voice not configured`);else if(this.#D)await this.#C.stopListening();else{this.stopSpeaking();try{await this.#C.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}}prewarmVoice(){if(!_u(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#T,t=()=>{let t=this.#C;t?.prewarm&&e===this.#T&&(this.#D||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#C&&this.#w?this.#w.then(t,()=>{}):t()}#oe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||this.status===`resuming`}cleanupVoice(){let e=this.#C!==null;if(this.#T++,this.#w=null,this.#C){let e=this.#C;this.#C=null,this.#te=this.#se(e)}this.#D=!1,this.#O=`disconnected`,this.#ce(!0),this.#ne?.settle(),this.#ne=null,this.#ee=new hf,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#se(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#ce(e){let t=e?this.#Q:null,n=this.#$;(t||n)&&(n&&this.#ee.cancel(),e&&(this.#Q=null),this.#$=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#kt(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#W=this.historyInternals.getStoredConversationRevision?.()??null,this.#G=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#le(e,t)}#le(e,t=!this.messages.length){if(this.#I||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#It()};this.#Pt(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){e.historyProvider!==this.historyInternals.historyProvider&&(this.#M+=1,this.#N+=1,this.config.backgroundConversations&&this.cancel(),this.#ut()),this.historyInternals=this.#ue(e),this.client.setHistoryInternals(this.historyInternals),this.#Oe()}destroy(){this.#ut(),this.#M+=1,this.#N+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#K?.(),this.#K=null,this.#q=null}#ue(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#De(e),t?.(e)}}}get#de(){return this.historyInternals.historyProvider??null}#fe(){let e=this.#de;if(!e)throw new Ff(`history_unavailable`,`No conversation history provider is installed`);return e}#pe(e){let t=this.#fe(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new zd(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#k,conversationRevision:this.#A,nextMessageCursor:this.#j,recovery:this.#L,sendBlocked:this.#R}}getActiveConversationId(){return this.#k}#me(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#he(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#z;e&&await e.catch(()=>{});let t=this.#V;t&&await t.catch(()=>{})}#ge(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Ff(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#fe().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#pe(e?.scope)})}async openConversation(e,t){let n=this.#fe();t?.busy===`background`&&this.assertBackgroundSwitchable(),t?.busy===`stop`&&this.cancel(),t?.busy!==`background`&&this.#ge();let r=this.#pe(t?.scope),i=++this.#M,a=this.#N;if(t?.busy===`background`&&await this.#lt(),await this.awaitHistorySettled(),i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let s=await n.prepareOpen(e,{context:r}),c=this.#F.then(async()=>{if(i!==this.#M)throw s.discard(),new Ff(`superseded`,`A later selection won`);t?.busy===`stop`&&this.cancel();try{t?.busy===`background`?this.assertBackgroundSwitchable():this.#ge()}catch(e){throw s.discard(),e}let r=this.#k,c=this.#e;t?.onBeforeCommit?.(),t?.busy===`background`&&(this.#m=[]),this.#I=!0,this.#P=a;try{if(await this.#Ce(s),a!==this.#N||n!==this.#de)throw new Ff(`superseded`,`The history identity changed`);if(t?.busy===`background`&&r&&this.#u){let e={conversationId:r,handle:this.#u,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#b,streamCheckpoint:this.#p};this.#h?.save(e)}this.#k=s.conversationId||e,this.#A=s.conversationRevision||o.conversationRevision||null,this.#j=o.nextCursor,this.#L=null,this.#R=!1,this.#Te();for(let e of o.messages)this.#H.set(e.id,e.content);this.#we();let i=this.#h?.take(this.#k);return this.hydrateMessages(i?.messages??o.messages),i&&(this.hydrateArtifacts(i.artifacts,i.selectedArtifactId,!0),this.#mt(i)),t?.onCommitted?.(),this.#me(),{summary:o.summary,nextMessageCursor:o.nextCursor}}finally{this.#I=!1,this.#P=null;let e=this.#m;if(this.#m=null,e&&this.#e===c&&this.#k===r)for(let{event:t,readOnlyReplay:n}of e)this.handleEvent(t,n)}}),l=c.then(()=>{},()=>{});this.#F=l,this.#z=l;try{return await c}finally{this.#z===l&&(this.#z=null)}}loadOlderMessages(e,t,n){let r=this.#fe(),i=this.#pe(n?.scope),a=t??this.#j;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#B.get(o);if(s)return s;let c=this.#_e(r,e,a,i).finally(()=>{this.#B.delete(o)});return this.#B.set(o,c),c}async#_e(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#k&&this.#k!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ve(a.messages),s=ud(this.messages,o);this.messages=this.#Rt(s.map(e=>this.#Ft(e))),this.#j=a.nextCursor;for(let e of a.messages)this.#H.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#me(),{messages:o,nextMessageCursor:a.nextCursor}}#ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&Fu(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return Iu(e)})}async startNewConversation(e){let t=this.#fe(),n=this.#pe(e?.scope),r=++this.#M,i=this.#N;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:n}),o=this.#F.then(async()=>{if(r!==this.#M)throw a.discard(),new Ff(`superseded`,`A later action won`);e?.onBeforeCommit?.(),this.#I=!0,this.#P=i;try{await this.#Ce(a)}finally{this.#I=!1,this.#P=null}if(i!==this.#N||t!==this.#de)throw new Ff(`superseded`,`The history identity changed`);this.#Ee(!1,!0),this.#k=a.conversationId||null,this.#A=a.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.clientSession&&this.#le(this.clientSession),e?.onCommitted?.(),this.#me()}),s=o.then(()=>{},()=>{});this.#F=s,this.#z=s;try{await o}finally{this.#z===s&&(this.#z=null)}}async#ye(e,t=!1){this.#Ee(t),await this.#Ce(e),this.#k=e.conversationId||null,this.#A=e.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.#me()}async deleteConversation(e,t){let n=this.#fe(),r=this.#pe(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),this.#h?.clear(e),e===this.#k&&await this.#be(r)}async updateConversation(e,t,n){let r=this.#fe();if(!r.update)throw new Ff(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#pe(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#de?.update==`function`}async clearConversationHistory(e){let t=this.#fe(),n=this.#pe(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return this.#ut(),await this.#be(n),r}async resetHistoryDevice(){let e=this.#fe();if(!e.resetDevice)throw new Ff(`history_unavailable`,`This history provider cannot reset the device`);this.#ut(),this.#M+=1,this.#N+=1,this.#V=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#R=!1,this.#me()}}async#be(e){this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#R=!0,this.#L=null,this.#me(),await this.#xe(e)}async#xe(e){let t=this.#de;if(!t)this.#R=!1,this.#me();else try{let n=await t.prepareStartNew({context:e});await this.#ye(n)}catch{this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#Se(){if(this.#L===`new_conversation_required`&&this.#de&&(this.#L=null,await this.#xe(this.#pe()),this.#L===`new_conversation_required`))throw new Ff(`new_conversation_required`,`A new conversation is required before sending`)}async#Ce(e){if(await e.commit(),this.#P!==null&&this.#P!==this.#N)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(this.#P===null||this.#P===this.#N)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#k=e.conversationId,this.#A=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#I||this.#le(e))}#we(){this.#k?this.config.setStoredConversationId?.(this.#k):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#A),this.historyInternals.setStoredMessageCursor?.(this.#j)}#Te(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H.clear(),this.#Pe(null)}#Ee(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.messages=[],this.#Te(),this.#B.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a(`cancel`)}#De(e){this.#ut(),this.#M+=1,this.#N+=1,this.#V=null,this.#R=!0,this.#Ee(),this.#k=e.conversationId,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.#he(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#z=Promise.resolve().then(()=>{this.#R=!1,this.#z=null,this.#me()})}#Oe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#K?.(),this.#K=null,this.#q=e,e&&(this.#K=e.subscribe(e=>this.#ke(e))))}#ke(e){if(e.source!==`external`||e.previousToken===null)return;this.#ut(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#M+=1,this.#N+=1,this.#V=null,this.#J=!0,this.#Y=null;let t=this.messages.length>0;t||this.#k!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#B.clear(),this.#Pe(null)),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#he(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#Ae(){return this.#J?(this.#Y||=this.#je().finally(()=>{this.#Y=null}),this.#Y):Promise.resolve()}async#je(){if(!this.isClientTokenMode())this.#J=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#J=!1}catch{}}reconcileBootConversation(e){let t=this.#de,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#k;if(!t||!n)return Promise.resolve();let r=this.#pe(e?.scope);this.#R=!0,this.#me();let i=this.#Me(t,n,r).finally(()=>{this.#R=this.#L!==null,this.#z===i&&(this.#z=null),this.#me()});return this.#z=i,i}async#Me(e,t,n){this.#k=t;let r=this.clientSession?.conversationRevision??this.#A??null,i=this.#G?this.#W:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#G=!1,this.#j=this.historyInternals.getStoredMessageCursor?.()??this.#j,await this.replayPendingProjections(),r&&i&&r===i){this.#A=r;return}let a=await e.getPage(t,{context:n}),o=this.#ve(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#Ft(e));else{let e=this.#u?this.#d:null;u=ud(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#Ft(e))}this.#j=a.nextCursor,this.#A=a.conversationRevision||r||null,this.#H.clear();for(let e of a.messages)this.#H.set(e.id,e.content);this.#we(),this.#t=void 0,this.messages=this.#Rt(u),this.callbacks.onMessagesChanged([...this.messages])}#Ne(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Pe(e){this.#U=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Fe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Ie(e){if(this.#Ne())for(let t of e){let e=ld(t);e!==void 0&&this.#H.set(t.id,e)}}#Le(){if(!this.#Ne())return;let e=this.#k;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=ld(e);n!==void 0&&this.#H.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#Pe({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Re(e,t))}#Re(e,t){let n=(this.#V??Promise.resolve()).catch(()=>{}).then(()=>this.#ze(e,t,!1)).finally(()=>{this.#V===n&&(this.#V=null)});this.#V=n}async#ze(e,t,n){if(this.#k!==e)return;let r=t.filter(e=>this.#H.get(e.id)!==e.displayContent);if(r.length===0)this.#Ve(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#H.set(e.id,e.displayContent);this.#k===e&&n&&(this.#A=n),this.#Ve(e,t)}catch(i){if(!n&&this.#Be(i)){await this.#ze(e,r,!0);return}if(i instanceof Fd&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ve(e,t);return}this.#he(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Be(e){return e instanceof Fd?e.code===`request_failed`:e instanceof Error}#Ve(e,t){let n=this.#Fe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#Pe(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#Ne())return;let e=this.#Fe();if(!e)return;if(this.#k&&e.conversationId!==this.#k){this.#Pe(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#Pe(null):(this.#Re(e.conversationId,t),await this.#V?.catch(()=>{}))}#He(){this.#k&&(this.#A=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ue(){await this.awaitHistorySettled(),await this.#Ae(),this.#L===`new_conversation_required`&&await this.#Se()}static#We(e){return e instanceof Fd&&e.code===`conversation_deleted`}async#Ge(t,n,r,i,a){let o=this.#e,s=e=>{this.#e===o&&this.handleEvent(e)};this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s);return}catch(t){if(n.signal.aborted||this.#e!==o||!e.#We(t))throw t;let c=await this.#Ke(i);if(!c)throw t;this.#Ie([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s)}}async#Ke(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(!0),this.#k=null,this.#A=null,this.#j=null,this.#I=!0;try{let e=this.#de;if(e){let t=await e.prepareStartNew({context:this.#pe()});await this.#ye(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#I=!1}return this.#Pt(n),this.#kt(!0),this.#he(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=gu(this.config,n),i=Pf(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&bu(n)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#at();return}this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.#M+=1,this.#N+=1,this.client=new Rd(this.config,this.historyInternals),a&&this.#at(),this.#Xe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#qe(e);return this.upsertMessage(t),t}#qe(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e;return{id:a??(t===`user`?Uc():t===`assistant`?Wc():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#It(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d},...e.dispatchError!==void 0&&{dispatchError:e.dispatchError}}}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=e.map(e=>this.#qe(e));return this.messages=this.#Rt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}updateComponentProps(e,t){let n=this.messages.find(t=>t.id===e),r=n&&df(n);return!n||n.role!==`assistant`||n.variant||!r?!1:(this.upsertMessage({...n,rawContent:JSON.stringify({text:n.content,component:r.component,props:t})}),!0)}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!t||t.role!==`assistant`||t.variant||!df(t)?!1:(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),!0)}async#Je(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
17
+ `),t.trim()}var yf,bf=B((()=>{yf=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function xf(e){return e.replace(/\/+$/,``)}async function Sf(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 Cf,wf=B((()=>{bf(),Cf=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new yf(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${xf(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Sf(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}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}}})),Tf,Ef=B((()=>{Tf=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),Df=/* @__PURE__ */ Vt({FallbackSpeechEngine:()=>Tf,RuntypeSpeechEngine:()=>Cf}),Of=B((()=>{wf(),Ef()}));const kf=()=>Promise.resolve().then(()=>(Of(),Df));H();const{setLoader:Af,load:jf}=V({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),Mf=jf;Kn(),ra(),Kc(),Gs(),q(),dd();const Nf=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Pf(e,t){return Nf.some(n=>e[n]!==t[n])}var Ff=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function If(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=n.message.trim(),i=/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.?)$/i.test(r),a=/^(Chat backend|Agent execution) request failed: \d{3}\b/.test(r),o=i?`Sorry: I couldn't reach the assistant. Please check your connection and try again.`:a?`Sorry: the chat service couldn't complete the request. Please try again.`:`Sorry: the chat encountered an unexpected error. Please reload the page and try again.`;return r?`${o}\n\n_Details: ${r}_`:o}const Lf=e=>Wn(e)||e===`suggest_replies`;var Rf=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${Wc()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:/* @__PURE__ */ new Set},e)for(let t of this.messages)t.role===`assistant`&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;this.#r!==null&&clearTimeout(this.#r),this.#r=null;let n=this.#e;if(this.#e=null,n){let t=n;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#o(){if(!this.#e||this.#r!==null)return;let e=this.#e;this.#r=setTimeout(()=>{this.#r=null,this.#e===e&&(!this.#n&&(this.streaming||this.#f||this.#_t()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#n?`error`:`success`))},0)}#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.#e=null,this.#n=!1,this.#r=null,this.streaming=!1,this.#s=/* @__PURE__ */ new Map,this.abortController=null,this.#l=Date.now(),this.clientSession=null,this.agentExecution=null,this.#u=null,this.#d=null,this.#f=!1,this.#m=null,this.#h=null,this.#g=null,this.#_=null,this.#v=null,this.#y=null,this.artifacts=/* @__PURE__ */ new Map,this.#b=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#x=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#S=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#C=null,this.#w=null,this.#T=0,this.#E=0,this.#D=!1,this.#O=`disconnected`,this.#k=null,this.#A=null,this.#j=null,this.#M=0,this.#N=0,this.#P=null,this.#F=Promise.resolve(),this.#I=!1,this.#L=null,this.#R=!1,this.#z=null,this.#B=/* @__PURE__ */ new Map,this.#V=null,this.#H=/* @__PURE__ */ new Map,this.#U=null,this.#W=null,this.#G=!1,this.#K=null,this.#q=null,this.#J=!1,this.#Y=null,this.#Q=null,this.#$=null,this.#ee=new hf,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new mf(()=>this.#ie()),this.#Ze=null,this.#Qe=0,this.handleEvent=(e,t=!1)=>{if(this.#m){this.#m.push({event:e,readOnlyReplay:t});return}let n=this.#re,r=!1;if(n&&(e.type===`error`||e.type===`status`&&e.status===`error`?n.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),r=!0)),e.type===`message`){this.#e&&!t&&e.message.role===`assistant`&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||e.message.variant===`approval`&&e.message.approval?.status===`pending`)&&this.#dt(`needs-attention`),r&&n.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#s.set(e.message.id,this.#c),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#d=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&ul().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(Wn(i.name)||i.name===`suggest_replies`&&na(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&a&&!t&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#et(e.message),e.message.agentMetadata?.executionId&&(!this.agentExecution||this.agentExecution.executionId!==e.message.agentMetadata.executionId?this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0}:e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration))}else if(e.type===`cursor`)this.#p=e.checkpoint,this.#ht(e.id);else if(e.type===`status`){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#dt(`running`)),e.status===`idle`&&!e.terminal&&this.#gt()){this.#vt();return}if(e.status===`error`?this.#dt(`failed`):e.terminal&&e.status===`idle`&&this.#dt(`completed`),this.#Ot(e.status),e.status===`connecting`)this.#kt(!0);else if(e.status===`idle`||e.status===`error`){this.#_t()||this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null,this.#He(),this.#Le());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#tt()}}else e.type===`error`?(this.#dt(`failed`),this.#Ot(`error`),this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#ct(e)},this.historyInternals=this.#ue(n),this.messages=[...e.initialMessages??[]].map(e=>({...Iu(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new Rd(e,this.historyInternals),this.#Oe(),this.#Xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#b=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#st(),this.callbacks.onStatusChanged(this.status),this.#Z(),this.#X()}#X(){this.config.voiceRecognition?.provider&&mu().catch(()=>{})}#Z(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&kf().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return yu(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#O}getVoiceNotice(){return this.#C?.takeNotice?.()??null}getVoiceDisclosure(){return this.#C?.getDisclosure?.()??null}getVoiceLevel(){return this.#C?.onLevel?this.#E:null}getVoiceInterruptionMode(){return this.#C?.getInterruptionMode?this.#C.getInterruptionMode():`none`}stopVoicePlayback(){this.#C?.stopPlayback&&(this.#ee.cancel(),this.#ne?.cancel(),this.#C.stopPlayback())}isBargeInActive(){return this.#C?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#C?.deactivateBargeIn&&await this.#C.deactivateBargeIn()}#Q;#$;#ee;#te;#ne;#re;#ie(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=pf.isSupported()?new pf({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return kf().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#te,r=++this.#T;this.#w=mu().then(async e=>{await n,r===this.#T&&this.#ae(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#T&&(this.#w=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#ae(e,t){this.#C=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#C,generation:()=>n.#T,get keyed(){return n.#ne},set keyed(e){n.#ne=e},get pendingUser(){return n.#Q},set pendingUser(e){n.#Q=e},get pendingAssistant(){return n.#$},set pendingAssistant(e){n.#$=e},turns:()=>n.#ee,busy:()=>n.#oe(),setStreaming:e=>n.#kt(e),setDelegation:e=>{n.#re=e},setLevel:e=>{n.#E=e},setStatus:e=>{n.#O=e,n.#D=e===`listening`},settlePending:e=>n.#ce(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#T;if(!this.#C&&this.#w&&await this.#w,e===this.#T){if(!this.#C)console.error(`Voice not configured`);else if(this.#D)await this.#C.stopListening();else{this.stopSpeaking();try{await this.#C.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}}prewarmVoice(){if(!_u(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#T,t=()=>{let t=this.#C;t?.prewarm&&e===this.#T&&(this.#D||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#C&&this.#w?this.#w.then(t,()=>{}):t()}#oe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||this.status===`resuming`}cleanupVoice(){let e=this.#C!==null;if(this.#T++,this.#w=null,this.#C){let e=this.#C;this.#C=null,this.#te=this.#se(e)}this.#D=!1,this.#O=`disconnected`,this.#ce(!0),this.#ne?.settle(),this.#ne=null,this.#ee=new hf,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#se(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#ce(e){let t=e?this.#Q:null,n=this.#$;(t||n)&&(n&&this.#ee.cancel(),e&&(this.#Q=null),this.#$=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#kt(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#W=this.historyInternals.getStoredConversationRevision?.()??null,this.#G=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#le(e,t)}#le(e,t=!this.messages.length){if(this.#I||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#It()};this.#Pt(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){e.historyProvider!==this.historyInternals.historyProvider&&(this.#M+=1,this.#N+=1,this.config.backgroundConversations&&this.cancel(),this.#ut()),this.historyInternals=this.#ue(e),this.client.setHistoryInternals(this.historyInternals),this.#Oe()}destroy(){this.#ut(),this.#M+=1,this.#N+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#K?.(),this.#K=null,this.#q=null}#ue(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#De(e),t?.(e)}}}get#de(){return this.historyInternals.historyProvider??null}#fe(){let e=this.#de;if(!e)throw new Ff(`history_unavailable`,`No conversation history provider is installed`);return e}#pe(e){let t=this.#fe(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new zd(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#k,conversationRevision:this.#A,nextMessageCursor:this.#j,recovery:this.#L,sendBlocked:this.#R}}getActiveConversationId(){return this.#k}#me(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#he(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#z;e&&await e.catch(()=>{});let t=this.#V;t&&await t.catch(()=>{})}#ge(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Ff(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#fe().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#pe(e?.scope)})}async openConversation(e,t){let n=this.#fe();t?.busy===`background`&&this.assertBackgroundSwitchable(),t?.busy===`stop`&&this.cancel(),t?.busy!==`background`&&this.#ge();let r=this.#pe(t?.scope),i=++this.#M,a=this.#N;if(t?.busy===`background`&&await this.#lt(),await this.awaitHistorySettled(),i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let s=await n.prepareOpen(e,{context:r}),c=this.#F.then(async()=>{if(i!==this.#M)throw s.discard(),new Ff(`superseded`,`A later selection won`);t?.busy===`stop`&&this.cancel();try{t?.busy===`background`?this.assertBackgroundSwitchable():this.#ge()}catch(e){throw s.discard(),e}let r=this.#k,c=this.#e;t?.onBeforeCommit?.(),t?.busy===`background`&&(this.#m=[]),this.#I=!0,this.#P=a;try{if(await this.#Ce(s),a!==this.#N||n!==this.#de)throw new Ff(`superseded`,`The history identity changed`);if(t?.busy===`background`&&r&&this.#u){let e={conversationId:r,handle:this.#u,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#b,streamCheckpoint:this.#p};this.#h?.save(e)}this.#k=s.conversationId||e,this.#A=s.conversationRevision||o.conversationRevision||null,this.#j=o.nextCursor,this.#L=null,this.#R=!1,this.#Te();for(let e of o.messages)this.#H.set(e.id,e.content);this.#we();let i=this.#h?.take(this.#k);return this.hydrateMessages(i?.messages??o.messages),i&&(this.hydrateArtifacts(i.artifacts,i.selectedArtifactId,!0),this.#mt(i)),t?.onCommitted?.(),this.#me(),{summary:o.summary,nextMessageCursor:o.nextCursor}}finally{this.#I=!1,this.#P=null;let e=this.#m;if(this.#m=null,e&&this.#e===c&&this.#k===r)for(let{event:t,readOnlyReplay:n}of e)this.handleEvent(t,n)}}),l=c.then(()=>{},()=>{});this.#F=l,this.#z=l;try{return await c}finally{this.#z===l&&(this.#z=null)}}loadOlderMessages(e,t,n){let r=this.#fe(),i=this.#pe(n?.scope),a=t??this.#j;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#B.get(o);if(s)return s;let c=this.#_e(r,e,a,i).finally(()=>{this.#B.delete(o)});return this.#B.set(o,c),c}async#_e(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#k&&this.#k!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ve(a.messages),s=ud(this.messages,o);this.messages=this.#Rt(s.map(e=>this.#Ft(e))),this.#j=a.nextCursor;for(let e of a.messages)this.#H.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#me(),{messages:o,nextMessageCursor:a.nextCursor}}#ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&Fu(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return Iu(e)})}async startNewConversation(e){let t=this.#fe(),n=this.#pe(e?.scope),r=++this.#M,i=this.#N;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:n}),o=this.#F.then(async()=>{if(r!==this.#M)throw a.discard(),new Ff(`superseded`,`A later action won`);e?.onBeforeCommit?.(),this.#I=!0,this.#P=i;try{await this.#Ce(a)}finally{this.#I=!1,this.#P=null}if(i!==this.#N||t!==this.#de)throw new Ff(`superseded`,`The history identity changed`);this.#Ee(!1,!0),this.#k=a.conversationId||null,this.#A=a.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.clientSession&&this.#le(this.clientSession),e?.onCommitted?.(),this.#me()}),s=o.then(()=>{},()=>{});this.#F=s,this.#z=s;try{await o}finally{this.#z===s&&(this.#z=null)}}async#ye(e,t=!1){this.#Ee(t),await this.#Ce(e),this.#k=e.conversationId||null,this.#A=e.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.#me()}async deleteConversation(e,t){let n=this.#fe(),r=this.#pe(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),this.#h?.clear(e),e===this.#k&&await this.#be(r)}async updateConversation(e,t,n){let r=this.#fe();if(!r.update)throw new Ff(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#pe(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#de?.update==`function`}async clearConversationHistory(e){let t=this.#fe(),n=this.#pe(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return this.#ut(),await this.#be(n),r}async resetHistoryDevice(){let e=this.#fe();if(!e.resetDevice)throw new Ff(`history_unavailable`,`This history provider cannot reset the device`);this.#ut(),this.#M+=1,this.#N+=1,this.#V=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#R=!1,this.#me()}}async#be(e){this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#R=!0,this.#L=null,this.#me(),await this.#xe(e)}async#xe(e){let t=this.#de;if(!t)this.#R=!1,this.#me();else try{let n=await t.prepareStartNew({context:e});await this.#ye(n)}catch{this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#Se(){if(this.#L===`new_conversation_required`&&this.#de&&(this.#L=null,await this.#xe(this.#pe()),this.#L===`new_conversation_required`))throw new Ff(`new_conversation_required`,`A new conversation is required before sending`)}async#Ce(e){if(await e.commit(),this.#P!==null&&this.#P!==this.#N)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(this.#P===null||this.#P===this.#N)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#k=e.conversationId,this.#A=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#I||this.#le(e))}#we(){this.#k?this.config.setStoredConversationId?.(this.#k):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#A),this.historyInternals.setStoredMessageCursor?.(this.#j)}#Te(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H.clear(),this.#Pe(null)}#Ee(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.messages=[],this.#Te(),this.#B.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a(`cancel`)}#De(e){this.#ut(),this.#M+=1,this.#N+=1,this.#V=null,this.#R=!0,this.#Ee(),this.#k=e.conversationId,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.#he(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#z=Promise.resolve().then(()=>{this.#R=!1,this.#z=null,this.#me()})}#Oe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#K?.(),this.#K=null,this.#q=e,e&&(this.#K=e.subscribe(e=>this.#ke(e))))}#ke(e){if(e.source!==`external`||e.previousToken===null)return;this.#ut(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#M+=1,this.#N+=1,this.#V=null,this.#J=!0,this.#Y=null;let t=this.messages.length>0;t||this.#k!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#B.clear(),this.#Pe(null)),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#he(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#Ae(){return this.#J?(this.#Y||=this.#je().finally(()=>{this.#Y=null}),this.#Y):Promise.resolve()}async#je(){if(!this.isClientTokenMode())this.#J=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#J=!1}catch{}}reconcileBootConversation(e){let t=this.#de,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#k;if(!t||!n)return Promise.resolve();let r=this.#pe(e?.scope);this.#R=!0,this.#me();let i=this.#Me(t,n,r).finally(()=>{this.#R=this.#L!==null,this.#z===i&&(this.#z=null),this.#me()});return this.#z=i,i}async#Me(e,t,n){this.#k=t;let r=this.clientSession?.conversationRevision??this.#A??null,i=this.#G?this.#W:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#G=!1,this.#j=this.historyInternals.getStoredMessageCursor?.()??this.#j,await this.replayPendingProjections(),r&&i&&r===i){this.#A=r;return}let a=await e.getPage(t,{context:n}),o=this.#ve(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#Ft(e));else{let e=this.#u?this.#d:null;u=ud(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#Ft(e))}this.#j=a.nextCursor,this.#A=a.conversationRevision||r||null,this.#H.clear();for(let e of a.messages)this.#H.set(e.id,e.content);this.#we(),this.#t=void 0,this.messages=this.#Rt(u),this.callbacks.onMessagesChanged([...this.messages])}#Ne(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Pe(e){this.#U=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Fe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Ie(e){if(this.#Ne())for(let t of e){let e=ld(t);e!==void 0&&this.#H.set(t.id,e)}}#Le(){if(!this.#Ne())return;let e=this.#k;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=ld(e);n!==void 0&&this.#H.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#Pe({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Re(e,t))}#Re(e,t){let n=(this.#V??Promise.resolve()).catch(()=>{}).then(()=>this.#ze(e,t,!1)).finally(()=>{this.#V===n&&(this.#V=null)});this.#V=n}async#ze(e,t,n){if(this.#k!==e)return;let r=t.filter(e=>this.#H.get(e.id)!==e.displayContent);if(r.length===0)this.#Ve(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#H.set(e.id,e.displayContent);this.#k===e&&n&&(this.#A=n),this.#Ve(e,t)}catch(i){if(!n&&this.#Be(i)){await this.#ze(e,r,!0);return}if(i instanceof Fd&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ve(e,t);return}this.#he(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Be(e){return e instanceof Fd?e.code===`request_failed`:e instanceof Error}#Ve(e,t){let n=this.#Fe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#Pe(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#Ne())return;let e=this.#Fe();if(!e)return;if(this.#k&&e.conversationId!==this.#k){this.#Pe(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#Pe(null):(this.#Re(e.conversationId,t),await this.#V?.catch(()=>{}))}#He(){this.#k&&(this.#A=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ue(){await this.awaitHistorySettled(),await this.#Ae(),this.#L===`new_conversation_required`&&await this.#Se()}static#We(e){return e instanceof Fd&&e.code===`conversation_deleted`}async#Ge(t,n,r,i,a){let o=this.#e,s=e=>{this.#e===o&&this.handleEvent(e)};this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s);return}catch(t){if(n.signal.aborted||this.#e!==o||!e.#We(t))throw t;let c=await this.#Ke(i);if(!c)throw t;this.#Ie([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s)}}async#Ke(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(!0),this.#k=null,this.#A=null,this.#j=null,this.#I=!0;try{let e=this.#de;if(e){let t=await e.prepareStartNew({context:this.#pe()});await this.#ye(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#I=!1}return this.#Pt(n),this.#kt(!0),this.#he(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=gu(this.config,n),i=Pf(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&bu(n)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#at();return}this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.#M+=1,this.#N+=1,this.client=new Rd(this.config,this.historyInternals),a&&this.#at(),this.#Xe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#qe(e);return this.upsertMessage(t),t}#qe(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e;return{id:a??(t===`user`?Uc():t===`assistant`?Wc():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#It(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d},...e.dispatchError!==void 0&&{dispatchError:e.dispatchError}}}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=e.map(e=>this.#qe(e));return this.messages=this.#Rt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}updateComponentProps(e,t){let n=this.messages.find(t=>t.id===e),r=n&&df(n);return!n||n.role!==`assistant`||n.variant||!r?!1:(this.upsertMessage({...n,rawContent:JSON.stringify({text:n.content,component:r.component,props:t})}),!0)}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!t||t.role!==`assistant`||t.variant||!df(t)?!1:(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),!0)}async#Je(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
18
18
 
19
19
  `),a=[i,t].filter(Boolean).join(`
20
20
 
21
21
  `),o=Array.isArray(e.contentParts)&&e.contentParts.length>0,s=r.contentParts.length>0;if(o){let t=[];i&&t.push(js(i)),t.push(...r.contentParts),t.push(...e.contentParts),e.contentParts=t}else if(s){let t=[];a&&t.push(js(a)),t.push(...r.contentParts),e.contentParts=t}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,t){let n=e.trim(),r=!!t?.replayFields&&(t.replayFields.llmContent!==void 0||t.replayFields.rawContent!==void 0||(t.replayFields.contextMentions?.length??0)>0);if(!n&&(!t?.contentParts||t.contentParts.length===0)&&(!t?.mentions||t.mentions.refs.length===0)&&!r)return;this.#re&&!t?.voiceTurn&&(this.#re.failed=!0,this.#re=null),(this.#z||this.#V||this.#R||this.#J)&&await this.#Ue(),this.stopSpeaking(),this.client.cancelStreams(),this.abortController?.abort(),this.#i(),this.#rt(),this.#Qe++,this.#Tt();let i=t?.voiceTurn?.userMessageId,a=i?this.messages.find(e=>e.id===i&&e.role===`user`):void 0,o=a?.id??Uc(),s=Wc();this.#d=null;let c=t?.contentParts&&ks(t.contentParts)?Vs:``,l={id:o,role:`user`,content:n||c,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#It(),viaVoice:t?.viaVoice||!1,...t?.contentParts&&t.contentParts.length>0&&{contentParts:t.contentParts},...t?.mentions&&t.mentions.refs.length>0&&{contextMentions:t.mentions.refs},...t?.contentSegments&&t.contentSegments.length>0&&{contentSegments:t.contentSegments},...t?.composerOptions&&{composerOptions:t.composerOptions},...t?.replayFields??{}};a?(a.viaVoice=!0,delete a.voiceCaption,a.content.trim()!==n&&(a.llmContent=n),this.callbacks.onMessagesChanged([...this.messages])):this.#Pt(l),this.#kt(!0);let u=new AbortController;this.abortController=u;let d=this.#e;if(t?.mentions){let e=this.messages.find(e=>e.id===o)??l;if(await this.#Je(e,n,t.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}if(t?.quote&&!t.replayFields){let e=this.messages.find(e=>e.id===o)??l,n=Xd({quote:t.quote,text:e.llmContent??e.content,contentParts:e.contentParts});n.contentParts&&(e.contentParts=n.contentParts),n.llmContent!==void 0&&(e.llmContent=n.llmContent),(n.contentParts||n.llmContent!==void 0)&&(e.quote={...t.quote},this.callbacks.onMessagesChanged([...this.messages]))}let f=(/* @__PURE__ */ new Date()).toISOString(),p=a?[...this.messages.filter(e=>e!==a),{...a,createdAt:f}]:[...this.messages],m=(a??this.messages.find(e=>e.id===o))?.createdAt??f,h=Gd(t?.voiceTurn?.priorToolResults,m);for(let e of h)this.messages.some(t=>t.id===e.id)||(this.#Pt(e),p.push({...e,createdAt:f}));let g=h.map(({agentMetadata:e})=>{let{toolCallId:t,toolName:n,args:r,result:i}=e.clientToolAnswer;return{toolCallId:t,name:n,arguments:r,result:i}});try{await this.#Ge(p,u,s,o,{composerOptions:t?.composerOptions,interrupt:t?.interrupt,voiceSpoken:!!t?.voiceTurn,...g.length>0&&{voicePriorToolResults:g}})}catch(e){if(this.#e!==d||this.status===`resuming`||this.#f)return;this.#re&&(this.#re.failed=!0);let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));t||this.#At(e),this.#Ot(`idle`),this.#kt(!1),this.abortController=null,this.#a(t?`cancel`:`error`,d),t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}resubmitFrom(e,t){let n=Qd(this.messages,e);if(!n)return!1;let r=this.messages[n.start],i=t.replacement,a=i?i.text:r.content,o=i?i.contentParts:r.contentParts;if(!(a?.trim()||(o?.length??0)>0||!i&&(r.llmContent?.trim()?.length??0)>0))return!1;let s=i?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}},c=i?this.#Ye(i.options):r.composerOptions,l=i?i.contentSegments:r.contentSegments,u=i?i.options?.quote:void 0,d=i?i.viaVoice:r.viaVoice;return this.cancel(),this.messages=this.messages.slice(0,n.start),this.sendMessage(a??``,{...o?.length?{contentParts:[...o]}:{},...l?.length?{contentSegments:[...l]}:{},...c?{composerOptions:c}:{},...u?{quote:u}:{},...s&&Object.keys(s).length>0?{replayFields:s}:{},viaVoice:d===!0}),!0}#Ye(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}async continueConversation(){if(this.streaming)return;(this.#z||this.#V||this.#R||this.#J)&&await this.#Ue(),this.abortController?.abort(),this.#Tt(),this.#i();let e=Wc();this.#d=null,this.#kt(!0);let t=new AbortController;this.abortController=t;let n=this.#e,r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},e=>{this.#e===n&&this.handleEvent(e)})}catch(e){if(this.#e!==n||this.status===`resuming`||this.#f)return;let t=e instanceof Error&&(e.name===`AbortError`||e.message.includes(`aborted`)||e.message.includes(`abort`));t||this.#At(e),this.#a(t?`cancel`:`error`,n),this.#Ot(`idle`),this.#kt(!1),this.abortController=null,t||(e instanceof Error?this.callbacks.onError?.(e):this.callbacks.onError?.(Error(String(e))))}}async connectStream(e,t){if(this.streaming&&!t?.allowReentry)return;this.#e||this.#i(),t?.allowReentry||this.abortController?.abort(),t?.preserveAssistantId&&t.assistantMessageId&&(this.#d=t.assistantMessageId);let n=t?.preserveAssistantId?t.assistantMessageId:void 0,r=!1;for(let e of this.messages)e.streaming&&e.id!==n&&(e.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.#kt(!0);let i=this.#e,a={};try{await this.client.processStream(e,e=>{if(this.#e!==i)return;let n=this.#c;this.#c=a;try{this.handleEvent(e,t?.readOnlyReplay)}finally{this.#c=n}},t?.assistantMessageId,t?.seedContent,this.abortController?.signal,t?.readOnlyReplay?this.messages:void 0,t?.readOnlyReplay?this.#p:void 0),this.#jt(a)}catch(e){if(this.#e!==i)return;if(this.status===`resuming`||this.#f){this.#Mt(a);return}this.#jt(a),this.#Ot(`error`),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null),this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))}}#Xe(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}if(e.signal?.aborted)return Promise.resolve(!1);let t;do t=`webmcp-${++this.#S}`;while(this.messages.some(e=>e.id===`approval-${t}`||e.approval?.id===t));let n={id:t,status:`pending`,agentId:``,executionId:``,toolName:e.toolName,...e.toolCallId?{toolCallId:e.toolCallId}:{},toolType:`webmcp`,description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,approval:n}),new Promise(t=>{this.webMcpApprovalResolvers.set(r,t),e.signal?.addEventListener(`abort`,()=>this.resolveWebMcpApproval(r,`timeout`),{once:!0})})}resolveWebMcpApproval(e,t){let n=this.webMcpApprovalResolvers.get(e);if(!n)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(t=>t.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:t,resolvedAt:Date.now()}}),n(t===`approved`)}#Ze;#Qe;#$e(e){let t=this.#Ze??={s:this,setStreaming:e=>this.#kt(e),appendMessage:e=>this.#Pt(e),nextSequence:()=>this.#It(),settleApprovalPausedToolCall:e=>this.#Nt(e),resumeAfter:e=>this.#u?.executionId===e?this.#u.lastEventId:void 0},n=fl();if(n)return e(n,t);let r=this.#Qe;return ul().then(n=>r===this.#Qe?e(n,t):void 0,e=>{this.callbacks.onError?.(e instanceof Error?e:Error(String(e)))})}resolveApproval(e,t,n){return this.#$e((r,i)=>r.resolveApproval(i,e,t,n))}resolveAskUserQuestion(e,t){return this.#$e((n,r)=>n.resolveAskUserQuestion(r,e,t))}resolveWebMcpToolCall(e){return this.#$e((t,n)=>t.resolveWebMcpToolCall(n,e))}persistAskUserQuestionProgress(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let n=this.messages.find(t=>t.id===e.id);n&&this.upsertMessage({...n,agentMetadata:{...n.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}#et(e){let t=e.agentMetadata?.executionId,n=e.toolCall?.id;if(!t||!n){let t=this.#x;queueMicrotask(()=>{t===this.#x&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(t);r||(r={snapshots:[],seen:/* @__PURE__ */ new Set},this.webMcpAwaitBatches.set(t,r)),!r.seen.has(n)&&(r.seen.add(n),r.snapshots.push(e))}#tt(){if(this.webMcpAwaitBatches.size===0)return;let e=this.#x;queueMicrotask(()=>{if(e===this.#x)for(let e of[...this.webMcpAwaitBatches.keys()])this.#nt(e)})}#nt(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:n}=t;n.length===1?this.resolveWebMcpToolCall(n[0]):n.length>1&&this.#$e((t,r)=>t.resolveWebMcpToolCallBatch(r,e,n))}#rt(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,`denied`);this.webMcpAwaitBatches.clear(),this.#x++}cancel(){this.client.cancelStreams(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.#kt(!1),this.#Ot(`idle`),this.#a(`cancel`)}clearMessages(){this.client.cancelStreams(),this.#ut(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.#t=void 0,this.messages=[],this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),this.#a(`cancel`)}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.#b}selectArtifact(e){this.#b=e,this.#st()}clearArtifacts(){this.#ot()}upsertArtifact(e){let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,n=e.artifactType===`markdown`?{id:t,artifactType:`markdown`,title:e.title,status:`complete`,markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:t,artifactType:`component`,title:e.title,status:`complete`,component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(t,n),this.#b=t,this.#st(),e.transcript!==!1&&this.#it(n),n}#it(e){let t=`artifact-ref-${e.id}`,n=Zn(Xn(this.config.features?.artifacts,e),{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:`complete`,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown===void 0?{}:{markdown:e.markdown}}),r=this.messages.find(e=>e.id===t);r?(r.rawContent=n,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages])):this.injectAssistantMessage({id:t,content:``,rawContent:n})}#at(){let e=!1;for(let t of this.artifacts.values()){let n=this.messages.find(e=>e.id===`artifact-ref-${t.id}`);if(!n)continue;let r=Zn(Xn(this.config.features?.artifacts,t),{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:t.status,...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}});n.rawContent!==r&&(n.rawContent=r,n.streaming=t.status===`streaming`,e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}#ot(){(this.artifacts.size!==0||this.#b!==null)&&(this.artifacts.clear(),this.#b=null,this.#st())}#st(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.#b})}#ct(e){switch(e.type){case`artifact_start`:e.artifactType===`markdown`?this.artifacts.set(e.id,{id:e.id,artifactType:`markdown`,title:e.title,status:`streaming`,markdown:``,...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:`component`,title:e.title,status:`streaming`,component:e.component??``,props:{}}),this.#b=e.id;break;case`artifact_delta`:{let t=this.artifacts.get(e.id);t?.artifactType===`markdown`&&(t.markdown=(t.markdown??``)+e.artDelta);break}case`artifact_update`:{let t=this.artifacts.get(e.id);t?.artifactType===`component`&&(t.props={...t.props,...e.props},e.component&&(t.component=e.component));break}case`artifact_complete`:{let t=this.artifacts.get(e.id);t&&(t.status=`complete`);break}default:return}this.#st()}hydrateMessages(e){this.client.cancelStreams(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.#t=void 0,this.messages=this.#Rt(e.map(e=>({...Iu(e),streaming:!1,sequence:e.sequence??this.#It()}))),this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),this.#a(`cancel`)}hydrateArtifacts(e,t=null,n=!1){this.artifacts.clear();for(let t of e)this.artifacts.set(t.id,{...t,status:n?t.status:`complete`});this.#b=t,this.#st()}assertBackgroundSwitchable(){let e=this.config.backgroundConversations;if(e?.capabilities?.durableExecution!==!0||e.capabilities?.readOnlyReplay!==!0||typeof e.reconnectStream!=`function`)throw new Ff(`background_unavailable`,`This backend does not support background conversations`);if(this.config.parseSSEEvent)throw new Ff(`background_unavailable`,`Background replay requires the native event parser`);if(this.#_t()||this.webMcpResolveControllers.size||this.webMcpAwaitBatches.size||(this.streaming||this.#f)&&(!this.#u||!this.#k))throw new Ff(`conversation_busy`,`This turn cannot safely continue in the background`)}async#lt(){if(this.#h)return;let e=this.config.backgroundConversations,t=this.#N,{BackgroundConversationController:n}=await Ud();if(t!==this.#N||e!==this.config.backgroundConversations)throw new Ff(`superseded`,`The history identity changed`);if(this.#h)return;this.#h=new n(e,e=>{this.#ft(e)});let r=!0;this.#g=this.#de?.subscribeIdentityStatus(()=>{r||(this.#h?.clear(),this.cancel())})??null,r=!1}#ut(){this.#h?.clear(),this.#h=null,this.#g?.(),this.#g=null}#dt(e){let t=this.#u?.executionId??this.agentExecution?.executionId,n=this.#k;if(!this.config.backgroundConversations||!t||!n)return;let r={conversationId:n,executionId:t,status:e,detached:!1};this.#ft(r)}#ft(e){try{this.config.onConversationExecutionState?.(e)}catch{}try{this.callbacks.onConversationExecutionState?.(e)}catch{}}#pt(){let e=this.config.backgroundConversations,t=this.#k;return e&&t?n=>e.reconnectStream({...n,conversationId:t}):this.config.reconnectStream}#mt(e){this.#i(e.handle.executionId),this.#d=e.handle.assistantMessageId;let t=this.messages.find(e=>e.id===this.#d);t&&(t.streaming=e.streamCheckpoint?.openAssistant??!0),this.#p=e.streamCheckpoint,this.agentExecution={executionId:e.handle.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#u=e.handle,this.#Dt(!0),this.#dt(e.observedStatus??`running`),this.#vt()}#ht(e){let t=this.agentExecution?.executionId;if(!t||!this.#d||this.agentExecution?.status!==`running`)return;let n=this.#u===null;this.#u={executionId:t,lastEventId:e,assistantMessageId:this.#d,status:`running`},this.#Dt(n),n&&this.#dt(`running`)}#gt(){return this.#u!==null&&typeof this.#pt()==`function`&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.#_t()}#_t(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant===`approval`&&e.approval?.status===`pending`)}#vt(){this.#f||this.#u&&typeof this.#pt()==`function`&&(this.#f=!0,this.callbacks.onReconnect?.({phase:`paused`,handle:this.#u}),this.#kt(!0),this.#Ot(`resuming`),this.#yt().then(e=>{this.#f&&this.#u&&e.begin()}))}#yt(){return this.#_?Promise.resolve(this.#_):(this.#v||(this.#v=Mf().then(({createReconnectController:e})=>{let t=e(this.#bt());return this.#_=t,t}),this.#v.catch(()=>{this.#v=null})),this.#v)}#bt(){let e=this;return{get config(){return{...e.config,reconnectStream:e.#pt()}},getResumable:()=>e.#u,clearResumable:()=>e.#Et(),getStatus:()=>e.status,setStatus:t=>e.#Ot(t),setStreaming:t=>e.#kt(t),setReconnecting:t=>{e.#f=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,isAwaitPending:()=>e.#_t(),notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,n,r)=>e.connectStream(t,{assistantMessageId:n,allowReentry:!0,preserveAssistantId:!0,seedContent:r,readOnlyReplay:!!e.config.backgroundConversations}),appendMessage:t=>e.#Pt(t),settleParked:t=>e.#xt(t),nextSequence:()=>e.#It(),emitReconnect:t=>e.callbacks.onReconnect?.(t),buildErrorContent:t=>If(Error(t),e.config.errorMessage),onError:t=>e.callbacks.onError?.(t)}}reconnectNow(){this.#f?this.#_?.wake():this.#vt()}resumeFromHandle(e){if(typeof this.config.reconnectStream!=`function`||this.#f)return;if(this.#i(e.executionId),this.#_t()){this.#St(e.executionId),this.#u={executionId:e.executionId,lastEventId:e.after,assistantMessageId:this.#d??``,status:`running`};return}let t=this.#Ct(e.executionId)?Wc():this.#wt();t||(t=Wc(),this.#Pt({id:t,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:this.#It()})),this.#d=t,this.#St(e.executionId),this.#u={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:`running`},this.#vt()}#xt(e){let t=this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0;if(!t&&!this.#_t()){if(!this.#Ct(e))return!1;this.#Et()}if(this.#f=!1,!t){let e=!1;for(let t of this.messages)t.streaming&&(t.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.#kt(!1),this.abortController=null}return this.#Ot(`idle`),!0}#St(e){this.agentExecution||={executionId:e,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0}}#Ct(e){return this.messages.some(t=>t.agentMetadata?.executionId===e&&[t.toolCall,...t.tools??[]].some(e=>e?.interrupted===!0))}#wt(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role===`assistant`&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role===`user`)break}return null}#Tt(){this.#f=!1,this.#_?.teardown(),this.#Et()}#Et(){this.#y&&=(clearTimeout(this.#y),null);let e=this.#u!==null;this.#u=null,this.#p=void 0,e&&this.config.onExecutionState?.(null)}#Dt(e){let t=this.config.onExecutionState;t&&(e?(this.#y&&=(clearTimeout(this.#y),null),t(this.#u)):this.#y||=setTimeout(()=>{this.#y=null,this.config.onExecutionState?.(this.#u)},500))}getResumableHandle(){return this.#u}#Ot(e){e===`error`&&(this.#n=!0,this.#o()),this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}#kt(e){if(e||this.#o(),this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&(this.#jt(void 0),this.speakLatestAssistantMessage())}speakLatestAssistantMessage(e){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider===`browser`||t.provider===`runtype`&&t.browserFallback))return;let n=[...this.messages].reverse().find(e=>e.role===`assistant`&&e.content&&!e.voiceProcessing);if(!n||e&&!e.includes(n.id))return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let r=gf(n.content);r.trim()&&this.readAloud.play(n.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(e){return ff(e)}toggleReadAloud(e){let t=this.messages.find(t=>t.id===e);if(!t||t.role!==`assistant`)return;let n=gf(t.content||``);if(!n.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:n,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<`u`&&`speechSynthesis`in window&&window.speechSynthesis.cancel()}#At(e){for(let e of this.messages)e.streaming=!1;let t=If(e,this.config.errorMessage);t?this.#Pt({id:Wc(),role:`assistant`,content:t,dispatchError:!0,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),sequence:this.#It()}):this.callbacks.onMessagesChanged([...this.messages])}#jt(e){for(let[t,n]of[...this.#s])n===e&&(this.#s.delete(t),this.#Nt(t))}#Mt(e){for(let[t,n]of this.#s)n===e&&this.#s.set(t,void 0)}#Nt(e){let t=this.messages.find(t=>t.id===e)?.approval,n=t?.toolCallId,r=n&&this.messages.find(e=>e.toolCall?.id===n),i=r&&r.toolCall;if(!i||i.status===`complete`||t.status===`pending`)return;let a={...i,status:`complete`,approvalStatus:t.status,completedAt:Date.now(),...t.status===`approved`?{superseded:!0}:{success:!1,error:t.status===`denied`?`Denied`:`Approval timed out`}};this.upsertMessage({...r,streaming:!1,toolCall:a})}#Pt(e){let t=this.#Ft(e),n=this.messages[this.messages.length-1];this.messages=!n||this.#Lt(n,t)<=0?[...this.messages,t]:this.#Rt([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.#Ft(e),n=this.messages.findIndex(e=>e.id===t.id);if(n===-1){this.#Pt(t);return}this.messages=this.messages.map((e,r)=>{if(r!==n||e.toolCall?.name&&Wn(e.toolCall.name)&&e.toolCall.status===`complete`&&t.toolCall?.id===e.toolCall.id&&t.toolCall.status!==`complete`&&(t.toolCall.status===`pending`&&!t.toolCall.name||!e.toolCall.interrupted&&(e.toolCall.result!==void 0||e.toolCall.success!==void 0)&&(!t.agentMetadata?.executionId||t.agentMetadata.executionId===e.agentMetadata?.executionId)))return e;let i={...e,...t};e.agentMetadata?.askUserQuestionAnswered===!0&&t.agentMetadata&&(i.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...e.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:e.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),e.agentMetadata?.suggestRepliesResolved===!0&&t.agentMetadata&&(i.agentMetadata={...i.agentMetadata??t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1});let a=e.agentMetadata?.clientToolAnswer;if(a&&i.agentMetadata&&!i.agentMetadata.clientToolAnswer&&(i.agentMetadata={...i.agentMetadata,clientToolAnswer:a}),e.approval&&t.approval&&e.approval.id===t.approval.id){let n=e.approval,r=t.approval;i.approval={...n,...r,executionId:r.executionId||n.executionId,toolCallId:r.toolCallId||n.toolCallId,toolName:r.toolName||n.toolName,description:r.description||n.description,toolType:r.toolType??n.toolType,reason:r.reason??n.reason,parameters:r.parameters??n.parameters}}let o=t.toolCall?.name,s=t.agentMetadata?.executionId,c=t.toolCall?.id;if(o&&Lf(o)&&s&&c&&t.agentMetadata?.awaitingLocalTool===!0){let t=`${s}:${c}`,n=this.webMcpInflightKeys.has(t),r=this.webMcpResolvedKeys.has(t),a=e.toolCall?.name,o=e.agentMetadata?.executionId===s&&e.toolCall?.id===c&&a!==void 0&&Lf(a)&&e.toolCall?.status===`complete`&&!e.toolCall.interrupted;(n||r||o)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=e.toolCall,i.streaming=e.streaming)}return i});let r=this.messages[n],i=this.messages[n-1],a=this.messages[n+1];(i&&this.#Lt(i,r)>0||a&&this.#Lt(r,a)>0)&&(this.messages=this.#Rt(this.messages)),this.callbacks.onMessagesChanged([...this.messages])}#Ft(e){return e.sequence===void 0?{...e,sequence:this.#It()}:{...e}}#It(){return this.#l++}#Lt(e,t){let n=new Date(e.createdAt).getTime(),r=new Date(t.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(r)&&n!==r)return n-r;let i=e.sequence??0,a=t.sequence??0;return i===a?e.id.localeCompare(t.id):i-a}#Rt(e){return[...e].sort((e,t)=>this.#Lt(e,t))}};X(),Gs(),_n(),Pn();function zf(e){let t=J(`div`,`persona-attachment-preview persona-relative persona-inline-block`),n=e,r=``,i=()=>{let{state:e}=n,r=n.config.attachments?.preview,i=e.kind===`image`,a=i?r?.image:r?.file,o=i?r?.image?.layout??`thumbnail`:r?.file?.layout??`tile`;if(t.dataset.kind=e.kind,t.dataset.layout=o,t.dataset.fileIcon=String(r?.file?.icon!==!1),t.dataset.iconPlacement=r?.file?.iconPlacement??`start`,t.dataset.removeVisibility=a?.remove?.visibility??`always`,t.dataset.removePlacement=a?.remove?.placement??`overlap`,t.replaceChildren(),i&&e.previewUrl){let n=Y(`img`,{className:`persona-attachment-image`,attrs:{src:e.previewUrl,alt:e.name},style:{objectFit:r?.image?.fit??`cover`}}),i=r?.image?.name??`hidden`;if(o===`chip`||i!==`hidden`){let r=J(`div`,`persona-attachment-image-card`);r.append(n),i!==`hidden`&&r.append(Y(`span`,{className:`persona-attachment-file-name`,text:i===`basename`?e.name.replace(/\.[^.]+$/,``):e.name})),t.append(r)}else t.append(n)}else{let n=J(`div`,`persona-attachment-file`),i=e.mimeType,a=i.includes(`spreadsheet`)||i.includes(`excel`)?he:i===`application/json`?me:i===`application/pdf`||i.startsWith(`text/`)||i.includes(`word`)?A:pe,o=(r?.file?.iconName?G(r.file.iconName,20,`currentColor`,1.5):null)??gn(a,20,`currentColor`,1.5);o&&r?.file?.icon!==!1&&(o.classList.add(`persona-attachment-file-icon`),n.append(o));let s=J(`div`,`persona-attachment-file-copy`),c=r?.file?.name??`hidden`;c!==`hidden`&&s.append(Y(`span`,{className:`persona-attachment-file-name`,text:c===`basename`?e.name.replace(/\.[^.]+$/,``):e.name}));let l=r?.file?.metadata,u=l===`size`?e.size<1024?`${e.size} B`:e.size<1048576?`${Math.round(e.size/1024)} KB`:`${(e.size/1048576).toFixed(1)} MB`:l===`line-count`&&e.lineCount!==void 0?`${e.lineCount} ${e.lineCount===1?`line`:`lines`}`:``;u&&s.append(Y(`span`,{className:`persona-attachment-file-metadata`,text:u})),s.childNodes.length&&n.append(s);let d=r?.file?.badge??`type`;d!==`none`&&n.append(Y(`span`,{className:`persona-attachment-file-badge`,text:d===`extension`?e.name.match(/\.([^.]+)$/)?.[1].toUpperCase()??Bs(i,e.name):Bs(i,e.name)})),t.append(n)}let s=Y(`div`,{className:`persona-attachment-status`,attrs:{"data-persona-attachment-status":``}}),c=J(`div`,`persona-attachment-progress`);c.append(J(`div`,`persona-attachment-progress__bar`));let l=Y(`button`,{className:`persona-attachment-retry`,attrs:{type:`button`,"aria-label":`Retry upload`}}),u=G(`rotate-cw`,12,`#ffffff`,2);u?l.append(u):l.textContent=`↻`,l.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n.actions.retry()}),s.append(c,l);let d=Y(`button`,{className:`persona-attachment-remove`,attrs:{type:`button`,"aria-label":`Remove attachment`}}),f=gn(z,10,`currentColor`,2);f?d.append(f):d.textContent=`×`,d.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n.actions.remove()}),t.append(s),((a?.remove?.placement===`inline`?t.querySelector(`.persona-attachment-file, .persona-attachment-image-card`):null)??t).append(d)},a=e=>{n=e;let{state:a}=n,o=JSON.stringify([n.config.attachments?.preview,a.lineCount,a.previewUrl]);r!==o&&(r=o,i()),t.dataset.status=a.status,t.setAttribute(`aria-busy`,String(a.status===`uploading`||a.status===`processing`)),t.title=a.status===`error`?`${a.name}: ${a.error??`Upload failed`}`:a.name;let s=t.querySelector(`.persona-attachment-progress__bar`);s&&(s.style.width=typeof a.progress==`number`?`${Math.round(a.progress*100)}%`:``)};return a(e),{element:t,update:a}}Gs();const Bf={add:e=>Ls(e)},Vf=e=>Number.isFinite(e)?Math.min(1,Math.max(0,e)):0,Hf={allowedTypes:Ws,maxFileSize:10485760,maxFiles:4};function Uf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}var Wf=class e{#e=[];#t;#n=/* @__PURE__ */ new Set;#r=/* @__PURE__ */ new Map;#i=null;#a=/* @__PURE__ */ new Map;#o=/* @__PURE__ */ new WeakMap;#s=!1;#c=!1;constructor(e={}){this.#t={allowedTypes:e.allowedTypes??Hf.allowedTypes,maxFileSize:e.maxFileSize??Hf.maxFileSize,maxFiles:e.maxFiles??Hf.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange,preview:e.preview,widgetConfig:e.widgetConfig,instanceId:e.instanceId,renderAttachmentPreview:e.renderAttachmentPreview,adapter:e.adapter}}#l(){return typeof this.#t.adapter?.add==`function`}#u(){return this.#l()?this.#t.adapter:Bf}setPreviewsContainer(e){this.#i!==e&&this.#y(),this.#i=e}remountPreviews(e){if(this.#y(),this.#i=e,e){e.innerHTML=``;for(let e of this.#e)this.#g(e)}this.#x()}updateConfig(e){if(`allowedTypes`in e&&(this.#t.allowedTypes=e.allowedTypes?.length?e.allowedTypes:Hf.allowedTypes),`maxFileSize`in e&&(this.#t.maxFileSize=e.maxFileSize??Hf.maxFileSize),`maxFiles`in e&&(this.#t.maxFiles=e.maxFiles??Hf.maxFiles),`onFileRejected`in e&&(this.#t.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.#t.onAttachmentsChange=e.onAttachmentsChange),`adapter`in e&&(this.#t.adapter=e.adapter),`preview`in e&&(this.#t.preview=e.preview),`widgetConfig`in e&&(this.#t.widgetConfig=e.widgetConfig),`instanceId`in e&&(this.#t.instanceId=e.instanceId),`renderAttachmentPreview`in e&&e.renderAttachmentPreview!==this.#t.renderAttachmentPreview)this.#t.renderAttachmentPreview=e.renderAttachmentPreview,this.remountPreviews(this.#i);else for(let e of this.#e)this.#_(e),this.#b(e)}isReady(){return this.#e.every(e=>e.status===`ready`)}getAttachments(){return[...this.#e]}getContentParts(){return this.#e.map(e=>e.contentPart).filter(e=>e!==null)}hasAttachments(){return this.#e.length>0}count(){return this.#e.length}async handleFileSelect(e){e&&e.length!==0&&await this.handleFiles(Array.from(e))}async handleFiles(e){if(!e.length||this.#s)return;let t=[];for(let n of e){if(this.#e.length>=this.#t.maxFiles){this.#t.onFileRejected?.(n,`count`);continue}let e=Rs(n,this.#t.allowedTypes,this.#t.maxFileSize);if(!e.valid){let t=e.error?.includes(`type`)?`type`:`size`;this.#t.onFileRejected?.(n,t);continue}let r={id:Uf(),file:n,previewUrl:Is(n)?URL.createObjectURL(n):null,contentPart:null,status:this.#l()?`uploading`:`processing`,progress:this.#l()?0:void 0};this.#e.push(r),this.#g(r),t.push(r),this.#b(r)}this.#x(),this.#m(),await Promise.all(t.map(e=>this.#d(e)))}async#d(e){let t=new AbortController;this.#a.set(e.id,t);let n=this.#u(),r=()=>this.#s||t.signal.aborted||this.#a.get(e.id)!==t||!this.#e.includes(e);try{let i=await n.add(e.file,{signal:t.signal,onProgress:t=>{r()||e.status!==`uploading`||(e.progress=Vf(t),this.#_(e),this.#m())}});if(r()){this.#s&&this.#c&&this.#p(i,n);return}this.#o.set(e,n),e.contentPart=i,e.status=`ready`,e.progress=void 0,e.error=void 0}catch(t){if(r())return;e.status=`error`,e.progress=void 0,e.error=t instanceof Error?t.message:String(t??`Upload failed`)}finally{this.#a.get(e.id)===t&&this.#a.delete(e.id)}this.#_(e),this.#m()}retryAttachment(e){let t=this.#e.find(t=>t.id===e);!t||t.status!==`error`||this.#s||(t.status=this.#l()?`uploading`:`processing`,t.progress=this.#l()?0:void 0,t.error=void 0,this.#_(t),this.#m(),this.#d(t))}#f(e){let t=this.#a.get(e);t&&(this.#a.delete(e),t.abort())}removeAttachment(e){let t=this.#e.findIndex(t=>t.id===e);if(t===-1)return;let n=this.#e[t];this.#f(e),n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.#e.splice(t,1),this.#v(e),this.#n.delete(e);let r=this.#i?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),n.status===`ready`&&n.contentPart&&this.#p(n.contentPart,this.#o.get(n)),this.#x(),this.#m()}async#p(e,t){try{await t?.remove?.(e,{signal:new AbortController().signal})}catch(e){console.error(`[AttachmentManager] adapter.remove failed:`,e)}}clearAttachments(){this.#y(),this.#n.clear();for(let e of this.#e)this.#f(e.id),e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.#e=[],this.#a.clear(),this.#i&&(this.#i.innerHTML=``),this.#x(),this.#m()}destroy(e){if(!this.#s){this.#s=!0,this.#y(),this.#c=e?.release===!0;for(let e of this.#a.values())e.abort();this.#a.clear();for(let e of this.#e)e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.#c&&e.status===`ready`&&e.contentPart&&this.#p(e.contentPart,this.#o.get(e));this.#e=[],this.#i=null}}#m(){this.#s||this.#t.onAttachmentsChange?.(this.getAttachments())}#h(e){let t={instanceId:this.#t.instanceId??``,state:Object.freeze({id:e.id,name:e.file.name,mimeType:e.file.type,size:e.file.size,status:e.status,progress:e.progress,error:e.error,lineCount:e.lineCount,kind:Is(e.file)?`image`:`file`,previewUrl:e.previewUrl}),config:{...this.#t.widgetConfig,attachments:{...this.#t.widgetConfig?.attachments,preview:this.#t.preview}},actions:{remove:()=>this.removeAttachment(e.id),retry:()=>this.retryAttachment(e.id)},defaultRenderer:()=>zf(t)};return t}#g(e){if(!this.#i)return;let t=this.#h(e),n=null;try{n=this.#t.renderAttachmentPreview?.(t)??null}catch(e){console.error(`[AttachmentManager] preview renderer failed:`,e)}n??=t.defaultRenderer();let r=n instanceof HTMLElement?{element:n}:n;r.element.dataset.attachmentId=e.id,this.#r.set(e.id,r),this.#i.appendChild(r.element)}#_(e){try{this.#r.get(e.id)?.update?.(this.#h(e))}catch(e){console.error(`[AttachmentManager] preview update failed:`,e)}}#v(e){let t=this.#r.get(e);if(t){this.#r.delete(e);try{t.destroy?.()}catch(e){console.error(`[AttachmentManager] preview cleanup failed:`,e)}finally{t.element.remove()}}}#y(){for(let e of this.#r.keys())this.#v(e)}async#b(e){let t=e.file;if(!this.#n.has(e.id)&&!(this.#t.preview?.file?.metadata!==`line-count`||t.size>1048576||![`text/plain`,`text/markdown`,`text/csv`,`application/json`].includes(t.type))){this.#n.add(e.id);try{let n=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>e(String(r.result??``)),r.onerror=()=>n(r.error),r.readAsText(t)});if(this.#s||!this.#e.includes(e)||n.includes(`\0`))return;e.lineCount=n===``?0:n.split(/\r\n|\r|\n/).length-+!!/\r?\n$|\r$/.test(n),this.#_(e)}catch{}}}#x(){this.#i&&(this.#i.style.display=this.#e.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,preview:t?.preview,adapter:t?.adapter})}};const Gf=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Kf=(e,t)=>e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.id===r.id&&e.name===r.name&&e.mimeType===r.mimeType&&e.size===r.size&&e.status===r.status&&e.progress===r.progress&&e.error===r.error});function qf(){let e={text:``,attachments:[],mentionRefs:[],selectedModelId:void 0,activeModeIds:[],quote:void 0,pendingSubmission:void 0,preparing:!1,streaming:!1,inputDisabled:!1,sendDisabled:!1},t=/* @__PURE__ */ new Set,n=null,r=!1,i=!1,a=()=>e.preparing?`preparing`:e.streaming?`streaming`:`idle`,o=()=>{let t=a();return Object.freeze({text:e.text,attachments:Object.freeze(e.attachments.map(e=>Object.freeze({...e}))),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:t,inputDisabled:e.inputDisabled,sendDisabled:t!==`idle`||e.sendDisabled||e.inputDisabled})},s=()=>(n||=o(),n),c=()=>{if(r=!1,i||t.size===0)return;let e=s();for(let n of[...t])try{n(e)}catch(e){typeof console<`u`&&console.error(`[AgentWidget] composer state listener failed:`,e)}},l=()=>{n=null,!(i||r)&&(r=!0,queueMicrotask(c))};return{getState:s,subscribe:e=>(t.add(e),()=>t.delete(e)),setText:t=>{e.text!==t&&(e.text=t,l())},setAttachments:t=>{Kf(e.attachments,t)||(e.attachments=[...t],l())},setMentionRefs:t=>{Gf(e.mentionRefs,t)||(e.mentionRefs=[...t],l())},setSelectedModelId:t=>{e.selectedModelId!==t&&(e.selectedModelId=t,l())},setActiveModeIds:t=>{Gf(e.activeModeIds,t)||(e.activeModeIds=[...t],l())},setQuote:t=>{let n=e.quote;(n?.text!==t?.text||n?.messageId!==t?.messageId||n?.sourceLabel!==t?.sourceLabel)&&(e.quote=t?{...t}:void 0,l())},setPendingSubmission:t=>{e.pendingSubmission!==t&&(e.pendingSubmission=t,l())},setPreparing:t=>{e.preparing!==t&&(e.preparing=t,l())},setStreaming:t=>{e.streaming!==t&&(e.streaming=t,l())},setInputDisabled:t=>{e.inputDisabled!==t&&(e.inputDisabled=t,l())},setSendDisabled:t=>{e.sendDisabled!==t&&(e.sendDisabled=t,l())},flush:()=>{r&&c()},destroy:()=>{i=!0,r=!1,t.clear()}}}X();const Jf=(e,...t)=>{for(let n of t){let t=e.querySelector(n);if(t)return t}return null},Yf=(e,t)=>{let n=J(`div`,e);return n.setAttribute(t,``),n.setAttribute(`data-persona-composer-synthesized`,``),n.style.display=`contents`,n};function Xf(e,t={}){let n=Jf(e,`[data-persona-composer-form]`),r=Jf(e,`[data-persona-composer-input]`);if(!n||!r){let e=`[Persona] composer surface is missing required element(s): ${[!n&&`form`,!r&&`input`].filter(Boolean).join(`, `)}. Mark them with data-persona-composer-form / data-persona-composer-input.`;if(t.debug&&(n||r))throw Error(e);return typeof console<`u`&&console.warn(e),null}let i={header:Jf(e,`[data-persona-composer-header]`),body:Jf(e,`[data-persona-composer-body]`),actionsStart:Jf(e,`[data-persona-composer-actions-start]`,`.persona-widget-composer__left-actions`),actionsEnd:Jf(e,`[data-persona-composer-actions-end]`,`.persona-widget-composer__right-actions`),actionsRow:Jf(e,`[data-persona-composer-actions]`,`.persona-widget-composer .persona-flex.persona-items-center.persona-justify-between`),suggestions:Jf(e,`[data-persona-composer-suggestions]`,`.persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2`),status:Jf(e,`[data-persona-composer-status]`)},a=/* @__PURE__ */ new Set,o=i.header;o||(a.add(`header`),o=Yf(`persona-widget-composer__header`,`data-persona-composer-header`),n.parentNode?n.parentNode.insertBefore(o,n):e.appendChild(o));let s=i.body??r.parentElement??n,c=(e,t,n,r,i)=>{if(t)return t;a.add(e);let o=Yf(n,r);return i.appendChild(o),o},l=c(`actionsStart`,i.actionsStart,`persona-widget-composer__left-actions`,`data-persona-composer-actions-start`,n),u=c(`actionsEnd`,i.actionsEnd,`persona-widget-composer__right-actions`,`data-persona-composer-actions-end`,n),d=c(`suggestions`,i.suggestions,`persona-widget-composer__suggestions`,`data-persona-composer-suggestions`,e),f=c(`status`,i.status,`persona-widget-composer__status`,`data-persona-composer-status`,e),p=[],m=(e,t)=>e.target===t.target&&e.type===t.type&&e.handler===t.handler,h=Jf(e,`[data-persona-composer-attachment-input]`,`input[type="file"]`)??void 0;return{footer:e,form:n,input:r,header:o,body:s,actionsStart:l,actionsEnd:u,suggestions:d,status:f,attachmentInput:h,attachmentPreviews:Jf(e,`[data-persona-composer-attachment-previews]`,`.persona-attachment-previews`)??void 0,attachmentButton:Jf(e,`[data-persona-composer-attachment-button]`,`.persona-attachment-button`)??void 0,sendButton:Jf(e,`[data-persona-composer-submit]`)??void 0,micButton:Jf(e,`[data-persona-composer-mic]`)??void 0,synthesized:a,found:i,addListener:(e,t,n,r)=>{e.addEventListener(t,n,r),p.push({target:e,type:t,handler:n,options:r})},removeListener:(e,t,n,r)=>{e.removeEventListener(t,n,r),p=p.filter(r=>!m(r,{target:e,type:t,handler:n}))},destroy:()=>{for(let e of p)e.target.removeEventListener(e.type,e.handler,e.options);p=[]}}}[...[`padding`,`rowGap`,`rowPadding`,`rowBorderRadius`,`fontSize`,`lineHeight`,`iconSize`,`iconGap`,`hoverBackground`,`focusBackground`,`descriptionColor`,`descriptionFontSize`,`dividerColor`,`dividerSpacing`,`minWidth`,`maxHeight`].map(e=>`--persona-components-composer-overflowMenu-${e}`)];function Zf(e,t,n,r){return e<=0?r:e>=t+n*2+120+(r?0:16)}const Qf=e=>Number.parseFloat(e)||0;function $f(e,t){let n=t.getComputedStyle(e);if(n.display===`none`)return 0;let r=Array.from(e.children).filter(e=>{if(!(e instanceof t.HTMLElement))return!1;let n=t.getComputedStyle(e);return n.display!==`none`&&![`absolute`,`fixed`].includes(n.position)});return r.reduce((e,n)=>{let r=t.getComputedStyle(n);return e+(r.display===`contents`?$f(n,t):Math.max(n.getBoundingClientRect().width,n.scrollWidth))+Qf(r.marginLeft)+Qf(r.marginRight)},0)+Math.max(0,r.length-1)*Qf(n.columnGap)+Qf(n.paddingLeft)+Qf(n.paddingRight)}function ep(e){let t=null,n=null,r=null,i=null,a=0,o=!0,s=!1,c=!1,l=()=>{i!==null&&t?.form.ownerDocument.defaultView?.cancelAnimationFrame(i),i=null,n?.disconnect(),r?.disconnect(),n=null,r=null,t?.form.ownerDocument.defaultView?.removeEventListener(`resize`,u)},u=()=>{if(c||i!==null)return;let n=t?.form.ownerDocument.defaultView;n&&(i=n.requestAnimationFrame(()=>{i=null,c||e.onMeasure()}))};return{measure:()=>{if(c)return o;let i=e.getSurface();if(i?.form!==t?.form||i?.input!==t?.input||i?.start!==t?.start||i?.end!==t?.end){l(),t=i,o=!0,s=!1,a=0;let e=t?.form.ownerDocument.defaultView;if(t&&e){if(e.addEventListener(`resize`,u),e.ResizeObserver!==void 0){n=new e.ResizeObserver(u);let r=[t.form,t.start,t.end,t.input];for(let e of r)n.observe(e)}e.MutationObserver!==void 0&&(r=new e.MutationObserver(e=>{e.some(e=>e.target!==t?.input||e.type!==`attributes`)&&u()}),r.observe(t.form,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`]}))}}t&&i&&(t.resizeInput=i.resizeInput);let d=t?.form.ownerDocument.defaultView;if(!t||!d)return!0;if(!t.form.clientWidth)return o;let f=d.getComputedStyle(t.form),p=Math.max(1,t.form.clientWidth-Qf(f.paddingLeft)-Qf(f.paddingRight)),m=$f(t.start,d)+$f(t.end,d),h=Qf(f.columnGap);s=m+h+(s?16:0)>p,o=Zf(p,m,h,o);let g=t.input.getBoundingClientRect().width;if(t.resizeInput!==!1&&g>0&&g!==a&&t.input.tagName===`TEXTAREA`){a=g,t.input.style.height=`auto`;let e=Qf(d.getComputedStyle(t.input).maxHeight)||1/0,n=Math.min(t.input.scrollHeight,e);t.input.style.height=`${n}px`}return o},toolbarCrowded:()=>s,refresh:u,destroy:()=>{c=!0,l(),t=null}}}const tp={mention:100,attachment:200,mic:800,overflow:900,send:1e3,custom:500};X();const np=`[data-persona-composer-chip-row]`;function rp(e){let t=e.querySelector(np);if(t)return t;let n=Y(`div`,{className:`persona-composer-chip-row`,attrs:{"data-persona-composer-chip-row":``}});n.style.display=`none`;let r=e.querySelector(`[data-persona-composer-quote], [data-persona-composer-pending]`);return r?.parentElement===e?e.insertBefore(n,r):e.appendChild(n),n}X(),Pn();function ip(e){let t=Y(`div`,{className:`persona-composer-quote`,attrs:{"data-persona-composer-quote":``}});t.style.display=`none`;let n=``,r=!1,i=n=>{let r=J(`span`,`persona-composer-quote-bar`),i=J(`div`,`persona-composer-quote-content`);if(n.sourceLabel){let e=J(`div`,`persona-composer-quote-source`);e.textContent=n.sourceLabel,i.appendChild(e)}let a=Y(`div`,{className:`persona-composer-quote-text`,attrs:{"data-persona-composer-quote-text":``}});a.textContent=Zd(n.text),i.appendChild(a);let o=Y(`button`,{className:`persona-composer-quote-dismiss`,attrs:{type:`button`,"aria-label":e.dismissLabel??`Remove quote`,"data-persona-composer-quote-dismiss":``}}),s=G(`x`,12,`currentColor`,2);s?o.appendChild(s):o.textContent=`×`,o.addEventListener(`click`,t=>{t.preventDefault(),t.stopPropagation(),e.onDismiss()}),t.replaceChildren(r,i,o)};return{element:t,render:e=>{if(r)return;let a=e?`${e.sourceLabel??``}${e.text}`:``;a!==n&&(n=a,e?(i(e),t.style.display=`flex`):(t.replaceChildren(),t.style.display=`none`))},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}X(),Pn();function ap(e){let t=Y(`div`,{className:`persona-composer-pending`,attrs:{"data-persona-composer-pending":``}});t.style.display=`none`;let n,r=!1,i=(e,t,n,r)=>{let i=Y(`button`,{className:`persona-composer-pending-action`,attrs:{type:`button`,"aria-label":t,[n]:``}}),a=G(e,12,`currentColor`,2);return a?i.appendChild(a):i.textContent=t,i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},a=e=>{let t=Zd(e.text??``,90);if(t)return t;let n=e.contentParts?.length??0;return n>0?n===1?`1 attachment`:`${n} attachments`:(e.mentionRefs?.length??0)>0?e.mentionRefs.map(e=>e.label).join(`, `):`Queued message`};return{element:t,render:o=>{if(r||o===n)return;if(n=o,!o){t.replaceChildren(),t.style.display=`none`;return}let s=J(`span`,`persona-composer-pending-badge`);s.textContent=e.label??`Sends next`;let c=Y(`div`,{className:`persona-composer-pending-text`,attrs:{"data-persona-composer-pending-text":``}});c.textContent=a(o),t.replaceChildren(s,c,i(`pencil`,e.editLabel??`Edit queued message`,`data-persona-composer-pending-edit`,e.onEdit),i(`x`,e.removeLabel??`Remove queued message`,`data-persona-composer-pending-remove`,e.onRemove)),t.style.display=`flex`},destroy:()=>{r=!0,t.replaceChildren(),t.remove()}}}X();function op(e){let t=Y(`div`,{className:`persona-message-edit`,attrs:{"data-persona-message-edit":e.messageId,"data-preserve-runtime":``}}),n=Y(`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 r=()=>{n.style.height=`auto`,n.style.height=`${n.scrollHeight}px`};n.addEventListener(`input`,r);let i=J(`div`,`persona-message-edit-actions`),a=(e,t,n,r)=>{let i=Y(`button`,{className:`persona-message-edit-button ${t}`,attrs:{type:`button`,[n]:``},text:e});return i.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),r()}),i},o=()=>{let t=n.value.trim();t&&e.onSave(t)};return i.append(a(e.cancelLabel??`Cancel`,`persona-message-edit-cancel`,`data-persona-message-edit-cancel`,e.onCancel),a(e.saveLabel??`Send`,`persona-message-edit-save`,`data-persona-message-edit-save`,o)),n.addEventListener(`keydown`,t=>{t.key===`Escape`?(t.preventDefault(),t.stopPropagation(),e.onCancel()):t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),o())}),t.append(n,i),{element:t,getValue:()=>n.value,focus:()=>{n.focus();let e=n.value.length;n.setSelectionRange(e,e),r()},destroy:()=>{t.replaceChildren(),t.remove()}}}function sp(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 cp(e,t){if(!e||typeof e.text!=`string`)return;let n=new Set(t.mentionSourceIds),r=(e.mentionRefs??[]).filter(e=>n.has(e.sourceId)),i=r.length===(e.mentionRefs?.length??0)&&r.length>0,a=new Set(t.modes.map(e=>e.id)),o=(e.activeModeIds??[]).filter(e=>a.has(e)),s=e.selectedModelId&&t.modelIds.includes(e.selectedModelId)?e.selectedModelId:void 0;return{text:e.text,...i?{mentionRefs:r}:{},...i&&e.contentSegments?.length?{contentSegments:e.contentSegments}:{},...s?{selectedModelId:s}:{},...o.length?{activeModeIds:o}:{},...e.quote?.text?{quote:e.quote}:{}}}function lp(e){let t=e.delay??500,n=null,r=!1,i=()=>{n!==null&&(clearTimeout(n),n=null)};return{schedule:()=>{r||(i(),n=setTimeout(()=>{n=null,e.write()},t))},flush:()=>{r||n===null||(i(),e.write())},cancel:i,destroy:()=>{r=!0,i()}}}const up=e=>`core:mode:${e}`;function dp(e,t){return e?t?.find(t=>t.id===e)?.presentation===`segmented`:!1}function fp(e,t){return e?t?.find(t=>t.id===e)?.chipVisibility===`hidden`:!1}function pp(e,t,n=!1){return e?.length?e.filter(e=>!dp(e.groupId,t)&&!fp(e.groupId,t)&&(!n||e.presentation===`overflow`||t?.find(t=>t.id===e.groupId)?.chipVisibility===`auto`)):[]}const mp=(e,t)=>e.groupId?t?.find(t=>t.id===e.groupId)?.selection??null:null;function hp(e,t,n,r){let i=n.find(e=>e.id===t);if(!i)return[...e];let a=e.includes(t),o=new Set(e);if(a)o.delete(t);else{if(mp(i,r)===`single`){let e=n.filter(e=>e.groupId===i.groupId).map(e=>e.id);o=new Set([...o].filter(t=>!e.includes(t)))}o.add(t)}return n.filter(e=>o.has(e.id)).map(e=>e.id)}function gp(e,t){return t?.length?t.filter(t=>e.includes(t.id)).map(e=>e.id):[]}function _p(e,t){return t?.length?t.filter(t=>e.includes(t.id)&&(t.persistence??`sticky`)!==`once`).map(e=>e.id):[]}function vp(e,t){if(t?.length&&e.length!==0)return t.find(t=>e.includes(t.id)&&t.placeholder)?.placeholder}function yp(e,t,n){let r=[];for(let i of e)r.includes(i)||(r=hp(r,i,t,n));return r}function bp(e){return e.wrapped||e.text.includes(`
22
- `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function xp(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Sp(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0),s=e.style.height,c=e.style.getPropertyPriority(`height`),l=e.tagName===`TEXTAREA`;l&&(e.style.height=`auto`);let u=e.scrollHeight-o;return l&&e.style.setProperty(`height`,s,c),u>a*1.5}function Cp(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function wp(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 Tp(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const Ep=e=>typeof e?.then==`function`;function Dp(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Op(e,t,n){let r;try{r=e(wp(t),{signal:n})}catch(e){return{status:`error`,error:e}}return Ep(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:Dp(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):Dp(t,r)}const kp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),Ap={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`};Es();const jp=`16px`,Mp=`transparent`,Np={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:(()=>{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})(),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`}},Pp={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`}},Fp={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:gs,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:jp,canvasBackground:Mp,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`}}},Ip=Np.colors.gray,Lp={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},Rp={...Np,colors:{...Np.colors,gray:Ip}},zp={...Np,colors:{...Np.colors,gray:Lp},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},Bp=Rp,Vp=Pp,Hp={...Pp,colors:{...Pp.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...Pp.typography,fontSize:`14px`,lineHeight:`1.5`}},Up=Vp,Wp=Fp,Gp={...Fp,scrollToBottom:{...Fp.scrollToBottom,background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,size:`32px`},messageActions:{background:`transparent`,border:`none`,hoverBackground:`components.button.ghost.hoverBackground`,hoverForeground:`semantic.colors.text`,borderRadius:`palette.radius.md`},launcher:Ap,activity:{rowHeight:`32px`,labelSize:`13px`,iconSize:`16px`,indent:`0px`,transcriptGap:`0px`,responseGap:`12px`,groupIndent:`16px`,groupGap:`2px`,groupPadding:`2px 0`,bodyPadding:`4px 0`,bodyFontWeight:`400`,sectionGap:`8px`,bodySurface:`transparent`},toolBubble:{shadow:`none`},reasoningBubble:{shadow:`none`},input:{...Fp.input,borderRadius:`palette.radius.full`},introCard:{...Fp.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...Fp.suggestion.chip,fontWeight:`400`},card:{...Fp.suggestion.card,fontWeight:`400`},list:{...Fp.suggestion.list,fontWeight:`400`}},panel:{...Fp.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...Fp.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`,iconPadding:`auto`,controlSize:`28px`,controlIconSize:`16px`,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:{...Fp.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...Fp.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:{...Fp.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},artifact:{...Fp.artifact,card:{background:`semantic.colors.surface`,border:`1px solid var(--persona-border)`,borderRadius:`palette.radius.lg`,hoverBackground:`components.button.ghost.hoverBackground`,hoverBorderColor:`semantic.colors.border`},inline:{background:`semantic.colors.surface`,border:`1px solid var(--persona-border)`,borderRadius:`palette.radius.lg`,chromeBackground:`semantic.colors.surface`,chromeBorder:`semantic.colors.border`,titleColor:`semantic.colors.text`,mutedColor:`semantic.colors.textMuted`}},composer:{...Fp.composer,padding:`8px`,fontSize:`15px`,lineHeight:`1.5`,controlSize:`32px`,controlIconSize:`20px`,expandedPadding:`12px 16px`,expandedBorderRadius:`24px`,sendIconSize:`18px`,sendButtonRadius:`9999px`,footerBorder:`none`,overflowMenu:{borderRadius:`12px`},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)`}},Kp=Wp,qp=e=>fs({future:e}),Jp=e=>qp(e)===`v5`?{palette:zp,semantic:Hp,components:Gp}:{palette:Rp,semantic:Vp,components:Wp};function Yp(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?Yp(e,r):r}function Xp(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=Yp(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Zp(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 Qp(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Qp(t,r):r}return n}function $p(e,t={}){let n=Jp(t.future),r=e?.components,i={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:r?Qp(n.components,r):n.components},a=r?.activity;for(let e of[`toolBubble`,`reasoningBubble`]){let t=i.components[e]={...i.components[e]};for(let n of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[n]!==void 0&&(n!==`bodySurface`||r?.[e]?.bodySurface===void 0)&&(t[n]=a[n])}let o=r?.collapsibleWidget?.surface;fs(t)===`v4`&&o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=r?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=r?.composer;i.components.composer={...i.components.composer},c?.padding!==void 0&&c.expandedPadding===void 0&&(i.components.composer.expandedPadding=c.padding),r?.input?.borderRadius!==void 0&&c?.expandedBorderRadius===void 0&&(i.components.composer.expandedBorderRadius=r.input.borderRadius);let l=r?.message;if(l?.gap!==void 0&&l.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Zp(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const em=e=>e.trim()===`0`?`0px`:e,tm=`--persona-`,nm=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},rm=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[tm+n],t!==void 0)break;t!==void 0&&(e[tm+n]=t)}},im=[[`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-textMuted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-textInverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`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`]],am=e=>{let t=Xp(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}return n},om=e=>{let t=e[`--persona-components-launcher-foreground`];e[`--persona-launcher-fg-muted`]=t&&t!==e[`--persona-primary`]?`color-mix(in srgb, ${t} 70%, transparent)`:e[`--persona-muted`]},sm=e=>{if(e[`--persona-components-header-iconPadding`]===`auto`){let t=(e[`--persona-components-header-iconBackground`]??e[`--persona-primary`]).trim().toLowerCase(),n=t.match(/^(?:rgba?|hsla?)\(([^)]+)\)$/)?.[1].split(/[,\s/]+/).filter(Boolean);e[`--persona-components-header-iconPadding`]=t===`transparent`||/^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(t)||n?.length===4&&parseFloat(n[3])===0?`0px`:`6px`}};function cm(e){let t=am(e);rm(t,im),rm(t,[[`ask-sheet-bg`,`components-askUserQuestion-sheet-background`],[`ask-sheet-border`,`components-askUserQuestion-sheet-border`],[`ask-sheet-shadow`,`components-askUserQuestion-sheet-shadow`],[`ask-pill-bg`,`components-askUserQuestion-pill-background`],[`ask-pill-fg`,`components-askUserQuestion-pill-foreground`],[`ask-pill-radius`,`components-askUserQuestion-pill-borderRadius`],[`ask-pill-bg-selected`,`components-askUserQuestion-pill-selectedBackground`],[`ask-pill-fg-selected`,`components-askUserQuestion-pill-selectedForeground`],[`ask-input-bg`,`components-askUserQuestion-customInput-background`],[`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`]]),om(t),rm(t,[[`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`]]),rm(t,[[`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`]]),t[`--persona-panel-border`]=t[`--persona-components-panel-border`]??`1px solid ${t[`--persona-border`]}`,rm(t,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),t[`--persona-panel-inset`]=t[`--persona-components-panel-inset`]??`16px`,t[`--persona-panel-canvas-bg`]=t[`--persona-components-panel-canvasBackground`]??`transparent`,rm(t,[[`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`]]);let n=(n,r,i,a=``)=>{if(n)for(let[o,s,c]of i){let i=n[a+o];i&&(t[`--persona-${r}${s}`]=c?Yp(e,i)??i:i)}};rm(t,[[`header-bg`,`components-header-background`,`surface`]]);let r=t[`--persona-header-bg`],i=t[`--persona-components-header-foreground`],a=i?`color-mix(in srgb, ${i} 72%, ${r})`:void 0;t[`--persona-header-border`]=t[`--persona-components-header-border`]??(i?`color-mix(in srgb, ${i} 14%, ${r})`:void 0)??t[`--persona-divider`],rm(t,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),sm(t),t[`--persona-header-title-fg`]=t[`--persona-components-header-title-color`]??t[`--persona-components-header-titleForeground`]??i??t[`--persona-primary`],t[`--persona-header-subtitle-fg`]=t[`--persona-components-header-subtitle-color`]??t[`--persona-components-header-subtitleForeground`]??a??t[`--persona-text-muted`],t[`--persona-header-action-icon-fg`]=t[`--persona-components-header-actionIconForeground`]??a??t[`--persona-muted`],rm(t,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=16px`]]),n(e.components?.header,`header-`,[[`shadow`,`shadow`],[`borderBottom`,`border-bottom`],[`minHeight`,`min-height`]]),n(t,`history-rail-header-`,[[`background`,`bg`],[`border`,`border`],[`minHeight`,`min-height`]],`--persona-components-history-railHeader-`),n(t,`history-overlay-`,[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]],`--persona-components-history-overlay-`),n(t,`history-menu-`,[[`background`,`bg`],[`borderRadius`,`radius`]],`--persona-components-history-menu-`);let o=e.components?.history?.motion;if(o){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},n=e(o.enterDurationMs);n!==void 0&&(t[`--persona-history-enter-ms`]=n);let r=e(o.exitDurationMs);r!==void 0&&(t[`--persona-history-exit-ms`]=r),o.enterEasing&&(t[`--persona-history-enter-easing`]=o.enterEasing),o.exitEasing&&(t[`--persona-history-exit-easing`]=o.exitEasing)}let s=t[`--persona-components-history-dangerForeground`];s&&(t[`--persona-history-danger-fg`]=s),t[`--persona-danger`]=t[`--persona-components-history-confirm-dangerBackground`]??t[`--persona-palette-colors-error-700`]??`#b42318`,t[`--persona-danger-fg`]=t[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let n=t[`--persona-components-history-confirm-${e}`];n&&(t[`--persona-history-confirm-${e}`]=n)}n(t,`tooltip-`,[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]],`--persona-components-tooltip-`),e.components?.tooltip?.arrow===!1&&(t[`--persona-tooltip-arrow-display`]=`none`),n(t,`scroll-to-bottom-count-`,[[`background`,`bg`],[`foreground`,`fg`],[`border`,`border`],[`borderRadius`,`radius`],[`size`,`size`],[`padding`,`padding`],[`fontSize`,`font-size`],[`fontWeight`,`font-weight`]],`--persona-components-scrollToBottom-countBadge-`),n(t,`message-action-`,[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]],`--persona-components-messageActions-`),rm(t,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let c=t[`--persona-components-introCard-background`],l=t[`--persona-components-introCard-shadow`],u=(!c||c===`transparent`||c===`none`)&&(!l||l===`none`),d=t[`--persona-components-introCard-padding`]??`1.5rem`;t[`--persona-intro-card-padding`]=u&&d===`1.5rem`?`1.5rem 0`:d,rm(t,[[`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`]]),rm(t,[[`panel-background`,`components-panel-background`,`surface`],[`transcript-background`,`components-message-background`,`container`],[`transcript-top-fade-background`,`components-message-topFadeBackground`,`transcript-background`],[`composer-footer-background`,`components-composer-footerBackground`,`surface`],[`composer-footer-padding`,`components-composer-footerPadding`,`=1rem 1.5rem`],[`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`]]),n(t,`md-`,[[`h1-fontSize`,`h1-size`],[`h1-fontWeight`,`h1-weight`],[`h2-fontSize`,`h2-size`],[`h2-fontWeight`,`h2-weight`]],`--persona-components-markdown-heading-`);let f=t[`--persona-components-markdown-prose-fontFamily`];f&&f!==`inherit`&&(t[`--persona-md-prose-font-family`]=f),rm(t,[[`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`]]),rm(t,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),rm(t,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),rm(t,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),rm(t,[[`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`]]);for(let[e,n]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=t[`--persona-components-collapsibleWidget-${e}`]??t[`--persona-${n}`];r!==void 0&&(t[`--persona-cw-${e}`]=r,t[`--cw-${e}`]=r)}rm(t,[[`message-border`,`components-message-border`,`border`]]),rm(t,[[`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 p=e.components;n(p?.iconButton,`icon-btn-`,[[`background`,`bg`],[`border`,`border`],[`color`,`color`],[`padding`,`padding`],[`borderRadius`,`radius`],[`hoverBackground`,`hover-bg`],[`hoverColor`,`hover-color`],[`activeBackground`,`active-bg`],[`activeBorder`,`active-border`]]),n(p?.labelButton,`label-btn-`,[[`background`,`bg`],[`border`,`border`],[`color`,`color`],[`padding`,`padding`],[`borderRadius`,`radius`],[`hoverBackground`,`hover-bg`],[`fontSize`,`font-size`],[`gap`,`gap`]]),n(p?.toggleGroup,`toggle-group-`,[[`gap`,`gap`],[`borderRadius`,`radius`]]);let m=p?.artifact;if(m?.toolbar){let r=m.toolbar;n(r,`artifact-toolbar-icon-`,[[`iconHoverColor`,`hover-color`],[`iconHoverBackground`,`hover-bg`],[`iconPadding`,`padding`],[`iconBorderRadius`,`radius`],[`iconBorder`,`border`]]),r.toggleGroupGap&&(t[`--persona-artifact-toolbar-toggle-group-gap`]=em(r.toggleGroupGap)),r.toggleBorderRadius&&(t[`--persona-artifact-toolbar-toggle-radius`]=r.toggleBorderRadius),r.toggleGroupPadding&&(t[`--persona-artifact-toolbar-toggle-group-padding`]=em(r.toggleGroupPadding)),n(r,`artifact-toolbar-toggle-group-`,[[`toggleGroupBorder`,`border`],[`toggleGroupBorderRadius`,`radius`]]),r.toggleGroupBackground&&(t[`--persona-artifact-toolbar-toggle-group-bg`]=Yp(e,r.toggleGroupBackground)??r.toggleGroupBackground),n(r,`artifact-toolbar-copy-`,[[`copyBackground`,`bg`],[`copyBorder`,`border`],[`copyColor`,`color`]]),r.copyBorderRadius&&(t[`--persona-artifact-toolbar-copy-radius`]=em(r.copyBorderRadius)),r.copyPadding&&(t[`--persona-artifact-toolbar-copy-padding`]=r.copyPadding),r.copyMenuBackground&&(t[`--persona-artifact-toolbar-copy-menu-bg`]=r.copyMenuBackground,t[`--persona-dropdown-bg`]=t[`--persona-dropdown-bg`]??r.copyMenuBackground),r.copyMenuBorder&&(t[`--persona-artifact-toolbar-copy-menu-border`]=r.copyMenuBorder,t[`--persona-dropdown-border`]=t[`--persona-dropdown-border`]??r.copyMenuBorder),r.copyMenuShadow&&(t[`--persona-artifact-toolbar-copy-menu-shadow`]=r.copyMenuShadow,t[`--persona-dropdown-shadow`]=t[`--persona-dropdown-shadow`]??r.copyMenuShadow),r.copyMenuBorderRadius&&(t[`--persona-artifact-toolbar-copy-menu-radius`]=r.copyMenuBorderRadius,t[`--persona-dropdown-radius`]=t[`--persona-dropdown-radius`]??r.copyMenuBorderRadius),r.copyMenuItemHoverBackground&&(t[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=r.copyMenuItemHoverBackground,t[`--persona-dropdown-item-hover-bg`]=t[`--persona-dropdown-item-hover-bg`]??r.copyMenuItemHoverBackground),n(r,`artifact-toolbar-`,[[`iconBackground`,`icon-bg`],[`toolbarBorder`,`border`]])}if(m?.tab){let e=m.tab;n(e,`artifact-tab-`,[[`background`,`bg`],[`activeBackground`,`active-bg`],[`activeBorder`,`active-border`],[`borderRadius`,`radius`],[`textColor`,`color`],[`hoverBackground`,`hover-bg`],[`listBackground`,`list-bg`],[`listBorderColor`,`list-border-color`],[`listPadding`,`list-padding`]])}if(m?.pane){let n=m.pane;n.toolbarBackground&&(t[`--persona-artifact-toolbar-bg`]=Yp(e,n.toolbarBackground)??n.toolbarBackground)}n(m?.card,`artifact-card-`,[[`background`,`bg`,!0],[`border`,`border`],[`borderRadius`,`radius`,!0],[`hoverBackground`,`hover-bg`,!0],[`hoverBorderColor`,`hover-border`,!0]]),n(m?.inline,`artifact-inline-`,[[`background`,`bg`,!0],[`border`,`border`],[`borderRadius`,`radius`,!0],[`chromeBackground`,`chrome-bg`,!0],[`chromeBorder`,`chrome-border`,!0],[`titleColor`,`title-color`,!0],[`mutedColor`,`muted-color`,!0],[`frameHeight`,`frame-height`]]);let h=p?.code;h&&(n(h,`code-`,[[`keywordColor`,`keyword-color`],[`stringColor`,`string-color`],[`commentColor`,`comment-color`],[`numberColor`,`number-color`],[`tagColor`,`tag-color`],[`attrColor`,`attr-color`],[`propertyColor`,`property-color`],[`lineNumberColor`,`line-number-color`],[`gutterBorderColor`,`gutter-border-color`]]),h.background&&(t[`--persona-code-bg`]=Yp(e,h.background)??h.background));let g=t[`--persona-surface`],_=t[`--persona-container`],v=t[`--persona-palette-colors-gray-100`]??`#f3f4f6`,y=t[`--persona-palette-colors-gray-200`]??`#e5e7eb`,b=t[`--persona-palette-colors-gray-300`]??`#d1d5db`,x=!_||_===g,S=nm(g??t[`--persona-background`]),C=x&&S!==void 0&&S<.179,ee=C?`rgba(255, 255, 255, 0.08)`:v,w=C?`rgba(255, 255, 255, 0.12)`:y,T=C?`rgba(255, 255, 255, 0.16)`:b,E=x?ee:_,te=x?w:_;return t[`--persona-icon-btn-hover-bg`]=t[`--persona-icon-btn-hover-bg`]??E,t[`--persona-icon-btn-active-bg`]=t[`--persona-icon-btn-active-bg`]??te,x&&(t[`--persona-icon-btn-active-border`]=t[`--persona-icon-btn-active-border`]??T),t[`--persona-label-btn-hover-bg`]=t[`--persona-label-btn-hover-bg`]??E,t[`--persona-artifact-tab-hover-bg`]=t[`--persona-artifact-tab-hover-bg`]??E,t[`--persona-artifact-card-hover-bg`]=t[`--persona-artifact-card-hover-bg`]??E,t}const lm={header:`Widget header bar`,messages:`Message list area`,"user-message":`User message bubble`,"assistant-message":`Assistant message bubble`,composer:`Footer / composer area`,container:`Main widget container`,"artifact-pane":`Artifact sidebar`,"artifact-toolbar":`Artifact toolbar`,"artifact-inline":`Inline artifact block`,"artifact-inline-chrome":`Inline artifact title bar`};Es(),ds(),yr(),dr(),Wr();const um=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),dm=(e,t)=>{if(!t||!um(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Sm(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:fs(t)===`v5`?`400px`:`420px`}}}:e},fm={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`}}},pm={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)`}}}},mm=fm,hm={...mm,colors:{...mm.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`}}},gm=pm,_m={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:{...pm.components,button:{...pm.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:{...pm.components?.eventStream,badge:{...pm.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`}}}}},vm=e=>fs({future:e})===`v5`?{palette:hm,components:_m}:{palette:mm,components:gm},ym=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},bm=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,xm=e=>{let t=e?.colorScheme??_r(e?.brand)??`light`;return t===`light`?`light`:t===`dark`?`dark`:bm()},Sm=e=>xm(e),Cm=(e,t={})=>$p(e,t),wm=(e,t={})=>{let n=vm(t.future),r=lr(n.components,e??{})??{};return $p({...r,palette:{...r.palette,colors:fs(t)===`v5`?lr(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Tm=e=>{let t=Sm(e),n=lr(vr(e?.brand,t,Jp(e?.future).components,e?.future?.v5Defaults),ym(e?.theme)),r=lr({components:{launcher:kp(e)===`circle`?Ap:{...Wp.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}},...ls(e)?{panel:{background:`transparent`,modes:{inline:{border:`none`,shadow:`none`,borderRadius:`0`}}},header:{background:`transparent`},message:{background:`transparent`},composer:{footerBackground:`transparent`,footerBorder:`none`,overlayBand:`transparent`}}:{}}},n),i=ym(e?.darkTheme),a=dm(t===`dark`?wm(lr(r??{},i??{}),{future:e?.future}):Cm(r,{future:e?.future}),e);return Object.defineProperty(a,Em,{value:[...Mr,`suggestion.chip.padding`,`suggestion.chip.fontWeight`].filter(n=>Ur(e,n,t))}),a},Em=Symbol(`persona.themeConsumerPaths`),Dm=e=>{let t=cm(e);t[`--persona-suggestion-compat-padding`]=`6px 12px`,t[`--persona-suggestion-compat-weight`]=`500`;for(let n of e[Em]??[]){let e=n.split(`.`).join(`-`),r=t[`--persona-components-${e}`];r!==void 0&&(t[n===`suggestion.chip.padding`?`--persona-suggestion-compat-padding`:n===`suggestion.chip.fontWeight`?`--persona-suggestion-compat-weight`:`--persona-consumer-${e}`]=r)}return t},Om=/* @__PURE__ */ new WeakMap,km=(e,t)=>{Am(e,Dm(Tm(t)),t)},Am=(e,t,n)=>{for(let n of Om.get(e)??[])n in t||e.style.removeProperty(n);Om.set(e,Object.keys(t));for(let[n,r]of Object.entries(t))e.style.setProperty(n,r);e.setAttribute(`data-persona-color-scheme`,Sm(n)),e.setAttribute(`data-persona-defaults`,fs(n))},jm=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(bm())});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)`),r=()=>e(bm());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Mm=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Nm=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Pm=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},Fm=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Im=()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},Lm=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Rm=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return Lm(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Lm(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},zm=e=>`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Bm=(e,t)=>{let n=Rm(e);if(!n)return``;let r=Im(),i=zm(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},Vm=e=>Bm(e,!1),Hm=e=>Bm(e,!0),Um=(e,t)=>t.key?.toLowerCase()===e.key&&(Im()?t.metaKey:t.ctrlKey)===e.mod&&!(Im()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Wm=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},Gm=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(Um(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!Wm(n))){e.preventDefault();try{i.run(e)}catch(e){Lm(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=Rm(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(Lm(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,Hm(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}},Km=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;zt.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute(`data-persona-reuse`)&&e.id===t.id)return!1;if(r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&(!t.hasAttribute(`data-preserve-animation`)||(e.dataset.personaLoadingLabel?e.dataset.personaLoadingAnimation!==t.dataset.personaLoadingAnimation:e.textContent!==t.textContent))&&void 0}}}}})},qm=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Jm={index:-1,draft:``};function Ym(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}const Xm=/* @__PURE__ */ new WeakMap;function Zm(e){if(typeof e==`string`)return e.length;if(!e)return 0;if(typeof e!=`object`)return JSON.stringify(e)?.length??0;let t=Xm.get(e);return t===void 0&&(t=JSON.stringify(e)?.length??0,Xm.set(e,t)),t}function Qm(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.dispatchError?`1`:`0`,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)??``,Zm(e.toolCall?.args),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??``,e.toolCall?.actionTitle??``,t].join(`\0`)}function $m(){return/* @__PURE__ */ new Map}function eh(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function th(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function nh(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const rh={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},ih=[`pre`,`code`,`a`,`script`,`style`],ah=e=>({type:e?.type??rh.type,placeholder:e?.placeholder??rh.placeholder,speed:e?.speed??rh.speed,duration:e?.duration??rh.duration,buffer:e?.buffer??rh.buffer}),oh=[{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`}],sh=/* @__PURE__ */ new Map;for(let e of oh)sh.set(e.name,e);const ch=[`wipe`,`glyph-cycle`],lh=e=>{sh.set(e.name,e)},uh=e=>{oh.some(t=>t.name===e)||sh.delete(e)},dh=()=>Array.from(sh.keys()),fh=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:sh.get(e)??null,ph=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
22
+ `)?!1:!(e.hasAttachments||e.hasChips||e.hasQuote||e.hasPendingSubmission)}function xp(){let e=!1;return{observe:(t,n)=>n?(t&&(e=!0),e):(e=!1,!1),release:()=>{e=!1}}}function Sp(e){if(!e)return!1;let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return!1;let n=t.getComputedStyle(e),r=Number.parseFloat(n.lineHeight),i=Number.parseFloat(n.fontSize),a=Number.isFinite(r)&&r>0?r:Number.isFinite(i)&&i>0?i*1.4:0;if(!a)return!1;let o=(Number.parseFloat(n.paddingTop)||0)+(Number.parseFloat(n.paddingBottom)||0),s=e.style.height,c=e.style.getPropertyPriority(`height`),l=e.tagName===`TEXTAREA`;l&&(e.style.height=`auto`);let u=e.scrollHeight-o;return l&&e.style.setProperty(`height`,s,c),u>a*1.5}function Cp(e){e&&(typeof e.requestSubmit==`function`?e.requestSubmit():e.dispatchEvent(new Event(`submit`,{bubbles:!0,cancelable:!0})))}function wp(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 Tp(e){return e.inputDisabled===!0||e.sendDisabled===!0||e.hasAttachments&&!e.attachmentsReady?!1:!!e.text||e.hasAttachments||e.hasMentions||e.hasServerMentions}const Ep=e=>typeof e?.then==`function`;function Dp(e,t){return t===!1?{status:`canceled`}:(!t||typeof t!=`object`||(typeof t.text==`string`&&(e.text=t.text),t.options&&(e.options={...e.options,...t.options})),{status:`proceed`})}function Op(e,t,n){let r;try{r=e(wp(t),{signal:n})}catch(e){return{status:`error`,error:e}}return Ep(r)?Promise.resolve(r).then(e=>n.aborted?{status:`aborted`}:Dp(t,e),e=>n.aborted?{status:`aborted`}:{status:`error`,error:e}):Dp(t,r)}const kp=e=>e?.launcher?.variant??(e?.future?.v5Defaults===!0?`circle`:`pill`),Ap={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`};Es();const jp=`16px`,Mp=`transparent`,Np={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:(()=>{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})(),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`}},Pp={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`}},Fp={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:gs,maxWidth:`none`,height:`min(640px, max(200px, calc(100vh - 64px)))`,maxHeight:`none`,borderRadius:`palette.radius.xl`,shadow:`palette.shadows.xl`,inset:jp,canvasBackground:Mp,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`}}},Ip=Np.colors.gray,Lp={50:`#fafafa`,100:`#f5f5f5`,200:`#e5e5e5`,300:`#d4d4d4`,400:`#a3a3a3`,500:`#737373`,600:`#525252`,700:`#404040`,800:`#262626`,900:`#171717`,950:`#0a0a0a`},Rp={...Np,colors:{...Np.colors,gray:Ip}},zp={...Np,colors:{...Np.colors,gray:Lp},radius:{none:`0px`,sm:`4px`,md:`8px`,lg:`12px`,xl:`16px`,"2xl":`24px`,full:`9999px`}},Bp=Rp,Vp=Pp,Hp={...Pp,colors:{...Pp.colors,surface:`#ffffff`,background:`#ffffff`,container:`semantic.colors.surface`,textInverse:`#ffffff`},typography:{...Pp.typography,fontSize:`14px`,lineHeight:`1.5`}},Up=Vp,Wp=Fp,Gp={...Fp,scrollToBottom:{...Fp.scrollToBottom,background:`semantic.colors.surface`,foreground:`semantic.colors.text`,border:`semantic.colors.border`,size:`32px`},messageActions:{background:`transparent`,border:`none`,hoverBackground:`components.button.ghost.hoverBackground`,hoverForeground:`semantic.colors.text`,borderRadius:`palette.radius.md`},launcher:Ap,activity:{labelSize:`13px`,iconSize:`16px`,indent:`0px`,transcriptGap:`0px`,responseGap:`12px`,groupIndent:`16px`,groupGap:`2px`,groupPadding:`2px 0`,bodyPadding:`4px 0`,bodyFontWeight:`400`,sectionGap:`8px`,bodySurface:`transparent`},toolBubble:{shadow:`none`},reasoningBubble:{shadow:`none`},input:{...Fp.input,borderRadius:`palette.radius.full`},introCard:{...Fp.introCard,title:{fontSize:`22px`,fontWeight:`500`}},suggestion:{chip:{...Fp.suggestion.chip,fontWeight:`400`},card:{...Fp.suggestion.card,fontWeight:`400`},list:{...Fp.suggestion.list,fontWeight:`400`}},panel:{...Fp.panel,width:`min(400px, calc(100vw - 24px))`,height:`min(704px, calc(100dvh - 104px))`,borderRadius:`palette.radius.xl`},header:{...Fp.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`,iconPadding:`auto`,controlSize:`28px`,controlIconSize:`16px`,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:{...Fp.message,gap:`20px`,fullscreenGap:`28px`,topFadeHeight:`18px`,user:{...Fp.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:{...Fp.message.assistant,background:`transparent`,border:`transparent`,borderWidth:`0px`,borderRadius:`0px`,shadow:`none`,padding:`0px`,fontSize:`14px`,lineHeight:`1.55`}},artifact:{...Fp.artifact,card:{background:`semantic.colors.surface`,border:`1px solid var(--persona-border)`,borderRadius:`palette.radius.lg`,hoverBackground:`components.button.ghost.hoverBackground`,hoverBorderColor:`semantic.colors.border`},inline:{background:`semantic.colors.surface`,border:`1px solid var(--persona-border)`,borderRadius:`palette.radius.lg`,chromeBackground:`semantic.colors.surface`,chromeBorder:`semantic.colors.border`,titleColor:`semantic.colors.text`,mutedColor:`semantic.colors.textMuted`}},composer:{...Fp.composer,padding:`8px`,fontSize:`15px`,lineHeight:`1.5`,controlSize:`32px`,controlIconSize:`20px`,expandedPadding:`12px 16px`,expandedBorderRadius:`24px`,sendIconSize:`18px`,sendButtonRadius:`9999px`,footerBorder:`none`,overflowMenu:{borderRadius:`12px`},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)`}},Kp=Wp,qp=e=>fs({future:e}),Jp=e=>qp(e)===`v5`?{palette:zp,semantic:Hp,components:Gp}:{palette:Rp,semantic:Vp,components:Wp};function Yp(e,t){if(!t.startsWith(`palette.`)&&!t.startsWith(`semantic.`)&&!t.startsWith(`components.`))return t;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return typeof r==`string`&&(r.startsWith(`palette.`)||r.startsWith(`semantic.`)||r.startsWith(`components.`))?Yp(e,r):r}function Xp(e){let t={};function n(r,i){for(let[a,o]of Object.entries(r)){let r=`${i}.${a}`;if(typeof o==`string`){let n=Yp(e,o);n!==void 0&&(t[r]={path:r,value:n,type:i.includes(`color`)?`color`:i.includes(`spacing`)?`spacing`:i.includes(`typography`)?`typography`:i.includes(`shadow`)?`shadow`:i.includes(`border`)?`border`:`color`})}else typeof o==`object`&&o&&n(o,r)}}return n(e.palette,`palette`),n(e.semantic,`semantic`),n(e.components,`components`),t}function Zp(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 Qp(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t&&typeof t==`object`&&!Array.isArray(t)&&r&&typeof r==`object`&&!Array.isArray(r)?Qp(t,r):r}return n}function $p(e,t={}){let n=Jp(t.future),r=e?.components,i={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:r?Qp(n.components,r):n.components},a=r?.activity;for(let e of[`toolBubble`,`reasoningBubble`]){let t=i.components[e]={...i.components[e]};for(let n of[`rowHeight`,`labelSize`,`iconSize`,`indent`,`bodySurface`])a?.[n]!==void 0&&(n!==`bodySurface`||r?.[e]?.bodySurface===void 0)&&(t[n]=a[n])}let o=r?.collapsibleWidget?.surface;fs(t)===`v4`&&o!==void 0&&a?.bodySurface===void 0&&(i.components.activity={...i.components.activity,bodySurface:o});let s=r?.header;s?.padding!==void 0&&s.minimalPadding===void 0&&(i.components.header.minimalPadding=i.components.header.padding);let c=r?.composer;i.components.composer={...i.components.composer},c?.padding!==void 0&&c.expandedPadding===void 0&&(i.components.composer.expandedPadding=c.padding),r?.input?.borderRadius!==void 0&&c?.expandedBorderRadius===void 0&&(i.components.composer.expandedBorderRadius=r.input.borderRadius);let l=r?.message;if(l?.gap!==void 0&&l.fullscreenGap===void 0&&(i.components.message.fullscreenGap=i.components.message.gap),t.validate!==!1){let e=Zp(i);if(!e.valid)throw Error(`Theme validation failed: ${e.errors.map(e=>e.message).join(`, `)}`)}if(t.plugins)for(let e of t.plugins)i=e.transform(i);return i}const em=e=>e.trim()===`0`?`0px`:e,tm=`--persona-`,nm=e=>{if(!e)return;let t=e.trim().toLowerCase(),n;if(t.charCodeAt(0)===35){let e=t.slice(1);if(!/^[0-9a-f]+$/.test(e))return;e.length===3||e.length===4?n=[0,1,2].map(t=>parseInt(e[t]+e[t],16)):(e.length===6||e.length===8)&&(n=[0,2,4].map(t=>parseInt(e.slice(t,t+2),16)))}else{let e=t.match(/^rgba?\(([^)]+)\)$/);if(e){let t=e[1].split(/[,/\s]+/).filter(Boolean);t.length>=3&&(n=t.slice(0,3).map(e=>{let t=e.endsWith(`%`),n=parseFloat(t?e.slice(0,-1):e);return t?n/100*255:n}))}}if(!n||n.some(e=>!Number.isFinite(e)))return;let[r,i,a]=n.map(e=>{let t=Math.max(0,Math.min(255,e))/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},rm=(e,t)=>{for(let[n,...r]of t){let t;for(let n of r)if(t=n.charCodeAt(0)===61?n.slice(1):e[tm+n],t!==void 0)break;t!==void 0&&(e[tm+n]=t)}},im=[[`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-textMuted`,`palette-colors-gray-500`],[`text-inverse`,`semantic-colors-textInverse`,`palette-colors-gray-50`],[`border`,`semantic-colors-border`,`palette-colors-gray-200`],[`divider`,`semantic-colors-divider`,`palette-colors-gray-200`],[`muted`,`text-muted`],[`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`]],am=e=>{let t=Xp(e),n={};for(let[e,r]of Object.entries(t)){let t=e.replace(/\./g,`-`);n[`--persona-${t}`]=r.value}return n},om=e=>{let t=e[`--persona-components-launcher-foreground`];e[`--persona-launcher-fg-muted`]=t&&t!==e[`--persona-primary`]?`color-mix(in srgb, ${t} 70%, transparent)`:e[`--persona-muted`]},sm=e=>{if(e[`--persona-components-header-iconPadding`]===`auto`){let t=(e[`--persona-components-header-iconBackground`]??e[`--persona-primary`]).trim().toLowerCase(),n=t.match(/^(?:rgba?|hsla?)\(([^)]+)\)$/)?.[1].split(/[,\s/]+/).filter(Boolean);e[`--persona-components-header-iconPadding`]=t===`transparent`||/^#(?:[\da-f]{3}0|[\da-f]{6}00)$/.test(t)||n?.length===4&&parseFloat(n[3])===0?`0px`:`6px`}};function cm(e){let t=am(e);rm(t,im),rm(t,[[`ask-sheet-bg`,`components-askUserQuestion-sheet-background`],[`ask-sheet-border`,`components-askUserQuestion-sheet-border`],[`ask-sheet-shadow`,`components-askUserQuestion-sheet-shadow`],[`ask-pill-bg`,`components-askUserQuestion-pill-background`],[`ask-pill-fg`,`components-askUserQuestion-pill-foreground`],[`ask-pill-radius`,`components-askUserQuestion-pill-borderRadius`],[`ask-pill-bg-selected`,`components-askUserQuestion-pill-selectedBackground`],[`ask-pill-fg-selected`,`components-askUserQuestion-pill-selectedForeground`],[`ask-input-bg`,`components-askUserQuestion-customInput-background`],[`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`]]),om(t),rm(t,[[`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`]]),rm(t,[[`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`]]),t[`--persona-panel-border`]=t[`--persona-components-panel-border`]??`1px solid ${t[`--persona-border`]}`,rm(t,[[`panel-shadow`,`components-panel-shadow`,`palette-shadows-xl`,`=0 25px 50px -12px rgba(0, 0, 0, 0.25)`]]),t[`--persona-panel-inset`]=t[`--persona-components-panel-inset`]??`16px`,t[`--persona-panel-canvas-bg`]=t[`--persona-components-panel-canvasBackground`]??`transparent`,rm(t,[[`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`]]);let n=(n,r,i,a=``)=>{if(n)for(let[o,s,c]of i){let i=n[a+o];i&&(t[`--persona-${r}${s}`]=c?Yp(e,i)??i:i)}};rm(t,[[`header-bg`,`components-header-background`,`surface`]]);let r=t[`--persona-header-bg`],i=t[`--persona-components-header-foreground`],a=i?`color-mix(in srgb, ${i} 72%, ${r})`:void 0;t[`--persona-header-border`]=t[`--persona-components-header-border`]??(i?`color-mix(in srgb, ${i} 14%, ${r})`:void 0)??t[`--persona-divider`],rm(t,[[`header-icon-bg`,`components-header-iconBackground`,`primary`],[`header-icon-fg`,`components-header-iconForeground`,`text-inverse`]]),sm(t),t[`--persona-header-title-fg`]=t[`--persona-components-header-title-color`]??t[`--persona-components-header-titleForeground`]??i??t[`--persona-primary`],t[`--persona-header-subtitle-fg`]=t[`--persona-components-header-subtitle-color`]??t[`--persona-components-header-subtitleForeground`]??a??t[`--persona-text-muted`],t[`--persona-header-action-icon-fg`]=t[`--persona-components-header-actionIconForeground`]??a??t[`--persona-muted`],rm(t,[[`header-control-size`,`components-header-controlSize`,`=32px`],[`header-control-icon-size`,`components-header-controlIconSize`,`=16px`]]),n(e.components?.header,`header-`,[[`shadow`,`shadow`],[`borderBottom`,`border-bottom`],[`minHeight`,`min-height`]]),n(t,`history-rail-header-`,[[`background`,`bg`],[`border`,`border`],[`minHeight`,`min-height`]],`--persona-components-history-railHeader-`),n(t,`history-overlay-`,[[`margin`,`margin`],[`borderRadius`,`radius`],[`shadow`,`shadow`],[`background`,`bg`]],`--persona-components-history-overlay-`),n(t,`history-menu-`,[[`background`,`bg`],[`borderRadius`,`radius`]],`--persona-components-history-menu-`);let o=e.components?.history?.motion;if(o){let e=e=>{if(e===void 0)return;let t=String(e).trim();return/^\d+(\.\d+)?$/.test(t)?`${t}ms`:t},n=e(o.enterDurationMs);n!==void 0&&(t[`--persona-history-enter-ms`]=n);let r=e(o.exitDurationMs);r!==void 0&&(t[`--persona-history-exit-ms`]=r),o.enterEasing&&(t[`--persona-history-enter-easing`]=o.enterEasing),o.exitEasing&&(t[`--persona-history-exit-easing`]=o.exitEasing)}let s=t[`--persona-components-history-dangerForeground`];s&&(t[`--persona-history-danger-fg`]=s),t[`--persona-danger`]=t[`--persona-components-history-confirm-dangerBackground`]??t[`--persona-palette-colors-error-700`]??`#b42318`,t[`--persona-danger-fg`]=t[`--persona-components-history-confirm-dangerForeground`]??`#ffffff`;for(let e of[`scrim`,`shadow`]){let n=t[`--persona-components-history-confirm-${e}`];n&&(t[`--persona-history-confirm-${e}`]=n)}n(t,`tooltip-`,[[`background`,`background`],[`foreground`,`foreground`],[`hintForeground`,`hint-fg`],[`borderRadius`,`radius`],[`fontSize`,`font-size`],[`padding`,`padding`],[`maxWidth`,`max-width`],[`shadow`,`shadow`]],`--persona-components-tooltip-`),e.components?.tooltip?.arrow===!1&&(t[`--persona-tooltip-arrow-display`]=`none`),n(t,`scroll-to-bottom-count-`,[[`background`,`bg`],[`foreground`,`fg`],[`border`,`border`],[`borderRadius`,`radius`],[`size`,`size`],[`padding`,`padding`],[`fontSize`,`font-size`],[`fontWeight`,`font-weight`]],`--persona-components-scrollToBottom-countBadge-`),n(t,`message-action-`,[[`background`,`bg`],[`border`,`border`],[`hoverBackground`,`hover-bg`],[`hoverForeground`,`hover-fg`],[`borderRadius`,`radius`]],`--persona-components-messageActions-`),rm(t,[[`intro-card-bg`,`components-introCard-background`,`=transparent`],[`intro-card-radius`,`components-introCard-borderRadius`,`=1rem`]]);let c=t[`--persona-components-introCard-background`],l=t[`--persona-components-introCard-shadow`],u=(!c||c===`transparent`||c===`none`)&&(!l||l===`none`),d=t[`--persona-components-introCard-padding`]??`1.5rem`;t[`--persona-intro-card-padding`]=u&&d===`1.5rem`?`1.5rem 0`:d,rm(t,[[`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`]]),rm(t,[[`panel-background`,`components-panel-background`,`surface`],[`transcript-background`,`components-message-background`,`container`],[`transcript-top-fade-background`,`components-message-topFadeBackground`,`transcript-background`],[`composer-footer-background`,`components-composer-footerBackground`,`surface`],[`composer-footer-padding`,`components-composer-footerPadding`,`=1rem 1.5rem`],[`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`]]),n(t,`md-`,[[`h1-fontSize`,`h1-size`],[`h1-fontWeight`,`h1-weight`],[`h2-fontSize`,`h2-size`],[`h2-fontWeight`,`h2-weight`]],`--persona-components-markdown-heading-`);let f=t[`--persona-components-markdown-prose-fontFamily`];f&&f!==`inherit`&&(t[`--persona-md-prose-font-family`]=f),rm(t,[[`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`]]),rm(t,[[`md-code-block-border-radius`,`components-markdown-codeBlock-borderRadius`,`radius-md`,`=0.375rem`]]),rm(t,[[`md-table-header-bg`,`components-markdown-table-headerBackground`,`container`],[`md-table-border-color`,`components-markdown-table-borderColor`,`border`]]),rm(t,[[`md-hr-color`,`components-markdown-hr-color`,`divider`]]),rm(t,[[`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`]]);for(let[e,n]of[[`container`,`surface`],[`surface`,`surface`],[`border`,`border`]]){let r=t[`--persona-components-collapsibleWidget-${e}`]??t[`--persona-${n}`];r!==void 0&&(t[`--persona-cw-${e}`]=r,t[`--cw-${e}`]=r)}rm(t,[[`message-border`,`components-message-border`,`border`]]),rm(t,[[`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 p=e.components;n(p?.iconButton,`icon-btn-`,[[`background`,`bg`],[`border`,`border`],[`color`,`color`],[`padding`,`padding`],[`borderRadius`,`radius`],[`hoverBackground`,`hover-bg`],[`hoverColor`,`hover-color`],[`activeBackground`,`active-bg`],[`activeBorder`,`active-border`]]),n(p?.labelButton,`label-btn-`,[[`background`,`bg`],[`border`,`border`],[`color`,`color`],[`padding`,`padding`],[`borderRadius`,`radius`],[`hoverBackground`,`hover-bg`],[`fontSize`,`font-size`],[`gap`,`gap`]]),n(p?.toggleGroup,`toggle-group-`,[[`gap`,`gap`],[`borderRadius`,`radius`]]);let m=p?.artifact;if(m?.toolbar){let r=m.toolbar;n(r,`artifact-toolbar-icon-`,[[`iconHoverColor`,`hover-color`],[`iconHoverBackground`,`hover-bg`],[`iconPadding`,`padding`],[`iconBorderRadius`,`radius`],[`iconBorder`,`border`]]),r.toggleGroupGap&&(t[`--persona-artifact-toolbar-toggle-group-gap`]=em(r.toggleGroupGap)),r.toggleBorderRadius&&(t[`--persona-artifact-toolbar-toggle-radius`]=r.toggleBorderRadius),r.toggleGroupPadding&&(t[`--persona-artifact-toolbar-toggle-group-padding`]=em(r.toggleGroupPadding)),n(r,`artifact-toolbar-toggle-group-`,[[`toggleGroupBorder`,`border`],[`toggleGroupBorderRadius`,`radius`]]),r.toggleGroupBackground&&(t[`--persona-artifact-toolbar-toggle-group-bg`]=Yp(e,r.toggleGroupBackground)??r.toggleGroupBackground),n(r,`artifact-toolbar-copy-`,[[`copyBackground`,`bg`],[`copyBorder`,`border`],[`copyColor`,`color`]]),r.copyBorderRadius&&(t[`--persona-artifact-toolbar-copy-radius`]=em(r.copyBorderRadius)),r.copyPadding&&(t[`--persona-artifact-toolbar-copy-padding`]=r.copyPadding),r.copyMenuBackground&&(t[`--persona-artifact-toolbar-copy-menu-bg`]=r.copyMenuBackground,t[`--persona-dropdown-bg`]=t[`--persona-dropdown-bg`]??r.copyMenuBackground),r.copyMenuBorder&&(t[`--persona-artifact-toolbar-copy-menu-border`]=r.copyMenuBorder,t[`--persona-dropdown-border`]=t[`--persona-dropdown-border`]??r.copyMenuBorder),r.copyMenuShadow&&(t[`--persona-artifact-toolbar-copy-menu-shadow`]=r.copyMenuShadow,t[`--persona-dropdown-shadow`]=t[`--persona-dropdown-shadow`]??r.copyMenuShadow),r.copyMenuBorderRadius&&(t[`--persona-artifact-toolbar-copy-menu-radius`]=r.copyMenuBorderRadius,t[`--persona-dropdown-radius`]=t[`--persona-dropdown-radius`]??r.copyMenuBorderRadius),r.copyMenuItemHoverBackground&&(t[`--persona-artifact-toolbar-copy-menu-item-hover-bg`]=r.copyMenuItemHoverBackground,t[`--persona-dropdown-item-hover-bg`]=t[`--persona-dropdown-item-hover-bg`]??r.copyMenuItemHoverBackground),n(r,`artifact-toolbar-`,[[`iconBackground`,`icon-bg`],[`toolbarBorder`,`border`]])}if(m?.tab){let e=m.tab;n(e,`artifact-tab-`,[[`background`,`bg`],[`activeBackground`,`active-bg`],[`activeBorder`,`active-border`],[`borderRadius`,`radius`],[`textColor`,`color`],[`hoverBackground`,`hover-bg`],[`listBackground`,`list-bg`],[`listBorderColor`,`list-border-color`],[`listPadding`,`list-padding`]])}if(m?.pane){let n=m.pane;n.toolbarBackground&&(t[`--persona-artifact-toolbar-bg`]=Yp(e,n.toolbarBackground)??n.toolbarBackground)}n(m?.card,`artifact-card-`,[[`background`,`bg`,!0],[`border`,`border`],[`borderRadius`,`radius`,!0],[`hoverBackground`,`hover-bg`,!0],[`hoverBorderColor`,`hover-border`,!0]]),n(m?.inline,`artifact-inline-`,[[`background`,`bg`,!0],[`border`,`border`],[`borderRadius`,`radius`,!0],[`chromeBackground`,`chrome-bg`,!0],[`chromeBorder`,`chrome-border`,!0],[`titleColor`,`title-color`,!0],[`mutedColor`,`muted-color`,!0],[`frameHeight`,`frame-height`]]);let h=p?.code;h&&(n(h,`code-`,[[`keywordColor`,`keyword-color`],[`stringColor`,`string-color`],[`commentColor`,`comment-color`],[`numberColor`,`number-color`],[`tagColor`,`tag-color`],[`attrColor`,`attr-color`],[`propertyColor`,`property-color`],[`lineNumberColor`,`line-number-color`],[`gutterBorderColor`,`gutter-border-color`]]),h.background&&(t[`--persona-code-bg`]=Yp(e,h.background)??h.background));let g=t[`--persona-surface`],_=t[`--persona-container`],v=t[`--persona-palette-colors-gray-100`]??`#f3f4f6`,y=t[`--persona-palette-colors-gray-200`]??`#e5e7eb`,b=t[`--persona-palette-colors-gray-300`]??`#d1d5db`,x=!_||_===g,S=nm(g??t[`--persona-background`]),C=x&&S!==void 0&&S<.179,ee=C?`rgba(255, 255, 255, 0.08)`:v,w=C?`rgba(255, 255, 255, 0.12)`:y,T=C?`rgba(255, 255, 255, 0.16)`:b,E=x?ee:_,te=x?w:_;return t[`--persona-icon-btn-hover-bg`]=t[`--persona-icon-btn-hover-bg`]??E,t[`--persona-icon-btn-active-bg`]=t[`--persona-icon-btn-active-bg`]??te,x&&(t[`--persona-icon-btn-active-border`]=t[`--persona-icon-btn-active-border`]??T),t[`--persona-label-btn-hover-bg`]=t[`--persona-label-btn-hover-bg`]??E,t[`--persona-artifact-tab-hover-bg`]=t[`--persona-artifact-tab-hover-bg`]??E,t[`--persona-artifact-card-hover-bg`]=t[`--persona-artifact-card-hover-bg`]??E,t}const lm={header:`Widget header bar`,messages:`Message list area`,"user-message":`User message bubble`,"assistant-message":`Assistant message bubble`,composer:`Footer / composer area`,container:`Main widget container`,"artifact-pane":`Artifact sidebar`,"artifact-toolbar":`Artifact toolbar`,"artifact-inline":`Inline artifact block`,"artifact-inline-chrome":`Inline artifact title bar`};Es(),ds(),yr(),dr(),Wr();const um=e=>!!e&&`launcher`in e&&(e.launcher?.sidebarMode===!0||e.launcher?.mountMode===`docked`),dm=(e,t)=>{if(!t||!um(t))return e;let n=t.theme?.components?.panel?.width,r=t.darkTheme?.components?.panel?.width;return(Sm(t)===`dark`?r??n:n)==null?{...e,components:{...e.components,panel:{...e.components.panel,width:fs(t)===`v5`?`400px`:`420px`}}}:e},fm={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`}}},pm={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)`}}}},mm=fm,hm={...mm,colors:{...mm.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`}}},gm=pm,_m={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:{...pm.components,button:{...pm.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:{...pm.components?.eventStream,badge:{...pm.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`}}}}},vm=e=>fs({future:e})===`v5`?{palette:hm,components:_m}:{palette:mm,components:gm},ym=e=>{if(e&&typeof e==`object`&&!Array.isArray(e))return e},bm=()=>typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches?`dark`:`light`,xm=e=>{let t=e?.colorScheme??_r(e?.brand)??`light`;return t===`light`?`light`:t===`dark`?`dark`:bm()},Sm=e=>xm(e),Cm=(e,t={})=>$p(e,t),wm=(e,t={})=>{let n=vm(t.future),r=lr(n.components,e??{})??{};return $p({...r,palette:{...r.palette,colors:fs(t)===`v5`?lr(n.palette.colors,r.palette?.colors):{...n.palette.colors,...r.palette?.colors}}},{validate:!1,future:t.future})},Tm=e=>{let t=Sm(e),n=lr(vr(e?.brand,t,Jp(e?.future).components,e?.future?.v5Defaults),ym(e?.theme)),r=lr({components:{launcher:kp(e)===`circle`?Ap:{...Wp.launcher,...e?.future?.v5Defaults?{offset:`1.5rem`}:{}},...ls(e)?{panel:{background:`transparent`,modes:{inline:{border:`none`,shadow:`none`,borderRadius:`0`}}},header:{background:`transparent`},message:{background:`transparent`},composer:{footerBackground:`transparent`,footerBorder:`none`,overlayBand:`transparent`}}:{}}},n),i=ym(e?.darkTheme),a=dm(t===`dark`?wm(lr(r??{},i??{}),{future:e?.future}):Cm(r,{future:e?.future}),e);return Object.defineProperty(a,Em,{value:[...Mr,`suggestion.chip.padding`,`suggestion.chip.fontWeight`].filter(n=>Ur(e,n,t))}),a},Em=Symbol(`persona.themeConsumerPaths`),Dm=e=>{let t=cm(e);t[`--persona-suggestion-compat-padding`]=`6px 12px`,t[`--persona-suggestion-compat-weight`]=`500`;for(let n of e[Em]??[]){let e=n.split(`.`).join(`-`),r=t[`--persona-components-${e}`];r!==void 0&&(t[n===`suggestion.chip.padding`?`--persona-suggestion-compat-padding`:n===`suggestion.chip.fontWeight`?`--persona-suggestion-compat-weight`:`--persona-consumer-${e}`]=r)}return t},Om=/* @__PURE__ */ new WeakMap,km=(e,t)=>{Am(e,Dm(Tm(t)),t)},Am=(e,t,n)=>{for(let n of Om.get(e)??[])n in t||e.style.removeProperty(n);Om.set(e,Object.keys(t));for(let[n,r]of Object.entries(t))e.style.setProperty(n,r);e.setAttribute(`data-persona-color-scheme`,Sm(n)),e.setAttribute(`data-persona-defaults`,fs(n))},jm=e=>{let t=[];if(typeof document<`u`&&typeof MutationObserver<`u`){let n=new MutationObserver(()=>{e(bm())});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)`),r=()=>e(bm());n.addEventListener?(n.addEventListener(`change`,r),t.push(()=>n.removeEventListener(`change`,r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(e=>e())}},Mm=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??`720px`:`768px`),Nm=(e,t)=>t||e?.composer?.placement!==`overlay`?`block`:`overlay`,Pm=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},Fm=e=>Math.max(0,Math.round(e.columnHeight*(1-e.fraction))-e.footerHeight),Im=()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e)},Lm=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Rm=e=>{let t=e.toLowerCase().split(`+`).map(e=>e.trim()),n=t.pop(),r={key:n,mod:!1,shift:!1,alt:!1};for(let n of t)if(n===`mod`||n===`cmd`||n===`ctrl`)r.mod=!0;else if(n===`shift`)r.shift=!0;else if(n===`alt`||n===`option`)r.alt=!0;else return Lm(`unknown modifier in`,e),null;return!r.mod||r.shift&&r.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Lm(`unsupported`,e),null):(n===`space`&&(r.key=` `),r)},zm=e=>`ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space`.split(` `).find(t=>t.toLowerCase()===e)??(e===` `?`Space`:e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),Bm=(e,t)=>{let n=Rm(e);if(!n)return``;let r=Im(),i=zm(n.key);if(!t&&r)return`${n.alt?`⌥`:``}${n.shift?`⇧`:``}⌘${i}`;let a=[t?r?`Meta`:`Control`:`Ctrl`];return n.alt&&a.push(`Alt`),n.shift&&a.push(`Shift`),a.push(i),a.join(`+`)},Vm=e=>Bm(e,!1),Hm=e=>Bm(e,!0),Um=(e,t)=>t.key?.toLowerCase()===e.key&&(Im()?t.metaKey:t.ctrlKey)===e.mod&&!(Im()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,Wm=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t===`INPUT`||t===`TEXTAREA`||t===`SELECT`||e.isContentEditable},Gm=e=>{let t=/* @__PURE__ */ new Map,n=e?.ownerDocument??(typeof document<`u`?document:null),r=(t,n)=>{if((t.scope??`widget`)===`page`)return!0;if(!e)return!1;let r=n.composedPath?.();return r?.length?r.includes(e):e.contains(n.target)},i=e=>{if(e.isComposing||!t.size)return;let n=e.composedPath?.()[0]??e.target;for(let i of t.values())if(Um(i.parsed,e)&&i.when?.()!==!1&&r(i,e)&&(i.allowInInput||!Wm(n))){e.preventDefault();try{i.run(e)}catch(e){Lm(`${i.id} threw on`,i.combo),console.warn(e)}return}};return n?.addEventListener(`keydown`,i),{register(e){let n=Rm(e.combo);if(!n)return()=>{};let r=`${n.mod?`m`:``}${n.shift?`s`:``}${n.alt?`a`:``}${n.key}`,i=t.get(r);return i?(Lm(`${i.id} already owns`,e.combo),()=>{}):(t.set(r,{...e,parsed:n}),e.element?.setAttribute(`aria-keyshortcuts`,Hm(e.combo)),()=>{t.get(r)?.id===e.id&&t.delete(r),e.element?.removeAttribute(`aria-keyshortcuts`)})},destroy(){t.clear(),n?.removeEventListener(`keydown`,i)}}},Km=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;zt.morph(e,t.innerHTML,{morphStyle:`innerHTML`,callbacks:{beforeNodeMorphed(e,t){if(e instanceof HTMLElement){if(t instanceof HTMLElement&&t.hasAttribute(`data-persona-reuse`)&&e.id===t.id)return!1;if(r){if(e.classList.contains(`persona-animate-typing`)||e.hasAttribute(`data-preserve-runtime`))return!1;if(e.hasAttribute(`data-tool-elapsed`))return t instanceof HTMLElement&&t.getAttribute(`data-tool-elapsed`)===e.getAttribute(`data-tool-elapsed`)?!1:void 0;if(e.hasAttribute(`data-preserve-animation`))return t instanceof HTMLElement&&(!t.hasAttribute(`data-preserve-animation`)||(e.dataset.personaLoadingLabel?e.dataset.personaLoadingAnimation!==t.dataset.personaLoadingAnimation:e.textContent!==t.textContent))&&void 0}}}}})},qm=e=>e.replace(/^\n+/,``).replace(/\s+$/,``),Jm={index:-1,draft:``};function Ym(e){let{direction:t,history:n,currentValue:r,atStart:i,state:a}=e,o=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t===`up`){if(!o&&!i)return{handled:!1,state:a};if(!o){let e=n.length-1;return{handled:!0,value:n[e],state:{index:e,draft:r}}}if(a.index>0){let e=a.index-1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,state:a}}if(!o)return{handled:!1,state:a};if(a.index<n.length-1){let e=a.index+1;return{handled:!0,value:n[e],state:{index:e,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}const Xm=/* @__PURE__ */ new WeakMap;function Zm(e){if(typeof e==`string`)return e.length;if(!e)return 0;if(typeof e!=`object`)return JSON.stringify(e)?.length??0;let t=Xm.get(e);return t===void 0&&(t=JSON.stringify(e)?.length??0,Xm.set(e,t)),t}function Qm(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.dispatchError?`1`:`0`,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)??``,Zm(e.toolCall?.args),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??``,e.toolCall?.actionTitle??``,t].join(`\0`)}function $m(){return/* @__PURE__ */ new Map}function eh(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function th(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function nh(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}const rh={type:`none`,placeholder:`none`,speed:120,duration:1800,buffer:`none`},ih=[`pre`,`code`,`a`,`script`,`style`],ah=e=>({type:e?.type??rh.type,placeholder:e?.placeholder??rh.placeholder,speed:e?.speed??rh.speed,duration:e?.duration??rh.duration,buffer:e?.buffer??rh.buffer}),oh=[{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`}],sh=/* @__PURE__ */ new Map;for(let e of oh)sh.set(e.name,e);const ch=[`wipe`,`glyph-cycle`],lh=e=>{sh.set(e.name,e)},uh=e=>{oh.some(t=>t.name===e)||sh.delete(e)},dh=()=>Array.from(sh.keys()),fh=(e,t)=>e===`none`?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:sh.get(e)??null,ph=(e,t,n,r,i)=>{if(!i)return e;if(n?.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t===`word`){let t=e.search(/\s(?=\S*$)/);return t<0?``:e.slice(0,t)}if(t===`line`){let t=e.lastIndexOf(`
23
23
  `);return t<0?``:e.slice(0,t)}return e},mh=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-char`,i.id=`stream-c-${n}-${r}`,i.style.setProperty(`--char-index`,String(r)),i.textContent=t,i},hh=(e,t,n,r)=>{let i=e.createElement(`span`);return i.className=`persona-stream-word`,i.id=`stream-w-${n}-${r}`,i.style.setProperty(`--word-index`,String(r)),i.textContent=t,i},gh=/\s/,_h=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let e=n;if(t.has(e.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},vh=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=0;for(;s<a.length;)if(gh.test(a[s])){let e=s;for(;e<a.length&&gh.test(a[e]);)e+=1;o.appendChild(r.createTextNode(a.slice(s,e))),s=e}else{let e=r.createElement(`span`);e.className=`persona-stream-word-group`;let i=s;for(;i<a.length&&!gh.test(a[i]);)e.appendChild(mh(r,a[i],t,n.value)),n.value+=1,i+=1;o.appendChild(e),s=i}i.replaceChild(o,e)},yh=(e,t,n)=>{let r=e.ownerDocument,i=e.parentNode;if(!r||!i)return;let a=e.nodeValue??``;if(!a)return;let o=r.createDocumentFragment(),s=a.split(/(\s+)/);for(let e of s)e&&(/^\s+$/.test(e)?o.appendChild(r.createTextNode(e)):(o.appendChild(hh(r,e,t,n.value)),n.value+=1));i.replaceChild(o,e)},bh=(e,t,n,r)=>{if(!e||typeof document>`u`)return e;let i=document.createElement(`div`);i.innerHTML=e;let a=new Set((r?.skipTags??ih).map(e=>e.toLowerCase())),o=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,null),s=[],c=o.nextNode();for(;c;)_h(c,a)||s.push(c),c=o.nextNode();let l={value:r?.startIndex??0},u=t===`char`?vh:yh;for(let e of s)u(e,n,l);return i.innerHTML},xh=(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},Sh=(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},Ch=/* @__PURE__ */ new WeakMap,wh=(e,t)=>{if(!e.styles)return;let n=Ch.get(t);if(n||(n=/* @__PURE__ */ new Set,Ch.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,`\\$&`);if(t.querySelector(`style[data-persona-animation="${r}"]`))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)},Th=/* @__PURE__ */ new WeakMap,Eh=(e,t)=>{if(!e.onAttach)return;let n=Th.get(t);if(n||(n=/* @__PURE__ */ new Map,Th.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Dh=e=>{let t=Th.get(e);if(t){for(let e of t.values())typeof e==`function`&&e();t.clear()}},Oh=(e,t)=>{wh(e,t),Eh(e,t)};H();const{setLoader:kh,load:Ah}=V({fallbackImport:()=>import(`@runtypelabs/persona/animations-extra`)}),jh=Ah;da();function Mh(e,t=la){let n=e.style.position,r=e.style.zIndex,i=e.style.isolation,a=getComputedStyle(e),o=a.position===`static`||a.position===``;return o&&(e.style.position=`relative`),e.style.zIndex=String(t),e.style.isolation=`isolate`,()=>{o&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=i}}let Nh=0,Ph=null;function Fh(e=document){if(Nh++,Nh===1){let t=e.body,n=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ph={originalOverflow:t.style.overflow,originalPosition:t.style.position,originalTop:t.style.top,originalWidth:t.style.width,scrollY:n},t.style.overflow=`hidden`,t.style.position=`fixed`,t.style.top=`-${n}px`,t.style.width=`100%`}let t=!1;return()=>{if(!t&&(t=!0,Nh=Math.max(0,Nh-1),Nh===0&&Ph)){let t=e.body,n=e.defaultView??window;t.style.overflow=Ph.originalOverflow,t.style.position=Ph.originalPosition,t.style.top=Ph.originalTop,t.style.width=Ph.originalWidth,n.scrollTo(0,Ph.scrollY),Ph=null}}}ds();const Ih={side:`right`,width:`420px`,animate:!0,reveal:`resize`,maxHeight:`100dvh`},Lh=e=>(e?.launcher?.mountMode??`floating`)===`docked`,Rh=e=>(e?.launcher?.mountMode??`floating`)===`composer-bar`,zh=e=>{let t=e?.launcher?.dock,n=as(e).dockWidth?t?.width:Yp(Tm(e),`components.panel.width`);return{side:t?.side??Ih.side,width:n??Ih.width,animate:t?.animate??Ih.animate,reveal:t?.reveal??Ih.reveal,maxHeight:t?.maxHeight??Ih.maxHeight}};X(),Pn(),_n(),Wr();const Bh=e=>e.closest(`[data-persona-instance]`)?.dataset.personaInstance,Vh=e=>e===`followUp`?`follow-up`:e,Hh=(e,t=0)=>{if(typeof e==`string`){let t=e.trim();return t?{id:t,label:t,prompt:t,emphasis:`default`}:null}let n=e.label.trim();if(!n)return null;let r=e.prompt?.trim()||n;return{id:e.id?.trim()||r||`suggestion-${t}`,label:n,prompt:r,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??`default`}},Uh=/* @__PURE__ */ new WeakSet,Wh=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,Gh=e=>{Wh()||e.forEach((e,t)=>{typeof e.animate==`function`&&e.animate([{opacity:`0`,transform:`translateY(4px)`},{opacity:`1`,transform:`none`}],{duration:250,delay:t*60,easing:`ease-out`,fill:`backwards`})})},Kh=e=>{let{item:t,index:n,surface:r,source:i,variant:a,streaming:o,config:c,plugins:l,chipsConfig:u,session:d,getTextarea:f,eventTarget:p,submitPrompt:m}=e,h=r===`followUp`,g=t.behavior,_=()=>{if(d.isStreaming()||p.closest(`[inert]`))return;let e={instanceId:Bh(p),suggestion:{...t},surface:r,source:i,behavior:g},n=p.dispatchEvent(new CustomEvent(`persona:suggestion:selected`,{detail:e,bubbles:!0,composed:!0,cancelable:!0}));if(h&&p.dispatchEvent(new CustomEvent(`persona:suggestReplies:selected`,{detail:{instanceId:Bh(p),suggestion:t.prompt},bubbles:!0,composed:!0})),!n)return;for(let e of l)if(e.onSuggestionSelect?.({suggestion:{...t},surface:r,source:i,variant:a,config:c})===!1)return;let o=f();g===`fill`?(o.value=t.prompt,o.dispatchEvent(new Event(`input`,{bubbles:!0,composed:!0})),o.focus()):m?m(t.prompt):(o.value=``,d.sendMessage(t.prompt))},v=()=>{let e=J(`button`,`persona-suggestion persona-suggestion--${a}`);if(e.type=`button`,e.disabled=o,e.dataset.suggestionId=t.id,e.dataset.emphasis=t.emphasis,e.dataset.behavior=g,a===`chip`){let t=c.suggestionChipsConfig===u?c:{suggestionChipsConfig:u},n=e=>Vr(t,`suggestionChipsConfig.${e}`),r=e=>Ur(c,`suggestion.chip.${e}`,`light`)||Ur(c,`suggestion.chip.${e}`,`dark`);u?.fontWeight&&(e.style.fontWeight=!n(`fontWeight`)&&r(`fontWeight`)?`var(--persona-suggestion-compat-weight, 500)`:u.fontWeight);let i=r(`padding`);i&&(e.classList.add(`persona-theme-padding`),e.style.setProperty(`--persona-theme-padding`,`var(--persona-suggestion-compat-padding, 6px 12px)`)),u?.paddingX&&(n(`paddingX`)||!i)&&(e.style.paddingLeft=u.paddingX,e.style.paddingRight=u.paddingX),u?.paddingY&&(n(`paddingY`)||!i)&&(e.style.paddingTop=u.paddingY,e.style.paddingBottom=u.paddingY)}if(t.icon){let n=G(t.icon,`var(--persona-suggestion-icon-size)`,`currentColor`,1.8);n&&(n.classList.add(`persona-suggestion__icon`),t.iconColor&&(n.style.color=t.iconColor),e.appendChild(n))}let n=J(`span`,`persona-suggestion__copy`);if(n.appendChild(Y(`span`,{className:`persona-suggestion__label`,text:t.label})),t.description&&a!==`chip`&&n.appendChild(Y(`span`,{className:`persona-suggestion__description`,text:t.description})),e.appendChild(n),a!==`chip`){let t=gn(s,16,`currentColor`,1.8);t&&(t.classList.add(`persona-suggestion__arrow`),e.appendChild(t))}return e.addEventListener(`click`,_),e},y=null;for(let e of l)if(e.renderSuggestion&&(y=e.renderSuggestion({suggestion:{...t},index:n,surface:r,source:i,variant:a,streaming:o,config:c,defaultRenderer:v,select:_}),y))break;return y??=v(),y.dataset.suggestionId||=t.id,y.dataset.behavior||=g,y.dataset.emphasis||=t.emphasis,y instanceof HTMLButtonElement||y.setAttribute(`aria-disabled`,o?`true`:`false`),y},qh=e=>{let t=[],n=[],r=null,i=null,a=()=>{e.removeAttribute(`data-scroll-left`),e.removeAttribute(`data-scroll-right`)},o=()=>{if(i=null,e.toggleAttribute(`data-edge-to-edge`,e.hasAttribute(`data-hide-scrollbar`)&&(e.hasAttribute(`data-persona-composer-suggestions`)||e.dataset.personaSuggestions===`follow-up`)&&e.dataset.variant===`chip`&&e.dataset.overflow===`scroll`),e.hasAttribute(`data-edge-to-edge`)&&e.parentElement){let t=e.parentElement,n=getComputedStyle(t),r=parseFloat(n.paddingLeft)||0,i=parseFloat(n.paddingRight)||0;e.style.setProperty(`--persona-suggestion-bleed-left`,`${r}px`),e.style.setProperty(`--persona-suggestion-bleed-right`,`${i}px`);let a=t.closest(`.persona-widget-container`)?.querySelector(`form`),o=t.getBoundingClientRect(),s=a?.getBoundingClientRect();e.style.setProperty(`--persona-suggestion-inset-left`,`${s?.width?s.left-o.left:r}px`),e.style.setProperty(`--persona-suggestion-inset-right`,`${s?.width?o.right-s.right:i}px`)}if(e.hidden||e.dataset.variant!==`chip`||e.dataset.overflow!==`scroll`){a();return}let t=Math.max(0,e.scrollWidth-e.clientWidth);if(t<=1){a();return}let n=getComputedStyle(e).direction===`rtl`,r=Math.min(t,Math.max(0,Math.abs(e.scrollLeft))),o=r<=4,s=r>=t-4,c=n?!s:!o,l=n?!o:!s;e.toggleAttribute(`data-scroll-left`,c),e.toggleAttribute(`data-scroll-right`,l)},s=()=>{i!==null||typeof requestAnimationFrame!=`function`?typeof requestAnimationFrame!=`function`&&o():i=requestAnimationFrame(o)};e.addEventListener(`scroll`,s,{passive:!0});let c=typeof ResizeObserver==`function`?new ResizeObserver(s):null;return c?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener(`scroll`,s),c?.disconnect(),i!==null&&typeof cancelAnimationFrame==`function`&&cancelAnimationFrame(i),i=null},render:(i,c,l,u,d,f)=>{e.replaceChildren(),t.length=0,n.length=0;let p=f?.source??`config`,m=f?.surface??(p===`config`?`starter`:`followUp`),h=m===`followUp`,g=f?.variant??`chip`,_=f?.behavior??`send`,v=f?.overflow??`wrap`,y=f?.config??{},b=f?.plugins??[];e.toggleAttribute(`data-hide-scrollbar`,y.future?.v5Defaults===!0),e.dataset.edgeStyle=y.suggestions?.[h?`followUps`:`starters`]?.edgeStyle??`fade`;let x=typeof f?.maxItems==`number`?Math.max(0,Math.floor(f.maxItems)):void 0,S=h?`followUps`:`starters`;!Uh.has(y)&&y.debug===!0&&g!==`chip`&&y.suggestions?.[S]?.overflow!==void 0&&(Uh.add(y),console.info(`[persona] suggestions.${S}.overflow applies to the "chip" variant only; the "${g}" variant manages its own stacking.`));let C=e=>e.map(Hh).filter(e=>e!==null).map(e=>({...e,behavior:e.behavior??_})),ee=C(i??[]);b.forEach(e=>{e.transformSuggestions&&(ee=C(e.transformSuggestions({suggestions:ee.map(e=>({...e})),surface:m,source:p,config:y})))});let w=x===void 0?ee:ee.slice(0,x);if(!w.length){e.hidden=!0,r=null,a();return}if(!h&&(u??c.getMessages()).some(e=>e.role===`user`)){e.hidden=!0,r=null;return}e.hidden=!1,e.classList.add(`persona-suggestions`),e.dataset.personaSuggestionSurface=Vh(m),e.dataset.variant=g,e.dataset.overflow=v;let T=document.createDocumentFragment(),E=c.isStreaming();w.forEach((r,i)=>{let a=Kh({item:r,index:i,surface:m,source:p,variant:g,streaming:E,config:y,plugins:b,chipsConfig:d,session:c,getTextarea:()=>l,eventTarget:e,submitPrompt:f?.submitPrompt});T.appendChild(a),n.push(a),[...a instanceof HTMLButtonElement?[a]:[],...Array.from(a.querySelectorAll(`button`))].forEach(e=>{t.includes(e)||(e.disabled=E,t.push(e))})}),e.appendChild(T),o(),s();let te=JSON.stringify({normalized:w,surface:m,variant:g,source:p});te!==r&&(r=te,Gh(n),e.dispatchEvent(new CustomEvent(`persona:suggestion:shown`,{detail:{instanceId:Bh(e),suggestions:w.map(e=>({...e})),surface:m,source:p,variant:g},bubbles:!0,composed:!0})),h&&e.dispatchEvent(new CustomEvent(`persona:suggestReplies:shown`,{detail:{instanceId:Bh(e),suggestions:w.map(e=>e.prompt)},bubbles:!0,composed:!0})))}}},Jh={"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`};X(),Pn(),Ro(),Uo();const Yh={x:[1.4,1.05]},Xh=`persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center`,Zh=(e,t,n={})=>{let{iconSize:r,iconText:i}=n,[a,o]=Yh[t]??[1,1.5],s=!r;e.classList.toggle(`persona-header-control--glyph`,s),e.classList.toggle(`persona-header-control--sparse`,s&&a!==1);let c=G(t,`${Math.round((parseFloat(r??``)||16)*a)}px`,`currentColor`,o);c?(c.style.display=`block`,s||(c.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((o/1.5).toFixed(4))})`),e.replaceChildren(c)):i&&(e.textContent=i)},Qh=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:r,iconName:i,iconText:a,wrapperClassName:o=Xh,size:s,iconSize:c,color:l,backgroundColor:u,borderWidth:d,borderColor:f,borderRadius:p,paddingX:m,paddingY:h,hidden:g,extraClassName:_,attrs:v}=e,y=J(`div`,o),b=!!(d||f),x=Y(`button`,{className:Gr(`persona-header-control`,`persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer`,!u&&`persona-bg-transparent hover:persona-bg-gray-100`,!b&&`persona-border-none`,!p&&`persona-rounded-full`,_),attrs:{type:`button`,"aria-label":t,...v},style:{width:s,height:s,minWidth:s,minHeight:s,display:g?`none`:void 0,color:l||ng.actionIconColor,backgroundColor:u,border:b?`${d||`0px`} solid ${f||`transparent`}`:void 0,borderRadius:p,paddingLeft:m,paddingRight:m,paddingTop:h,paddingBottom:h}});return i?Zh(x,i,{iconSize:c,iconText:a}):a&&(x.textContent=a),y.appendChild(x),So({anchor:x,trigger:y,text:()=>x.getAttribute(`aria-label`)??t,hint:r,enabled:n}),{button:x,wrapper:y}},$h=(e,t,n,r={})=>{let i=t?.launcher,a=i?.clearChat,o=e=>n===`close`?`launcher.closeButton${e[0].toUpperCase()}${e.slice(1)}`:`launcher.clearChat.${e===`color`?`iconColor`:e}`,s=e=>Bo(t,o(e)),c=(e,r)=>zo(t,`header.${n}`,e,r),l=(e,t,n)=>s(e)||c(t,n),u=r.buttonSize||s(`size`);Ho(e,u||c(`size`,`var(--persona-header-control-size, 32px)`),u),!u&&c(`size`,``)===``&&(e.style.width=e.style.height=``);let d=n===`close`?i?.closeButtonBackgroundColor:a?.backgroundColor;e.style.color=l(`color`,`foreground`,ng.actionIconColor),e.style.backgroundColor=s(`backgroundColor`)||(c(`background`,``)?c(`background`,d||`transparent`):d||``),e.classList.toggle(`hover:persona-bg-gray-100`,!d&&!s(`backgroundColor`)&&c(`background`,``)===``);let f=n===`close`?i?.closeButtonBorderWidth:a?.borderWidth,p=n===`close`?i?.closeButtonBorderColor:a?.borderColor,m=!!(f||p||c(`borderWidth`,``)||c(`borderColor`,``));e.style.border=m?`${l(`borderWidth`,`borderWidth`,f||`0px`)} solid ${l(`borderColor`,`borderColor`,p||`transparent`)}`:``,e.classList.toggle(`persona-border-none`,!m);let h=n===`close`?i?.closeButtonBorderRadius:a?.borderRadius;e.style.borderRadius=s(`borderRadius`)||(c(`borderRadius`,``)?c(`borderRadius`,`var(--persona-components-header-controlBorderRadius, 9999px)`):h||``),e.classList.toggle(`persona-rounded-full`,!e.style.borderRadius);let g=n===`close`?i?.closeButtonPaddingX:a?.paddingX,_=n===`close`?i?.closeButtonPaddingY:a?.paddingY,v=c(`padding`,`0px`);Vo(e,v,s(`paddingX`)||(v===`0px`?g:void 0),s(`paddingY`)||(v===`0px`?_:void 0));let y=n===`close`?i?.closeButtonIconName??`x`:a?.iconName??`refresh-cw`;Zh(e,y,{iconSize:r.iconSize,iconText:n===`close`?i?.closeButtonIconText??`×`:void 0});let b=e.querySelector(`svg`);if(b){let e=Yh[y]?.[0]??1,t=c(`iconSize`,``);!r.iconSize&&t&&(b.style.width=b.style.height=`calc(${c(`iconSize`,`var(--persona-header-control-icon-size, 16px)`)} * ${e})`),c(`iconStrokeWidth`,``)&&(b.style.strokeWidth=`calc(${c(`iconStrokeWidth`,`var(--persona-components-header-controlStrokeWidth, 1.5)`)} * ${e===1?1:.7})`)}},eg=(e,t={})=>{let{showClose:n=!0,wrapperClassName:r=Xh,buttonSize:i,iconSize:a}=t,o=e?.launcher??{},s=o.closeButtonTooltipText??`Close chat`,c=o.closeButtonShowTooltip??!0,{button:l,wrapper:u}=Qh({ariaLabel:s,tooltip:c,iconName:o.closeButtonIconName??`x`,iconText:o.closeButtonIconText??`×`,wrapperClassName:r,size:i??o.closeButtonSize,iconSize:a,color:o.closeButtonColor,backgroundColor:o.closeButtonBackgroundColor,borderWidth:o.closeButtonBorderWidth,borderColor:o.closeButtonBorderColor,borderRadius:o.closeButtonBorderRadius,paddingX:o.closeButtonPaddingX,paddingY:o.closeButtonPaddingY,hidden:!n});return $h(l,e,`close`,{buttonSize:i,iconSize:a}),{button:l,wrapper:u}},tg=(e,t={})=>{let{wrapperClassName:n=`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`,buttonSize:r,iconSize:i}=t,a=(e?.launcher??{}).clearChat??{},o=a.tooltipText??`Clear chat`,s=a.showTooltip??!0,{button:c,wrapper:l}=Qh({ariaLabel:o,tooltip:s,iconName:a.iconName??`refresh-cw`,wrapperClassName:n,size:r??a.size,iconSize:i,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return $h(c,e,`clear`,{buttonSize:r,iconSize:i}),{button:c,wrapper:l}};X(),Pn(),Es();const ng={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)`},rg={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)`},ig={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)`},ag=e=>{let{config:t,showClose:n=!0}=e,r=Y(`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:ng.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)))`}}),i=t?.launcher??{},a=i.headerIconSize??`40px`,o=i.closeButtonPlacement??`inline`,s=i.headerIconHidden??!1,c=i.headerIconName,l=Y(`div`,{className:`persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl`,style:{height:a,width:a,boxSizing:`content-box`,padding:`var(--persona-components-header-iconPadding, 0px)`,flexShrink:`0`,backgroundColor:`var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))`,color:`var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))`}});if(!s){if(c){let e=parseFloat(a)||24,n=G(c,e*.6,`currentColor`,1);n?(n.style.width=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,n.style.height=`calc(${e}px * var(--persona-components-header-iconScale, 0.6))`,l.replaceChildren(n)):l.textContent=t?.launcher?.agentIconText??`💬`}else if(t?.launcher?.iconUrl){let e=J(`img`);e.src=t.launcher.iconUrl,e.alt=``,e.className=`persona-rounded-xl persona-object-cover`,e.style.height=a,e.style.width=a,l.replaceChildren(e)}else l.textContent=t?.launcher?.agentIconText??`💬`}let u=J(`div`,`persona-flex persona-flex-col persona-flex-1 persona-min-w-0`),d=Y(`span`,{className:`persona-text-base persona-font-semibold`,text:t?.launcher?.title??`Chat Assistant`,style:{color:ng.titleColor,...rg}}),f=Y(`span`,{className:`persona-text-xs`,text:t?.launcher?.subtitle??`Here to help you get answers fast`,style:{color:ng.subtitleColor,...ig}});u.append(d,f),s?r.append(u):r.append(l,u);let p=i.clearChat??{},m=p.enabled??!0,h=p.placement??`inline`,g=null,_=null;if(m){let e=tg(t,{wrapperClassName:h===`top-right`?`persona-absolute persona-top-4 persona-z-50`:`persona-relative persona-ml-auto persona-clear-chat-button-wrapper`});g=e.button,_=e.wrapper,h===`top-right`&&(_.style.right=`48px`),h===`inline`&&r.appendChild(_)}let{button:v,wrapper:y}=eg(t,{showClose:n,wrapperClassName:o===`top-right`?`persona-absolute persona-top-4 persona-right-4 persona-z-50`:m&&h===`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`});return o!==`top-right`&&r.appendChild(y),{header:r,iconHolder:l,headerTitle:d,headerSubtitle:f,closeButton:v,closeButtonWrapper:y,clearChatButton:g,clearChatButtonWrapper:_}},og=(e,t,n)=>{let r=n?.launcher??{},i=r.closeButtonPlacement??`inline`,a=r.clearChat?.placement??`inline`;e.appendChild(t.header),i===`top-right`&&(e.style.position=`relative`,e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a===`top-right`&&(e.style.position=`relative`,e.appendChild(t.clearChatButtonWrapper))};X();const sg=e=>{let t=ag({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let e=t.headerTitle.parentElement;e&&(e.style.cursor=`pointer`,e.setAttribute(`role`,`button`),e.setAttribute(`tabindex`,`0`),e.addEventListener(`click`,()=>n()),e.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n())}))}return t};function cg(e,t,n){if(t?.length)for(let r of t){let{button:t,wrapper:i}=Qh({ariaLabel:r.ariaLabel??r.label??r.id,iconName:r.icon,iconText:r.icon?void 0:r.label,tooltipHint:r.shortcut?Vm(r.shortcut):void 0,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`});if(t.setAttribute(`data-persona-header-action`,r.id),r.shortcut){let e=Hm(r.shortcut);e&&t.setAttribute(`aria-keyshortcuts`,e)}if(r.menuItems?.length){let e=Gl({items:r.menuItems,onSelect:e=>n?.(e),anchor:i,position:`bottom-right`});i.appendChild(e.element),t.addEventListener(`click`,t=>{t.stopPropagation(),e.toggle()})}else t.addEventListener(`click`,()=>n?.(r.id));e.appendChild(i)}}const lg=e=>{let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:i,onHeaderAction:a}=e,o=t?.launcher??{},s=J(`div`,`persona-flex persona-items-center persona-justify-between`);s.setAttribute(`data-persona-theme-zone`,`header`),s.style.minHeight=ng.minHeight,s.style.padding=`var(--persona-components-header-minimalPadding, var(--persona-components-header-padding, 16px 24px))`,s.style.backgroundColor=`var(--persona-header-bg, var(--persona-surface, #ffffff))`,s.style.borderBottomColor=`var(--persona-header-border, var(--persona-divider, #f1f5f9))`,s.style.boxShadow=`var(--persona-header-shadow, none)`,s.style.borderBottom=`var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))`;let c=i?.titleMenu,l,u;if(c){let e=Xl({label:o.title??`Chat Assistant`,menuItems:c.menuItems,onSelect:t=>{let n=n=>{n===!1&&e.element.dispatchEvent(new CustomEvent(`persona:title-menu-builtin`,{bubbles:!0,composed:!0,detail:{actionId:t,instanceId:e.element.closest(`[data-persona-instance]`)?.dataset.personaInstance}}))},r=c.onSelect(t);r instanceof Promise?r.then(n,()=>{}):n(r)},hover:c.hover,className:``});l=e.element,l.style.color=ng.titleColor,u=l.querySelector(`.persona-combo-btn-label`)??l}else{if(l=J(`div`,`persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1`),u=J(`span`,`persona-text-base persona-font-semibold persona-truncate`),u.style.color=ng.titleColor,Object.assign(u.style,rg),u.textContent=o.title??`Chat Assistant`,l.appendChild(u),i?.onTitleClick){l.style.cursor=`pointer`,l.setAttribute(`role`,`button`),l.setAttribute(`tabindex`,`0`);let e=i.onTitleClick;l.addEventListener(`click`,t=>{t.target.closest(`button`)||e()}),l.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e())})}let e=i?.titleRowHover;e&&(l.style.borderRadius=e.borderRadius??`10px`,l.style.padding=e.padding??`6px 4px 6px 12px`,l.style.margin=`-6px 0 -6px -12px`,l.style.border=`1px solid transparent`,l.style.transition=`background-color 0.15s ease, border-color 0.15s ease`,l.style.width=`fit-content`,l.style.flex=`none`,l.addEventListener(`mouseenter`,()=>{l.style.backgroundColor=e.background??``,l.style.borderColor=e.border??``}),l.addEventListener(`mouseleave`,()=>{l.style.backgroundColor=``,l.style.borderColor=`transparent`}))}s.appendChild(l);let d=`persona-relative persona-inline-flex persona-items-center persona-justify-center`,{button:f,wrapper:p}=eg(t,{showClose:n,wrapperClassName:d});r&&f.addEventListener(`click`,r);let m=J(`div`,`persona-flex persona-items-center persona-gap-1`);c||cg(m,i?.trailingActions,i?.onAction??a);let h=o.clearChat??{},g=null,_=null;if(h.enabled??!0){let e=h.placement??`inline`,n=tg(t,{wrapperClassName:e===`top-right`?`persona-absolute persona-top-4 persona-z-50`:d});g=n.button,_=n.wrapper,e===`top-right`?_.style.right=`48px`:m.appendChild(_)}m.appendChild(p),s.appendChild(m);let v=J(`div`);v.style.display=`none`;let y=J(`span`);return y.style.display=`none`,{header:s,iconHolder:v,headerTitle:u,headerSubtitle:y,closeButton:f,closeButtonWrapper:p,clearChatButton:g,clearChatButtonWrapper:_}},ug={default:sg,minimal:lg},dg=e=>ug[e]??ug.default,fg=(e,t,n)=>{if(t?.render){let r=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=J(`div`);i.style.display=`none`;let a=J(`span`),o=J(`span`),s=J(`button`);s.style.display=`none`;let c=J(`div`);return c.style.display=`none`,{header:r,iconHolder:i,headerTitle:a,headerSubtitle:o,closeButton:s,closeButtonWrapper:c,clearChatButton:null,clearChatButtonWrapper:null}}let r=t?.layout??`default`,i=dg(r)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(i.iconHolder.style.display=`none`),t.showTitle===!1&&(i.headerTitle.style.display=`none`),t.showSubtitle===!1&&(i.headerSubtitle.style.display=`none`),t.showCloseButton===!1&&(i.closeButton.style.display=`none`),t.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display=`none`)),i};function pg(e,t){if(!t.defaultPrevented){for(let n of t.composedPath()){if(n===e)break;if(n instanceof Element&&n.matches(`button, input, textarea, select, a[href], label, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="combobox"], [tabindex]`))return}(e.querySelector(`[data-persona-composer-input][contenteditable="true"]`)??e.querySelector(`textarea[data-persona-composer-input]`))?.focus()}}X(),_c();const mg=e=>{let{config:t}=e,n=Y(`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`}}),r=gc(),i=Y(`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:a,attachAutoResize:o}=oc(t);o();let s=dc(t),c=pc(t),l=mc(t),u=hc(t),d=Y(`div`,{className:`persona-widget-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});i.append(d),l&&(d.append(l.previewsContainer),i.append(l.input)),i.append(a);let f=Y(`div`,{className:`persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full`,attrs:{"data-persona-composer-actions":``}}),p=Y(`div`,{className:`persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-start":``}}),m=Y(`div`,{className:`persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-2`,attrs:{"data-persona-composer-actions-end":``}});return l&&p.append(l.wrapper),c&&m.append(c.wrapper),m.append(s.wrapper),f.append(p,m),i.append(f),i.addEventListener(`click`,e=>{pg(i,e)}),t?.statusIndicator?.mode===`transient`?n.append(r,u,i):n.append(r,i,u),{footer:n,suggestions:r,composerForm:i,header:d,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:u,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:f,leftActions:p,rightActions:m,setSendButtonMode:s.setMode}};X(),_n(),_c(),nc();const hg=()=>{let e=Y(`button`,{className:`persona-pill-peek`,attrs:{type:`button`,"data-persona-pill-peek":``,"aria-label":`Show conversation`,tabindex:`-1`}}),t=J(`span`,`persona-pill-peek__icon`),n=gn(Ve,16,`currentColor`,1.5);n&&t.appendChild(n);let r=J(`span`,`persona-pill-peek__text`),i=J(`span`,`persona-pill-peek__caret`),a=gn(w,16,`currentColor`,1.5);return a&&i.appendChild(a),e.append(t,r,i),{root:e,textNode:r}},gg=e=>{let{config:t}=e,n=Y(`div`,{className:`persona-widget-footer persona-widget-footer--pill`,attrs:{"data-persona-theme-zone":`composer`}}),r=gc(),i=hc(t);i.style.display=`none`;let{textarea:a,attachAutoResize:o}=oc(t,{defaultMaxLines:5});o();let s=dc(t),c=pc(t),l=mc(t);l&&l.previewsContainer.classList.add(`persona-pill-composer__previews`);let u=Y(`form`,{className:`persona-widget-composer persona-pill-composer`,attrs:{"data-persona-composer-form":``}}),d=Y(`div`,{className:`persona-widget-composer__left-actions persona-pill-composer__left`,attrs:{"data-persona-composer-actions-start":``}});l&&d.append(l.wrapper);let f=Y(`div`,{className:`persona-widget-composer__right-actions persona-pill-composer__right`,attrs:{"data-persona-composer-actions-end":``}});c&&f.append(c.wrapper),f.append(s.wrapper),u.addEventListener(`click`,e=>{pg(u,e)}),l&&u.append(l.input),u.append(d,a,f);let p=Y(`div`,{className:`persona-pill-composer__header`,attrs:{"data-persona-composer-header":``},style:{display:`contents`}});n.append(p),l&&p.append(l.previewsContainer),n.append(r,u,i);let m=u;return{footer:n,suggestions:r,composerForm:u,header:p,textarea:a,sendButton:s.button,sendButtonWrapper:s.wrapper,micButton:c?.button??null,micButtonWrapper:c?.wrapper??null,statusText:i,attachmentButton:l?.button??null,attachmentButtonWrapper:l?.wrapper??null,attachmentInput:l?.input??null,attachmentPreviewsContainer:l?.previewsContainer??null,actionsRow:m,leftActions:d,rightActions:f,setSendButtonMode:s.setMode}};X(),kc(),Pn(),Gs();const _g=e=>{switch(e){case`max_tool_calls`:return`Tool limit reached.`;case`length`:return`Output token limit reached.`;case`content_filter`:return`The provider filtered this response.`;case`error`:return`Something went wrong generating this response.`;default:return null}},vg=(e,t)=>{if(!e)return null;let n=_g(e);if(n===null)return null;let r=t?.[e];return(r===void 0?n:r)||null},yg=(e,t)=>Y(`div`,{className:`persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic`,attrs:{"data-stop-reason":e,role:`note`},style:{opacity:`0.75`},text:t}),bg=e=>{let t=e.toLowerCase();return!t.startsWith(`data:image/svg+xml`)&&!!(/^(?:https?|blob):/i.test(e)||t.startsWith(`data:image/`)||!e.includes(`:`))},xg=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(`:`))},Sg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`image`&&typeof e.image==`string`&&e.image.trim().length>0),Cg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`audio`&&typeof e.audio==`string`&&e.audio.trim().length>0),wg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`video`&&typeof e.video==`string`&&e.video.trim().length>0),Tg=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(e=>e.type===`file`&&typeof e.data==`string`&&e.data.trim().length>0),Eg=e=>{if(!e||e.length===0)return null;let t=Y(`div`,{className:`persona-mention-context-row persona-message-mentions`,attrs:{"data-message-mentions":``}});t.style.display=`flex`;for(let n of e){let e=Y(`div`,{className:`persona-mention-chip persona-mention-chip-readonly`,attrs:{"data-status":`ready`,title:n.label}}),r=J(`span`,`persona-mention-chip-icon`),i=G(n.iconName??`at-sign`,13,`currentColor`,2);i&&r.appendChild(i),e.appendChild(r),e.appendChild(Y(`span`,{className:`persona-mention-chip-label`,text:n.label})),t.appendChild(e)}return t},Dg=(e,t)=>{let n=document.createDocumentFragment();for(let r of e)r.kind===`text`?n.appendChild(document.createTextNode(r.text)):n.appendChild(Oc(r.ref,{readonly:!0,render:t}));return n},Og=(e,t,n,r)=>{let i=Math.random().toString(36).slice(2,8),a=e=>`${i}:${e}`,o=n(t.map((e,t)=>e.kind===`text`?e.text:a(t)).join(``));if(!t.every((e,t)=>e.kind===`text`||o.includes(a(t)))){e.replaceChildren(Dg(t,r));return}e.innerHTML=o;let s=RegExp(`${i}:(\\d+)`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=[];for(let e=c.nextNode();e;e=c.nextNode())l.push(e);for(let e of l){let n=e;for(let e=s.exec(n.data);e;e=s.exec(n.data)){let i=t[Number(e[1])],a=n.splitText(e.index);a.data=a.data.slice(e[0].length),i?.kind===`mention`&&a.parentNode?.insertBefore(Oc(i.ref,{readonly:!0,render:r}),a),n=a}}},kg=(e,t,n)=>{if(e.length===0)return null;try{let r=J(`div`,`persona-flex persona-flex-col persona-gap-2`);r.setAttribute(`data-message-attachments`,`images`),t&&(r.style.marginBottom=`8px`);let i=0,a=!1,o=()=>{a||(a=!0,r.remove(),n?.())};return e.forEach((e,t)=>{let n=J(`img`);n.alt=e.alt?.trim()||`Attached image ${t+1}`,n.loading=`lazy`,n.decoding=`async`,n.referrerPolicy=`no-referrer`,n.style.display=`block`,n.style.width=`100%`,n.style.maxWidth=`320px`,n.style.maxHeight=`320px`,n.style.height=`auto`,n.style.objectFit=`contain`,n.style.borderRadius=`10px`,n.style.backgroundColor=`var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))`,n.style.border=`1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))`;let a=!1;i+=1,n.addEventListener(`error`,()=>{a||(a=!0,i=Math.max(0,i-1),n.remove(),i===0&&o())}),n.addEventListener(`load`,()=>{a=!0}),bg(e.image)?(n.src=e.image,r.appendChild(n)):(a=!0,i=Math.max(0,i-1),n.remove())}),i===0?(o(),null):r}catch{return n?.(),null}},Ag=e=>{if(e.length===0)return null;try{let t=J(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`audio`);let n=0;return e.forEach(e=>{if(!xg(e.audio))return;let r=J(`audio`);r.controls=!0,r.preload=`metadata`,r.src=e.audio,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jg=e=>{if(e.length===0)return null;try{let t=J(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`video`);let n=0;return e.forEach(e=>{if(!xg(e.video))return;let r=J(`video`);r.controls=!0,r.preload=`metadata`,r.src=e.video,r.style.display=`block`,r.style.width=`100%`,r.style.maxWidth=`320px`,r.style.maxHeight=`320px`,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}},Mg=e=>{if(e.length===0)return null;try{let t=J(`div`,`persona-flex persona-flex-col persona-gap-2`);t.setAttribute(`data-message-attachments`,`files`);let n=0;return e.forEach(e=>{if(!xg(e.data))return;let r=J(`a`);r.href=e.data,r.download=e.filename,r.target=`_blank`,r.rel=`noopener noreferrer`,r.textContent=e.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}},Ng=(e={})=>{let t=e.loadingIndicator,n=e.future?.v5Defaults;if((t?.variant??(n?`label`:`dots`))===`label`){let r=Y(`div`,{className:`persona-loading-label`,attrs:{role:`status`}});n&&t?.showBubble!==!0&&r.classList.add(`persona-activity-row`,`persona-activity-header`);let i=e.features?.toolCallDisplay,a=t?.iconVisibility??(i?.grouped!==!1&&(i?.groupedMode??`collapsible`)===`collapsible`?i?.groupIconVisibility:void 0)??i?.iconVisibility,o=t?.iconName??`loader-circle`;if(a!==`never`&&(n||t?.iconName||t?.iconVisibility)){let e=G(o,16);e&&(e.classList.add(`persona-activity-icon`),e.dataset.loadingIconAnimation=t?.iconAnimation??(o===`loader-circle`?`spin`:`none`),r.appendChild(e))}let s=Y(`span`,{text:t?.label??`Thinking…`});return r.appendChild(s),Rl()?.applyLoadingLabel(s,e,`waiting`),r}let r=J(`div`,`persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2`);for(let e=0;e<3;e++){let t=J(`div`,`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=`${e*250}ms`,r.appendChild(t)}let i=J(`span`,`persona-sr-only`);return i.textContent=`Loading`,r.appendChild(i),r},Pg=(e,t,n)=>t?.({config:n??{},streaming:!0,location:e,defaultRenderer:()=>Ng(n)})??Ng(n),Fg=(e,t)=>{let n=J(`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`),r=t===`user`?e.userAvatar:e.assistantAvatar;if(r){if(r.startsWith(`http`)||r.startsWith(`/`)||r.startsWith(`data:`)){let e=J(`img`);e.src=r,e.alt=t===`user`?`User`:`Assistant`,e.className=`persona-w-full persona-h-full persona-rounded-full persona-object-cover`,n.appendChild(e)}else n.textContent=r,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},Ig=(e,t,n=`div`)=>{let r=J(n,`persona-text-xs persona-text-persona-muted`),i=new Date(e.createdAt);return r.textContent=t.format?t.format(i):i.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`}),r},Lg=(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`)}return n},Rg={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`}},zg=(e,t,n=`bubble`,r)=>{if(!r)return;let i=t===`user`?`user`:`assistant`,a=Rg[n??`bubble`]??Rg.bubble;r.padding&&(e.style.padding=`var(--persona-message-${i}-padding, ${a.padding})`),r.fontSize&&(e.style.fontSize=`var(--persona-message-${i}-font-size, ${a.fontSize})`),r.lineHeight&&(e.style.lineHeight=`var(--persona-message-${i}-line-height, ${a.lineHeight})`),r.fontFamily&&(e.style.fontFamily=`var(--persona-message-${i}-font-family, inherit)`)},Bg=e=>`custom:${e}`,Vg=(e,t)=>t!==`user`&&t!==`assistant`?[]:(e?.custom??[]).filter(e=>(e.roles??[`assistant`]).includes(t)),Hg=(e,t,n,r,i=!1)=>{let a=t.showCopy??!0,o=t.showUpvote??!1,s=t.showDownvote??!1,c=t.showReadAloud??!1,l=(t.showRegenerate??!1)&&r?.canRegenerate===!0,u=(t.showEdit??!1)&&r?.canEdit===!0,d=(t.showQuote??!1)&&r?.canQuote!==!1,f=Vg(t,e.role);if(!a&&!o&&!s&&!c&&!l&&!u&&!d&&f.length===0){let t=J(`div`);return t.style.display=`none`,t.id=`actions-${e.id}`,t.setAttribute(`data-actions-for`,e.id),t}let p=t.visibility??(i&&r?.isLastAssistant?`always`:`hover`),m=t.align??`right`,h=t.layout??`pill-inside`,g={left:`persona-message-actions-left`,center:`persona-message-actions-center`,right:`persona-message-actions-right`}[m],_={"pill-inside":`persona-message-actions-pill`,"row-inside":`persona-message-actions-row`}[h],v=J(`div`,`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${_} ${p===`hover`?`persona-message-actions-hover`:``} ${i?`persona-message-actions-adaptive`:``}`);v.id=`actions-${e.id}`,v.setAttribute(`data-actions-for`,e.id);let y=(e,t,n)=>{let r=Kl({icon:e,label:t,size:14,className:`persona-message-action-btn`,chromeless:!0});return r.setAttribute(`data-action`,n),r};a&&v.appendChild(y(`copy`,`Copy message`,`copy`)),c&&v.appendChild(y(`volume-2`,`Read aloud`,`read-aloud`)),o&&v.appendChild(y(`thumbs-up`,`Upvote`,`upvote`)),s&&v.appendChild(y(`thumbs-down`,`Downvote`,`downvote`)),l&&v.appendChild(y(`refresh-cw`,`Regenerate response`,`regenerate`)),u&&v.appendChild(y(`pencil`,`Edit message`,`edit`)),d&&v.appendChild(y(`quote`,`Quote message`,`quote`));for(let e of f)v.appendChild(y(e.iconName??`ellipsis`,e.label,Bg(e.id)));return v},Ug=(e,t,n,r,i,a)=>{let o=n??{},s=o.layout??`bubble`,c=o.avatar,l=o.timestamp,u=c?.show??!1,d=l?.show??!1,f=c?.position??`left`,p=l?.position??`below`,m=Lg(e.role,s),h=J(`div`,m.join(` `));h.id=`bubble-${e.id}`,h.setAttribute(`data-message-id`,e.id),h.setAttribute(`data-persona-theme-zone`,e.role===`user`?`user-message`:`assistant-message`);let g=Jp(a?.widgetConfig?.future).components.message,_=a?.widgetConfig?.theme?.components?.message;zg(h,e.role,s,e.role===`user`?{...g.user,..._?.user,...a?.widgetConfig?.darkTheme?.components?.message?.user}:{...g.assistant,..._?.assistant,...a?.widgetConfig?.darkTheme?.components?.message?.assistant}),s===`flat`?(h.style.backgroundColor=`transparent`,h.style.color=e.role===`user`?`var(--persona-primary, var(--persona-text))`:`var(--persona-message-assistant-text, var(--persona-text))`):e.role===`user`?(h.style.backgroundColor=`var(--persona-message-user-bg, var(--persona-accent))`,h.style.color=`var(--persona-message-user-text, white)`):e.role===`assistant`&&(h.style.backgroundColor=`var(--persona-message-assistant-bg, var(--persona-container))`,h.style.color=`var(--persona-message-assistant-text, var(--persona-text))`);let v=Sg(e),y=e.content?.trim()??``,b=v.length>0&&y===`[Image]`,x=ah(a?.widgetConfig?.features?.streamAnimation),S=a?.widgetConfig?.features?.streamAnimation?.plugins,C=e.role===`assistant`&&x.type!==`none`?fh(x.type,S):null,ee=e.role===`assistant`&&C?.isAnimating?.(e)===!0,w=e.role===`assistant`&&C!==null&&(!!e.streaming||ee);w&&C?.bubbleClass&&h.classList.add(C.bubbleClass);let T=document.createElement(`div`);T.classList.add(`persona-message-content`),e.streaming&&T.classList.add(`persona-content-streaming`),w&&C&&(C.containerClass&&T.classList.add(C.containerClass),T.style.setProperty(`--persona-stream-step`,`${x.speed}ms`),T.style.setProperty(`--persona-stream-duration`,`${x.duration}ms`));let E=w?ph(e.content??``,x.buffer,C,e,!!e.streaming):e.content??``,te=()=>{let n=t({text:E,message:e,streaming:!!e.streaming,raw:e.rawContent});return w&&C?.wrap===`char`?bh(n,`char`,e.id,{skipTags:C.skipTags}):w&&C?.wrap===`word`?bh(n,`word`,e.id,{skipTags:C.skipTags}):n},D=null;if(b?(D=document.createElement(`div`),D.innerHTML=te(),D.style.display=`none`,T.appendChild(D)):e.contentSegments?.length?Og(T,e.contentSegments,n=>t({text:n,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):T.innerHTML=te(),w&&C?.useCaret&&!b&&y){let e=xh(),t=T.querySelectorAll(`.persona-stream-char, .persona-stream-word`),n=t[t.length-1];if(n?.parentNode)n.parentNode.insertBefore(e,n.nextSibling);else{let t=T.lastElementChild;t?t.appendChild(e):T.appendChild(e)}}if(d&&p===`inline`&&e.createdAt){let t=Ig(e,l,`span`);t.classList.add(`persona-timestamp-inline`);let n=T.lastElementChild;n?n.appendChild(t):T.appendChild(t)}if(v.length>0){let e=kg(v,!b&&!!y,()=>{b&&D&&(D.style.display=``)});e?h.appendChild(e):b&&D&&(D.style.display=``)}let ne=Cg(e);if(ne.length>0){let e=Ag(ne);e&&h.appendChild(e)}let re=wg(e);if(re.length>0){let e=jg(re);e&&h.appendChild(e)}let ie=Tg(e);if(ie.length>0){let e=Mg(ie);e&&h.appendChild(e)}let ae=e.contentSegments?.length?null:Eg(e.contextMentions);if(ae&&h.appendChild(ae),h.appendChild(T),d&&p===`below`&&e.createdAt){let t=Ig(e,l);t.classList.add(`persona-mt-1`),h.appendChild(t)}let oe=e.role===`assistant`?vg(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role===`assistant`){let e=!!(E&&E.trim()),t=x.placeholder===`skeleton`,n=t&&x.buffer===`line`&&e;if(e)n&&h.appendChild(Sh());else if(t)h.appendChild(Sh());else{let e=Pg(`inline`,a?.loadingIndicatorRenderer,a?.widgetConfig);e&&h.appendChild(e)}}oe&&e.stopReason&&!e.streaming&&(y||(T.style.display=`none`),h.appendChild(yg(e.stopReason,oe)));let O=e.role===`assistant`&&!e.streaming&&!e.voiceCaption&&e.content&&e.content.trim()&&r?.enabled!==!1,se=a?.actionEligibility,ce=e.role===`user`&&!e.streaming&&r?.enabled!==!1&&(r?.showEdit===!0&&se?.canEdit===!0||r?.showQuote===!0&&se?.canQuote===!0||Vg(r,`user`).length>0);if((O||ce)&&r){let t=Hg(e,ce?{...r,showCopy:!1,showUpvote:!1,showDownvote:!1,showReadAloud:!1}:r,i,se,a?.widgetConfig?.future?.v5Defaults===!0&&r.visibility===void 0);h.appendChild(t)}if(!u||e.role===`system`)return h;let k=J(`div`,`persona-message-with-avatar persona-flex persona-gap-2 ${e.role===`user`?`persona-flex-row-reverse`:``}`),le=Fg(c,e.role);return f===`right`||f===`left`&&e.role===`user`?k.append(h,le):k.append(le,h),k},Wg=(e,t,n,r,i,a)=>{let o=n??{};return e.role===`user`&&o.renderUserMessage?o.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role===`assistant`&&o.renderAssistantMessage?o.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ug(e,t,n,r,i,a)};X(),Pn();const Gg=(e,t)=>{if(e.replaceChildren(),!t)e.hidden=!0;else if(typeof t==`function`){let n=null;try{n=t()}catch(e){console.warn(`[persona] welcome.icon renderer threw`,e)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1}else{if(t.type===`lucide`){let n=G(t.name,40);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type===`image`?e.appendChild(Y(`img`,{className:`persona-welcome-icon-image`,attrs:{src:t.url,alt:t.alt}})):e.appendChild(Y(`span`,{className:`persona-welcome-icon-text`,text:t.text}));e.hidden=!1}},Kg=(e,t,n={})=>{let r=Y(`div`,{className:`persona-welcome-icon`,attrs:{"data-persona-welcome-icon":``}});r.hidden=!0;let i=J(`p`,`persona-welcome-kicker`);i.hidden=!0;let a=J(`h2`,`persona-welcome-title`),o=J(`p`,`persona-welcome-subtitle`),s=Y(`div`,{className:`persona-welcome-head-text`},i,a),c=Y(`div`,{className:`persona-welcome-title-row`},r,s);return{host:Y(`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,o,t),iconHolder:r,kicker:i,title:a,subtitle:o,starterSuggestions:t}},qg=(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)},Jg=(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===``,Gg(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`)},Yg=`data-persona-welcome-overlay`,Xg=`persona-welcome-overlay-active`,Zg=/* @__PURE__ */ new WeakMap,Qg=(e,t,n)=>{n.setAttribute(`data-persona-welcome-plugin`,``),t.appendChild(n),t.setAttribute(`data-persona-welcome-content`,`plugin`),t.setAttribute(Yg,``),e.classList.contains(Xg)||(Zg.set(e,e.scrollTop),e.classList.add(Xg),e.scrollTop=0)},$g=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute(`data-persona-welcome-content`),t.removeAttribute(Yg),e.classList.contains(Xg)&&(e.classList.remove(Xg),e.scrollTop=Zg.get(e)??e.scrollTop,Zg.delete(e))},e_=()=>{let e=Y(`div`,{className:`persona-welcome-greeting persona-flex persona-flex-col`,attrs:{"data-persona-welcome-greeting":``}});return e.hidden=!0,e},t_=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let r=n?.layout?.messages?.layout??`bubble`,i=Y(`div`,{className:Lg(`assistant`,r).join(` `),attrs:{"data-persona-theme-zone":`assistant-message`},text:t,style:r===`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(Y(`div`,{className:`persona-flex`},i)),e.hidden=!1},n_=()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,r_=(e,t)=>{if(n_()||typeof e.animate!=`function`||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),r=e.parentElement,i=0,a=0,o=0;if(r){let t=getComputedStyle(r);i=parseFloat(t.rowGap)||0;let s=e.previousElementSibling,c=e.nextElementSibling,l=r.getBoundingClientRect().top+(parseFloat(t.borderTopWidth)||0)+(parseFloat(t.paddingTop)||0)-r.scrollTop;a=Math.max(0,s?n.top-s.getBoundingClientRect().bottom-i:n.top-l),o=Math.max(0,c?c.getBoundingClientRect().top-n.bottom-i:0)}let s=e.style.overflow;e.style.overflow=`hidden`;let c=getComputedStyle(e),l=parseFloat(c.paddingTop)||0,u=parseFloat(c.paddingBottom)||0,d=e.animate([{opacity:`1`,transform:`none`,height:`${n.height}px`,minHeight:`0px`,paddingTop:`${l}px`,paddingBottom:`${u}px`,marginTop:`${a}px`,marginBottom:`${o}px`},{opacity:`0`,transform:`translateY(-4px)`,height:`0px`,minHeight:`0px`,paddingTop:`0px`,paddingBottom:`0px`,marginTop:`0px`,marginBottom:`${-i}px`}],{duration:180,easing:`ease-out`,fill:`forwards`}),f=!1,p=()=>{f||(f=!0,e.style.overflow=s,t(d))};return d.finished.then(p).catch(p),d},i_=(e,t,n,r=260)=>{if(t<=1||n_()||typeof e.animate!=`function`||!e.isConnected)return null;let i=n===`drop`?-t:t;return e.animate([{transform:`translateY(${i}px)`},{transform:`none`}],{duration:r,easing:`cubic-bezier(0.2, 0, 0, 1)`,fill:`none`})},a_=/* @__PURE__ */ new WeakSet,o_=(e,t)=>!!e&&e[t]!==void 0,s_=(e,t)=>{e&&e.debug===!0&&t.length&&!a_.has(e)&&(a_.add(e),t.forEach(e=>console.warn(`[persona] ${e}`)))},c_=(e,t=e?.launcher?.fullHeight===!0&&!e.launcher.sidebarMode&&e.launcher.mountMode!==`docked`)=>{let n=e?.welcome,r=e?.copy,i=e?.future?.v5Defaults===!0,a=n?.layout??(i?`centered`:`top`),o=o_(n,`variant`)?n.variant:r?.showWelcomeCard===!1?`none`:`card`,s=o===`hero`&&!i&&n?.layout===void 0?`on-first-message`:o_(n,`dismiss`)?n.dismiss:i||o===`hero`?`on-first-message`:`never`,c=[];for(let[e,t]of[[`title`,`welcomeTitle`],[`subtitle`,`welcomeSubtitle`],[`variant`,`showWelcomeCard`]])o_(n,e)&&o_(r,t)&&c.push(`welcome.${e} and copy.${t} are both set; welcome.${e} wins. copy.${t} is deprecated.`);o===`hero`&&o_(n,`message`)&&c.push(`welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.`),!i&&n?.layout===void 0&&o===`hero`&&o_(n,`dismiss`)&&n.dismiss!==`on-first-message`&&c.push(`welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".`);let l=n?.anchor??(o!==`none`&&a===`centered`&&t?`center`:`bottom`),u=Pm(n?.anchorComposerTop)!==null;return o_(n,`anchorComposerTop`)&&!u&&c.push(`welcome.anchorComposerTop must be a percentage between 0% and 100%; falling back to "44%".`),l!==`center`&&(o_(n,`anchorComposerTop`)||o_(n,`composerGap`))&&c.push(`welcome.anchorComposerTop is ignored unless welcome.anchor is "center".`),s_(e,c),{title:o_(n,`title`)?n.title:r?.welcomeTitle??(i?`What can I help with?`:`Hello 👋`),kicker:n?.kicker??``,subtitle:o_(n,`subtitle`)?n.subtitle:r?.welcomeSubtitle??(i?``:`I can answer questions and help you get things done here.`),icon:n?.icon,align:n?.align===`start`||n?.align===`center`?n.align:a===`centered`?`center`:void 0,iconPlacement:n?.icon&&typeof n.icon!=`function`&&n.icon.placement===`inline`?`inline`:`above`,variant:o,dismiss:s,message:o===`hero`?void 0:n?.message,layout:a,anchor:l,anchorComposerTop:u?n.anchorComposerTop:`44%`,composerGap:n?.composerGap?.trim()||`24px`}},l_=(e=[])=>e.some(e=>e.role===`user`||e.role===`assistant`&&(e.content.trim()||e.contentParts?.some(e=>e.type!==`text`||e.text.trim())||e.toolCall||e.tools?.length||e.reasoning||e.approval)),u_=e=>l_(e)?`active`:`empty`,d_=(e,t)=>e.variant!==`none`&&(e.dismiss===`never`||!l_(t));X(),da(),ds();const f_=`var(--persona-components-panel-height)`,p_=e=>{let t=as(e),n=t.launcherWidth?e?.launcher?.width:t.legacyLauncherWidth?e?.launcherWidth:void 0,r=e?.launcher?.heightOffset??0,i=r===0?`max(200px, ${f_})`:`max(200px, calc(${f_} - ${r}px))`;return{width:n??`var(--persona-components-panel-width)`,maxWidth:n??`var(--persona-components-panel-maxWidth)`,height:i,maxHeight:`var(--persona-components-panel-maxHeight)`}},m_=e=>{let t=as(e);return t.launcherWidth||t.legacyLauncherWidth||e?.theme?.components?.panel?.width!==void 0?p_(e).width:`100%`},h_=`16px`,g_=`10px`,__=`14px`,v_=e=>{let t=e?.launcher?.enabled??!0,n=Lh(e);if(Rh(e)){let t=e?.launcher?.composerBar??{},n=J(`div`,`persona-widget-wrapper persona-fixed persona-transition`);n.setAttribute(`data-persona-composer-bar`,``),n.dataset.state=`collapsed`,n.dataset.expandedSize=t.expandedSize??`anchored`,n.style.zIndex=String(e?.launcher?.zIndex??1e5);let r=J(`div`,`persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);r.style.width=`100%`,n.appendChild(r);let i=J(`div`,`persona-widget-pill-root`);return i.setAttribute(`data-persona-composer-bar`,``),i.dataset.state=`collapsed`,i.dataset.expandedSize=t.expandedSize??`anchored`,i.style.zIndex=String(e?.launcher?.zIndex??1e5),{wrapper:n,panel:r,pillRoot:i}}if(n){let e=J(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`),t=J(`div`,`persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col`);return e.appendChild(t),{wrapper:e,panel:t}}if(!t){let t=J(`div`,`persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0`),n=J(`div`,`persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0`);return t.style.width=m_(e),n.style.width=`100%`,t.appendChild(n),{wrapper:t,panel:n}}let r=e?.launcher??{},i=r.position&&Jh[r.position]?Jh[r.position]:Jh[`bottom-right`],a=J(`div`,`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??1e5);let o=J(`div`,`persona-widget-panel persona-relative persona-min-h-[320px]`),s=p_(e);return o.style.width=s.width,o.style.maxWidth=s.maxWidth,a.appendChild(o),{wrapper:a,panel:o}},y_=e=>{let t=Y(`div`,{className:`persona-suggestions`,attrs:{"data-persona-suggestions":Vh(e)}});return t.hidden=!0,t},b_=(e,t)=>{let n=y_(`starter`),r=Kg(e,n,{flatShadow:Lh(e)}),i=c_(e);Jg(r,i),qg(t,r.host,d_(i,e?.initialMessages));let a=e_();return t_(a,i.message,e),{welcome:r,greetingHost:a}},x_=(e,t)=>{let n=J(`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:r,wrapper:i}=eg(e,{showClose:t,wrapperClassName:`persona-composer-bar-close`,buttonSize:h_,iconSize:g_});i.style.position=`absolute`,i.style.top=`8px`,i.style.right=`8px`,i.style.zIndex=`10`;let a=e?.launcher?.clearChat?.enabled??!0,o=null,s=null;if(a){let t=tg(e,{wrapperClassName:`persona-composer-bar-clear-chat`,buttonSize:h_,iconSize:__});o=t.button,s=t.wrapper,s.style.position=`absolute`,s.style.top=`8px`,s.style.right=`32px`,s.style.zIndex=`10`}let c=Y(`span`,{className:`persona-widget-header`,attrs:{"data-persona-theme-zone":`header`},style:{display:`none`}}),l=Y(`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`}});l.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:u,greetingHost:d}=b_(e,l),{host:f,title:p,subtitle:m}=u,h=u.starterSuggestions,g=J(`div`,`persona-widget-messages persona-flex persona-flex-col`);g.style.gap=`var(--persona-components-message-gap, 12px)`;let _=y_(`followUp`),v=Mm(e,!0);v&&(g.style.maxWidth=v,g.style.marginLeft=`auto`,g.style.marginRight=`auto`,g.style.width=`100%`),l.append(f,d,g,_);let y=Y(`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`}}),b=gg({config:e}),{root:x,textNode:S}=hg();return n.append(c,i,l,y),s&&n.appendChild(s),{container:n,body:l,messagesWrapper:g,starterSuggestions:h,transcriptSuggestions:_,composerOverlay:y,suggestions:b.suggestions,textarea:b.textarea,sendButton:b.sendButton,sendButtonWrapper:b.sendButtonWrapper,micButton:b.micButton,micButtonWrapper:b.micButtonWrapper,composerForm:b.composerForm,statusText:b.statusText,welcomeHost:f,welcomeIconHolder:u.iconHolder,greetingHost:d,introKicker:u.kicker,introTitle:p,introSubtitle:m,closeButton:r,closeButtonWrapper:i,clearChatButton:o,clearChatButtonWrapper:s,iconHolder:J(`span`),headerTitle:J(`span`),headerSubtitle:J(`span`),header:c,footer:b.footer,attachmentButton:b.attachmentButton,attachmentButtonWrapper:b.attachmentButtonWrapper,attachmentInput:b.attachmentInput,attachmentPreviewsContainer:b.attachmentPreviewsContainer,actionsRow:b.actionsRow,leftActions:b.leftActions,rightActions:b.rightActions,setSendButtonMode:b.setSendButtonMode,peekBanner:x,peekTextNode:S}},S_=(e,t=!0)=>{if(Rh(e))return x_(e,t);let n=Y(`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`}}),r=e?.layout?.header,i=us(e),a=r?fg(e,r,{showClose:t}):ag({config:e,showClose:t}),o=Y(`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`}});o.style.setProperty(`scrollbar-gutter`,`stable`);let{welcome:s,greetingHost:c}=b_(e,o),{host:l,title:u,subtitle:d}=s,f=s.starterSuggestions,p=J(`div`,`persona-widget-messages persona-flex persona-flex-col`);p.style.gap=`var(--persona-components-message-gap, 12px)`;let m=y_(`followUp`),h=Mm(e,!1);h&&(p.style.maxWidth=h,p.style.marginLeft=`auto`,p.style.marginRight=`auto`,p.style.width=`100%`),o.append(l,c,p,m);let g=mg({config:e}),_=e?.layout?.showFooter!==!1;i||(a.header.style.display=`none`),og(n,a,e),n.append(o);let v=Y(`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 _||(g.footer.style.display=`none`),n.append(g.footer),n.append(v),{container:n,body:o,messagesWrapper:p,starterSuggestions:f,transcriptSuggestions:m,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,welcomeHost:l,welcomeIconHolder:s.iconHolder,greetingHost:c,introKicker:s.kicker,introTitle:u,introSubtitle:d,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};X(),Pn(),da();const C_=(e,t)=>{let n=J(`button`);n.type=`button`,n.innerHTML=`
24
24
  <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">💬</span>
25
25
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />