@runtypelabs/persona 4.17.1 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3I2S3I5P.js +1 -0
- package/dist/chunk-76IELU7F.js +1 -0
- package/dist/chunk-EFJBUH5F.js +1 -0
- package/dist/chunk-PDPVORUF.js +1 -0
- package/dist/chunk-Q735PSZL.js +1 -0
- package/dist/chunk-VK6JOIYJ.js +1 -0
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +4 -4
- package/dist/{context-mentions-BTSTIBFC.js → context-mentions-MJL6S6P2.js} +1 -1
- package/dist/context-mentions.cjs +9 -8
- package/dist/context-mentions.d.cts +1212 -14
- package/dist/context-mentions.d.ts +1212 -14
- package/dist/context-mentions.js +9 -8
- package/dist/event-stream-view-4EZ7BGFK.js +1 -0
- package/dist/event-stream-view.cjs +129 -0
- package/dist/event-stream-view.d.cts +8384 -0
- package/dist/event-stream-view.d.ts +8384 -0
- package/dist/event-stream-view.js +129 -0
- package/dist/history-view-BD6OXLNA.js +898 -0
- package/dist/history-view.cjs +898 -0
- package/dist/history-view.d.cts +1461 -0
- package/dist/history-view.d.ts +1461 -0
- package/dist/history-view.js +898 -0
- package/dist/index.cjs +77 -77
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1987 -17
- package/dist/index.d.ts +1987 -17
- package/dist/index.global.js +67 -66
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +77 -77
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -4
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +0 -8
- package/dist/plugin-kit.d.ts +0 -8
- package/dist/plugin-kit.js +1 -1
- package/dist/smart-dom-reader.d.cts +1212 -14
- package/dist/smart-dom-reader.d.ts +1212 -14
- package/dist/theme-editor-preview.cjs +970 -73
- package/dist/theme-editor-preview.d.cts +1331 -15
- package/dist/theme-editor-preview.d.ts +1331 -15
- package/dist/theme-editor-preview.js +81 -81
- package/dist/theme-editor.cjs +7 -7
- package/dist/theme-editor.d.cts +1215 -15
- package/dist/theme-editor.d.ts +1215 -15
- package/dist/theme-editor.js +9 -9
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +226 -7
- package/dist/theme-reference.d.ts +226 -7
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +1 -1
- package/package.json +16 -4
- package/src/client-history-rest.test.ts +1034 -0
- package/src/client-visitor-history.test.ts +596 -0
- package/src/client.ts +1040 -24
- package/src/components/artifact-inline.ts +8 -1
- package/src/components/artifact-pane.test.ts +278 -1
- package/src/components/artifact-pane.ts +135 -67
- package/src/components/artifact-preview.test.ts +14 -1
- package/src/components/artifact-preview.ts +9 -0
- package/src/components/header-builder.ts +3 -0
- package/src/components/header-layouts.test.ts +171 -7
- package/src/components/header-layouts.ts +83 -53
- package/src/components/header-parts.test.ts +154 -1
- package/src/components/header-parts.ts +266 -138
- package/src/components/history-confirm-dialog.ts +177 -0
- package/src/components/history-shell-copy.ts +99 -0
- package/src/components/history-view/announcer.ts +40 -0
- package/src/components/history-view/copy.ts +105 -0
- package/src/components/history-view/css.ts +1078 -0
- package/src/components/history-view/grouping.test.ts +142 -0
- package/src/components/history-view/grouping.ts +142 -0
- package/src/components/history-view/icons.ts +73 -0
- package/src/components/history-view/rows.ts +341 -0
- package/src/components/history-view/state.ts +309 -0
- package/src/components/history-view.test.ts +2660 -0
- package/src/components/history-view.ts +1891 -0
- package/src/components/launcher-surface.test.ts +133 -0
- package/src/components/launcher.test.ts +18 -0
- package/src/components/launcher.ts +7 -7
- package/src/components/panel.ts +17 -7
- package/src/components/welcome.ts +72 -2
- package/src/defaults.ts +36 -3
- package/src/event-stream-view-bundle.test.ts +69 -0
- package/src/event-stream-view-entry.ts +19 -0
- package/src/event-stream-view-loader.ts +31 -0
- package/src/event-stream-view.ts +19 -0
- package/src/generated/runtype-openapi-contract.ts +1 -0
- package/src/history-render.ts +325 -0
- package/src/history-view-bundle.test.ts +78 -0
- package/src/history-view-entry.ts +41 -0
- package/src/history-view-loader.test.ts +30 -0
- package/src/history-view-loader.ts +32 -0
- package/src/history-view.ts +28 -0
- package/src/index-core.ts +50 -2
- package/src/index-global.ts +55 -0
- package/src/internal/demo-history-provider.test.ts +402 -0
- package/src/internal/demo-history-provider.ts +689 -0
- package/src/internal/history-provider-registry.ts +25 -0
- package/src/internal/history-provider.ts +150 -0
- package/src/internal/runtype-history-provider.test.ts +313 -0
- package/src/internal/runtype-history-provider.ts +240 -0
- package/src/plugin-kit.test.ts +16 -0
- package/src/plugin-kit.ts +13 -5
- package/src/plugins/types.ts +177 -1
- package/src/session-history.test.ts +1397 -0
- package/src/session.ts +1200 -26
- package/src/styles/widget-styles.test.ts +133 -0
- package/src/styles/widget.css +227 -8
- package/src/theme-editor/preview-utils.test.ts +19 -0
- package/src/theme-editor/preview-utils.ts +15 -1
- package/src/theme-editor/preview.ts +7 -1
- package/src/theme-editor/role-mappings.ts +4 -1
- package/src/theme-editor/sections.test.ts +168 -1
- package/src/theme-editor/sections.ts +136 -7
- package/src/theme-editor/webmcp/summary.ts +16 -2
- package/src/theme-reference.ts +20 -6
- package/src/types/theme.ts +213 -7
- package/src/types.ts +927 -7
- package/src/ui.artifact-rail-resize.test.ts +235 -0
- package/src/ui.attachments-drop.test.ts +1 -0
- package/src/ui.header-update-stability.test.ts +2 -2
- package/src/ui.history-chunk.test.ts +72 -0
- package/src/ui.history-config-provider.test.ts +318 -0
- package/src/ui.history-controller.test.ts +711 -0
- package/src/ui.history-lifecycle.test.ts +456 -0
- package/src/ui.history-render-hooks.test.ts +904 -0
- package/src/ui.history-shell.test.ts +1887 -0
- package/src/ui.rail-overlay.test.ts +573 -0
- package/src/ui.rail-resize.test.ts +284 -0
- package/src/ui.rebuild-composer.test.ts +21 -0
- package/src/ui.render-welcome.test.ts +42 -0
- package/src/ui.shortcuts.test.ts +166 -0
- package/src/ui.ts +3071 -240
- package/src/utils/__fixtures__/client-conversation-history-wire.json +108 -0
- package/src/utils/artifact-file.ts +15 -0
- package/src/utils/artifact-gate.test.ts +4 -0
- package/src/utils/artifact-gate.ts +13 -17
- package/src/utils/artifact-resize.test.ts +28 -0
- package/src/utils/artifact-resize.ts +9 -2
- package/src/utils/buttons.ts +188 -1
- package/src/utils/config-merge.test.ts +91 -0
- package/src/utils/dropdown.ts +10 -1
- package/src/utils/history-messages.test.ts +284 -0
- package/src/utils/history-messages.ts +284 -0
- package/src/utils/icons.ts +3 -0
- package/src/utils/shortcuts.test.ts +288 -0
- package/src/utils/shortcuts.ts +221 -0
- package/src/utils/theme.test.ts +501 -4
- package/src/utils/theme.ts +42 -3
- package/src/utils/tokens.ts +153 -15
- package/src/utils/tooltip-timing.ts +4 -0
- package/src/utils/tooltip.test.ts +249 -7
- package/src/utils/tooltip.ts +146 -4
- package/src/utils/visitor-store.test.ts +425 -0
- package/src/utils/visitor-store.ts +337 -0
- package/dist/chunk-QJ4LV2KW.js +0 -1
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),n=!1;for(let o=0;o<
|
|
3
|
-
`):
|
|
1
|
+
import{a as kg}from"./chunk-5EIIHQLQ.js";import{a as Ig}from"./chunk-PDPVORUF.js";import{a as Pg,b as Lg}from"./chunk-IO5VVUKP.js";import{a as Wg,b as Bg,c as Ao,d as kr,e as Dg,f as _g,g as Og,h as Nd,i as Ng}from"./chunk-VK6JOIYJ.js";import{a as ce}from"./chunk-3I2S3I5P.js";import{a as Er,d as Fd}from"./chunk-EFJBUH5F.js";import{b as Hg,c as Rg}from"./chunk-Q735PSZL.js";import{a as C,b as Eg,c as fe,d as On}from"./chunk-76IELU7F.js";var no=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,i=null;return{setLoader:p=>{o=p,n&&(r=null,i=null)},load:()=>r?Promise.resolve(r):i||(i=(o??e)().then(g=>(r=g,g)).catch(g=>{throw i=null,g}),i),provide:p=>{r=p},getSync:()=>r}};var{setLoader:ST,load:aw,provide:TT,getSync:$d}=no({fallbackImport:()=>import("./markdown-parsers-entry-NVFT3TE6.js")}),gl=new Set,lw=()=>{let t=[...gl];gl.clear();for(let e of t)try{e()}catch{}};var cw=()=>{let t=$d();return t?Promise.resolve(t):aw().then(e=>(lw(),e))},ml=t=>$d()?()=>{}:(gl.add(t),cw().catch(()=>{}),()=>{gl.delete(t)});var So=$d;var dw=t=>{if(t)return t},jd=t=>{let e=null;return n=>{let o=So();if(!o)return Vo(n);if(!e){let{Marked:r}=o,i=t?.markedOptions;e=new r({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=dw(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},hl=t=>t?jd({markedOptions:t.options,renderer:t.renderer}):jd(),kT=jd();var Vo=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var pw={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},uw=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,fw=()=>{let t=null;return e=>{let n=So();if(!n)return Vo(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,i)=>{if(i.attrName==="src"||i.attrName==="href"){let a=i.attrValue;a.toLowerCase().startsWith("data:")&&!uw.test(a)&&(i.attrValue="",i.keepAttr=!1)}})}return t.sanitize(e,pw)}},yl=t=>t===!1?null:typeof t=="function"?t:fw();var Fg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,$g=t=>t.includes("|"),jg=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},gw=t=>`| ${t.join(" | ")} |`,mw=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,hw=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),zg=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],i=e[o+1];if(!$g(r)||Fg.test(r)||!Fg.test(i))continue;let a=jg(r).length;if(a<1)continue;let l=mw(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let d=o+2;for(;d<e.length;d++){let u=e[d];if(u.trim()===""||!$g(u))break;let p=gw(hw(jg(u),a));e[d]!==p&&(e[d]=p,n=!0)}o=d-1}return n?e.join(`
|
|
3
|
+
`):t};var Ug="var(--persona-md-table-scroll-fade, 24px)",Vg=new WeakSet;function Kg(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function qg(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":Ug),t.style.setProperty("--persona-fade-r",r<=1?"0px":Ug)}function zd(t){Vg.has(t)||(Vg.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&qg(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(qg)}var To="webmcp:",Ud=new Map,Gg=t=>{Ud.clear();for(let e of t){let n=e.title?.trim();n&&Ud.set(e.name,n)}},Pi=t=>Ud.get(Jg(t)),bl={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Yg=null;function Qg(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${yw(e.join(""))}`}function Xg(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);n=Math.imul(n^i,2654435761),o=Math.imul(o^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function yw(t){let e=Xg(t,0).toString(36),n=Xg(t,2654435761).toString(36);return`${e}.${n}`}var vl=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return bl.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Gg(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let i={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=vw(r.inputSchema);return a&&(i.parametersSchema=a),i})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Yn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Yn(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let i=Jg(e),a;try{a=await r.getTools()}catch(b){let A=b instanceof Error?b.message:String(b);return Yn(`Failed to read WebMCP registry: ${A}`)}Gg(a);let l=a.find(b=>b.name===i);if(!l)return Yn(`WebMCP tool not registered on this page: ${i}`);if(!this.passesClientAllowlist(i))return Yn(`WebMCP tool not allowed by client allowlist: ${i}`);if(o?.aborted)return Yn("Aborted by cancel()");let d=Pi(i),u={toolName:i,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(u))return Yn("User declined the tool call.");if(o?.aborted)return Yn("Aborted by cancel()");let p=new AbortController,g=!1,y=setTimeout(()=>{g=!0,p.abort()},this.timeoutMs),h=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",h,{once:!0}));try{let b=await r.executeTool(l,Aw(n),{signal:p.signal});return ww(b)}catch(b){if(g)return Yn(`WebMCP tool '${i}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Yn("Aborted by cancel()");let A=b instanceof Error?b.message:String(b);return Yn(A)}finally{clearTimeout(y),o&&o.removeEventListener("abort",h)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Yg?await Yg():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){bl.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,bl.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){let n=this.confirmHandler??Cw;try{return await n(e)}catch(o){return bl.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>bw(e,o))}},Jg=t=>t.startsWith(To)?t.slice(To.length):t,gs=t=>t.startsWith(To),bw=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},vw=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},ww=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Sw(e)}]}},Yn=t=>({isError:!0,content:[{type:"text",text:t}]}),Cw=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=xw(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
|
-
${
|
|
6
|
+
${e}`:"")+(t.description?`
|
|
7
7
|
|
|
8
|
-
${e.description}`:"");return window.confirm(n)},eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},th=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},nh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function yn(e){return e==="card"?"collapsed":e}function Ar(e){return e.split(";",1)[0].trim().toLowerCase()}function oh(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Ar(r)===t)return{mode:yn(s),selector:Ar(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ar(r)===o)return{mode:yn(s),selector:o}}function rh(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:yn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Ar(t.file.mimeType):void 0,u=l?oh(o.files.byMediaType,l):void 0;if(l&&u)return{mode:u.mode,matchedBy:{type:"mediaType",mediaType:l,selector:u.selector}};if(o.files.default)return{mode:yn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:yn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:yn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:yn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:yn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function ho(e,t){return rh(e,t).mode}function xs(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 sh="agent_",ah="flow_";function Vp(e){return e.startsWith(sh)?{kind:"agentId",agentId:e}:e.startsWith(ah)?{kind:"flowId",flowId:e}:null}function qp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=Vp(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let u=t?.[a];if(!u)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(l).payload}}let r=Vp(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as ih,ARR as lh,OBJ as ch,STR as dh}from"partial-json";var Rl="ask_user_question",Cs=8,Sr="data-persona-ask-sheet-for",ph="Other",uh="Other\u2026",Gp="Type your own answer here",Yp="Send",fh="Next",gh="Back",mh="Submit all",hh="Skip",yh=3,Hl="data-ask-current-index",Bl="data-ask-question-count",Xp="data-ask-answers",Dl="data-ask-grouped",Qp="data-ask-layout",bh=e=>e.layout==="pills"?"pills":"rows",vh=e=>e.getAttribute(Qp)==="pills"?"pills":"rows",Kp=!1,Jp=e=>e.replace(/["\\]/g,"\\$&"),qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Rl,Fl=e=>e?.features?.askUserQuestion??{},Tr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=ih(r,dh|ch|lh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},As=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Cs&&!Kp&&(Kp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Cs}.`)),t.slice(0,Cs)},wh=e=>As(e)[0]??null,xh=(e,t)=>As(e)[t]??null,Ch=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Zp=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Ah=(e,t,n,o)=>{let s=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,a.appendChild(l),e.description){let d=b("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let u=Zp(n,o,t);u&&s.appendChild(u)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Sh=e=>{let n=b("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Th=(e,t,n,o)=>{let s=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,u=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(u.length===0&&!n){for(let c=0;c<yh;c++)s.appendChild(Sh(o));return s}if(u.forEach((c,f)=>{s.appendChild(Ah(c,f,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?ph:uh;if(o==="rows"){let f=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(u.length)),f.setAttribute("data-ask-other-row","true");let w=b("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??Gp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),w.appendChild(g),f.appendChild(w);let v=Zp(o,a,u.length);v&&f.appendChild(v),s.appendChild(f)}else{let f=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,s.appendChild(f)}}return s},eu=(e,t)=>{let o=b("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Gp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=b("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Yp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Mh=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Yp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Eh=(e,t,n)=>{let o=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??gh,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??hh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let u=e===t-1;return l.textContent=u?n.submitAllLabel??mh:n.nextLabel??fh,l.setAttribute("data-ask-user-action",u?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ko=e=>{let t=e.getAttribute(Xp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},tu=(e,t)=>{e.setAttribute(Xp,JSON.stringify(t))},bn=e=>{let t=Number(e.getAttribute(Hl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},kh=(e,t)=>{e.setAttribute(Hl,String(Math.max(0,Math.floor(t))))},Mr=e=>{let t=Number(e.getAttribute(Bl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=e=>e.getAttribute(Dl)==="true",Lh=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Ph=(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)))},Na=(e,t)=>{let{payload:n}=Tr(t),o=As(n),r=Ko(e),s={},a=new Set;return o.forEach((l,u)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,u)&&(s[d]=r[u]))}),s},nu=e=>{let t=Ko(e),n=bn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(u=>r.add(u));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(u=>{let d=u.getAttribute("data-option-label")??"",c=r.has(d);u.setAttribute("aria-pressed",c?"true":"false"),u.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(u=>u.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},ou=e=>{if(!yo(e))return;let t=Ko(e),n=bn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Ol=(e,t,n)=>{let o=Fl(n),r=vh(e),{payload:s,complete:a}=Tr(t),l=yo(e),u=bn(e),d=Mr(e),c=l?xh(s,u):wh(s),f=!!c?.multiSelect,w=e.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${u+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let S=typeof c?.question=="string"?c.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let S=Th(c,o,a,r);C.replaceWith(S)}if(r!=="rows"){let S=e.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(eu(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(Mh(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let B=e.querySelector('[data-ask-nav-row="true"]');if(l){let S=Eh(u,d,o);B?B.replaceWith(S):e.appendChild(S)}else B&&B.remove();nu(e),ou(e)},Ih=(e,t,n)=>{let o=Fl(t),r=bh(o),s=e.toolCall.id,a=As(n),l=Math.max(1,a.length),u=l>1,d=Lh(e,a),c=u?Ph(e,l):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Sr,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",e.id),f.setAttribute(Bl,String(l)),f.setAttribute(Hl,String(c)),f.setAttribute(Dl,u?"true":"false"),f.setAttribute(Qp,r),tu(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Ch(f,o);let w=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",w.appendChild(g);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",w.appendChild(v),f.appendChild(w);let T=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),f.appendChild(T),r!=="rows"&&f.appendChild(eu(o,r)),Ol(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Wh=(e,t,n)=>{let{payload:o}=Tr(t),r=Math.max(1,As(o).length);r>Mr(e)&&(e.setAttribute(Bl,String(r)),r>1&&!yo(e)&&e.setAttribute(Dl,"true")),Ol(e,t,n)};var _a=(e,t,n)=>{if(!n||!qo(e)||Fl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Sr}]`).forEach(d=>{d.getAttribute(Sr)!==r&&d.remove()});let a=n.querySelector(`[${Sr}="${Jp(r)}"]`);if(a){Wh(a,e,t);return}let{payload:l}=Tr(e),u=Ih(e,t,l);n.appendChild(u)},Er=(e,t)=>{if(!e)return;let n=t?`[${Sr}="${Jp(t)}"]`:`[${Sr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Nl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),bo=(e,t)=>{let n=Ko(e),o=bn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,tu(e,n),nu(e),ou(e)},$a=(e,t,n,o)=>{let r=Mr(e),s=Math.max(0,Math.min(r-1,o));kh(e,s),Ol(e,t,n)};var Xn="suggest_replies";var Rh={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},su={name:Xn,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:Rh,origin:"sdk",annotations:{readOnlyHint:!0}},_l=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ss=e=>e.variant==="tool"&&e.toolCall?.name===Xn,Hh=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},au=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ss(n))continue;let o=Hh(n.toolCall?.args);return o.length>0?o:null}return null},ru=new Set,Bh=(e,t,n)=>{let o=`${e}:${t}:${n}`;ru.has(o)||(ru.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},vo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let l=t?.[a],u=n?.[a];l===void 0||u===void 0||l!==u&&Bh(a,u,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Dh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Cs,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},Fh={name:Rl,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:Dh,origin:"sdk",annotations:{readOnlyHint:!0}},Ua=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Fh),vo(e).expose&&t.push(su),t};import{parse as Oh,STR as Nh,OBJ as _h}from"partial-json";var iu=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Es=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},du=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},pu=()=>{let e=zh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},uu=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Oh(n,Nh|_h);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?iu(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=iu(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}};var fu=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var gu="4.17.1";var ks=gu;var Vh="https://api.runtype.com/v1/dispatch",qa="https://api.runtype.com";function qh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Ul=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Kh(e){switch(e){case"json":return uu;case"regex-json":return pu;case"xml":return fu;default:return du}}var mu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Gh(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=mu(n);if(!mu(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=Es(e);return Es(t)!==null&&a===null?t:e}var Ls=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Vh,this.headers={"Content-Type":"application/json","X-Persona-Version":ks,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Kh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new Oa(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=qp(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Ul).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ks},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}u(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||qa}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?zp(n):void 0,l=this.clientToolsFingerprintSessionId===t,u=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let w=0;;w++){if(f=await o({...s&&(c||!u)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),f.status===409&&w===0&&s&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||qa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(u.sessionId=a),r&&a){let d=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(a,d,w=>{let g={...u,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(u),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Ul).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Ul).sort((l,u)=>{let d=new Date(l.createdAt).getTime(),c=new Date(u.createdAt).getTime();return d-c}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,u]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=u);let s=[...Ua(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let u=l;return r.clientTools!==void 0&&!("clientTools"in u)&&(u.clientTools=r.clientTools),u}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let u=c=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=f,r(f),f},d=c=>o.current?o.current:u(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),u(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,l="",u=Date.now(),d=0,c=()=>u+d++,f=M=>{let I=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,W=M.tools?M.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...M,reasoning:I,toolCall:h,tools:W}},w=M=>{if(M.role!=="assistant"||M.variant)return!0;let I=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||I||h||!!M.stopReason},g=M=>{w(M)&&n({type:"message",message:f(M)})},v=null,C=null,T={current:null},B={current:null},S=null,k="",P=new Map,H=new Map,F=new Map,N=new Map,z=new Map,j={lastId:null,byStep:new Map},te={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},G=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Q=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ie=o,Y=!1,ue=()=>{if(v)return v;let M,I="",h=S;return!Y&&ie?(M=ie,Y=!0,I=r??""):ie&&h?M=`${ie}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:M,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(v),v},X=(M,I)=>{j.lastId=I,M&&j.byStep.set(M,I)},ge=(M,I)=>{let h=M.reasoningId??M.id,W=G(M);if(h){let R=String(h);return X(W,R),R}if(W){let R=j.byStep.get(W);if(R)return j.lastId=R,R}if(j.lastId&&!I)return j.lastId;if(!I)return null;let L=`reason-${c()}`;return X(W,L),L},Z=M=>{let I=N.get(M);if(I)return I;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return N.set(M,h),g(h),h},pe=(M,I)=>{te.lastId=I,M&&te.byCall.set(M,I)},ee=new Set,me=new Map,we=new Set,he=new Map,ke=M=>{if(!M)return!1;let I=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return I==="emit_artifact_markdown"||I==="emit_artifact_component"},Ne=(M,I)=>{let h=M.toolId??M.id,W=Q(M);if(h){let R=String(h);return pe(W,R),R}if(W){let R=te.byCall.get(W);if(R)return te.lastId=R,R}if(te.lastId&&!I)return te.lastId;if(!I)return null;let L=`tool-${c()}`;return pe(W,L),L},Ue=M=>{let I=z.get(M);if(I)return I;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),g(h),h},Qe=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let I=Number(M);if(!Number.isNaN(I)&&Number.isFinite(I))return I;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Oe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},_e=new Map,Ae=new Map,Se=new Map,ze=(M,I,h)=>{let W=Se.get(M);W||(W=[],Se.set(M,W));let L=0,R=W.length;for(;L<R;){let $=L+R>>>1;W[$].seq<I?L=$+1:R=$}W[L]?.seq===I?W[L]={seq:I,text:h}:W.splice(L,0,{seq:I,text:h});let q="";for(let $=0;$<W.length;$++)q+=W[$].text;return q},Gt=(M,I)=>{let h=Oe(I),W=Ae.get(M.id),L=Gh(W,h);M.rawContent=L;let R=_e.get(M.id),q=de=>{let Pe=M.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(M.content=de)},$=()=>{if(R){let de=R.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(M.id),Ae.delete(M.id),M.streaming=!1,g(M)};if(!R){q(h),$();return}let K=Es(L);if(K!==null&&K.trim()!==""){q(K),$();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let Ve=R.getExtractedText();return Ve!==null&&Ve.trim()!==""?Ve:h},je;try{je=R.processChunk(L)}catch{q(h),$();return}if(je instanceof Promise){je.then(de=>{q(ce(de)),$()}).catch(()=>{q(h),$()});return}q(ce(je)),$()},gt=null,Ht=(M,I,h,W)=>{M.rawContent=I,_e.has(M.id)||_e.set(M.id,this.createStreamParser());let L=_e.get(M.id),R=I.trim().startsWith("{")||I.trim().startsWith("[");if(R&&Ae.set(M.id,I),L.__isPlainTextParser===!0){M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M);return}let $=L.processChunk(I);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(M.content=ce,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(M.content=K,g(M)):!R&&!I.trim().startsWith("<")&&(M.content=W!==void 0?I:M.content+h,Ae.delete(M.id),_e.delete(M.id),M.rawContent=void 0,g(M))}},xn=(M,I)=>{let h=I??M.content;if(h==null||h===""){M.streaming=!1,g(M);return}let L=Ae.get(M.id)??Oe(h);M.rawContent=L;let R=_e.get(M.id),q=null,$=!1;if(R&&(q=R.getExtractedText(),q===null&&(q=Es(L)),q===null)){let K=R.processChunk(L);K instanceof Promise?($=!0,K.then(ce=>{let je=typeof ce=="string"?ce:ce?.text??null;je!==null&&(M.content=je,M.streaming=!1,_e.delete(M.id),Ae.delete(M.id),g(M))}).catch(()=>{})):q=typeof K=="string"?K:K?.text??null}if(!$){q!==null&&q.trim()!==""?M.content=q:Ae.has(M.id)||(M.content=Oe(h));let K=_e.get(M.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,g(M)}},Cn=(M,I,h)=>{let W=H.get(M);if(W)return W;let L={id:`nested-${I}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:I}};return H.set(M,L),g(L),L},et=[],Le,ye=new Map,tt=0,Te="agent",ve=!1,re=null,xe=null,An=new Map,ne=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let I=et[M].payloadType,h=et[M].payload;if(!ve&&Te!=="flow"&&typeof h.stepType=="string"&&(Te="flow"),I==="reasoning_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L),Cn(W,L,"reasoning");continue}let R=ge(h,!0)??`reason-${c()}`,q=Z(R);q.reasoning=q.reasoning??{id:R,status:"streaming",chunks:[]},q.reasoning.startedAt=q.reasoning.startedAt??Qe(h.startedAt??h.timestamp),q.reasoning.completedAt=void 0,q.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),q.streaming=!0,q.reasoning.status="streaming",g(q)}else if(I==="reasoning_delta"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let $=H.get(W),K=h.reasoningText??h.text??h.delta??"";K&&h.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=Z(L);R.reasoning=R.reasoning??{id:L,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Qe(h.startedAt??h.timestamp);let q=h.reasoningText??h.text??h.delta??"";if(q&&h.hidden!==!0){let $=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if($!==void 0){let K=ze(L,$,String(q));R.reasoning.chunks=[K]}else R.reasoning.chunks.push(String(q))}if(R.reasoning.status=h.done?"complete":"streaming",h.done){R.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let $=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-$)}R.streaming=R.reasoning.status!=="complete",g(R)}else if(I==="reasoning_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)&&H.has(W)){let K=H.get(W);if(K.reasoning){let ce=typeof h.text=="string"?h.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}P.delete(W),H.delete(W);continue}let L=ge(h,!1)??ge(h,!0)??`reason-${c()}`,R=typeof h.text=="string"?h.text:"";!N.get(L)&&(R||h.scope==="loop")&&Z(L);let q=N.get(L);if(q?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(q.reasoning.scope=h.scope),R&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(R),q.reasoning.status="complete",q.reasoning.completedAt=Qe(h.completedAt??h.timestamp);let K=q.reasoning.startedAt??Date.now();q.reasoning.durationMs=Math.max(0,(q.reasoning.completedAt??Date.now())-K),q.streaming=!1,g(q)}let $=G(h);$&&j.byStep.delete($)}else if(I==="tool_start"){v&&(v.streaming=!1,g(v),v=null),typeof h.iteration=="number"&&(tt=h.iteration);let W=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??Ne(h,!0)??`tool-${c()}`,L=h.toolName??h.name;if(ke(L)){ee.add(W);continue}pe(Q(h),W);let R=Ue(W),q=R.toolCall??{id:W,status:"pending"};q.name=L??q.name,q.status="running",h.parameters!==void 0?q.args=h.parameters:h.args!==void 0&&(q.args=h.args),q.startedAt=q.startedAt??Qe(h.startedAt??h.timestamp),q.completedAt=void 0,q.durationMs=void 0,R.toolCall=q,R.streaming=!0,h.executionId&&(R.agentMetadata={executionId:h.executionId,iteration:h.iteration}),g(R)}else if(I==="tool_output_delta"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W))continue;let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.startedAt=R.startedAt??Qe(h.startedAt??h.timestamp);let q=h.text??h.delta??h.message??"";q&&(R.chunks=R.chunks??[],R.chunks.push(String(q))),R.status="running",L.toolCall=R,L.streaming=!0;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L)}else if(I==="tool_complete"){let W=Ne(h,!1)??Ne(h,!0)??`tool-${c()}`;if(ee.has(W)){ee.delete(W);continue}let L=Ue(W),R=L.toolCall??{id:W,status:"running"};R.status="complete",h.result!==void 0&&(R.result=h.result),typeof h.duration=="number"&&(R.duration=h.duration),R.completedAt=Qe(h.completedAt??h.timestamp);let q=h.duration??h.executionTime;if(typeof q=="number")R.durationMs=q;else{let ce=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-ce)}L.toolCall=R,L.streaming=!1;let $=h.agentContext;($||h.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:$?.executionId??h.executionId,iteration:$?.iteration??h.iteration}),g(L);let K=Q(h);K&&te.byCall.delete(K)}else if(I==="await"&&h.toolName){let W=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,L=W??h.toolId??`local-${c()}`,R=Ue(L),q=h.toolName,$=h.origin==="webmcp"&&!Cr(q)?`webmcp:${q}`:q,K=Cr($),ce=R.toolCall??{id:L,status:"pending"};ce.name=$,ce.args=h.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(h.startedAt??h.timestamp??h.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,R.toolCall=ce,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:h.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...W?{webMcpToolCallId:W}:{}},g(R)}else if(I==="text_start"){let W=typeof h.id=="string"?h.id:null,L=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(W&&L){P.set(W,L);continue}let R=v;R&&(Te==="flow"?(xn(R),gt=R):(R.streaming=!1,g(R)),v=null),S=typeof h.id=="string"?h.id:S,k=""}else if(I==="text_delta"){let W=typeof h.id=="string"?h.id:null,L=W?P.get(W):void 0;if(W&&L){let q=typeof h.delta=="string"?h.delta:"",$=(F.get(W)??"")+q;if(F.set(W,$),$.trim()==="")continue;let K=Cn(W,L);K.agentMetadata={...K.agentMetadata,executionId:h.executionId,parentToolId:L},Ht(K,$,q,void 0);continue}if(S=typeof h.id=="string"?h.id:S,Te==="flow"){let q=typeof h.delta=="string"?h.delta:"";if(k+=q,k.trim()==="")continue;let $=ue();$.agentMetadata={executionId:h.executionId,iteration:h.iteration},Ht($,k,q,void 0),C=$;continue}let R=ue();R.content+=h.delta??"",R.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:re??void 0,agentName:xe?.agentName},C=R,g(R)}else if(I==="text_complete"){let W=typeof h.id=="string"?h.id:null;if(W&&P.has(W)){let R=H.get(W);R&&xn(R),P.delete(W),F.delete(W),H.delete(W);continue}let L=v;L&&(Te==="flow"?(xn(L),gt=L):((L.content??"")===""&&typeof h.text=="string"&&(L.content=h.text),L.streaming=!1,g(L)),v=null),S=null,k=""}else if(I==="step_complete"){let W=h.stepType,L=h.executionType;if(W==="tool"||L==="context")continue;if(h.success===!1){let R=h.error,q=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error(q)});let $=v;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let R=gt;gt=null;let q=h.stopReason,$=h.result?.response;if(R)q&&(R.stopReason=q),$!=null?Gt(R,$):R.streaming!==!1&&(_e.delete(R.id),Ae.delete(R.id),R.streaming=!1,g(R));else{let K=$!=null&&$!=="";if(K||q){let ce=ue();q&&(ce.stopReason=q),K?xn(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(I==="execution_start")Te=h.kind==="flow"?"flow":"agent",ve=!0,Te==="agent"&&(xe={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Qe(h.startedAt)});else if(I==="turn_start"){let W=typeof h.iteration=="number"?h.iteration:tt;if(W!==tt){if(xe&&(xe.currentIteration=W),ne==="separate"&&W>1){let L=v;L&&(L.streaming=!1,g(L),An.set(W-1,L),v=null)}tt=W}re=typeof h.id=="string"?h.id:null,C=null}else if(I==="tool_input_delta"){let W=h.toolCallId??te.lastId;if(W){let L=z.get(W);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(h.delta??""),g(L))}}else{if(I==="tool_input_complete")continue;if(I==="turn_complete"){let W=h.stopReason,L=v??C;if(W&&L!==null){let R=h.id;(!R||L.agentMetadata?.turnId===R)&&(L.stopReason=W,g(L))}re===h.id&&(re=null)}else if(I==="media_start"){let W=String(h.id);ye.set(W,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(I==="media_delta"){let W=ye.get(String(h.id));W&&typeof h.delta=="string"&&W.parts.push(h.delta)}else if(I==="media_complete"){let W=String(h.id),L=ye.get(W);ye.delete(W);let R=(typeof h.mediaType=="string"?h.mediaType:void 0)??L?.mediaType??"application/octet-stream",q=typeof h.data=="string"?h.data:void 0,$=typeof h.url=="string"?h.url:L&&L.parts.length>0?L.parts.join(""):void 0,K=null;if(q)K={type:"media",data:q,mediaType:R};else if($){let Pe=R.toLowerCase();K={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:$,mediaType:R}}let ce=h.toolCallId??L?.toolCallId,je=K?[K]:[],de=[];for(let Pe of je){if(!Pe||typeof Pe!="object")continue;let Ve=Pe,$e=typeof Ve.type=="string"?Ve.type:void 0,Re=typeof Ve.mediaType=="string"?Ve.mediaType.toLowerCase():"",Ce=null,nt="";if($e==="media"){let xt=typeof Ve.data=="string"?Ve.data:void 0;if(!xt)continue;nt=Re.length>0?Re:"application/octet-stream",Ce=`data:${nt};base64,${xt}`}else if($e==="image-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else if($e==="file-url"){let xt=typeof Ve.url=="string"?Ve.url:void 0;if(!xt)continue;nt=Re,Ce=xt}else continue;if(Ce)if($e==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:Ce,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:Ce,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:Ce,mimeType:nt});else{let xt=nt||"application/octet-stream";de.push({type:"file",data:Ce,mimeType:xt,filename:qh(xt)})}}if(de.length>0){let Pe=c(),Ve=ce,Re={id:`agent-media-${typeof Ve=="string"&&Ve.length>0?`${Ve}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:tt}};g(Re);let Ce=v;Ce&&(Ce.streaming=!1,g(Ce)),v=null,T.current=null}}else if(I==="execution_complete"){let W=h.kind??Te;W==="agent"&&xe&&(xe.status=h.success?"complete":"error",xe.completedAt=Qe(h.completedAt),xe.stopReason=h.stopReason);let L=v;L&&(W==="flow"&&L.streaming!==!1?xn(L):(L.streaming=!1,g(L)),v=null),S=null,k="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(I==="execution_error"){let W=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(W)})}else if(I!=="ping"){if(I==="approval_start"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="step_await"&&h.awaitReason==="approval_required"){let W=h.approvalId??`approval-${c()}`,L={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:"pending",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};g(L)}else if(I==="approval_complete"){let W=h.approvalId;if(W){let R={id:`approval-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:W,status:h.decision??"approved",agentId:xe?.agentId??"virtual",executionId:h.executionId??xe?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};g(R)}}else if(I==="artifact_start"||I==="artifact_delta"||I==="artifact_update"||I==="artifact_complete"){if(I==="artifact_start"){let W=h.artifactType,L=String(h.id),R=typeof h.title=="string"?h.title:void 0,q=h.file,$;q&&typeof q=="object"&&!Array.isArray(q)&&typeof q.path=="string"&&typeof q.mimeType=="string"&&($={path:q.path,mimeType:q.mimeType,...typeof q.language=="string"?{language:q.language}:{}}),n({type:"artifact_start",id:L,artifactType:W,title:R,component:typeof h.component=="string"?h.component:void 0,...$?{file:$}:{}});let K=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(he.set(L,{markdown:"",title:R,file:$,...K?{props:K}:{}}),!we.has(L)){we.add(L);let ce=ho(this.config.features?.artifacts,{artifactType:W,...$?{file:$}:{}}),je=typeof h.component=="string"?h.component:void 0,de={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:xs(ce,{artifactId:L,title:R,artifactType:W,status:"streaming",...$?{file:$}:{},...je?{component:je}:{}})};me.set(L,de),g(de)}}else if(I==="artifact_delta"){let W=String(h.id),L=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:W,artDelta:L});let R=he.get(W);R&&(R.markdown+=L)}else if(I==="artifact_update"){let W=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:W,component:typeof h.component=="string"?h.component:void 0});let L=he.get(String(h.id));L&&(L.props={...L.props??{},...W})}else if(I==="artifact_complete"){let W=String(h.id);n({type:"artifact_complete",id:W});let L=me.get(W);if(L){L.streaming=!1;try{let R=JSON.parse(L.rawContent??"{}");if(R.props){R.props.status="complete";let q=he.get(W);q?.markdown&&(R.props.markdown=q.markdown),q?.file&&(R.props.file=q.file),R.component==="PersonaArtifactInline"&&q?.props&&Object.keys(q.props).length>0&&(R.props.componentProps=q.props)}L.rawContent=JSON.stringify(R)}catch{}he.delete(W),g(L),me.delete(W)}}}else if(I==="transcript_insert"){let W=h.message;if(!W||typeof W!="object")continue;let L=String(W.id??`msg-${c()}`),R=W.role,$={id:L,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof W.content=="string"?W.content:"",rawContent:typeof W.rawContent=="string"?W.rawContent:void 0,createdAt:typeof W.createdAt=="string"?W.createdAt:new Date().toISOString(),streaming:W.streaming===!0,...typeof W.variant=="string"?{variant:W.variant}:{},sequence:c()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&we.add(ce)}catch{}v=null,T.current=null,_e.delete(L),Ae.delete(L)}else if(I==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let W=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(W)});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}else if(I==="step_error"||I==="dispatch_error"||I==="flow_error"){let W=null;if(h.error instanceof Error)W=h.error;else if(I==="dispatch_error"){let L=h.message??h.error;L!=null&&L!==""&&(W=new Error(String(L)))}else{let L=h.error;typeof L=="string"&&L!==""?W=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(W=new Error(String(L.message??L)))}if(W){n({type:"error",error:W});let L=v;L&&L.streaming&&(L.streaming=!1,g(L)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:I}=await s.read();if(M)break;l+=a.decode(I,{stream:!0});let h=l.split(`
|
|
8
|
+
${t.description}`:"");return window.confirm(n)},xw=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Aw=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Sw=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Nn(t){return t==="card"?"collapsed":t}function ms(t){return t.split(";",1)[0].trim().toLowerCase()}function Tw(t,e){if(!t)return;let n=Object.entries(t);for(let[r,i]of n)if(ms(r)===e)return{mode:Nn(i),selector:ms(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,i]of n)if(ms(r)===o)return{mode:Nn(i),selector:o}}function Mw(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:Nn(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?ms(e.file.mimeType):void 0,d=l?Tw(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:Nn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:Nn(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let i=o.byType?.[e.artifactType];if(i)return{mode:Nn(i),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:Nn(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:Nn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function qo(t,e){return Mw(t,e).mode}function Li(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Ew="agent_",kw="flow_";function Zg(t){return t.startsWith(Ew)?{kind:"agentId",agentId:t}:t.startsWith(kw)?{kind:"flowId",flowId:t}:null}function em(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let u=Zg(l);if(u)return u;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=Zg(n);if(r)return r;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as Pw,ARR as Lw,OBJ as Iw,STR as Hw}from"partial-json";var Vd="ask_user_question",Ii=8,hs="data-persona-ask-sheet-for",Rw="Other",Ww="Other\u2026",nm="Type your own answer here",om="Send",Bw="Next",Dw="Back",_w="Submit all",Ow="Skip",Nw=3,qd="data-ask-current-index",Kd="data-ask-question-count",rm="data-ask-answers",Gd="data-ask-grouped",sm="data-ask-layout",Fw=t=>t.layout==="pills"?"pills":"rows",$w=t=>t.getAttribute(sm)==="pills"?"pills":"rows",tm=!1,im=t=>t.replace(/["\\]/g,"\\$&"),Pr=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Vd,Yd=t=>t?.features?.askUserQuestion??{},ys=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),i=Pw(r,Hw|Iw|Lw);if(i&&typeof i=="object")return{payload:i,complete:n}}catch{}return{payload:null,complete:n}},Hi=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Ii&&!tm&&(tm=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ii}.`)),e.slice(0,Ii)},jw=t=>Hi(t)[0]??null,zw=(t,e)=>Hi(t)[e]??null,Uw=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},am=(t,e,n)=>{if(t!=="rows")return null;let o=C("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=C("span","persona-ask-row-check");o.appendChild(r)}else{let r=C("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Vw=(t,e,n,o)=>{let i=C("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",o?"checkbox":"button"),i.setAttribute("aria-pressed","false"),i.setAttribute("data-ask-user-action","pick"),i.setAttribute("data-option-index",String(e)),i.setAttribute("data-option-label",t.label),n==="rows"){let a=C("span","persona-ask-row-content"),l=C("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let u=C("span","persona-ask-row-description");u.textContent=t.description,a.appendChild(u)}i.appendChild(a);let d=am(n,o,e);d&&i.appendChild(d)}else i.textContent=t.label,t.description&&(i.title=t.description);return i},qw=t=>{let n=C("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Kw=(t,e,n,o)=>{let i=C("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");i.setAttribute("role","group"),i.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<Nw;p++)i.appendChild(qw(o));return i}if(d.forEach((p,g)=>{i.appendChild(Vw(p,g,o,a))}),t?.allowFreeText!==!1){let p=o==="rows"?Rw:Ww;if(o==="rows"){let g=C("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(d.length)),g.setAttribute("data-ask-other-row","true");let y=C("span","persona-ask-row-content"),h=document.createElement("input");h.type="text",h.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",h.placeholder=e.freeTextPlaceholder??nm,h.setAttribute("data-ask-free-text-input","true"),h.setAttribute("aria-label",e.freeTextLabel??p),y.appendChild(h),g.appendChild(y);let b=am(o,a,d.length);b&&g.appendChild(b),i.appendChild(g)}else{let g=C("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=e.freeTextLabel??p,i.appendChild(g)}}return i},lm=(t,e)=>{let o=C("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??nm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let i=C("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=t.submitLabel??om,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Gw=t=>{let e=C("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=C("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??om,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Yw=(t,e,n)=>{let o=C("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=C("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Dw,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let i=C("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=C("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Ow,a.setAttribute("data-ask-user-action","skip"),i.appendChild(a);let l=C("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=t===e-1;return l.textContent=d?n.submitAllLabel??_w:n.nextLabel??Bw,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,i.appendChild(l),o.appendChild(i),o},Lr=t=>{let e=t.getAttribute(rm);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(t,e)=>{t.setAttribute(rm,JSON.stringify(e))},Fn=t=>{let e=Number(t.getAttribute(qd)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Xw=(t,e)=>{t.setAttribute(qd,String(Math.max(0,Math.floor(e))))},bs=t=>{let e=Number(t.getAttribute(Kd)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Ko=t=>t.getAttribute(Gd)==="true",Qw=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,i)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[i]=l)}}),o},Jw=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},wl=(t,e)=>{let{payload:n}=ys(e),o=Hi(n),r=Lr(t),i={},a=new Set;return o.forEach((l,d)=>{let u=typeof l?.question=="string"?l.question:"";u&&(a.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),a.add(u),Object.prototype.hasOwnProperty.call(r,d)&&(i[u]=r[d]))}),i},dm=t=>{let e=Lr(t),n=Fn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let i=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');i.forEach(d=>{let u=d.getAttribute("data-option-label")??"",p=r.has(u);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(i).map(d=>d.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},pm=t=>{if(!Ko(t))return;let e=Lr(t),n=Fn(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,i=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');i&&(i.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},Xd=(t,e,n)=>{let o=Yd(n),r=$w(t),{payload:i,complete:a}=ys(e),l=Ko(t),d=Fn(t),u=bs(t),p=l?zw(i,d):jw(i),g=!!p?.multiSelect,y=t.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${u}`:"");let h=t.querySelector('[data-ask-stepper="true"]');h&&h.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let I=typeof p?.question=="string"?p.question:"";b.textContent=I,b.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let A=t.querySelector('[data-ask-pill-list="true"]');if(A){let I=Kw(p,o,a,r);A.replaceWith(I)}if(r!=="rows"){let I=t.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(lm(o,r))}let k=t.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!k?t.appendChild(Gw(o)):(!g||l)&&k&&k.remove(),t.setAttribute("data-multi-select",g?"true":"false");let N=t.querySelector('[data-ask-nav-row="true"]');if(l){let I=Yw(d,u,o);N?N.replaceWith(I):t.appendChild(I)}else N&&N.remove();dm(t),pm(t)},Zw=(t,e,n)=>{let o=Yd(e),r=Fw(o),i=t.toolCall.id,a=Hi(n),l=Math.max(1,a.length),d=l>1,u=Qw(t,a),p=d?Jw(t,l):0,g=C("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(hs,i),g.setAttribute("data-tool-call-id",i),g.setAttribute("data-message-id",t.id),g.setAttribute(Kd,String(l)),g.setAttribute(qd,String(p)),g.setAttribute(Gd,d?"true":"false"),g.setAttribute(sm,r),cm(g,u),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Uw(g,o);let y=C("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),h=C("div","persona-ask-sheet-question persona-flex-1");h.setAttribute("data-ask-question","true"),h.textContent="",y.appendChild(h);let b=C("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",y.appendChild(b),g.appendChild(y);let k=C("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),g.appendChild(k),r!=="rows"&&g.appendChild(lm(o,r)),Xd(g,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},eC=(t,e,n)=>{let{payload:o}=ys(e),r=Math.max(1,Hi(o).length);r>bs(t)&&(t.setAttribute(Kd,String(r)),r>1&&!Ko(t)&&t.setAttribute(Gd,"true")),Xd(t,e,n)};var Cl=(t,e,n)=>{if(!n||!Pr(t)||Yd(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${hs}]`).forEach(u=>{u.getAttribute(hs)!==r&&u.remove()});let a=n.querySelector(`[${hs}="${im(r)}"]`);if(a){eC(a,t,e);return}let{payload:l}=ys(t),d=Zw(t,e,l);n.appendChild(d)},vs=(t,e)=>{if(!t)return;let n=e?`[${hs}="${im(e)}"]`:`[${hs}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let i=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(i)?i:180)})},Qd=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Go=(t,e)=>{let n=Lr(t),o=Fn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,cm(t,n),dm(t),pm(t)},xl=(t,e,n,o)=>{let r=bs(t),i=Math.max(0,Math.min(r-1,o));Xw(t,i),Xd(t,e,n)};var Mo="suggest_replies";var tC={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},fm={name:Mo,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:tC,origin:"sdk",annotations:{readOnlyHint:!0}},Jd=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ri=t=>t.variant==="tool"&&t.toolCall?.name===Mo,nC=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let i=r;if(typeof i.label!="string"||!i.label.trim())return[];let a={label:i.label.trim()};return typeof i.prompt=="string"&&i.prompt.trim()&&(a.prompt=i.prompt.trim()),typeof i.description=="string"&&i.description.trim()&&(a.description=i.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},gm=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Ri(n))continue;let o=nC(n.toolCall?.args);return o.length>0?o:null}return null},um=new Set,oC=(t,e,n)=>{let o=`${t}:${e}:${n}`;um.has(o)||(um.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},Yo=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&oC(a,d,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,i=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:i}};var rC={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ii,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},sC={name:Vd,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:rC,origin:"sdk",annotations:{readOnlyHint:!0}},Al=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(sC),Yo(t).expose&&e.push(fm),e};import{parse as iC,STR as aC,OBJ as lC}from"partial-json";var mm=t=>t.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Xo=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},cC=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},hm=t=>t.status==="complete"?cC(t):t.status==="pending"?"Waiting":"",dC=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var ym=t=>t.status==="complete"?dC(t):"Using tool...",Sl=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Bi=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Sl(e)},Tl=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return Sl(e)},Zd=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Bi(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ml=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,i=0,a;for(;(a=r.exec(n))!==null;)a.index>i&&Wi(o,n.slice(i,a.index),[]),a[1]!==void 0?Wi(o,a[1],["bold"]):a[2]!==void 0?Wi(o,a[2],["italic"]):a[3]!==void 0&&Wi(o,a[3],["dim"]),i=a.index+a[0].length;return i<n.length&&Wi(o,n.slice(i),[]),o},Wi=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},pC=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,i=o.match(r);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let i=n(o);return i!==null&&(t=i),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Di=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},bm=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},vm=()=>{let t=pC();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},wm=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=iC(n,aC|lC);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?mm(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=mm(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Cm=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var xm="4.18.0";var ws=xm;var Cs="[Image]";function Am(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function El(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Qo(t){return{type:"text",text:t}}function Sm(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Tm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fC=["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"],Eo=[...Tm,...fC];function gC(t){return Tm.includes(t)||t.startsWith("image/")}function kl(t){return gC(t.type)}function Mm(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function Em(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;kl(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function km(t,e=Eo,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function mC(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Pm(t,e){let n=mC(e).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"}[t]||n||"FILE"}var hC=["user","assistant","system"],yC=0;function Lm(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function Pl(t){return typeof t=="string"?t:void 0}function bC(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?Qo(e.text):null;case"image":return typeof e.image=="string"?Sm(e.image,{mimeType:Pl(e.mimeType),alt:Pl(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Mm(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...Pl(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...Pl(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function vC(t,e){let n=Lm(e),o=t.map(a=>Lm(a.timestamp)),r=new Array(t.length),i=0;for(;i<o.length;){let a=o[i];if(a!==null){r[i]=a,i+=1;continue}let l=i;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-i+1,u=i>0?r[i-1]:null,p=l+1<o.length?o[l+1]:null,g=p!==null&&n!==null?Math.min(p,n):p??n;for(let y=0;y<d;y+=1)r[i+y]=g!==null?g-(d-y):u!==null?u+y+1:yC+y;i=l+1}return r.map(a=>new Date(a).toISOString())}function Im(t,e){let n=vC(t,e?.beforeCreatedAt),o=[];return t.forEach((r,i)=>{if(typeof r?.id!="string"||r.id===""||!hC.includes(r.role))return;let a=r.role,l=n[i];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(bC).filter(p=>p!==null),u=Am(d);o.push({id:r.id,role:a,content:u||(El(d)?Cs:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function _i(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function Oi(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let i=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(i)&&!Number.isNaN(a)&&i!==a)return i-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var wC="https://api.runtype.com/v1/dispatch",Hm="https://api.runtype.com",Re=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Rm=32768,ep=49152,Wm=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:typeof e.flowId=="string"?e.flowId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},Bm=t=>"reason"in t?t.reason:void 0,Dm="The identity proof was not admitted; account history is unavailable",_m="The identity proof was rejected",Om="The request carried no visitor credential",Nm="The stored visitor belongs to a different signed-in user",Fm=(t,e)=>t instanceof Re&&t.code===e;function CC(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let i=e.slice(r+1).split(";")[0]?.trim()??"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var tp=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function xC(t){switch(t){case"json":return wm;case"regex-json":return vm;case"xml":return Cm;default:return bm}}var $m=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function AC(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=$m(n);if(!$m(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Di(t);return Di(e)!==null&&a===null?e:t}var Ni=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??wC,this.headers={"Content-Type":"application/json","X-Persona-Version":ws,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??xC(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new vl(e.webmcp):null}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let i=em(o,r);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Hm}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&Bm(n)===Bm(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let r=this.routing(),i=r.agentId??r.flowId,a=n?e.conversationId:void 0,l={token:this.config.clientToken,...i&&{flowId:i},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...a?{conversationId:a}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},d=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ws},body:JSON.stringify(l)});if(!d.ok){let p=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&p.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),a)throw new Re("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw n&&d.status===401&&p.error==="visitor_required"?new Re("visitor_required","Visitor credential no longer resolves"):a&&d.status===404?new Re("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):d.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let u=await d.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(e&&n)try{let o=await this.createClientSession({conversationId:e});return this.finishInit(o,e,!1)}catch(o){if(!Fm(o,"not_found")&&!Fm(o,"visitor_required"))throw o;return this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),i=await this.claimFirstConversation(r);return this.finishInit(i,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),i=this.finishInit(r,o,!1);return this.clientSession=i,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),i}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable())return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Re("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Re("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ws},body:JSON.stringify(r)});if(!i.ok){let a=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[i,a]of Object.entries(n))a===void 0||a===""||o.set(i,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Re("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Re("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Re("proof_not_admitted",Dm);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Re("invalid_identity_proof",_m);if(r.includes("visitor token required"))throw new Re("visitor_token_missing",Om);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Re("visitor_identity_mismatch",Nm);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Re("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Re("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Re("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Re("proof_not_admitted",Dm);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Re("invalid_identity_proof",_m)):r.includes("visitor token required")?new Re("visitor_token_missing",Om):r.includes("visitor_identity_mismatch")?new Re("visitor_identity_mismatch",Nm):new Re("unauthorized",o||"History request was not authorized")}return new Re("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Re("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Re("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Re("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),i=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(i=await this.resolveIdentityProof(r,o),i&&(r=await this.bindIdentity(r,i,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new Re("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":ws,...u?{"X-Visitor-Token":u}:{},...i?{"X-Identity-Proof":i}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(p.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),i,o);continue}if(!p.ok)throw await this.historyErrorFor(p,o);let g=p.headers.get("X-History-Identity-Status"),y=await p.json().catch(()=>{});if(a&&a.revision()!==d)throw new Re("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(g,i!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Re("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Wm),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:Wm(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let u=d.displayContent.length;if(u>Rm)throw new Re("payload_too_large",`displayContent exceeds the ${Rm} character limit`);o+=u}if(o>ep)throw new Re("payload_too_large",`Display projection batch exceeds the ${ep} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,i=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=ep,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===i&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let p=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:p}),p}let r=await this.buildPayload(e.messages),i=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([p])=>p!=="sessionId"&&p!=="session_id")):void 0,a=this.isHistoryCapable(),l={sessionId:o.sessionId,messages:e.messages.filter(tp).map(p=>{let g=a?_i(p):void 0;return{id:p.id,role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,...g!==void 0&&{displayContent:g}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...i&&Object.keys(i).length>0&&{metadata:i},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:d,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,p=>{let g={...l,...p};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ws},body:JSON.stringify(g),signal:e.signal})});if(!d.ok){let p=await d.json().catch(()=>({error:"Chat request failed"}));if(d.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let y=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:y}),y}if(d.status===429){let y=new Error(p.hint||"Message limit reached for this session.");throw n({type:"error",error:y}),y}if(d.status===410&&p.error==="conversation_deleted"){let y=new Re("conversation_deleted","This conversation was deleted");throw n({type:"error",error:y}),y}let g=new Error(p.error||"Failed to send message");throw n({type:"error",error:g}),g}if(!d.body){let p=new Error("No response body received");throw n({type:"error",error:p}),p}u(),n({type:"status",status:"connected"});try{await this.streamResponse(d.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!(r instanceof Re)&&!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else i=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else i=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let i=!!(n&&n.length>0),a=i?Qg(n):void 0,l=this.clientToolsFingerprintSessionId===e,d=i&&l&&this.lastSentClientToolsFingerprint===a,u=!i&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,p=!1,g;for(let y=0;;y++){if(g=await o({...i&&(p||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&y===0&&i&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,i?this.sentNonEmptyClientToolsSessionId=e:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),i=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Hm}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(d.sessionId=a),r&&a){let u=[...Al(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:p,commit:g}=await this.sendWithClientToolsDiff(a,u,y=>{let h={...d,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",h),fetch(i,{method:"POST",headers:l,body:JSON.stringify(h),signal:o?.signal})},{emptyMeansReplace:!0});return p.ok&&g(),p}return fetch(i,{method:"POST",headers:l,body:JSON.stringify(d),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let i=await r({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(tp).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},i=[...Al(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];i.length>0&&(r.clientTools=i);let a=await this.buildContextAggregate(e);return a&&(r.context=a),r}async buildPayload(e){let n=e.slice().filter(tp).sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,d]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=d);let i=[...Al(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];i.length>0&&(r.clientTools=i);let a=await this.buildContextAggregate(e);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let d=l;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,i,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=p=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:i(),...p!==void 0&&{partId:p}};return o.current=g,r(g),g},u=p=>o.current?o.current:d(p);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let p=u(l.partId);l.partId!==void 0&&!p.partId&&(p.partId=l.partId),p.content+=l.text,r(p)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let i=e.getReader(),a=new TextDecoder,l="",d=Date.now(),u=0,p=()=>d+u++,g=O=>{let ee=O.reasoning?{...O.reasoning,chunks:[...O.reasoning.chunks]}:void 0,w=O.toolCall?{...O.toolCall,chunks:O.toolCall.chunks?[...O.toolCall.chunks]:void 0}:void 0,x=O.tools?O.tools.map(L=>({...L,chunks:L.chunks?[...L.chunks]:void 0})):void 0;return{...O,reasoning:ee,toolCall:w,tools:x}},y=O=>{if(O.role!=="assistant"||O.variant)return!0;let ee=Array.isArray(O.contentParts)&&O.contentParts.length>0,w=typeof O.rawContent=="string"&&O.rawContent.trim()!=="";return typeof O.content=="string"&&O.content.trim()!==""||ee||w||!!O.stopReason},h=O=>{y(O)&&n({type:"message",message:g(O)})},b=null,A=null,k={current:null},N={current:null},I=null,P="",S=new Map,W=new Map,R=new Map,H=new Map,z=new Map,V={lastId:null,byStep:new Map},ne={lastId:null,byCall:new Map},$=O=>{if(O==null)return null;try{return String(O)}catch{return null}},X=O=>$(O.stepId??O.step_id??O.step??O.parentId??O.flowStepId??O.flow_step_id),ue=O=>$(O.callId??O.call_id??O.requestId??O.request_id??O.toolCallId??O.tool_call_id??O.stepId??O.step_id),we=o,be=!1,pe=()=>{if(b)return b;let O,ee="",w=I;return!be&&we?(O=we,be=!0,ee=r??""):we&&w?O=`${we}_${w}`:O=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:O,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},h(b),b},J=(O,ee)=>{V.lastId=ee,O&&V.byStep.set(O,ee)},re=(O,ee)=>{let w=O.reasoningId??O.id,x=X(O);if(w){let E=String(w);return J(x,E),E}if(x){let E=V.byStep.get(x);if(E)return V.lastId=E,E}if(V.lastId&&!ee)return V.lastId;if(!ee)return null;let L=`reason-${p()}`;return J(x,L),L},ae=O=>{let ee=H.get(O);if(ee)return ee;let w={id:`reason-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:O,status:"streaming",chunks:[]}};return H.set(O,w),h(w),w},T=(O,ee)=>{ne.lastId=ee,O&&ne.byCall.set(O,ee)},Z=new Set,de=new Map,Ce=new Set,he=new Map,ve=O=>{if(!O)return!1;let ee=O.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},xe=(O,ee)=>{let w=O.toolId??O.id,x=ue(O);if(w){let E=String(w);return T(x,E),E}if(x){let E=ne.byCall.get(x);if(E)return ne.lastId=E,E}if(ne.lastId&&!ee)return ne.lastId;if(!ee)return null;let L=`tool-${p()}`;return T(x,L),L},Pe=O=>{let ee=z.get(O);if(ee)return ee;let w={id:`tool-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:O,status:"pending"}};return z.set(O,w),h(w),w},Xe=O=>{if(typeof O=="number"&&Number.isFinite(O))return O;if(typeof O=="string"){let ee=Number(O);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let w=Date.parse(O);if(!Number.isNaN(w))return w}return Date.now()},Qe=O=>{if(typeof O=="string")return O;if(O==null)return"";try{return JSON.stringify(O)}catch{return String(O)}},We=new Map,nt=new Map,bt=new Map,mt=(O,ee,w)=>{let x=bt.get(O);x||(x=[],bt.set(O,x));let L=0,E=x.length;for(;L<E;){let G=L+E>>>1;x[G].seq<ee?L=G+1:E=G}x[L]?.seq===ee?x[L]={seq:ee,text:w}:x.splice(L,0,{seq:ee,text:w});let B="";for(let G=0;G<x.length;G++)B+=x[G].text;return B},Pn=(O,ee)=>{let w=Qe(ee),x=nt.get(O.id),L=AC(x,w);O.rawContent=L;let E=We.get(O.id),B=le=>{let it=O.content??"";le.trim()!==""&&(it.trim().length===0||le.startsWith(it)||le.trimStart().startsWith(it.trim()))&&(O.content=le)},G=()=>{if(E){let le=E.close?.();le instanceof Promise&&le.catch(()=>{})}We.delete(O.id),nt.delete(O.id),O.streaming=!1,h(O)};if(!E){B(w),G();return}let Q=Di(L);if(Q!==null&&Q.trim()!==""){B(Q),G();return}let K=le=>{let it=typeof le=="string"?le:le?.text??null;if(it!==null&&it.trim()!=="")return it;let et=E.getExtractedText();return et!==null&&et.trim()!==""?et:w},q;try{q=E.processChunk(L)}catch{B(w),G();return}if(q instanceof Promise){q.then(le=>{B(K(le)),G()}).catch(()=>{B(w),G()});return}B(K(q)),G()},Me=null,Ke=(O,ee,w,x)=>{O.rawContent=ee,We.has(O.id)||We.set(O.id,this.createStreamParser());let L=We.get(O.id),E=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(E&&nt.set(O.id,ee),L.__isPlainTextParser===!0){O.content=x!==void 0?ee:O.content+w,nt.delete(O.id),We.delete(O.id),O.rawContent=void 0,h(O);return}let G=L.processChunk(ee);if(G instanceof Promise)G.then(Q=>{let K=typeof Q=="string"?Q:Q?.text??null;K!==null&&K.trim()!==""?(O.content=K,h(O)):!E&&!ee.trim().startsWith("<")&&(O.content=x!==void 0?ee:O.content+w,nt.delete(O.id),We.delete(O.id),O.rawContent=void 0,h(O))}).catch(()=>{O.content=x!==void 0?ee:O.content+w,nt.delete(O.id),We.delete(O.id),O.rawContent=void 0,h(O)});else{let Q=typeof G=="string"?G:G?.text??null;Q!==null&&Q.trim()!==""?(O.content=Q,h(O)):!E&&!ee.trim().startsWith("<")&&(O.content=x!==void 0?ee:O.content+w,nt.delete(O.id),We.delete(O.id),O.rawContent=void 0,h(O))}},ot=(O,ee)=>{let w=ee??O.content;if(w==null||w===""){O.streaming=!1,h(O);return}let L=nt.get(O.id)??Qe(w);O.rawContent=L;let E=We.get(O.id),B=null,G=!1;if(E&&(B=E.getExtractedText(),B===null&&(B=Di(L)),B===null)){let Q=E.processChunk(L);Q instanceof Promise?(G=!0,Q.then(K=>{let q=typeof K=="string"?K:K?.text??null;q!==null&&(O.content=q,O.streaming=!1,We.delete(O.id),nt.delete(O.id),h(O))}).catch(()=>{})):B=typeof Q=="string"?Q:Q?.text??null}if(!G){B!==null&&B.trim()!==""?O.content=B:nt.has(O.id)||(O.content=Qe(w));let Q=We.get(O.id);if(Q){let K=Q.close?.();K instanceof Promise&&K.catch(()=>{}),We.delete(O.id)}nt.delete(O.id),O.streaming=!1,h(O)}},qt=(O,ee,w)=>{let x=W.get(O);if(x)return x;let L={id:`nested-${ee}-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...w?{variant:w}:{},...w==="reasoning"?{reasoning:{id:O,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return W.set(O,L),h(L),L},jt=[],zn,Ye=new Map,Je=0,ht="agent",Qt=!1,io=null,Lt=null,Ho=new Map,zr=this.config.iterationDisplay??"separate";for(zn=()=>{for(let O=0;O<jt.length;O++){let ee=jt[O].payloadType,w=jt[O].payload;if(!Qt&&ht!=="flow"&&typeof w.stepType=="string"&&(ht="flow"),ee==="reasoning_start"){let x=typeof w.id=="string"?w.id:null,L=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(x&&L){S.set(x,L),qt(x,L,"reasoning");continue}let E=re(w,!0)??`reason-${p()}`,B=ae(E);B.reasoning=B.reasoning??{id:E,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Xe(w.startedAt??w.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(B.reasoning.scope=w.scope),B.streaming=!0,B.reasoning.status="streaming",h(B)}else if(ee==="reasoning_delta"){let x=typeof w.id=="string"?w.id:null;if(x&&S.has(x)&&W.has(x)){let G=W.get(x),Q=w.reasoningText??w.text??w.delta??"";Q&&w.hidden!==!0&&G.reasoning&&(G.reasoning.chunks.push(String(Q)),h(G));continue}let L=re(w,!1)??re(w,!0)??`reason-${p()}`,E=ae(L);E.reasoning=E.reasoning??{id:L,status:"streaming",chunks:[]},E.reasoning.startedAt=E.reasoning.startedAt??Xe(w.startedAt??w.timestamp);let B=w.reasoningText??w.text??w.delta??"";if(B&&w.hidden!==!0){let G=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(G!==void 0){let Q=mt(L,G,String(B));E.reasoning.chunks=[Q]}else E.reasoning.chunks.push(String(B))}if(E.reasoning.status=w.done?"complete":"streaming",w.done){E.reasoning.completedAt=Xe(w.completedAt??w.timestamp);let G=E.reasoning.startedAt??Date.now();E.reasoning.durationMs=Math.max(0,(E.reasoning.completedAt??Date.now())-G)}E.streaming=E.reasoning.status!=="complete",h(E)}else if(ee==="reasoning_complete"){let x=typeof w.id=="string"?w.id:null;if(x&&S.has(x)&&W.has(x)){let Q=W.get(x);if(Q.reasoning){let K=typeof w.text=="string"?w.text:"";K&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(K),Q.reasoning.status="complete",Q.streaming=!1,h(Q)}S.delete(x),W.delete(x);continue}let L=re(w,!1)??re(w,!0)??`reason-${p()}`,E=typeof w.text=="string"?w.text:"";!H.get(L)&&(E||w.scope==="loop")&&ae(L);let B=H.get(L);if(B?.reasoning){(w.scope==="loop"||w.scope==="turn")&&(B.reasoning.scope=w.scope),E&&B.reasoning.chunks.length===0&&B.reasoning.chunks.push(E),B.reasoning.status="complete",B.reasoning.completedAt=Xe(w.completedAt??w.timestamp);let Q=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-Q),B.streaming=!1,h(B)}let G=X(w);G&&V.byStep.delete(G)}else if(ee==="tool_start"){b&&(b.streaming=!1,h(b),b=null),typeof w.iteration=="number"&&(Je=w.iteration);let x=(typeof w.toolCallId=="string"?w.toolCallId:void 0)??xe(w,!0)??`tool-${p()}`,L=w.toolName??w.name;if(ve(L)){Z.add(x);continue}T(ue(w),x);let E=Pe(x),B=E.toolCall??{id:x,status:"pending"};B.name=L??B.name,B.status="running",w.parameters!==void 0?B.args=w.parameters:w.args!==void 0&&(B.args=w.args),B.startedAt=B.startedAt??Xe(w.startedAt??w.timestamp),B.completedAt=void 0,B.durationMs=void 0,E.toolCall=B,E.streaming=!0,w.executionId&&(E.agentMetadata={executionId:w.executionId,iteration:w.iteration}),h(E)}else if(ee==="tool_output_delta"){let x=xe(w,!1)??xe(w,!0)??`tool-${p()}`;if(Z.has(x))continue;let L=Pe(x),E=L.toolCall??{id:x,status:"running"};E.startedAt=E.startedAt??Xe(w.startedAt??w.timestamp);let B=w.text??w.delta??w.message??"";B&&(E.chunks=E.chunks??[],E.chunks.push(String(B))),E.status="running",L.toolCall=E,L.streaming=!0;let G=w.agentContext;(G||w.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:G?.executionId??w.executionId,iteration:G?.iteration??w.iteration}),h(L)}else if(ee==="tool_complete"){let x=xe(w,!1)??xe(w,!0)??`tool-${p()}`;if(Z.has(x)){Z.delete(x);continue}let L=Pe(x),E=L.toolCall??{id:x,status:"running"};E.status="complete",w.result!==void 0&&(E.result=w.result),typeof w.duration=="number"&&(E.duration=w.duration),E.completedAt=Xe(w.completedAt??w.timestamp);let B=w.duration??w.executionTime;if(typeof B=="number")E.durationMs=B;else{let K=E.startedAt??Date.now();E.durationMs=Math.max(0,(E.completedAt??Date.now())-K)}L.toolCall=E,L.streaming=!1;let G=w.agentContext;(G||w.executionId)&&(L.agentMetadata=L.agentMetadata??{executionId:G?.executionId??w.executionId,iteration:G?.iteration??w.iteration}),h(L);let Q=ue(w);Q&&ne.byCall.delete(Q)}else if(ee==="await"&&w.toolName){let x=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,L=x??w.toolId??`local-${p()}`,E=Pe(L),B=w.toolName,G=w.origin==="webmcp"&&!gs(B)?`webmcp:${B}`:B,Q=gs(G),K=E.toolCall??{id:L,status:"pending"};K.name=G,K.args=w.parameters,K.status=Q?"running":"complete",K.chunks=K.chunks??[],K.startedAt=K.startedAt??Xe(w.startedAt??w.timestamp??w.awaitedAt),Q?(K.completedAt=void 0,K.duration=void 0,K.durationMs=void 0):K.completedAt=K.completedAt??K.startedAt,E.toolCall=K,E.streaming=!1,E.agentMetadata={...E.agentMetadata,executionId:w.executionId??E.agentMetadata?.executionId,awaitingLocalTool:!0,...x?{webMcpToolCallId:x}:{}},h(E)}else if(ee==="text_start"){let x=typeof w.id=="string"?w.id:null,L=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(x&&L){S.set(x,L);continue}let E=b;E&&(ht==="flow"?(ot(E),Me=E):(E.streaming=!1,h(E)),b=null),I=typeof w.id=="string"?w.id:I,P=""}else if(ee==="text_delta"){let x=typeof w.id=="string"?w.id:null,L=x?S.get(x):void 0;if(x&&L){let B=typeof w.delta=="string"?w.delta:"",G=(R.get(x)??"")+B;if(R.set(x,G),G.trim()==="")continue;let Q=qt(x,L);Q.agentMetadata={...Q.agentMetadata,executionId:w.executionId,parentToolId:L},Ke(Q,G,B,void 0);continue}if(I=typeof w.id=="string"?w.id:I,ht==="flow"){let B=typeof w.delta=="string"?w.delta:"";if(P+=B,P.trim()==="")continue;let G=pe();G.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ke(G,P,B,void 0),A=G;continue}let E=pe();E.content+=w.delta??"",E.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:io??void 0,agentName:Lt?.agentName},A=E,h(E)}else if(ee==="text_complete"){let x=typeof w.id=="string"?w.id:null;if(x&&S.has(x)){let E=W.get(x);E&&ot(E),S.delete(x),R.delete(x),W.delete(x);continue}let L=b;L&&(ht==="flow"?(ot(L),Me=L):((L.content??"")===""&&typeof w.text=="string"&&(L.content=w.text),L.streaming=!1,h(L)),b=null),I=null,P=""}else if(ee==="step_complete"){let x=w.stepType,L=w.executionType;if(x==="tool"||L==="context")continue;if(w.success===!1){let E=w.error,B=typeof E=="string"&&E!==""?E:E!=null&&typeof E=="object"&&Reflect.has(E,"message")?String(E.message??"Step failed"):"Step failed";n({type:"error",error:new Error(B)});let G=b;G&&G.streaming&&(G.streaming=!1,h(G)),n({type:"status",status:"idle"});continue}{let E=Me;Me=null;let B=w.stopReason,G=w.result?.response;if(E)B&&(E.stopReason=B),G!=null?Pn(E,G):E.streaming!==!1&&(We.delete(E.id),nt.delete(E.id),E.streaming=!1,h(E));else{let Q=G!=null&&G!=="";if(Q||B){let K=pe();B&&(K.stopReason=B),Q?ot(K,G):(K.streaming=!1,h(K))}}continue}}else if(ee==="execution_start")ht=w.kind==="flow"?"flow":"agent",Qt=!0,ht==="agent"&&(Lt={executionId:w.executionId,agentId:w.agentId??"virtual",agentName:w.agentName??"",status:"running",currentIteration:0,maxTurns:w.maxTurns??1,startedAt:Xe(w.startedAt)});else if(ee==="turn_start"){let x=typeof w.iteration=="number"?w.iteration:Je;if(x!==Je){if(Lt&&(Lt.currentIteration=x),zr==="separate"&&x>1){let L=b;L&&(L.streaming=!1,h(L),Ho.set(x-1,L),b=null)}Je=x}io=typeof w.id=="string"?w.id:null,A=null}else if(ee==="tool_input_delta"){let x=w.toolCallId??ne.lastId;if(x){let L=z.get(x);L?.toolCall&&(L.toolCall.chunks=L.toolCall.chunks??[],L.toolCall.chunks.push(w.delta??""),h(L))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let x=w.stopReason,L=b??A;if(x&&L!==null){let E=w.id;(!E||L.agentMetadata?.turnId===E)&&(L.stopReason=x,h(L))}io===w.id&&(io=null)}else if(ee==="media_start"){let x=String(w.id);Ye.set(x,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ee==="media_delta"){let x=Ye.get(String(w.id));x&&typeof w.delta=="string"&&x.parts.push(w.delta)}else if(ee==="media_complete"){let x=String(w.id),L=Ye.get(x);Ye.delete(x);let E=(typeof w.mediaType=="string"?w.mediaType:void 0)??L?.mediaType??"application/octet-stream",B=typeof w.data=="string"?w.data:void 0,G=typeof w.url=="string"?w.url:L&&L.parts.length>0?L.parts.join(""):void 0,Q=null;if(B)Q={type:"media",data:B,mediaType:E};else if(G){let it=E.toLowerCase();Q={type:it==="image"||it.startsWith("image/")?"image-url":"file-url",url:G,mediaType:E}}let K=w.toolCallId??L?.toolCallId,q=Q?[Q]:[],le=[];for(let it of q){if(!it||typeof it!="object")continue;let et=it,yt=typeof et.type=="string"?et.type:void 0,me=typeof et.mediaType=="string"?et.mediaType.toLowerCase():"",ye=null,Jt="";if(yt==="media"){let Ne=typeof et.data=="string"?et.data:void 0;if(!Ne)continue;Jt=me.length>0?me:"application/octet-stream",ye=`data:${Jt};base64,${Ne}`}else if(yt==="image-url"){let Ne=typeof et.url=="string"?et.url:void 0;if(!Ne)continue;Jt=me,ye=Ne}else if(yt==="file-url"){let Ne=typeof et.url=="string"?et.url:void 0;if(!Ne)continue;Jt=me,ye=Ne}else continue;if(ye)if(yt==="image-url"||Jt.startsWith("image/"))le.push({type:"image",image:ye,...Jt.includes("/")?{mimeType:Jt}:{}});else if(Jt.startsWith("audio/"))le.push({type:"audio",audio:ye,mimeType:Jt});else if(Jt.startsWith("video/"))le.push({type:"video",video:ye,mimeType:Jt});else{let Ne=Jt||"application/octet-stream";le.push({type:"file",data:ye,mimeType:Ne,filename:CC(Ne)})}}if(le.length>0){let it=p(),et=K,me={id:`agent-media-${typeof et=="string"&&et.length>0?`${et}-${it}`:String(it)}`,role:"assistant",content:"",contentParts:le,createdAt:new Date().toISOString(),streaming:!1,sequence:it,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Je}};h(me);let ye=b;ye&&(ye.streaming=!1,h(ye)),b=null,k.current=null}}else if(ee==="execution_complete"){let x=w.kind??ht;x==="agent"&&Lt&&(Lt.status=w.success?"complete":"error",Lt.completedAt=Xe(w.completedAt),Lt.stopReason=w.stopReason);let L=b;L&&(x==="flow"&&L.streaming!==!1?ot(L):(L.streaming=!1,h(L)),b=null),I=null,P="",Me=null,n({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let x=typeof w.error=="string"?w.error:w.error?.message??"Execution error";n({type:"error",error:new Error(x)})}else if(ee!=="ping"){if(ee==="approval_start"){let x=w.approvalId??`approval-${p()}`,L={id:`approval-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:x,status:"pending",agentId:Lt?.agentId??"virtual",executionId:w.executionId??Lt?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};h(L)}else if(ee==="step_await"&&w.awaitReason==="approval_required"){let x=w.approvalId??`approval-${p()}`,L={id:`approval-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:x,status:"pending",agentId:Lt?.agentId??"virtual",executionId:w.executionId??Lt?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};h(L)}else if(ee==="approval_complete"){let x=w.approvalId;if(x){let E={id:`approval-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:x,status:w.decision??"approved",agentId:Lt?.agentId??"virtual",executionId:w.executionId??Lt?.executionId??"",toolName:w.toolName??"",description:w.description??"",resolvedAt:Date.now()}};h(E)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let x=w.artifactType,L=String(w.id),E=typeof w.title=="string"?w.title:void 0,B=w.file,G;B&&typeof B=="object"&&!Array.isArray(B)&&typeof B.path=="string"&&typeof B.mimeType=="string"&&(G={path:B.path,mimeType:B.mimeType,...typeof B.language=="string"?{language:B.language}:{}}),n({type:"artifact_start",id:L,artifactType:x,title:E,component:typeof w.component=="string"?w.component:void 0,...G?{file:G}:{}});let Q=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?{...w.props}:void 0;if(he.set(L,{markdown:"",title:E,file:G,...Q?{props:Q}:{}}),!Ce.has(L)){Ce.add(L);let K=qo(this.config.features?.artifacts,{artifactType:x,...G?{file:G}:{}}),q=typeof w.component=="string"?w.component:void 0,le={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Li(K,{artifactId:L,title:E,artifactType:x,status:"streaming",...G?{file:G}:{},...q?{component:q}:{}})};de.set(L,le),h(le)}}else if(ee==="artifact_delta"){let x=String(w.id),L=typeof w.delta=="string"?w.delta:String(w.delta??"");n({type:"artifact_delta",id:x,artDelta:L});let E=he.get(x);E&&(E.markdown+=L)}else if(ee==="artifact_update"){let x=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:x,component:typeof w.component=="string"?w.component:void 0});let L=he.get(String(w.id));L&&(L.props={...L.props??{},...x})}else if(ee==="artifact_complete"){let x=String(w.id);n({type:"artifact_complete",id:x});let L=de.get(x);if(L){L.streaming=!1;try{let E=JSON.parse(L.rawContent??"{}");if(E.props){E.props.status="complete";let B=he.get(x);B?.markdown&&(E.props.markdown=B.markdown),B?.file&&(E.props.file=B.file),E.component==="PersonaArtifactInline"&&B?.props&&Object.keys(B.props).length>0&&(E.props.componentProps=B.props)}L.rawContent=JSON.stringify(E)}catch{}he.delete(x),h(L),de.delete(x)}}}else if(ee==="transcript_insert"){let x=w.message;if(!x||typeof x!="object")continue;let L=String(x.id??`msg-${p()}`),E=x.role,G={id:L,role:E==="user"?"user":E==="system"?"system":"assistant",content:typeof x.content=="string"?x.content:"",rawContent:typeof x.rawContent=="string"?x.rawContent:void 0,createdAt:typeof x.createdAt=="string"?x.createdAt:new Date().toISOString(),streaming:x.streaming===!0,...typeof x.variant=="string"?{variant:x.variant}:{},sequence:p()};if(h(G),G.rawContent)try{let K=JSON.parse(G.rawContent)?.props?.artifactId;typeof K=="string"&&Ce.add(K)}catch{}b=null,k.current=null,We.delete(L),nt.delete(L)}else if(ee==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let x=typeof w.error=="string"?w.error:w.error?.message!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(x)});let L=b;L&&L.streaming&&(L.streaming=!1,h(L)),n({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let x=null;if(w.error instanceof Error)x=w.error;else if(ee==="dispatch_error"){let L=w.message??w.error;L!=null&&L!==""&&(x=new Error(String(L)))}else{let L=w.error;typeof L=="string"&&L!==""?x=new Error(L):L!=null&&typeof L=="object"&&Reflect.has(L,"message")&&(x=new Error(String(L.message??L)))}if(x){n({type:"error",error:x});let L=b;L&&L.streaming&&(L.streaming=!1,h(L)),n({type:"status",status:"idle"})}}}}}jt.length=0};;){let{done:O,value:ee}=await i.read();if(O)break;l+=a.decode(ee,{stream:!0});let w=l.split(`
|
|
12
12
|
|
|
13
|
-
`);l=
|
|
14
|
-
`),R="message",q="",$=null;for(let de of L)de.startsWith("event:")?R=de.replace("event:","").trim():de.startsWith("data:")?q+=de.replace("data:","").trim():de.startsWith("id:")&&($=de.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!q){K();continue}let ce;try{ce=JSON.parse(q)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let je=R!=="message"?R:ce.type??"message";if(this.onSSEEvent?.(je,ce),this.parseSSEEvent){T.current=v;let de=await this.handleCustomSSEEvent(ce,n,T,g,c,B);if(T.current&&T.current!==v&&(v=T.current),de){K();continue}}et.push({payloadType:je,payload:ce}),Le(),K()}}Le()}};function Ka(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function kr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function hu(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Lr(e){return{type:"text",text:e}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Yh=["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"],Qn=[...yu,...Yh];function Xh(e){return yu.includes(e)||e.startsWith("image/")}function Ya(e){return Xh(e.type)}async function bu(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ya(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function vu(e,t=Qn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Qh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wu(e,t){let n=Qh(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 xu=16e3,Jh=24e3,Zh=4096,ey=1380533830;function ty(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===ey?new Uint8Array(e,44):new Uint8Array(e)}function ny(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var Ps=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:xu,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(f=>f.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:xu});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Mp(Jh);if(r!==this.callGeneration){u.destroy(),s.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${ny(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let w=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Zh,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let u=l.inputBuffer.getChannelData(0),d=new Int16Array(u.length);for(let c=0;c<u.length;c++){let f=Math.max(-1,Math.min(1,u[c]));d[c]=f<0?f*32768:f*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=ty(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Go=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ps(e.runtype);case"browser":if(!Go.isSupported())throw new Error("Browser speech recognition not supported");return new Go(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Cu(e){if(e?.type==="custom"&&e.custom)return Pr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return Pr({type:"runtype",runtype:e.runtype});if(Go.isSupported())return Pr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function zl(e){try{return Cu(e),!0}catch{return!1}}function Xa(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Ir=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(l=>l.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Xa(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Is=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function jl(e){if(!e)return"";let t=oy(e);return Au(t!==null?t:e)}function oy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Au(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
|
-
`),
|
|
16
|
-
`),
|
|
13
|
+
`);l=w.pop()??"";for(let x of w){let L=x.split(`
|
|
14
|
+
`),E="message",B="",G=null;for(let le of L)le.startsWith("event:")?E=le.replace("event:","").trim():le.startsWith("data:")?B+=le.replace("data:","").trim():le.startsWith("id:")&&(G=le.slice(3).trim());let Q=()=>{G!==null&&G!==""&&n({type:"cursor",id:G})};if(!B){Q();continue}let K;try{K=JSON.parse(B)}catch(le){n({type:"error",error:le instanceof Error?le:new Error("Failed to parse chat stream payload")});continue}let q=E!=="message"?E:K.type??"message";if(this.onSSEEvent?.(q,K),this.parseSSEEvent){k.current=b;let le=await this.handleCustomSSEEvent(K,n,k,h,p,N);if(k.current&&k.current!==b&&(b=k.current),le){Q();continue}}jt.push({payloadType:q,payload:K}),zn(),Q()}}zn()}};function Ll(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function xs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var jm=16e3,SC=24e3,TC=4096,MC=1380533830;function EC(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===MC?new Uint8Array(t,44):new Uint8Array(t)}function kC(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Fi=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let i=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:jm,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){i.getTracks().forEach(g=>g.stop());return}this.mediaStream=i;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:jm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new kg(SC);if(r!==this.callGeneration){d.destroy(),i.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${kC(o)}/ws/agents/${encodeURIComponent(e)}/voice`,p=new WebSocket(u,["runtype.bearer",n]);p.binaryType="arraybuffer",this.ws=p,p.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,i,p,r))},p.onmessage=g=>this.handleMessage(g,r),p.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},p.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let y=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(i){throw this.cleanup(),this.emitError(i),this.emitStatus("error"),i}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let i=e.createMediaStreamSource(n);this.sourceNode=i;let a=e.createScriptProcessor(TC,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),u=new Int16Array(d.length);for(let p=0;p<d.length;p++){let g=Math.max(-1,Math.min(1,d[p]));u[p]=g<0?g*32768:g*32767}o.send(u.buffer)},i.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=EC(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Ir=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(i=>i[0]).map(i=>i.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(i=>i({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function As(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Fi(t.runtype);case"browser":if(!Ir.isSupported())throw new Error("Browser speech recognition not supported");return new Ir(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function zm(t){if(t?.type==="custom"&&t.custom)return As({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return As({type:"runtype",runtype:t.runtype});if(Ir.isSupported())return As({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function np(t){try{return zm(t),!0}catch{return!1}}function Il(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ss=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let a=i.find(l=>l.name===e.voice);a&&(r.voice=a)}else i.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(i):Il(i));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var $i=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function op(t){if(!t)return"";let e=PC(t);return Um(e!==null?e:t)}function PC(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Um(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
|
+
`),e=e.replace(/\n{2,}/g,`
|
|
16
|
+
`),e.trim()}var Vm=null;var rp=()=>Vm?Vm():import("./runtype-tts-entry-UJAEF7NZ.js");var LC=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function IC(t,e){return LC.some(n=>t[n]!==e[n])}var oo=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function sp(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]}),Tu=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Mu=e=>Cr(e)||e===Xn,Qa=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Is(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Cr(n.name)||n.name===Xn&&vo(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ls(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Vl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return zl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=Ir.isSupported()?new Ir({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return Vl().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:u})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new u(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Pr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let u=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=u.id}if(l){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let u=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=u.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!sy(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Ls(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:u,streaming:d=!1,voiceProcessing:c,rawContent:f}=t,g={id:a??(n==="user"?Ka():n==="assistant"?kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...f!==void 0&&{rawContent:f}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:l,id:u,createdAt:d,sequence:c,streaming:f=!1,voiceProcessing:w,rawContent:g}=o,C={id:u??(r==="user"?Ka():r==="assistant"?kr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:u}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...u!==void 0&&{sequence:u}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
18
|
+
_Details: ${n.message}_`:o}var ji=t=>({isError:!0,content:[{type:"text",text:t}]}),qm=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Km=t=>gs(t)||t===Mo,Hl=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new $i(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(gs(n.name)||n.name===Mo&&Yo(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!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.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Ni(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||rp().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 np(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Ss.isSupported()?new Ss({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=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(o&&r&&i)return rp().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let u=new l({host:o,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new d(u,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(a&&n)return i&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=As(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,a,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=d.id}if(l){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=d.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{this.config.voiceRecognition?.onMetrics?.(i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{this.voiceStatus=i,this.voiceActive=i==="listening",this.callbacks.onVoiceStatusChanged?.(i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}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}};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.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new oo("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",i=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(i))throw new Er("unsupported_scope","This history scope is not supported.");return{scope:i}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new oo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let i=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(i!==this.historyOpenEpoch)throw new oo("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(i!==this.historyOpenEpoch)throw l.discard(),new oo("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),i=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let u=this.fetchOlderPage(r,e,a,i).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,u),u}async fetchOlderPage(e,n,o,r){let i=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...i?{beforeCreatedAt:i}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=Oi(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,i=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw i.discard(),new oo("superseded","A later action won");await this.installFreshConversation(i)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new oo("history_unavailable","This history provider cannot update conversations");let i=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:i})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new oo("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new oo("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let i=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===i&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=i,i}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,i=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&i&&r===i){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(g=>g.id)),d=this.messages.some(g=>l.has(g.id)),u=a.messages[0]?.createdAt,p;if(!d)p=a.messages.map(g=>this.ensureSequence(g));else{let g=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(h=>l.has(h.id)||h.id===g?!0:u!==void 0&&h.createdAt<u);p=Oi(y,a.messages).map(h=>this.ensureSequence(h))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let g of a.messages)this.acknowledgedProjections.set(g.id,g.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=_i(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=_i(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(i=>this.acknowledgedProjections.get(i.id)!==i.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:i}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&i&&(this.activeConversationRevision=i),this.clearFinalizedMarker(e,n)}catch(i){if(!o&&this.isTransientProjectionError(i)){await this.finalizeProjections(e,r,!0);return}if(i instanceof Re&&(i.code==="not_found"||i.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof Re?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),i=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(i=>i.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof Re&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o},this.handleEvent);return}catch(i){if(!t.isConversationDeleted(i))throw i;let a=await this.recoverFromDeletedConversation(r);if(!a)throw i;this.recordDispatchedProjections([a]),await this.client.dispatch({messages:[a],signal:n.signal,assistantMessageId:o},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let i=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(i)}else{this.client.clearClientSession();let i=await this.client.initSession();this.bindActivatedSession(i)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!IC(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let i=this.client.getSSEEventCallback();this.config=o,this.client=new Ni(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),i&&this.client.setSSEEventCallback(i)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:i,id:a,createdAt:l,sequence:d,streaming:u=!1,voiceProcessing:p,rawContent:g}=e,h={id:a??(n==="user"?Ll():n==="assistant"?xs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...p!==void 0&&{voiceProcessing:p},...g!==void 0&&{rawContent:g}};return this.upsertMessage(h),h}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 n=[];for(let o of e){let{role:r,content:i,llmContent:a,contentParts:l,id:d,createdAt:u,sequence:p,streaming:g=!1,voiceProcessing:y,rawContent:h}=o,A={id:d??(r==="user"?Ll():r==="assistant"?xs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:i,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...h!==void 0&&{rawContent:h}};n.push(A)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:i,id:a,createdAt:l,sequence:d}=e,u={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let i=r.blocks.join(`
|
|
19
19
|
|
|
20
|
-
`),a=[
|
|
20
|
+
`),a=[i,n].filter(Boolean).join(`
|
|
21
21
|
|
|
22
|
-
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,u=r.contentParts.length>0;if(l){let d=[];s&&d.push(Lr(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(u){let d=[];a&&d.push(Lr(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Ka(),s=kr();this.activeAssistantMessageId=null;let a=n?.contentParts&&hu(n.contentParts)?Ga:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let u=new AbortController;if(this.abortController=u,n?.mentions){let c=this.messages.find(f=>f.id===r)??l;if(await this.applyMentionBundle(c,o,n.mentions.finalize),u.signal.aborted||this.abortController!==u)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:u.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!f){let w=ql(c,this.config.errorMessage);if(w){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:w,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=kr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=ql(r,this.config.errorMessage);if(a){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let u=this.config.approval,d=u&&typeof u=="object"?u.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let f=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}f=c.body}else c instanceof ReadableStream&&(f=c);f?await this.connectStream(f,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,f=Array.isArray(c?.questions)?c.questions:[];if(f.length===1){let w=typeof f[0]?.question=="string"?f[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,u=t.toolCall?.args,d=Array.isArray(u?.questions)?u.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([f,w])=>`${f}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((f,w)=>{let g=typeof f?.question=="string"?f.question:"";if(!g)return;let v=c[g],C=Array.isArray(v)?v.join(", "):typeof v=="string"?v:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let f=await c.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Xn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async u=>{let d=u.toolCall?.name,c=u.toolCall?.id;if(!d||!c)return null;let f=`${t}:${c}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(f),o.push(f);let w=this.markWebMcpToolRunning(u),g=u.agentMetadata?.webMcpToolCallId??d;if(d===Xn)return{dedupeKey:f,resumeKey:g,output:_l(),toolMessage:u,startedAt:w,completedAt:Date.now()};let v=new AbortController;this.webMcpResolveControllers.add(v),r.push(v);let C=this.client.executeWebMcpToolCall(d,u.toolCall?.args,v.signal),T;if(!C)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await C}catch(B){let S=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return S||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(u,Ws(S?"Aborted by cancel()":Tu(B)),w),this.webMcpInflightKeys.delete(f),null}return v.signal.aborted?(this.markWebMcpToolComplete(u,Ws("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:g,output:T,toolMessage:u,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let u={};for(let c of l)u[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,u,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Xn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,Ws("Aborted by cancel()"),c.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of r)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let v=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v))return;this.webMcpInflightKeys.add(v);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(v)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(v)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:u}=l;this.setStreaming(!0);let d=o===Xn,c=t.toolCall?.args,f=d?null:this.client.executeWebMcpToolCall(o,c,u),w="execute",g=a;try{let v;if(d?v=_l():f?v=await f:v={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),u.aborted){this.markWebMcpToolComplete(t,Ws("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,C,v,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,v,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:u})}catch(v){let C=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));(w==="execute"||C||u.aborted)&&this.markWebMcpToolComplete(t,Ws(C||u.aborted?"Aborted by cancel()":Tu(v)),a),C||this.callbacks.onError?.(v instanceof Error?v:new Error(String(v)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=ho(this.config.features?.artifacts,t),r=xs(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=ho(this.config.features?.artifacts,n),s=xs(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>ql(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=kr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=jl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Xa(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=jl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,f=n.approval;a.approval={...c,...f,executionId:f.executionId||c.executionId,toolName:f.toolName||c.toolName,description:f.description||c.description,toolType:f.toolType??c.toolType,reason:f.reason??c.reason,parameters:f.parameters??c.parameters}}let l=n.toolCall?.name,u=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Mu(l)&&u&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${u}:${d}`,f=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,v=r.agentMetadata?.executionId===u&&r.toolCall?.id===d&&g!==void 0&&Mu(g)&&r.toolCall?.status==="complete";(f||w||v)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Ja={allowedTypes:Qn,maxFileSize:10*1024*1024,maxFiles:4};function ay(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function iy(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Rs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ja.allowedTypes,maxFileSize:t.maxFileSize??Ja.maxFileSize,maxFiles:t.maxFiles??Ja.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ja.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=vu(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await bu(n),s=Ya(n)?URL.createObjectURL(n):null,a={id:ay(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ya(t.file),o=b("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=b("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=iy(t.file.type),u=ae(l,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let d=b("span");d.textContent=wu(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Nt=1e5,Za=Nt+1;var ly=8,cy=8,Kl=10,Gl=new WeakMap,Eu=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,dy=e=>{let t=e.getRootNode?.();return Eu(t)?t:e.ownerDocument.body},Yl=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function _t(e){Gl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=ly,viewportPadding:a=cy}=e,l=()=>t.ownerDocument,u=()=>l().defaultView??window,d=null,c=null,f=null,w=!1,g=!1,v=!1,C=()=>(typeof o=="function"?o():o).trim(),T=()=>{f?.(),f=null,d?.remove(),d=null,c=null},B=()=>{if(!d)return;let te=l(),A=u(),G=t.getBoundingClientRect(),Q=d.getBoundingClientRect(),ie=te.documentElement.clientWidth||A.innerWidth,Y=te.documentElement.clientHeight||A.innerHeight,ue=ie-a-Q.width,X=G.left+G.width/2-Q.width/2,ge=Yl(X,a,ue),Z=G.top-a,pe=Y-a-G.bottom,ee=Q.height+s,me=Z>=ee||Z>=pe?"top":"bottom",we=me==="top"?G.top-s-Q.height:G.bottom+s,he=Y-a-Q.height,ke=Yl(we,a,he),Ne=G.left+G.width/2,Ue=Math.max(Kl,Q.width-Kl),Qe=Yl(Ne-ge,Kl,Ue);d.dataset.placement=me,d.style.left=`${ge}px`,d.style.top=`${ke}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Qe}px`)},S=()=>{if(v||!r||d||!t.isConnected)return;let te=C(),A=dy(t);if(!te||!A)return;let G=l(),Q=u();d=G.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Za),c=G.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=te,d.appendChild(c);let ie=G.createElement("span");ie.className="persona-control-tooltip__arrow",d.appendChild(ie),A.appendChild(d),B(),d.dataset.state="open";let Y=()=>{if(!t.isConnected){T();return}c&&(c.textContent=C()),B()};Q.addEventListener("scroll",Y,!0),Q.addEventListener("resize",Y);let ue=t.getRootNode(),X=Eu(ue)?ue:G.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||T()});ge?.observe(X,{childList:!0,subtree:!0}),f=()=>{Q.removeEventListener("scroll",Y,!0),Q.removeEventListener("resize",Y),ge?.disconnect()}},k=()=>{w||g?S():T()},P=()=>{let te=u();(!te.matchMedia||!te.matchMedia("(hover: none)").matches)&&(w=!0,k())},H=()=>{w=!1,k()},F=()=>{g=!0,k()},N=()=>{g=!1,k()},z=te=>{te.key==="Escape"&&(w=!1,g=!1,T())};n.addEventListener("mouseenter",P),n.addEventListener("mouseleave",H),t.addEventListener("focus",F),t.addEventListener("blur",N),t.addEventListener("keydown",z);let j={get isOpen(){return d!==null},show:S,hide:T,reposition:B,destroy:()=>{v||(v=!0,T(),n.removeEventListener("mouseenter",P),n.removeEventListener("mouseleave",H),t.removeEventListener("focus",F),t.removeEventListener("blur",N),t.removeEventListener("keydown",z),Gl.delete(t))}};return Gl.set(t,j),j}function ku(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",u=b("div","persona-send-button-wrapper"),d=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),n()}),u.appendChild(d),_t({anchor:d,trigger:u,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:u}}var{setLoader:aC,load:py}=xr({fallbackImport:()=>import("./context-mentions-BTSTIBFC.js")});var Xl=py;var{setLoader:cC,load:uy}=xr({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var Lu=uy;function Hs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Ee("span",{className:Pn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=ae(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=b("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Ee("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Pu(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Lp(t).filter(k=>k.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(k=>k.sources.some(P=>typeof P.matchCommand=="function")),r=k=>o.some(P=>P.trigger?P.position==="line-start"?k.split(`
|
|
23
|
-
`).some(
|
|
24
|
-
`)[0]).startsWith(P.trigger):!1),s=(k,P)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${k}`,{detail:P}))}catch{}},a=Ee("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,u=null,d=e.textarea,c=null,f=null,w=null,g=null,v=()=>{if(l)return Promise.resolve(l);if(u)return u;let k=Xl().then(P=>(l=P.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:s}),l)).catch(P=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",P),u===k&&(u=null),null));return u=k,k},C=()=>{Lu().then(k=>{let P=k.mountInlineComposer({textarea:e.textarea,renderToken:F=>Hs(F,{render:t.renderMentionToken}),onMentionRemoved:F=>l?.untrackMention(F)});c=P.input,f=P.destroy;let H=d;H.replaceWith(P.element),d=P.element,g={next:P.element,prev:H},w?.(P.element,H),l?l.rebindComposer(P.input):u&&u.then(F=>F?.rebindComposer(P.input))}).catch(k=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",k)})};t.display==="inline"&&C();let T=[],B=new Map;for(let k of n){if(!k.showButton)continue;let P=ku({config:{...t,buttonIconName:k.buttonIconName,buttonTooltipText:k.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{v().then(H=>H?.openMenu(k.trigger))}});T.push(P),B.set(k.trigger,P.button)}let S=(k,P,H)=>{let F=B.get(P);F&&(F.setAttribute("aria-expanded",k?"true":"false"),k?F.setAttribute("aria-controls",H):F.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(k=>k.wrapper),contextRow:a,handleInput:k=>{if(l){l.handleInput();return}if(!kp(k))return;let P=d,H=P.selectionStart??0;Ep(P.value,H,n)&&v().then(F=>F?.handleInput())},handleKeydown:k=>{if(l?.isMenuOpen())return l.handleKeydown(k);if(k.key==="Backspace"&&l?.hasMentions()&&!g){let P=d,H=P.selectionStart===0&&P.selectionEnd===0;if((P.value.length===0||H)&&l.removeLastChip())return k.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async k=>r(k)?(l??await v())?.dispatchInlineCommand(k)??null:null,clear:()=>l?.clear(),prefetch:()=>{Xl().catch(()=>{})},onComposerSwap:k=>{w=k,g&&k(g.next,g.prev)},destroy:()=>{l?.destroy(),f?.();for(let k of T)k.wrapper.remove();a.remove()}}}var Iu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Bs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Iu(s)&&Iu(r)?n[o]=Bs(s,r):n[o]=r}return n}var Jn="min(440px, calc(100vw - 24px))",Ru="440px",fy={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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",size:"32px",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)"},rt={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",launcher:fy,copy:{inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},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};function Wu(e,t){if(!(!e&&!t))return e?t?Bs(e,t):e:t}function ei(e){return e?{...rt,...e,theme:Wu(rt.theme,e.theme),darkTheme:Wu(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,s=rt.features?.scrollBehavior,a=e.features?.scrollBehavior,l=rt.features?.streamAnimation,u=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,f=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},v=l===void 0&&u===void 0?void 0:{...l,...u},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...w!==void 0?{scrollToBottom:w}:{},...g!==void 0?{scrollBehavior:g}:{},...f!==void 0?{artifacts:f}:{},...v!==void 0?{streamAnimation:v}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var ti="16px",ni="transparent",gy={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"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},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"}},my={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"}},hy={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:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Jn,maxWidth:Ru,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:ti,canvasBackground:ni},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{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"}},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"}}};function Qt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Qt(e,o):o}function Hu(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let u=Qt(e,a);u!==void 0&&(t[l]={path:l,value:u,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yy(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 Bu(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Bu(s,r):n[o]=r}return n}function by(e,t){return t?Bu(e,t):e}function Wr(e,t={}){let n={palette:gy,semantic:my,components:hy},o={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:by(n.components,e?.components)};if(t.validate!==!1){let r=yy(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Du(e){let t=Hu(e),n={};for(let[A,G]of Object.entries(t)){let Q=A.replace(/\./g,"-");n[`--persona-${Q}`]=G.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??ti,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ni,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let r=n["--persona-components-introCard-background"],s=n["--persona-components-introCard-shadow"],a=(!r||r==="transparent"||r==="none")&&(!s||s==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=a&&l==="1.5rem"?"1.5rem 0":l,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let u=n["--persona-components-markdown-heading-h1-fontSize"];u&&(n["--persona-md-h1-size"]=u);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let f=n["--persona-components-markdown-heading-h2-fontWeight"];f&&(n["--persona-md-h2-weight"]=f);let w=n["--persona-components-markdown-prose-fontFamily"];w&&w!=="inherit"&&(n["--persona-md-prose-font-family"]=w),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let g=e.components,v=g?.iconButton;v&&(v.background&&(n["--persona-icon-btn-bg"]=v.background),v.border&&(n["--persona-icon-btn-border"]=v.border),v.color&&(n["--persona-icon-btn-color"]=v.color),v.padding&&(n["--persona-icon-btn-padding"]=v.padding),v.borderRadius&&(n["--persona-icon-btn-radius"]=v.borderRadius),v.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=v.hoverBackground),v.hoverColor&&(n["--persona-icon-btn-hover-color"]=v.hoverColor),v.activeBackground&&(n["--persona-icon-btn-active-bg"]=v.activeBackground),v.activeBorder&&(n["--persona-icon-btn-active-border"]=v.activeBorder));let C=g?.labelButton;C&&(C.background&&(n["--persona-label-btn-bg"]=C.background),C.border&&(n["--persona-label-btn-border"]=C.border),C.color&&(n["--persona-label-btn-color"]=C.color),C.padding&&(n["--persona-label-btn-padding"]=C.padding),C.borderRadius&&(n["--persona-label-btn-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-label-btn-hover-bg"]=C.hoverBackground),C.fontSize&&(n["--persona-label-btn-font-size"]=C.fontSize),C.gap&&(n["--persona-label-btn-gap"]=C.gap));let T=g?.toggleGroup;T&&(T.gap&&(n["--persona-toggle-group-gap"]=T.gap),T.borderRadius&&(n["--persona-toggle-group-radius"]=T.borderRadius));let B=g?.artifact;if(B?.toolbar){let A=B.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(B?.tab){let A=B.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(B?.pane){let A=B.pane;if(A.toolbarBackground){let G=Qt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(B?.card){let A=B.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(B?.inline){let A=B.inline;A.background&&(n["--persona-artifact-inline-bg"]=Qt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let S=g?.code;S&&(S.keywordColor&&(n["--persona-code-keyword-color"]=S.keywordColor),S.stringColor&&(n["--persona-code-string-color"]=S.stringColor),S.commentColor&&(n["--persona-code-comment-color"]=S.commentColor),S.numberColor&&(n["--persona-code-number-color"]=S.numberColor),S.tagColor&&(n["--persona-code-tag-color"]=S.tagColor),S.attrColor&&(n["--persona-code-attr-color"]=S.attrColor),S.propertyColor&&(n["--persona-code-property-color"]=S.propertyColor),S.lineNumberColor&&(n["--persona-code-line-number-color"]=S.lineNumberColor),S.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=S.gutterBorderColor),S.background&&(n["--persona-code-bg"]=Qt(e,S.background)??S.background));let k=n["--persona-surface"],P=n["--persona-container"],H=n["--persona-palette-colors-gray-100"]??"#f3f4f6",F=n["--persona-palette-colors-gray-200"]??"#e5e7eb",N=n["--persona-palette-colors-gray-300"]??"#d1d5db",z=!P||P===k,j=z?H:P,te=z?F:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??j,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??te,z&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??N),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??j,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??j,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??j,n}var vy={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"}}},Fu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ql=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",wy=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ql()},Ou=e=>wy(e),xy=e=>Wr(e),Cy=e=>Wr({...e,palette:{...e?.palette,colors:{...vy.colors,...e?.palette?.colors}}},{validate:!1}),Rr=e=>{let t=Ou(e),n=Fu(e?.theme),o=Fu(e?.darkTheme);return t==="dark"?Cy(Bs(n??{},o??{})):xy(n)},Ay=e=>Du(e),Ds=(e,t)=>{let n=Rr(t),o=Ay(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Ou(t))},oi=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ql())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ql());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var xo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function Bn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Nu(e){let t=Bn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function ri(e){if(typeof e!="string")return"";let t=e.indexOf(`
|
|
25
|
-
`);if(
|
|
26
|
-
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function
|
|
27
|
-
`).length,
|
|
28
|
-
`);for(let a=0;a<
|
|
29
|
-
`)),n=b("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Gu(e,t,n){let o=e.length<=Ey?ky(t,n):null,r=o?Dy(e,o):[{type:"plain",value:e}];return Fy(r)}function Dr(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Za)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let T=ae(g.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let C=document.createElement("span");C.textContent=g.label,v.appendChild(C),v.addEventListener("click",T=>{T.stopPropagation(),c(),n(g.id)}),a.appendChild(v)}let l=null;function u(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!o.contains(v.target)&&c()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function f(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:f,destroy:w}}function Wt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=e,u=b("button","persona-icon-btn"+(s?" "+s:""));u.type="button",u.setAttribute("aria-label",n),u.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&u.appendChild(d),a&&u.addEventListener("click",a),l)for(let[c,f]of Object.entries(l))u.setAttribute(c,f);return u}function Qo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:u}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=b("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let w=ae(t,s??14,"currentColor",2);w&&c.appendChild(w)}let f=b("span");if(f.textContent=n,c.appendChild(f),l&&c.addEventListener("click",l),u)for(let[w,g]of Object.entries(u))c.setAttribute(w,g);return c}function ii(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=b("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function u(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let f;c.icon?f=Wt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,u(),o(c.id)}}):(f=b("button","persona-icon-btn"+(c.className?" "+c.className:"")),f.type="button",f.setAttribute("aria-label",c.label),f.title=c.label,f.textContent=c.label,f.addEventListener("click",()=>{a=c.id,u(),o(c.id)})),f.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:f}),s.appendChild(f)}function d(c){a=c,u()}return{element:s,setSelected:d}}function Yu(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:u}=e,d=b("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=b("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let f=ae(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),u&&(d.style.borderRadius=u.borderRadius??"10px",d.style.padding=u.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=u.background??"",d.style.borderColor=u.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=Dr({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",g=>{g.stopPropagation();let v=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",v?"false":"true"),w.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let g=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var li="persona-artifact-custom-action-btn";function Fr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+li+(n?" persona-artifact-doc-copy-btn":"");o=b("button",r)}else{let r="persona-icon-btn "+li+(n?" persona-artifact-doc-icon-btn":"");o=b("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=b("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Qo({icon:e.icon,label:e.label,className:li+(n?" persona-artifact-doc-copy-btn":"")}):o=Wt({icon:e.icon,label:e.label,className:li+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Fs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Xu(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Bn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",u=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Co(n):l==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let w=document.createElement("div");w.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=r;let v=document.createElement("div");if(v.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",v.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,T={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...u?{presentation:u}:{}},B=Br(T,C,"card");Xo(v,B,C)}else s&&Hr(s),v.textContent=d;if(w.append(g,v),c.append(f,w),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let B={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let S of C)try{if(S.visible===void 0||S.visible(B)){let k=Fr(S);k.setAttribute("data-artifact-custom-action",S.id),k.className=`${k.className} persona-flex-shrink-0`,c.append(k)}}catch{}}let T=Qo({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",s),c.append(T)}return c}var ci=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Xu(e,t)});if(l)return l}return Xu(e,t)};var So=new WeakMap;function tc(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=So.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function tf(e){return So.has(e)}function Oy(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Qu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Bn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Co(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Ny(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var Ju=180,_y=240,$y=.8,Uy=300,zy=500,jy="cubic-bezier(0.2, 0, 0, 1)",Zu=240,Vy=.35;function qy(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Ju,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of a)B.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let u=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!u||Math.abs(u-t)<1){l(),r();return}let d=Math.abs(t-u),c=Math.round(Math.min(zy,Math.max(Uy,_y+d*$y))),f=Math.round(c*Vy),w=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=w?w.animate([{opacity:0},{opacity:1}],{duration:Zu,delay:f,easing:"ease-out",fill:"backwards"}):null,v=e.animate([{height:`${t}px`},{height:`${u}px`}],{duration:c,easing:jy});e.style.height=`${u}px`;let C=!1,T=()=>{C||(C=!0,l(),r())};Promise.allSettled([v.finished,g?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,f+Zu)+120)},Ju)}function Ky(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Os="--persona-artifact-inline-body-height";function Gy(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",u=l==="clip"?!1:t?.followOutput!==!1,d,c,f=t?.fadeMask;f===!0?(d=!0,c=!0):f===!1?(d=!1,c=!1):f&&typeof f=="object"?(d=f.top===!0,c=f.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:u,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:g}}function ef(e,t){let n=Oy(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Ky(o),u=o?.inlineActions??[],d=Gy(o),c=d.completeDisplay==="card",f=null,w=n,g=b("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let v=Z=>ci(Ny(Z),t),C=Z=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(Os),g.replaceChildren(v(Z)),So.set(g,pe=>{g.replaceChildren(v(pe))})};if(c&&n.status==="complete")return C(n),g;let T=di(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode}),B=b("div","persona-artifact-inline-body");B.appendChild(T.el);let S=Z=>{let pe=Z.status!=="complete",ee=pe?d.streamingHeight:d.completeHeight,me=typeof ee=="number";me?g.style.setProperty(Os,`${ee}px`):g.style.removeProperty(Os);let we=!!T.el.querySelector(".persona-code-pre"),he=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",we),B.classList.toggle("persona-artifact-inline-body--sized",me&&he),B.classList.toggle("persona-artifact-inline-body--cap",!pe&&!he&&typeof d.completeHeight=="number")},k=n.status,P=(Z,pe)=>{k!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(Os,`${d.completeHeight}px`):g.style.removeProperty(Os),of(B,pe?.suppressTransition?"none":d.transition,Z.id,()=>{T.update(Z),S(Z)})):T.update(Z),S(Z),k=Z.status};S(n);let H=d.overflow==="clip"&&a&&!!n.id;if(H&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Qu(n).title} in panel`)),!r)return g.appendChild(B),So.set(g,P),g;let F=b("div","persona-artifact-inline-chrome");F.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let N=b("div","persona-artifact-inline-chrome-lead"),z=b("span","persona-flex persona-items-center persona-flex-shrink-0"),j=ae("file-text",16,"currentColor",2);j&&z.appendChild(j);let te=b("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),A=b("span","persona-artifact-inline-type");N.append(z,te,A);let G=b("div","persona-artifact-inline-chrome-actions"),Q=b("span","persona-flex persona-items-center persona-gap-1"),ie=()=>f??d.viewMode,Y=l?ii({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ie(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let pe=Z==="source"?"source":"rendered";pe!==ie()&&(f=pe,T.update(w),S(w))}}):null,ue=s?Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ue&&n.id&&ue.setAttribute("data-copy-artifact",n.id);let X=a?Wt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;X&&n.id&&X.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),Y&&G.appendChild(Y.element),ue&&G.appendChild(ue),X&&G.appendChild(X),F.append(N,G),g.append(F,B);let ge=Z=>{let{title:pe,typeLabel:ee}=Qu(Z);te.textContent=pe,te.title=pe,H&&B.setAttribute("aria-label",`Open ${pe} in panel`);let me=Z.status!=="complete";if(me){A.classList.contains("persona-artifact-inline-status")||(A.className="persona-artifact-inline-status",A.removeAttribute("data-preserve-animation"),A.replaceChildren());let we=Br(Z,o,"inline-chrome");Xo(A,we,o)}else Hr(Z.id),A.className="persona-artifact-inline-type",A.removeAttribute("data-preserve-animation"),A.replaceChildren(),A.textContent=ee;if(ue&&ue.classList.toggle("persona-hidden",me),Y){let we=Z.artifactType==="markdown"?Z.file:void 0,he=!1;if(!me&&we&&d.viewMode!=="source"){let ke=Yo(we);ke==="markdown"?he=!0:(ke==="html"||ke==="svg")&&(he=o?.filePreview?.enabled!==!1)}Y.element.classList.toggle("persona-hidden",!he),Y.setSelected(ie())}if(Q.replaceChildren(),!me&&u.length>0){let we=Fs(Z);if(we)for(let he of u)try{if(he.visible===void 0||he.visible(we)){let ke=Fr(he,{documentChrome:!0});ke.setAttribute("data-artifact-custom-action",he.id),ke.classList.add("persona-flex-shrink-0"),Q.appendChild(ke)}}catch{}}};return ge(n),So.set(g,(Z,pe)=>{if(c&&k!=="complete"&&Z.status==="complete"){let ee=g.isConnected?g.getBoundingClientRect().height:0;k="complete";let me=Z,we=!1,he=ke=>{me=ke,we=!0};So.set(g,he),qy(g,ee,{swap:()=>{C(me),we=!1,So.set(g,he)},onSettled:()=>{we?C(me):So.set(g,ke=>{g.replaceChildren(v(ke))})}});return}(Z.status!=="complete"||Z.id!==w.id)&&(f=null),w=Z,P(Z,pe),ge(Z)}),g}var nf=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>ef(e,t)});if(l)return l}return ef(e,t)};var nc=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Zn=new nc;Zn.register("PersonaArtifactCard",ci,{bubbleChrome:!1});Zn.register("PersonaArtifactInline",nf,{bubbleChrome:!1});function Ns(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?ri(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var oc=!1;function Yy(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function of(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||oc||s){o();return}oc=!0;let a=Yy(n);e.style.setProperty("view-transition-name",a);let l=()=>{oc=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Xy="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Qy="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Jy(e){let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Zy(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var eb=220;function tb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function nb(e){return`
|
|
30
|
-
<script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function ob(e,t,n){let o=b("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=b("div","persona-artifact-frame-loading-indicator");r.appendChild($u());let s=null;return n.label!==!1&&(s=b("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function rb(e,t,n,o,r,s){let a=null,l=0,u=!1,d=new Set,c=()=>{d.forEach(k=>clearTimeout(k)),d.clear()},f=(k,P)=>{let H=setTimeout(()=>{d.delete(H),k()},P);d.add(H)},w=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||u)return;let k=ob(r,s,o);a=k.el,e.appendChild(a),l=Date.now(),o.label!==!1&&f(k.revealLabel,o.labelDelayMs)},v=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),f(w,eb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):t.removeEventListener("load",S)},T=()=>{if(u||(u=!0,C(),c(),!a))return;let k=Math.max(0,o.minVisibleMs-(Date.now()-l));k>0?f(v,k):v()};function B(k){if(n===null)return;let P=k.data;!P||P.persona!=="artifact-preview-ready"||P.token!==n||k.source===t.contentWindow&&T()}function S(){let k=P=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>P()):setTimeout(P,0)};k(()=>k(()=>T()))}return f(g,o.delayMs),f(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):t.addEventListener("load",S),()=>{u=!0,c(),C(),w()}}function di(e,t){let{config:n}=t,o=t.registry??Zn,r=t.bodyLayout,s=n.markdown?Ba(n.markdown):null,a=Da(n.sanitize),l=e,u=!1,d=X=>{let ge=Gn()!==null;s&&!ge&&!u&&(u=!0,Ha(()=>ue(l)));let Z=s?s(X):mo(X);return s&&ge&&a?a(Z):Z},c=b("div","persona-artifact-preview-body"),f=null,w=null,g=null,v=()=>{g&&(g(),g=null),f=null,w=null},C=null,T=null,B=null,S=!1,k=()=>{C=null,T=null,B=null,S=!1},P=null,H=null,F=()=>{P=null,H=null},N=40,z=0,j=X=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>X()):setTimeout(X,0),te=X=>X.scrollHeight-X.clientHeight-X.scrollTop<=N,A=X=>{if(!r)return;let ge=X.scrollHeight-X.clientHeight>1,Z=X.scrollHeight-X.clientHeight-X.scrollTop;X.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&X.scrollTop>1),X.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&Z>1)},G=X=>{z||(z=j(()=>{z=0,X.scrollTop=X.scrollHeight,A(X)}))},Q=(X,ge,Z,pe)=>{let ee=!!r,me=Z.id+"|"+(ee?"w":"p");if(!C||B!==me||C.parentElement!==c){v(),F(),c.replaceChildren();let ke=b("pre",Xy+" persona-code-pre"),Ne=b("code","persona-code");if(ke.appendChild(Ne),ee){let Ue=b("div","persona-artifact-source-window");if(Ue.appendChild(ke),c.appendChild(Ue),!(r?.overflow==="clip")&&typeof Ue.addEventListener=="function"){let Oe=()=>Ue.scrollHeight-Ue.clientHeight>1;Ue.addEventListener("scroll",()=>{te(Ue)&&(S=!1),A(Ue)},{passive:!0}),Ue.addEventListener("wheel",_e=>{Oe()&&_e.deltaY<0&&(S=!0)},{passive:!0}),Ue.addEventListener("touchmove",()=>{Oe()&&(S=!0)},{passive:!0})}C=Ue}else c.appendChild(ke),C=ke;T=Ne,B=me}let we=ee?C:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",pe),we.classList.toggle("persona-artifact-source-window--clip",pe&&r?.overflow==="clip"));let he=we?te(we):!0;if(T.replaceChildren(Gu(X,ge?.language,ge?.path)),we){let ke=Z.status!=="complete";pe&&ke&&r?.followOutput&&!S&&he?G(we):ke||(S=!1),A(we)}},ie=X=>{v(),k(),F(),c.replaceChildren();let ge=b("div",Qy);ge.innerHTML=d(X),c.appendChild(ge)},Y=X=>{let ge=X.id,Z=n.features?.artifacts,pe=Br(X,Z,"status-body");if(P&&H===ge&&P.parentElement===c){let we=P.querySelector(".persona-artifact-status-view-text");we&&Xo(we,pe,Z);return}v(),k(),c.replaceChildren();let ee=b("div","persona-artifact-status-view"),me=b("div","persona-artifact-status-view-text");Xo(me,pe,Z),ee.appendChild(me),c.appendChild(ee),P=ee,H=ge},ue=X=>{l=X;let ge=t.resolveViewMode?.(X)??r?.viewMode??"rendered",Z=X.artifactType==="markdown"?X.file:void 0,pe=X.status!=="complete";pe||Hr(X.id);let ee=pe?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&pe){Y(X);return}if(Z){let he=ri(X.markdown??""),ke=Yo(Z),Ne=n.features?.artifacts?.filePreview?.enabled!==!1;if(!pe&&ge==="rendered"&&Ne&&(ke==="html"||ke==="svg")){let Qe=X.id+"\0"+he;if(f&&w===Qe&&f.parentElement===c)return;k(),F(),v(),c.replaceChildren();let Oe=n.features?.artifacts?.filePreview,_e=Oe?.iframeSandbox??"allow-scripts";!Oe?.dangerouslyAllowSameOrigin&&_e.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),_e=_e.split(/\s+/).filter(gt=>gt&>!=="allow-same-origin").join(" "));let Ae=Zy(Oe?.loading),Se=b("div","persona-artifact-frame"),ze=b("iframe","persona-artifact-iframe");ze.setAttribute("sandbox",_e),ze.setAttribute("data-artifact-id",X.id);let Gt=null;Ae.enabled&&Ae.injectReadySignal?(Gt=tb(),ze.srcdoc=he+nb(Gt)):ze.srcdoc=he,Se.appendChild(ze),c.appendChild(Se),Ae.enabled&&(g=rb(Se,ze,Gt,Ae,X.id,n)),f=Se,w=Qe;return}if(v(),!pe&&ke==="markdown"&&ge==="rendered"){ie(he);return}Q(he,{language:Z.language,path:Z.path},X,me);return}if(X.artifactType==="markdown"){if(ge==="source"){v(),Q(X.markdown??"",void 0,X,me);return}ie(X.markdown??"");return}v(),k(),F(),c.replaceChildren();let we=X.component?o.get(X.component):void 0;if(we){let ke={message:{id:X.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Ne=we(X.props??{},ke);if(Ne){c.appendChild(Ne);return}}catch{}}c.appendChild(Jy(X))};return ue(e),{el:c,update(X){ue(X)}}}import{Idiomorph as sb}from"idiomorph";var pi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;sb.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var rf=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var rc={index:-1,draft:""};function sf(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function af(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function lf(){return new Map}function cf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function df(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function pf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function uf(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function ui(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Dn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function eo(e,t){return Dn(e)-e.scrollTop<=t}function fi(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&u&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function gi(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function ff(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function sc(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function gf(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var _s={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ab=["pre","code","a","script","style"],mi=e=>({type:e?.type??_s.type,placeholder:e?.placeholder??_s.placeholder,speed:e?.speed??_s.speed,duration:e?.duration??_s.duration,buffer:e?.buffer??_s.buffer}),ib=[{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"}],hf=new Map;for(let e of ib)hf.set(e.name,e);var Or=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:hf.get(e)??null,hi=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
|
|
31
|
-
`);return s<0?"":e.slice(0,s)}return e},lb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},cb=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},ac=/\s/,db=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},pb=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(ac.test(s[l])){let u=l;for(;u<s.length&&ac.test(s[u]);)u+=1;a.appendChild(o.createTextNode(s.slice(l,u))),l=u}else{let u=o.createElement("span");u.className="persona-stream-word-group";let d=l;for(;d<s.length&&!ac.test(s[d]);)u.appendChild(lb(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(u),l=d}r.replaceChild(a,e)},ub=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let u of l)u&&(/^\s+$/.test(u)?a.appendChild(o.createTextNode(u)):(a.appendChild(cb(o,u,t,n.value)),n.value+=1));r.replaceChild(a,e)},$s=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??ab).map(f=>f.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],u=a.nextNode();for(;u;)db(u,s)||l.push(u),u=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?pb:ub;for(let f of l)c(f,n,d);return r.innerHTML},yi=(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},Us=(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},mf=new WeakMap,fb=(e,t)=>{if(!e.styles)return;let n=mf.get(t);if(n||(n=new Set,mf.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},ic=new WeakMap,gb=(e,t)=>{if(!e.onAttach)return;let n=ic.get(t);if(n||(n=new Map,ic.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},yf=e=>{let t=ic.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},bi=(e,t)=>{fb(e,t),gb(e,t)};function lc(e,t=Nt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var zs=0,To=null;function cc(e=document){if(zs++,zs===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;To={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,zs=Math.max(0,zs-1),zs===0&&To)){let n=e.body,o=e.defaultView??window;n.style.overflow=To.originalOverflow,n.style.position=To.originalPosition,n.style.top=To.originalTop,n.style.width=To.originalWidth,o.scrollTo(0,To.scrollY),To=null}}}var js={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Rt=e=>(e?.launcher?.mountMode??"floating")==="docked",Vs=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",vn=e=>{let t=e?.launcher?.dock;return{side:t?.side??js.side,width:t?.width??js.width,animate:t?.animate??js.animate,reveal:t?.reveal??js.reveal,maxHeight:t?.maxHeight??js.maxHeight}};var dc=e=>e==="followUp"?"follow-up":e,pc=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},mb=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},bf=new WeakSet,hb=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yb=e=>{hb()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},uc=e=>{var S,k,P;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:u,chipsConfig:d,session:c,getTextarea:f,eventTarget:w}=e,g=o==="followUp",v=t.behavior,C=()=>{if(c.isStreaming())return;let H={suggestion:{...t},surface:o,source:r,behavior:v},F=w.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:H,bubbles:!0,composed:!0,cancelable:!0}));if(g&&w.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!F)return;for(let z of u)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let N=f();if(v==="fill"){N.value=t.prompt,N.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),N.focus();return}N.value="",c.sendMessage(t.prompt)},T=()=>{let H=b("button",`persona-suggestion persona-suggestion--${s}`);if(H.type="button",H.disabled=a,H.dataset.suggestionId=t.id,H.dataset.emphasis=t.emphasis,H.dataset.behavior=v,s==="chip"&&(d?.fontFamily&&(H.style.fontFamily=mb(d.fontFamily)),d?.fontWeight&&(H.style.fontWeight=d.fontWeight),d?.paddingX&&(H.style.paddingLeft=d.paddingX,H.style.paddingRight=d.paddingX),d?.paddingY&&(H.style.paddingTop=d.paddingY,H.style.paddingBottom=d.paddingY)),t.icon){let N=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);N&&(N.classList.add("persona-suggestion__icon"),t.iconColor&&(N.style.color=t.iconColor),H.appendChild(N))}let F=b("span","persona-suggestion__copy");if(F.appendChild(Ee("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&F.appendChild(Ee("span",{className:"persona-suggestion__description",text:t.description})),H.appendChild(F),s!=="chip"){let N=ae("arrow-right",16,"currentColor",1.8);N&&(N.classList.add("persona-suggestion__arrow"),H.appendChild(N))}return H.addEventListener("click",C),H},B=null;for(let H of u)if(H.renderSuggestion&&(B=H.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:T,select:C}),B))break;return B??(B=T()),(S=B.dataset).suggestionId||(S.suggestionId=t.id),(k=B.dataset).behavior||(k.behavior=v),(P=B.dataset).emphasis||(P.emphasis=t.emphasis),B instanceof HTMLButtonElement||B.setAttribute("aria-disabled",a?"true":"false"),B},qs=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let f=getComputedStyle(e).direction==="rtl",w=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),g=4,v=w<=g,C=w>=c-g,T=f?!C:!v,B=f?!v:!C;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",B)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",l,{passive:!0});let u=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return u?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),u?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,f,w,g,v,C)=>{e.replaceChildren(),t.length=0,n.length=0;let T=C?.source??"config",B=C?.surface??(T==="config"?"starter":"followUp"),S=B==="followUp",k=C?.variant??"chip",P=C?.behavior??"send",H=C?.overflow??"wrap",F=C?.config??{},N=C?.plugins??[],z=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,j=S?"followUps":"starters";!bf.has(F)&&F.debug===!0&&k!=="chip"&&F.suggestions?.[j]?.overflow!==void 0&&(bf.add(F),console.info(`[persona] suggestions.${j}.overflow applies to the "chip" variant only; the "${k}" variant manages its own stacking.`));let te=ue=>ue.map(pc).filter(X=>X!==null).map(X=>({...X,behavior:X.behavior??P})),A=te(c??[]);N.forEach(ue=>{ue.transformSuggestions&&(A=te(ue.transformSuggestions({suggestions:A.map(X=>({...X})),surface:B,source:T,config:F})))});let G=z===void 0?A:A.slice(0,z);if(!G.length){e.hidden=!0,o=null,s();return}if(!S&&(g??f.getMessages()).some(X=>X.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=dc(B),e.dataset.variant=k,e.dataset.overflow=H;let Q=document.createDocumentFragment(),ie=f.isStreaming();G.forEach((ue,X)=>{let ge=uc({item:ue,index:X,surface:B,source:T,variant:k,streaming:ie,config:F,plugins:N,chipsConfig:v,session:f,getTextarea:()=>w,eventTarget:e});Q.appendChild(ge),n.push(ge),[...ge instanceof HTMLButtonElement?[ge]:[],...Array.from(ge.querySelectorAll("button"))].forEach(pe=>{t.includes(pe)||(pe.disabled=ie,t.push(pe))})}),e.appendChild(Q),a(),l();let Y=JSON.stringify({normalized:G,surface:B,variant:k,source:T});Y!==o&&(o=Y,yb(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(ue=>({...ue})),surface:B,source:T,variant:k},bubbles:!0,composed:!0})),S&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(ue=>ue.prompt)},bubbles:!0,composed:!0})))}}};var ln={"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"};var bb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",vi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=bb,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},l=r??a.closeButtonSize??"32px",u=b("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,f=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Ee("button",{className:Pn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Kt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=ae(f,s,"currentColor",1);return C?(C.style.display="block",v.appendChild(C)):v.textContent=w,u.appendChild(v),_t({anchor:v,trigger:u,text:()=>v.getAttribute("aria-label")??d,enabled:c}),{button:v,wrapper:u}},vb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wi=(e,t={})=>{let{wrapperClassName:n=vb,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},l=o??a.size??"32px",u=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",f=a.borderWidth??"",w=a.borderColor??"",g=a.borderRadius??"",v=a.paddingX??"",C=a.paddingY??"",T=a.tooltipText??"Clear chat",B=a.showTooltip??!0,S=b("div",n),k=!!(f||w),P=Ee("button",{className:Pn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:d||Kt.actionIconColor,backgroundColor:c||void 0,border:k?`${f||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),H=ae(u,r,"currentColor",1);return H&&(H.style.display="block",P.appendChild(H)),S.appendChild(P),_t({anchor:P,trigger:S,text:()=>P.getAttribute("aria-label")??T,enabled:B}),{button:P,wrapper:S}};var Kt={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-action-icon-fg, var(--persona-muted, #9ca3af))"},fc={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)"},wb={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)"},Jo=e=>{let{config:t,showClose:n=!0}=e,o=Ee("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,u=r.headerIconName,d=Ee("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(u){let H=parseFloat(s)||24,F=ae(u,H*.6,"currentColor",1);F?d.replaceChildren(F):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let H=b("img");H.src=t.launcher.iconUrl,H.alt="",H.className="persona-rounded-xl persona-object-cover",H.style.height=s,H.style.width=s,d.replaceChildren(H)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Ee("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Kt.titleColor,...fc}}),w=Ee("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Kt.subtitleColor,...wb}});c.append(f,w),l?o.append(c):o.append(d,c);let g=r.clearChat??{},v=g.enabled??!0,C=g.placement??"inline",T=null,B=null;if(v){let F=wi(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=F.button,B=F.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:P}=vi(t,{showClose:n,wrapperClassName:S});return a!=="top-right"&&o.appendChild(P),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:w,closeButton:k,closeButtonWrapper:P,clearChatButton:T,clearChatButtonWrapper:B}},Ks=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var xb=e=>{let t=Jo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Cb(e,t,n){if(t?.length)for(let o of t){let r=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Kt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ae(o.icon,16,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=b("div","persona-relative");s.appendChild(r);let a=Dr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Ab=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},l=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let u=r?.titleMenu,d,c;if(u)d=Yu({label:a.title??"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,d.style.color=Kt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=b("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Kt.titleColor,Object.assign(c.style,fc),c.textContent=a.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let P=r.onTitleClick;d.addEventListener("click",H=>{H.target.closest("button")||P()}),d.addEventListener("keydown",H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),P())})}let k=r?.titleRowHover;k&&(d.style.borderRadius=k.borderRadius??"10px",d.style.padding=k.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=k.background??"",d.style.borderColor=k.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f=a.closeButtonSize??"32px",w=b("div",""),g=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=f,g.style.width=f,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Kt.actionIconColor;let v=a.closeButtonIconName??"x",C=ae(v,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),w.appendChild(g);let T=b("div","persona-flex persona-items-center persona-gap-1");u||Cb(T,r?.trailingActions,r?.onAction??s),T.appendChild(w),l.appendChild(T);let B=b("div");B.style.display="none";let S=b("span");return S.style.display="none",{header:l,iconHolder:B,headerTitle:c,headerSubtitle:S,closeButton:g,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},vf={default:xb,minimal:Ab},Sb=e=>vf[e]??vf.default,xi=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=b("div");l.style.display="none";let u=b("span"),d=b("span"),c=b("button");c.style.display="none";let f=b("div");return f.style.display="none",{header:a,iconHolder:l,headerTitle:u,headerSubtitle:d,closeButton:c,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Sb(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ci=e=>{let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let u=t.ownerDocument?.defaultView;if(!u?.getComputedStyle)return o;let d=u.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let u=t.style.maxHeight;if(u!==s){let c=parseFloat(u);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let u=Math.min(t.scrollHeight,a());t.style.height=`${u}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:l}},Ai=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",u=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,f=t.size??"40px",w=t.backgroundColor,g=t.textColor,v=b("div","persona-send-button-wrapper"),C=Ee("button",{className:Pn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&w||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),T=null,B=null;if(n){let P=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),H=t.iconStrokeWidth??2,F=g?.trim()||"currentColor";r?(T=ae(r,P,F,H),T?C.appendChild(T):C.textContent=o):C.textContent=o,B=ae(s,P,F,H)}else C.textContent=u;C.setAttribute("aria-label",a),v.appendChild(C),_t({anchor:C,trigger:v,text:()=>C.getAttribute("aria-label")??"",enabled:c});let S="send";return{button:C,wrapper:v,setMode:P=>{if(P===S)return;S=P;let H=P==="stop"?l:a;if(C.setAttribute("aria-label",H),n){if(T&&B){let F=P==="stop"?B:T;C.replaceChildren(F)}}else C.textContent=P==="stop"?d:u}}},Si=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",l=t.iconName??"mic",u=t.iconSize??a,d=parseFloat(u)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,w=b("div","persona-send-button-wrapper"),g=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:u,height:u,minWidth:u,minHeight:u,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=ae(l,d,f||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",w.appendChild(g);let T=t.tooltipText??"Start voice recognition",B=t.showTooltip??!1;return _t({anchor:g,trigger:w,text:()=>g.getAttribute("aria-label")??T,enabled:B}),{button:g,wrapper:w}},Ti=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=b("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Qn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,u=Math.round(l*.6),d=b("div","persona-send-button-wrapper"),c=Ee("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),f=ae(s,u,"currentColor",1.5);f?c.appendChild(f):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let w=t.buttonTooltipText??"Attach file";return _t({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??w}),{button:c,wrapper:d,input:r,previewsContainer:o}},Mi=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=b("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Ei=()=>Ee("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Gs=e=>{let{config:t}=e,n=Ee("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Ei(),r=Ee("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":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ci(t);a();let l=Ai(t),u=Si(t),d=Ti(t),c=Mi(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let f=Ee("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),u&&g.append(u.wrapper),g.append(l.wrapper),f.append(w,g),r.append(f),r.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==u?.button&&v.target!==u?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:w,rightActions:g,setSendButtonMode:l.setMode}};var wf=()=>{let e=Ee("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=ae("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),s=ae("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ki=e=>{let{config:t}=e,n=Ee("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ei(),r=Mi(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Ci(t);s.style.maxHeight="100px",a();let l=Ai(t),u=Si(t),d=Ti(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Ee("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&f.append(d.wrapper);let w=b("div","persona-widget-composer__right-actions persona-pill-composer__right");u&&w.append(u.wrapper),w.append(l.wrapper),c.addEventListener("click",v=>{v.target!==l.button&&v.target!==l.wrapper&&v.target!==u?.button&&v.target!==u?.wrapper&&v.target!==d?.button&&v.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(f,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:u?.button??null,micButtonWrapper:u?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:f,rightActions:w,setSendButtonMode:l.setMode}};var Tb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Mb=(e,t)=>{if(!e)return null;let n=Tb(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Eb=(e,t)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},kb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},gc=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(":"))},mc=320,Sf=320,Lb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Pb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Ib=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Wb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Rb=e=>{if(!e||e.length===0)return null;let t=Ee("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Ee("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=b("span","persona-mention-chip-icon"),s=ae(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Ee("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Hb=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Hs(o.ref,{readonly:!0,render:t}))}return n},xf="\uE000",Cf="\uE001",Bb=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=w=>`${xf}${r}:${w}${Cf}`,a=t.map((w,g)=>w.kind==="text"?w.text:s(g)).join(""),l=n(a);if(!t.every((w,g)=>w.kind==="text"||l.includes(s(g)))){e.replaceChildren(Hb(t,o));return}e.innerHTML=l;let d=new RegExp(`${xf}${r}:(\\d+)${Cf}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let w=c.nextNode();w;w=c.nextNode())f.push(w);for(let w of f){let g=w;for(let v=d.exec(g.data);v;v=d.exec(g.data)){let C=t[Number(v[1])],T=g.splitText(v.index);T.data=T.data.slice(v[0].length),C?.kind==="mention"&&T.parentNode?.insertBefore(Hs(C.ref,{readonly:!0,render:o}),T),g=T}}},Db=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,u)=>{let d=b("img");d.alt=l.alt?.trim()||`Attached image ${u+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${mc}px`,d.style.maxHeight=`${Sf}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),kb(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},Fb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!gc(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ob=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!gc(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${mc}px`,r.style.maxHeight=`${Sf}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Nb=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!gc(o.data))return;let r=b("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ys=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},_b=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Ys};if(t){let r=t(o);if(r!==null)return r}return Ys()},$b=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Af=(e,t,n="div")=>{let o=b(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Xs=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Ub=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let v=b("div");return v.style.display="none",v.id=`actions-${e.id}`,v.setAttribute("data-actions-for",e.id),v}let l=t.visibility??"hover",u=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[u],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${e.id}`,w.setAttribute("data-actions-for",e.id);let g=(v,C,T)=>{let B=Wt({icon:v,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",T),B};return o&&w.appendChild(g("copy","Copy message","copy")),a&&w.appendChild(g("volume-2","Read aloud","read-aloud")),r&&w.appendChild(g("thumbs-up","Upvote","upvote")),s&&w.appendChild(g("thumbs-down","Downvote","downvote")),w},hc=(e,t,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",u=a.avatar,d=a.timestamp,c=u?.show??!1,f=d?.show??!1,w=u?.position??"left",g=d?.position??"below",v=Xs(e.role,l),C=b("div",v.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Lb(e),B=e.content?.trim()??"",k=T.length>0&&B===Ga,P=mi(s?.widgetConfig?.features?.streamAnimation),H=s?.widgetConfig?.features?.streamAnimation?.plugins,F=e.role==="assistant"&&P.type!=="none"?Or(P.type,H):null,N=e.role==="assistant"&&F?.isAnimating?.(e)===!0,z=e.role==="assistant"&&F!==null&&(!!e.streaming||N);z&&F?.bubbleClass&&C.classList.add(F.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),z&&F&&(F.containerClass&&j.classList.add(F.containerClass),j.style.setProperty("--persona-stream-step",`${P.speed}ms`),j.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let te=z?hi(e.content??"",P.buffer,F,e,!!e.streaming):e.content??"",A=()=>{let ee=t({text:te,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&F?.wrap==="char"?$s(ee,"char",e.id,{skipTags:F.skipTags}):z&&F?.wrap==="word"?$s(ee,"word",e.id,{skipTags:F.skipTags}):ee},G=null;if(k?(G=document.createElement("div"),G.innerHTML=A(),G.style.display="none",j.appendChild(G)):e.contentSegments?.length?Bb(j,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):j.innerHTML=A(),z&&F?.useCaret&&!k&&B){let ee=yi(),me=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=me[me.length-1];if(we?.parentNode)we.parentNode.insertBefore(ee,we.nextSibling);else{let he=j.lastElementChild;he?he.appendChild(ee):j.appendChild(ee)}}if(f&&g==="inline"&&e.createdAt){let ee=Af(e,d,"span");ee.classList.add("persona-timestamp-inline");let me=j.lastElementChild;me?me.appendChild(ee):j.appendChild(ee)}if(T.length>0){let ee=Db(T,!k&&!!B,()=>{k&&G&&(G.style.display="")});ee?C.appendChild(ee):k&&G&&(G.style.display="")}let Q=Pb(e);if(Q.length>0){let ee=Fb(Q);ee&&C.appendChild(ee)}let ie=Ib(e);if(ie.length>0){let ee=Ob(ie);ee&&C.appendChild(ee)}let Y=Wb(e);if(Y.length>0){let ee=Nb(Y);ee&&C.appendChild(ee)}let ue=e.contentSegments?.length?null:Rb(e.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(j),f&&g==="below"&&e.createdAt){let ee=Af(e,d);ee.classList.add("persona-mt-1"),C.appendChild(ee)}let X=e.role==="assistant"?Mb(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(te&&te.trim()),me=P.placeholder==="skeleton",we=me&&P.buffer==="line"&ⅇif(ee)we&&C.appendChild(Us());else if(me)C.appendChild(Us());else{let he=_b("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);he&&C.appendChild(he)}}if(X&&e.stopReason&&!e.streaming&&(B||(j.style.display="none"),C.appendChild(Eb(e.stopReason,X))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Ub(e,o,r);C.appendChild(ee)}if(!c||e.role==="system")return C;let Z=b("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),pe=$b(u,e.role);return w==="right"||w==="left"&&e.role==="user"?Z.append(C,pe):Z.append(pe,C),Z};var zb=40,jb=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=ae(t.name,zb);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(Ee("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(Ee("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},Tf=(e,t,n={})=>{let o=Ee("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=b("h2","persona-welcome-title"),s=b("p","persona-welcome-subtitle");return{host:Ee("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)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},Nr=(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)},Pi=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",jb(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Vb="data-persona-welcome-plugin",Mf="data-persona-welcome-overlay",Li="persona-welcome-overlay-active",yc=new WeakMap,Ef=(e,t,n)=>{n.setAttribute(Vb,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Mf,""),e.classList.contains(Li)||(yc.set(e,e.scrollTop),e.classList.add(Li),e.scrollTop=0)},kf=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Mf),e.classList.contains(Li)&&(e.classList.remove(Li),e.scrollTop=yc.get(e)??e.scrollTop,yc.delete(e))},Lf=()=>{let e=Ee("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Ii=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=Ee("div",{className:Xs("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(Ee("div",{className:"persona-flex"},r)),e.hidden=!1},qb=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Pf=(e,t)=>{if(qb()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var Kb="Hello \u{1F44B}",Gb="I can answer questions and help you get things done here.",If=new WeakSet,wn=(e,t)=>!!e&&e[t]!==void 0,Yb=(e,t)=>{!e||e.debug!==!0||!t.length||If.has(e)||(If.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},Zo=e=>{let t=e?.welcome,n=e?.copy,o=wn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":wn(t,"dismiss")?t.dismiss:"never",s=[];return wn(t,"title")&&wn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wn(t,"subtitle")&&wn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wn(t,"variant")&&wn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&wn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&wn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),Yb(e,s),{title:wn(t,"title")?t.title:n?.welcomeTitle??Kb,subtitle:wn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??Gb,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},_r=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var Wf=e=>{let t=e?.launcher?.enabled??!0,n=Rt(e);if(Vs(e)){let c=e?.launcher?.composerBar??{},f=b("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Nt);let w=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",f.appendChild(w);let g=b("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Nt),{wrapper:f,panel:w,pillRoot:g}}if(n){let c=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(f),{wrapper:c,panel:f}}if(!t){let c=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=e?.launcher?.width??"100%";return c.style.width=w,f.style.width="100%",c.appendChild(f),{wrapper:c,panel:f}}let r=e?.launcher??{},s=r.position&&ln[r.position]?ln[r.position]:ln["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Nt);let l=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??Jn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},bc=e=>{let t=Ee("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":dc(e)}});return t.hidden=!0,t},Rf=(e,t)=>{let n=bc("starter"),o=Tf(e,n,{flatShadow:Rt(e)}),r=Zo(e);Pi(o,r),Nr(t,o.host,_r(r,e?.initialMessages));let s=Lf();return Ii(s,r.message,e),{welcome:o,greetingHost:s}},Xb=(e,t)=>{let n=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=vi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let N=wi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=N.button,l=N.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let u=Ee("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Ee("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:f}=Rf(e,d),{host:w,title:g,subtitle:v}=c,C=c.starterSuggestions,T=b("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),B=bc("followUp"),S=xo(e,!0);S&&(T.style.maxWidth=S,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),d.append(w,f,T,B);let k=Ee("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),P=ki({config:e}),{root:H,textNode:F}=wf();return n.append(u,r,d,k),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:T,starterSuggestions:C,transcriptSuggestions:B,composerOverlay:k,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,welcomeHost:w,welcomeIconHolder:c.iconHolder,greetingHost:f,introTitle:g,introSubtitle:v,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:u,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:H,peekTextNode:F}},Hf=(e,t=!0)=>{if(Vs(e))return Xb(e,t);let n=Ee("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?xi(e,o,{showClose:t}):Jo({config:e,showClose:t}),a=Ee("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"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:u}=Rf(e,a),{host:d,title:c,subtitle:f}=l,w=l.starterSuggestions,g=b("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),v=bc("followUp"),C=xo(e,!1);C&&(g.style.maxWidth=C,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),a.append(d,u,g,v);let T=Gs({config:e}),B=e?.layout?.showFooter!==!1;r?Ks(n,s,e):(s.header.style.display="none",Ks(n,s,e)),n.append(a);let S=Ee("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return B||(T.footer.style.display="none"),n.append(T.footer),n.append(S),{container:n,body:a,messagesWrapper:g,starterSuggestions:w,transcriptSuggestions:v,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:d,welcomeIconHolder:l.iconHolder,greetingHost:u,introTitle:c,introSubtitle:f,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var vc=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
22
|
+
`),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=r.contentParts.length>0;if(l){let u=[];i&&u.push(Qo(i)),u.push(...r.contentParts),u.push(...e.contentParts),e.contentParts=u}else if(d){let u=[];a&&u.push(Qo(a)),u.push(...r.contentParts),e.contentParts=u}else i&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Ll(),i=xs();this.activeAssistantMessageId=null;let a=n?.contentParts&&El(n.contentParts)?Cs:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let p=this.messages.find(g=>g.id===r)??l;if(await this.applyMentionBundle(p,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,d,i,r)}catch(p){if(this.status==="resuming"||this.reconnecting)return;let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));if(!g){let y=sp(p,this.config.errorMessage);if(y){let h={id:i,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(p instanceof Error?this.callbacks.onError?.(p):this.callbacks.onError?.(new Error(String(p))))}}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=xs();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let i=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!i){let a=sp(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,i||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let i of this.messages)i.streaming&&i.id!==o&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(i){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(i=>i.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,i={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(p=>p.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:i};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,u=d&&typeof d=="object"?d.onDecision:void 0;try{let p;if(u?p=await u({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):p=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),p){let g=null;if(p instanceof Response){if(!p.ok){let y=await p.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${p.status}`)}g=p.body}else p instanceof ReadableStream&&(g=p);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(p=>p.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,i=e.toolCall?.name;if(!r||!i){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let p=e.toolCall?.args,g=Array.isArray(p?.questions)?p.questions:[];if(g.length===1){let y=typeof g[0]?.question=="string"?g[0].question:"";y&&(a={[y]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,d=e.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=a??{};u.forEach((g,y)=>{let h=typeof g?.question=="string"?g.question:"";if(!h)return;let b=p[h],A=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:h,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[i]:n});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Mo?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),i){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...i},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],i=new AbortController;this.webMcpResolveControllers.add(i),this.setStreaming(!0);let a=await Promise.all(n.map(async d=>{let u=d.toolCall?.name,p=d.toolCall?.id;if(!u||!p)return null;let g=`${e}:${p}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(g),o.push(g);let y=this.markWebMcpToolRunning(d),h=d.agentMetadata?.webMcpToolCallId??u;if(u===Mo)return{dedupeKey:g,resumeKey:h,output:Jd(),toolMessage:d,startedAt:y,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let A=this.client.executeWebMcpToolCall(u,d.toolCall?.args,b.signal),k;if(!A)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await A}catch(N){let I=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return I||this.callbacks.onError?.(N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(d,ji(I?"Aborted by cancel()":qm(N)),y),this.webMcpInflightKeys.delete(g),null}return b.signal.aborted?(this.markWebMcpToolComplete(d,ji("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:h,output:k,toolMessage:d,startedAt:y,completedAt:Date.now()}})),l=[];try{if(l=a.filter(p=>p!==null),l.length===0)return;let d={};for(let p of l)d[p.resumeKey]=p.output;let u=await this.client.resumeFlow(e,d,{signal:i.signal});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of l)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===Mo?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let p of l)this.markWebMcpToolComplete(p.toolMessage,ji("Aborted by cancel()"),p.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(A){this.callbacks.onError?.(A instanceof Error?A:new Error(String(A)))}finally{this.webMcpInflightKeys.delete(b)}return}let i=`${n}:${r}`;if(this.webMcpInflightKeys.has(i)||this.webMcpResolvedKeys.has(i)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(i);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let u=o===Mo,p=e.toolCall?.args,g=u?null:this.client.executeWebMcpToolCall(o,p,d),y="execute",h=a;try{let b;if(u?b=Jd():g?b=await g:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},h=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ji("Aborted by cancel()"),a);return}let A=e.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,A,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(i),this.markWebMcpToolComplete(e,b,a,h,u?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(b){let A=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(y==="execute"||A||d.aborted)&&this.markWebMcpToolComplete(e,ji(A||d.aborted?"Aborted by cancel()":qm(b)),a),A||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(i),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let i=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!i.ok){let a=await i.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${i.status}`)}r?.onHttpOk?.(),i.body?await this.connectStream(i.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){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.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=qo(this.config.features?.artifacts,e),r=Li(o,{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}:{}}),i=this.messages.find(a=>a.id===n);if(i){i.rawContent=r,i.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=qo(this.config.features?.artifacts,n),i=Li(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==i&&(o.rawContent=i,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(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.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-JKIJBHS5.js").then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>sp(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=xs(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(i=>i.role==="assistant"&&i.content&&!i.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=op(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Il(e)}toggleReadAloud(e){let n=this.messages.find(i=>i.id===e);if(!n||n.role!=="assistant")return;let o=op(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,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()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,i)=>{if(i!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let p=r.approval,g=n.approval;a.approval={...p,...g,executionId:g.executionId||p.executionId,toolName:g.toolName||p.toolName,description:g.description||p.description,toolType:g.toolType??p.toolType,reason:g.reason??p.reason,parameters:g.parameters??p.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,u=n.toolCall?.id;if(l&&Km(l)&&d&&u&&n.agentMetadata?.awaitingLocalTool===!0){let p=`${d}:${u}`,g=this.webMcpInflightKeys.has(p),y=this.webMcpResolvedKeys.has(p),h=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===u&&h!==void 0&&Km(h)&&r.toolCall?.status==="complete";(g||y||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),i=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(i)&&r!==i)return r-i;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var Rl={allowedTypes:Eo,maxFileSize:10*1024*1024,maxFiles:4};function HC(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function RC(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var zi=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??Rl.allowedTypes,maxFileSize:e.maxFileSize??Rl.maxFileSize,maxFiles:e.maxFiles??Rl.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Rl.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=km(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Em(n),i=kl(n)?URL.createObjectURL(n):null,a={id:HC(),file:n,previewUrl:i,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(i=>i.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=kl(e.file),o=C("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let a=C("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=C("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=RC(e.file.type),d=ce(l,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let u=C("span");u.textContent=Pm(e.file.type,e.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--persona-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",a.appendChild(u),o.appendChild(a)}let r=C("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let i=ce("x",10,"var(--persona-text-inverse, #ffffff)",2);i?r.appendChild(i):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};var Dt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Yt=1e5,Ts=Yt+1;var WC=8,BC=8,ip=10,Gm=200,Ym=300,Xm=0,Wl=t=>Math.max(0,t);function Qm(t){t.delayMs!==void 0&&(Gm=Wl(t.delayMs)),t.skipDelayMs!==void 0&&(Ym=Wl(t.skipDelayMs))}var DC=()=>Date.now()<Xm,_C=t=>{Xm=t>0?Date.now()+t:0},ap=new WeakMap,Jm=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,OC=t=>{let e=t.getRootNode?.();return Jm(e)?e:t.ownerDocument.body},lp=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),NC=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function Xt(t){ap.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:i=!0,gap:a=WC,viewportPadding:l=BC}=t,d=()=>e.ownerDocument,u=()=>d().defaultView??window,p=null,g=null,y=null,h=null,b,A=!1,k=!1,N=!1,I=()=>(typeof o=="function"?o():o).trim(),P=()=>(typeof r=="function"?r():r??"").trim(),S=()=>Wl(t.delayMs??Gm),W=()=>Wl(t.skipDelayMs??Ym),R=()=>{b!==void 0&&(u().clearTimeout(b),b=void 0)},H=()=>{R();let ae=p!==null;h?.(),h=null,p?.remove(),p=null,g=null,y=null,ae&&_C(W())},z=()=>{if(!p)return;let ae=d(),T=u(),Z=e.getBoundingClientRect(),de=p.getBoundingClientRect(),Ce=ae.documentElement.clientWidth||T.innerWidth,he=ae.documentElement.clientHeight||T.innerHeight,ve=Ce-l-de.width,xe=Z.left+Z.width/2-de.width/2,Pe=lp(xe,l,ve),Xe=Z.top-l,Qe=he-l-Z.bottom,We=de.height+a,nt=Xe>=We||Xe>=Qe?"top":"bottom",bt=nt==="top"?Z.top-a-de.height:Z.bottom+a,mt=he-l-de.height,Pn=lp(bt,l,mt),Me=Z.left+Z.width/2,Ke=Math.max(ip,de.width-ip),ot=lp(Me-Pe,ip,Ke);p.dataset.placement=nt,p.style.left=`${Pe}px`,p.style.top=`${Pn}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${ot}px`)},V=()=>{if(N||!i||p||!e.isConnected)return;let ae=I(),T=OC(e);if(!ae||!T)return;let Z=d(),de=u();p=Z.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ts);let Ce=de.getComputedStyle?.(e);if(Ce){for(let We of NC){let nt=Ce.getPropertyValue(We).trim();nt&&p.style.setProperty(We,nt)}Ce.fontFamily&&(p.style.fontFamily=Ce.fontFamily)}g=Z.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ae,p.appendChild(g);let he=P();he&&(y=Z.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=he,p.appendChild(y));let ve=Z.createElement("span");ve.className="persona-control-tooltip__arrow",p.appendChild(ve),T.appendChild(p),z(),p.dataset.state="open";let xe=()=>{if(!e.isConnected){H();return}g&&(g.textContent=I()),y&&(y.textContent=P()),z()};de.addEventListener("scroll",xe,!0),de.addEventListener("resize",xe);let Pe=e.getRootNode(),Xe=Jm(Pe)?Pe:Z.documentElement,Qe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||H()});Qe?.observe(Xe,{childList:!0,subtree:!0}),h=()=>{de.removeEventListener("scroll",xe,!0),de.removeEventListener("resize",xe),Qe?.disconnect()}},ne=ae=>{if(!(N||p)){if(R(),ae||S()<=0||DC()){V();return}b=u().setTimeout(()=>{b=void 0,V()},S())}},$=()=>{A||k?ne(k):H()},X=()=>{let ae=u();(!ae.matchMedia||!ae.matchMedia("(hover: none)").matches)&&(A=!0,$())},ue=()=>{A=!1,$()},we=()=>{try{k=e.matches(":focus-visible")}catch{k=!0}$()},be=()=>{k=!1,$()},pe=()=>{A=!1,k=!1,H()},J=ae=>{ae.key==="Escape"&&pe()};n.addEventListener("mouseenter",X),n.addEventListener("mouseleave",ue),e.addEventListener("focus",we),e.addEventListener("blur",be),e.addEventListener("keydown",J),e.addEventListener("click",pe);let re={get isOpen(){return p!==null},show:V,hide:H,reposition:z,destroy:()=>{N||(N=!0,H(),n.removeEventListener("mouseenter",X),n.removeEventListener("mouseleave",ue),e.removeEventListener("focus",we),e.removeEventListener("blur",be),e.removeEventListener("keydown",J),e.removeEventListener("click",pe),ap.delete(e))}};return ap.set(e,re),re}function Zm(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,i=Math.round(r*.6),a=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",d=C("div","persona-send-button-wrapper"),u=fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),p=ce(a,i,"currentColor",1.5);return p?u.appendChild(p):u.textContent="+",u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),d.appendChild(u),Xt({anchor:u,trigger:d,text:()=>u.getAttribute("aria-label")??l}),{button:u,wrapper:d}}var{setLoader:XM,load:FC}=no({fallbackImport:()=>import("./context-mentions-MJL6S6P2.js")});var cp=FC;var{setLoader:ZM,load:$C}=no({fallbackImport:()=>import("./context-mentions-inline-TTCN7ZM2.js"),resetOnSetLoader:!0});var eh=$C;function qi(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=fe("span",{className:On("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=ce(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=C("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(fe("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function th(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Ig(e).filter(P=>P.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(P=>P.sources.some(S=>typeof S.matchCommand=="function")),r=P=>o.some(S=>S.trigger?S.position==="line-start"?P.split(`
|
|
23
|
+
`).some(R=>R.startsWith(S.trigger)):(S.position==="anywhere"?P:P.split(`
|
|
24
|
+
`)[0]).startsWith(S.trigger):!1),i=(P,S)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${P}`,{detail:S}))}catch{}},a=fe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,d=null,u=t.textarea,p=null,g=null,y=null,h=null,b=()=>{if(l)return Promise.resolve(l);if(d)return d;let P=cp().then(S=>(l=S.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:p??void 0,anchor:t.anchor,contextRow:a,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:I,emit:i}),l)).catch(S=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",S),d===P&&(d=null),null));return d=P,P},A=()=>{eh().then(P=>{let S=P.mountInlineComposer({textarea:t.textarea,renderToken:R=>qi(R,{render:e.renderMentionToken}),onMentionRemoved:R=>l?.untrackMention(R)});p=S.input,g=S.destroy;let W=u;W.replaceWith(S.element),u=S.element,h={next:S.element,prev:W},y?.(S.element,W),l?l.rebindComposer(S.input):d&&d.then(R=>R?.rebindComposer(S.input))}).catch(P=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",P)})};e.display==="inline"&&A();let k=[],N=new Map;for(let P of n){if(!P.showButton)continue;let S=Zm({config:{...e,buttonIconName:P.buttonIconName,buttonTooltipText:P.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{b().then(W=>W?.openMenu(P.trigger))}});k.push(S),N.set(P.trigger,S.button)}let I=(P,S,W)=>{let R=N.get(S);R&&(R.setAttribute("aria-expanded",P?"true":"false"),P?R.setAttribute("aria-controls",W):R.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(P=>P.wrapper),contextRow:a,handleInput:P=>{if(l){l.handleInput();return}if(!Lg(P))return;let S=u,W=S.selectionStart??0;Pg(S.value,W,n)&&b().then(R=>R?.handleInput())},handleKeydown:P=>{if(l?.isMenuOpen())return l.handleKeydown(P);if(P.key==="Backspace"&&l?.hasMentions()&&!h){let S=u,W=S.selectionStart===0&&S.selectionEnd===0;if((S.value.length===0||W)&&l.removeLastChip())return P.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async P=>r(P)?(l??await b())?.dispatchInlineCommand(P)??null:null,clear:()=>l?.clear(),prefetch:()=>{cp().catch(()=>{})},onComposerSwap:P=>{y=P,h&&P(h.next,h.prev)},destroy:()=>{l?.destroy(),g?.();for(let P of k)P.wrapper.remove();a.remove()}}}var nh=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ms(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let i=n[o];nh(i)&&nh(r)?n[o]=Ms(i,r):n[o]=r}return n}var ko="min(440px, calc(100vw - 24px))",rh="440px",jC={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:ko,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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)"},qe={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:jC,copy:{inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function oh(t,e){if(!(!t&&!e))return t?e?Ms(t,e):t:e}function Bl(t){return t?{...qe,...t,theme:oh(qe.theme,t.theme),darkTheme:oh(qe.darkTheme,t.darkTheme),launcher:{...qe.launcher,...t.launcher,dock:{...qe.launcher?.dock,...t.launcher?.dock},clearChat:{...qe.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...qe.tooltip,...t.tooltip},copy:{...qe.copy,...t.copy},sendButton:{...qe.sendButton,...t.sendButton},statusIndicator:{...qe.statusIndicator,...t.statusIndicator},voiceRecognition:{...qe.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=qe.features?.artifacts,n=t.features?.artifacts,o=qe.features?.scrollToBottom,r=t.features?.scrollToBottom,i=qe.features?.scrollBehavior,a=t.features?.scrollBehavior,l=qe.features?.streamAnimation,d=t.features?.streamAnimation,u=qe.features?.askUserQuestion,p=t.features?.askUserQuestion,g=qe.features?.history,y=t.features?.history,h=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},A=i===void 0&&a===void 0?void 0:{...i,...a},k=l===void 0&&d===void 0?void 0:{...l,...d},N=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},I=g===void 0&&y===void 0?void 0:{...g,...y,copy:{...g?.copy,...y?.copy}};return{...qe.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...A!==void 0?{scrollBehavior:A}:{},...h!==void 0?{artifacts:h}:{},...k!==void 0?{streamAnimation:k}:{},...N!==void 0?{askUserQuestion:N}:{},...I!==void 0?{history:I}:{}}})(),suggestionChips:t.suggestionChips??qe.suggestionChips,suggestionChipsConfig:{...qe.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...qe.layout,...t.layout,header:{...qe.layout?.header,...t.layout?.header},messages:{...qe.layout?.messages,...t.layout?.messages,avatar:{...qe.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...qe.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...qe.layout?.slots,...t.layout?.slots}},markdown:{...qe.markdown,...t.markdown,options:{...qe.markdown?.options,...t.markdown?.options}},messageActions:{...qe.messageActions,...t.messageActions}}:qe}var Dl="16px",_l="transparent",zC={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"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},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"}},UC={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"}},VC={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:ko,maxWidth:rh,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Dl,canvasBackground:_l},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{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"}},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"}}};function cn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?cn(t,o):o}function sh(t){let e={};function n(o,r){for(let[i,a]of Object.entries(o)){let l=`${r}.${i}`;if(typeof a=="string"){let d=cn(t,a);d!==void 0&&(e[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function qC(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function ih(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let i=n[o];i&&typeof i=="object"&&!Array.isArray(i)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=ih(i,r):n[o]=r}return n}function KC(t,e){return e?ih(t,e):t}function Es(t,e={}){let n={palette:zC,semantic:UC,components:VC},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:KC(n.components,t?.components)};if(e.validate!==!1){let r=qC(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(i=>i.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}var dp=t=>t.trim()==="0"?"0px":t;function ah(t){let e=sh(t),n={};for(let[T,Z]of Object.entries(e)){let de=T.replace(/\./g,"-");n[`--persona-${de}`]=Z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-surface"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-primary"];let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Dl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??_l,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"];let r=n["--persona-header-bg"],i=n["--persona-components-header-foreground"],a=i?`color-mix(in srgb, ${i} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(i?`color-mix(in srgb, ${i} 14%, ${r})`:void 0)??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??i??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],n["--persona-header-control-size"]=n["--persona-components-header-controlSize"]??"32px",n["--persona-header-control-icon-size"]=n["--persona-components-header-controlIconSize"]??"20px";let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[T,Z]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${T}`];de&&(n[`--persona-history-overlay-${Z}`]=de)}for(let[T,Z]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${T}`];de&&(n[`--persona-history-menu-${Z}`]=de)}let g=t.components?.history?.motion;if(g){let T=Ce=>{if(Ce===void 0)return;let he=String(Ce).trim();return/^\d+(\.\d+)?$/.test(he)?`${he}ms`:he},Z=T(g.enterDurationMs);Z!==void 0&&(n["--persona-history-enter-ms"]=Z);let de=T(g.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let T of["scrim","shadow"]){let Z=n[`--persona-components-history-confirm-${T}`];Z&&(n[`--persona-history-confirm-${T}`]=Z)}for(let[T,Z]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${T}`];de&&(n[`--persona-tooltip-${Z}`]=de)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[T,Z]of[["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${T}`];de&&(n[`--persona-message-action-${Z}`]=de)}n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let h=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],A=(!h||h==="transparent"||h==="none")&&(!b||b==="none"),k=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=A&&k==="1.5rem"?"1.5rem 0":k,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let N=n["--persona-components-markdown-heading-h1-fontSize"];N&&(n["--persona-md-h1-size"]=N);let I=n["--persona-components-markdown-heading-h1-fontWeight"];I&&(n["--persona-md-h1-weight"]=I);let P=n["--persona-components-markdown-heading-h2-fontSize"];P&&(n["--persona-md-h2-size"]=P);let S=n["--persona-components-markdown-heading-h2-fontWeight"];S&&(n["--persona-md-h2-weight"]=S);let W=n["--persona-components-markdown-prose-fontFamily"];W&&W!=="inherit"&&(n["--persona-md-prose-font-family"]=W),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let R=t.components,H=R?.iconButton;H&&(H.background&&(n["--persona-icon-btn-bg"]=H.background),H.border&&(n["--persona-icon-btn-border"]=H.border),H.color&&(n["--persona-icon-btn-color"]=H.color),H.padding&&(n["--persona-icon-btn-padding"]=H.padding),H.borderRadius&&(n["--persona-icon-btn-radius"]=H.borderRadius),H.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=H.hoverBackground),H.hoverColor&&(n["--persona-icon-btn-hover-color"]=H.hoverColor),H.activeBackground&&(n["--persona-icon-btn-active-bg"]=H.activeBackground),H.activeBorder&&(n["--persona-icon-btn-active-border"]=H.activeBorder));let z=R?.labelButton;z&&(z.background&&(n["--persona-label-btn-bg"]=z.background),z.border&&(n["--persona-label-btn-border"]=z.border),z.color&&(n["--persona-label-btn-color"]=z.color),z.padding&&(n["--persona-label-btn-padding"]=z.padding),z.borderRadius&&(n["--persona-label-btn-radius"]=z.borderRadius),z.hoverBackground&&(n["--persona-label-btn-hover-bg"]=z.hoverBackground),z.fontSize&&(n["--persona-label-btn-font-size"]=z.fontSize),z.gap&&(n["--persona-label-btn-gap"]=z.gap));let V=R?.toggleGroup;V&&(V.gap&&(n["--persona-toggle-group-gap"]=V.gap),V.borderRadius&&(n["--persona-toggle-group-radius"]=V.borderRadius));let ne=R?.artifact;if(ne?.toolbar){let T=ne.toolbar;T.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=T.iconHoverColor),T.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=T.iconHoverBackground),T.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=T.iconPadding),T.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=T.iconBorderRadius),T.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=T.iconBorder),T.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=dp(T.toggleGroupGap)),T.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=T.toggleBorderRadius),T.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=dp(T.toggleGroupPadding)),T.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=T.toggleGroupBorder),T.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=T.toggleGroupBorderRadius),T.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=cn(t,T.toggleGroupBackground)??T.toggleGroupBackground),T.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=T.copyBackground),T.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=T.copyBorder),T.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=T.copyColor),T.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=dp(T.copyBorderRadius)),T.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=T.copyPadding),T.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=T.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??T.copyMenuBackground),T.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=T.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??T.copyMenuBorder),T.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=T.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??T.copyMenuShadow),T.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=T.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??T.copyMenuBorderRadius),T.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=T.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??T.copyMenuItemHoverBackground),T.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=T.iconBackground),T.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=T.toolbarBorder)}if(ne?.tab){let T=ne.tab;T.background&&(n["--persona-artifact-tab-bg"]=T.background),T.activeBackground&&(n["--persona-artifact-tab-active-bg"]=T.activeBackground),T.activeBorder&&(n["--persona-artifact-tab-active-border"]=T.activeBorder),T.borderRadius&&(n["--persona-artifact-tab-radius"]=T.borderRadius),T.textColor&&(n["--persona-artifact-tab-color"]=T.textColor),T.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=T.hoverBackground),T.listBackground&&(n["--persona-artifact-tab-list-bg"]=T.listBackground),T.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=T.listBorderColor),T.listPadding&&(n["--persona-artifact-tab-list-padding"]=T.listPadding)}if(ne?.pane){let T=ne.pane;if(T.toolbarBackground){let Z=cn(t,T.toolbarBackground)??T.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Z}}if(ne?.card){let T=ne.card;T.background&&(n["--persona-artifact-card-bg"]=T.background),T.border&&(n["--persona-artifact-card-border"]=T.border),T.borderRadius&&(n["--persona-artifact-card-radius"]=T.borderRadius),T.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=T.hoverBackground),T.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=T.hoverBorderColor)}if(ne?.inline){let T=ne.inline;T.background&&(n["--persona-artifact-inline-bg"]=cn(t,T.background)??T.background),T.border&&(n["--persona-artifact-inline-border"]=T.border),T.borderRadius&&(n["--persona-artifact-inline-radius"]=T.borderRadius),T.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=cn(t,T.chromeBackground)??T.chromeBackground),T.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=cn(t,T.chromeBorder)??T.chromeBorder),T.titleColor&&(n["--persona-artifact-inline-title-color"]=cn(t,T.titleColor)??T.titleColor),T.mutedColor&&(n["--persona-artifact-inline-muted-color"]=cn(t,T.mutedColor)??T.mutedColor),T.frameHeight&&(n["--persona-artifact-inline-frame-height"]=T.frameHeight)}let $=R?.code;$&&($.keywordColor&&(n["--persona-code-keyword-color"]=$.keywordColor),$.stringColor&&(n["--persona-code-string-color"]=$.stringColor),$.commentColor&&(n["--persona-code-comment-color"]=$.commentColor),$.numberColor&&(n["--persona-code-number-color"]=$.numberColor),$.tagColor&&(n["--persona-code-tag-color"]=$.tagColor),$.attrColor&&(n["--persona-code-attr-color"]=$.attrColor),$.propertyColor&&(n["--persona-code-property-color"]=$.propertyColor),$.lineNumberColor&&(n["--persona-code-line-number-color"]=$.lineNumberColor),$.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=$.gutterBorderColor),$.background&&(n["--persona-code-bg"]=cn(t,$.background)??$.background));let X=n["--persona-surface"],ue=n["--persona-container"],we=n["--persona-palette-colors-gray-100"]??"#f3f4f6",be=n["--persona-palette-colors-gray-200"]??"#e5e7eb",pe=n["--persona-palette-colors-gray-300"]??"#d1d5db",J=!ue||ue===X,re=J?we:ue,ae=J?be:ue;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??re,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ae,J&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??pe),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??re,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??re,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??re,n}var GC={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"}}},YC={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},lh=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},pp=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",XC=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":pp()},ch=t=>XC(t),QC=t=>Es(t),JC=t=>{let e=Ms(YC,t??{})??{};return Es({...e,palette:{...e.palette,colors:{...GC.colors,...e.palette?.colors}}},{validate:!1})},ks=t=>{let e=ch(t),n=lh(t?.theme),o=lh(t?.darkTheme);return e==="dark"?JC(Ms(n??{},o??{})):QC(n)},ZC=t=>ah(t),Ki=(t,e)=>{let n=ks(e),o=ZC(n);for(let[r,i]of Object.entries(o))t.style.setProperty(r,i);t.setAttribute("data-persona-color-scheme",ch(e))},Ol=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(pp())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(pp());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};var Jo=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var dh=null;var up=()=>{if(dh!==null)return dh;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},ex="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",Nl=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Fl=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return Nl("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(Nl("unsupported",t),null):(n==="space"&&(o.key=" "),o)},tx=t=>ex.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),ph=(t,e)=>{let n=Fl(t);if(!n)return"";let o=up(),r=tx(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let i=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&i.push("Alt"),n.shift&&i.push("Shift"),i.push(r),i.join("+")},$l=t=>ph(t,!1),Gi=t=>ph(t,!0),nx=(t,e)=>e.key?.toLowerCase()===t.key&&(up()?e.metaKey:e.ctrlKey)===t.mod&&!(up()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,ox=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},uh=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(i,a)=>{if((i.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=i=>{if(i.isComposing||!e.size)return;let a=i.composedPath?.()[0]??i.target;for(let l of e.values())if(nx(l.parsed,i)&&l.when?.()!==!1&&o(l,i)&&!(!l.allowInInput&&ox(a))){i.preventDefault();try{l.run(i)}catch(d){Nl(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(i){let a=Fl(i.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(Nl(`${d.id} already owns`,i.combo),()=>{}):(e.set(l,{...i,parsed:a}),i.element?.setAttribute("aria-keyshortcuts",Gi(i.combo)),()=>{e.get(l)?.id===i.id&&e.delete(l),i.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};function ro(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function fh(t){let e=ro(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function jl(t){if(typeof t!="string")return"";let e=t.indexOf(`
|
|
25
|
+
`);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
|
|
26
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Hr(t){let e=fh(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Zo(t){switch(Hr(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=fh(t.path);return e?e.toUpperCase():"File"}}}function zl(t){let e=t.markdown??"";return t.file?{filename:ro(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:jl(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function Ul(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}var fp="http://www.w3.org/2000/svg";function gh(t){let e=document.createElementNS(fp,"svg");e.setAttribute("class",On("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(fp,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(fp,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var er=(t,e,n)=>{let o=n;for(let r of e){let i=C("span","persona-tool-char");i.style.setProperty("--char-index",String(o)),i.textContent=r===" "?"\xA0":r,t.appendChild(i),o++}return o};function mh(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),er(t,e,0)}var gp="persona-artifact-status-label",hh="persona-artifact-status-detail",yh="data-artifact-status-label",mp=new Map,bh=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Ps(t){t&&mp.delete(t)}function rx(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Zo(e):t.artifactType==="component"?"Component":"Document"}function Ls(t,e,n){let o=rx(t),r=`Generating ${o.toLowerCase()}...`,i=e?.statusLabel;if(typeof i=="string")return{label:i};if(typeof i!="function")return{label:r};let a=t.id,l=mp.get(a);t.status!=="complete"&&l===void 0&&(l=bh(),mp.set(a,l));let d=l===void 0?0:Math.max(0,bh()-l),u=t.artifactType==="component",p=!u&&typeof t.markdown=="string"?t.markdown:"",g=u?0:p.length,y=u||p===""?0:p.split(`
|
|
27
|
+
`).length,h=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:h,chars:g,lines:y,elapsedMs:d,content:()=>u?"":p,surface:n};try{let A=i(b);return typeof A=="string"?{label:A}:A&&typeof A=="object"&&typeof A.label=="string"?{label:A.label,detail:typeof A.detail=="string"?A.detail:void 0}:{label:r}}catch{return{label:r}}}function sx(t){t.className=gp,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function Rr(t,e,n){let o=t.querySelector(`:scope > .${gp}`);o||(o=C("span",gp),t.appendChild(o)),o.getAttribute(yh)!==e.label&&(sx(o),mh(o,e.label,n),o.setAttribute(yh,e.label));let r=t.querySelector(`:scope > .${hh}`),i=e.detail;i?(r||(r=C("span",hh),t.appendChild(r)),r.textContent!==i&&(r.textContent=i)):r&&r.remove()}var ix={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},ax=15e4,Vl={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function lx(t,e){let n=(t||"").trim().toLowerCase();if(n&&Vl[n])return Vl[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Vl[r])return Vl[r]}}return null}function ql(t,e){let n=[],o=0,r=0,i=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let d=l.re.exec(t);if(d&&d.index===o&&d[0].length>0){i(o);let u=l.map?l.map(d[0]):l.type;n.push({type:u,value:d[0]}),o+=d[0].length,r=o,a=!0;break}}a||(o+=1)}return i(t.length),n}var cx=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),dx=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>cx.has(t)?"keyword":"plain"}];function vh(t){return ql(t,dx)}var px=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function ux(t){let e=ql(t,px);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var fx=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function wh(t){let e=ql(t,fx),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let i=r.value.replace(/\s+$/,"");i&&(n=i[i.length-1])}return e}var gx=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function mx(t){let e=[],n=(i,a)=>{a&&e.push({type:i,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,d=t.slice(r,l);for(let p of ql(d,gx))e.push(p);r=l;let u=/^<\s*(script|style)\b/i.exec(d);if(u&&!/\/>\s*$/.test(d)){let p=u[1].toLowerCase(),y=new RegExp("</\\s*"+p+"\\s*>","i").exec(t.slice(r)),h=y?r+y.index:o,b=t.slice(r,h),A=p==="script"?vh(b):wh(b);for(let k of A)e.push(k);r=h}continue}let i=t.indexOf("<",r);if(i===r)n("plain",t[r]),r+=1;else{let a=i===-1?o:i;n("plain",t.slice(r,a)),r=a}}return e}function hx(t,e){switch(e){case"html":return mx(t);case"css":return wh(t);case"js":return vh(t);case"json":return ux(t)}}function yx(t){let e=Eg(),n=C("span","persona-code-line"),o=(r,i)=>{if(!i)return;let a=ix[r];if(a){let l=C("span",a);l.textContent=i,n.appendChild(l)}else n.appendChild(document.createTextNode(i))};for(let r of t){let i=r.value.split(`
|
|
28
|
+
`);for(let a=0;a<i.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
|
|
29
|
+
`)),n=C("span","persona-code-line")),o(r.type,i[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Ch(t,e,n){let o=t.length<=ax?lx(e,n):null,r=o?hx(t,o):[{type:"plain",value:t}];return yx(r)}function Yi(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:i,onOpenChange:a}=t,l=C("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),i?(l.style.position="fixed",l.style.zIndex=String(Ts)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of e){if(b.dividerBefore){let N=document.createElement("hr");l.appendChild(N)}let A=document.createElement("button");if(A.type="button",A.setAttribute("role","menuitem"),A.setAttribute("data-dropdown-item-id",b.id),b.destructive&&A.setAttribute("data-destructive",""),b.icon){let N=ce(b.icon,16,"currentColor",1.5);N&&A.appendChild(N)}let k=document.createElement("span");k.textContent=b.label,A.appendChild(k),A.addEventListener("click",N=>{N.stopPropagation(),g(),n(b.id)}),l.appendChild(A)}let d=null;function u(){if(!i)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function p(){let b=l.classList.contains("persona-hidden");u(),l.classList.remove("persona-hidden"),b&&a?.(!0),requestAnimationFrame(()=>{let A=k=>{!l.contains(k.target)&&!o.contains(k.target)&&g()};document.addEventListener("click",A,!0),d=()=>document.removeEventListener("click",A,!0)})}function g(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&a?.(!1)}function y(){l.classList.contains("persona-hidden")?p():g()}function h(){g(),l.remove()}return i&&i.appendChild(l),{element:l,show:p,hide:g,toggle:y,destroy:h}}function _t(t){let{icon:e,label:n,size:o,strokeWidth:r,className:i,onClick:a,aria:l}=t,d=C("button","persona-icon-btn"+(i?" "+i:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let u=ce(e,o??16,"currentColor",r??2);if(u&&d.appendChild(u),a&&d.addEventListener("click",a),l)for(let[p,g]of Object.entries(l))d.setAttribute(p,g);return d}function Wr(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:i,className:a,onClick:l,aria:d}=t,u="persona-label-btn";o!=="default"&&(u+=" persona-label-btn--"+o),u+=" persona-label-btn--"+r,a&&(u+=" "+a);let p=C("button",u);if(p.type="button",p.setAttribute("aria-label",n),e){let y=ce(e,i??14,"currentColor",2);y&&p.appendChild(y)}let g=C("span");if(g.textContent=n,p.appendChild(g),l&&p.addEventListener("click",l),d)for(let[y,h]of Object.entries(d))p.setAttribute(y,h);return p}function Kl(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,i=C("div","persona-toggle-group"+(r?" "+r:""));i.setAttribute("role","group");let a=n,l=[];function d(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of e){let g;p.icon?g=_t({icon:p.icon,label:p.label,className:p.className,onClick:()=>{a=p.id,d(),o(p.id)}}):(g=C("button","persona-icon-btn"+(p.className?" "+p.className:"")),g.type="button",g.setAttribute("aria-label",p.label),g.title=p.label,g.textContent=p.label,g.addEventListener("click",()=>{a=p.id,d(),o(p.id)})),g.setAttribute("aria-pressed",p.id===a?"true":"false"),l.push({id:p.id,btn:g}),i.appendChild(g)}function u(p){a=p,d()}return{element:i,setSelected:u}}function xh(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:i,onSelect:a,onPrimary:l,position:d="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:g,className:y,primaryClassName:h,chevronClassName:b}=t,A=C("div","persona-split-btn"+(y?" "+y:"")),k={label:e,className:"persona-split-btn-primary"+(h?" "+h:""),onClick:l},N=r&&n?_t({...k,icon:n,size:o??14}):Wr({...k,icon:n,iconSize:o??14}),I=_t({icon:"chevron-down",label:p,size:g??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});A.append(N,I);let P=null,S=()=>{if(P)return P;let W=(typeof u=="function"?u():u)??void 0;return P=Yi({items:i,onSelect:a,anchor:A,position:d,portal:W,onOpenChange:R=>{I.setAttribute("aria-expanded",R?"true":"false")}}),W||A.appendChild(P.element),P};return A.isConnected?S():requestAnimationFrame(()=>{P||S()}),I.addEventListener("click",W=>{W.stopPropagation(),S().toggle()}),{element:A,primaryButton:N,chevronButton:I,openMenu:()=>S().show(),closeMenu:()=>P?.hide(),toggleMenu:()=>S().toggle(),destroy:()=>{P?.destroy(),A.remove()}}}function Ah(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:i="bottom-left",portal:a,className:l,hover:d}=t,u=C("div","persona-combo-btn"+(l?" "+l:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",e);let p=C("span","persona-combo-btn-label");p.textContent=e,u.appendChild(p);let g=ce(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",u.appendChild(g)),d&&(u.style.borderRadius=d.borderRadius??"10px",u.style.padding=d.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=d.background??"",u.style.borderColor=d.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let y=Yi({items:o,onSelect:b=>{u.setAttribute("aria-expanded","false"),r(b)},anchor:u,position:i,portal:a});a||u.appendChild(y.element);let h=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",b=>{if(b.stopPropagation(),h())return;let A=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",A?"false":"true"),y.toggle()}),u.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u.click())}),{element:u,setLabel:b=>{p.textContent=b,u.setAttribute("aria-label",b)},open:()=>{u.setAttribute("aria-expanded","true"),y.show()},close:()=>{u.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let b=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",b?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),u.remove()}}}var Gl="persona-artifact-custom-action-btn";function Is(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+Gl+(n?" persona-artifact-doc-copy-btn":"");o=C("button",r)}else{let r="persona-icon-btn "+Gl+(n?" persona-artifact-doc-icon-btn":"");o=C("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=C("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Wr({icon:t.icon,label:t.label,className:Gl+(n?" persona-artifact-doc-copy-btn":"")}):o=_t({icon:t.icon,label:t.label,className:Gl+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Xi(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function Sh(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?ro(n.path):o,i=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",d=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,u=n?Zo(n):l==="component"?"Component":"Document",p=document.createElement("div");p.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",`Open ${r} in artifact panel`),i&&p.setAttribute("data-open-artifact",i);let g=document.createElement("div");g.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-muted, #9ca3af)",g.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let y=document.createElement("div");y.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let h=document.createElement("div");h.className="persona-truncate persona-text-sm persona-font-medium",h.style.color="var(--persona-text, #1f2937)",h.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let A=e?.config?.features?.artifacts,k={id:i,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},N=Ls(k,A,"card");Rr(b,N,A)}else i&&Ps(i),b.textContent=u;if(y.append(h,b),p.append(g,y),a==="complete"){let A=e?.config?.features?.artifacts?.cardActions;if(A&&A.length>0){let N={artifactId:i||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let I of A)try{if(I.visible===void 0||I.visible(N)){let P=Is(I);P.setAttribute("data-artifact-custom-action",I.id),P.className=`${P.className} persona-flex-shrink-0`,p.append(P)}}catch{}}let k=Wr({label:"Download",className:"persona-flex-shrink-0"});k.title=`Download ${r}`,k.setAttribute("data-download-artifact",i),p.append(k)}return p}var Yl=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",i=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:i},config:e.config,defaultRenderer:()=>Sh(t,e)});if(l)return l}return Sh(t,e)};var tr=new WeakMap;function hp(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let i=tr.get(r);if(!i)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&i(a,n)})}function Ph(t){return tr.has(t)}function bx(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let i=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...i?{file:i}:{},...r?{presentation:r}:{}}}function Th(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?ro(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Zo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function vx(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var Mh=180,wx=240,Cx=.8,xx=300,Ax=500,Sx="cubic-bezier(0.2, 0, 0, 1)",Eh=240,Tx=.35;function Mx(t,e,n){let{swap:o,onSettled:r}=n,i=!1;try{i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{i=!1}if(!e||!t.isConnected||i||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Mh,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let N of a)N.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let d=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!d||Math.abs(d-e)<1){l(),r();return}let u=Math.abs(e-d),p=Math.round(Math.min(Ax,Math.max(xx,wx+u*Cx))),g=Math.round(p*Tx),y=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,h=y?y.animate([{opacity:0},{opacity:1}],{duration:Eh,delay:g,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:p,easing:Sx});t.style.height=`${d}px`;let A=!1,k=()=>{A||(A=!0,l(),r())};Promise.allSettled([b.finished,h?.finished].filter(Boolean)).then(k),window.setTimeout(k,Math.max(p,g+Eh)+120)},Mh)}function Ex(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Qi="--persona-artifact-inline-body-height";function kx(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,i=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,i=a):a&&typeof a=="object"&&(r=a.streaming??320,i=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:e?.followOutput!==!1,u,p,g=e?.fadeMask;g===!0?(u=!0,p=!0):g===!1?(u=!1,p=!1):g&&typeof g=="object"?(u=g.top===!0,p=g.bottom===!0):l==="clip"?(u=!1,p=!0):(u=!0,p=!0);let y=e?.transition==="none"?"none":"auto",h=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:i,followOutput:d,overflow:l,fadeTop:u,fadeBottom:p,transition:y,completeDisplay:h}}function kh(t,e){let n=bx(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:i,showExpand:a,showViewToggle:l}=Ex(o),d=o?.inlineActions??[],u=kx(o),p=u.completeDisplay==="card",g=null,y=n,h=C("div","persona-artifact-inline persona-w-full persona-max-w-full");h.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&h.setAttribute("data-artifact-inline",n.id);let b=T=>Yl(vx(T),e),A=null,k=T=>{A?.destroy(),A=null,h.classList.add("persona-artifact-inline--card"),h.style.removeProperty(Qi),h.replaceChildren(b(T)),tr.set(h,Z=>{h.replaceChildren(b(Z))})};if(p&&n.status==="complete")return k(n),h;let N=Xl(n,{config:e.config,bodyLayout:u,resolveViewMode:()=>g??u.viewMode});A=N;let I=C("div","persona-artifact-inline-body");I.appendChild(N.el);let P=T=>{let Z=T.status!=="complete",de=Z?u.streamingHeight:u.completeHeight,Ce=typeof de=="number";Ce?h.style.setProperty(Qi,`${de}px`):h.style.removeProperty(Qi);let he=!!N.el.querySelector(".persona-code-pre"),ve=!!N.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");I.classList.toggle("persona-artifact-content-flush",he),I.classList.toggle("persona-artifact-inline-body--sized",Ce&&ve),I.classList.toggle("persona-artifact-inline-body--cap",!Z&&!ve&&typeof u.completeHeight=="number")},S=n.status,W=(T,Z)=>{S!=="complete"&&T.status==="complete"?(typeof u.completeHeight=="number"?h.style.setProperty(Qi,`${u.completeHeight}px`):h.style.removeProperty(Qi),Ih(I,Z?.suppressTransition?"none":u.transition,T.id,()=>{N.update(T),P(T)})):N.update(T),P(T),S=T.status};P(n);let R=u.overflow==="clip"&&a&&!!n.id;if(R&&(I.setAttribute("data-expand-artifact-inline",n.id),I.setAttribute("role","button"),I.setAttribute("tabindex","0"),I.classList.add("persona-cursor-pointer"),I.setAttribute("aria-label",`Open ${Th(n).title} in panel`)),!r)return h.appendChild(I),tr.set(h,W),h;let H=C("div","persona-artifact-inline-chrome");H.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let z=C("div","persona-artifact-inline-chrome-lead"),V=C("span","persona-flex persona-items-center persona-flex-shrink-0"),ne=ce("file-text",16,"currentColor",2);ne&&V.appendChild(ne);let $=C("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),X=C("span","persona-artifact-inline-type");z.append(V,$,X);let ue=C("div","persona-artifact-inline-chrome-actions"),we=C("span","persona-flex persona-items-center persona-gap-1"),be=()=>g??u.viewMode,pe=l?Kl({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:be(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:T=>{let Z=T==="source"?"source":"rendered";Z!==be()&&(g=Z,N.update(y),P(y))}}):null,J=i?_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;J&&n.id&&J.setAttribute("data-copy-artifact",n.id);let re=a?_t({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;re&&n.id&&re.setAttribute("data-expand-artifact-inline",n.id),ue.appendChild(we),pe&&ue.appendChild(pe.element),J&&ue.appendChild(J),re&&ue.appendChild(re),H.append(z,ue),h.append(H,I);let ae=T=>{let{title:Z,typeLabel:de}=Th(T);$.textContent=Z,$.title=Z,R&&I.setAttribute("aria-label",`Open ${Z} in panel`);let Ce=T.status!=="complete";if(Ce){X.classList.contains("persona-artifact-inline-status")||(X.className="persona-artifact-inline-status",X.removeAttribute("data-preserve-animation"),X.replaceChildren());let he=Ls(T,o,"inline-chrome");Rr(X,he,o)}else Ps(T.id),X.className="persona-artifact-inline-type",X.removeAttribute("data-preserve-animation"),X.replaceChildren(),X.textContent=de;if(J&&J.classList.toggle("persona-hidden",Ce),pe){let he=T.artifactType==="markdown"?T.file:void 0,ve=!1;if(!Ce&&he&&u.viewMode!=="source"){let xe=Hr(he);xe==="markdown"?ve=!0:(xe==="html"||xe==="svg")&&(ve=o?.filePreview?.enabled!==!1)}pe.element.classList.toggle("persona-hidden",!ve),pe.setSelected(be())}if(we.replaceChildren(),!Ce&&d.length>0){let he=Xi(T);if(he)for(let ve of d)try{if(ve.visible===void 0||ve.visible(he)){let xe=Is(ve,{documentChrome:!0});xe.setAttribute("data-artifact-custom-action",ve.id),xe.classList.add("persona-flex-shrink-0"),we.appendChild(xe)}}catch{}}};return ae(n),tr.set(h,(T,Z)=>{if(p&&S!=="complete"&&T.status==="complete"){let de=h.isConnected?h.getBoundingClientRect().height:0;S="complete";let Ce=T,he=!1,ve=xe=>{Ce=xe,he=!0};tr.set(h,ve),Mx(h,de,{swap:()=>{k(Ce),he=!1,tr.set(h,ve)},onSettled:()=>{he?k(Ce):tr.set(h,xe=>{h.replaceChildren(b(xe))})}});return}(T.status!=="complete"||T.id!==y.id)&&(g=null),y=T,W(T,Z),ae(T)}),h}var Lh=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",i=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:i},config:e.config,defaultRenderer:()=>kh(t,e)});if(l)return l}return kh(t,e)};var yp=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Po=new yp;Po.register("PersonaArtifactCard",Yl,{bubbleChrome:!1});Po.register("PersonaArtifactInline",Lh,{bubbleChrome:!1});function Ji(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?jl(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var bp=!1;function Px(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Ih(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,i=!1;try{i=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{i=!1}if(e!=="auto"||!t||typeof r!="function"||bp||i){o();return}bp=!0;let a=Px(n);t.style.setProperty("view-transition-name",a);let l=()=>{bp=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Lx="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Ix="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Hx(t){let e=C("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=C("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=C("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function Rx(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var Wx=220;function Bx(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Dx(t){return`
|
|
30
|
+
<script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function _x(t,e,n){let o=C("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=C("div","persona-artifact-frame-loading-indicator");r.appendChild(gh());let i=null;return n.label!==!1&&(i=C("div","persona-artifact-frame-loading-text"),i.textContent=n.label,r.appendChild(i)),o.appendChild(r),{el:o,revealLabel:()=>{i&&i.classList.add("persona-artifact-frame-loading-text--visible")}}}function Ox(t,e,n,o,r,i){let a=null,l=0,d=!1,u=new Set,p=()=>{u.forEach(P=>clearTimeout(P)),u.clear()},g=(P,S)=>{let W=setTimeout(()=>{u.delete(W),P()},S);u.add(W)},y=()=>{a&&a.parentElement&&a.remove(),a=null},h=()=>{if(a||d)return;let P=_x(r,i,o);a=P.el,t.appendChild(a),l=Date.now(),o.label!==!1&&g(P.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),g(y,Wx))},A=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",N):e.removeEventListener("load",I)},k=()=>{if(d||(d=!0,A(),p(),!a))return;let P=Math.max(0,o.minVisibleMs-(Date.now()-l));P>0?g(b,P):b()};function N(P){if(n===null)return;let S=P.data;!S||S.persona!=="artifact-preview-ready"||S.token!==n||P.source===e.contentWindow&&k()}function I(){let P=S=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>S()):setTimeout(S,0)};P(()=>P(()=>k()))}return g(h,o.delayMs),g(k,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",N):e.addEventListener("load",I),()=>{d=!0,p(),A(),y()}}function Xl(t,e){let{config:n}=e,o=e.registry??Po,r=e.bodyLayout,i=n.markdown?hl(n.markdown):null,a=yl(n.sanitize),l=t,d=!1,u=J=>{let re=So()!==null;i&&!re&&!d&&(d=!0,ml(()=>pe(l)));let ae=i?i(J):Vo(J);return i&&re&&a?a(ae):ae},p=C("div","persona-artifact-preview-body"),g=null,y=null,h=null,b=()=>{h&&(h(),h=null),g=null,y=null},A=null,k=null,N=null,I=!1,P=()=>{A=null,k=null,N=null,I=!1},S=null,W=null,R=()=>{S=null,W=null},H=40,z=0,V=J=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>J()):setTimeout(J,0),ne=J=>J.scrollHeight-J.clientHeight-J.scrollTop<=H,$=J=>{if(!r)return;let re=J.scrollHeight-J.clientHeight>1,ae=J.scrollHeight-J.clientHeight-J.scrollTop;J.classList.toggle("persona-artifact-fade-top",r.fadeTop&&re&&J.scrollTop>1),J.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&re&&ae>1)},X=J=>{z||(z=V(()=>{z=0,J.scrollTop=J.scrollHeight,$(J)}))},ue=(J,re,ae,T)=>{let Z=!!r,de=ae.id+"|"+(Z?"w":"p");if(!A||N!==de||A.parentElement!==p){b(),R(),p.replaceChildren();let ve=C("pre",Lx+" persona-code-pre"),xe=C("code","persona-code");if(ve.appendChild(xe),Z){let Pe=C("div","persona-artifact-source-window");if(Pe.appendChild(ve),p.appendChild(Pe),!(r?.overflow==="clip")&&typeof Pe.addEventListener=="function"){let Qe=()=>Pe.scrollHeight-Pe.clientHeight>1;Pe.addEventListener("scroll",()=>{ne(Pe)&&(I=!1),$(Pe)},{passive:!0}),Pe.addEventListener("wheel",We=>{Qe()&&We.deltaY<0&&(I=!0)},{passive:!0}),Pe.addEventListener("touchmove",()=>{Qe()&&(I=!0)},{passive:!0})}A=Pe}else p.appendChild(ve),A=ve;k=xe,N=de}let Ce=Z?A:null;Ce&&(Ce.classList.toggle("persona-artifact-source-window--fixed",T),Ce.classList.toggle("persona-artifact-source-window--clip",T&&r?.overflow==="clip"));let he=Ce?ne(Ce):!0;if(k.replaceChildren(Ch(J,re?.language,re?.path)),Ce){let ve=ae.status!=="complete";T&&ve&&r?.followOutput&&!I&&he?X(Ce):ve||(I=!1),$(Ce)}},we=J=>{b(),P(),R(),p.replaceChildren();let re=C("div",Ix);re.innerHTML=u(J),p.appendChild(re)},be=J=>{let re=J.id,ae=n.features?.artifacts,T=Ls(J,ae,"status-body");if(S&&W===re&&S.parentElement===p){let Ce=S.querySelector(".persona-artifact-status-view-text");Ce&&Rr(Ce,T,ae);return}b(),P(),p.replaceChildren();let Z=C("div","persona-artifact-status-view"),de=C("div","persona-artifact-status-view-text");Rr(de,T,ae),Z.appendChild(de),p.appendChild(Z),S=Z,W=re},pe=J=>{l=J;let re=e.resolveViewMode?.(J)??r?.viewMode??"rendered",ae=J.artifactType==="markdown"?J.file:void 0,T=J.status!=="complete";T||Ps(J.id);let Z=T?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&T){be(J);return}if(ae){let he=jl(J.markdown??""),ve=Hr(ae),xe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!T&&re==="rendered"&&xe&&(ve==="html"||ve==="svg")){let Xe=J.id+"\0"+he;if(g&&y===Xe&&g.parentElement===p)return;P(),R(),b(),p.replaceChildren();let Qe=n.features?.artifacts?.filePreview,We=Qe?.iframeSandbox??"allow-scripts";!Qe?.dangerouslyAllowSameOrigin&&We.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),We=We.split(/\s+/).filter(Me=>Me&&Me!=="allow-same-origin").join(" "));let nt=Rx(Qe?.loading),bt=C("div","persona-artifact-frame"),mt=C("iframe","persona-artifact-iframe");mt.setAttribute("sandbox",We),mt.setAttribute("data-artifact-id",J.id);let Pn=null;nt.enabled&&nt.injectReadySignal?(Pn=Bx(),mt.srcdoc=he+Dx(Pn)):mt.srcdoc=he,bt.appendChild(mt),p.appendChild(bt),nt.enabled&&(h=Ox(bt,mt,Pn,nt,J.id,n)),g=bt,y=Xe;return}if(b(),!T&&ve==="markdown"&&re==="rendered"){we(he);return}ue(he,{language:ae.language,path:ae.path},J,de);return}if(J.artifactType==="markdown"){if(re==="source"){b(),ue(J.markdown??"",void 0,J,de);return}we(J.markdown??"");return}b(),P(),R(),p.replaceChildren();let Ce=J.component?o.get(J.component):void 0;if(Ce){let ve={message:{id:J.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let xe=Ce(J.props??{},ve);if(xe){p.appendChild(xe);return}}catch{}}p.appendChild(Hx(J))};return pe(t),{el:p,update(J){pe(J)},destroy(){b()}}}import{Idiomorph as Nx}from"idiomorph";var Ql=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Nx.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,i){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return i instanceof HTMLElement&&i.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(i instanceof HTMLElement&&!i.hasAttribute("data-preserve-animation"))return;if(i instanceof HTMLElement&&i.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=i.textContent??"";if(a!==l)return}return!1}}}}})};var Hh=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var vp={index:-1,draft:""};function Rh(t){let{direction:e,history:n,currentValue:o,atStart:r,state:i}=t,a=i.index!==-1;if(n.length===0)return{handled:!1,state:i};if(e==="up"){if(!a&&!r)return{handled:!1,state:i};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(i.index>0){let l=i.index-1;return{handled:!0,value:n[l],state:{index:l,draft:i.draft}}}return{handled:!0,state:i}}if(!a)return{handled:!1,state:i};if(i.index<n.length-1){let l=i.index+1;return{handled:!0,value:n[l],state:{index:l,draft:i.draft}}}return{handled:!0,value:i.draft,state:{index:-1,draft:i.draft}}}function Wh(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function Bh(){return new Map}function Dh(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function _h(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Oh(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}var Zi={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Fx=["pre","code","a","script","style"],Jl=t=>({type:t?.type??Zi.type,placeholder:t?.placeholder??Zi.placeholder,speed:t?.speed??Zi.speed,duration:t?.duration??Zi.duration,buffer:t?.buffer??Zi.buffer}),$x=[{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"}],Fh=new Map;for(let t of $x)Fh.set(t.name,t);var Hs=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Fh.get(t)??null,Zl=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let i=t.search(/\s(?=\S*$)/);return i<0?"":t.slice(0,i)}if(e==="line"){let i=t.lastIndexOf(`
|
|
31
|
+
`);return i<0?"":t.slice(0,i)}return t},jx=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},zx=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},wp=/\s/,Ux=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Vx=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let i=t.nodeValue??"";if(!i)return;let a=o.createDocumentFragment(),l=0;for(;l<i.length;)if(wp.test(i[l])){let d=l;for(;d<i.length&&wp.test(i[d]);)d+=1;a.appendChild(o.createTextNode(i.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=l;for(;u<i.length&&!wp.test(i[u]);)d.appendChild(jx(o,i[u],e,n.value)),n.value+=1,u+=1;a.appendChild(d),l=u}r.replaceChild(a,t)},qx=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let i=t.nodeValue??"";if(!i)return;let a=o.createDocumentFragment(),l=i.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(zx(o,d,e,n.value)),n.value+=1));r.replaceChild(a,t)},ea=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let i=new Set((o?.skipTags??Fx).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)Ux(d,i)||l.push(d),d=a.nextNode();let u={value:o?.startIndex??0},p=e==="char"?Vx:qx;for(let g of l)p(g,n,u);return r.innerHTML},ec=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ta=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Nh=new WeakMap,Kx=(t,e)=>{if(!t.styles)return;let n=Nh.get(e);if(n||(n=new Set,Nh.set(e,n)),n.has(t.name)){let i=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${i}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},Cp=new WeakMap,Gx=(t,e)=>{if(!t.onAttach)return;let n=Cp.get(e);if(n||(n=new Map,Cp.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},$h=t=>{let e=Cp.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},tc=(t,e)=>{Kx(t,e),Gx(t,e)};function xp(t,e=Yt){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,i=getComputedStyle(t),a=i.position==="static"||i.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var na=0,nr=null;function Ap(t=document){if(na++,na===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;nr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,na=Math.max(0,na-1),na===0&&nr)){let n=t.body,o=t.defaultView??window;n.style.overflow=nr.originalOverflow,n.style.position=nr.originalPosition,n.style.top=nr.originalTop,n.style.width=nr.originalWidth,o.scrollTo(0,nr.scrollY),nr=null}}}var oa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Pt=t=>(t?.launcher?.mountMode??"floating")==="docked",ra=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",$n=t=>{let e=t?.launcher?.dock;return{side:e?.side??oa.side,width:e?.width??oa.width,animate:e?.animate??oa.animate,reveal:e?.reveal??oa.reveal,maxHeight:e?.maxHeight??oa.maxHeight}};var Sp=t=>t==="followUp"?"follow-up":t,Tp=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},Yx=t=>{switch(t){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},jh=new WeakSet,Xx=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Qx=t=>{Xx()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Mp=t=>{var I,P,S;let{item:e,index:n,surface:o,source:r,variant:i,streaming:a,config:l,plugins:d,chipsConfig:u,session:p,getTextarea:g,eventTarget:y}=t,h=o==="followUp",b=e.behavior,A=()=>{if(p.isStreaming())return;let W={suggestion:{...e},surface:o,source:r,behavior:b},R=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:W,bubbles:!0,composed:!0,cancelable:!0}));if(h&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!R)return;for(let z of d)if(z.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:i,config:l})===!1)return;let H=g();if(b==="fill"){H.value=e.prompt,H.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),H.focus();return}H.value="",p.sendMessage(e.prompt)},k=()=>{let W=C("button",`persona-suggestion persona-suggestion--${i}`);if(W.type="button",W.disabled=a,W.dataset.suggestionId=e.id,W.dataset.emphasis=e.emphasis,W.dataset.behavior=b,i==="chip"&&(u?.fontFamily&&(W.style.fontFamily=Yx(u.fontFamily)),u?.fontWeight&&(W.style.fontWeight=u.fontWeight),u?.paddingX&&(W.style.paddingLeft=u.paddingX,W.style.paddingRight=u.paddingX),u?.paddingY&&(W.style.paddingTop=u.paddingY,W.style.paddingBottom=u.paddingY)),e.icon){let H=ce(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);H&&(H.classList.add("persona-suggestion__icon"),e.iconColor&&(H.style.color=e.iconColor),W.appendChild(H))}let R=C("span","persona-suggestion__copy");if(R.appendChild(fe("span",{className:"persona-suggestion__label",text:e.label})),e.description&&i!=="chip"&&R.appendChild(fe("span",{className:"persona-suggestion__description",text:e.description})),W.appendChild(R),i!=="chip"){let H=ce("arrow-right",16,"currentColor",1.8);H&&(H.classList.add("persona-suggestion__arrow"),W.appendChild(H))}return W.addEventListener("click",A),W},N=null;for(let W of d)if(W.renderSuggestion&&(N=W.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:i,streaming:a,config:l,defaultRenderer:k,select:A}),N))break;return N??(N=k()),(I=N.dataset).suggestionId||(I.suggestionId=e.id),(P=N.dataset).behavior||(P.behavior=b),(S=N.dataset).emphasis||(S.emphasis=e.emphasis),N instanceof HTMLButtonElement||N.setAttribute("aria-disabled",a?"true":"false"),N},sa=t=>{let e=[],n=[],o=null,r=null,i=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){i();return}let p=Math.max(0,t.scrollWidth-t.clientWidth);if(p<=1){i();return}let g=getComputedStyle(t).direction==="rtl",y=Math.min(p,Math.max(0,Math.abs(t.scrollLeft))),h=4,b=y<=h,A=y>=p-h,k=g?!A:!b,N=g?!b:!A;t.toggleAttribute("data-scroll-left",k),t.toggleAttribute("data-scroll-right",N)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,g,y,h,b,A)=>{t.replaceChildren(),e.length=0,n.length=0;let k=A?.source??"config",N=A?.surface??(k==="config"?"starter":"followUp"),I=N==="followUp",P=A?.variant??"chip",S=A?.behavior??"send",W=A?.overflow??"wrap",R=A?.config??{},H=A?.plugins??[],z=typeof A?.maxItems=="number"?Math.max(0,Math.floor(A.maxItems)):void 0,V=I?"followUps":"starters";!jh.has(R)&&R.debug===!0&&P!=="chip"&&R.suggestions?.[V]?.overflow!==void 0&&(jh.add(R),console.info(`[persona] suggestions.${V}.overflow applies to the "chip" variant only; the "${P}" variant manages its own stacking.`));let ne=pe=>pe.map(Tp).filter(J=>J!==null).map(J=>({...J,behavior:J.behavior??S})),$=ne(p??[]);H.forEach(pe=>{pe.transformSuggestions&&($=ne(pe.transformSuggestions({suggestions:$.map(J=>({...J})),surface:N,source:k,config:R})))});let X=z===void 0?$:$.slice(0,z);if(!X.length){t.hidden=!0,o=null,i();return}if(!I&&(h??g.getMessages()).some(J=>J.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Sp(N),t.dataset.variant=P,t.dataset.overflow=W;let ue=document.createDocumentFragment(),we=g.isStreaming();X.forEach((pe,J)=>{let re=Mp({item:pe,index:J,surface:N,source:k,variant:P,streaming:we,config:R,plugins:H,chipsConfig:b,session:g,getTextarea:()=>y,eventTarget:t});ue.appendChild(re),n.push(re),[...re instanceof HTMLButtonElement?[re]:[],...Array.from(re.querySelectorAll("button"))].forEach(T=>{e.includes(T)||(T.disabled=we,e.push(T))})}),t.appendChild(ue),a(),l();let be=JSON.stringify({normalized:X,surface:N,variant:P,source:k});be!==o&&(o=be,Qx(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:X.map(pe=>({...pe})),surface:N,source:k,variant:P},bubbles:!0,composed:!0})),I&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:X.map(pe=>pe.prompt)},bubbles:!0,composed:!0})))}}};var En={"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"};var Jx="persona-header-control",Zx="persona-header-control--glyph",eA="persona-header-control--sparse",tA=20,nA={x:[1.4,1.05]},zh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",oA="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nc=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[i,a]=nA[e]??[1,1.5],l=!o;t.classList.toggle(Zx,l),t.classList.toggle(eA,l&&i!==1);let d=parseFloat(o??"")||tA,u=ce(e,`${Math.round(d*i)}px`,"currentColor",a);u?(u.style.display="block",l||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(u)):r&&(t.textContent=r)},Br=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:i,wrapperClassName:a=zh,size:l,iconSize:d,color:u,backgroundColor:p,borderWidth:g,borderColor:y,borderRadius:h,paddingX:b,paddingY:A,hidden:k,extraClassName:N,attrs:I}=t,P=C("div",a),S=!!(g||y),W=fe("button",{className:On(Jx,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!S&&"persona-border-none",!h&&"persona-rounded-full",N),attrs:{type:"button","aria-label":e,...I},style:{width:l,height:l,minWidth:l,minHeight:l,display:k?"none":void 0,color:u||dn.actionIconColor,backgroundColor:p,border:S?`${g||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:h,paddingLeft:b,paddingRight:b,paddingTop:A,paddingBottom:A}});return r?nc(W,r,{iconSize:d,iconText:i}):i&&(W.textContent=i),P.appendChild(W),Xt({anchor:W,trigger:P,text:()=>W.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:W,wrapper:P}},Rs=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=zh,buttonSize:r,iconSize:i}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:u,wrapper:p}=Br({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:i,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:u,wrapper:p}},Ws=(t,e={})=>{let{wrapperClassName:n=oA,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:u,wrapper:p}=Br({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:u,wrapper:p}};var dn={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-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},Ep={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)"},rA={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)"},Dr=t=>{let{config:e,showClose:n=!0}=t,o=fe("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:dn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},i=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,u=fe("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:i,width:i,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let W=parseFloat(i)||24,R=ce(d,W*.6,"currentColor",1);R?u.replaceChildren(R):u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let W=C("img");W.src=e.launcher.iconUrl,W.alt="",W.className="persona-rounded-xl persona-object-cover",W.style.height=i,W.style.width=i,u.replaceChildren(W)}else u.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let p=C("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=fe("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:dn.titleColor,...Ep}}),y=fe("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:dn.subtitleColor,...rA}});p.append(g,y),l?o.append(p):o.append(u,p);let h=r.clearChat??{},b=h.enabled??!0,A=h.placement??"inline",k=null,N=null;if(b){let R=Ws(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=R.button,N=R.wrapper,A==="top-right"&&(N.style.right="48px"),A==="inline"&&o.appendChild(N)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&A==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:S}=Rs(e,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(S),{header:o,iconHolder:u,headerTitle:g,headerSubtitle:y,closeButton:P,closeButtonWrapper:S,clearChatButton:k,clearChatButtonWrapper:N}},ia=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",i=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&i==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var sA=t=>{let e=Dr({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function iA(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:i}=Br({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?$l(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=Gi(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Yi({items:o.menuItems,onSelect:l=>n?.(l),anchor:i,position:"bottom-right"});i.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(i)}}var aA=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:i}=t,a=e?.launcher??{},l=C("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=dn.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,u,p;if(d){let S=Ah({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:W=>{let R=z=>{z===!1&&S.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:W}}))},H=d.onSelect(W);H instanceof Promise?H.then(R,()=>{}):R(H)},hover:d.hover,className:""});u=S.element,u.style.color=dn.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=C("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=C("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=dn.titleColor,Object.assign(p.style,Ep),p.textContent=a.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let W=r.onTitleClick;u.addEventListener("click",R=>{R.target.closest("button")||W()}),u.addEventListener("keydown",R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),W())})}let S=r?.titleRowHover;S&&(u.style.borderRadius=S.borderRadius??"10px",u.style.padding=S.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=S.background??"",u.style.borderColor=S.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}l.appendChild(u);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:h}=Rs(e,{showClose:n,wrapperClassName:g});o&&y.addEventListener("click",o);let b=C("div","persona-flex persona-items-center persona-gap-1");d||iA(b,r?.trailingActions,r?.onAction??i);let A=a.clearChat??{},k=null,N=null;if(A.enabled??!0){let S=A.placement??"inline",W=Ws(e,{wrapperClassName:S==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});k=W.button,N=W.wrapper,S==="top-right"?N.style.right="48px":b.appendChild(N)}b.appendChild(h),l.appendChild(b);let I=C("div");I.style.display="none";let P=C("span");return P.style.display="none",{header:l,iconHolder:I,headerTitle:p,headerSubtitle:P,closeButton:y,closeButtonWrapper:h,clearChatButton:k,clearChatButtonWrapper:N}},Uh={default:sA,minimal:aA},lA=t=>Uh[t]??Uh.default,oc=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=C("div");l.style.display="none";let d=C("span"),u=C("span"),p=C("button");p.style.display="none";let g=C("div");return g.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:u,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",i=lA(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(i.iconHolder.style.display="none"),e.showTitle===!1&&(i.headerTitle.style.display="none"),e.showSubtitle===!1&&(i.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(i.closeButton.style.display="none"),e.showClearChat===!1&&i.clearChatButtonWrapper&&(i.clearChatButtonWrapper.style.display="none")),i};var rc=t=>{let e=C("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.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",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let d=e.ownerDocument?.defaultView;if(!d?.getComputedStyle)return o;let u=d.getComputedStyle(e).lineHeight;if(!u||!u.trim().endsWith("px"))return o;let p=parseFloat(u);return Number.isFinite(p)&&p>0?p:o},i=`${n*o}px`;e.style.maxHeight=i,e.style.overflowY="auto";let a=()=>{let d=e.style.maxHeight;if(d!==i){let p=parseFloat(d);if(Number.isFinite(p)&&p>0)return p}let u=n*r();return i=`${u}px`,e.style.maxHeight=i,u},l=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,a());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:l}},sc=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,i=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",u=t?.copy?.stopButtonLabel??"Stop",p=e.showTooltip??!1,g=e.size??"40px",y=e.backgroundColor,h=e.textColor,b=C("div","persona-send-button-wrapper"),A=fe("button",{className:On("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!y&&"persona-bg-persona-primary",!n&&!h&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?h||"var(--persona-button-primary-fg, #ffffff)":h||void 0,backgroundColor:n&&y||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),k=null,N=null;if(n){let S=parseFloat(e.iconSize??"")||Math.round((parseFloat(g)||24)*.5),W=e.iconStrokeWidth??2,R=h?.trim()||"currentColor";r?(k=ce(r,S,R,W),k?A.appendChild(k):A.textContent=o):A.textContent=o,N=ce(i,S,R,W)}else A.textContent=d;A.setAttribute("aria-label",a),b.appendChild(A),Xt({anchor:A,trigger:b,text:()=>A.getAttribute("aria-label")??"",enabled:p});let I="send";return{button:A,wrapper:b,setMode:S=>{if(S===I)return;I=S;let W=S==="stop"?l:a;if(A.setAttribute("aria-label",W),n){if(k&&N){let R=S==="stop"?N:k;A.replaceChildren(R)}}else A.textContent=S==="stop"?u:d}}},ic=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",d=e.iconSize??a,u=parseFloat(d)||24,p=e.backgroundColor??t?.sendButton?.backgroundColor,g=e.iconColor??t?.sendButton?.textColor,y=C("div","persona-send-button-wrapper"),h=fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),A=ce(l,u,g||"currentColor",1.5);A?h.appendChild(A):h.textContent="\u{1F3A4}",y.appendChild(h);let k=e.tooltipText??"Start voice recognition",N=e.showTooltip??!1;return Xt({anchor:h,trigger:y,text:()=>h.getAttribute("aria-label")??k,enabled:N}),{button:h,wrapper:y}},ac=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=C("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Eo).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let i=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,d=Math.round(l*.6),u=C("div","persona-send-button-wrapper"),p=fe("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),g=ce(i,d,"currentColor",1.5);g?p.appendChild(g):p.textContent="\u{1F4CE}",p.addEventListener("click",h=>{h.preventDefault(),r.click()}),u.appendChild(p);let y=e.buttonTooltipText??"Attach file";return Xt({anchor:p,trigger:u,text:()=>p.getAttribute("aria-label")??y}),{button:p,wrapper:u,input:r,previewsContainer:o}},lc=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=C("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let i=e.idleText??"Online";if(e.idleLink){let a=C("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=i,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=i;return o},cc=()=>fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var aa=t=>{let{config:e}=t,n=fe("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=cc(),r=fe("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":""},style:{outline:"none"}}),{textarea:i,attachAutoResize:a}=rc(e);a();let l=sc(e),d=ic(e),u=ac(e),p=lc(e);u&&(u.previewsContainer.style.gap="8px",r.append(u.previewsContainer,u.input)),r.append(i);let g=fe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=C("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),h=C("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return u&&y.append(u.wrapper),d&&h.append(d.wrapper),h.append(l.wrapper),g.append(y,h),r.append(g),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&i.focus()}),n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,textarea:i,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:g,leftActions:y,rightActions:h,setSendButtonMode:l.setMode}};var Vh=()=>{let t=fe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=C("span","persona-pill-peek__icon"),n=ce("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=C("span","persona-pill-peek__text"),r=C("span","persona-pill-peek__caret"),i=ce("chevron-up",16,"currentColor",1.5);return i&&r.appendChild(i),t.append(e,o,r),{root:t,textNode:o}},dc=t=>{let{config:e}=t,n=fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=cc(),r=lc(e);r.style.display="none";let{textarea:i,attachAutoResize:a}=rc(e);i.style.maxHeight="100px",a();let l=sc(e),d=ic(e),u=ac(e);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=fe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=C("div","persona-widget-composer__left-actions persona-pill-composer__left");u&&g.append(u.wrapper);let y=C("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&y.append(d.wrapper),y.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&i.focus()}),u&&p.append(u.input),p.append(g,i,y),u&&n.append(u.previewsContainer),n.append(o,p,r);let h=p;return{footer:n,suggestions:o,composerForm:p,textarea:i,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:h,leftActions:g,rightActions:y,setSendButtonMode:l.setMode}};var cA=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},dA=(t,e)=>{if(!t)return null;let n=cA(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},pA=(t,e)=>{let n=C("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},uA=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},kp=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Pp=320,Yh=320,fA=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),gA=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),mA=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),hA=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),yA=t=>{if(!t||t.length===0)return null;let e=fe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=fe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=C("span","persona-mention-chip-icon"),i=ce(n.iconName??"at-sign",13,"currentColor",2);i&&r.appendChild(i),o.appendChild(r),o.appendChild(fe("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},bA=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(qi(o.ref,{readonly:!0,render:e}))}return n},qh="\uE000",Kh="\uE001",vA=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),i=y=>`${qh}${r}:${y}${Kh}`,a=e.map((y,h)=>y.kind==="text"?y.text:i(h)).join(""),l=n(a);if(!e.every((y,h)=>y.kind==="text"||l.includes(i(h)))){t.replaceChildren(bA(e,o));return}t.innerHTML=l;let u=new RegExp(`${qh}${r}:(\\d+)${Kh}`),p=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),g=[];for(let y=p.nextNode();y;y=p.nextNode())g.push(y);for(let y of g){let h=y;for(let b=u.exec(h.data);b;b=u.exec(h.data)){let A=e[Number(b[1])],k=h.splitText(b.index);k.data=k.data.slice(b[0].length),A?.kind==="mention"&&k.parentNode?.insertBefore(qi(A.ref,{readonly:!0,render:o}),k),h=k}}},wA=(t,e,n)=>{if(t.length===0)return null;try{let o=C("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,i=!1,a=()=>{i||(i=!0,o.remove(),n?.())};return t.forEach((l,d)=>{let u=C("img");u.alt=l.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Pp}px`,u.style.maxHeight=`${Yh}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&a())}),u.addEventListener("load",()=>{p=!0}),uA(l.image)?(u.src=l.image,o.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},CA=t=>{if(t.length===0)return null;try{let e=C("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!kp(o.audio))return;let r=C("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pp}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},xA=t=>{if(t.length===0)return null;try{let e=C("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!kp(o.video))return;let r=C("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Pp}px`,r.style.maxHeight=`${Yh}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},AA=t=>{if(t.length===0)return null;try{let e=C("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!kp(o.data))return;let r=C("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},la=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},SA=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:la};if(e){let r=e(o);if(r!==null)return r}return la()},TA=(t,e)=>{let n=C("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=C("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Gh=(t,e,n="div")=>{let o=C(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},ca=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="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"),t==="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"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},MA=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,i=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!i&&!a){let b=C("div");return b.style.display="none",b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id),b}let l=e.visibility??"hover",d=e.align??"right",u=e.layout??"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],y=C("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${t.id}`,y.setAttribute("data-actions-for",t.id);let h=(b,A,k)=>{let N=_t({icon:b,label:A,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",k),N};return o&&y.appendChild(h("copy","Copy message","copy")),a&&y.appendChild(h("volume-2","Read aloud","read-aloud")),r&&y.appendChild(h("thumbs-up","Upvote","upvote")),i&&y.appendChild(h("thumbs-down","Downvote","downvote")),y},Lp=(t,e,n,o,r,i)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,u=a.timestamp,p=d?.show??!1,g=u?.show??!1,y=d?.position??"left",h=u?.position??"below",b=ca(t.role,l),A=C("div",b.join(" "));A.id=`bubble-${t.id}`,A.setAttribute("data-message-id",t.id),A.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),l==="flat"?(A.style.backgroundColor="transparent",A.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let k=fA(t),N=t.content?.trim()??"",P=k.length>0&&N===Cs,S=Jl(i?.widgetConfig?.features?.streamAnimation),W=i?.widgetConfig?.features?.streamAnimation?.plugins,R=t.role==="assistant"&&S.type!=="none"?Hs(S.type,W):null,H=t.role==="assistant"&&R?.isAnimating?.(t)===!0,z=t.role==="assistant"&&R!==null&&(!!t.streaming||H);z&&R?.bubbleClass&&A.classList.add(R.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),t.streaming&&V.classList.add("persona-content-streaming"),z&&R&&(R.containerClass&&V.classList.add(R.containerClass),V.style.setProperty("--persona-stream-step",`${S.speed}ms`),V.style.setProperty("--persona-stream-duration",`${S.duration}ms`));let ne=z?Zl(t.content??"",S.buffer,R,t,!!t.streaming):t.content??"",$=()=>{let Z=e({text:ne,message:t,streaming:!!t.streaming,raw:t.rawContent});return z&&R?.wrap==="char"?ea(Z,"char",t.id,{skipTags:R.skipTags}):z&&R?.wrap==="word"?ea(Z,"word",t.id,{skipTags:R.skipTags}):Z},X=null;if(P?(X=document.createElement("div"),X.innerHTML=$(),X.style.display="none",V.appendChild(X)):t.contentSegments?.length?vA(V,t.contentSegments,Z=>e({text:Z,message:t,streaming:!!t.streaming,raw:t.rawContent}),i?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=$(),z&&R?.useCaret&&!P&&N){let Z=ec(),de=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=de[de.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(Z,Ce.nextSibling);else{let he=V.lastElementChild;he?he.appendChild(Z):V.appendChild(Z)}}if(g&&h==="inline"&&t.createdAt){let Z=Gh(t,u,"span");Z.classList.add("persona-timestamp-inline");let de=V.lastElementChild;de?de.appendChild(Z):V.appendChild(Z)}if(k.length>0){let Z=wA(k,!P&&!!N,()=>{P&&X&&(X.style.display="")});Z?A.appendChild(Z):P&&X&&(X.style.display="")}let ue=gA(t);if(ue.length>0){let Z=CA(ue);Z&&A.appendChild(Z)}let we=mA(t);if(we.length>0){let Z=xA(we);Z&&A.appendChild(Z)}let be=hA(t);if(be.length>0){let Z=AA(be);Z&&A.appendChild(Z)}let pe=t.contentSegments?.length?null:yA(t.contextMentions);if(pe&&A.appendChild(pe),A.appendChild(V),g&&h==="below"&&t.createdAt){let Z=Gh(t,u);Z.classList.add("persona-mt-1"),A.appendChild(Z)}let J=t.role==="assistant"?dA(t.stopReason,i?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Z=!!(ne&&ne.trim()),de=S.placeholder==="skeleton",Ce=de&&S.buffer==="line"&&Z;if(Z)Ce&&A.appendChild(ta());else if(de)A.appendChild(ta());else{let he=SA("inline",i?.loadingIndicatorRenderer,i?.widgetConfig);he&&A.appendChild(he)}}if(J&&t.stopReason&&!t.streaming&&(N||(V.style.display="none"),A.appendChild(pA(t.stopReason,J))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let Z=MA(t,o,r);A.appendChild(Z)}if(!p||t.role==="system")return A;let ae=C("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),T=TA(d,t.role);return y==="right"||y==="left"&&t.role==="user"?ae.append(A,T):ae.append(T,A),ae};var EA=40,kA=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ce(e.name,EA);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(fe("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(fe("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},Xh=(t,e,n={})=>{let o=fe("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=C("h2","persona-welcome-title"),i=C("p","persona-welcome-subtitle");return{host:fe("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)"}},o,r,i,e),iconHolder:o,title:r,subtitle:i,starterSuggestions:e}},Bs=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},uc=(t,e)=>{t.title.textContent=e.title,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",kA(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss)},PA="data-persona-welcome-plugin",Qh="data-persona-welcome-overlay",pc="persona-welcome-overlay-active",Ip=new WeakMap,Hp=(t,e,n)=>{n.setAttribute(PA,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(Qh,""),t.classList.contains(pc)||(Ip.set(t,t.scrollTop),t.classList.add(pc),t.scrollTop=0)},Rp=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(Qh),t.classList.contains(pc)&&(t.classList.remove(pc),t.scrollTop=Ip.get(t)??t.scrollTop,Ip.delete(t))},Jh=()=>{let t=fe("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},fc=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=fe("div",{className:ca("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(fe("div",{className:"persona-flex"},r)),t.hidden=!1},LA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Zh=(t,e)=>{if(LA()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,i=0,a=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let A=t.previousElementSibling,k=t.nextElementSibling,I=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;i=Math.max(0,A?n.top-A.getBoundingClientRect().bottom-r:n.top-I),a=Math.max(0,k?k.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),u=parseFloat(d.paddingTop)||0,p=parseFloat(d.paddingBottom)||0,g=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${i}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,h=()=>{y||(y=!0,t.style.overflow=l,e(g))};return g.finished.then(h).catch(h),g};var IA="Hello \u{1F44B}",HA="I can answer questions and help you get things done here.",ey=new WeakSet,jn=(t,e)=>!!t&&t[e]!==void 0,RA=(t,e)=>{!t||t.debug!==!0||!e.length||ey.has(t)||(ey.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},_r=t=>{let e=t?.welcome,n=t?.copy,o=jn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":jn(e,"dismiss")?e.dismiss:"never",i=[];return jn(e,"title")&&jn(n,"welcomeTitle")&&i.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),jn(e,"subtitle")&&jn(n,"welcomeSubtitle")&&i.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),jn(e,"variant")&&jn(n,"showWelcomeCard")&&i.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&jn(e,"message")&&i.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&jn(e,"dismiss")&&e.dismiss!=="on-first-message"&&i.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),RA(t,i),{title:jn(e,"title")?e.title:n?.welcomeTitle??IA,subtitle:jn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??HA,icon:e?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:e?.message}},Ds=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var ty="16px",Wp="10px",Bp="14px",ny=t=>{let e=t?.launcher?.enabled??!0,n=Pt(t);if(ra(t)){let p=t?.launcher?.composerBar??{},g=C("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Yt);let y=C("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let h=C("div","persona-widget-pill-root");return h.setAttribute("data-persona-composer-bar",""),h.dataset.state="collapsed",h.dataset.expandedSize=p.expandedSize??"anchored",h.style.zIndex=String(t?.launcher?.zIndex??Yt),{wrapper:g,panel:y,pillRoot:h}}if(n){let p=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=C("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!e){let p=C("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=C("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=t?.launcher?.width??"100%";return p.style.width=y,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let r=t?.launcher??{},i=r.position&&En[r.position]?En[r.position]:En["bottom-right"],a=C("div",`persona-widget-wrapper persona-fixed ${i} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??Yt);let l=C("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=t?.launcher?.width??t?.launcherWidth??ko;return l.style.width=u,l.style.maxWidth=u,a.appendChild(l),{wrapper:a,panel:l}},Dp=t=>{let e=fe("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Sp(t)}});return e.hidden=!0,e},oy=(t,e)=>{let n=Dp("starter"),o=Xh(t,n,{flatShadow:Pt(t)}),r=_r(t);uc(o,r),Bs(e,o.host,Ds(r,t?.initialMessages));let i=Jh();return fc(i,r.message,t),{welcome:o,greetingHost:i}},WA=(t,e)=>{let n=C("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Rs(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:ty,iconSize:Wp});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let i=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(i){let H=Ws(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:ty,iconSize:Bp});a=H.button,l=H.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=fe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=fe("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"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:g}=oy(t,u),{host:y,title:h,subtitle:b}=p,A=p.starterSuggestions,k=C("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),N=Dp("followUp"),I=Jo(t,!0);I&&(k.style.maxWidth=I,k.style.marginLeft="auto",k.style.marginRight="auto",k.style.width="100%"),u.append(y,g,k,N);let P=fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),S=dc({config:t}),{root:W,textNode:R}=Vh();return n.append(d,r,u,P),l&&n.appendChild(l),{container:n,body:u,messagesWrapper:k,starterSuggestions:A,transcriptSuggestions:N,composerOverlay:P,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:y,welcomeIconHolder:p.iconHolder,greetingHost:g,introTitle:h,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:C("span"),headerTitle:C("span"),headerSubtitle:C("span"),header:d,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode,peekBanner:W,peekTextNode:R}},ry=(t,e=!0)=>{if(ra(t))return WA(t,e);let n=fe("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,i=o?oc(t,o,{showClose:e}):Dr({config:t,showClose:e}),a=fe("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"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=oy(t,a),{host:u,title:p,subtitle:g}=l,y=l.starterSuggestions,h=C("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=Dp("followUp"),A=Jo(t,!1);A&&(h.style.maxWidth=A,h.style.marginLeft="auto",h.style.marginRight="auto",h.style.width="100%"),a.append(u,d,h,b);let k=aa({config:t}),N=t?.layout?.showFooter!==!1;r?ia(n,i,t):(i.header.style.display="none",ia(n,i,t)),n.append(a);let I=fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return N||(k.footer.style.display="none"),n.append(k.footer),n.append(I),{container:n,body:a,messagesWrapper:h,starterSuggestions:y,transcriptSuggestions:b,composerOverlay:I,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,welcomeHost:u,welcomeIconHolder:l.iconHolder,greetingHost:d,introTitle:p,introSubtitle:g,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,header:i.header,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode}};var _p=(t,e)=>{let n=C("button");n.type="button",n.innerHTML=`
|
|
32
32
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
33
33
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
34
34
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
35
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-
|
|
36
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
35
|
+
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>
|
|
36
|
+
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
|
|
37
37
|
</span>
|
|
38
38
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
39
|
-
`,n.addEventListener("click",
|
|
40
|
-
`):""},
|
|
41
|
-
`);let r=
|
|
42
|
-
`):""},Cc=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},lv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=iv(e,o?.previewMaxLines??3),a=n?cu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",u=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&u.activeTextTemplate?d=$l(n,u.activeTextTemplate,d):!l&&u.completeTextTemplate&&(d=$l(n,u.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},$f=(e,t,n)=>{let o=Ur.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",f=ae(o?"chevron-up":"chevron-down",16,c,2);f?d.appendChild(f):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Ac=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&Ur.has(e.id),{summary:u,previewText:d,isActive:c}=lv(e,t),f=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",a&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let w=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let v=String(n.startedAt??Date.now()),C=()=>{let A=b("span","");return A.setAttribute("data-tool-elapsed",v),A.textContent=Ms(n),A},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:u,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:Ms(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(g.textContent=T,w.appendChild(g)):T instanceof HTMLElement?w.appendChild(T):(g.textContent=u,w.appendChild(g));let B=s.loadingAnimation??"none",S=o.activeTextTemplate,k=o.completeTextTemplate,P=c?S:k,H=T instanceof HTMLElement,F=(A,G)=>{g.textContent="";let Q=n.name?.trim()||"tool",ie=Va(A,Q),Y=0;for(let ue of ie){let X=ue.styles.length>0?(()=>{let ge=b("span",ue.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(ge),ge})():g;if(ue.isDuration&&c)X.appendChild(C());else{let ge=ue.isDuration?Ms(n):ue.text;G?Y=Ao(X,ge,Y):X.appendChild(document.createTextNode(ge))}}};if(!H)if(c&&B!=="none"){let A=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${A}ms`),P&&F(P,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${A}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),P)F(P,!0);else{let G=g.textContent||u;g.textContent="",Ao(g,G,0)}}else P&&F(P,!1);let N=null;if(a){N=b("div","persona-flex persona-items-center");let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,A,2);G?N.appendChild(G):N.textContent=l?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(N),f.append(w,Q)}else f.append(w);let z=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let A=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});av(z,A)||(z.textContent=d),z.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(f,z),r;let j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(j.style.display=l?"":"none",o.contentBackgroundColor&&(j.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(j.style.color=o.contentTextColor),o.contentPaddingX&&(j.style.paddingLeft=o.contentPaddingX,j.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(j.style.paddingTop=o.contentPaddingY,j.style.paddingBottom=o.contentPaddingY),n.name){let A=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?A.style.color=o.contentTextColor:o.headerTextColor&&(A.style.color=o.headerTextColor),A.textContent=n.name,j.appendChild(A)}if(n.args!==void 0){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=wo(n.args),A.append(G,Q),j.appendChild(A)}if(n.chunks&&n.chunks.length){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=n.chunks.join(""),A.append(G,Q),j.appendChild(A)}if(n.status==="complete"&&n.result!==void 0){let A=b("div","persona-space-y-1"),G=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Cc(Q,o),Q.textContent=wo(n.result),A.append(G,Q),j.appendChild(A)}if(n.status==="complete"&&typeof n.duration=="number"){let A=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(A.style.color=o.contentTextColor),A.textContent=`Duration: ${n.duration}ms`,j.appendChild(A)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),N){N.innerHTML="";let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,A,2);G?N.appendChild(G):N.textContent=l?"Hide":"Show"}j.style.display=l?"":"none",z.style.display=l?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(f,z,j),r};var er=new Map,Wi=e=>{let n=(e.startsWith(Yn)?e.slice(Yn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Uf=e=>e?.approval!==!1?e?.approval:void 0,zf=(e,t)=>{let n=Uf(t)?.detailsDisplay??"collapsed";return er.get(e)??n==="expanded"},jf=(e,t,n)=>{let o=Uf(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Vf=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=zf(e,n);jf(o,s,n),r.style.display=s?"":"none"};var Ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=b("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let u=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ae(u,20,d,2);c&&l.appendChild(c);let f=b("div","persona-flex-1 persona-min-w-0"),w=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",w.appendChild(g),!r){let N=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");N.setAttribute("data-approval-status",n.status),n.status==="approved"?(N.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",N.style.color="var(--persona-palette-colors-success-700, #15803d)",N.textContent="Approved"):n.status==="denied"?(N.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",N.style.color="var(--persona-palette-colors-error-700, #b91c1c)",N.textContent="Denied"):n.status==="timeout"&&(N.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",N.style.color="var(--persona-palette-colors-warning-700, #b45309)",N.textContent="Timeout"),w.appendChild(N)}f.appendChild(w);let C=n.toolType==="webmcp"||n.toolName.startsWith(Yn)?ws(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,S=T||(B?n.description:`The assistant wants to use \u201C${C??Wi(n.toolName)}\u201D.`),k=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=S,f.appendChild(k),n.reason){let N=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");N.setAttribute("data-approval-reason","true"),o?.reasonColor?N.style.color=o.reasonColor:o?.descriptionColor&&(N.style.color=o.descriptionColor);let z=b("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,N.appendChild(z),N.appendChild(document.createTextNode(n.reason)),f.appendChild(N)}let P=o?.detailsDisplay??"collapsed",H=!!n.description&&!B,F=H||!!n.parameters;if(P!=="hidden"&&F){let N=zf(e.id,t),z=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let j=b("span");j.setAttribute("data-approval-details-label","true");let te=b("span","persona-inline-flex persona-items-center");te.setAttribute("data-approval-details-chevron","true"),z.append(j,te),jf(z,N,t),f.appendChild(z);let A=b("div");if(A.setAttribute("data-approval-details","true"),A.style.display=N?"":"none",H){let G=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,A.appendChild(G)}if(n.parameters){let G=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=wo(n.parameters),A.appendChild(G)}f.appendChild(A)}if(r){let N=b("div","persona-flex persona-gap-2 persona-mt-2");N.setAttribute("data-approval-buttons","true");let z=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let j=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);j&&(j.style.marginRight="4px",z.appendChild(j));let te=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(te);let A=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");A.type="button",A.style.backgroundColor=o?.denyButtonColor??"transparent",A.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",A.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,A.setAttribute("data-approval-action","deny");let G=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",A.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");A.appendChild(Q),N.append(z,A),f.appendChild(N)}return a.append(l,f),s.appendChild(a),s};var cv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),qf=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},tr=(e,t)=>{qf(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},dv=e=>e?.approval!==!1?e?.approval:void 0,pv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return er.get(e)??n==="expanded"},Sc=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},uv=(e,t)=>{let n=b("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Yn)?ws(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??Wi(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let u=document.createElement("strong");if(u.textContent=a,n.appendChild(u),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},fv=e=>{let t=b("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=b("span","persona-approval-resolved-name");return o.textContent=e.toolName?Wi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},gv=(e,t,n,o,r,s,a)=>{let l=b("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let u=o?.detailsDisplay??"collapsed",d=!!n.description&&u!=="hidden",c=n.parameters!=null&&u!=="hidden",f=d||c,w=f&&pv(t.id,o),g=o?.showDetailsLabel??"Show details",v=o?.hideDetailsLabel??"Hide details",C=b("button","persona-approval-head");C.type="button",f?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",w?"true":"false"),C.setAttribute("aria-label",w?v:g)):C.setAttribute("data-static","true");let T=b("span","persona-approval-logo"),B=ae("shield-check",16,"currentColor",2);B&&T.appendChild(B),C.appendChild(T);let S=uv(n,o);if(f){let z=b("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let j=ae("chevron-down",14,"currentColor",2);j&&z.appendChild(j),S.append(" "),S.appendChild(z)}C.appendChild(S),l.appendChild(C);let k=b("div","persona-approval-body");if(f){let z=b("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!w,d){let j=b("p","persona-approval-desc");o?.descriptionColor&&(j.style.color=o.descriptionColor),j.textContent=n.description,z.appendChild(j)}if(c){let j=b("pre","persona-approval-params");o?.parameterBackgroundColor&&(j.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(j.style.color=o.parameterTextColor),j.textContent=wo(n.parameters),z.appendChild(j)}k.appendChild(z)}if(n.reason){let z=b("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let j=b("span","persona-approval-reason-label");j.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(j,document.createTextNode(n.reason)),k.appendChild(z)}let P=b("div","persona-approval-actions"),H=null,F=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},N=b("button","persona-approval-deny");if(N.type="button",N.setAttribute("data-action","deny"),o?.denyButtonColor&&(N.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(N.style.color=o.denyButtonTextColor),N.append(o?.denyLabel??"Deny"),a){let z=b("div","persona-approval-split"),j=b("button","persona-approval-primary");j.type="button",j.setAttribute("data-action","always"),F(j),j.append(o?.approveLabel??"Always allow",Sc("\u23CE"));let te=b("button","persona-approval-caret");te.type="button",te.setAttribute("data-action","toggle-menu"),te.setAttribute("aria-label","More options"),F(te);let A=ae("chevron-down",15,"currentColor",2);A&&te.appendChild(A),z.append(j,te),P.append(z,N),N.append(Sc("Esc"));let G=b("div","persona-approval-menu"),Q=b("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Sc("\u2318\u23CE")),G.appendChild(Q),H=Pp({anchor:z,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,H),Q.addEventListener("click",()=>{tr(e,t.id),r()})}else{let z=b("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),F(z),z.append(o?.approveLabel??"Allow"),P.append(z,N)}return k.appendChild(P),l.appendChild(k),l.addEventListener("click",z=>{let j=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!j)return;let te=j.getAttribute("data-action");if(te==="toggle-params"){let A=l.querySelector('[data-role="params"]');if(A){let G=A.hidden;A.hidden=!G,C.setAttribute("aria-expanded",G?"true":"false"),C.setAttribute("aria-label",G?v:g),er.set(t.id,G)}return}if(te==="toggle-menu"){H?.toggle();return}if(te==="always"){tr(e,t.id),r({remember:!0});return}if(te==="allow"){tr(e,t.id),r();return}if(te==="deny"){tr(e,t.id),s();return}}),l},Kf=()=>{let e=cv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let u=dv(a);if(l.status!=="pending"){if(tr(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return fv(l)}qf(e,o.id);let d=u?.enableAlwaysAllow===!0,c=gv(e,o,l,u,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=w=>{Ip(w)||o.id===e.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),tr(e,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])tr(e,o);e.latestPendingApprovalId=null}}};var Qs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Js=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var mv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hv=new Set(["step_start","execution_start"]),yv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bv=new Set(["step_complete","agent_turn_complete"]),vv=new Set(["flow_complete","agent_complete"]),Gf=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Xf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,nr=(e,t)=>{let n=e[t];return Xf(n)?n:void 0};function Tc(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Hi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function wv(e,t){return typeof t.type=="string"?t.type:e}function xv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Cv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Yf(e){let t=nr(e,"result"),n=[nr(e,"tokens"),nr(e,"totalTokens"),t?nr(t,"tokens"):void 0,nr(e,"usage"),t?nr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(e.outputTokens)??cn(e.completionTokens)??(t?cn(t.outputTokens)??cn(t.completionTokens):void 0)}function Av(e){let t=nr(e,"result");return cn(e.executionTime)??cn(e.executionTimeMs)??cn(e.execution_time)??cn(e.duration)??(t?cn(t.executionTime)??cn(t.executionTimeMs):void 0)}function Sv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Zs=class{constructor(t=Sv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Hi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!Xf(n)){Gf.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=wv(t,n),r=this.now();if(mv.has(o)){this.startRun(r);return}if(hv.has(o)){this.run||this.startRun(r);return}if(yv.has(o)){if(!Cv(o,n))return;let s=xv(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+Tc(a.visibleCharCount),u=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Hi(l,u),outputTokens:l,durationMs:u,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(bv.has(o)){if(!this.run)return;let s=this.run,a=Yf(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,u=s.exactOutputTokens+Tc(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Hi(u,d),outputTokens:u,durationMs:d,source:l?"usage":"estimate"};return}if(vv.has(o)){if(!this.run)return;let s=this.run,a=Yf(n),l=a??s.exactOutputTokens+Tc(s.visibleCharCount),u=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Hi(l,d),outputTokens:l,durationMs:d,source:u},this.run=null;return}if(Gf.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Av(n)??o-t.startedAt}};function zr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Tv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Mv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ev=["flowName","stepName","reasoningText","text","name","tool","toolName"],kv=100;function Lv(e,t){let n={...Tv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Mv}function Pv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Iv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Wv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Rv(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Hv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Bv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Dv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Fv(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),u=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=o,l.appendChild(u),l}}function Mc(e,t,n,o,r,s,a,l){let u=r.has(e.id),d=b("div","persona-border-b persona-border-persona-divider persona-text-xs");zr(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:u,onToggleExpand:()=>s(e.id)});if(w)return d.appendChild(w),d}return d.appendChild(f()),d;function f(){let w=b("div",""),g=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ae(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&v.appendChild(C);let T=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";T.textContent=B==="relative"?Pv(e.timestamp,n):Iv(e.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(t+1));let k=Lv(e.type,o.badgeColors),P=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=k.bg,P.style.color=k.text,P.style.borderColor=k.text+"50",P.textContent=e.type;let H=o.descriptionFields??Ev,F=Wv(e.payload,H),N=null;F&&(N=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=F);let z=b("div","persona-flex-1 persona-min-w-0"),j=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),te=ae("clipboard","12px","currentColor",1.5);return te&&j.appendChild(te),j.addEventListener("click",async A=>{A.stopPropagation(),await Rv(Hv(e)),j.innerHTML="";let G=ae("check","12px","currentColor",1.5);G&&j.appendChild(G),setTimeout(()=>{j.innerHTML="";let Q=ae("clipboard","12px","currentColor",1.5);Q&&j.appendChild(Q)},1500)}),g.appendChild(v),g.appendChild(T),S&&g.appendChild(S),g.appendChild(P),N&&g.appendChild(N),g.appendChild(z),g.appendChild(j),w.appendChild(g),u&&w.appendChild(Fv(e,a,l)),w}}function Qf(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,l=r?.features?.scrollToBottom,u=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",f=r?.features?.eventStream??{},w=s.find(v=>v.renderEventStreamView);if(w?.renderEventStreamView&&r){let v=w.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(v)return{element:v,update:()=>{},destroy:()=>{}}}return g();function g(){let v=f.classNames,C=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");zr(C,v?.panel);let T=[],B="",S="",k=null,P=[],H={},F=0,N=ui(),z=0,j=0,te=!1,A=null,G=!1,Q=0,ie=new Set,Y=new Map,ue="",X="",ge=null,Z,pe,ee,me,we=null,he=null,ke=null;function Ne(){let $=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(zr(K,v?.headerBar),a){he=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),he.style.cursor="help",we=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),we.textContent="-- tok/s",ke=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ke.style.display="none",ke.style.pointerEvents="none";let xt=he,dn=ke,ra=()=>{if(!dn.textContent)return;let pn=xt.getBoundingClientRect(),it=$.getBoundingClientRect();dn.style.left=`${pn.left-it.left}px`,dn.style.top=`${pn.bottom-it.top+4}px`,dn.style.display="block"},oe=()=>{dn.style.display="none"};he.addEventListener("mouseenter",ra),he.addEventListener("mouseleave",oe),he.appendChild(we)}let ce=b("div","persona-flex-1");Z=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let je=b("option","");je.value="",je.textContent="All events (0)",Z.appendChild(je),pe=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),pe.type="button",pe.title="Copy All";let Pe=ae("clipboard-copy","12px","currentColor",1.5);Pe&&pe.appendChild(Pe);let Ve=b("span","persona-event-copy-all persona-text-xs");Ve.textContent="Copy All",pe.appendChild(Ve),he&&K.appendChild(he),K.appendChild(ce),K.appendChild(Z),K.appendChild(pe);let $e=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");zr($e,v?.searchBar);let Re=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),Ce=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Re&&Ce.appendChild(Re),ee=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),zr(ee,v?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",me=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let nt=ae("x","12px","currentColor",2);return nt&&me.appendChild(nt),$e.appendChild(Ce),$e.appendChild(ee),$e.appendChild(me),$.appendChild(K),$.appendChild($e),ke&&$.appendChild(ke),$}let Ue,Qe=s.find($=>$.renderEventStreamToolbar);Qe?.renderEventStreamToolbar&&r?Ue=Qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Ne(),eventCount:t.getSize(),filteredCount:0,onFilterChange:K=>{B=K,Le(),Te()},onSearchChange:K=>{S=K,Le(),Te()}})??Ne():Ue=Ne();let Oe=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Oe.style.display="none";function _e(){if(!a||!we||!he)return;let $=a(),K=Bv($);we.textContent=K;let ce=Dv($);ke&&(ke.textContent=ce,ce||(ke.style.display="none")),he.setAttribute("aria-label",ce?`Throughput: ${K}, ${ce}`:`Throughput: ${K}`)}let Ae=b("div","persona-flex-1 persona-min-h-0 persona-relative"),Se=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Se.style.height="100%";let ze=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");zr(ze,v?.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Gt=ae(d,"14px","currentColor",2);Gt&&ze.appendChild(Gt);let gt=b("span","");gt.textContent=c,ze.appendChild(gt);let Ht=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ht.style.display="none",Ae.appendChild(Se),Ae.appendChild(Ht),Ae.appendChild(ze),C.setAttribute("tabindex","0"),C.appendChild(Ue),C.appendChild(Oe),C.appendChild(Ae);function xn(){let $=t.getAll(),K={};for(let $e of $)K[$e.type]=(K[$e.type]||0)+1;let ce=Object.keys(K).sort(),je=ce.length!==P.length||!ce.every(($e,Re)=>$e===P[Re]),de=!je&&ce.some($e=>K[$e]!==H[$e]),Pe=$.length!==Object.values(H).reduce(($e,Re)=>$e+Re,0);if(!je&&!de&&!Pe||(P=ce,H=K,!Z))return;let Ve=Z.value;if(Z.options[0].textContent=`All events (${$.length})`,je){for(;Z.options.length>1;)Z.remove(1);for(let $e of ce){let Re=b("option","");Re.value=$e,Re.textContent=`${$e} (${K[$e]||0})`,Z.appendChild(Re)}Ve&&ce.includes(Ve)?Z.value=Ve:Ve&&(Z.value="",B="")}else for(let $e=1;$e<Z.options.length;$e++){let Re=Z.options[$e];Re.textContent=`${Re.value} (${K[Re.value]||0})`}}function Cn(){let $=t.getAll();if(B&&($=$.filter(K=>K.type===B)),S){let K=S.toLowerCase();$=$.filter(ce=>ce.type.toLowerCase().includes(K)||ce.payload.toLowerCase().includes(K))}return $}function et(){return B!==""||S!==""}function Le(){F=0,z=0,N.resume(),ze.style.display="none"}function ye($){ie.has($)?ie.delete($):ie.add($),ge=$;let K=Se.scrollTop,ce=N.isFollowing();G=!0,N.pause(),Te(),Se.scrollTop=K,ce&&N.resume(),G=!1}function tt(){return eo(Se,50)}function Te(){j=Date.now(),te=!1,_e(),xn();let $=t.getEvictedCount();$>0?(Oe.textContent=`${$.toLocaleString()} older events truncated`,Oe.style.display=""):Oe.style.display="none",T=Cn();let K=T.length,ce=t.getSize()>0;K===0&&ce&&et()?(Ht.textContent=S?`No events matching '${S}'`:"No events matching filter",Ht.style.display="",Se.style.display="none"):(Ht.style.display="none",Se.style.display=""),pe&&(pe.title=et()?`Copy Filtered (${K})`:"Copy All"),u&&!N.isFollowing()&&K>F&&(z+=K-F,gt.textContent=c?`${c}${z>0?` (${z})`:""}`:"",ze.style.display=""),F=K;let je=t.getAll(),de=je.length>0?je[0].timestamp:0,Pe=new Set(T.map(Re=>Re.id));for(let Re of ie)Pe.has(Re)||ie.delete(Re);let Ve=B!==ue||S!==X,$e=Y.size===0&&T.length>0;if(Ve||$e||T.length===0){Se.innerHTML="",Y.clear();let Re=document.createDocumentFragment();for(let Ce=0;Ce<T.length;Ce++){let nt=Mc(T[Ce],Ce,de,f,ie,ye,s,r);Y.set(T[Ce].id,nt),Re.appendChild(nt)}Se.appendChild(Re),ue=B,X=S,ge=null}else{if(ge!==null){let Ce=Y.get(ge);if(Ce&&Ce.parentNode===Se){let nt=T.findIndex(xt=>xt.id===ge);if(nt>=0){let xt=Mc(T[nt],nt,de,f,ie,ye,s,r);Se.insertBefore(xt,Ce),Ce.remove(),Y.set(ge,xt)}}ge=null}let Re=new Set(T.map(Ce=>Ce.id));for(let[Ce,nt]of Y)Re.has(Ce)||(nt.remove(),Y.delete(Ce));for(let Ce=0;Ce<T.length;Ce++){let nt=T[Ce];if(!Y.has(nt.id)){let xt=Mc(nt,Ce,de,f,ie,ye,s,r);Y.set(nt.id,xt),Se.appendChild(xt)}}}N.isFollowing()&&(Se.scrollTop=Se.scrollHeight)}function ve(){if(Date.now()-j>=kv){A!==null&&(cancelAnimationFrame(A),A=null),Te();return}te||(te=!0,A=requestAnimationFrame(()=>{A=null,Te()}))}let re=($,K)=>{if(!pe)return;pe.innerHTML="";let ce=ae($,"12px","currentColor",1.5);ce&&pe.appendChild(ce);let je=b("span","persona-text-xs");je.textContent="Copy All",pe.appendChild(je),setTimeout(()=>{pe.innerHTML="";let de=ae("clipboard-copy","12px","currentColor",1.5);de&&pe.appendChild(de);let Pe=b("span","persona-text-xs");Pe.textContent="Copy All",pe.appendChild(Pe),pe.disabled=!1},K)},xe=async()=>{if(pe){pe.disabled=!0;try{let $;et()?$=T:n?($=await n(),$.length===0&&($=t.getAll())):$=t.getAll();let K=$.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),re("check",1500)}catch{re("x",1500)}}},An=()=>{Z&&(B=Z.value,Le(),Te())},ne=()=>{!ee||!me||(me.style.display=ee.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{S=ee.value,Le(),Te()},150))},M=()=>{!ee||!me||(ee.value="",S="",me.style.display="none",k&&clearTimeout(k),Le(),Te())},I=()=>{if(G)return;let $=Se.scrollTop,{action:K,nextLastScrollTop:ce}=fi({following:N.isFollowing(),currentScrollTop:$,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=ce,K==="resume"?(N.resume(),z=0,ze.style.display="none"):K==="pause"&&(N.pause(),u&&(gt.textContent=c,ze.style.display=""))},h=$=>{let K=gi({following:N.isFollowing(),deltaY:$.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});K==="pause"?(N.pause(),u&&(gt.textContent=c,ze.style.display="")):K==="resume"&&(N.resume(),z=0,ze.style.display="none")},W=()=>{u&&(Se.scrollTop=Se.scrollHeight,N.resume(),z=0,ze.style.display="none")},L=$=>{let K=$.target;if(!K||K.closest("button"))return;let ce=K.closest("[data-event-id]");if(!ce)return;let je=ce.getAttribute("data-event-id");je&&ye(je)},R=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),ee?.focus(),ee?.select();return}$.key==="Escape"&&(ee&&document.activeElement===ee?(M(),ee.blur(),C.focus()):o&&o())};pe&&pe.addEventListener("click",xe),Z&&Z.addEventListener("change",An),ee&&ee.addEventListener("input",ne),me&&me.addEventListener("click",M),Se.addEventListener("scroll",I),Se.addEventListener("wheel",h,{passive:!0}),Se.addEventListener("click",L),ze.addEventListener("click",W),C.addEventListener("keydown",R);function q(){k&&clearTimeout(k),A!==null&&(cancelAnimationFrame(A),A=null),te=!1,Y.clear(),pe&&pe.removeEventListener("click",xe),Z&&Z.removeEventListener("change",An),ee&&ee.removeEventListener("input",ne),me&&me.removeEventListener("click",M),Se.removeEventListener("scroll",I),Se.removeEventListener("wheel",h),Se.removeEventListener("click",L),ze.removeEventListener("click",W),C.removeEventListener("keydown",R)}return{element:C,update:ve,destroy:q}}}function Jf(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},u=f=>{let w=f;return s.findIndex(g=>g===w||g.contains(w))},d=f=>{let w=u(f.target);if(w<0)return;let g=w;if(f.key===r)g=Math.min(w+1,s.length-1);else if(f.key===o)g=Math.max(w-1,0);else if(f.key==="Home")g=0;else if(f.key==="End")g=s.length-1;else return;f.preventDefault(),g!==w&&t.onSelect(g)},c=f=>{let w=u(f.target);w>=0&&l(s[w])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(f,w){if(s=f,f.forEach((g,v)=>{g.setAttribute("role","tab");let C=v===w;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||w<0&&v===0?0:-1}),a){let g=(w>=0?f[w]:void 0)??f[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Zf(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),u=n?.tabFadeSize?.trim(),d=ne=>({start:ne===!1?!1:typeof ne=="object"&&ne?ne.start!==!1:!0,end:ne===!1?!1:typeof ne=="object"&&ne?ne.end!==!1:!0}),{start:c,end:f}=d(n?.tabFade),w=typeof document<"u"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{w?.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"),G?.hide()};w&&w.addEventListener("click",()=>{g(),t.onDismiss?.()});let v=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");v.setAttribute("data-persona-theme-zone","artifact-pane"),r&&v.classList.add("persona-artifact-pane-document");let C=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let T=b("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=s;let B=Wt({icon:"x",label:a});B.addEventListener("click",()=>{g(),t.onDismiss?.()});let S="rendered",k=ii({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ne=>{S=ne==="source"?"source":"rendered",re()}}),P=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),H=n?.documentToolbarShowCopyLabel===!0,F=n?.documentToolbarShowCopyChevron===!0,N=n?.documentToolbarCopyMenuItems,z=!!(F&&N&&N.length>0),j=null,te,A=null,G=null;if(r&&(H||F)&&!z){if(te=H?Qo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F){let ne=ae("chevron-down",14,"currentColor",2);ne&&te.appendChild(ne)}}else r&&z?(j=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),te=H?Qo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=Wt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),j.append(te,A)):r?te=Wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(te=Wt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&te.classList.add("persona-hidden"));let Q=r?Wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Wt({icon:"refresh-cw",label:"Refresh"}),ie=r?Wt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Wt({icon:"x",label:a}),Y=Wt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Y.classList.add("persona-hidden");let ue=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),X=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ne=Ae.find(W=>W.id===Se)??Ae[Ae.length-1],M=ne?.id??null,I=ne?.artifactType==="markdown"?ne.markdown??"":"",h=ne?JSON.stringify({component:ne.component,props:ne.props},null,2):"";return{markdown:I,jsonPayload:h,id:M}},Z=async()=>{let ne=Ae.find(M=>M.id===Se)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(Ns(ne))}catch{}};if(te.addEventListener("click",async()=>{let ne=n?.onDocumentToolbarCopyMenuSelect;if(ne&&z){let{markdown:M,jsonPayload:I,id:h}=ge();try{await ne({actionId:"primary",artifactId:h,markdown:M,jsonPayload:I})}catch{}return}await Z()}),A&&N?.length){let ne=()=>v.closest("[data-persona-root]")??document.body,M=()=>{G=Dr({items:N.map(I=>({id:I.id,label:I.label})),onSelect:async I=>{let{markdown:h,jsonPayload:W,id:L}=ge(),R=n?.onDocumentToolbarCopyMenuSelect;try{R?await R({actionId:I,artifactId:L,markdown:h,jsonPayload:W}):I==="markdown"||I==="md"?await navigator.clipboard.writeText(h):I==="json"||I==="source"?await navigator.clipboard.writeText(W):await navigator.clipboard.writeText(h||W)}catch{}},anchor:j??A,position:"bottom-right",portal:ne()})};v.isConnected?M():requestAnimationFrame(M),A.addEventListener("click",I=>{I.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),ie.addEventListener("click",()=>{g(),t.onDismiss?.()});let pe=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),j?P.append(j,Q,ie):P.append(te,Q,ie),P.insertBefore(ue,ie),P.insertBefore(Y,ie),C.append(k.element,pe,P);else{let ne=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ne.append(te,ue,Y,B),C.appendChild(T),C.appendChild(ne)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ee=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");u&&ee.style.setProperty("--persona-artifact-tab-fade-size",u);let me=e.features?.artifacts?.renderTabBar,we=b("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),he=Jf(ee,{onSelect:ne=>t.onSelect(Ae[ne].id)}),ke=ne=>{let M=ne.scrollWidth-ne.clientWidth,I=M>1,h=Math.abs(ne.scrollLeft);ne.classList.toggle("persona-artifact-tab-fade-start",c&&I&&h>1),ne.classList.toggle("persona-artifact-tab-fade-end",f&&I&&h<M-1)},Ne=0,Ue=()=>{if(Ne)return;let ne=()=>{Ne=0,ke(ee)};Ne=typeof requestAnimationFrame=="function"?requestAnimationFrame(ne):setTimeout(ne,0)};ee.addEventListener("scroll",()=>Ue(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ke(ee)).observe(ee);let Qe=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Oe=()=>{Qe.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Oe):setTimeout(Oe,0)};if(l){for(let ne of[ee,we])ne.style.paddingLeft=l,ne.style.paddingRight=l;Qe.style.padding=l}v.appendChild(C),v.appendChild(ee),v.appendChild(we),v.appendChild(Qe);let Ae=[],Se=null,ze=!1,Gt=!1,gt=!0,Ht=!1,xn=null,Cn="",et=null,Le=!1,ye=ne=>ne.artifactType==="markdown"&&!!ne.file||r?S:"rendered",tt=ne=>{r||(ne&&!Le?(C.insertBefore(k.element,T),Le=!0):!ne&&Le&&(k.element.remove(),Le=!1))},Te=()=>Se&&Ae.find(ne=>ne.id===Se)||Ae[Ae.length-1],ve=()=>{let ne=Fs(Te());if(!ne){ue.replaceChildren();return}let M=X.filter(I=>I.visible===void 0||I.visible(ne)).map(I=>Fr(I,{documentChrome:r,onClick:()=>{let h=Fs(Te());if(h)try{Promise.resolve(I.onClick(h)).catch(()=>{})}catch{}}}));ue.replaceChildren(...M)},re=()=>{ve();let ne=r&&Ae.length<=1,M=!!me;if(ee.classList.toggle("persona-hidden",ne||M),we.classList.toggle("persona-hidden",ne||!M),M&&me){let W=Ae.map(L=>L.id).join("|")+" "+(Se??"");if(W!==Cn){Cn=W;let L=me({records:Ae,selectedId:Se,onSelect:t.onSelect});we.firstElementChild!==L&&we.replaceChildren(L)}}else{he.beforeRender(),ee.replaceChildren();let W=[],L=-1;for(let[R,q]of Ae.entries()){let $=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");$.type="button";let K=q.artifactType==="markdown"?q.file:void 0,ce=K?Bn(K.path):q.title||q.id.slice(0,8),je=K?.path||q.title||ce;$.textContent=ce,$.title=je,$.setAttribute("aria-label",je),q.id===Se&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),L=R),$.addEventListener("click",()=>t.onSelect(q.id)),ee.appendChild($),W.push($)}if(he.render(W,L),L>=0&&Se!==xn){xn=Se;let R=W[L];typeof R.scrollIntoView=="function"&&R.scrollIntoView({block:"nearest",inline:"nearest"})}ke(ee)}let I=Se&&Ae.find(W=>W.id===Se)||Ae[Ae.length-1];if(!I){Qe.replaceChildren(),et=null,tt(!1);return}let h=I.artifactType==="markdown"?I.file:void 0;if(tt(!!h&&Yo(h)!=="other"),r){let W=h?Co(h):I.artifactType==="markdown"?"MD":I.component??"Component",L=(I.title||"Document").trim(),R=h?Bn(h.path):L.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${R} \xB7 ${W}`}else T.textContent=h?Bn(h.path):s;et?(et.el.parentElement!==Qe&&Qe.replaceChildren(et.el),et.update(I)):(et=di(I,{config:e,resolveViewMode:ye}),Qe.replaceChildren(et.el)),Qe.classList.toggle("persona-artifact-content-flush",!!Qe.querySelector(".persona-code-pre"))},xe=()=>{let ne=Ae.length>0;if(v.classList.toggle("persona-hidden",!ne),w){let h=((typeof v.closest=="function"?v.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ne&&h&&ze?(w.classList.remove("persona-hidden"),v.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open"))}},An=()=>{Ht=!1,re(),xe()};return{element:v,backdrop:w,update(ne){let M=ne.selectedId??ne.artifacts[ne.artifacts.length-1]?.id??null,I=M!==Se;Ae=ne.artifacts,Se=M,Ae.length>0&&(ze=!0),Ht=!0,gt&&An(),I&&Oe()},setMobileOpen(ne){ze=ne,!ne&&w?(w.classList.add("persona-hidden"),v.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(ne){ne!==Gt&&(Gt=ne,_e());let M=ae(ne?"minimize":"maximize",16,"currentColor",2);M&&Y.replaceChildren(M);let I=ne?"Collapse artifacts panel":"Expand artifacts panel";Y.setAttribute("aria-label",I),Y.title=I},setExpandToggleVisible(ne){Y.classList.toggle("persona-hidden",!ne)},setCopyButtonVisible(ne){r||te.classList.toggle("persona-hidden",!ne)},setCustomActions(ne){X=ne,ve()},setTabFade(ne){let M=d(ne);M.start===c&&M.end===f||(c=M.start,f=M.end,ke(ee))},setRenderTabBar(ne){ne!==me&&(me=ne,Cn="",re())},setVisible(ne){ne!==gt&&(gt=ne,ne&&Ht&&An())}}}function Jt(e){return e?.features?.artifacts?.enabled===!0}function eg(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Ov(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var tg=["panel","seamless","detached"];function Ec(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&tg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function kc(e){return!e||!Jt(e)?!1:Ec(e)==="detached"}function ea(e,t){if(!Jt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Ov(e),eg(e,t);return}let n=t.features?.artifacts?.layout,o=Ec(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let u=n?.documentToolbarToggleActiveBorderColor?.trim();u?e.style.setProperty("--persona-artifact-doc-toggle-active-border",u):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),eg(e,t)}function ta(e,t){for(let l of tg)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Jt(t))return;let n=t.features?.artifacts?.layout,o=Ec(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function ng(e,t){return!t||!Jt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var Nv=new Set(["__proto__","prototype","constructor"]),_v=new Set(["collapsed","card","panel","inline"]),og=new Set(["markdown","component"]),$v=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,or=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Di=e=>!Nv.has(e),Lc=e=>typeof e=="string"&&_v.has(e),rr=e=>Object.keys(e).length>0;function Fn(e,t,n,o){e.push({path:t,code:n,message:o})}var Uv="Ignored because this key is not part of the persisted preference schema.",Bi="Ignored an unsupported value.",zv="Expected collapsed, panel, or inline.",jv='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',rg={kind:"mode",message:Bi},jr={kind:"string",message:"Expected a CSS length string."},to={kind:"boolean"},Vv={paneWidth:jr,paneMaxWidth:jr,paneMinWidth:jr,expandedPanelWidth:jr,resizableMinWidth:jr,resizableMaxWidth:jr,expandLauncherPanelWhenOpen:to,resizable:to},qv={kind:"object",message:"Expected a preference object.",children:{showToolCalls:to,showReasoning:to,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Bi},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Bi},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Bi},expandable:to,grouped:to}},reasoningDisplay:{kind:"object",children:{expandable:to,activePreview:to}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:rg,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:rg,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:og,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:og}}},filePreview:{kind:"object",children:{enabled:to}},layout:{kind:"object",children:Vv}}}}};function sg(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Fn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Fn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Fn(o,n,"invalid_value",t.message);case"mode":return Lc(e)?yn(e):Fn(o,n,"invalid_value",t.message);case"modeMap":{if(!or(e))return Fn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,l]of Object.entries(e)){let u=r?a:Ar(a);Di(a)&&(r?r.has(a):$v.test(u))?Lc(l)?s[u]=yn(l):Fn(o,`${n}.${a}`,"invalid_value",zv):Fn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":jv)}return rr(s)?s:void 0}case"object":{if(t.bareMode&&Lc(e))return yn(e);if(!or(e))return Fn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Di(l)||!r.includes(l))&&Fn(o,s(l),"unknown_key",Uv);let a={};for(let l of r){let u=t.children[l],d=sg(e[l],u,s(l),o);if(u.deprecated&&e[l]!==void 0&&Fn(o,s(l),"deprecated_key",u.deprecated),d===void 0)continue;let c=u.alias??l,f=a[c];a[c]=or(f)&&or(d)?{...f,...d}:d}return rr(a)?a:void 0}}}function Kv(e){let t=[];return{preferences:(e===null?void 0:sg(e,qv,"",t))??{},issues:t}}function Vr(e){if(Array.isArray(e))return e.map(Vr);if(!or(e))return e;let t={};for(let[n,o]of Object.entries(e))Di(n)&&o!==void 0&&(t[n]=Vr(o));return t}function ag(e,t){let n=Vr(e);for(let[o,r]of Object.entries(t)){if(!Di(o)||r===void 0)continue;let s=n[o];n[o]=or(s)&&or(r)?ag(s,r):Vr(r)}return n}function Gv(e){let t={},n;for(let r of e){let s=Kv(r).preferences;n=ig(n,s.artifacts?.display),t=ag(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Yv(e,t){if(t===void 0)return e===void 0?void 0:Vr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...rr(r)?{byMediaType:r}:{}};return rr(s)?s:void 0}function ig(e,t){if(t===void 0)return e===void 0?void 0:Vr(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=Yv(n.files,t.files),a={...o?{default:o}:{},...rr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return rr(a)?a:void 0}function Xv(e={},t){let n=Gv(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=ig(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Pc(e){let t=e.preferences;return!t||!rr(t)?e:{...e,features:Xv(e.features??{},[t])}}function Qv(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Jv(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Zv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ew(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Ic(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function lg(e,t,n,o,r,s){let a=Qv(r,200),l=ew(t,n,o,200);l=Math.max(a,l);let u=Jv(s);return u!==null&&(l=Math.min(l,u)),Zv(e,a,l)}var cg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Wc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=cg[a]??cg.init;s.classList.add("persona-form-card","persona-space-y-4");let u=b("div","persona-space-y-1"),d=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,u.appendChild(d),l.description){let v=b("p","persona-text-sm persona-text-persona-muted");v.textContent=l.description,u.appendChild(v)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(v=>{let C=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${v.name}`;let T=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=v.label,C.appendChild(T);let B=v.type??"text",S;B==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=B),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${a}-${v.name}`,S.name=v.name,S.placeholder=v.placeholder??"",v.required&&(S.required=!0),C.appendChild(S),c.appendChild(C)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=l.submitLabel??"Submit",f.appendChild(w),f.appendChild(g),c.appendChild(f),s.replaceChildren(u,c),c.addEventListener("submit",async v=>{v.preventDefault();let C=n.formEndpoint??"/form",T=new FormData(c),B={};T.forEach((S,k)=>{B[k]=S}),B.type=a,g.disabled=!0,w.textContent="Submitting\u2026";try{let S=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let k=await S.json();w.textContent=k.message??"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(S){w.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Rc=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Hc=new Rc;var dg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tw=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),pg=(e,t,n)=>{if(!dg(e)||!dg(t)||tw.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=pg(e[r],t[r],s)}return o};function ug(e,t){let n=pg(e,t,"");return ei(n)}var fg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var nw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ow=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Dc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=nw(e),n=ow(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Bc=e=>typeof e=="string"?e:e==null?"":String(e),na={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Bc(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Bc(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Bc(n.text)}}},gg=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fc=e=>{let t=new Set(gg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(gg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let u={action:l,message:s.message};e.emit("action:detected",u);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",u)},f=d(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!f)continue;if(f.handled){let w=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:w,resubmit:f.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var rw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},sw=e=>e.map(t=>({...t,streaming:!1})),aw=e=>e.map(t=>({...t,status:"complete"})),mg=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?rw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?sw(n.messages):void 0,artifacts:n.artifacts?aw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as rM,STR as sM,OBJ as aM}from"partial-json";function hg(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Zn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function yg(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 Oc(e){let t=yg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function bg(e){let t=yg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vg(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:u=!0,ratingLabels:d=iw}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let f=null,w=document.createElement("div");w.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=o,g.appendChild(v);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),w.appendChild(g);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let F=1;F<=5;F++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${F} star${F>1?"s":""}: ${d[F-1]}`),N.title=d[F-1],N.dataset.rating=String(F),N.innerHTML=`
|
|
39
|
+
`,n.addEventListener("click",e);let o=i=>{let a=i.launcher??{},l=Pt(i),d=n.querySelector("[data-role='launcher-title']");if(d){let P=a.title??"Chat Assistant";d.textContent=P,d.setAttribute("title",P)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let P=a.subtitle??"Here to help you get answers fast";u.textContent=P,u.setAttribute("title",P)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||l?p.style.display="none":p.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let P=a.agentIconSize??"40px";if(g.style.height=P,g.style.width=P,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let S=parseFloat(P)||24,W=ce(a.agentIconName,S*.6,"var(--persona-text-inverse, #ffffff)",1.5);W?(g.appendChild(W),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let P=a.agentIconSize??"40px";y.style.height=P,y.style.width=P,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let h=n.querySelector("[data-role='launcher-call-to-action-icon']");if(h){let P=a.callToActionIconSize??"32px";h.style.height=P,h.style.width=P,a.callToActionIconBackgroundColor?(h.style.backgroundColor=a.callToActionIconBackgroundColor,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(h.style.color=a.callToActionIconColor,h.classList.remove("persona-text-persona-call-to-action")):(h.style.color="",h.classList.add("persona-text-persona-call-to-action"));let S=0;if(a.callToActionIconPadding?(h.style.boxSizing="border-box",h.style.padding=a.callToActionIconPadding,S=(parseFloat(a.callToActionIconPadding)||0)*2):(h.style.boxSizing="",h.style.padding=""),a.callToActionIconHidden)h.style.display="none";else if(h.style.display=l?"none":"",h.innerHTML="",a.callToActionIconName){let W=parseFloat(P)||24,R=Math.max(W-S,8),H=ce(a.callToActionIconName,R,"currentColor",1.5);H?h.appendChild(H):h.textContent=a.callToActionIconText??"\u2197"}else h.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&En[a.position]?En[a.position]:En["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",k="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?k:`${A} ${b}`,l||(n.style.zIndex=String(a.zIndex??Yt));let N="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??N,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},BA="teaser-dismissed",iy=new Set,sy=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${BA}`},DA=(t,e)=>{if(iy.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},_A=(t,e)=>{if(iy.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},OA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,NA=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Pt(t??{})?null:e},ay=(t,e)=>{let n=C("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,i=null,a=null,l=null,d=null,u=!1,p=!1,g=!1,y=!1,h=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{d!==null&&(clearTimeout(d),d=null)},A=()=>{!i||!u||(u=!1,i.hidden=!0)},k=be=>{b(),g=!0,A(),_A(sy(o),be&&h())},N=be=>{!r||g||k(be==="user"&&u)},I=()=>{d=null,!(!i||g||y)&&(p=!0,u=!0,i.hidden=!1,!(OA()||typeof i.animate!="function")&&i.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},P=()=>{!r||!i||g||p||y||DA(sy(o),h())||(b(),d=setTimeout(I,Math.max(0,r.delayMs??0)))},S=()=>{k(h()),e()},W=be=>{be.stopPropagation(),k(h())},H=_p(t,()=>{N("user"),e()}),z=()=>{b(),l?.removeEventListener("click",S),a?.removeEventListener("click",W),i?.remove(),i=null,l=null,a=null,u=!1},V=()=>{l=fe("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",S),a=fe("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",W),i=fe("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(i,H.element)},ne=()=>{let be=o.launcher?.position??"bottom-right",pe=En[be]??En["bottom-right"];if(!i){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",H.element.style.position="";return}n.className=On("persona-launcher-surface",pe),n.setAttribute("data-teaser",be),n.style.zIndex=String(o.launcher?.zIndex??Yt),H.element.style.position="static"},$=be=>{let pe=NA(be);if(r=pe,!pe){z();return}i||V(),l.textContent=pe.text,a.hidden=pe.dismissible===!1,a.setAttribute("aria-label",pe.dismissLabel??"Dismiss message"),P()},X=be=>{o=be,H.update(be),$(be),ne()},ue=(be,pe="user")=>{y=be,be&&N(pe)},we=()=>{z(),H.destroy(),n.remove()};return n.appendChild(H.element),t&&($(t),ne()),{element:n,launcher:H,get teaser(){return i?{element:i,show:I,dismiss:k}:null},setPanelOpen:ue,update:X,destroy:we}};var ly=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=ny(t),i=ry(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:i.container,body:i.body,messagesWrapper:i.messagesWrapper,starterSuggestions:i.starterSuggestions,transcriptSuggestions:i.transcriptSuggestions,composerOverlay:i.composerOverlay,welcomeHost:i.welcomeHost,welcomeIconHolder:i.welcomeIconHolder,greetingHost:i.greetingHost,introTitle:i.introTitle,introSubtitle:i.introSubtitle},d={element:i.header,iconHolder:i.iconHolder,headerTitle:i.headerTitle,headerSubtitle:i.headerSubtitle,closeButton:i.closeButton,closeButtonWrapper:i.closeButtonWrapper,clearChatButton:i.clearChatButton,clearChatButtonWrapper:i.clearChatButtonWrapper},u={footer:i.footer,form:i.composerForm,textarea:i.textarea,sendButton:i.sendButton,sendButtonWrapper:i.sendButtonWrapper,micButton:i.micButton,micButtonWrapper:i.micButtonWrapper,statusText:i.statusText,suggestions:i.suggestions,attachmentButton:i.attachmentButton,attachmentButtonWrapper:i.attachmentButtonWrapper,attachmentInput:i.attachmentInput,attachmentPreviewsContainer:i.attachmentPreviewsContainer,actionsRow:i.actionsRow,leftActions:i.leftActions,rightActions:i.rightActions,setSendButtonMode:i.setSendButtonMode,peekBanner:i.peekBanner,peekTextNode:i.peekTextNode};return{shell:a,panelElements:i,transcript:l,header:d,composer:u,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{u.footer.replaceWith(y),u.footer=y}}},Op=({config:t,plugins:e,onToggle:n})=>{let o=e.find(i=>i.renderLauncher);if(o?.renderLauncher){let i=o.renderLauncher({config:t,defaultRenderer:()=>_p(t,n).element,onToggle:n});if(i)return{instance:null,element:i}}let r=ay(t,n);return{instance:r,element:r.element}};var FA=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},$A=(t,e,n)=>`${FA(t)}plugin:${e}:${n}`,cy=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let i=a=>$A(t(),r,a);return{get:a=>{let l=i(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return e.get(l)??null},set:(a,l)=>{let d=i(a),u=o();if(u)try{u.setItem(d,l);return}catch{n=!0}e.set(d,l)},remove:a=>{let l=i(a);e.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var _s=new Set,jA=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),zA=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
|
|
40
|
+
`):""},dy=(t,e)=>{let n=_s.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=ce(n?"chevron-up":"chevron-down",16,"currentColor",2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Np=(t,e)=>{let n=t.reasoning,o=C("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},i=r.expandable!==!1,a=i&&_s.has(t.id),l=n.status!=="complete",d=zA(t,r.previewMaxLines??3),u=C("button",i?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",i&&(u.setAttribute("aria-expanded",a?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","reasoning");let p=C("div","persona-flex persona-flex-col persona-text-left"),g=C("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",h=e?.reasoning??{},b=String(n.startedAt??Date.now()),A=()=>{let we=C("span","");return we.setAttribute("data-tool-elapsed",b),we.textContent=Tl(n),we},k=h.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:e??{},elapsed:Tl(n),createElapsedElement:A});typeof k=="string"&&k.trim()?(g.textContent=k,p.appendChild(g)):k instanceof HTMLElement?p.appendChild(k):(g.textContent=y,p.appendChild(g));let N=C("span","persona-text-xs persona-text-persona-primary");N.textContent=hm(n),p.appendChild(N);let I=r.loadingAnimation??"none",P=h.activeTextTemplate,S=h.completeTextTemplate,W=l?P:S,R=k instanceof HTMLElement,H=(we,be)=>{g.textContent="";let pe=Ml(we,""),J=0;for(let re of pe){let ae=re.styles.length>0?(()=>{let T=C("span",re.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(T),T})():g;if(re.isDuration&&l)ae.appendChild(A());else{let T=re.isDuration?Tl(n):re.text;be?J=er(ae,T,J):ae.appendChild(document.createTextNode(T))}}};if(!R&&W)if(N.style.display="none",g.style.display="",l&&I!=="none"){let we=h.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),I==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`),H(W,!1)):(g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`),I==="shimmer-color"&&(h.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor)),H(W,!0))}else H(W,!1);else if(!R&&l&&I!=="none"){g.style.display="";let we=h.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),I==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`);else{g.classList.add(`persona-tool-loading-${I}`),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`),I==="shimmer-color"&&(h.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",h.loadingAnimationColor),h.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",h.loadingAnimationSecondaryColor));let be=g.textContent||y;g.textContent="",er(g,be,0)}n.status==="complete"&&(g.style.display="none")}else R||(n.status==="complete"?g.style.display="none":g.style.display="");let z=null;if(i){z=C("div","persona-flex persona-items-center");let be=ce(a?"chevron-up":"chevron-down",16,"currentColor",2);be?z.appendChild(be):z.textContent=a?"Hide":"Show";let pe=C("div","persona-flex persona-items-center persona-ml-auto");pe.append(z),u.append(p,pe)}else u.append(p);let V=C("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","reasoning"),V.style.display="none",V.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&d){let we=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:d,isActive:l,config:e??{}});jA(V,we)||(V.textContent=d),V.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!i)return o.append(u,V),o;let ne=C("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");ne.style.display=a?"":"none";let $=n.chunks.join(""),X=C("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return X.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),ne.appendChild(X),(()=>{if(u.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let be=ce(a?"chevron-up":"chevron-down",16,"currentColor",2);be?z.appendChild(be):z.textContent=a?"Hide":"Show"}ne.style.display=a?"":"none",V.style.display=a?"none":V.textContent||V.childNodes.length?"":"none"})(),o.append(u,V,ne),o};var Os=new Set,UA=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),VA=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
|
|
41
|
+
`);let r=Xo(n.args).trim();return r?r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
|
|
42
|
+
`):""},Fp=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},qA=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",i=VA(t,o?.previewMaxLines??3),a=n?ym(n):"";if(!n)return{summary:a,previewText:i,isActive:!1};let l=n.status!=="complete",d=e?.toolCall??{},u=a;return r==="tool-name"?u=n.name?.trim()||a:r==="tool-preview"&&i&&(u=i),l&&d.activeTextTemplate?u=Zd(n,d.activeTextTemplate,u):!l&&d.completeTextTemplate&&(u=Zd(n,d.completeTextTemplate,u)),{summary:u,previewText:i,isActive:l}},py=(t,e,n)=>{let o=Os.has(t),r=n?.toolCall??{},i=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!i||!a)return;i.setAttribute("aria-expanded",o?"true":"false");let u=i.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(u){u.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=ce(o?"chevron-up":"chevron-down",16,p,2);g?u.appendChild(g):u.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},$p=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=C("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let i=e?.features?.toolCallDisplay??{},a=i.expandable!==!1,l=a&&Os.has(t.id),{summary:d,previewText:u,isActive:p}=qA(t,e),g=C("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",l?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let y=C("div","persona-flex persona-flex-col persona-text-left"),h=C("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(h.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),A=()=>{let $=C("span","");return $.setAttribute("data-tool-elapsed",b),$.textContent=Bi(n),$},k=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:u,collapsedMode:i.collapsedMode??"tool-call",isActive:p,config:e??{},elapsed:Bi(n),createElapsedElement:A});typeof k=="string"&&k.trim()?(h.textContent=k,y.appendChild(h)):k instanceof HTMLElement?y.appendChild(k):(h.textContent=d,y.appendChild(h));let N=i.loadingAnimation??"none",I=o.activeTextTemplate,P=o.completeTextTemplate,S=p?I:P,W=k instanceof HTMLElement,R=($,X)=>{h.textContent="";let ue=n.name?.trim()||"tool",we=Ml($,ue),be=0;for(let pe of we){let J=pe.styles.length>0?(()=>{let re=C("span",pe.styles.map(ae=>`persona-tool-text-${ae}`).join(" "));return h.appendChild(re),re})():h;if(pe.isDuration&&p)J.appendChild(A());else{let re=pe.isDuration?Bi(n):pe.text;X?be=er(J,re,be):J.appendChild(document.createTextNode(re))}}};if(!W)if(p&&N!=="none"){let $=o.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),N==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${$}ms`),S&&R(S,!1);else if(h.classList.add(`persona-tool-loading-${N}`),h.style.setProperty("--persona-tool-anim-duration",`${$}ms`),N==="shimmer-color"&&(o.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),S)R(S,!0);else{let X=h.textContent||d;h.textContent="",er(h,X,0)}}else S&&R(S,!1);let H=null;if(a){H=C("div","persona-flex persona-items-center");let $=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",X=ce(l?"chevron-up":"chevron-down",16,$,2);X?H.appendChild(X):H.textContent=l?"Hide":"Show";let ue=C("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ue.append(H),g.append(y,ue)}else g.append(y);let z=C("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!l&&p&&i.activePreview&&u){let $=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:u,isActive:p,config:e??{}});UA(z,$)||(z.textContent=u),z.style.display=""}if(!l&&p&&i.activeMinHeight&&(r.style.minHeight=i.activeMinHeight),!a)return r.append(g,z),r;let V=C("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=l?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let $=C("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?$.style.color=o.contentTextColor:o.headerTextColor&&($.style.color=o.headerTextColor),$.textContent=n.name,V.appendChild($)}if(n.args!==void 0){let $=C("div","persona-space-y-1"),X=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let ue=C("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",Fp(ue,o),ue.textContent=Xo(n.args),$.append(X,ue),V.appendChild($)}if(n.chunks&&n.chunks.length){let $=C("div","persona-space-y-1"),X=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let ue=C("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",Fp(ue,o),ue.textContent=n.chunks.join(""),$.append(X,ue),V.appendChild($)}if(n.status==="complete"&&n.result!==void 0){let $=C("div","persona-space-y-1"),X=C("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let ue=C("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",Fp(ue,o),ue.textContent=Xo(n.result),$.append(X,ue),V.appendChild($)}if(n.status==="complete"&&typeof n.duration=="number"){let $=C("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&($.style.color=o.contentTextColor),$.textContent=`Duration: ${n.duration}ms`,V.appendChild($)}return(()=>{if(g.setAttribute("aria-expanded",l?"true":"false"),H){H.innerHTML="";let $=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",X=ce(l?"chevron-up":"chevron-down",16,$,2);X?H.appendChild(X):H.textContent=l?"Hide":"Show"}V.style.display=l?"":"none",z.style.display=l?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(g,z,V),r};var Or=new Map,gc=t=>{let n=(t.startsWith(To)?t.slice(To.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},uy=t=>t?.approval!==!1?t?.approval:void 0,fy=(t,e)=>{let n=uy(e)?.detailsDisplay??"collapsed";return Or.get(t)??n==="expanded"},gy=(t,e,n)=>{let o=uy(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let i=t.querySelector("[data-approval-details-chevron]");if(i){i.innerHTML="";let a=ce(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&i.appendChild(a)}},my=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let i=fy(t,n);gy(o,i,n),r.style.display=i?"":"none"};var mc=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",i=C("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",i.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",i.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return i;let a=C("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=C("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",u=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",p=ce(d,20,u,2);p&&l.appendChild(p);let g=C("div","persona-flex-1 persona-min-w-0"),y=C("div","persona-flex persona-items-center persona-gap-2"),h=C("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(h.style.color=o.titleColor),h.textContent=o?.title??"Approval Required",y.appendChild(h),!r){let H=C("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");H.setAttribute("data-approval-status",n.status),n.status==="approved"?(H.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",H.style.color="var(--persona-palette-colors-success-700, #15803d)",H.textContent="Approved"):n.status==="denied"?(H.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",H.style.color="var(--persona-palette-colors-error-700, #b91c1c)",H.textContent="Denied"):n.status==="timeout"&&(H.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",H.style.color="var(--persona-palette-colors-warning-700, #b45309)",H.textContent="Timeout"),y.appendChild(H)}g.appendChild(y);let A=n.toolType==="webmcp"||n.toolName.startsWith(To)?Pi(n.toolName):void 0,k=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...A?{displayTitle:A}:{},...n.reason?{reason:n.reason}:{}}),N=!n.toolName,I=k||(N?n.description:`The assistant wants to use \u201C${A??gc(n.toolName)}\u201D.`),P=C("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=I,g.appendChild(P),n.reason){let H=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");H.setAttribute("data-approval-reason","true"),o?.reasonColor?H.style.color=o.reasonColor:o?.descriptionColor&&(H.style.color=o.descriptionColor);let z=C("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,H.appendChild(z),H.appendChild(document.createTextNode(n.reason)),g.appendChild(H)}let S=o?.detailsDisplay??"collapsed",W=!!n.description&&!N,R=W||!!n.parameters;if(S!=="hidden"&&R){let H=fy(t.id,e),z=C("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=C("span");V.setAttribute("data-approval-details-label","true");let ne=C("span","persona-inline-flex persona-items-center");ne.setAttribute("data-approval-details-chevron","true"),z.append(V,ne),gy(z,H,e),g.appendChild(z);let $=C("div");if($.setAttribute("data-approval-details","true"),$.style.display=H?"":"none",W){let X=C("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(X.style.color=o.descriptionColor),X.textContent=n.description,$.appendChild(X)}if(n.parameters){let X=C("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(X.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(X.style.color=o.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=Xo(n.parameters),$.appendChild(X)}g.appendChild($)}if(r){let H=C("div","persona-flex persona-gap-2 persona-mt-2");H.setAttribute("data-approval-buttons","true");let z=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let V=ce("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",z.appendChild(V));let ne=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(ne);let $=C("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");$.type="button",$.style.backgroundColor=o?.denyButtonColor??"transparent",$.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",$.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,$.setAttribute("data-approval-action","deny");let X=ce("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",$.appendChild(X));let ue=document.createTextNode(o?.denyLabel??"Deny");$.appendChild(ue),H.append(z,$),g.appendChild(H)}return a.append(l,g),i.appendChild(a),i};var KA=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),hy=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},Nr=(t,e)=>{hy(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},GA=t=>t?.approval!==!1?t?.approval:void 0,YA=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Or.get(t)??n==="expanded"},jp=t=>{let e=C("span","persona-approval-kbd");return e.textContent=t,e},XA=(t,e)=>{let n=C("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(To)?Pi(t.toolName):void 0,i=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(i)return n.textContent=i,n;let a=r??gc(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),l){n.append(" from ");let u=document.createElement("strong");u.textContent=l,n.appendChild(u)}return n},QA=t=>{let e=C("div","persona-approval-resolved"),n=ce("ban",15,"currentColor",2);n&&e.appendChild(n);let o=C("span","persona-approval-resolved-name");return o.textContent=t.toolName?gc(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},JA=(t,e,n,o,r,i,a)=>{let l=C("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",u=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",g=u||p,y=g&&YA(e.id,o),h=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",A=C("button","persona-approval-head");A.type="button",g?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",y?"true":"false"),A.setAttribute("aria-label",y?b:h)):A.setAttribute("data-static","true");let k=C("span","persona-approval-logo"),N=ce("shield-check",16,"currentColor",2);N&&k.appendChild(N),A.appendChild(k);let I=XA(n,o);if(g){let z=C("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let V=ce("chevron-down",14,"currentColor",2);V&&z.appendChild(V),I.append(" "),I.appendChild(z)}A.appendChild(I),l.appendChild(A);let P=C("div","persona-approval-body");if(g){let z=C("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!y,u){let V=C("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,z.appendChild(V)}if(p){let V=C("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=Xo(n.parameters),z.appendChild(V)}P.appendChild(z)}if(n.reason){let z=C("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let V=C("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(V,document.createTextNode(n.reason)),P.appendChild(z)}let S=C("div","persona-approval-actions"),W=null,R=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},H=C("button","persona-approval-deny");if(H.type="button",H.setAttribute("data-action","deny"),o?.denyButtonColor&&(H.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(H.style.color=o.denyButtonTextColor),H.append(o?.denyLabel??"Deny"),a){let z=C("div","persona-approval-split"),V=C("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),R(V),V.append(o?.approveLabel??"Always allow",jp("\u23CE"));let ne=C("button","persona-approval-caret");ne.type="button",ne.setAttribute("data-action","toggle-menu"),ne.setAttribute("aria-label","More options"),R(ne);let $=ce("chevron-down",15,"currentColor",2);$&&ne.appendChild($),z.append(V,ne),S.append(z,H),H.append(jp("Esc"));let X=C("div","persona-approval-menu"),ue=C("button","persona-approval-menu-item");ue.type="button",ue.append("Allow once",jp("\u2318\u23CE")),X.appendChild(ue),W=Hg({anchor:z,content:X,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,W),ue.addEventListener("click",()=>{Nr(t,e.id),r()})}else{let z=C("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),R(z),z.append(o?.approveLabel??"Allow"),S.append(z,H)}return P.appendChild(S),l.appendChild(P),l.addEventListener("click",z=>{let V=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!V)return;let ne=V.getAttribute("data-action");if(ne==="toggle-params"){let $=l.querySelector('[data-role="params"]');if($){let X=$.hidden;$.hidden=!X,A.setAttribute("aria-expanded",X?"true":"false"),A.setAttribute("aria-label",X?b:h),Or.set(e.id,X)}return}if(ne==="toggle-menu"){W?.toggle();return}if(ne==="always"){Nr(t,e.id),r({remember:!0});return}if(ne==="allow"){Nr(t,e.id),r();return}if(ne==="deny"){Nr(t,e.id),i();return}}),l},yy=()=>{let t=KA();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:i,config:a})=>{let l=o?.approval;if(!l)return null;let d=GA(a);if(l.status!=="pending"){if(Nr(t,o.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return QA(l)}hy(t,o.id);let u=d?.enableAlwaysAllow===!0,p=JA(t,o,l,d,r,i,u);if(u){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=y=>{Rg(y)||o.id===t.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),Nr(t,o.id),y.key==="Escape"?i():y.metaKey||y.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return p}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])Nr(t,o);t.latestPendingApprovalId=null}}};var da=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var pa=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();i.onsuccess=()=>{e(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();i.onsuccess=()=>{e()},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var ZA=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),eS=new Set(["step_start","execution_start"]),tS=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),nS=new Set(["step_complete","agent_turn_complete"]),oS=new Set(["flow_complete","agent_complete"]),by=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),wy=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),kn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Fr=(t,e)=>{let n=t[e];return wy(n)?n:void 0};function zp(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function hc(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function rS(t,e){return typeof e.type=="string"?e.type:t}function sS(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function iS(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function vy(t){let e=Fr(t,"result"),n=[Fr(t,"tokens"),Fr(t,"totalTokens"),e?Fr(e,"tokens"):void 0,Fr(t,"usage"),e?Fr(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=kn(o.output)??kn(o.outputTokens)??kn(o.completionTokens);if(r!==void 0)return r}return kn(t.outputTokens)??kn(t.completionTokens)??(e?kn(e.outputTokens)??kn(e.completionTokens):void 0)}function aS(t){let e=Fr(t,"result");return kn(t.executionTime)??kn(t.executionTimeMs)??kn(t.execution_time)??kn(t.duration)??(e?kn(e.executionTime)??kn(e.executionTimeMs):void 0)}function lS(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ua=class{constructor(e=lS){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:hc(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!wy(n)){by.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=rS(e,n),r=this.now();if(ZA.has(o)){this.startRun(r);return}if(eS.has(o)){this.run||this.startRun(r);return}if(tS.has(o)){if(!iS(o,n))return;let i=sS(n);if(!i)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=i.length;let l=a.exactOutputTokens+zp(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:hc(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(nS.has(o)){if(!this.run)return;let i=this.run,a=vy(n);a!==void 0&&(i.exactOutputTokens+=a,i.visibleCharCount=0);let l=i.exactOutputTokens>0,d=i.exactOutputTokens+zp(i.visibleCharCount),u=this.resolveDuration(i,n,r);this.metric={status:"running",tokensPerSecond:hc(d,u),outputTokens:d,durationMs:u,source:l?"usage":"estimate"};return}if(oS.has(o)){if(!this.run)return;let i=this.run,a=vy(n),l=a??i.exactOutputTokens+zp(i.visibleCharCount),d=a!==void 0||i.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(i,n,r);this.metric={status:"complete",tokensPerSecond:hc(l,u),outputTokens:l,durationMs:u,source:d},this.run=null;return}if(by.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:aS(n)??o-e.startedAt}};var{setLoader:SP,load:cS}=no({fallbackImport:()=>import("./event-stream-view-4EZ7BGFK.js")});var Cy=cS;function xy(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let i=[],a=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},d=g=>{let y=g;return i.findIndex(h=>h===y||h.contains(y))},u=g=>{let y=d(g.target);if(y<0)return;let h=y;if(g.key===r)h=Math.min(y+1,i.length-1);else if(g.key===o)h=Math.max(y-1,0);else if(g.key==="Home")h=0;else if(g.key==="End")h=i.length-1;else return;g.preventDefault(),h!==y&&e.onSelect(h)},p=g=>{let y=d(g.target);y>=0&&l(i[y])};return t.addEventListener("keydown",u),t.addEventListener("focusin",p),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(g,y){if(i=g,g.forEach((h,b)=>{h.setAttribute("role","tab");let A=b===y;h.setAttribute("aria-selected",A?"true":"false"),h.tabIndex=A||y<0&&b===0?0:-1}),a){let h=(y>=0?g[y]:void 0)??g[0];h&&typeof h.focus=="function"&&(l(h),h.focus())}},destroy(){t.removeEventListener("keydown",u),t.removeEventListener("focusin",p)}}}function Ay(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",i=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),u=x=>({start:x===!1?!1:typeof x=="object"&&x?x.start!==!1:!0,end:x===!1?!1:typeof x=="object"&&x?x.end!==!1:!0}),{start:p,end:g}=u(n?.tabFade),y=typeof document<"u"?C("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,h=()=>{y?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),$?.closeMenu()};y&&y.addEventListener("click",()=>{h(),e.onDismiss?.()});let b=C("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let A=C("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");A.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&A.classList.add("persona-artifact-toolbar-document");let k=C("span","persona-text-xs persona-font-medium persona-truncate");k.textContent=i;let N=_t({icon:"x",label:a});N.addEventListener("click",()=>{h(),e.onDismiss?.()});let I="rendered",P=Kl({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:x=>{I=x==="source"?"source":"rendered",O()}}),S=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=n?.documentToolbarShowCopyLabel===!0,R=n?.documentToolbarShowCopyChevron===!0,H=n?.documentToolbarCopyMenuItems,z=!!(R&&H&&H.length>0),V=null,ne,$=null;if(r&&(W||R)&&!z){if(ne=W?Wr({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let x=ce("chevron-down",14,"currentColor",2);x&&ne.appendChild(x)}}else r&&z?($=xh({label:"Copy",icon:"copy",iconSize:14,iconOnly:!W,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(H??[]).map(x=>({id:x.id,label:x.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:x=>{Ce(x)}}),V=$.element,ne=$.primaryButton):r?ne=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(ne=_t({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&ne.classList.add("persona-hidden"));let X=r?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||X.classList.add("persona-hidden");let ue=r?_t({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:a}),we=_t({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&we.classList.add("persona-hidden");let be=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),pe=t.features?.artifacts?.toolbarActions??[],J=()=>{let x=Me.find(q=>q.id===Ke)??Me[Me.length-1],L=x?.id??null,E=x?.artifactType==="markdown"?x.markdown??"":"",B=x?JSON.stringify({component:x.component,props:x.props},null,2):"",{filename:G,mime:Q,content:K}=zl({title:x?.title,markdown:x?.markdown??"",file:x?.file});return{markdown:E,jsonPayload:B,id:L,file:x?.file,suggestedFilename:G,mime:Q,content:K}},re=()=>{let{suggestedFilename:x,mime:L,content:E}=J();E&&Ul({filename:x,mime:L,content:E})},ae=x=>{let{id:L,...E}=J();return{actionId:x,artifactId:L,...E}},T=async()=>{let x=Me.find(L=>L.id===Ke)??Me[Me.length-1];try{return await navigator.clipboard.writeText(Ji(x)),!0}catch{return!1}},Z=null,de=()=>{Z?.();let x=ne.querySelector("svg"),L=Number(x?.getAttribute("width"))||16,E=ce("check",L,"currentColor",2);if(!x||!E)return;x.replaceWith(E);let B=ne.querySelector("span");B&&(B.textContent="Copied");let G=setTimeout(()=>Z?.(),2e3);Z=()=>{clearTimeout(G),E.replaceWith(x),B&&(B.textContent="Copy"),Z=null}};ne.addEventListener("click",async()=>{let x=n?.onDocumentToolbarCopyMenuSelect;if(x&&z){try{if(await x(ae("primary"))===!1){await T()&&de();return}de()}catch{}return}await T()&&de()});async function Ce(x){let L=n?.onDocumentToolbarCopyMenuSelect;try{if(L&&await L(ae(x))!==!1)return;if(x==="download"){re();return}let{markdown:E,jsonPayload:B}=J();x==="markdown"||x==="md"?await navigator.clipboard.writeText(E):x==="json"||x==="source"?await navigator.clipboard.writeText(B):await navigator.clipboard.writeText(E||B),de()}catch{}}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}O()}),ue.addEventListener("click",()=>{h(),e.onDismiss?.()});let he=C("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)A.replaceChildren(),V?S.append(V,X,ue):S.append(ne,X,ue),S.insertBefore(be,ue),S.insertBefore(we,ue),A.append(P.element,he,S);else{let x=C("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");x.append(ne,be,we,N),A.appendChild(k),A.appendChild(x)}l&&(A.style.paddingLeft=l,A.style.paddingRight=l);let ve=C("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");d&&ve.style.setProperty("--persona-artifact-tab-fade-size",d);let xe=t.features?.artifacts?.renderTabBar,Pe=C("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Xe=xy(ve,{onSelect:x=>e.onSelect(Me[x].id)}),Qe=x=>{let L=x.scrollWidth-x.clientWidth,E=L>1,B=Math.abs(x.scrollLeft);x.classList.toggle("persona-artifact-tab-fade-start",p&&E&&B>1),x.classList.toggle("persona-artifact-tab-fade-end",g&&E&&B<L-1)},We=0,nt=()=>{if(We)return;let x=()=>{We=0,Qe(ve)};We=typeof requestAnimationFrame=="function"?requestAnimationFrame(x):setTimeout(x,0)};ve.addEventListener("scroll",()=>nt(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Qe(ve)).observe(ve);let bt=C("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),mt=()=>{bt.scrollLeft=0},Pn=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(mt):setTimeout(mt,0)};if(l){for(let x of[ve,Pe])x.style.paddingLeft=l,x.style.paddingRight=l;bt.style.padding=l}b.appendChild(A),b.appendChild(ve),b.appendChild(Pe),b.appendChild(bt);let Me=[],Ke=null,ot=!1,qt=!1,jt=!0,zn=!1,Ye=null,Je="",ht=null,Qt=!1,io=x=>x.artifactType==="markdown"&&!!x.file||r?I:"rendered",Lt=x=>{r||(x&&!Qt?(A.insertBefore(P.element,k),Qt=!0):!x&&Qt&&(P.element.remove(),Qt=!1))},Ho=()=>Ke&&Me.find(x=>x.id===Ke)||Me[Me.length-1],zr=()=>{let x=Xi(Ho());if(!x){be.replaceChildren();return}let L=pe.filter(E=>E.visible===void 0||E.visible(x)).map(E=>Is(E,{documentChrome:r,onClick:()=>{let B=Xi(Ho());if(B)try{Promise.resolve(E.onClick(B)).catch(()=>{})}catch{}}}));be.replaceChildren(...L)},O=()=>{zr();let x=r&&Me.length<=1,L=!!xe;if(ve.classList.toggle("persona-hidden",x||L),Pe.classList.toggle("persona-hidden",x||!L),L&&xe){let G=Me.map(Q=>Q.id).join("|")+" "+(Ke??"");if(G!==Je){Je=G;let Q=xe({records:Me,selectedId:Ke,onSelect:e.onSelect});Pe.firstElementChild!==Q&&Pe.replaceChildren(Q)}}else{Xe.beforeRender(),ve.replaceChildren();let G=[],Q=-1;for(let[K,q]of Me.entries()){let le=C("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");le.type="button";let it=q.artifactType==="markdown"?q.file:void 0,et=it?ro(it.path):q.title||q.id.slice(0,8),yt=it?.path||q.title||et;le.textContent=et,le.title=yt,le.setAttribute("aria-label",yt),q.id===Ke&&(le.classList.add("persona-bg-persona-container","persona-border-persona-border"),Q=K),le.addEventListener("click",()=>e.onSelect(q.id)),ve.appendChild(le),G.push(le)}if(Xe.render(G,Q),Q>=0&&Ke!==Ye){Ye=Ke;let K=G[Q];typeof K.scrollIntoView=="function"&&K.scrollIntoView({block:"nearest",inline:"nearest"})}Qe(ve)}let E=Ke&&Me.find(G=>G.id===Ke)||Me[Me.length-1];if(!E){bt.replaceChildren(),ht?.destroy(),ht=null,Lt(!1);return}let B=E.artifactType==="markdown"?E.file:void 0;if(Lt(!!B&&Hr(B)!=="other"),r){let G=B?Zo(B):E.artifactType==="markdown"?"MD":E.component??"Component",Q=(E.title||"Document").trim(),K=B?ro(B.path):Q.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${K} \xB7 ${G}`}else k.textContent=B?ro(B.path):i;ht?(ht.el.parentElement!==bt&&bt.replaceChildren(ht.el),ht.update(E)):(ht=Xl(E,{config:t,resolveViewMode:io}),bt.replaceChildren(ht.el)),bt.classList.toggle("persona-artifact-content-flush",!!bt.querySelector(".persona-code-pre"))},ee=()=>{let x=Me.length>0;if(b.classList.toggle("persona-hidden",!x),y){let B=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;x&&B&&ot?(y.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},w=()=>{zn=!1,O(),ee()};return{element:b,backdrop:y,update(x){let L=x.selectedId??x.artifacts[x.artifacts.length-1]?.id??null,E=L!==Ke;Me=x.artifacts,Ke=L,Me.length>0&&(ot=!0),zn=!0,jt&&w(),E&&mt()},setMobileOpen(x){ot=x,!x&&y?(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ee()},setExpanded(x){x!==qt&&(qt=x,Pn());let L=ce(x?"minimize":"maximize",16,"currentColor",2);L&&we.replaceChildren(L);let E=x?"Collapse artifacts panel":"Expand artifacts panel";we.setAttribute("aria-label",E),we.title=E},setExpandToggleVisible(x){we.classList.toggle("persona-hidden",!x)},setCopyButtonVisible(x){r||ne.classList.toggle("persona-hidden",!x)},setRefreshButtonVisible(x){X.classList.toggle("persona-hidden",!x)},setCustomActions(x){pe=x,zr()},setTabFade(x){let L=u(x);L.start===p&&L.end===g||(p=L.start,g=L.end,Qe(ve))},setRenderTabBar(x){x!==xe&&(xe=x,Je="",O())},setVisible(x){x!==jt&&(jt=x,x&&zn&&w())},destroy(){ht?.destroy(),ht=null}}}function pn(t){return t?.features?.artifacts?.enabled===!0}function Sy(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!pn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function dS(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Ty=["panel","seamless","detached"];function Up(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Ty.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Vp(t){return!t||!pn(t)?!1:Up(t)==="detached"}function fa(t,e){if(!pn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),dS(t),Sy(t,e);return}let n=e.features?.artifacts?.layout,o=Up(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let u=l?.trim();u?t.style.setProperty(d,u):t.style.removeProperty(d)}Sy(t,e)}function ga(t,e){for(let l of Ty)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!pn(e))return;let n=e.features?.artifacts?.layout,o=Up(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function My(t,e){return!e||!pn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var pS=new Set(["__proto__","prototype","constructor"]),uS=new Set(["collapsed","card","panel","inline"]),Ey=new Set(["markdown","component"]),fS=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,$r=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),bc=t=>!pS.has(t),qp=t=>typeof t=="string"&&uS.has(t),jr=t=>Object.keys(t).length>0;function so(t,e,n,o){t.push({path:e,code:n,message:o})}var gS="Ignored because this key is not part of the persisted preference schema.",yc="Ignored an unsupported value.",mS="Expected collapsed, panel, or inline.",hS='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',ky={kind:"mode",message:yc},Ns={kind:"string",message:"Expected a CSS length string."},Lo={kind:"boolean"},yS={paneWidth:Ns,paneMaxWidth:Ns,paneMinWidth:Ns,expandedPanelWidth:Ns,resizableMinWidth:Ns,resizableMaxWidth:Ns,expandLauncherPanelWhenOpen:Lo,resizable:Lo},bS={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Lo,showReasoning:Lo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:yc},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:yc},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:yc},expandable:Lo,grouped:Lo}},reasoningDisplay:{kind:"object",children:{expandable:Lo,activePreview:Lo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:ky,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:ky,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Ey,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Ey}}},filePreview:{kind:"object",children:{enabled:Lo}},layout:{kind:"object",children:yS}}}}};function Py(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:so(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:so(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:so(o,n,"invalid_value",e.message);case"mode":return qp(t)?Nn(t):so(o,n,"invalid_value",e.message);case"modeMap":{if(!$r(t))return so(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,i={};for(let[a,l]of Object.entries(t)){let d=r?a:ms(a);bc(a)&&(r?r.has(a):fS.test(d))?qp(l)?i[d]=Nn(l):so(o,`${n}.${a}`,"invalid_value",mS):so(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":hS)}return jr(i)?i:void 0}case"object":{if(e.bareMode&&qp(t))return Nn(t);if(!$r(t))return so(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),i=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!bc(l)||!r.includes(l))&&so(o,i(l),"unknown_key",gS);let a={};for(let l of r){let d=e.children[l],u=Py(t[l],d,i(l),o);if(d.deprecated&&t[l]!==void 0&&so(o,i(l),"deprecated_key",d.deprecated),u===void 0)continue;let p=d.alias??l,g=a[p];a[p]=$r(g)&&$r(u)?{...g,...u}:u}return jr(a)?a:void 0}}}function vS(t){let e=[];return{preferences:(t===null?void 0:Py(t,bS,"",e))??{},issues:e}}function Fs(t){if(Array.isArray(t))return t.map(Fs);if(!$r(t))return t;let e={};for(let[n,o]of Object.entries(t))bc(n)&&o!==void 0&&(e[n]=Fs(o));return e}function Ly(t,e){let n=Fs(t);for(let[o,r]of Object.entries(e)){if(!bc(o)||r===void 0)continue;let i=n[o];n[o]=$r(i)&&$r(r)?Ly(i,r):Fs(r)}return n}function wS(t){let e={},n;for(let r of t){let i=vS(r).preferences;n=Iy(n,i.artifacts?.display),e=Ly(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function CS(t,e){if(e===void 0)return t===void 0?void 0:Fs(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...jr(r)?{byMediaType:r}:{}};return jr(i)?i:void 0}function Iy(t,e){if(e===void 0)return t===void 0?void 0:Fs(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},i=CS(n.files,e.files),a={...o?{default:o}:{},...jr(r)?{byKind:r}:{},...i!==void 0?{files:i}:{}};return jr(a)?a:void 0}function xS(t={},e){let n=wS(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},i={...r};if(n.artifacts.display!==void 0){let a=Iy(r.display,n.artifacts.display);a!==void 0&&(i.display=a)}n.artifacts.filePreview&&(i.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...r.layout,...n.artifacts.layout}),o.artifacts=i}return o}function Kp(t){let e=t.preferences;return!e||!jr(e)?t:{...t,features:xS(t.features??{},[e])}}function AS(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function SS(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function TS(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function MS(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Gp(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function Hy(t,e,n,o,r,i,a=200){let l=AS(r,200),d=MS(e,n,o,a);d=Math.max(l,d);let u=SS(i);return u!==null&&(d=Math.min(d,u)),TS(t,l,d)}var Ry={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Yp=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(i=>{if(i.dataset.enhanced==="true")return;let a=i.dataset.tvForm??"init";i.dataset.enhanced="true";let l=Ry[a]??Ry.init;i.classList.add("persona-form-card","persona-space-y-4");let d=C("div","persona-space-y-1"),u=C("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(u.textContent=l.title,d.appendChild(u),l.description){let b=C("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let A=C("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${e.id}-${a}-${b.name}`;let k=C("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=b.label,A.appendChild(k);let N=b.type??"text",I;N==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=N),I.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",I.id=`${e.id}-${a}-${b.name}`,I.name=b.name,I.placeholder=b.placeholder??"",b.required&&(I.required=!0),A.appendChild(I),p.appendChild(A)});let g=C("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=C("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),h=C("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");h.type="submit",h.textContent=l.submitLabel??"Submit",g.appendChild(y),g.appendChild(h),p.appendChild(g),i.replaceChildren(d,p),p.addEventListener("submit",async b=>{b.preventDefault();let A=n.formEndpoint??"/form",k=new FormData(p),N={};k.forEach((I,P)=>{N[P]=I}),N.type=a,h.disabled=!0,y.textContent="Submitting\u2026";try{let I=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let P=await I.json();y.textContent=P.message??"Thanks! We'll be in touch soon.",P.success&&P.nextPrompt&&await o.sendMessage(String(P.nextPrompt))}catch(I){y.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{h.disabled=!1}})})};var Xp=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,a)=>(a.priority??0)-(i.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Qp=new Xp;var Wy=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ES=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),By=(t,e,n)=>{if(!Wy(t)||!Wy(e)||ES.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let i=n?`${n}.${r}`:r;o[r]=By(t[r],e[r],i)}return o};function Dy(t,e){let n=By(t,e,"");return Bl(n)}var _y=()=>{let t=new Map,e=(r,i)=>(t.has(r)||t.set(r,new Set),t.get(r).add(i),()=>n(r,i)),n=(r,i)=>{t.get(r)?.delete(i)};return{on:e,off:n,emit:(r,i)=>{t.get(r)?.forEach(a=>{try{a(i)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var kS=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},PS=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let i=e[r];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},Zp=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=kS(t),n=PS(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...i}=o;return{type:String(r),payload:i,raw:o}}catch{return null}},Jp=t=>typeof t=="string"?t:t==null?"":String(t),ma={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Jp(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Jp(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Jp(n.text)}}},Oy=t=>Array.isArray(t)?t.map(e=>String(e)):[],eu=t=>{let e=new Set(Oy(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Oy(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let a=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!a&&typeof i.text=="string"&&i.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((u,p)=>u||p?.({text:a,message:i.message})||null,null):null;if(!l)return null;e.add(i.message.id),o();let d={action:l,message:i.message};t.emit("action:detected",d);for(let u of t.handlers)if(u)try{let p=()=>{t.emit("action:resubmit",d)},g=u(l,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:p});if(!g)continue;if(g.handled){let y=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:y,resubmit:g.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var LS=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},IS=t=>t.map(e=>({...e,streaming:!1})),HS=t=>t.map(e=>({...e,status:"complete"})),Ny=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?LS(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?IS(n.messages):void 0,artifacts:n.artifacts?HS(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var RS=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},Fy=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return RS(t)},WS=async(t,e)=>{let n=await Fy(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Fy(`${t}\0${e}`)}`}};var $y=(t,e,n)=>{let o="",r="",i="",a=!1,l=!1,d=0,u=null,p=null,g=new Set,y=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},h=()=>{let R=y();if(!R)return u;try{return R.getItem(o)}catch{return a=!0,u}},b=(R,H)=>{if(l||R===u)return;let z=u;u=R,d+=1;let V={previousToken:z,token:R,source:H,revision:d};for(let ne of g)ne(V)},A=R=>{l||R.key!==null&&R.key!==o||b(R.key===null?null:R.newValue??null,"external")},k=(async()=>{let R=await WS(t,e);o=R.storageKey,r=R.leaseKey,i=R.lockName,u=h(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),N=R=>new Promise(H=>setTimeout(H,R)),I=()=>{let R=y();if(!R)return null;try{let H=R.getItem(r);if(!H)return null;let z=JSON.parse(H);return typeof z?.expiresAt=="number"&&typeof z?.ownerNonce=="string"?z:null}catch{return null}},P=R=>{let H=y();if(H)try{I()?.ownerNonce===R&&H.removeItem(r)}catch{}},S=R=>new Promise(H=>{let z=setTimeout(V,R);function V(){clearTimeout(z),window.removeEventListener("storage",ne),H()}function ne($){($.key===null||$.key===r)&&V()}window.addEventListener("storage",ne)}),W=async R=>{let H=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,z=Date.now()+15e3;for(;Date.now()<z;){let V=y();if(!V)break;let ne=Date.now(),$=I();if($&&$.expiresAt>ne&&$.ownerNonce!==H){await S(Math.min($.expiresAt-ne,500));continue}try{V.setItem(r,JSON.stringify({ownerNonce:H,expiresAt:ne+1e4}))}catch{a=!0;break}if(await N(20+Math.random()*40),I()?.ownerNonce!==H){await S(500);continue}p=H;try{return await R()}finally{p=null,P(H)}}return R()};return{ready:k,async get(){return await k,b(h(),"external"),u},async set(R){await k;let H=y();if(H)try{H.setItem(o,R)}catch{a=!0}b(R,"local")},async clear(){await k;let R=y();if(R)try{R.removeItem(o)}catch{a=!0}b(null,"local")},revision(){return d},subscribe(R){return g.add(R),()=>{g.delete(R)}},async withFirstInitLock(R){await k;let H=globalThis.navigator?.locks;return H?.request?H.request(i,()=>R()):y()?W(R):R()},matches(R,H,z){return R===t&&H===e&&z===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",A),p&&P(p)}}};var{setLoader:YP,load:BS}=no({fallbackImport:()=>import("./history-view-BD6OXLNA.js")});var tu=BS;var nu=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Io=t=>Object.freeze({...t}),jy=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),zy=t=>t?Io(t):null;function Uy(t){let{plugins:e,config:n}=t,o=!1,r=!1,i=!1,a=!1,l=null,d=[],u=()=>{for(let S of d.splice(0))try{S()}catch(W){nu("renderHistoryView cleanup",W)}},p=(S,W)=>{for(let R of e){let H=R[S];if(H)try{let z=H(W);if(z)return z}catch(z){nu(S,z)}}return null},g=()=>({presentation:t.getPresentation(),config:n}),y={header:S=>a?p("renderHistoryHeader",Object.freeze({...g(),returnSurface:t.getReturnSurface(),identityStatus:Io(S.identityStatus),pendingAction:zy(S.pendingAction),copy:Io(S.copy),actions:Object.freeze({close:A.close,startNewConversation:A.startNewConversation}),defaultRenderer:S.defaultRenderer})):null,conversation:S=>a?p("renderHistoryConversation",Object.freeze({...g(),conversation:jy(S.conversation),active:S.active,pending:S.pending,open:S.open,requestDelete:S.requestDelete,defaultRenderer:S.defaultRenderer})):null,state:S=>a?p("renderHistoryState",Object.freeze({...g(),state:Io(S.state),identityStatus:Io(S.identityStatus),copy:Io(S.copy),...S.retry?{retry:S.retry}:{},...S.startNewConversation?{startNewConversation:S.startNewConversation}:{},defaultRenderer:S.defaultRenderer})):null},h=e.flatMap(S=>(S.railSections??[]).map(W=>({...W,placement:W.placement??"above-conversations",items:[],render:R=>W.render(Object.freeze({collapsed:R,presentation:t.getPresentation(),actions:A}))}))),b=t.createView({slots:y,renderDom:!1,onModelChange:()=>P(),railSections:h}),A=Object.freeze({...b.operations,close:t.close}),k=()=>(a=!0,b.setDomRenderEnabled(!0),b.element),N=S=>Object.freeze({conversations:Object.freeze(S.conversations.map(jy)),activeConversationId:S.activeConversationId,state:Io(S.state),pendingAction:zy(S.pendingAction),identityStatus:Io(S.identityStatus),nextCursor:S.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Io(b.copy),actions:A,defaultRenderer:k,requestRender:()=>P(),onCleanup:W=>{d.push(W)}}),I=()=>{a=!1;let S=null;for(let R of e)if(R.renderHistoryView){try{S=R.renderHistoryView(N(b.getModel()))}catch(H){nu("renderHistoryView",H),S=null}if(S)break}let W=!S||S.contains(b.element);return a=W,b.setDomRenderEnabled(W),S??b.element};function P(){if(!(!i||o||r)){r=!0;try{u();let S=I();if(S===l)return;let W=l;l=S,t.onElementChanged(S,W)}finally{r=!1}}}return i=!0,P(),{view:b,get element(){return l??b.element},requestRender:P,dispose:()=>{o=!0,u()}}}var DS=null;function Vy(){return DS}var _S=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),OS=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),ou=t=>OS.get(t)??"Conversation history is unavailable right now.";function NS(t){if(t instanceof Er)return t;if(t instanceof Re){let e=_S.get(t.code)??"unavailable";return new Er(e,ou(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new Er("unavailable",ou("unavailable"))}function qy(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new Er("unsupported_scope",ou("unsupported_scope"))},i=async(l,d)=>{r(l);try{return await d()}catch(u){throw NS(u)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return i(l.context.scope,async()=>{let d=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return i(d.context.scope,async()=>{let u=await e().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),p=Im(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:Oi([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(l,d){return i(d.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return i(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,d){await i(d.context.scope,()=>e().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return i(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var FS="button:not([disabled])";function vc(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,i=fe("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=fe("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=fe("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},fe("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),fe("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),fe("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},i,a));for(let u of[i,a])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";i.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",i.style.background="transparent",i.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=fe("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(u=>{let p=!1,g=h=>{p||(p=!0,d.removeEventListener("keydown",y,!0),d.remove(),e?.focus(),u(h))};function y(h){if(h.key==="Escape"){h.preventDefault(),h.stopPropagation(),g(!1);return}if(h.key!=="Tab")return;let b=Array.from(l.querySelectorAll(FS));if(b.length===0)return;let A=b[0],k=b[b.length-1],N=document.activeElement;h.shiftKey&&(N===A||!l.contains(N))?(h.preventDefault(),k.focus()):!h.shiftKey&&N===k&&(h.preventDefault(),A.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",h=>{h.target===d&&g(!1)}),i.addEventListener("click",()=>g(!1)),a.addEventListener("click",()=>g(!0)),t.host.appendChild(d),i.focus()})}import{parse as iL,STR as aL,OBJ as lL}from"partial-json";function Ky(t,e){let{config:n,message:o,onPropsUpdate:r}=e,i=Po.get(t.component);if(!i)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return i(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Gy(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function ru(t){let e=Gy(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Yy(t){let e=Gy(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var $S=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xy(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:u=$S}=t,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let g=null,y=document.createElement("div");y.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,h.appendChild(b);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=r,h.appendChild(A),y.appendChild(h);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let N=[];for(let R=1;R<=5;R++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${R} star${R>1?"s":""}: ${u[R-1]}`),H.title=u[R-1],H.dataset.rating=String(R),H.innerHTML=`
|
|
43
43
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
44
44
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
45
45
|
</svg>
|
|
46
|
-
`,N.addEventListener("click",()=>{f=F,B.forEach((z,j)=>{let te=j<F;z.classList.toggle("selected",te),z.setAttribute("aria-checked",j===F-1?"true":"false")})}),B.push(N),T.appendChild(N)}w.appendChild(T);let S=null;if(u){let F=document.createElement("div");F.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),F.appendChild(S),w.appendChild(F)}let k=document.createElement("div");k.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=l,P.addEventListener("click",()=>{n?.(),c.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let F=S?.value.trim()||void 0;await t(f,F),c.remove()}catch(F){H.disabled=!1,H.textContent=a,console.error("[CSAT Feedback] Failed to submit:",F)}}),k.appendChild(P),k.appendChild(H),w.appendChild(k),c.appendChild(w),c}function wg(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:u=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let w=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,v.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,v.appendChild(T),g.appendChild(v);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=d;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=c,S.appendChild(k),S.appendChild(P);let H=document.createElement("div");H.className="persona-feedback-numbers";let F=[];for(let A=0;A<=10;A++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${A} out of 10`),G.textContent=String(A),G.dataset.rating=String(A),A<=6?G.classList.add("persona-feedback-detractor"):A<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{w=A,F.forEach((Q,ie)=>{Q.classList.toggle("selected",ie===A),Q.setAttribute("aria-checked",ie===A?"true":"false")})}),F.push(G),H.appendChild(G)}B.appendChild(S),B.appendChild(H),g.appendChild(B);let N=null;if(u){let A=document.createElement("div");A.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),A.appendChild(N),g.appendChild(A)}let z=document.createElement("div");z.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=l,j.addEventListener("click",()=>{n?.(),f.remove()});let te=document.createElement("button");return te.type="button",te.className="persona-feedback-btn persona-feedback-btn-submit",te.textContent=a,te.addEventListener("click",async()=>{if(w===null){H.classList.add("persona-feedback-shake"),setTimeout(()=>H.classList.remove("persona-feedback-shake"),500);return}te.disabled=!0,te.textContent="Submitting...";try{let A=N?.value.trim()||void 0;await t(w,A),f.remove()}catch(A){te.disabled=!1,te.textContent=a,console.error("[NPS Feedback] Failed to submit:",A)}}),z.appendChild(j),z.appendChild(te),g.appendChild(z),f.appendChild(g),f}var qr="persona-chat-history",lw=30*1e3,cw=641,dw={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function pw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=dw[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Fi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function uw(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function fw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Nc=e=>!e||typeof e!="object"?{}:{...e},xg=e=>e.map(t=>({...t,streaming:!1})),Cg=(e,t,n)=>{let o=e?.markdown?Ba(e.markdown):null,r=Da(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let u=Gn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Bp(a):a,f=o(c);d=r&&u?r(f):f}else d=mo(a);return d}};function Ag(e){let t=b("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=ae(n,o,r,s);if(a&&t.appendChild(a),e?.label){let l=b("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var gw=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},mw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:gw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Sg=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=ei(t),r=o.features;o=Pc(o);let s=Hc.getForInstance(o.plugins),a=!1,l=Nf(()=>o),{plugin:u,teardown:d}=Kf();o.components&&Zn.registerAll(o.components);let c=fg(),w=o.persistState===!1?null:o.storageAdapter??mg(),g={},v=null,C=!1,T=i=>{if(o.onStateLoaded)try{let p=o.onStateLoaded(i);if(p&&typeof p=="object"&&"state"in p){let{state:m,open:y}=p;return y&&(C=!0),m}return p}catch(p){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return i};if(w?.load)try{let i=w.load();if(i&&typeof i.then=="function")v=i.then(p=>T(p??{messages:[],metadata:{}}));else{let m=T(i??{messages:[],metadata:{}});m.metadata&&(g=Nc(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=T({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let B=()=>g,S=i=>{g=i({...g})??{},nl()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dc],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick],H=Fc({parsers:k,handlers:P,getSessionMetadata:B,updateSessionMetadata:S,emit:c.emit,documentRef:typeof document<"u"?document:null});H.syncFromMetadata();let F=o.launcher?.enabled??!0,N=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,j=N,te=F,A=o.layout?.header?.layout,G=!1,Q=()=>Vs(o),ie=()=>F||Q(),Y=Q()?!1:F?N:!0,ue=!1,X=null,ge=()=>{ue=!0,X&&clearTimeout(X),X=setTimeout(()=>{ue&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ue=!1)},1e4)},Z=Cg(o,H,ge),pe=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,we=o.features?.scrollToBottom??{},he=o.features?.scrollBehavior??{},Ne=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Ue=me?new Js(Ne):null,Qe=o.features?.eventStream?.maxEvents??2e3,Oe=me?new Qs(Qe,Ue):null,_e=me?new Zs:null,Ae=null,Se=!1,ze=null,Gt=0;Ue?.open().then(()=>Oe?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let gt={onCopy:i=>{c.emit("message:copy",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.id,"copy").catch(p=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",p)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{c.emit("message:feedback",i),_?.isClientTokenMode()&&_.submitMessageFeedback(i.messageId,i.type).catch(p=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",p)}),o.messageActions?.onFeedback?.(i)}},Ht=o.statusIndicator??{},xn=i=>i==="idle"?Ht.idleText??It.idle:i==="connecting"?Ht.connectingText??It.connecting:i==="connected"?Ht.connectedText??It.connected:i==="error"?Ht.errorText??It.error:i==="paused"?Ht.pausedText??It.paused:i==="resuming"?Ht.resumingText??It.resuming:It[i];function Cn(i,p,m,y){if(y==="idle"&&m.idleLink){i.textContent="";let x=document.createElement("a");x.href=m.idleLink,x.target="_blank",x.rel="noopener noreferrer",x.textContent=p,x.style.color="inherit",x.style.textDecoration="none",i.appendChild(x)}else i.textContent=p}let et=Of({config:o,showClose:ie()}),{wrapper:Le,panel:ye,pillRoot:tt}=et.shell,Te=et.panelElements,{container:ve,body:re,messagesWrapper:xe,starterSuggestions:An,transcriptSuggestions:ne,suggestions:M,textarea:I,sendButton:h,sendButtonWrapper:W,composerForm:L,statusText:R,welcomeHost:q,welcomeIconHolder:$,greetingHost:K,introTitle:ce,introSubtitle:je,closeButton:de,iconHolder:Pe,headerTitle:Ve,headerSubtitle:$e,header:Re,footer:Ce,actionsRow:nt,rightActions:xt}=Te,dn=Te.leftActions,ra=Te.setSendButtonMode,oe=Te.micButton,pn=Te.micButtonWrapper,it=Te.attachmentButton,un=Te.attachmentButtonWrapper,St=Te.attachmentInput,Sn=Te.attachmentPreviewsContainer;ve.classList.add("persona-relative"),re.classList.add("persona-relative");let Dg=12,Gr=()=>we.label??"",Fg=()=>we.iconName??"arrow-down",Og=()=>we.enabled!==!1,nn=()=>he.mode??"anchor-top",no=()=>nn()==="follow"||nn()==="anchor-top"&&rs,Yr=()=>he.anchorTopOffset??16,Ng=()=>he.restorePosition??"bottom",qc=()=>he.pauseOnInteraction===!0,Kc=()=>he.showActivityWhilePinned!==!1,Gc=()=>he.announce===!0,Ni=()=>he.scrollbar??"on-scroll",Et=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Et.type="button",Et.style.display="none",Et.setAttribute("data-persona-scroll-to-bottom","true");let Xr=b("span","persona-flex persona-items-center"),_i=b("span",""),Mo=b("span","");Mo.setAttribute("data-persona-scroll-to-bottom-count",""),Mo.style.display="none",Et.append(Xr,_i,Mo),ve.appendChild(Et);let fn=b("div","persona-stream-anchor-spacer");fn.setAttribute("aria-hidden","true"),fn.setAttribute("data-persona-anchor-spacer",""),fn.style.flexShrink="0",fn.style.pointerEvents="none",fn.style.height="0px",fn.style.display="none",re.appendChild(fn);let Eo=b("div","persona-sr-only");Eo.setAttribute("aria-live","polite"),Eo.setAttribute("aria-atomic","true"),Eo.setAttribute("role","status"),Eo.setAttribute("data-persona-live-region",""),Object.assign(Eo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),ve.appendChild(Eo);let Qr=null,sa=null,Yc=i=>{!Gc()||!i||(sa=i,Qr===null&&(Qr=setTimeout(()=>{Qr=null,sa&&Gc()&&(Eo.textContent=sa),sa=null},400)))},ko=()=>{let p=Ce.style.display==="none"?0:Ce.offsetHeight;Et.style.bottom=`${p+Dg}px`};ko();let Xc=()=>{let i=!!Gr();Et.setAttribute("aria-label",Gr()||"Jump to latest"),Et.title=Gr(),Et.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Xr.innerHTML="";let p=ae(Fg(),"14px","currentColor",2);p?(Xr.appendChild(p),Xr.style.display=""):Xr.style.display="none",_i.textContent=Gr(),_i.style.display=i?"":"none"};Xc();let yt=null,Yt=null,Qc=null,Jc=s.find(i=>i.renderHeader);if(Jc?.renderHeader){let i=Jc.renderHeader({config:o,defaultRenderer:()=>{let p=Jo({config:o,showClose:ie()});return Ks(ve,p,o),p.header},onClose:()=>lt(!1,"user")});if(i){let p=ve.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(i),Re=i,et.header.element=i)}}let $i=()=>{if(!Oe)return;if(Se=!0,!Ae&&Oe&&(Ae=Qf({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Jr(),config:o,plugins:s,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Ae&&(re.style.display="none",Ce.parentNode?.insertBefore(Ae.element,Ce),Ae.update()),Je){Je.style.boxShadow=`inset 0 0 0 1.5px ${Kt.actionIconColor}`;let p=o.features?.eventStream?.classNames?.toggleButtonActive;p&&p.split(/\s+/).forEach(m=>m&&Je.classList.add(m))}let i=()=>{if(!Se)return;let p=Date.now();p-Gt>=200&&(Ae?.update(),Gt=p),ze=requestAnimationFrame(i)};Gt=0,ze=requestAnimationFrame(i),$t(),c.emit("eventStream:opened",{timestamp:Date.now()})},Jr=()=>{if(Se){if(Se=!1,Ae&&Ae.element.remove(),re.style.display="",Je){Je.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(p=>p&&Je.classList.remove(p))}ze!==null&&(cancelAnimationFrame(ze),ze=null),$t(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Je=null;if(me){let i=o.features?.eventStream?.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");Je=b("button",p),Je.style.width="28px",Je.style.height="28px",Je.style.color=Kt.actionIconColor,Je.type="button",Je.setAttribute("aria-label","Event Stream"),Je.title="Event Stream";let m=ae("activity","18px","currentColor",1.5);m&&Je.appendChild(m);let y=Te.clearChatButtonWrapper,x=Te.closeButtonWrapper,E=y||x;E&&E.parentNode===Re?Re.insertBefore(Je,E):Re.appendChild(Je),Je.addEventListener("click",()=>{Se?Jr():$i()})}let Zc=i=>{let p=o.attachments;if(!p?.enabled)return;let m=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!m){m=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let x=i.querySelector("[data-persona-composer-form]");x?.parentNode?x.parentNode.insertBefore(m,x):i.insertBefore(m,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let x=b("input");x.type="file",x.setAttribute("data-persona-composer-attachment-input",""),x.accept=(p.allowedTypes??Qn).join(","),x.multiple=(p.maxFiles??4)>1,x.style.display="none",x.setAttribute("aria-label",p.buttonTooltipText??"Attach files"),i.appendChild(x)}},Ui=s.find(i=>i.renderComposer),zi=!1,ed=i=>{if(!Ui?.renderComposer)return null;let p=o.composer,m=a?_.isStreaming():!1;return Ui.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Dm(),storage:l(Ui.id),onSubmit:y=>{if(!_||_.isStreaming())return;let x=y.trim(),E=yt?.hasAttachments()??!1;if(!x&&!E)return;tp();let U;E&&(U=[],U.push(...yt.getContentParts()),x&&U.push(Lr(x))),_.sendMessage(x,{contentParts:U}),E&&yt.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{St?.click()},models:p?.models,selectedModelId:p?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Qc?.()}:void 0})},td=ed(()=>Gs({config:o}).footer);td&&(et.replaceComposer(td),Ce=et.composer.footer,zi=!0);let nd=i=>{let p=(...fe)=>{for(let le of fe){let be=i.querySelector(le);if(be)return be}return null},m=i.querySelector("[data-persona-composer-form]"),y=i.querySelector("[data-persona-composer-input]"),x=i.querySelector("[data-persona-composer-submit]"),E=i.querySelector("[data-persona-composer-mic]"),U=i.querySelector("[data-persona-composer-status]");m&&(L=m),y&&(I=y),x&&(h=x),E&&(oe=E,pn=E.parentElement),U&&(R=U);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(M=O);let V=p("[data-persona-composer-attachment-button]",".persona-attachment-button");V&&(it=V,un=V.parentElement),St=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Sn=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let J=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");J&&(nt=J),dn=p(".persona-widget-composer__left-actions")};Zc(Ce),nd(Ce);let Zr=xo(o,Q());Zr&&(xe.style.maxWidth=Zr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",K.style.maxWidth=Zr,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",An.style.maxWidth=Zr,ne.style.maxWidth=Zr,ne.style.marginLeft="auto",ne.style.marginRight="auto",ne.style.width="100%");let od=()=>{let i=xo(o,Q());if(!(!i||Q()))for(let p of[L,M,Sn,R])p&&(p.style.maxWidth=i,p.style.marginLeft="auto",p.style.marginRight="auto")};od();let rd=()=>{!o.attachments?.enabled||!St||!Sn||(yt?yt.remountPreviews(Sn):(yt=Rs.fromConfig(o.attachments),yt.setPreviewsContainer(Sn)),St.addEventListener("change",i=>{let p=i.target;yt?.handleFileSelect(p.files),p.value=""}),ve.querySelector(".persona-attachment-drop-overlay")||ve.appendChild(Ag(o.attachments.dropOverlay)))};rd();let _g=()=>Yt?.prefetch(),sd=()=>{if(!(!o.contextMentions?.enabled||!I)&&(Yt=Pu({config:o,textarea:I,anchor:L??I,getMessages:()=>_.getMessages(),liveRegionHost:ve}),Yt)){let i=I;i.parentElement?.insertBefore(Yt.contextRow,i);let p=Yt.affordanceButtons;for(let m=p.length-1;m>=0;m--){let y=p[m];dn?dn.insertBefore(y,dn.firstChild):L?.appendChild(y)}}};sd(),(()=>{let i=o.layout?.slots??{},p=y=>{switch(y){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return xe;case"footer-top":return M;case"composer":return L;case"footer-bottom":return R;default:return null}},m=(y,x)=>{switch(y){case"header-left":case"header-center":case"header-right":if(y==="header-left")Re.insertBefore(x,Re.firstChild);else if(y==="header-right")Re.appendChild(x);else{let E=Re.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(x,E.nextSibling):Re.appendChild(x)}break;case"body-top":{let E=re.querySelector("[data-persona-intro-card]");E?E.replaceWith(x):re.insertBefore(x,re.firstChild);break}case"body-bottom":re.appendChild(x);break;case"footer-top":M.replaceWith(x);break;case"footer-bottom":R.replaceWith(x);break;default:break}};for(let[y,x]of Object.entries(i))if(x)try{let E=x({config:o,defaultContent:()=>p(y)});E&&m(y,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${y}":`,E)}})();let ad=i=>{let m=i.target.closest('button[data-expand-header="true"]');if(!m)return;let y=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let E=m.getAttribute("data-bubble-type");if(E==="reasoning")$r.has(x)?$r.delete(x):$r.add(x),_f(x,y);else if(E==="tool")Ur.has(x)?Ur.delete(x):Ur.add(x),$f(x,y,o);else if(E==="approval"){let O=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",V=er.get(x)??O;er.set(x,!V),Vf(x,y,o)}Bo.delete(x)};xe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ad(i))}),xe.addEventListener("keydown",i=>{let p=i.target;(i.key==="Enter"||i.key===" ")&&p.closest('button[data-expand-header="true"]')&&(i.preventDefault(),ad(i))}),xe.addEventListener("copy",i=>{let{clipboardData:p}=i;if(!p)return;let m=xe.getRootNode(),y=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let x=y.toString(),E=rf(x);!E||E===x||(p.setData("text/plain",E),i.preventDefault())});let ji=new Map,id=null,ld="idle",$g={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ug=(i,p)=>{let{icon:m,label:y}=$g[p];i.setAttribute("aria-label",y),i.title=y,i.setAttribute("aria-pressed",p==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",p!=="idle"),i.classList.toggle("persona-message-action-loading",p==="loading");let x=ae(m,14,"currentColor",2);x&&(i.innerHTML="",i.appendChild(x))},cd=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{let y=p.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Ug(p,y&&y===id?ld:"idle")})};xe.addEventListener("click",i=>{let m=i.target.closest(".persona-message-action-btn[data-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.closest("[data-actions-for]");if(!y)return;let x=y.getAttribute("data-actions-for");if(!x)return;let E=m.getAttribute("data-action");if(E==="copy"){let O=_.getMessages().find(V=>V.id===x);if(O&>.onCopy){let V=O.content||"";navigator.clipboard.writeText(V).then(()=>{m.classList.add("persona-message-action-success");let J=ae("check",14,"currentColor",2);J&&(m.innerHTML="",m.appendChild(J)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let fe=ae("copy",14,"currentColor",2);fe&&(m.innerHTML="",m.appendChild(fe))},2e3)}).catch(J=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",J)}),gt.onCopy(O)}}else if(E==="read-aloud")_.toggleReadAloud(x);else if(E==="upvote"||E==="downvote"){let O=(ji.get(x)??null)===E,V=E==="upvote"?"thumbs-up":"thumbs-down";if(O){ji.delete(x),m.classList.remove("persona-message-action-active");let J=ae(V,14,"currentColor",2);J&&(m.innerHTML="",m.appendChild(J))}else{let J=E==="upvote"?"downvote":"upvote",fe=y.querySelector(`[data-action="${J}"]`);if(fe){fe.classList.remove("persona-message-action-active");let ct=ae(J==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(fe.innerHTML="",fe.appendChild(ct))}ji.set(x,E),m.classList.add("persona-message-action-active");let le=ae(V,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(le)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Ge=_.getMessages().find(mt=>mt.id===x);Ge&>.onFeedback&>.onFeedback({type:E,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",i=>{let m=i.target.closest("button[data-approval-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.closest(".persona-approval-bubble");if(!y)return;let x=y.getAttribute("data-message-id");if(!x)return;let E=m.getAttribute("data-approval-action");if(!E)return;let U=E==="approve"?"approved":"denied",V=_.getMessages().find(fe=>fe.id===x);if(!V?.approval)return;let J=y.querySelector("[data-approval-buttons]");J&&J.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),V.approval.toolType==="webmcp"?_.resolveWebMcpApproval(x,U):_.resolveApproval(V.approval,U)});let Ye=null,es=null,Lo=()=>{},ts="none",aa=null,Tn={artifacts:[],selectedId:null},On=!1,Mn=!1,ns=!1,sr=!1,dd=()=>sr||Tn.artifacts.some(i=>ho(o.features?.artifacts,i)==="panel"),ia=()=>Tn.artifacts.length>0&&!On&&dd(),st={current:null},Vi=(i,p)=>{let m=_.getArtifactById(p),y=m?.markdown,x=m?.title||"artifact",E=m?.file,U=m?.artifactType??"markdown";if(!y){let J=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(J){let le=_.getMessages().find(be=>be.id===J);if(le?.rawContent)try{let be=JSON.parse(le.rawContent);y=be?.props?.markdown,x=be?.props?.title||x,be?.props?.file&&typeof be.props.file=="object"&&(E=be.props.file),!m&&typeof be?.props?.artifactType=="string"&&(U=be.props.artifactType)}catch{}}}return{markdown:y,title:x,file:E,artifactType:U}};xe.addEventListener("click",i=>{let m=i.target.closest("[data-download-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-download-artifact");if(!y||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:y})===!0)return;let{markdown:E,title:U,file:O}=Vi(m,y);if(!E)return;let{filename:V,mime:J,content:fe}=_u({title:U,markdown:E,file:O}),le=new Blob([fe],{type:J}),be=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=be,Ge.download=V,Ge.click(),URL.revokeObjectURL(be)}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-artifact-custom-action]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-artifact-custom-action");if(!y)return;let x=m.closest("[data-artifact-inline]"),E=x?null:m.closest("[data-open-artifact]"),U=x?x.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,V=(x?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(mt=>mt.id===y);if(!V)return;let{markdown:J,title:fe,file:le,artifactType:be}=Vi(m,U??""),Ge={artifactId:U,title:fe,artifactType:be,markdown:J,file:le};try{Promise.resolve(V.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-copy-artifact]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-copy-artifact");if(!y)return;let x=_.getArtifactById(y),E="";if(x)E=Ns(x);else{let{markdown:U,file:O,artifactType:V}=Vi(m,y);V==="markdown"&&(E=Ns({id:y,artifactType:"markdown",status:"complete",markdown:U??"",...O?{file:O}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let U=ae("check",16,"currentColor",2);U&&(m.replaceChildren(U),setTimeout(()=>{let O=ae("copy",16,"currentColor",2);O&&m.replaceChildren(O)},1500))}).catch(()=>{})}),xe.addEventListener("click",i=>{let m=i.target.closest("[data-expand-artifact-inline]");if(!m)return;i.preventDefault(),i.stopPropagation();let y=m.getAttribute("data-expand-artifact-inline");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(On=!1,sr=!0,Mn=!0,ns=!0,_.selectArtifact(y),Nn())}),xe.addEventListener("click",i=>{let p=i.target;if(p.closest("[data-download-artifact]")||p.closest("[data-artifact-custom-action]"))return;let m=p.closest("[data-open-artifact]");if(!m)return;let y=m.getAttribute("data-open-artifact");!y||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:y})===!0||(i.preventDefault(),i.stopPropagation(),On=!1,sr=!0,_.selectArtifact(y),Nn())}),xe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let p=i.target;!p.hasAttribute("data-open-artifact")&&!p.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),p.click())});let ar=Te.composerOverlay,ir=(i,p,m)=>{let y=p.trim();if(!y||!st.current)return;let x=i.getAttribute("data-tool-call-id")??"",E=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:x,answer:y,answers:m.structured,values:m.values??(m.source==="multi"?y.split(", "):[y]),isFreeText:E,source:m.source},bubbles:!0,composed:!0})),Er(ar,x);let U=st.current.getMessages().find(O=>O.toolCall?.id===x);U?.agentMetadata?.awaitingLocalTool?st.current.resolveAskUserQuestion(U,m.structured??y):st.current.sendMessage(y)},Po=i=>{let p=st.current;if(!p)return;let m=i.getAttribute("data-tool-call-id")??"",y=p.getMessages().find(x=>x.toolCall?.id===m);y&&p.persistAskUserQuestionProgress(y,{answers:Na(i,y),currentIndex:bn(i)})},pd=i=>Object.entries(i).map(([p,m])=>`${p}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),qi=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let p=bn(i),m=Mr(i);if(p>=m-1)return;let y=st.current?.getMessages().find(x=>x.toolCall?.id===i.getAttribute("data-tool-call-id"));y&&($a(i,y,o,p+1),Po(i))};ar.addEventListener("click",i=>{let m=i.target.closest("[data-ask-user-action]");if(!m)return;let y=m.closest("[data-persona-ask-sheet-for]");if(!y)return;let x=m.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),x==="dismiss"){let E=y.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),Er(ar,E);let U=st.current?.getMessages().find(O=>O.toolCall?.id===E);U?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(U),st.current?.resolveAskUserQuestion(U,"(dismissed)"));return}if(x==="pick"){let E=m.getAttribute("data-option-label");if(!E)return;let U=y.getAttribute("data-multi-select")==="true",O=yo(y);if(O&&U){let V=Ko(y)[bn(y)],J=new Set(Array.isArray(V)?V:[]);J.has(E)?J.delete(E):J.add(E),bo(y,Array.from(J)),Po(y);return}if(O){bo(y,E),Po(y),qi(y);return}if(U){let V=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",V?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!V);let J=y.querySelector('[data-ask-user-action="submit-multi"]');J&&(J.disabled=Nl(y).length===0);return}ir(y,E,{source:"pick",values:[E]});return}if(x==="submit-multi"){let E=Nl(y);if(E.length===0)return;ir(y,E.join(", "),{source:"multi",values:E});return}if(x==="open-free-text"){let E=y.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(x==="focus-free-text"){y.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(x==="submit-free-text"){let U=y.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!U.trim())return;if(yo(y)){bo(y,U.trim()),Po(y),qi(y);return}ir(y,U,{source:"free-text"});return}if(x==="next"||x==="back"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(le=>le.toolCall?.id===E);if(!U)return;let V=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(V){let le=Ko(y)[bn(y)];(typeof le!="string"||le!==V)&&bo(y,V)}let J=x==="next"?1:-1,fe=bn(y)+J;$a(y,U,o,fe),Po(y);return}if(x==="submit-all"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(le=>le.toolCall?.id===E);if(!U)return;let V=y.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";V&&bo(y,V);let J=Na(y,U);st.current.persistAskUserQuestionProgress(U,{answers:J,currentIndex:bn(y)});let fe=pd(J);ir(y,fe||"(submitted)",{source:"submit-all",structured:J});return}if(x==="skip"){if(!st.current)return;let E=y.getAttribute("data-tool-call-id")??"",U=st.current.getMessages().find(be=>be.toolCall?.id===E);if(!U)return;let O=yo(y),V=bn(y),J=Mr(y),fe=V>=J-1;if(!O){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),Er(ar,E),U.agentMetadata?.awaitingLocalTool&&(st.current.markAskUserQuestionResolved(U),st.current.resolveAskUserQuestion(U,"(dismissed)"));return}bo(y,"");let le=y.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),fe){let be=Na(y,U),Ge=pd(be);ir(y,Ge||"(skipped)",{source:"submit-all",structured:be});return}$a(y,U,o,V+1),Po(y);return}}),ar.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let m=i.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let y=m.closest("[data-persona-ask-sheet-for]");if(!y)return;i.preventDefault();let x=m.value;if(x.trim()){if(yo(y)){bo(y,x.trim()),Po(y),qi(y);return}ir(y,x,{source:"free-text"})}});let ud=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let p=i.target;if(p?.tagName==="INPUT"||p?.tagName==="TEXTAREA"||p?.isContentEditable)return;let m=ar.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let y=Number(i.key),E=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];E&&(i.preventDefault(),E.click())};document.addEventListener("keydown",ud);let oo=null,bt=null,os=null,la=null,Ki=()=>{},fd=!1,ca="",da="";function Gi(){la?.(),la=null}let gd=()=>{if(!oo||!bt)return;let i=e.classList.contains("persona-artifact-welded-split"),p=e.ownerDocument.defaultView??window,m=p.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||m){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let y=oo.firstElementChild;if(!y||y===bt)return;let x=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${x}px`,bt.style.zIndex="5";let E=Ic(oo,p),U=y.offsetWidth+E/2-x/2;bt.style.left=`${Math.max(0,U)}px`},pa=()=>{},zg=()=>{let i=e.ownerDocument.defaultView??window,p=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!p||i.innerWidth>m?!1:F||Rt(o)},ua=()=>!Jt(o)||!ia()||e.classList.contains("persona-artifact-narrow-host")||zg()||(e.ownerDocument.defaultView??window).innerWidth<cw?"none":kc(o)?"detached":"welded",Nn=()=>{if(!Ye||!Jt(o))return;ea(e,o),ta(e,o),pa();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,p=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",p>0&&p<=i);let m=ia();Ye.setVisible(m),Ye.update(Tn),On?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Mn=!1,ns=!1):Tn.artifacts.length>0&&dd()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Mn=!1,ns=!1);let y=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(y),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!y&&!ns&&(Mn=!1),Mn!==fd){let E=Ye.element;Mn?(ca=E.style.width,da=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(ca&&(E.style.width=ca),da&&(E.style.maxWidth=da),ca="",da=""),fd=Mn}e.classList.toggle("persona-artifact-expanded",Mn),Ye.setExpanded(Mn);let x=ua();x!==ts&&(ts=x,Lo()),Ki()};if(Jt(o)){ye.style.position="relative";let i=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ve),Ye=Zf(o,{onSelect:m=>st.current?.selectArtifact(m),onDismiss:()=>{On=!0,Nn()},onToggleExpand:()=>{let m=!Mn,y=Tn.selectedId??Tn.artifacts[Tn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:y,expanded:m})!==!0&&(Mn=m,m||(ns=!1),Nn())}}),Ye.element.classList.add("persona-hidden"),oo=p,p.appendChild(i),p.appendChild(Ye.element),Ye.backdrop&&ye.appendChild(Ye.backdrop),ye.appendChild(p),Ki=()=>{if(!oo||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){os?.(),os=null,Gi(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){let y=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");y.setAttribute("role","separator"),y.setAttribute("aria-orientation","vertical"),y.setAttribute("aria-label","Resize artifacts panel"),y.tabIndex=0;let x=e.ownerDocument,E=x.defaultView??window,U=O=>{if(!Ye||O.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;O.preventDefault(),Gi();let V=O.clientX,J=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,le=Ge=>{let mt=oo.getBoundingClientRect().width,ct=e.classList.contains("persona-artifact-welded-split"),sn=Ic(oo,E),At=ct?0:y.getBoundingClientRect().width||6,Lt=J-(Ge.clientX-V),D=lg(Lt,mt,sn,At,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${D}px`,Ye.element.style.maxWidth="none",gd()},be=()=>{x.removeEventListener("pointermove",le),x.removeEventListener("pointerup",be),x.removeEventListener("pointercancel",be),la=null;try{y.releasePointerCapture(O.pointerId)}catch{}};la=be,x.addEventListener("pointermove",le),x.addEventListener("pointerup",be),x.addEventListener("pointercancel",be);try{y.setPointerCapture(O.pointerId)}catch{}};y.addEventListener("pointerdown",U),bt=y,oo.insertBefore(y,Ye.element),os=()=>{y.removeEventListener("pointerdown",U)}}if(bt){let y=ia();bt.classList.toggle("persona-hidden",!y),gd()}},pa=()=>{if(!F||!Ye||(o.launcher?.sidebarMode??!1)||Rt(o)&&vn(o).reveal==="emerge")return;let y=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=E||!ng(o,F))return;let U=o.launcher?.width??o.launcherWidth??Jn,O=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ia()?(ye.style.width=O,ye.style.maxWidth=O):(ye.style.width=U,ye.style.maxWidth=U)},typeof ResizeObserver<"u"&&(es=new ResizeObserver(()=>{Nn()}),es.observe(ye))}else ye.appendChild(ve);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(Ce)),e.appendChild(Le),tt&&e.appendChild(tt);let Yi=()=>{if(Q()){ye.style.width="100%",ye.style.maxWidth="100%";let Mt=o.launcher?.composerBar??{},tn=Le.dataset.state==="expanded",Pa=Mt.expandedSize??"anchored";if(!(tn&&Pa!=="fullscreen")){ve.style.background="",ve.style.border="",ve.style.borderRadius="",ve.style.overflow="",ve.style.boxShadow="";return}let bs=o.theme?.components?.panel,Ia=Rr(o),vr=(qn,Vo)=>qn==null||qn===""?Vo:Qt(Ia,qn)??qn,Wa="1px solid var(--persona-border)",kl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",jo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ve.style.background="var(--persona-surface, #ffffff)",ve.style.border=vr(bs?.border,Wa),ve.style.borderRadius=vr(bs?.borderRadius,jo),ve.style.boxShadow=vr(bs?.shadow,kl),ve.style.overflow="hidden";return}let i=Rt(o),p=o.launcher?.sidebarMode??!1,m=i||p||(o.launcher?.fullHeight??!1),y=o.launcher?.enabled===!1,x=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,U=Rr(o),O=(Mt,tn)=>Mt==null||Mt===""?tn:Qt(U,Mt)??Mt,V=e.ownerDocument.defaultView??window,J=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,le=V.innerWidth<=fe,be=J&&le&&F,Ge=i&&J&&le,mt=o.launcher?.position??"bottom-left",ct=mt==="bottom-left"||mt==="top-left",sn=o.launcher?.zIndex??Nt,At="var(--persona-panel-border, 1px solid var(--persona-border))",Lt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",D="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ie=x&&!be&&!Ge;Ie?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let De=Ie?At:p||be?"none":At,Me=Ie?Lt:be?"none":p?ct?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":y?"none":Lt;i&&!be&&!Ie&&(Me="none",De="none");let Ct=Ie?D:p||be?"0":D,dt=O(E?.border,De),Ft=O(E?.shadow,Me),pt=O(E?.borderRadius,Ct),en=ua(),Pt=en==="detached",We=en==="welded";e.classList.toggle("persona-artifact-detached-split",Pt),e.classList.toggle("persona-artifact-welded-split",We);let Fe="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",wt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&kc(o)&&y&&!i;e.classList.toggle("persona-artifact-chat-flush",wt);let at=Pt||wt?"none":Ft,ut=Pt?At:We?"none":dt,Xe=Pt?D:pt;wt&&(ut="none",Xe="0");let He=E?.borderRadius!=null&&E.borderRadius!=="",ht=wt&&!He?"0":pt,jt=re.scrollTop;e.style.cssText="",Le.style.cssText="",ye.style.cssText="",ve.style.cssText="",re.style.cssText="",Ce.style.cssText="",Se&&(re.style.display="none"),(m||y)&&(e.style.minWidth="0");let hn=()=>{if(jt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===jt)return;let tn=re.scrollHeight-re.clientHeight;tn<=0||(re.scrollTop=Math.min(jt,tn))})};if(be){Le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Le.style.cssText=`
|
|
46
|
+
`,H.addEventListener("click",()=>{g=R,N.forEach((z,V)=>{let ne=V<R;z.classList.toggle("selected",ne),z.setAttribute("aria-checked",V===R-1?"true":"false")})}),N.push(H),k.appendChild(H)}y.appendChild(k);let I=null;if(d){let R=document.createElement("div");R.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=i,I.rows=3,I.setAttribute("aria-label","Additional comments"),R.appendChild(I),y.appendChild(R)}let P=document.createElement("div");P.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=l,S.addEventListener("click",()=>{n?.(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(g===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let R=I?.value.trim()||void 0;await e(g,R),p.remove()}catch(R){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",R)}}),P.appendChild(S),P.appendChild(W),y.appendChild(P),p.appendChild(y),p}function Qy(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:i="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,b.appendChild(A);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=r,b.appendChild(k),h.appendChild(b);let N=document.createElement("div");N.className="persona-feedback-rating persona-feedback-rating-nps",N.setAttribute("role","radiogroup"),N.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=u;let S=document.createElement("span");S.className="persona-feedback-label-high",S.textContent=p,I.appendChild(P),I.appendChild(S);let W=document.createElement("div");W.className="persona-feedback-numbers";let R=[];for(let $=0;$<=10;$++){let X=document.createElement("button");X.type="button",X.className="persona-feedback-rating-btn persona-feedback-number-btn",X.setAttribute("role","radio"),X.setAttribute("aria-checked","false"),X.setAttribute("aria-label",`Rating ${$} out of 10`),X.textContent=String($),X.dataset.rating=String($),$<=6?X.classList.add("persona-feedback-detractor"):$<=8?X.classList.add("persona-feedback-passive"):X.classList.add("persona-feedback-promoter"),X.addEventListener("click",()=>{y=$,R.forEach((ue,we)=>{ue.classList.toggle("selected",we===$),ue.setAttribute("aria-checked",we===$?"true":"false")})}),R.push(X),W.appendChild(X)}N.appendChild(I),N.appendChild(W),h.appendChild(N);let H=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=i,H.rows=3,H.setAttribute("aria-label","Additional comments"),$.appendChild(H),h.appendChild($)}let z=document.createElement("div");z.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),g.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="persona-feedback-btn persona-feedback-btn-submit",ne.textContent=a,ne.addEventListener("click",async()=>{if(y===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let $=H?.value.trim()||void 0;await e(y,$),g.remove()}catch($){ne.disabled=!1,ne.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),z.appendChild(V),z.appendChild(ne),h.appendChild(z),g.appendChild(h),g}var $s="persona-chat-history",US=30*1e3,VS=641,qS={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function KS(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let i=qS[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${i}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function wc(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function GS(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function YS(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var su=t=>!t||typeof t!="object"?{}:{...t},Jy=t=>t.map(e=>({...e,streaming:!1})),Zy=(t,e,n)=>{let o=t?.markdown?hl(t.markdown):null,r=yl(t?.sanitize);return t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),i=>{let a=i.text??"",l=i.message.rawContent??null;if(e){let p=e.process({text:a,raw:l??a,message:i.message,streaming:i.streaming});p!==null&&(a=p.text,p.persist||(i.message.__skipPersist=!0),p.resubmit&&!i.streaming&&n&&n())}let d=So()!==null,u;if(t?.postprocessMessage){let p=t.postprocessMessage({...i,text:a,raw:l??i.text??""});u=r?r(p):p}else if(o){let p=i.streaming?zg(a):a,g=o(p);u=r&&d?r(g):g}else u=Vo(a);return u}};function eb(t){let e=C("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",i=t?.iconStrokeWidth??.5,a=ce(n,o,r,i);if(a&&e.appendChild(a),t?.label){let l=C("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var XS=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let i=n[o];n[o]=i?{...i,...r}:r}return n},QS=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:XS(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),tb=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Bl(e),r=()=>{Qm({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let i=o.features;o=Kp(o);let a=Qp.getForInstance(o.plugins),l=uh(t),d=[],u=!1,p=cy(()=>o),{plugin:g,teardown:y}=yy();o.components&&Po.registerAll(o.components);let h=_y(),A=o.persistState===!1?null:o.storageAdapter??Ny(),k={},N=null,I,P=new Promise(s=>{I=s}),S=!1,W=s=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(s);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:m}=c;return m&&(S=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return s};if(A?.load)try{let s=A.load();if(s&&typeof s.then=="function")N=s.then(c=>W(c??{messages:[],metadata:{}}));else{let f=W(s??{messages:[],metadata:{}});f.metadata&&(k=su(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null})}}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",s)}else if(o.onStateLoaded)try{let s=W({messages:[],metadata:{}});s.messages?.length&&(o={...o,initialMessages:s.messages})}catch(s){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",s)}N||I();let R=()=>k,H=s=>{k=s({...k})??{},_c()},z=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zp],V=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick],ne=eu({parsers:z,handlers:V,getSessionMetadata:R,updateSessionMetadata:H,emit:h.emit,documentRef:typeof document<"u"?document:null});ne.syncFromMetadata();let $=o.launcher?.enabled??!0,X=o.launcher?.autoExpand??!1,ue=o.autoFocusInput??!1,we=X,be=$,pe=o.layout?.header?.layout,J=!1,re=()=>ra(o),ae=()=>$||re(),T=re()?!1:$?X:!0,Z=!1,de=null,Ce=()=>{Z=!0,de&&clearTimeout(de),de=setTimeout(()=>{Z&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},he=Zy(o,ne,Ce),ve=o.features?.showReasoning??!0,xe=o.features?.showToolCalls??!0,Pe=o.features?.showEventStreamToggle??!1,Xe=o.features?.scrollToBottom??{},Qe=o.features?.scrollBehavior??{},We=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",bt=`${We()}event-stream`,mt=Pe?new pa(bt):null,Pn=o.features?.eventStream?.maxEvents??2e3,Me=Pe?new da(Pn,mt):null,Ke=Pe?new ua:null,ot=null,qt=!1,jt=null,zn=0,Ye=!1,Je=null,ht=()=>{},Qt=()=>{},io=()=>{},Lt=()=>{},Ho=()=>{},zr=()=>qt||Ye&&Je==="panel";mt?.open().then(()=>Me?.restore()).catch(s=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",s)});let O={onCopy:s=>{h.emit("message:copy",s),D?.isClientTokenMode()&&D.submitMessageFeedback(s.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(s)},onFeedback:s=>{h.emit("message:feedback",s),D?.isClientTokenMode()&&D.submitMessageFeedback(s.messageId,s.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(s)}},ee=o.statusIndicator??{},w=s=>s==="idle"?ee.idleText??Dt.idle:s==="connecting"?ee.connectingText??Dt.connecting:s==="connected"?ee.connectedText??Dt.connected:s==="error"?ee.errorText??Dt.error:s==="paused"?ee.pausedText??Dt.paused:s==="resuming"?ee.resumingText??Dt.resuming:Dt[s];function x(s,c,f,m){if(m==="idle"&&f.idleLink){s.textContent="";let v=document.createElement("a");v.href=f.idleLink,v.target="_blank",v.rel="noopener noreferrer",v.textContent=c,v.style.color="inherit",v.style.textDecoration="none",s.appendChild(v)}else s.textContent=c}let L=ly({config:o,showClose:ae()}),{wrapper:E,panel:B,pillRoot:G}=L.shell,Q=L.panelElements,{container:K,body:q,messagesWrapper:le,starterSuggestions:it,transcriptSuggestions:et,suggestions:yt,textarea:me,sendButton:ye,sendButtonWrapper:Jt,composerForm:Ne,statusText:tn,welcomeHost:un,welcomeIconHolder:fb,greetingHost:bn,introTitle:gb,introSubtitle:mb,closeButton:He,iconHolder:vt,headerTitle:Ro,headerSubtitle:or,header:Se,footer:De,actionsRow:hb,rightActions:yb}=Q,Ur=Q.leftActions,uu=Q.setSendButtonMode,oe=Q.micButton,ao=Q.micButtonWrapper,dt=Q.attachmentButton,Ln=Q.attachmentButtonWrapper,St=Q.attachmentInput,Un=Q.attachmentPreviewsContainer;K.classList.add("persona-relative"),q.classList.add("persona-relative");let bb=12,zs=()=>Xe.label??"",vb=()=>Xe.iconName??"arrow-down",wb=()=>Xe.enabled!==!1,vn=()=>Qe.mode??"anchor-top",Wo=()=>vn()==="follow"||vn()==="anchor-top"&&Zs,Us=()=>Qe.anchorTopOffset??16,Cb=()=>Qe.restorePosition??"bottom",fu=()=>Qe.pauseOnInteraction===!0,gu=()=>Qe.showActivityWhilePinned!==!1,mu=()=>Qe.announce===!0,xc=()=>Qe.scrollbar??"on-scroll",It=C("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let Vs=C("span","persona-flex persona-items-center"),Ac=C("span",""),rr=C("span","");rr.setAttribute("data-persona-scroll-to-bottom-count",""),rr.style.display="none",It.append(Vs,Ac,rr),K.appendChild(It);let In=C("div","persona-stream-anchor-spacer");In.setAttribute("aria-hidden","true"),In.setAttribute("data-persona-anchor-spacer",""),In.style.flexShrink="0",In.style.pointerEvents="none",In.style.height="0px",In.style.display="none",q.appendChild(In);let lo=C("div","persona-sr-only");lo.setAttribute("aria-live","polite"),lo.setAttribute("aria-atomic","true"),lo.setAttribute("role","status"),lo.setAttribute("data-persona-live-region",""),Object.assign(lo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),K.appendChild(lo);let qs=null,ya=null,hu=s=>{!mu()||!s||(ya=s,qs===null&&(qs=setTimeout(()=>{qs=null,ya&&mu()&&(lo.textContent=ya),ya=null},400)))},sr=()=>{let c=De.style.display==="none"?0:De.offsetHeight;It.style.bottom=`${c+bb}px`};sr();let yu=()=>{let s=!!zs();It.setAttribute("aria-label",zs()||"Jump to latest"),It.title=zs(),It.setAttribute("data-persona-scroll-to-bottom-has-label",s?"true":"false"),Vs.innerHTML="";let c=ce(vb(),"14px","currentColor",2);c?(Vs.appendChild(c),Vs.style.display=""):Vs.style.display="none",Ac.textContent=zs(),Ac.style.display=s?"":"none"};yu();let pt=null,nn=null,bu=null,vu=a.find(s=>s.renderHeader);if(vu?.renderHeader){let s=vu.renderHeader({config:o,defaultRenderer:()=>{let c=Dr({config:o,showClose:ae()});return ia(K,c,o),c.header},onClose:()=>rt(!1,"user")});if(s){let c=Se;c&&(c.replaceWith(s),Se=s,L.header.element=s)}}let wu=()=>{ot&&(q.style.display="none",De.parentNode?.insertBefore(ot.element,De),ot.update())},Sc=()=>{if(!Me)return;if(qt=!0,ot?wu():Cy().then(c=>{ot||!qt||!Me||(ot=c.createEventStreamView({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>Vr(),config:o,plugins:a,getThroughput:()=>Ke?.getMetric()??{status:"idle"}}),wu())}).catch(()=>{Vr()}),Ue){Ue.style.boxShadow=`inset 0 0 0 1.5px ${dn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&Ue.classList.add(f))}let s=()=>{if(!qt)return;let c=Date.now();c-zn>=200&&(ot?.update(),zn=c),jt=requestAnimationFrame(s)};zn=0,jt=requestAnimationFrame(s),Nt(),h.emit("eventStream:opened",{timestamp:Date.now()})},Vr=()=>{if(qt){if(qt=!1,ot&&ot.element.remove(),q.style.display="",Ue){Ue.style.boxShadow="";let s=o.features?.eventStream?.classNames?.toggleButtonActive;s&&s.split(/\s+/).forEach(c=>c&&Ue.classList.remove(c))}jt!==null&&(cancelAnimationFrame(jt),jt=null),Nt(),h.emit("eventStream:closed",{timestamp:Date.now()})}},Ue=null;if(Pe){let s=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(s?.toggleButton?" "+s.toggleButton:"");Ue=C("button",c),Ue.style.width="28px",Ue.style.height="28px",Ue.style.color=dn.actionIconColor,Ue.type="button",Ue.setAttribute("aria-label","Event Stream"),Ue.title="Event Stream";let f=ce("activity","18px","currentColor",1.5);f&&Ue.appendChild(f);let m=Q.clearChatButtonWrapper,v=Q.closeButtonWrapper,M=m||v;M&&M.parentNode===Se?Se.insertBefore(Ue,M):Se.appendChild(Ue),Ue.addEventListener("click",()=>{qt?Vr():Sc()})}let Cu=s=>{let c=o.attachments;if(!c?.enabled)return;let f=s.querySelector("[data-persona-composer-attachment-previews]")??s.querySelector(".persona-attachment-previews");if(!f){f=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let v=s.querySelector("[data-persona-composer-form]");v?.parentNode?v.parentNode.insertBefore(f,v):s.insertBefore(f,s.firstChild)}if(!(s.querySelector("[data-persona-composer-attachment-input]")??s.querySelector('input[type="file"]'))){let v=C("input");v.type="file",v.setAttribute("data-persona-composer-attachment-input",""),v.accept=(c.allowedTypes??Eo).join(","),v.multiple=(c.maxFiles??4)>1,v.style.display="none",v.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),s.appendChild(v)}},Tc=a.find(s=>s.renderComposer),Ks=!1,xu=s=>{if(!Tc?.renderComposer)return null;let c=o.composer,f=u?D.isStreaming():!1;return Tc.renderComposer({config:o,defaultRenderer:s,requestRender:()=>nw(),storage:p(Tc.id),onSubmit:m=>{if(!D||D.isStreaming())return;let v=m.trim(),M=pt?.hasAttachments()??!1;if(!v&&!M)return;og();let j;M&&(j=[],j.push(...pt.getContentParts()),v&&j.push(Qo(v))),D.sendMessage(v,{contentParts:j}),M&&pt.clearAttachments()},streaming:f,disabled:f,openAttachmentPicker:()=>{St?.click()},models:c?.models,selectedModelId:c?.selectedModelId,onModelChange:m=>{o.composer={...o.composer,selectedModelId:m},o.agent&&(o.agent={...o.agent,model:m})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{bu?.()}:void 0})},Au=xu(()=>aa({config:o}).footer);Au&&(L.replaceComposer(Au),De=L.composer.footer,Ks=!0);let Su=s=>{let c=(...te)=>{for(let ie of te){let ge=s.querySelector(ie);if(ge)return ge}return null},f=s.querySelector("[data-persona-composer-form]"),m=s.querySelector("[data-persona-composer-input]"),v=s.querySelector("[data-persona-composer-submit]"),M=s.querySelector("[data-persona-composer-mic]"),j=s.querySelector("[data-persona-composer-status]");f&&(Ne=f),m&&(me=m),v&&(ye=v),M&&(oe=M,ao=M.parentElement),j&&(tn=j);let F=c("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(yt=F);let Y=c("[data-persona-composer-attachment-button]",".persona-attachment-button");Y&&(dt=Y,Ln=Y.parentElement),St=c("[data-persona-composer-attachment-input]",'input[type="file"]'),Un=c("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let U=c("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");U&&(hb=U),Ur=c(".persona-widget-composer__left-actions")};Cu(De),Su(De);let Gs=Jo(o,re());Gs&&(le.style.maxWidth=Gs,le.style.marginLeft="auto",le.style.marginRight="auto",le.style.width="100%",bn.style.maxWidth=Gs,bn.style.marginLeft="auto",bn.style.marginRight="auto",bn.style.width="100%",it.style.maxWidth=Gs,et.style.maxWidth=Gs,et.style.marginLeft="auto",et.style.marginRight="auto",et.style.width="100%");let Tu=()=>{let s=Jo(o,re());if(!(!s||re()))for(let c of[Ne,yt,Un,tn])c&&(c.style.maxWidth=s,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Tu();let Mu=()=>{!o.attachments?.enabled||!St||!Un||(pt?pt.remountPreviews(Un):(pt=zi.fromConfig(o.attachments),pt.setPreviewsContainer(Un)),St.addEventListener("change",s=>{let c=s.target;pt?.handleFileSelect(c.files),c.value=""}),K.querySelector(".persona-attachment-drop-overlay")||K.appendChild(eb(o.attachments.dropOverlay)))};Mu();let xb=()=>nn?.prefetch(),Eu=()=>{if(!(!o.contextMentions?.enabled||!me)&&(nn=th({config:o,textarea:me,anchor:Ne??me,getMessages:()=>D.getMessages(),liveRegionHost:K}),nn)){let s=me;s.parentElement?.insertBefore(nn.contextRow,s);let c=nn.affordanceButtons;for(let f=c.length-1;f>=0;f--){let m=c[f];Ur?Ur.insertBefore(m,Ur.firstChild):Ne?.appendChild(m)}}};Eu(),(()=>{let s=o.layout?.slots??{},c=m=>{switch(m){case"body-top":return q.querySelector("[data-persona-intro-card]");case"messages":return le;case"footer-top":return yt;case"composer":return Ne;case"footer-bottom":return tn;default:return null}},f=(m,v)=>{switch(m){case"header-left":case"header-center":case"header-right":if(m==="header-left")Se.insertBefore(v,Se.firstChild);else if(m==="header-right")Se.appendChild(v);else{let M=Se.querySelector(".persona-flex-col");M?M.parentNode?.insertBefore(v,M.nextSibling):Se.appendChild(v)}break;case"body-top":{let M=q.querySelector("[data-persona-intro-card]");M?M.replaceWith(v):q.insertBefore(v,q.firstChild);break}case"body-bottom":q.appendChild(v);break;case"footer-top":yt.replaceWith(v);break;case"footer-bottom":tn.replaceWith(v);break;default:break}};for(let[m,v]of Object.entries(s))if(v)try{let M=v({config:o,defaultContent:()=>c(m)});M&&f(m,M)}catch(M){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${m}":`,M)}})();let ku=s=>{let f=s.target.closest('button[data-expand-header="true"]');if(!f)return;let m=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!m)return;let v=m.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-bubble-type");if(M==="reasoning")_s.has(v)?_s.delete(v):_s.add(v),dy(v,m);else if(M==="tool")Os.has(v)?Os.delete(v):Os.add(v),py(v,m,o);else if(M==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=Or.get(v)??F;Or.set(v,!Y),my(v,m,o)}Cn.delete(v)};le.addEventListener("pointerdown",s=>{s.target.closest('button[data-expand-header="true"]')&&(s.preventDefault(),ku(s))}),le.addEventListener("keydown",s=>{let c=s.target;(s.key==="Enter"||s.key===" ")&&c.closest('button[data-expand-header="true"]')&&(s.preventDefault(),ku(s))}),le.addEventListener("copy",s=>{let{clipboardData:c}=s;if(!c)return;let f=le.getRootNode(),m=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!m||m.isCollapsed)return;let v=m.toString(),M=Hh(v);!M||M===v||(c.setData("text/plain",M),s.preventDefault())});let Mc=new Map,Pu=null,Lu="idle",Ab={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Sb=(s,c)=>{let{icon:f,label:m}=Ab[c];s.setAttribute("aria-label",m),s.title=m,s.setAttribute("aria-pressed",c==="idle"?"false":"true"),s.classList.toggle("persona-message-action-active",c!=="idle"),s.classList.toggle("persona-message-action-loading",c==="loading");let v=ce(f,14,"currentColor",2);v&&(s.innerHTML="",s.appendChild(v))},Iu=()=>{le.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let m=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Sb(c,m&&m===Pu?Lu:"idle")})};le.addEventListener("click",s=>{let f=s.target.closest(".persona-message-action-btn[data-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let m=f.closest("[data-actions-for]");if(!m)return;let v=m.getAttribute("data-actions-for");if(!v)return;let M=f.getAttribute("data-action");if(M==="copy"){let F=D.getMessages().find(Y=>Y.id===v);if(F&&O.onCopy){let Y=F.content||"";navigator.clipboard.writeText(Y).then(()=>{f.classList.add("persona-message-action-success");let U=ce("check",14,"currentColor",2);U&&(f.innerHTML="",f.appendChild(U)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let te=ce("copy",14,"currentColor",2);te&&(f.innerHTML="",f.appendChild(te))},2e3)}).catch(U=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",U)}),O.onCopy(F)}}else if(M==="read-aloud")D.toggleReadAloud(v);else if(M==="upvote"||M==="downvote"){let F=(Mc.get(v)??null)===M,Y=M==="upvote"?"thumbs-up":"thumbs-down";if(F){Mc.delete(v),f.classList.remove("persona-message-action-active");let U=ce(Y,14,"currentColor",2);U&&(f.innerHTML="",f.appendChild(U))}else{let U=M==="upvote"?"downvote":"upvote",te=m.querySelector(`[data-action="${U}"]`);if(te){te.classList.remove("persona-message-action-active");let Ut=ce(U==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ut&&(te.innerHTML="",te.appendChild(Ut))}Mc.set(v,M),f.classList.add("persona-message-action-active");let ie=ce(Y,14,"currentColor",2);ie&&(ie.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ie)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Ve=D.getMessages().find(gt=>gt.id===v);Ve&&O.onFeedback&&O.onFeedback({type:M,messageId:Ve.id,message:Ve})}}}),le.addEventListener("click",s=>{let f=s.target.closest("button[data-approval-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let m=f.closest(".persona-approval-bubble");if(!m)return;let v=m.getAttribute("data-message-id");if(!v)return;let M=f.getAttribute("data-approval-action");if(!M)return;let j=M==="approve"?"approved":"denied",Y=D.getMessages().find(te=>te.id===v);if(!Y?.approval)return;let U=m.querySelector("[data-approval-buttons]");U&&U.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?D.resolveWebMcpApproval(v,j):D.resolveApproval(Y.approval,j)});let Be=null,Ys=null,ir=()=>{},Xs="none",ba=null,Vn={artifacts:[],selectedId:null},co=!1,qn=!1,Qs=!1,qr=!1,Hu=()=>qr||Vn.artifacts.some(s=>qo(o.features?.artifacts,s)==="panel"),va=()=>Vn.artifacts.length>0&&!co&&Hu(),tt={current:null},Ec=(s,c)=>{let f=D.getArtifactById(c),m=f?.markdown,v=f?.title||"artifact",M=f?.file,j=f?.artifactType??"markdown";if(!m){let U=s.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(U){let ie=D.getMessages().find(ge=>ge.id===U);if(ie?.rawContent)try{let ge=JSON.parse(ie.rawContent);m=ge?.props?.markdown,v=ge?.props?.title||v,ge?.props?.file&&typeof ge.props.file=="object"&&(M=ge.props.file),!f&&typeof ge?.props?.artifactType=="string"&&(j=ge.props.artifactType)}catch{}}}return{markdown:m,title:v,file:M,artifactType:j}};le.addEventListener("click",s=>{let f=s.target.closest("[data-download-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let m=f.getAttribute("data-download-artifact");if(!m||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:m})===!0)return;let{markdown:M,title:j,file:F}=Ec(f,m);M&&Ul(zl({title:j,markdown:M,file:F}))}),le.addEventListener("click",s=>{let f=s.target.closest("[data-artifact-custom-action]");if(!f)return;s.preventDefault(),s.stopPropagation();let m=f.getAttribute("data-artifact-custom-action");if(!m)return;let v=f.closest("[data-artifact-inline]"),M=v?null:f.closest("[data-open-artifact]"),j=v?v.getAttribute("data-artifact-inline"):M?.getAttribute("data-open-artifact")??null,Y=(v?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===m);if(!Y)return;let{markdown:U,title:te,file:ie,artifactType:ge}=Ec(f,j??""),Ve={artifactId:j,title:te,artifactType:ge,markdown:U,file:ie};try{Promise.resolve(Y.onClick(Ve)).catch(()=>{})}catch{}}),le.addEventListener("click",s=>{let f=s.target.closest("[data-copy-artifact]");if(!f)return;s.preventDefault(),s.stopPropagation();let m=f.getAttribute("data-copy-artifact");if(!m)return;let v=D.getArtifactById(m),M="";if(v)M=Ji(v);else{let{markdown:j,file:F,artifactType:Y}=Ec(f,m);Y==="markdown"&&(M=Ji({id:m,artifactType:"markdown",status:"complete",markdown:j??"",...F?{file:F}:{}}))}M&&navigator.clipboard.writeText(M).then(()=>{let j=ce("check",16,"currentColor",2);j&&(f.replaceChildren(j),setTimeout(()=>{let F=ce("copy",16,"currentColor",2);F&&f.replaceChildren(F)},1500))}).catch(()=>{})}),le.addEventListener("click",s=>{let f=s.target.closest("[data-expand-artifact-inline]");if(!f)return;s.preventDefault(),s.stopPropagation();let m=f.getAttribute("data-expand-artifact-inline");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(co=!1,qr=!0,qn=!0,Qs=!0,D.selectArtifact(m),po())}),le.addEventListener("click",s=>{let c=s.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let m=f.getAttribute("data-open-artifact");!m||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:m})===!0||(s.preventDefault(),s.stopPropagation(),co=!1,qr=!0,D.selectArtifact(m),po())}),le.addEventListener("keydown",s=>{if(s.key!=="Enter"&&s.key!==" ")return;let c=s.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(s.preventDefault(),c.click())});let Kr=Q.composerOverlay,Gr=(s,c,f)=>{let m=c.trim();if(!m||!tt.current)return;let v=s.getAttribute("data-tool-call-id")??"",M=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:v,answer:m,answers:f.structured,values:f.values??(f.source==="multi"?m.split(", "):[m]),isFreeText:M,source:f.source},bubbles:!0,composed:!0})),vs(Kr,v);let j=tt.current.getMessages().find(F=>F.toolCall?.id===v);j?.agentMetadata?.awaitingLocalTool?tt.current.resolveAskUserQuestion(j,f.structured??m):tt.current.sendMessage(m)},ar=s=>{let c=tt.current;if(!c)return;let f=s.getAttribute("data-tool-call-id")??"",m=c.getMessages().find(v=>v.toolCall?.id===f);m&&c.persistAskUserQuestionProgress(m,{answers:wl(s,m),currentIndex:Fn(s)})},Ru=s=>Object.entries(s).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),kc=s=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=Fn(s),f=bs(s);if(c>=f-1)return;let m=tt.current?.getMessages().find(v=>v.toolCall?.id===s.getAttribute("data-tool-call-id"));m&&(xl(s,m,o,c+1),ar(s))};Kr.addEventListener("click",s=>{let f=s.target.closest("[data-ask-user-action]");if(!f)return;let m=f.closest("[data-persona-ask-sheet-for]");if(!m)return;let v=f.getAttribute("data-ask-user-action");if(s.preventDefault(),s.stopPropagation(),v==="dismiss"){let M=m.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),vs(Kr,M);let j=tt.current?.getMessages().find(F=>F.toolCall?.id===M);j?.agentMetadata?.awaitingLocalTool&&(tt.current?.markAskUserQuestionResolved(j),tt.current?.resolveAskUserQuestion(j,"(dismissed)"));return}if(v==="pick"){let M=f.getAttribute("data-option-label");if(!M)return;let j=m.getAttribute("data-multi-select")==="true",F=Ko(m);if(F&&j){let Y=Lr(m)[Fn(m)],U=new Set(Array.isArray(Y)?Y:[]);U.has(M)?U.delete(M):U.add(M),Go(m,Array.from(U)),ar(m);return}if(F){Go(m,M),ar(m),kc(m);return}if(j){let Y=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Y?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Y);let U=m.querySelector('[data-ask-user-action="submit-multi"]');U&&(U.disabled=Qd(m).length===0);return}Gr(m,M,{source:"pick",values:[M]});return}if(v==="submit-multi"){let M=Qd(m);if(M.length===0)return;Gr(m,M.join(", "),{source:"multi",values:M});return}if(v==="open-free-text"){let M=m.querySelector('[data-ask-free-text-row="true"]');M&&(M.classList.remove("persona-hidden"),M.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(v==="focus-free-text"){m.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(v==="submit-free-text"){let j=m.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!j.trim())return;if(Ko(m)){Go(m,j.trim()),ar(m),kc(m);return}Gr(m,j,{source:"free-text"});return}if(v==="next"||v==="back"){if(!tt.current)return;let M=m.getAttribute("data-tool-call-id")??"",j=tt.current.getMessages().find(ie=>ie.toolCall?.id===M);if(!j)return;let Y=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Y){let ie=Lr(m)[Fn(m)];(typeof ie!="string"||ie!==Y)&&Go(m,Y)}let U=v==="next"?1:-1,te=Fn(m)+U;xl(m,j,o,te),ar(m);return}if(v==="submit-all"){if(!tt.current)return;let M=m.getAttribute("data-tool-call-id")??"",j=tt.current.getMessages().find(ie=>ie.toolCall?.id===M);if(!j)return;let Y=m.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Y&&Go(m,Y);let U=wl(m,j);tt.current.persistAskUserQuestionProgress(j,{answers:U,currentIndex:Fn(m)});let te=Ru(U);Gr(m,te||"(submitted)",{source:"submit-all",structured:U});return}if(v==="skip"){if(!tt.current)return;let M=m.getAttribute("data-tool-call-id")??"",j=tt.current.getMessages().find(ge=>ge.toolCall?.id===M);if(!j)return;let F=Ko(m),Y=Fn(m),U=bs(m),te=Y>=U-1;if(!F){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:M},bubbles:!0,composed:!0})),vs(Kr,M),j.agentMetadata?.awaitingLocalTool&&(tt.current.markAskUserQuestionResolved(j),tt.current.resolveAskUserQuestion(j,"(dismissed)"));return}Go(m,"");let ie=m.querySelector('[data-ask-free-text-input="true"]');if(ie&&(ie.value=""),te){let ge=wl(m,j),Ve=Ru(ge);Gr(m,Ve||"(skipped)",{source:"submit-all",structured:ge});return}xl(m,j,o,Y+1),ar(m);return}}),Kr.addEventListener("keydown",s=>{if(s.key!=="Enter")return;let f=s.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let m=f.closest("[data-persona-ask-sheet-for]");if(!m)return;s.preventDefault();let v=f.value;if(v.trim()){if(Ko(m)){Go(m,v.trim()),ar(m),kc(m);return}Gr(m,v,{source:"free-text"})}});let Wu=s=>{if(!/^[1-9]$/.test(s.key)||s.metaKey||s.ctrlKey||s.altKey)return;let c=s.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=Kr.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let m=Number(s.key),M=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[m-1];M&&(s.preventDefault(),M.click())};document.addEventListener("keydown",Wu);let Xn=null,ut=null,Js=null,wa=null,Pc=()=>{},Bu=!1,Ca="",xa="";function Lc(){wa?.(),wa=null}let Tb=()=>{let s=pi&&ss?.isConnected?ss:null,c=s?s.getBoundingClientRect().width:0;return c<=0?200:c+360},Du=()=>{if(!Xn||!ut)return;let s=t.classList.contains("persona-artifact-welded-split"),c=t.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!s||t.classList.contains("persona-artifact-narrow-host")||f){ut.style.removeProperty("position"),ut.style.removeProperty("left"),ut.style.removeProperty("top"),ut.style.removeProperty("bottom"),ut.style.removeProperty("width"),ut.style.removeProperty("z-index");return}let m=Xn.firstElementChild;if(!m||m===ut)return;let v=10;ut.style.position="absolute",ut.style.top="0",ut.style.bottom="0",ut.style.width=`${v}px`,ut.style.zIndex="5";let M=Gp(Xn,c),j=m.offsetWidth+M/2-v/2;ut.style.left=`${Math.max(0,j)}px`},Aa=()=>{},Mb=()=>{let s=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||s.innerWidth>f?!1:$||Pt(o)},Sa=()=>!pn(o)||!va()||t.classList.contains("persona-artifact-narrow-host")||Mb()||(t.ownerDocument.defaultView??window).innerWidth<VS?"none":Vp(o)?"detached":"welded",po=()=>{if(!Be||!pn(o))return;fa(t,o),ga(t,o),Aa();let s=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=B.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",c>0&&c<=s);let f=va();Be.setVisible(f),Be.update(Vn),co?(Be.setMobileOpen(!1),Be.element.classList.add("persona-hidden"),Be.backdrop?.classList.add("persona-hidden"),qn=!1,Qs=!1):Vn.artifacts.length>0&&Hu()?(Be.element.classList.remove("persona-hidden"),Be.setMobileOpen(!0)):(Be.setMobileOpen(!1),Be.element.classList.add("persona-hidden"),Be.backdrop?.classList.add("persona-hidden"),qn=!1,Qs=!1);let m=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Be.setExpandToggleVisible(m),Be.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Be.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),Be.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Be.setTabFade(o.features?.artifacts?.layout?.tabFade),Be.setRenderTabBar(o.features?.artifacts?.renderTabBar),!m&&!Qs&&(qn=!1),qn!==Bu){let M=Be.element;qn?(Ca=M.style.width,xa=M.style.maxWidth,M.style.removeProperty("width"),M.style.removeProperty("max-width")):(Ca&&(M.style.width=Ca),xa&&(M.style.maxWidth=xa),Ca="",xa=""),Bu=qn}t.classList.toggle("persona-artifact-expanded",qn),Be.setExpanded(qn);let v=Sa();v!==Xs&&(Xs=v,ir()),Pc()};if(pn(o)){B.style.position="relative";let s=C("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=C("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");s.appendChild(K),Be=Ay(o,{onSelect:f=>tt.current?.selectArtifact(f),onDismiss:()=>{co=!0,po()},onToggleExpand:()=>{let f=!qn,m=Vn.selectedId??Vn.artifacts[Vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:m,expanded:f})!==!0&&(qn=f,f||(Qs=!1),po())}}),Be.element.classList.add("persona-hidden"),Xn=c,c.appendChild(s),c.appendChild(Be.element),Be.backdrop&&B.appendChild(Be.backdrop),B.appendChild(c),Pc=()=>{if(!Xn||!Be)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Js?.(),Js=null,Lc(),ut&&(ut.remove(),ut=null),Be.element.style.removeProperty("width"),Be.element.style.removeProperty("maxWidth");return}if(!ut){let m=C("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");m.setAttribute("role","separator"),m.setAttribute("aria-orientation","vertical"),m.setAttribute("aria-label","Resize artifacts panel"),m.tabIndex=0;let v=t.ownerDocument,M=v.defaultView??window,j=F=>{if(!Be||F.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||M.innerWidth<=640)return;F.preventDefault(),Lc();let Y=F.clientX,U=Be.element.getBoundingClientRect().width,te=o.features?.artifacts?.layout,ie=Ve=>{let gt=Xn.getBoundingClientRect().width,Ut=t.classList.contains("persona-artifact-welded-split"),hn=Gp(Xn,M),xt=Ut?0:m.getBoundingClientRect().width||6,Tt=U-(Ve.clientX-Y),_=Hy(Tt,gt,hn,xt,te?.resizableMinWidth,te?.resizableMaxWidth,Tb());Be.element.style.width=`${_}px`,Be.element.style.maxWidth="none",Du()},ge=()=>{v.removeEventListener("pointermove",ie),v.removeEventListener("pointerup",ge),v.removeEventListener("pointercancel",ge),wa=null;try{m.releasePointerCapture(F.pointerId)}catch{}};wa=ge,v.addEventListener("pointermove",ie),v.addEventListener("pointerup",ge),v.addEventListener("pointercancel",ge);try{m.setPointerCapture(F.pointerId)}catch{}};m.addEventListener("pointerdown",j),ut=m,Xn.insertBefore(m,Be.element),Js=()=>{m.removeEventListener("pointerdown",j)}}if(ut){let m=va();ut.classList.toggle("persona-hidden",!m),Du()}},Aa=()=>{if(!$||!Be||(o.launcher?.sidebarMode??!1)||Pt(o)&&$n(o).reveal==="emerge")return;let m=t.ownerDocument.defaultView??window,v=o.launcher?.mobileFullscreen??!0,M=o.launcher?.mobileBreakpoint??640;if(v&&m.innerWidth<=M||!My(o,$))return;let j=o.launcher?.width??o.launcherWidth??ko,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";va()?(B.style.width=F,B.style.maxWidth=F):(B.style.width=j,B.style.maxWidth=j)},typeof ResizeObserver<"u"&&(Ys=new ResizeObserver(()=>{po()}),Ys.observe(B))}else B.appendChild(K);re()&&G&&(Q.peekBanner&&G.appendChild(Q.peekBanner),G.appendChild(De)),t.appendChild(E),G&&t.appendChild(G);let Ic=()=>{if(re()){B.style.width="100%",B.style.maxWidth="100%";let Et=o.launcher?.composerBar??{},ln=E.dataset.state==="expanded",Ti=Et.expandedSize??"anchored";if(!(ln&&Ti!=="fullscreen")){K.style.background="",K.style.border="",K.style.borderRadius="",K.style.overflow="",K.style.boxShadow="";return}let Mi=o.theme?.components?.panel,Mg=ks(o),dl=(Mr,ul)=>Mr==null||Mr===""?ul:cn(Mg,Mr)??Mr,Wt="1px solid var(--persona-border)",Od="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",pl="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";K.style.background="var(--persona-surface, #ffffff)",K.style.border=dl(Mi?.border,Wt),K.style.borderRadius=dl(Mi?.borderRadius,pl),K.style.boxShadow=dl(Mi?.shadow,Od),K.style.overflow="hidden";return}let s=Pt(o),c=o.launcher?.sidebarMode??!1,f=s||c||(o.launcher?.fullHeight??!1),m=o.launcher?.enabled===!1,v=o.launcher?.detachedPanel===!0,M=o.theme?.components?.panel,j=ks(o),F=(Et,ln)=>Et==null||Et===""?ln:cn(j,Et)??Et,Y=t.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640,ie=Y.innerWidth<=te,ge=U&&ie&&$,Ve=s&&U&&ie,gt=o.launcher?.position??"bottom-left",Ut=gt==="bottom-left"||gt==="top-left",hn=o.launcher?.zIndex??Yt,xt="var(--persona-panel-border, 1px solid var(--persona-border))",Tt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=v&&!ge&&!Ve;ke?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Le=ke?xt:c||ge?"none":xt,Ae=ke?Tt:ge?"none":c?Ut?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":m?"none":Tt;s&&!ge&&!ke&&(Ae="none",Le="none");let At=ke?_:c||ge?"0":_,at=F(M?.border,Le),Vt=F(M?.shadow,Ae),st=F(M?.borderRadius,At),sn=Sa(),Kt=sn==="detached",Ft=sn==="welded";t.classList.toggle("persona-artifact-detached-split",Kt),t.classList.toggle("persona-artifact-welded-split",Ft);let Ie="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Te=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&pn(o)&&Vp(o)&&m&&!s;t.classList.toggle("persona-artifact-chat-flush",Te);let Ht=Kt||Te?"none":Vt,lt=Kt?xt:Ft?"none":at,$e=Kt?_:st;Te&&(lt="none",$e="0");let Rt=M?.borderRadius!=null&&M.borderRadius!=="",Mt=Te&&!Rt?"0":st,Zt=q.scrollTop;t.style.cssText="",E.style.cssText="",B.style.cssText="",K.style.cssText="",q.style.cssText="",Ks||(De.style.cssText=""),qt&&(q.style.display="none"),(f||m)&&(t.style.minWidth="0");let _n=()=>{if(Zt<=0)return;(q.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(q.scrollTop===Zt)return;let ln=q.scrollHeight-q.clientHeight;ln<=0||(q.scrollTop=Math.min(Zt,ln))})};if(ge){E.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),E.style.cssText=`
|
|
47
47
|
position: fixed !important;
|
|
48
48
|
inset: 0 !important;
|
|
49
49
|
width: 100% !important;
|
|
@@ -53,9 +53,9 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
53
53
|
padding: 0 !important;
|
|
54
54
|
display: flex !important;
|
|
55
55
|
flex-direction: column !important;
|
|
56
|
-
z-index: ${
|
|
56
|
+
z-index: ${hn} !important;
|
|
57
57
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
58
|
-
`,
|
|
58
|
+
`,B.style.cssText=`
|
|
59
59
|
position: relative !important;
|
|
60
60
|
display: flex !important;
|
|
61
61
|
flex-direction: column !important;
|
|
@@ -68,7 +68,7 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
68
68
|
padding: 0 !important;
|
|
69
69
|
box-shadow: none !important;
|
|
70
70
|
border-radius: 0 !important;
|
|
71
|
-
`,
|
|
71
|
+
`,K.style.cssText=`
|
|
72
72
|
display: flex !important;
|
|
73
73
|
flex-direction: column !important;
|
|
74
74
|
flex: 1 1 0% !important;
|
|
@@ -79,33 +79,33 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
79
79
|
overflow: hidden !important;
|
|
80
80
|
border-radius: 0 !important;
|
|
81
81
|
border: none !important;
|
|
82
|
-
`,
|
|
82
|
+
`,q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",De.style.flexShrink="0",J=!0,_n();return}let en=o?.launcher?.width??o?.launcherWidth??ko;if(!c&&!s)m&&f?(B.style.width="100%",B.style.maxWidth="100%"):(B.style.width=en,B.style.maxWidth=en);else if(s)if($n(o).reveal==="emerge"&&!v){let ln=$n(o).width;B.style.width=ln,B.style.maxWidth=ln}else B.style.width="100%",B.style.maxWidth="100%";if(Aa(),B.style.boxShadow=Ht,B.style.borderRadius=Mt,Kt?B.style.border="none":Ft&&(B.style.border=at),K.style.border=lt,K.style.borderRadius=$e,K.style.boxShadow=Kt&&!Te?Ie:"",Te&&(K.style.background="transparent",q.style.background="transparent",De.style.background="transparent",De.style.borderTop="none"),Ft){let Et=o.features?.artifacts?.layout;ba=Et?.unifiedSplitOuterRadius?.trim()||Et?.paneBorderRadius?.trim()||st}else ba=null;if(s&&!ge&&!ke&&!Kt&&!Ft&&M?.border===void 0&&(K.style.border="none",$n(o).side==="right"?K.style.borderLeft="1px solid var(--persona-border)":K.style.borderRight="1px solid var(--persona-border)"),s&&!ge&&Ft&&M?.border===void 0&&($n(o).side==="right"?B.style.borderLeft="1px solid var(--persona-border)":B.style.borderRight="1px solid var(--persona-border)"),f&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",m&&(t.style.width="100%"),E.style.display="flex",E.style.flexDirection="column",E.style.flex="1 1 0%",E.style.minHeight="0",E.style.maxHeight="100%",E.style.height="100%",m&&(E.style.overflow="hidden"),B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",Kt||(B.style.overflow="hidden"),K.style.display="flex",K.style.flexDirection="column",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.maxHeight="100%",K.style.overflow="hidden",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",De.style.flexShrink="0"),m&&(ke||Kt||Te)&&!s&&(Te||(E.style.padding="var(--persona-panel-inset)"),E.style.background="var(--persona-panel-canvas-bg)"),E.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!c&&!m&&!s&&(En[gt]??En["bottom-right"]).split(" ").forEach(ln=>E.classList.add(ln)),c){let Et=o.launcher?.sidebarWidth??"420px";v?E.style.cssText=`
|
|
83
83
|
position: fixed !important;
|
|
84
84
|
top: var(--persona-panel-inset) !important;
|
|
85
85
|
bottom: var(--persona-panel-inset) !important;
|
|
86
|
-
width: ${
|
|
86
|
+
width: ${Et} !important;
|
|
87
87
|
height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
88
88
|
max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
|
|
89
89
|
margin: 0 !important;
|
|
90
90
|
padding: 0 !important;
|
|
91
91
|
display: flex !important;
|
|
92
92
|
flex-direction: column !important;
|
|
93
|
-
z-index: ${
|
|
94
|
-
${
|
|
95
|
-
`:
|
|
93
|
+
z-index: ${hn} !important;
|
|
94
|
+
${Ut?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
95
|
+
`:E.style.cssText=`
|
|
96
96
|
position: fixed !important;
|
|
97
97
|
top: 0 !important;
|
|
98
98
|
bottom: 0 !important;
|
|
99
|
-
width: ${
|
|
99
|
+
width: ${Et} !important;
|
|
100
100
|
height: 100vh !important;
|
|
101
101
|
max-height: 100vh !important;
|
|
102
102
|
margin: 0 !important;
|
|
103
103
|
padding: 0 !important;
|
|
104
104
|
display: flex !important;
|
|
105
105
|
flex-direction: column !important;
|
|
106
|
-
z-index: ${
|
|
107
|
-
${
|
|
108
|
-
`,
|
|
106
|
+
z-index: ${hn} !important;
|
|
107
|
+
${Ut?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
108
|
+
`,B.style.cssText=`
|
|
109
109
|
position: relative !important;
|
|
110
110
|
display: flex !important;
|
|
111
111
|
flex-direction: column !important;
|
|
@@ -116,10 +116,10 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
116
116
|
min-height: 0 !important;
|
|
117
117
|
margin: 0 !important;
|
|
118
118
|
padding: 0 !important;
|
|
119
|
-
box-shadow: ${
|
|
120
|
-
border-radius: ${
|
|
121
|
-
${
|
|
122
|
-
`,
|
|
119
|
+
box-shadow: ${Ht} !important;
|
|
120
|
+
border-radius: ${Mt} !important;
|
|
121
|
+
${Kt?"border: none !important;":Ft?`border: ${at} !important;`:""}
|
|
122
|
+
`,B.style.setProperty("width","100%","important"),B.style.setProperty("max-width","100%","important"),K.style.cssText=`
|
|
123
123
|
display: flex !important;
|
|
124
124
|
flex-direction: column !important;
|
|
125
125
|
flex: 1 1 0% !important;
|
|
@@ -128,40 +128,40 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
128
128
|
min-height: 0 !important;
|
|
129
129
|
max-height: 100% !important;
|
|
130
130
|
overflow: hidden !important;
|
|
131
|
-
border-radius: ${
|
|
132
|
-
border: ${
|
|
133
|
-
${
|
|
134
|
-
${
|
|
135
|
-
`,
|
|
131
|
+
border-radius: ${$e} !important;
|
|
132
|
+
border: ${lt} !important;
|
|
133
|
+
${Kt&&!Te?`box-shadow: ${Ie} !important;`:""}
|
|
134
|
+
${Te?"background: transparent !important;":""}
|
|
135
|
+
`,Ks||(De.style.cssText=`
|
|
136
136
|
flex-shrink: 0 !important;
|
|
137
137
|
border-top: none !important;
|
|
138
138
|
padding: 8px 16px 12px 16px !important;
|
|
139
|
-
${
|
|
140
|
-
`}if(!y&&!i){let Mt="max-height: -moz-available !important; max-height: stretch !important;",tn=p?"":"padding-top: 1.25em !important;",Pa=p?"":`z-index: ${o.launcher?.zIndex??Nt} !important;`;Le.style.cssText+=Mt+tn+Pa}hn()},Xi=()=>{e.style.setProperty("--persona-content-max-width",xo(o,Q()))},md=()=>{if(Q())return;let i=Rt(o),p=o.launcher?.sidebarMode??!1;if(i||p||(o.launcher?.fullHeight??!1)||!F)return;let y=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(x&&y.innerWidth<=E)return;let U=y.innerHeight,O=64,V=o.launcher?.heightOffset??0,J=Math.max(200,U-O),fe=Math.min(640,J);ye.style.height=`${Math.max(200,fe-V)}px`};Yi(),Ds(e,o),ea(e,o),ta(e,o),Xi(),Lo=()=>{Yi(),md(),Ds(e,o),ea(e,o),ta(e,o),Xi(),aa?e.style.setProperty("--persona-artifact-welded-outer-radius",aa):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Be=[];Be.push(()=>{document.removeEventListener("keydown",ud)}),Be.push(()=>{Qr!==null&&clearTimeout(Qr)});let Wn=null,Rn=null;Be.push(()=>{Wn?.(),Wn=null,Rn?.(),Rn=null}),es&&Be.push(()=>{es?.disconnect(),es=null}),Be.push(()=>{os?.(),os=null,Gi(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),me&&Be.push(()=>{ze!==null&&(cancelAnimationFrame(ze),ze=null),Ae?.destroy(),Ae=null,Oe?.destroy(),Oe=null,Ue=null});let Io=null,hd=()=>{Io&&(Io(),Io=null),o.colorScheme==="auto"&&(Io=oi(()=>{Ds(e,o)}))};hd(),Be.push(()=>{Io&&(Io(),Io=null)}),Be.push(d);let fa=o.features?.streamAnimation;if(fa?.type&&fa.type!=="none"){let i=Or(fa.type,fa.plugins);i&&(bi(i,e),Be.push(()=>yf(e)))}let _n=qs(M),yd=qs(An),bd=qs(ne),Wo=[_n,yd,bd];Be.push(()=>{Wo.forEach(i=>i.destroy())});let Ro=null,_,Ho=null,vd=!1,wd=0,xd=null,Cd=i=>i.reduce((p,m)=>m.role==="user"?p+1:p,0),Ad=i=>{for(let p=i.length-1;p>=0;p--)if(Ss(i[p]))return i[p].id??null;return null},Sd=!1,jg=()=>{Sd||o.debug!==!0||(Sd=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Td=!1,Md=!1,Ed=(i,p)=>{Td||o.debug!==!0||!p.enabled||p.expose||vd||Md&&(_.isStreaming()||i.some(Ss)||(Td=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},lr=i=>{if(!_)return;let p=i??_.getMessages(),m=J=>{J.render([],_,I,p)},y=J=>{Wo.forEach(fe=>{fe!==J&&m(fe)})};Ho&&(Cd(p)>wd||Ad(p)!==xd)&&(Ho=null);let x=vo(o);Ed(p,x);let E=x.enabled?au(p):null,U=Ho??E,O=Ho?"host":"agent";if(U){let J=o.suggestions?.followUps,fe=J?.placement??(J?"auto":"composer"),be=(fe==="auto"?Q()?"composer":"after-message":fe)==="after-message"?bd:_n;y(be),be.render(U,_,I,p,o.suggestionChipsConfig,{source:O,surface:"followUp",variant:J?.variant??"chip",behavior:J?.behavior??"send",overflow:J?.overflow??"wrap",maxItems:J?.maxItems??4,config:o,plugins:s});return}if(p.some(J=>J.role==="user")){Wo.forEach(m);return}let V=o.suggestions?.starters;if(V){let J=_r(Zo(o),p),fe=V.placement??"auto",le=fe==="auto"?J?"welcome":"composer":fe;if(le==="welcome"&&!J){jg(),Wo.forEach(m);return}let be=le==="welcome"?yd:_n;y(be),be.render(V.items??o.suggestionChips,_,I,p,o.suggestionChipsConfig,{surface:"starter",variant:V.variant??"card",behavior:V.behavior??"send",overflow:V.overflow??"wrap",maxItems:V.maxItems??4,config:o,plugins:s});return}y(_n),_n.render(o.suggestionChips,_,I,p,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},kd=()=>{Ho&&(Ho=null,lr())},Vg=i=>{let p=Array.isArray(i)?[...i]:[];if(!p.length){kd();return}let m=_?_.getMessages():[];Ho=p,vd=!0,wd=Cd(m),xd=Ad(m),lr(m)},En=!1,Bo=lf(),cr=new Map,Do=new Map,ro=new Map,Qi=0,qg=Gn()!==null,on=ui(),rn=0,so=null,Zt=!1,ga=!1,ao=0,Bt=null,Fo=null,Ji=!1,ma=!1,Oo=null,rs=!0,ha=!1,dr=null,ya=!1,No=()=>{ya=!0,Xg()},Zi=null,Kg=4,$n=24,Gg=80,Yg=1e3,Un=null,Ld=()=>{e.setAttribute("data-persona-scrollbar",Ni()),Ni()!=="on-scroll"&&(Un!==null&&clearTimeout(Un),Un=null,re.removeAttribute("data-persona-scrollbar-visible"))},Xg=()=>{Ni()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Un!==null&&clearTimeout(Un),Un=setTimeout(()=>{Un=null,eo(re,$n)&&re.removeAttribute("data-persona-scrollbar-visible")},Yg))};Ld(),Be.push(()=>{Un!==null&&clearTimeout(Un)});let el=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Pd=o.voiceRecognition?.autoResume??!1,zn=i=>{c.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},kn=()=>{S(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Qg=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Nc(g.voiceState),p=!!i.active,m=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,p&&Date.now()-m<lw&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("restore"),_.isVoiceActive()&&hr()}):Ma("restore"))},1e3)},Jg=()=>_?xg(_.getMessages()).filter(i=>!i.__skipPersist):[],ba=null,Id=(i,p)=>{typeof console<"u"&&console.error(i,p)},tl=(i,p)=>{let m=()=>{try{let U=i();return!U||typeof U.then!="function"?null:Promise.resolve(U).catch(O=>{Id(p,O)})}catch(U){return Id(p,U),null}},y=ba,x=y?y.then(()=>m()??void 0):m();if(!x)return;let E=x.finally(()=>{ba===E&&(ba=null)});ba=E};function nl(i){if(!w?.save)return;let m={messages:i?xg(i):_?Jg():[],metadata:g,artifacts:Tn.artifacts,selectedArtifactId:Tn.selectedId};tl(()=>w.save(m),"[AgentWidget] Failed to persist state:")}let pr=null,Wd=()=>Le.querySelector("#persona-scroll-container")||re,ur=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Zt=!1},Rd=()=>{so!==null&&(cancelAnimationFrame(so),so=null),ga=!1,ur()},Zg=()=>En&&rl()&&(nn()!=="anchor-top"||Kc()),ol=()=>{let i=Gr()||"Jump to latest",p=Zg();Et.toggleAttribute("data-persona-scroll-to-bottom-streaming",p),ao>0?(Mo.textContent=String(ao),Mo.style.display="",Et.setAttribute("aria-label",`${i} (${ao} new)`)):(Mo.textContent="",Mo.style.display="none",Et.setAttribute("aria-label",p?`${i} (response streaming below)`:i))},Hd=()=>{ao!==0&&(ao=0,ol())},em=()=>{let i=Bt?.spacerHeight??0;return i<=0?eo(re,$n):xa(i)-re.scrollTop-re.clientHeight<=$n},rl=()=>no()?!on.isFollowing():!em(),sl=()=>!!_&&_.getMessages().length>0,$t=()=>{if(!Og()||Se){Et.parentNode&&Et.remove(),Et.style.display="none";return}Et.parentNode!==ve&&ve.appendChild(Et),ko();let p=Dn(re)>0&&rl()&&sl();p?ol():Hd(),Et.style.display=p?"":"none"},ss=()=>{on.pause()&&(Rd(),$t())},io=()=>{on.resume(),Hd(),$t()},lo=(i=!1)=>{no()&&sl()&&on.isFollowing()&&(!i&&!En||(so!==null&&(cancelAnimationFrame(so),so=null),ga=!0,so=requestAnimationFrame(()=>{so=null,ga=!1,on.isFollowing()&&tm(Wd(),i?220:140)})))},Bd=(i,p,m,y=()=>!0)=>{let x=i.scrollTop,E=p(),U=E-x;if(ur(),Math.abs(U)<1){Zt=!0,i.scrollTop=E,rn=i.scrollTop,Zt=!1;return}let O=performance.now();Zt=!0;let V=fe=>1-Math.pow(1-fe,3),J=fe=>{if(!y()){ur();return}let le=p();le!==E&&(E=le,U=E-x);let be=fe-O,Ge=Math.min(be/m,1),mt=V(Ge),ct=x+U*mt;i.scrollTop=ct,rn=i.scrollTop,Ge<1?pr=requestAnimationFrame(J):(i.scrollTop=E,rn=i.scrollTop,pr=null,Zt=!1)};pr=requestAnimationFrame(J)},tm=(i,p=500)=>{let m=Dn(i)-i.scrollTop;if(Math.abs(m)<1){rn=i.scrollTop;return}if(Math.abs(m)>=Gg){ur(),Zt=!0,i.scrollTop=Dn(i),rn=i.scrollTop,Zt=!1;return}Bd(i,()=>Dn(i),p,()=>on.isFollowing())},Dd=()=>{if(!sl()){$t();return}let i=Wd();Zt=!0,i.scrollTop=Dn(i),rn=i.scrollTop,Zt=!1,$t()},_o=i=>{let p=0,m=i;for(;m&&m!==re;)p+=m.offsetTop,m=m.offsetParent;return p},nm=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},va=()=>ff(nm(),re),Fd=()=>{if(Ng()!=="last-user-turn")return!1;let i=_?.getMessages()??[];if(i.length<2)return!1;let p=[...i].reverse().find(E=>E.role==="user");if(!p)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(p.id):p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=re.querySelector(`[data-message-id="${m}"]`);if(!y)return!1;let x=Math.min(Math.max(0,_o(y)-Yr()),Dn(re));return Zt=!0,re.scrollTop=x,rn=re.scrollTop,Zt=!1,nn()==="follow"&&!eo(re,$n)&&on.pause(),$t(),!0},wa=i=>{let p=Math.max(0,Math.round(i));fn.style.height=`${p}px`,fn.style.display=p>0?"":"none",Bt&&(Bt.spacerHeight=Math.max(0,i))},xa=i=>{let p=parseFloat(getComputedStyle(re).paddingBottom)||0,m=0;for(let x of Array.from(re.children)){if(x===fn||x.offsetHeight===0)continue;let E=_o(x)+x.offsetHeight;E>m&&(m=E)}let y=re.scrollHeight-i;return m>0?Math.min(m+p,y):y},om=()=>{if(!Bt||Bt.spacerHeight<=0)return;let i=xa(Bt.spacerHeight),p=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+$n);p<Bt.spacerHeight&&(wa(p),$t())},as=()=>{Fo!==null&&(cancelAnimationFrame(Fo),Fo=null),ur(),Bt=null,fn.style.height="0px",fn.style.display="none"},Od=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),al=i=>re.querySelector(`[data-message-id="${Od(i)}"]`),Nd=i=>{Fo!==null&&cancelAnimationFrame(Fo),Fo=requestAnimationFrame(()=>{Fo=null;let p=Od(i),m=re.querySelector(`[data-message-id="${p}"]`);if(!m)return;let y=_o(m),x=Bt?.spacerHeight??0,E=xa(x),{targetScrollTop:U,spacerHeight:O}=sc({anchorOffsetTop:y,topOffset:Yr(),viewportHeight:re.clientHeight,contentHeight:E,slack:$n});Bt={initialSpacerHeight:O,contentHeightAtAnchor:E,spacerHeight:O},wa(O),Bd(re,()=>m.isConnected?Math.max(0,_o(m)-Yr()):U,220)})},_d=()=>{if(nn()!=="anchor-top"||!Bt||!dr)return;let i=al(dr);if(!i)return;ur();let p=Bt.spacerHeight,m=xa(p),{targetScrollTop:y,spacerHeight:x}=sc({anchorOffsetTop:_o(i),topOffset:Yr(),viewportHeight:re.clientHeight,contentHeight:m,slack:$n});Bt={initialSpacerHeight:x,contentHeightAtAnchor:m,spacerHeight:x},wa(x),Zt=!0,re.scrollTop=y,rn=re.scrollTop,Zt=!1,$t()},rm=()=>{if(no()){if(!on.isFollowing()||eo(re,1))return;lo(!En);return}if(Bt&&Bt.initialSpacerHeight>0){let i=re.scrollHeight-Bt.spacerHeight,p=gf({initialSpacerHeight:Bt.initialSpacerHeight,contentHeightAtAnchor:Bt.contentHeightAtAnchor,currentContentHeight:i});p!==Bt.spacerHeight&&wa(p)}$t()},sm=i=>{let p=nn();p==="follow"?(io(),lo(!0)):p==="anchor-top"&&(rs=!1,ha=!0,ya=!1,dr=i,Nd(i))},am=()=>{if(nn()==="anchor-top"){if(ha){rs=!1;return}rs=!0,as(),io(),lo(!0)}},im=96,lm=i=>{if(Oo===null)return!0;let p=al(Oo),m=al(i);if(!p||!m)return!0;let y=_o(m)-_o(p);return Yr()+y>re.clientHeight-im},cm=i=>{if(nn()!=="anchor-top"||!ha||ya||va())return;let p=Oo===null;for(let m of i){if(!p){m.id===Oo&&(p=!0);continue}if(uf(m)){if(m.id===dr||!lm(m.id))return;dr=m.id,Nd(m.id);return}}},dm=i=>{let p=new Map;i.forEach(m=>{let y=el.get(m.id);p.set(m.id,{streaming:m.streaming,role:m.role}),!y&&m.role==="assistant"&&(c.emit("assistant:message",m),!ma&&(nn()!=="anchor-top"||Kc())&&rl()&&(ao+=1,ol(),$t(),Yc(ao===1?"1 new message below.":`${ao} new messages below.`))),m.role==="assistant"&&y?.streaming&&m.streaming===!1&&c.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(y?m.approval.status!=="pending"&&c.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):c.emit("approval:requested",{approval:m.approval,message:m}))}),el.clear(),p.forEach((m,y)=>{el.set(y,m)})},Ca=(i,p)=>{let m=p==="user"?"user":"assistant",y=o.layout?.messages?.[m],x=y?.width??"content",E=y?.maxWidth??(x==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${p}`,`persona-message-width-${x}`),i.classList.toggle("persona-justify-end",p==="user"),i.setAttribute("data-message-role",p),i.setAttribute("data-message-width",x),i.style.setProperty("--persona-message-row-max-width",E)},$o=(i,p)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${i}`,m.setAttribute("data-wrapper-id",i),Ca(m,p),m},pm=(i,p,m)=>{let y=document.createElement("div"),E=(()=>{let D=s.find(Ie=>Ie.renderLoadingIndicator);if(D?.renderLoadingIndicator)return D.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),U=(D,Ie)=>Ie==null?!1:typeof Ie=="string"?(D.textContent=Ie,!0):(D.appendChild(Ie),!0),O=new Set,V=new Map,J=new Set,fe=s.some(D=>D.renderAskUserQuestion),le=[],be=[],Ge=o.enableComponentStreaming!==!1,mt=o.approval!==!1,ct=[];if(p.forEach(D=>{O.add(D.id),V.set(D.id,D.role);let Ie=fe&&qo(D),De=mt&&D.variant==="approval"&&!!D.approval,Me=!Ie&&D.role==="assistant"&&!D.variant&&Ge&&Oc(D);!De&&ro.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),ro.delete(D.id)),!Me&&Do.has(D.id)&&(i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),Do.delete(D.id));let Ct=qo(D)?`:${D.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${D.agentMetadata?.askUserQuestionAnswers?Object.keys(D.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=af(D,Qi)+Ct,Ft=Ie||De||Me?null:cf(Bo,D.id,dt);if(Ft){y.appendChild(Ft.cloneNode(!0)),qo(D)&&D.toolCall?.id&&D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}let pt=null,en=s.find(Fe=>!!(D.variant==="reasoning"&&Fe.renderReasoning||D.variant==="tool"&&Fe.renderToolCall||!D.variant&&Fe.renderMessage)),Pt=o.layout?.messages;if(qo(D)&&D.agentMetadata?.askUserQuestionAnswered===!0){cr.delete(D.id),i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ss(D)&&vo(o).enabled)return;if(qo(D)&&o.features?.askUserQuestion?.enabled!==!1){let Fe=s.find(Ut=>typeof Ut.renderAskUserQuestion=="function");if(Fe&&st.current){let Ut=cr.get(D.id),zt=Ut!==dt,wt=null;if(zt){let{payload:Xe,complete:He}=Tr(D),ht=D.id,jt=()=>st.current?.getMessages().find(hn=>hn.id===ht);wt=Fe.renderAskUserQuestion({message:D,payload:Xe,complete:He,resolve:hn=>{let ys=jt();ys&&st.current?.resolveAskUserQuestion(ys,hn)},dismiss:()=>{let hn=jt();hn?.agentMetadata?.awaitingLocalTool&&(st.current?.markAskUserQuestionResolved(hn),st.current?.resolveAskUserQuestion(hn,"(dismissed)"))},config:o})}let at=Ut!=null;if(zt&&wt===null&&!at){D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}let ut=$o(D.id,D.role);ut.setAttribute("data-ask-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),le.push({messageId:D.id,fingerprint:dt,bubble:wt});return}else{D.agentMetadata?.awaitingLocalTool===!0&&!D.agentMetadata?.askUserQuestionAnswered&&(J.add(D.toolCall.id),_a(D,o,Te.composerOverlay));return}}else if(De){let Fe=s.find(at=>typeof at.renderApproval=="function")??u,zt=ro.get(D.id)!==dt,wt=null;if(zt&&Fe?.renderApproval){let at=D.id,ut=(Xe,He)=>{let ht=st.current?.getMessages().find(jt=>jt.id===at);ht?.approval&&(ht.approval.toolType==="webmcp"?st.current?.resolveWebMcpApproval(ht.id,Xe):st.current?.resolveApproval(ht.approval,Xe,He))};wt=Fe.renderApproval({message:D,defaultRenderer:()=>Ri(D,o),config:o,approve:Xe=>ut("approved",Xe),deny:Xe=>ut("denied",Xe)})}if(zt&&wt===null)i.querySelector(`#wrapper-${D.id}`)?.removeAttribute("data-preserve-runtime"),ro.delete(D.id),pt=Ri(D,o);else{let at=$o(D.id,D.role);at.setAttribute("data-approval-plugin-stub","true"),at.setAttribute("data-preserve-runtime","true"),y.appendChild(at),ct.push({messageId:D.id,fingerprint:dt,bubble:wt});return}}else if(en)if(D.variant==="reasoning"&&D.reasoning&&en.renderReasoning){if(!pe)return;pt=en.renderReasoning({message:D,defaultRenderer:()=>xc(D,o),config:o})}else if(D.variant==="tool"&&D.toolCall&&en.renderToolCall){if(!ee)return;pt=en.renderToolCall({message:D,defaultRenderer:()=>Ac(D,o),config:o})}else en.renderMessage&&(pt=en.renderMessage({message:D,defaultRenderer:()=>{let Fe=hc(D,m,Pt,o.messageActions,gt,{loadingIndicatorRenderer:E,widgetConfig:o});return D.role!=="user"&&Wc(Fe,D,o,_),Fe},config:o}));if(!pt&&Me){let Fe=bg(D);if(Fe){let Ut=Do.get(D.id),zt=Ut!==dt,wt=o.wrapComponentDirectiveInBubble!==!1&&Zn.getOptions(Fe.component)?.bubbleChrome!==!1,at=null;if(zt){let ut=hg(Fe,{config:o,message:D,transform:m});if(ut&&Fe.component==="PersonaArtifactInline"){let Xe=ut.hasAttribute("data-artifact-inline")?ut:ut.querySelector("[data-artifact-inline]"),He=Xe?.getAttribute("data-artifact-inline")??"",ht=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,jt=He?i.querySelector(`#wrapper-${D.id}`)?.querySelector(`[data-artifact-inline="${ht}"]`)??null:null;Xe&&jt&&jt!==Xe&&tf(jt)&&(Xe===ut?ut=jt:Xe.replaceWith(jt))}if(ut)if(wt){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${D.id}`,Xe.setAttribute("data-message-id",D.id),D.content&&D.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Xe.appendChild(He)}Xe.appendChild(ut),at=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${D.id}`,Xe.setAttribute("data-message-id",D.id),Xe.setAttribute("data-persona-component-directive","true"),D.content&&D.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=m({text:D.content,message:D,streaming:!!D.streaming,raw:D.rawContent}),Xe.appendChild(He)}Xe.appendChild(ut),at=Xe}}if(at||Ut!=null){let ut=$o(D.id,D.role);ut.setAttribute("data-component-directive-stub","true"),ut.setAttribute("data-preserve-runtime","true"),y.appendChild(ut),be.push({messageId:D.id,fingerprint:dt,bubble:at});return}}}if(!pt)if(D.variant==="reasoning"&&D.reasoning){if(!pe)return;pt=xc(D,o)}else if(D.variant==="tool"&&D.toolCall){if(!ee)return;pt=Ac(D,o)}else if(D.variant==="approval"&&D.approval){if(o.approval===!1)return;pt=Ri(D,o)}else{let Fe=o.layout?.messages;Fe?.renderUserMessage&&D.role==="user"?pt=Fe.renderUserMessage({message:D,config:o,streaming:!!D.streaming}):Fe?.renderAssistantMessage&&D.role==="assistant"?pt=Fe.renderAssistantMessage({message:D,config:o,streaming:!!D.streaming}):pt=hc(D,m,Fe,o.messageActions,gt,{loadingIndicatorRenderer:E,widgetConfig:o}),D.role!=="user"&&pt&&Wc(pt,D,o,_)}let We=$o(D.id,D.role);We.appendChild(pt),df(Bo,D.id,dt,We),y.appendChild(We)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ie=>{let De=Ie.getAttribute("data-persona-ask-sheet-for");De&&!J.has(De)&&Er(Te.composerOverlay,De)}),o.features?.toolCallDisplay?.grouped){let D=[],Ie=[],De=o.features.toolCallDisplay.groupedMode==="summary";p.forEach(Me=>{if(Me.variant==="tool"&&Me.toolCall&&ee){Ie.push(Me);return}Me.variant==="reasoning"&&!pe||((Ie.length>1||De&&Ie.length>0)&&D.push(Ie),Ie=[])}),(Ie.length>1||De&&Ie.length>0)&&D.push(Ie),D.forEach(Me=>{let Ct=Me.map(Fe=>Array.from(y.children).find(Ut=>Ut instanceof HTMLElement&&Ut.getAttribute("data-wrapper-id")===Fe.id)).filter(Fe=>!!Fe);if(Ct.length<(De?1:2))return;let dt=$o(`tool-group-${Me[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Me[0].id}`;let en=`Called ${Me.length} ${Me.length===1?"tool":"tools"}`,Pt=o.toolCall?.renderGroupedSummary?.({messages:Me,toolCalls:Me.map(Fe=>Fe.toolCall).filter(Fe=>!!Fe),defaultSummary:en,config:o});U(pt,Pt)||(pt.textContent=en);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Me[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(pt),De||Ft.appendChild(We),dt.appendChild(Ft),Ct[0].before(dt),Ct.forEach((Fe,Ut)=>{if(De){Fe.remove();return}Fe.style.setProperty("--persona-message-row-max-width","100%");let zt=document.createElement("div");zt.className="persona-tool-group-item persona-relative",zt.setAttribute("data-persona-tool-group-item","true"),Ut<Ct.length-1&&zt.setAttribute("data-persona-tool-group-connector","true"),zt.appendChild(Fe),We.appendChild(zt)})})}pf(Bo,O);let sn=p.some(D=>D.role==="assistant"&&D.streaming),At=p[p.length-1],Lt=At?.role==="assistant"&&!At.streaming&&At.variant!=="approval";if(En&&p.some(D=>D.role==="user")&&!sn&&!Lt){let D={config:o,streaming:!0,location:"standalone",defaultRenderer:Ys},Ie=s.find(Me=>Me.renderLoadingIndicator),De=null;if(Ie?.renderLoadingIndicator&&(De=Ie.renderLoadingIndicator(D)),De===null&&o.loadingIndicator?.render&&(De=o.loadingIndicator.render(D)),De===null&&(De=Ys()),De){let Me=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Me.className=Ct?Xs("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Me.setAttribute("data-typing-indicator","true"),Ct&&(Me.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Me.appendChild(De);let Ft=$o("typing-indicator","assistant");Ft.appendChild(Me),y.appendChild(Ft)}}if(!En&&p.length>0){let D=p[p.length-1],Ie={config:o,lastMessage:D,messageCount:p.length},De=s.find(Ct=>Ct.renderIdleIndicator),Me=null;if(De?.renderIdleIndicator&&(Me=De.renderIdleIndicator(Ie)),Me===null&&o.loadingIndicator?.renderIdle&&(Me=o.loadingIndicator.renderIdle(Ie)),Me){let Ct=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;Ct.className=dt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(Me);let Ft=$o("idle-indicator","assistant");Ft.appendChild(Ct),y.appendChild(Ft)}}if(Np(y),pi(i,y),Il(i),le.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of le){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),cr.set(D,Ie)))}if(cr.size>0)for(let D of cr.keys())O.has(D)||cr.delete(D);if(be.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of be){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),Do.set(D,Ie)))}if(Do.size>0)for(let D of Do.keys())O.has(D)||Do.delete(D);if(ct.length>0)for(let{messageId:D,fingerprint:Ie,bubble:De}of ct){let Me=i.querySelector(`#wrapper-${D}`);Me&&(Ca(Me,V.get(D)??"assistant"),De!==null&&(Me.replaceChildren(De),Me.setAttribute("data-bubble-fp",Ie),ro.set(D,Ie)))}if(ro.size>0)for(let D of ro.keys())O.has(D)||ro.delete(D)},is=(i,p,m)=>{pm(i,p,m),cd()},ls=null,um=()=>{if(ls)return;let i=m=>{let y=m.composedPath();y.includes(Le)||tt&&y.includes(tt)||lt(!1,"user")};ls=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},$d=()=>{if(!ls)return;(e.ownerDocument??document).removeEventListener("pointerdown",ls,!0),ls=null};Be.push(()=>$d());let cs=null,fm=()=>{if(cs)return;let i=m=>{m.key==="Escape"&&(m.isComposing||lt(!1,"user"))};cs=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Ud=()=>{if(!cs)return;(e.ownerDocument??document).removeEventListener("keydown",cs,!0),cs=null};Be.push(()=>Ud());let ds=!1,zd=new Set,gm=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},fr=()=>{if(!Q())return;let i=Te.peekBanner,p=Te.peekTextNode;if(!i||!p)return;if(Y){i.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],y;for(let At=m.length-1;At>=0;At--){let Lt=m[At];if(Lt.role==="assistant"&&Lt.content){y=Lt;break}}if(!y){i.classList.remove("persona-pill-peek--visible");return}let x=y.content,E=!!y.streaming,U=gm(),O=mi(U),V=O.type!=="none"?Or(O.type,U?.plugins):null,J=V?.isAnimating?.(y)===!0,fe=V!==null&&(E||J);fe&&V&&!zd.has(V.name)&&(bi(V,e),zd.add(V.name));let le=fe&&V?.containerClass?V.containerClass:null,be=p.dataset.personaPeekStreamClass??null;be&&be!==le&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),le&&be!==le&&(p.classList.add(le),p.dataset.personaPeekStreamClass=le),fe?(p.style.setProperty("--persona-stream-step",`${O.speed}ms`),p.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ge=fe?hi(x,O.buffer,V,y,E):x;if(fe&&O.placeholder==="skeleton"&&E&&(!Ge||!Ge.trim())){let At=document.createElement("div"),Lt=Us();Lt.classList.add("persona-pill-peek__skeleton"),At.appendChild(Lt),pi(p,At)}else{let At=Math.max(0,Ge.length-100),Lt=Ge.length>100?Ge.slice(-100):Ge,D=mo(Lt);if(!fe||!V){let Ie=Ge.length>100?`\u2026${Lt}`:Lt;p.textContent!==Ie&&(p.textContent=Ie)}else{let Ie=D;(V.wrap==="char"||V.wrap==="word")&&(Ie=$s(D,V.wrap,`peek-${y.id}`,{skipTags:V.skipTags,startIndex:At}));let De=document.createElement("div");if(De.innerHTML=Ie,V.useCaret&&Lt.length>0){let Me=yi(),Ct=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=Ct[Ct.length-1];dt?.parentNode?dt.parentNode.insertBefore(Me,dt.nextSibling):De.appendChild(Me)}pi(p,De),V.onAfterRender?.({container:p,bubble:i,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let sn=En||ds;i.classList.toggle("persona-pill-peek--visible",sn)};if(Q()){let i=Te.peekBanner;if(i){let y=x=>{x.preventDefault(),x.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",y),Be.push(()=>{i.removeEventListener("pointerdown",y)})}let p=()=>{ds||(ds=!0,fr())},m=()=>{ds&&(ds=!1,fr())};ye.addEventListener("pointerenter",p),ye.addEventListener("pointerleave",m),Be.push(()=>{ye.removeEventListener("pointerenter",p),ye.removeEventListener("pointerleave",m)}),tt&&(tt.addEventListener("pointerenter",p),tt.addEventListener("pointerleave",m),Be.push(()=>{tt.removeEventListener("pointerenter",p),tt.removeEventListener("pointerleave",m)}))}let mm=i=>{let p=o.launcher?.composerBar??{},m=p.expandedSize??"anchored",y=p.bottomOffset??"16px",x=p.collapsedMaxWidth,E=p.expandedMaxWidth??"880px",U=p.expandedTopOffset??"5vh",O=p.modalMaxWidth??"880px",V=p.modalMaxHeight??"min(90vh, 800px)",J="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",le=Le.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",tt){let be=tt.style;be.bottom=y,be.width=x??""}if(i&&m!=="fullscreen"){if(m==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=O,le.maxWidth=J,le.maxHeight=V,le.height=V;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${y} + ${fe})`,le.top=U,le.width=E,le.maxWidth=J}},ps=()=>{if(!ie())return;if(Q()){let J=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Y?"expanded":"collapsed";Le.dataset.state=fe,Le.dataset.expandedSize=J,tt&&(tt.dataset.state=fe,tt.dataset.expandedSize=J),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),mm(Y),ve.style.display=Y?"flex":"none",Lo(),Y?(um(),fm()):($d(),Ud()),fr();return}let i=Rt(o),p=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,y=o.launcher?.mobileFullscreen??!0,x=p.innerWidth<=m,E=y&&x&&F,U=vn(o).reveal;Y?(Le.style.removeProperty("display"),Le.style.display=i?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),Tt?(Tt.setPanelOpen(!0),Tt.element.style.display="none"):Xt&&(Xt.style.display="none")):(i?i&&(U==="overlay"||U==="push")&&!E?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),Tt?(Tt.setPanelOpen(!1),Tt.element.style.display=i?"none":""):Xt&&(Xt.style.display=i?"none":""))},lt=(i,p="user")=>{if(!ie()||Y===i)return;let m=Y;Y=i,ps();let y=(()=>{let E=o.launcher?.sidebarMode??!1,U=e.ownerDocument.defaultView??window,O=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640,J=U.innerWidth<=V,fe=Rt(o)&&O&&J,le=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||O&&J&&F||fe||le})();if(Y&&y){if(!Wn){let E=e.getRootNode(),U=E instanceof ShadowRoot?E.host:e.closest(".persona-host");U&&(Wn=lc(U,o.launcher?.zIndex??Nt))}Rn||(Rn=cc(e.ownerDocument))}else Y||(Wn?.(),Wn=null,Rn?.(),Rn=null);Y&&(ms(),Fd()||(nn()==="follow"?lo(!0):Dd()));let x={open:Y,source:p,timestamp:Date.now()};Y&&!m?c.emit("widget:opened",x):!Y&&m&&c.emit("widget:closed",x),c.emit("widget:state",{open:Y,launcherEnabled:F,voiceActive:Ke.active,streaming:_.isStreaming()})},Aa=i=>{ra(i?"stop":"send"),oe&&(oe.disabled=i),Wo.forEach(p=>{p.elements.forEach(m=>{m.toggleAttribute("data-disabled",i),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",i?"true":"false")}),p.buttons.forEach(m=>{m.disabled=i})}),pl.forEach(p=>{p.toggleAttribute("data-disabled",i),p instanceof HTMLButtonElement?p.disabled=i:p.setAttribute("aria-disabled",i?"true":"false"),p.querySelectorAll("button").forEach(m=>{m.disabled=i})}),Ce.dataset.personaComposerStreaming=i?"true":"false",Ce.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=i)})},il=()=>{Ke.active||I&&I.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>il(),200)});let ll=!q.hidden,co=null,jd=!v,Vd=null,qd,Kd=null,us=null,cl=i=>{let p=Zo(o),m=`${p.variant}|${p.dismiss}|${p.title}|${p.subtitle}`;(m!==Vd||p.icon!==qd)&&(Vd=m,qd=p.icon,Pi({host:q,iconHolder:$,title:ce,subtitle:je,starterSuggestions:An},p));let y=p.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${p.message}`;y!==Kd&&(Kd=y,Ii(K,p.message,o));let x=i??(_?_.getMessages():o.initialMessages),E=_r(p,x),U=E!==ll;if(ll=E,us){co?.cancel(),co=null,Nr(re,q,!0);return}if(U&&!E&&p.dismiss==="on-first-message"&&jd){co=Pf(q,O=>{co===O&&(co=null),!ll&&!us&&(Nr(re,q,!1),_d()),O?.cancel()});return}if(co){if(!E)return;co.cancel(),co=null}Nr(re,q,E),U&&!E&&_d()},dl=[],pl=[],ul=!1,Gd=null,Yd,Xd=()=>{pl.length=0;let i=dl.splice(0,dl.length);for(let p of i)try{p()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Be.push(Xd);let hm=(i,p)=>{let m=pc(i,p);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),b("span");let y=o.suggestions?.starters,x=uc({item:{...m,behavior:m.behavior??y?.behavior??"send"},index:p,surface:"starter",source:"config",variant:y?.variant??"card",streaming:a?_.isStreaming():!1,config:o,plugins:s,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>I,eventTarget:q});return pl.push(x),x},fl=()=>{if(ul)return;ul=!0;let i=Zo(o);Gd=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Yd=i.icon;try{Xd(),kf(re,q,us),us=null;let p=_?_.getMessages():o.initialMessages,m=_r(i,p),y=0,x=null;for(let E of s)if(E.renderWelcome&&(x=E.renderWelcome({config:i,variant:i.variant,visible:m,defaultRenderer:()=>q,sendMessage:U=>{if(!_||_.isStreaming())return;let O=U.trim();O&&_.sendMessage(O)},requestRender:()=>fl(),renderStarter:U=>hm(U,y++),storage:l(E.id),onCleanup:U=>{dl.push(U)}}),x))break;x&&x!==q&&(us=x,Ef(re,q,x))}finally{ul=!1}cl()},ym=()=>{let i=Zo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Gd&&i.icon===Yd||fl()},gl=()=>{cl(),zi||(I.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(h.textContent=o.copy?.sendButtonLabel??"Send")),I.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',I.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=g.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{S(p=>({...p,sessionId:i}))}});let Uo=null,bm=()=>{Uo==null&&(Uo=setInterval(()=>{let i=xe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Uo),Uo=null;return}let p=Date.now();i.forEach(m=>{let y=Number(m.getAttribute("data-tool-elapsed"));y&&(m.textContent=za(p-y))})},100))},ml=(i,p)=>{if(Object.is(i,p))return!0;if(i===null||p===null||typeof i!="object"||typeof p!="object")return!1;if(Array.isArray(i)||Array.isArray(p))return!Array.isArray(i)||!Array.isArray(p)||i.length!==p.length?!1:i.every((U,O)=>ml(U,p[O]));let m=i,y=p,x=Object.keys(m),E=Object.keys(y);return x.length===E.length&&x.every(U=>Object.prototype.hasOwnProperty.call(y,U)&&ml(m[U],y[U]))},Qd=i=>{let{content:p,rawContent:m,llmContent:y,...x}=i;return x},hl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Oc(i),vm=(i,p,m)=>{if(i.length!==p.length)return!1;let y=i[m.index],x=p[m.index];return!y||!x||y.id!==m.id||x.id!==m.id?!1:(!Object.is(y.content,x.content)||!Object.is(y.rawContent,x.rawContent)||!Object.is(y.llmContent,x.llmContent))&&hl(y)&&hl(x)&&ml(Qd(y),Qd(x))},Jd=null,gr=null,zo=null,jn=null,Sa=i=>{Jd=i;let p,m;gr=null;for(let x=i.length-1;x>=0;x-=1){let E=i[x];if(!p&&E.role==="user"&&(p=E),!m&&E.role==="assistant"&&(m=E),!gr&&hl(E)&&(gr={index:x,id:E.id}),p&&m&&gr)break}is(xe,i,Z),tc(xe,Tn.artifacts,{suppressTransition:En}),bm(),cl(i),lr(i),lo(!En),dm(i),i.length===0&&(as(),rs=!0,ha=!1,dr=null,ya=!1),!Ji||ma?(Ji=!0,Oo=p?.id??null,Zi=m?.id??null):p&&p.id!==Oo?(Oo=p.id,sm(p.id)):m&&m.id!==Zi&&am(),m&&(Zi=m.id),cm(i);let y=Ke.lastUserMessageId;p&&p.id!==y&&(Ke.lastUserMessageId=p.id,c.emit("user:message",p)),Ke.lastUserMessageWasVoice=!!p?.viaVoice,nl(i),fr()},yl=()=>{jn!==null&&(cancelAnimationFrame(jn),jn=null);let i=zo;zo=null,i&&Sa(i)},Zd=()=>{jn!==null&&cancelAnimationFrame(jn),jn=null,zo=null},wm=i=>{let p=zo??Jd;if(En&&p&&gr&&vm(p,i,gr)){zo=i,jn===null&&(jn=requestAnimationFrame(()=>{jn=null;let m=zo;zo=null,m&&Sa(m)}));return}if(i.length===0){Zd(),Sa(i);return}yl(),Sa(i)};_=new Qa(o,{onMessagesChanged(i){wm(i)},onStatusChanged(i){let p=o.statusIndicator??{};Cn(R,(y=>y==="idle"?p.idleText??It.idle:y==="connecting"?p.connectingText??It.connecting:y==="connected"?p.connectedText??It.connected:y==="error"?p.errorText??It.error:y==="paused"?p.pausedText??It.paused:y==="resuming"?p.resumingText??It.resuming:It[y])(i),p,i)},onStreamingChanged(i){i||(_?.getMessages().length===0?Zd():yl()),En=i,Aa(i),_&&is(xe,_.getMessages(),Z),i||(lo(!0),om(),Md=!0,_&&Ed(_.getMessages(),vo(o))),$t(),Yc(i?"Responding\u2026":"Response complete."),fr()},onVoiceStatusChanged(i){if(c.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Vn(),hr();break;case"processing":Vn(),Im();break;case"speaking":Vn(),Wm();break;default:i==="idle"&&_.isBargeInActive()?(Vn(),hr(),oe?.setAttribute("aria-label","End voice session")):(Ke.active=!1,Vn(),zn("system"),kn());break}},onArtifactsState(i){Tn=i,i.artifacts.length===0&&(sr=!1),tc(xe,i.artifacts,{suppressTransition:En}),Nn(),nl()},onReconnect(i){let{executionId:p,lastEventId:m}=i.handle;i.phase==="paused"?c.emit("stream:paused",{executionId:p,after:m}):i.phase==="resuming"?c.emit("stream:resuming",{executionId:p,after:m,attempt:i.attempt??1}):c.emit("stream:resumed",{executionId:p,after:m})}}),st.current=_,Be.push(()=>_.cancel());let bl=null;if(_.onReadAloudChange((i,p)=>{id=i,ld=p,cd();let m=i??bl;i&&(bl=i);let y=m?_.getMessages().find(x=>x.id===m)??null:null;c.emit("message:read-aloud",{messageId:m,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(bl=null)}),a=!0,Ji=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&_.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Oe||o.onSSEEvent)&&_.setSSEEventCallback((i,p)=>{o.onSSEEvent?.(i,p),_e?.processEvent(i,p),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(p)})});let ep=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};v?v.then(i=>{if(i){if(i.metadata&&(g=Nc(i.metadata),H.syncFromMetadata()),i.messages?.length){ma=!0;try{_.hydrateMessages(i.messages)}finally{ma=!1}}i.artifacts?.length&&_.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{jd=!0,ep()}):ep();let tp=()=>{!Q()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},xm=(i,p)=>i?p?{refs:[...i.refs,...p.refs],finalize:async()=>{let[m,y]=await Promise.allSettled([i.finalize(),p.finalize()]),x=[];return m.status==="fulfilled"?x.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),y.status==="fulfilled"?x.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),mw(x)}}:i:p,Cm=()=>{let p=I.getInlineMessageFields?.();return p&&p.contentSegments.some(y=>y.kind==="mention")?p.contentSegments:void 0},fs=!1,Am=async i=>{let p=I.value.trim(),m=yt?.hasAttachments()??!1,y=p?await(Yt?.takeInlineCommand(p)??Promise.resolve(null)):null;if(y?.kind==="action"){I.value="",I.style.height="auto",gs(),Yt?.clear();return}let x=Yt?.collectForSubmit()??null,E=y?.kind==="server"?y.mentions:null,U=xm(x,E),O=y?.kind==="prompt"?y.sendText:p,V=!!x&&x.refs.length>0;if(!O&&!m&&!V&&!E)return;tp();let J;m&&(J=[],J.push(...yt.getContentParts()),O&&J.push(Lr(O)));let fe=y?.kind==="prompt"?void 0:Cm();I.value="",I.style.height="auto",gs(),_.sendMessage(O,{contentParts:J,mentions:U??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),m&&yt.clearAttachments(),x&&Yt?.clear()},vl=async i=>{if(!fs){fs=!0;try{await Am(i)}finally{fs=!1}}},Ta=i=>{if(i.preventDefault(),_.isStreaming()){_.cancel(),_e?.reset(),Ae?.update();return}fs||vl()},Sm=()=>o.features?.composerHistory!==!1,wl={...rc},xl=!1,gs=()=>{wl={...rc}},Tm=()=>_.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Mm=i=>{if(!I)return;xl=!0,I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0})),xl=!1;let p=I.value.length;I.setSelectionRange(p,p)},Em=i=>{xl||(i.isComposing||Yt?.handleInput(i.inputType??void 0),gs())},km=i=>{if(I&&!(!i.isComposing&&Yt?.handleKeydown(i))){if(Sm()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let p=I.selectionStart===0&&I.selectionEnd===0,m=sf({direction:i.key==="ArrowUp"?"up":"down",history:Tm(),currentValue:I.value,atStart:p,state:wl});if(wl=m.state,m.handled){i.preventDefault(),m.value!==void 0&&Mm(m.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(_.isStreaming()){i.preventDefault();return}if(fs){i.preventDefault();return}gs(),i.preventDefault(),h.click()}}},np=i=>{i.key!=="Escape"||i.isComposing||_.isStreaming()&&i.composedPath().includes(ve)&&(_.cancel(),_e?.reset(),Ae?.update(),gs(),i.preventDefault(),i.stopImmediatePropagation())},Lm=async i=>{if(o.attachments?.enabled!==!0||!yt)return;let p=pw(i.clipboardData);p.length!==0&&(i.preventDefault(),await yt.handleFiles(p))},gn=null,Hn=!1,mr=null,vt=null,op=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ma=(i="user")=>{if(Hn||_.isStreaming())return;let p=op();if(!p)return;gn=new p;let y=(o.voiceRecognition??{}).pauseDuration??2e3;gn.continuous=!0,gn.interimResults=!0,gn.lang="en-US";let x=I.value;gn.onresult=E=>{let U="",O="";for(let J=0;J<E.results.length;J++){let fe=E.results[J],le=fe[0].transcript;fe.isFinal?U+=le+" ":O=le}let V=x+U+O;I.value=V,mr&&clearTimeout(mr),(U||O)&&(mr=window.setTimeout(()=>{I.value.trim()&&gn&&Hn&&(po(),vl({viaVoice:!0}))},y))},gn.onerror=E=>{E.error!=="no-speech"&&po()},gn.onend=()=>{if(Hn){let E=I.value.trim();E&&E!==x.trim()&&vl({viaVoice:!0}),po()}};try{if(gn.start(),Hn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),zn(i),kn(),oe){let E=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let U=E.recordingBackgroundColor,O=E.recordingIconColor,V=E.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=U??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=O??"var(--persona-voice-recording-indicator, #ffffff)",O){let J=oe.querySelector("svg");J&&J.setAttribute("stroke",O)}V&&(oe.style.borderColor=V),oe.setAttribute("aria-label","Stop voice recognition")}}catch{po("system")}},po=(i="user")=>{if(Hn){if(Hn=!1,mr&&(clearTimeout(mr),mr=null),gn){try{gn.stop()}catch{}gn=null}if(Ke.active=!1,zn(i),kn(),oe){if(oe.classList.remove("persona-voice-recording"),vt){oe.style.backgroundColor=vt.backgroundColor,oe.style.color=vt.color,oe.style.borderColor=vt.borderColor;let p=oe.querySelector("svg");p&&p.setAttribute("stroke",vt.color||"currentColor"),vt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Pm=(i,p)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),y=i?.provider?.type==="runtype",x=i?.provider?.type==="custom";if(!(m||y||x))return null;let U=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button";let V=i?.tooltipText??"Start voice recognition";O.setAttribute("aria-label",V);let J=i?.iconName??"mic",fe=p?.size??"40px",le=i?.iconSize??fe,be=parseFloat(le)||24,Ge=i?.backgroundColor??p?.backgroundColor,mt=i?.iconColor??p?.textColor;O.style.width=le,O.style.height=le,O.style.minWidth=le,O.style.minHeight=le,O.style.fontSize="18px",O.style.lineHeight="1",mt?O.style.color=mt:O.style.color="var(--persona-text, #111827)";let sn=ae(J,be,mt||"currentColor",1.5);sn?O.appendChild(sn):O.textContent="\u{1F3A4}",Ge?O.style.backgroundColor=Ge:O.style.backgroundColor="",i?.borderWidth&&(O.style.borderWidth=i.borderWidth,O.style.borderStyle="solid"),i?.borderColor&&(O.style.borderColor=i.borderColor),i?.paddingX&&(O.style.paddingLeft=i.paddingX,O.style.paddingRight=i.paddingX),i?.paddingY&&(O.style.paddingTop=i.paddingY,O.style.paddingBottom=i.paddingY),U.appendChild(O);let At=i?.showTooltip??!1;return _t({anchor:O,trigger:U,text:()=>O.getAttribute("aria-label")??V,enabled:At}),{micButton:O,micButtonWrapper:U}},Cl=()=>{if(!oe||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Al=(i,p)=>{if(!oe)return;let m=oe.querySelector("svg");m&&m.remove();let y=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),x=ae(i,y,p,1.5);x&&oe.appendChild(x)},Ea=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hr=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=i.recordingBackgroundColor,m=i.recordingIconColor,y=i.recordingBorderColor;if(Ea(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=p??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let x=oe.querySelector("svg");x&&x.setAttribute("stroke",m)}y&&(oe.style.borderColor=y),oe.setAttribute("aria-label","Stop voice recognition")},Im=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=_.getVoiceInterruptionMode(),m=i.processingIconName??"loader",y=i.processingIconColor??vt?.color??"",x=i.processingBackgroundColor??vt?.backgroundColor??"",E=i.processingBorderColor??vt?.borderColor??"";Ea(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=x,oe.style.borderColor=E;let U=y||"currentColor";oe.style.color=U,Al(m,U),oe.setAttribute("aria-label","Processing voice input"),p==="none"&&(oe.style.cursor="default")},Wm=()=>{if(!oe)return;Cl();let i=o.voiceRecognition??{},p=_.getVoiceInterruptionMode(),m=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=i.speakingIconName??m,x=i.speakingIconColor??(p==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),E=i.speakingBackgroundColor??(p==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),U=i.speakingBorderColor??(p==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");Ea(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=E,oe.style.borderColor=U;let O=x||"currentColor";oe.style.color=O,Al(y,O);let V=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",V),p==="none"&&(oe.style.cursor="default"),p==="barge-in"&&oe.classList.add("persona-voice-recording")},Vn=()=>{oe&&(Ea(),vt&&(oe.style.backgroundColor=vt.backgroundColor??"",oe.style.color=vt.color??"",oe.style.borderColor=vt.borderColor??"",Al(vt.iconName,vt.color||"currentColor"),vt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},yr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=_.getVoiceStatus(),p=_.getVoiceInterruptionMode();if(p==="none"&&(i==="processing"||i==="speaking"))return;if(p==="cancel"&&(i==="processing"||i==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,kn(),zn("user"),Vn()});return}_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),Ke.manuallyDeactivated=!_.isVoiceActive(),kn(),zn("user"),_.isVoiceActive()?hr():Vn()});return}if(Hn){let i=I.value.trim();Ke.manuallyDeactivated=!0,kn(),po("user"),i&&(I.value="",I.style.height="auto",_.sendMessage(i))}else Ke.manuallyDeactivated=!1,kn(),Ma("user")};Qc=yr,oe&&(oe.addEventListener("click",yr),Be.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Vn()):po("system"),oe&&oe.removeEventListener("click",yr)}));let Rm=c.on("assistant:complete",()=>{Pd&&(Ke.active||Ke.manuallyDeactivated||Pd==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("auto"),_.isVoiceActive()&&hr()}):Ma("auto"))},600))});Be.push(Rm);let Hm=c.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});Be.push(Hm);let rp=()=>{lt(!Y,"user")},Tt=null,Xt=null;if(F&&!Q()){let{instance:i,element:p}=wc({config:o,plugins:s,onToggle:rp});Tt=i,i||(Xt=p)}Tt?e.appendChild(Tt.element):Xt&&e.appendChild(Xt),ps(),lr(),gl(),fl(),Aa(_.isStreaming()),Fd()||(nn()==="follow"?lo(!0):Dd()),Qg(),z&&(!F||Q()?setTimeout(()=>il(),0):Y&&setTimeout(()=>il(),200));let ms=()=>{if(Q()){ko(),ps();return}let i=Rt(o),p=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileFullscreen??!0,x=o.launcher?.mobileBreakpoint??640,E=m.innerWidth<=x,U=y&&E&&F;try{if(U){Lo(),ts=ua();return}let O=!1;G&&(G=!1,Lo(),O=!0);let V=ua();if(!O&&V!==ts&&(Lo(),O=!0),ts=V,O&&Ki(),!F&&!i){ye.style.height="",ye.style.width="";return}if(!p&&!i){let fe=o?.launcher?.width??o?.launcherWidth??Jn;ye.style.width=fe,ye.style.maxWidth=fe}pa(),md()}finally{if(ko(),ps(),Y&&F){let V=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),J=o.launcher?.sidebarMode??!1,fe=o.launcher?.mobileFullscreen??!0,le=Rt(o)&&fe&&V,be=J||fe&&V&&F||le;if(be&&!Rn){let Ge=e.getRootNode(),mt=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");mt&&!Wn&&(Wn=lc(mt,o.launcher?.zIndex??Nt)),Rn=cc(e.ownerDocument)}else be||(Wn?.(),Wn=null,Rn?.(),Rn=null)}}};ms();let sp=e.ownerDocument.defaultView??window;if(sp.addEventListener("resize",ms),Be.push(()=>sp.removeEventListener("resize",ms)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{ko()});i.observe(Ce),Be.push(()=>i.disconnect())}rn=re.scrollTop;let ap=Dn(re),ip=()=>{let i=re.scrollTop,p=Dn(re),m=p<ap;if(ap=p,!no()){rn=i,$t();return}let{action:y,nextLastScrollTop:x}=fi({following:on.isFollowing(),currentScrollTop:i,lastScrollTop:rn,nearBottom:eo(re,$n),userScrollThreshold:Kg,isAutoScrolling:Zt||ga||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(rn=x,y==="resume"){va()||io();return}y==="pause"&&ss()};if(re.addEventListener("scroll",ip,{passive:!0}),Be.push(()=>re.removeEventListener("scroll",ip)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{rm(),Il(xe)});i.observe(xe),i.observe(re),Be.push(()=>i.disconnect())}let lp=()=>{no()&&on.isFollowing()&&va()&&ss()},cp=re.ownerDocument;cp.addEventListener("selectionchange",lp),Be.push(()=>{cp.removeEventListener("selectionchange",lp)});let Bm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),dp=i=>{Bm.has(i.key)&&(No(),qc()&&no()&&on.isFollowing()&&ss())},pp=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(No(),qc()&&no()&&on.isFollowing()&&ss())};re.addEventListener("keydown",dp),re.addEventListener("focusin",pp),Be.push(()=>{re.removeEventListener("keydown",dp),re.removeEventListener("focusin",pp)});let up=i=>{if(i.deltaY!==0&&No(),!no())return;let p=gi({following:on.isFollowing(),deltaY:i.deltaY,nearBottom:eo(re,$n),resumeWhenNearBottom:!0});p==="pause"?ss():p==="resume"&&!va()&&io()};re.addEventListener("wheel",up,{passive:!0}),re.addEventListener("touchmove",No,{passive:!0}),re.addEventListener("pointerdown",No,{passive:!0}),Be.push(()=>{re.removeEventListener("touchmove",No),re.removeEventListener("pointerdown",No)}),Be.push(()=>re.removeEventListener("wheel",up)),Et.addEventListener("click",()=>{as(),re.scrollTop=re.scrollHeight,rn=re.scrollTop,io(),lo(!0),$t()}),Be.push(()=>Et.remove()),Be.push(()=>{Rd(),as()});let fp=()=>{de&&(Ro&&(de.removeEventListener("click",Ro),Ro=null),ie()?(de.style.display="",Ro=()=>{lt(!1,"user")},de.addEventListener("click",Ro)):de.style.display="none")};fp(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{_.clearMessages(),Bo.clear(),io(),Er(Te.composerOverlay);try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(p),w?.clear&&tl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),g={},H.syncFromMetadata(),Oe?.clear(),_e?.reset(),Ae?.update()})})(),L&&L.addEventListener("submit",Ta);let gp=[["keydown",km],["input",Em],["paste",Lm],["focus",_g]],Sl=i=>{if(i)for(let[p,m]of gp)i.addEventListener(p,m)},Tl=i=>{if(i)for(let[p,m]of gp)i.removeEventListener(p,m)};Sl(I);let mp=()=>{Yt?.onComposerSwap((i,p)=>{Tl(p),I=i,Sl(i)})};mp();let Ml=!1;function Dm(){if(!Ml){Ml=!0;try{let i=I?.value??"",p=Ce.ownerDocument??document,m=I?p.activeElement===I:!1;Tl(I),L?.removeEventListener("submit",Ta),oe?.removeEventListener("click",yr),Yt?.destroy(),Yt=null;let y=null,x=()=>(y=Q()?ki({config:o}):Gs({config:o}),y.footer),E=ed(x)??x();et.replaceComposer(E),Ce=et.composer.footer;let U=y!==null&&E===y.footer;zi=!U,ra=U?y.setSendButtonMode:()=>{},Zc(Ce),nd(Ce),od(),rd(),sd(),mp(),L&&L.addEventListener("submit",Ta),Sl(I),oe?.addEventListener("click",yr);let O=Wo.indexOf(_n);_n.destroy(),_n=qs(M),O>=0&&(Wo[O]=_n),I&&(I.value=i),gl(),lr(),Aa(_.isStreaming()),Lo(),ko(),m&&I?.focus()}finally{Ml=!1}}}let hp=e.ownerDocument??document;hp.addEventListener("keydown",np,!0);let yp="persona-attachment-drop-active",hs=0,El=()=>{hs=0,ve.classList.remove(yp)},br=()=>o.attachments?.enabled===!0&&yt!==null,bp=i=>{!Fi(i.dataTransfer)||!br()||(hs++,hs===1&&ve.classList.add(yp))},vp=i=>{!Fi(i.dataTransfer)||!br()||(hs--,hs<=0&&El())},wp=i=>{!Fi(i.dataTransfer)||!br()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},xp=i=>{if(!Fi(i.dataTransfer)||!br())return;i.preventDefault(),i.stopPropagation(),El();let p=Array.from(i.dataTransfer.files??[]);p.length!==0&&yt.handleFiles(p)},uo=!0;ve.addEventListener("dragenter",bp,uo),ve.addEventListener("dragleave",vp,uo),e.addEventListener("dragover",wp,uo),e.addEventListener("drop",xp,uo);let ka=e.ownerDocument,Cp=i=>{br()&&i.preventDefault()},Ap=i=>{br()&&i.preventDefault()};ka.addEventListener("dragover",Cp),ka.addEventListener("drop",Ap),Be.push(()=>{L&&L.removeEventListener("submit",Ta),Tl(I),hp.removeEventListener("keydown",np,!0),Yt?.destroy()}),Be.push(()=>{ve.removeEventListener("dragenter",bp,uo),ve.removeEventListener("dragleave",vp,uo),e.removeEventListener("dragover",wp,uo),e.removeEventListener("drop",xp,uo),ka.removeEventListener("dragover",Cp),ka.removeEventListener("drop",Ap),El()}),Be.push(()=>{_.cancel()}),Tt?Be.push(()=>{Tt?.destroy()}):Xt&&Be.push(()=>{Xt?.remove()});let kt={update(i){let p=o.toolCall,m=o.messageActions,y=o.layout?.messages,x=o.colorScheme,E=o.loadingIndicator,U=o.iterationDisplay,O=o.features?.showReasoning,V=o.features?.showToolCalls,J=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=ug({...o,features:r},i),r=o.features,o=Pc(o),Yi(),Ds(e,o),ea(e,o),ta(e,o),Nn(),o.colorScheme!==x&&hd();let be=Hc.getForInstance(o.plugins);s.length=0,s.push(...be),F=o.launcher?.enabled??!0,N=o.launcher?.autoExpand??!1,pe=o.features?.showReasoning??!0,ee=o.features?.showToolCalls??!0,we=o.features?.scrollToBottom??{};let Ge=nn();he=o.features?.scrollBehavior??{},Ge!==nn()&&(as(),io()),Ld(),Xc(),$t();let mt=me;if(me=o.features?.showEventStreamToggle??!1,me&&!mt){if(Oe||(Ue=new Js(Ne),Oe=new Qs(Qe,Ue),_e=_e??new Zs,Ue.open().then(()=>Oe?.restore()).catch(()=>{}),_.setSSEEventCallback((se,qe)=>{o.onSSEEvent?.(se,qe),_e?.processEvent(se,qe),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify(qe)})})),!Je&&Re){let se=o.features?.eventStream?.classNames,qe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(se?.toggleButton?" "+se.toggleButton:"");Je=b("button",qe),Je.style.width="28px",Je.style.height="28px",Je.style.color=Kt.actionIconColor,Je.type="button",Je.setAttribute("aria-label","Event Stream"),Je.title="Event Stream";let ft=ae("activity","18px","currentColor",1.5);ft&&Je.appendChild(ft);let Ze=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Vt=Ze||ot;Vt&&Vt.parentNode===Re?Re.insertBefore(Je,Vt):Re.appendChild(Je),Je.addEventListener("click",()=>{Se?Jr():$i()})}}else!me&&mt&&(Jr(),Je&&(Je.remove(),Je=null),Oe?.clear(),Ue?.destroy(),Oe=null,Ue=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Tt&&(Tt.destroy(),Tt=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Tt&&!Xt){let{instance:se,element:qe}=wc({config:o,plugins:s,onToggle:rp});Tt=se,se||(Xt=qe),e.appendChild(qe)}Tt&&Tt.update(o),Ve&&o.launcher?.title!==void 0&&(Ve.textContent=o.launcher.title),$e&&o.launcher?.subtitle!==void 0&&($e.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==A&&Re){let se=ct?xi(o,ct,{showClose:ie(),onClose:()=>lt(!1,"user")}):Jo({config:o,showClose:ie(),onClose:()=>lt(!1,"user")});et.replaceHeader(se),Re=et.header.element,Pe=et.header.iconHolder,Ve=et.header.headerTitle,$e=et.header.headerSubtitle,de=et.header.closeButton,A=ct?.layout}else if(ct){if(Pe&&(Pe.style.display=ct.showIcon===!1?"none":""),Ve&&(Ve.style.display=ct.showTitle===!1?"none":""),$e&&($e.style.display=ct.showSubtitle===!1?"none":""),de){let se=ie()&&ct.showCloseButton!==!1;de.style.display=se?"":"none"}if(Te.clearChatButtonWrapper){let se=ct.showClearChat;if(se!==void 0){Te.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:qe}=Te;qe&&!qe.classList.contains("persona-absolute")&&(se?qe.classList.remove("persona-ml-auto"):qe.classList.add("persona-ml-auto"))}}}let At=o.layout?.showHeader!==!1;Re&&(Re.style.display=At?"":"none");let Lt=o.layout?.showFooter!==!1;Ce&&(Ce.style.display=Lt?"":"none"),ko(),$t(),F!==te?F?lt(N,"auto"):(Y=!0,ps()):N!==j&<(N,"auto"),j=N,te=F,ms(),fp();let De=JSON.stringify(o.toolCall)!==JSON.stringify(p),Me=JSON.stringify(o.messageActions)!==JSON.stringify(m),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(y),dt=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,Ft=o.iterationDisplay!==U,pt=(o.features?.showReasoning??!0)!==(O??!0)||(o.features?.showToolCalls??!0)!==(V??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(J)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(De||Me||Ct||dt||Ft||pt)&&_&&(Qi++,is(xe,_.getMessages(),Z));let Pt=o.features?.streamAnimation?.type;if(Pt!==le&&Pt&&Pt!=="none"){let se=Or(Pt,o.features?.streamAnimation?.plugins);se&&bi(se,e)}let We=o.launcher??{},Fe=We.headerIconHidden??!1,Ut=o.layout?.header?.showIcon,zt=Fe||Ut===!1,wt=We.headerIconName,at=We.headerIconSize??"48px";if(Pe){let se=ve.querySelector(".persona-border-b-persona-divider"),qe=se?.querySelector(".persona-flex-col");if(zt)Pe.style.display="none",se&&qe&&!se.contains(qe)&&se.insertBefore(qe,se.firstChild);else{if(Pe.style.display="",Pe.style.height=at,Pe.style.width=at,se&&qe&&(se.contains(Pe)?Pe.nextSibling!==qe&&(Pe.remove(),se.insertBefore(Pe,qe)):se.insertBefore(Pe,qe)),wt){let Ze=parseFloat(at)||24,ot=ae(wt,Ze*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let Ze=Pe.querySelector("img");if(Ze)Ze.src=We.iconUrl,Ze.style.height=at,Ze.style.width=at;else{let ot=document.createElement("img");ot.src=We.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=at,ot.style.width=at,Pe.replaceChildren(ot)}}else{let Ze=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Ze||ot)&&Pe.replaceChildren(),Pe.textContent=We.agentIconText??"\u{1F4AC}"}let ft=Pe.querySelector("img");ft&&(ft.style.height=at,ft.style.width=at)}}let ut=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(Ve&&(Ve.style.display=ut===!1?"none":""),$e&&($e.style.display=Xe===!1?"none":""),de){let se=ie()&&o.layout?.header?.showCloseButton!==!1;de.style.display=se?"":"none";let qe=We.closeButtonSize??"32px",ft=We.closeButtonPlacement??"inline";de.style.height=qe,de.style.width=qe;let{closeButtonWrapper:Ze}=Te,ot=ft==="top-right",Vt=Ze?.classList.contains("persona-absolute");if(Ze&&ot!==Vt)if(Ze.remove(),ot)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ve.style.position="relative",ve.appendChild(Ze);else{let go=We.clearChat?.placement??"inline",vs=We.clearChat?.enabled??!0;Ze.className=vs&&go==="inline"?"":"persona-ml-auto";let Sp=ve.querySelector(".persona-border-b-persona-divider");Sp&&Sp.appendChild(Ze)}if(de.style.color=We.closeButtonColor||Kt.actionIconColor,We.closeButtonBackgroundColor?(de.style.backgroundColor=We.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let go=We.closeButtonBorderWidth||"0px",vs=We.closeButtonBorderColor||"transparent";de.style.border=`${go} solid ${vs}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");We.closeButtonBorderRadius?(de.style.borderRadius=We.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(de.style.paddingLeft=We.closeButtonPaddingX,de.style.paddingRight=We.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),We.closeButtonPaddingY?(de.style.paddingTop=We.closeButtonPaddingY,de.style.paddingBottom=We.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let an=We.closeButtonIconName??"x",Ln=We.closeButtonIconText??"\xD7";de.innerHTML="";let Ot=ae(an,"28px","currentColor",1);Ot?(Ot.style.display="block",de.appendChild(Ot)):de.textContent=Ln;let qt=We.closeButtonTooltipText??"Close chat",Kn=We.closeButtonShowTooltip??!0;de.setAttribute("aria-label",qt),Ze&&_t({anchor:de,trigger:Ze,text:()=>de?.getAttribute("aria-label")??qt,enabled:Kn})}let{clearChatButton:He,clearChatButtonWrapper:ht}=Te;if(He){let se=We.clearChat??{},qe=se.enabled??!0,ft=o.layout?.header?.showClearChat,Ze=ft!==void 0?ft:qe,ot=se.placement??"inline";if(ht){ht.style.display=Ze?"":"none";let{closeButtonWrapper:Vt}=Te;!Q()&&Vt&&!Vt.classList.contains("persona-absolute")&&(Ze?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let an=ot==="top-right",Ln=ht.classList.contains("persona-absolute");if(!Q()&&an!==Ln&&Ze){if(ht.remove(),an)ht.className="persona-absolute persona-top-4 persona-z-50",ht.style.right="48px",ve.style.position="relative",ve.appendChild(ht);else{ht.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ht.style.right="";let qt=ve.querySelector(".persona-border-b-persona-divider"),Kn=Te.closeButtonWrapper;qt&&Kn&&Kn.parentElement===qt?qt.insertBefore(ht,Kn):qt&&qt.appendChild(ht)}let Ot=Te.closeButtonWrapper;Ot&&!Ot.classList.contains("persona-absolute")&&(an?Ot.classList.add("persona-ml-auto"):Ot.classList.remove("persona-ml-auto"))}}if(Ze){if(!Q()){let go=se.size??"32px";He.style.height=go,He.style.width=go}let Vt=se.iconName??"refresh-cw",an=se.iconColor??"";He.style.color=an||Kt.actionIconColor,He.innerHTML="";let Ln=Q()?"14px":"20px",Ot=ae(Vt,Ln,"currentColor",1);if(Ot&&(Ot.style.display="block",He.appendChild(Ot)),se.backgroundColor?(He.style.backgroundColor=se.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let go=se.borderWidth||"0px",vs=se.borderColor||"transparent";He.style.border=`${go} solid ${vs}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");se.borderRadius?(He.style.borderRadius=se.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),se.paddingX?(He.style.paddingLeft=se.paddingX,He.style.paddingRight=se.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),se.paddingY?(He.style.paddingTop=se.paddingY,He.style.paddingBottom=se.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let qt=se.tooltipText??"Clear chat",Kn=se.showTooltip??!0;He.setAttribute("aria-label",qt),ht&&_t({anchor:He,trigger:ht,text:()=>He?.getAttribute("aria-label")??qt,enabled:Kn})}}let jt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Dc],hn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[na.message,na.messageAndClick];H=Fc({parsers:jt,handlers:hn,getSessionMetadata:B,updateSessionMetadata:S,emit:c.emit,documentRef:typeof document<"u"?document:null}),Z=Cg(o,H,ge),_.updateConfig(o),is(xe,_.getMessages(),Z),lr(),gl(),ym(),Aa(_.isStreaming());let ys=o.voiceRecognition?.enabled===!0,La=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mt=o.voiceRecognition?.provider?.type==="runtype";if(ys&&(La||Mt))if(!oe||!pn){let se=Pm(o.voiceRecognition,o.sendButton);se&&(oe=se.micButton,pn=se.micButtonWrapper,xt.insertBefore(pn,W),oe.addEventListener("click",yr),oe.disabled=_.isStreaming())}else{let se=o.voiceRecognition??{},qe=o.sendButton??{},ft=se.iconName??"mic",Ze=qe.size??"40px",ot=se.iconSize??Ze,Vt=parseFloat(ot)||24;oe.style.width=ot,oe.style.height=ot,oe.style.minWidth=ot,oe.style.minHeight=ot;let an=se.iconColor??qe.textColor;oe.innerHTML="";let Ln=ae(ft,Vt,an||"currentColor",1.5);Ln?oe.appendChild(Ln):oe.textContent="\u{1F3A4}";let Ot=se.backgroundColor??qe.backgroundColor;Ot?oe.style.backgroundColor=Ot:oe.style.backgroundColor="",an?oe.style.color=an:oe.style.color="var(--persona-text, #111827)",se.borderWidth?(oe.style.borderWidth=se.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),se.borderColor?oe.style.borderColor=se.borderColor:oe.style.borderColor="",se.paddingX?(oe.style.paddingLeft=se.paddingX,oe.style.paddingRight=se.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),se.paddingY?(oe.style.paddingTop=se.paddingY,oe.style.paddingBottom=se.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let qt=se.tooltipText??"Start voice recognition",Kn=se.showTooltip??!1;oe.setAttribute("aria-label",qt),pn&&_t({anchor:oe,trigger:pn,text:()=>oe?.getAttribute("aria-label")??qt,enabled:Kn}),pn.style.display="",oe.disabled=_.isStreaming()}else oe&&pn&&(pn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Hn&&po());if(o.attachments?.enabled===!0){if(!un||!it){let se=o.attachments??{},ft=(o.sendButton??{}).size??"40px";Sn||(Sn=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Sn.style.display="none",L.insertBefore(Sn,I)),St||(St=document.createElement("input"),St.type="file",St.accept=(se.allowedTypes??Qn).join(","),St.multiple=(se.maxFiles??4)>1,St.style.display="none",St.setAttribute("aria-label","Attach files"),L.insertBefore(St,I)),un=b("div","persona-send-button-wrapper"),it=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let Ze=se.buttonIconName??"paperclip",ot=ft,Vt=parseFloat(ot)||40,an=Math.round(Vt*.6);it.style.width=ot,it.style.height=ot,it.style.minWidth=ot,it.style.minHeight=ot,it.style.fontSize="18px",it.style.lineHeight="1";let Ln=ae(Ze,an,"currentColor",1.5);Ln?it.appendChild(Ln):it.textContent="\u{1F4CE}",it.addEventListener("click",qt=>{qt.preventDefault(),St?.click()}),un.appendChild(it);let Ot=se.buttonTooltipText??"Attach file";_t({anchor:it,trigger:un,text:()=>it?.getAttribute("aria-label")??Ot}),dn?dn.append(un):L.appendChild(un),!yt&&St&&Sn&&(yt=Rs.fromConfig(se),yt.setPreviewsContainer(Sn),St.addEventListener("change",async()=>{yt&&St?.files&&(await yt.handleFileSelect(St.files),St.value="")}))}else{un.style.display="";let se=o.attachments??{};St&&(St.accept=(se.allowedTypes??Qn).join(","),St.multiple=(se.maxFiles??4)>1),yt&&yt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(ve.querySelector(".persona-attachment-drop-overlay")?.remove(),ve.appendChild(Ag(o.attachments?.dropOverlay)),it){let se=o.attachments??{},qe=se.buttonTooltipText??"Attach file";it.setAttribute("aria-label",qe),it.textContent="";let ft=parseFloat(o.sendButton?.size??"40px")||40,Ze=ae(se.buttonIconName??"paperclip",Math.round(ft*.6),"currentColor",1.5);Ze?it.appendChild(Ze):it.textContent="\u{1F4CE}",un&&_t({anchor:it,trigger:un,text:()=>it?.getAttribute("aria-label")??qe})}}else un&&(un.style.display="none"),yt&&yt.clearAttachments(),ve.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},bs=Dt.useIcon??!1,Ia=Dt.iconText??"\u2191",vr=Dt.iconName,Wa=Dt.tooltipText??"Send message",kl=Dt.showTooltip??!1,jo=Dt.size??"40px",qn=Dt.backgroundColor,Vo=Dt.textColor;if(bs){if(h.style.width=jo,h.style.height=jo,h.style.minWidth=jo,h.style.minHeight=jo,h.style.fontSize="18px",h.style.lineHeight="1",Vo?h.style.color=Vo:h.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(h.innerHTML="",vr){let se=parseFloat(jo)||24,qe=Vo?.trim()||"currentColor",ft=ae(vr,se,qe,2);ft?h.appendChild(ft):h.textContent=Ia}else h.textContent=Ia;h.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",qn?(h.style.backgroundColor=qn,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary"))}else h.textContent=o.copy?.sendButtonLabel??"Send",h.style.width="",h.style.height="",h.style.minWidth="",h.style.minHeight="",h.style.fontSize="",h.style.lineHeight="",h.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",qn?(h.style.backgroundColor=qn,h.classList.remove("persona-bg-persona-accent")):h.classList.add("persona-bg-persona-accent"),Vo?h.style.color=Vo:h.classList.add("persona-text-white");Dt.borderWidth?(h.style.borderWidth=Dt.borderWidth,h.style.borderStyle="solid"):(h.style.borderWidth="",h.style.borderStyle=""),Dt.borderColor?h.style.borderColor=Dt.borderColor:h.style.borderColor="",Dt.paddingX?(h.style.paddingLeft=Dt.paddingX,h.style.paddingRight=Dt.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),Dt.paddingY?(h.style.paddingTop=Dt.paddingY,h.style.paddingBottom=Dt.paddingY):(h.style.paddingTop="",h.style.paddingBottom=""),_.isStreaming()||h.setAttribute("aria-label",Wa),W&&_t({anchor:h,trigger:W,text:()=>h.getAttribute("aria-label")??Wa,enabled:kl});let wr=xo(o,Q());Xi(),wr?(xe.style.maxWidth=wr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",K.style.maxWidth=wr,K.style.marginLeft="auto",K.style.marginRight="auto",K.style.width="100%",L&&(L.style.maxWidth=wr,L.style.marginLeft="auto",L.style.marginRight="auto"),M&&(M.style.maxWidth=wr,M.style.marginLeft="auto",M.style.marginRight="auto"),R.style.maxWidth=wr,R.style.marginLeft="auto",R.style.marginRight="auto"):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",K.style.maxWidth="",K.style.marginLeft="",K.style.marginRight="",K.style.width="",L&&(L.style.maxWidth="",L.style.marginLeft="",L.style.marginRight=""),M&&(M.style.maxWidth="",M.style.marginLeft="",M.style.marginRight=""),R.style.maxWidth="",R.style.marginLeft="",R.style.marginRight="");let fo=o.statusIndicator??{},Fm=fo.visible??!0;if(R.style.display=Fm?"":"none",_){let se=_.getStatus();Cn(R,(ft=>ft==="idle"?fo.idleText??It.idle:ft==="connecting"?fo.connectingText??It.connecting:ft==="connected"?fo.connectedText??It.connected:ft==="error"?fo.errorText??It.error:It[ft])(se),fo,se)}R.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Om=fo.align==="left"?"persona-text-left":fo.align==="center"?"persona-text-center":"persona-text-right";R.classList.add(Om)},open(){ie()&<(!0,"api")},close(){ie()&<(!1,"api")},toggle(){ie()&<(!Y,"api")},reconnect(){_.reconnectNow()},clearChat(){On=!1,_.clearMessages(),Bo.clear(),io();try{localStorage.removeItem(qr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${qr}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==qr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),w?.clear&&tl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),g={},H.syncFromMetadata(),Oe?.clear(),_e?.reset(),Ae?.update()},setMessage(i){return!I||_.isStreaming()?!1:(!Y&&ie()&<(!0,"system"),I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(_.isStreaming())return!1;let p=i?.trim()||I.value.trim();return p?(!Y&&ie()&<(!0,"system"),I.value="",I.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!Y&&ie()&<(!0,"system"),Ke.manuallyDeactivated=!1,kn(),_.toggleVoice().then(()=>{Ke.active=_.isVoiceActive(),zn("user"),_.isVoiceActive()&&hr()})),!0):Hn?!0:op()?(!Y&&ie()&<(!0,"system"),Ke.manuallyDeactivated=!1,kn(),Ma("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,kn(),zn("user"),Vn()}),!0):!1:Hn?(Ke.manuallyDeactivated=!0,kn(),po("user"),!0):!1},injectMessage(i){return!Y&&ie()&<(!0,"system"),_.injectMessage(i)},injectAssistantMessage(i){!Y&&ie()&<(!0,"system");let p=_.injectAssistantMessage(i);return ue&&(ue=!1,X&&(clearTimeout(X),X=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(i){return!Y&&ie()&<(!0,"system"),_.injectUserMessage(i)},injectSystemMessage(i){return!Y&&ie()&<(!0,"system"),_.injectSystemMessage(i)},injectMessageBatch(i){return!Y&&ie()&<(!0,"system"),_.injectMessageBatch(i)},injectComponentDirective(i){return!Y&&ie()&<(!0,"system"),_.injectComponentDirective(i)},injectTestMessage(i){!Y&&ie()&<(!0,"system"),_.injectTestEvent(i)},async connectStream(i,p){return _.connectStream(i,p)},__pushEventStreamEvent(i){Oe&&(_e?.processEvent(i.type,i.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!me||!Oe||$i()},hideEventStream(){Se&&Jr()},isEventStreamVisible(){return Se},showArtifacts(){Jt(o)&&(On=!1,sr=!0,Nn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(On=!0,Nn())},upsertArtifact(i){return Jt(o)?(ho(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(On=!1,sr=!0),_.upsertArtifact(i)):null},selectArtifact(i){Jt(o)&&_.selectArtifact(i)},clearArtifacts(){Jt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return F&&!Y&&!Q()||!I?!1:(I.focus(),!0)},async resolveApproval(i,p,m){let x=_.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===i);if(!x?.approval)throw new Error(`Approval not found: ${i}`);if(x.approval.toolType==="webmcp"){_.resolveWebMcpApproval(x.id,p);return}return _.resolveApproval(x.approval,p,m)},setFollowUpSuggestions(i){Vg(i)},clearFollowUpSuggestions(){kd()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...g}},updatePersistentMetadata(i){S(i)},on(i,p){return c.on(i,p)},off(i,p){c.off(i,p)},isOpen(){return ie()&&Y},isVoiceActive(){return Ke.active},toggleReadAloud(i){_.toggleReadAloud(i)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(i){return _.getReadAloudState(i)},onReadAloudChange(i){return _.onReadAloudChange(i)},getState(){return{open:ie()&&Y,launcherEnabled:F,voiceActive:Ke.active,streaming:_.isStreaming()}},showCSATFeedback(i){!Y&&ie()&<(!0,"system");let p=xe.querySelector(".persona-feedback-container");p&&p.remove();let m=vg({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});xe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Y&&ie()&<(!0,"system");let p=xe.querySelector(".persona-feedback-container");p&&p.remove();let m=wg({onSubmit:async(y,x)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(y,x),i?.onSubmit?.(y,x)},onDismiss:i?.onDismiss,...i});xe.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,p){return _.submitCSATFeedback(i,p)},async submitNPSFeedback(i,p){return _.submitNPSFeedback(i,p)},destroy(){yl(),Uo!=null&&(clearInterval(Uo),Uo=null),Be.forEach(i=>i()),Le.remove(),tt?.remove(),Tt?.destroy(),Xt?.remove(),Ro&&de.removeEventListener("click",Ro)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,p={controller:kt,getMessages:kt.getMessages,getStatus:kt.getStatus,getMetadata:kt.getPersistentMetadata,updateMetadata:kt.updatePersistentMetadata,clearHistory:()=>kt.clearChat(),setVoiceActive:m=>m?kt.startVoiceRecognition():kt.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Be.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.focusInput()};if(window.addEventListener("persona:focusInput",p),Be.push(()=>{window.removeEventListener("persona:focusInput",p)}),me){let O=J=>{let fe=J.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.showEventStream()},V=J=>{let fe=J.detail;(!fe?.instanceId||fe.instanceId===i)&&kt.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",V),Be.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",V)})}let m=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.showArtifacts()},y=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.hideArtifacts()},x=O=>{let V=O.detail;V?.instanceId&&V.instanceId!==i||V?.artifact&&kt.upsertArtifact(V.artifact)},E=O=>{let V=O.detail;V?.instanceId&&V.instanceId!==i||typeof V?.id=="string"&&kt.selectArtifact(V.id)},U=O=>{let V=O.detail;(!V?.instanceId||V.instanceId===i)&&kt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",x),window.addEventListener("persona:selectArtifact",E),window.addEventListener("persona:clearArtifacts",U),Be.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",x),window.removeEventListener("persona:selectArtifact",E),window.removeEventListener("persona:clearArtifacts",U)})}let mn=uw(o.persistState);if(mn&&ie()){let i=fw(mn.storage),p=`${mn.keyPrefix}widget-open`,m=`${mn.keyPrefix}widget-voice`,y=`${mn.keyPrefix}widget-voice-mode`;if(i){let x=mn.persist?.openState&&i.getItem(p)==="true",E=mn.persist?.voiceState&&i.getItem(m)==="true",U=mn.persist?.voiceState&&i.getItem(y)==="true";if(x&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open(),setTimeout(()=>{if(E||U)kt.startVoiceRecognition();else if(mn.persist?.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0)),mn.persist?.openState&&(c.on("widget:opened",()=>{i.setItem(p,"true")}),c.on("widget:closed",()=>{i.setItem(p,"false")})),mn.persist?.voiceState&&(c.on("voice:state",O=>{i.setItem(m,O.active?"true":"false")}),c.on("user:message",O=>{i.setItem(y,O.viaVoice?"true":"false")})),mn.clearOnChatClear){let O=()=>{i.removeItem(p),i.removeItem(m),i.removeItem(y)},V=()=>O();window.addEventListener("persona:clear-chat",V),Be.push(()=>{window.removeEventListener("persona:clear-chat",V)})}}}if(C&&ie()&&(Tt?.setPanelOpen(!0,"auto"),setTimeout(()=>{kt.open()},0)),fr(),!qg){let i=Ha(()=>{_&&(Qi++,Bo.clear(),is(xe,_.getMessages(),Z))});Be.push(i)}return kt};var Tg=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},yw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},bw=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Mg=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},zc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Eg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",zc(e)},_c=e=>{e.style.transition=""},$c=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Uc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Oi=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},vw=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},ww=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},xw=e=>{let t=Rr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Qt(t,r)??r;return{inset:o(n?.inset,ti),canvasBackground:o(n?.canvasBackground,ni)}},kg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Cw=(e,t,n,o,r,s,a,l)=>{let u=vn(s),d=u.reveal==="push",c=l!=null,f=l?.inset??"",w=l?.canvasBackground??"";vw(e,t,n,o,d),ww(e,t,n,o,u.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=u.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,v=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,T=g!=null?g.innerWidth<=C:!1;if(v&&T&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$c(t),_c(o),Eg(o),Uc(n),Oi(r,o),kg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Nt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Eg(o),hw(o,u.maxHeight),kg(o,c&&a,f,w),u.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$c(t),_c(o),Uc(n),Oi(r,o);let S=u.animate?"transform 180ms ease":"none",k=u.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":k;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=u.width,o.style.maxWidth=u.width,o.style.minWidth=u.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=S,o.style.transform=P,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",u.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(u.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",_c(o),zc(o),Oi(r,o);let S=Tg(u.width,e.clientWidth),k=Math.max(0,e.clientWidth),P=u.animate?"margin-left 180ms ease":"none",H=u.side==="right"?a?-S:0:a?0:-S;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${k+S}px`,t.style.transition=P,t.style.marginLeft=`${H}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=u.width,o.style.minWidth=u.width,o.style.maxWidth=u.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",$c(t),zc(o),Uc(n),Oi(r,o);let S=u.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?u.width:"0px",P=u.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",H=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${k}`,o.style.width=k,o.style.maxWidth=k,o.style.minWidth=k,o.style.minHeight="0",yw(o,u.maxHeight),o.style.overflow=S||H?"hidden":"visible",o.style.transition=P,S){o.style.alignItems=u.side==="right"?"flex-start":"flex-end";let F=c?`calc(${Tg(u.width,e.clientWidth)}px - (2 * ${f}))`:u.width;r.style.width=F,r.style.minWidth=F,r.style.maxWidth=F,r.style.boxSizing="border-box"}}},Aw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Mg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Mg(n,o)},destroy(){n.remove()}}},Sw=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),l=n.createElement("div"),u=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),u.appendChild(e);let w=null,g=()=>{w?.disconnect(),w=null},v=null,C=()=>{v=t?.launcher?.detachedPanel===!0?xw(t):null};C();let T=()=>{Cw(a,l,u,d,c,t,f,v)},B=null,S=()=>{B?.(),B=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(B=oi(()=>{C(),T()}))},k=()=>{g(),vn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{T()}),w.observe(a)))},P=!1,H=()=>{T(),k(),f&&!P&&a.dataset.personaDockMobileFullscreen!=="true"&&(P=!0,bw(a,vn(t)))},F=a.ownerDocument.defaultView,N=()=>{H()};return F?.addEventListener("resize",N),vn(t).reveal==="push"?(l.appendChild(u),l.appendChild(d),a.appendChild(l)):(a.appendChild(u),a.appendChild(d)),H(),S(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let j=z.launcherEnabled?z.open:!0;f!==j&&(f=j,H())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(f=!0),C(),H(),S()},destroy(){F?.removeEventListener("resize",N),B?.(),B=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Lg=(e,t)=>Rt(t)?Sw(e,t):Aw(e,t);var oa={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Pg=.15,Ig=1.5,jc="persona-preview-shell-theme",Tw={load:()=>null,save:()=>{},clear:()=>{}},Mw=["How do I get started?","Pricing & plans","Talk to support"];function Vc(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ew(e){return e==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Wg(e){let t=Ew(e);return`* { box-sizing: border-box; }
|
|
139
|
+
${Te?"background: transparent !important;":""}
|
|
140
|
+
`)}if(!m&&!s){let Et="max-height: -moz-available !important; max-height: stretch !important;",ln=c?"":"padding-top: 1.25em !important;",Ti=c?"":`z-index: ${o.launcher?.zIndex??Yt} !important;`;E.style.cssText+=Et+ln+Ti}_n()},Hc=()=>{t.style.setProperty("--persona-content-max-width",Jo(o,re()))},_u=()=>{if(re())return;let s=Pt(o),c=o.launcher?.sidebarMode??!1;if(s||c||(o.launcher?.fullHeight??!1)||!$)return;let m=t.ownerDocument.defaultView??window,v=o.launcher?.mobileFullscreen??!0,M=o.launcher?.mobileBreakpoint??640;if(v&&m.innerWidth<=M)return;let j=m.innerHeight,F=64,Y=o.launcher?.heightOffset??0,U=Math.max(200,j-F),te=Math.min(640,U);B.style.height=`${Math.max(200,te-Y)}px`};Ic(),Ki(t,o),fa(t,o),ga(t,o),Hc(),ir=()=>{Ic(),_u(),Ki(t,o),fa(t,o),ga(t,o),Hc(),ba?t.style.setProperty("--persona-artifact-welded-outer-radius",ba):t.style.removeProperty("--persona-artifact-welded-outer-radius"),Qt(),ht()};let Ee=[];Ee.push(()=>{d.forEach(s=>s()),l.destroy()}),Ee.push(()=>{document.removeEventListener("keydown",Wu)}),Ee.push(()=>{qs!==null&&clearTimeout(qs)});let Qn=null,Jn=null;Ee.push(()=>{Qn?.(),Qn=null,Jn?.(),Jn=null}),Ys&&Ee.push(()=>{Ys?.disconnect(),Ys=null}),Ee.push(()=>{Js?.(),Js=null,Lc(),ut&&(ut.remove(),ut=null),Be?.element.style.removeProperty("width"),Be?.element.style.removeProperty("maxWidth"),Be?.destroy()}),Pe&&Ee.push(()=>{jt!==null&&(cancelAnimationFrame(jt),jt=null),ot?.destroy(),ot=null,Me?.destroy(),Me=null,mt=null});let lr=null,Ou=()=>{lr&&(lr(),lr=null),o.colorScheme==="auto"&&(lr=Ol(()=>{Ki(t,o)}))};Ou(),Ee.push(()=>{lr&&(lr(),lr=null)}),Ee.push(y);let Ta=o.features?.streamAnimation;if(Ta?.type&&Ta.type!=="none"){let s=Hs(Ta.type,Ta.plugins);s&&(tc(s,t),Ee.push(()=>$h(t)))}let uo=sa(yt),Nu=sa(it),Fu=sa(et),cr=[uo,Nu,Fu];Ee.push(()=>{cr.forEach(s=>s.destroy())});let dr=null,D,pr=null,$u=!1,ju=0,zu=null,Uu=s=>s.reduce((c,f)=>f.role==="user"?c+1:c,0),Vu=s=>{for(let c=s.length-1;c>=0;c--)if(Ri(s[c]))return s[c].id??null;return null},qu=!1,Eb=()=>{qu||o.debug!==!0||(qu=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Ku=!1,Gu=!1,Yu=(s,c)=>{Ku||o.debug!==!0||!c.enabled||c.expose||$u||Gu&&(D.isStreaming()||s.some(Ri)||(Ku=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Yr=s=>{if(!D)return;let c=s??D.getMessages(),f=U=>{U.render([],D,me,c)},m=U=>{cr.forEach(te=>{te!==U&&f(te)})};pr&&(Uu(c)>ju||Vu(c)!==zu)&&(pr=null);let v=Yo(o);Yu(c,v);let M=v.enabled?gm(c):null,j=pr??M,F=pr?"host":"agent";if(j){let U=o.suggestions?.followUps,te=U?.placement??(U?"auto":"composer"),ge=(te==="auto"?re()?"composer":"after-message":te)==="after-message"?Fu:uo;m(ge),ge.render(j,D,me,c,o.suggestionChipsConfig,{source:F,surface:"followUp",variant:U?.variant??"chip",behavior:U?.behavior??"send",overflow:U?.overflow??"wrap",maxItems:U?.maxItems??4,config:o,plugins:a});return}if(c.some(U=>U.role==="user")){cr.forEach(f);return}let Y=o.suggestions?.starters;if(Y){let U=Ds(_r(o),c),te=Y.placement??"auto",ie=te==="auto"?U?"welcome":"composer":te;if(ie==="welcome"&&!U){Eb(),cr.forEach(f);return}let ge=ie==="welcome"?Nu:uo;m(ge),ge.render(Y.items??o.suggestionChips,D,me,c,o.suggestionChipsConfig,{surface:"starter",variant:Y.variant??"card",behavior:Y.behavior??"send",overflow:Y.overflow??"wrap",maxItems:Y.maxItems??4,config:o,plugins:a});return}m(uo),uo.render(o.suggestionChips,D,me,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a})},Xu=()=>{pr&&(pr=null,Yr())},kb=s=>{let c=Array.isArray(s)?[...s]:[];if(!c.length){Xu();return}let f=D?D.getMessages():[];pr=c,$u=!0,ju=Uu(f),zu=Vu(f),Yr(f)},wn=!1,Cn=Bh(),Xr=new Map,ur=new Map,Bo=new Map,Rc=0,Pb=So()!==null,xn=Bg(),An=0,Do=null,fn=!1,Ma=!1,_o=0,Ot=null,fr=null,Wc=!1,Qr=!1,gr=null,Zs=!0,Ea=!1,Jr=null,ka=!1,mr=()=>{ka=!0,Rb()},Bc=null,Lb=4,fo=24,Ib=80,Hb=1e3,go=null,Qu=()=>{t.setAttribute("data-persona-scrollbar",xc()),xc()!=="on-scroll"&&(go!==null&&clearTimeout(go),go=null,q.removeAttribute("data-persona-scrollbar-visible"))},Rb=()=>{xc()==="on-scroll"&&(q.setAttribute("data-persona-scrollbar-visible",""),go!==null&&clearTimeout(go),go=setTimeout(()=>{go=null,kr(q,fo)&&q.removeAttribute("data-persona-scrollbar-visible")},Hb))};Qu(),Ee.push(()=>{go!==null&&clearTimeout(go)});let Dc=new Map,_e={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ju=o.voiceRecognition?.autoResume??!1,mo=s=>{h.emit("voice:state",{active:_e.active,source:s,timestamp:Date.now()})},Kn=()=>{H(s=>({...s,voiceState:{active:_e.active,timestamp:Date.now(),manuallyDeactivated:_e.manuallyDeactivated}}))},Wb=()=>{if(o.voiceRecognition?.enabled===!1)return;let s=su(k.voiceState),c=!!s.active,f=Number(s.timestamp??0);_e.manuallyDeactivated=!!s.manuallyDeactivated,c&&Date.now()-f<US&&setTimeout(()=>{_e.active||(_e.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?D.toggleVoice().then(()=>{_e.active=D.isVoiceActive(),mo("restore"),D.isVoiceActive()&&ds()}):il("restore"))},1e3)},Bb=()=>D?Jy(D.getMessages()).filter(s=>!s.__skipPersist):[],Pa=null,Zu=(s,c)=>{typeof console<"u"&&console.error(s,c)},La=(s,c)=>{let f=()=>{try{let j=s();return!j||typeof j.then!="function"?null:Promise.resolve(j).catch(F=>{Zu(c,F)})}catch(j){return Zu(c,j),null}},m=Pa,v=m?m.then(()=>f()??void 0):f();if(!v)return;let M=v.finally(()=>{Pa===M&&(Pa=null)});Pa=M};function _c(s){if(!A?.save)return;let f={messages:s?Jy(s):D?Bb():[],metadata:k,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};La(()=>A.save(f),"[AgentWidget] Failed to persist state:")}let Zr=null,ef=()=>E.querySelector("#persona-scroll-container")||q,es=()=>{Zr!==null&&(cancelAnimationFrame(Zr),Zr=null),fn=!1},tf=()=>{Do!==null&&(cancelAnimationFrame(Do),Do=null),Ma=!1,es()},Db=()=>wn&&Nc()&&(vn()!=="anchor-top"||gu()),Oc=()=>{let s=zs()||"Jump to latest",c=Db();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),_o>0?(rr.textContent=String(_o),rr.style.display="",It.setAttribute("aria-label",`${s} (${_o} new)`)):(rr.textContent="",rr.style.display="none",It.setAttribute("aria-label",c?`${s} (response streaming below)`:s))},nf=()=>{_o!==0&&(_o=0,Oc())},_b=()=>{let s=Ot?.spacerHeight??0;return s<=0?kr(q,fo):Wa(s)-q.scrollTop-q.clientHeight<=fo},Nc=()=>Wo()?!xn.isFollowing():!_b(),Fc=()=>!!D&&D.getMessages().length>0,Nt=()=>{if(!wb()||zr()){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==K&&K.appendChild(It),sr();let c=Ao(q)>0&&Nc()&&Fc();c?Oc():nf(),It.style.display=c?"":"none"},ei=()=>{xn.pause()&&(tf(),Nt())},gn=()=>{xn.resume(),nf(),Nt()},Oo=(s=!1)=>{Wo()&&Fc()&&xn.isFollowing()&&(!s&&!wn||(Do!==null&&(cancelAnimationFrame(Do),Do=null),Ma=!0,Do=requestAnimationFrame(()=>{Do=null,Ma=!1,xn.isFollowing()&&Ob(ef(),s?220:140)})))},of=(s,c,f,m=()=>!0)=>{let v=s.scrollTop,M=c(),j=M-v;if(es(),Math.abs(j)<1){fn=!0,s.scrollTop=M,An=s.scrollTop,fn=!1;return}let F=performance.now();fn=!0;let Y=te=>1-Math.pow(1-te,3),U=te=>{if(!m()){es();return}let ie=c();ie!==M&&(M=ie,j=M-v);let ge=te-F,Ve=Math.min(ge/f,1),gt=Y(Ve),Ut=v+j*gt;s.scrollTop=Ut,An=s.scrollTop,Ve<1?Zr=requestAnimationFrame(U):(s.scrollTop=M,An=s.scrollTop,Zr=null,fn=!1)};Zr=requestAnimationFrame(U)},Ob=(s,c=500)=>{let f=Ao(s)-s.scrollTop;if(Math.abs(f)<1){An=s.scrollTop;return}if(Math.abs(f)>=Ib){es(),fn=!0,s.scrollTop=Ao(s),An=s.scrollTop,fn=!1;return}of(s,()=>Ao(s),c,()=>xn.isFollowing())},Ia=()=>{if(!Fc()){Nt();return}let s=ef();fn=!0,s.scrollTop=Ao(s),An=s.scrollTop,fn=!1,Nt()},hr=s=>{let c=0,f=s;for(;f&&f!==q;)c+=f.offsetTop,f=f.offsetParent;return c},Nb=()=>{let s=q.getRootNode();return(typeof s.getSelection=="function"?s.getSelection():null)??q.ownerDocument.getSelection()},Ha=()=>Og(Nb(),q),$c=()=>{if(Cb()!=="last-user-turn")return!1;let s=D?.getMessages()??[];if(s.length<2)return!1;let c=[...s].reverse().find(M=>M.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),m=q.querySelector(`[data-message-id="${f}"]`);if(!m)return!1;let v=Math.min(Math.max(0,hr(m)-Us()),Ao(q));return fn=!0,q.scrollTop=v,An=q.scrollTop,fn=!1,vn()==="follow"&&!kr(q,fo)&&xn.pause(),Nt(),!0},Ra=s=>{let c=Math.max(0,Math.round(s));In.style.height=`${c}px`,In.style.display=c>0?"":"none",Ot&&(Ot.spacerHeight=Math.max(0,s))},Wa=s=>{let c=parseFloat(getComputedStyle(q).paddingBottom)||0,f=0;for(let v of Array.from(q.children)){if(v===In||v.offsetHeight===0)continue;let M=hr(v)+v.offsetHeight;M>f&&(f=M)}let m=q.scrollHeight-s;return f>0?Math.min(f+c,m):m},Fb=()=>{if(!Ot||Ot.spacerHeight<=0)return;let s=Wa(Ot.spacerHeight),c=Math.max(0,Math.round(q.scrollTop)+q.clientHeight-s+fo);c<Ot.spacerHeight&&(Ra(c),Nt())},Gn=()=>{fr!==null&&(cancelAnimationFrame(fr),fr=null),es(),Ot=null,In.style.height="0px",In.style.display="none"},rf=s=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),jc=s=>q.querySelector(`[data-message-id="${rf(s)}"]`),sf=s=>{fr!==null&&cancelAnimationFrame(fr),fr=requestAnimationFrame(()=>{fr=null;let c=rf(s),f=q.querySelector(`[data-message-id="${c}"]`);if(!f)return;let m=hr(f),v=Ot?.spacerHeight??0,M=Wa(v),{targetScrollTop:j,spacerHeight:F}=Nd({anchorOffsetTop:m,topOffset:Us(),viewportHeight:q.clientHeight,contentHeight:M,slack:fo});Ot={initialSpacerHeight:F,contentHeightAtAnchor:M,spacerHeight:F},Ra(F),of(q,()=>f.isConnected?Math.max(0,hr(f)-Us()):j,220)})},ho=()=>{if(vn()!=="anchor-top"||!Ot||!Jr)return;let s=jc(Jr);if(!s)return;es();let c=Ot.spacerHeight,f=Wa(c),{targetScrollTop:m,spacerHeight:v}=Nd({anchorOffsetTop:hr(s),topOffset:Us(),viewportHeight:q.clientHeight,contentHeight:f,slack:fo});Ot={initialSpacerHeight:v,contentHeightAtAnchor:f,spacerHeight:v},Ra(v),fn=!0,q.scrollTop=m,An=q.scrollTop,fn=!1,Nt()},$b=()=>{if(Wo()){if(!xn.isFollowing()||kr(q,1))return;Oo(!wn);return}if(Ot&&Ot.initialSpacerHeight>0){let s=q.scrollHeight-Ot.spacerHeight,c=Ng({initialSpacerHeight:Ot.initialSpacerHeight,contentHeightAtAnchor:Ot.contentHeightAtAnchor,currentContentHeight:s});c!==Ot.spacerHeight&&Ra(c)}Nt()},jb=s=>{let c=vn();c==="follow"?(gn(),Oo(!0)):c==="anchor-top"&&(Zs=!1,Ea=!0,ka=!1,Jr=s,sf(s))},zb=()=>{if(vn()==="anchor-top"){if(Ea){Zs=!1;return}Zs=!0,Gn(),gn(),Oo(!0)}},Ub=96,Vb=s=>{if(gr===null)return!0;let c=jc(gr),f=jc(s);if(!c||!f)return!0;let m=hr(f)-hr(c);return Us()+m>q.clientHeight-Ub},qb=s=>{if(vn()!=="anchor-top"||!Ea||ka||Ha())return;let c=gr===null;for(let f of s){if(!c){f.id===gr&&(c=!0);continue}if(Wg(f)){if(f.id===Jr||!Vb(f.id))return;Jr=f.id,sf(f.id);return}}},Kb=s=>{let c=new Map;s.forEach(f=>{let m=Dc.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!m&&f.role==="assistant"&&(h.emit("assistant:message",f),!Qr&&(vn()!=="anchor-top"||gu())&&Nc()&&(_o+=1,Oc(),Nt(),hu(_o===1?"1 new message below.":`${_o} new messages below.`))),f.role==="assistant"&&m?.streaming&&f.streaming===!1&&h.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(m?f.approval.status!=="pending"&&h.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):h.emit("approval:requested",{approval:f.approval,message:f}))}),Dc.clear(),c.forEach((f,m)=>{Dc.set(m,f)})},Ba=(s,c)=>{let f=c==="user"?"user":"assistant",m=o.layout?.messages?.[f],v=m?.width??"content",M=m?.maxWidth??(v==="full"?"100%":"85%");s.classList.add("persona-message-row"),s.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),s.classList.add(`persona-message-row-${c}`,`persona-message-width-${v}`),s.classList.toggle("persona-justify-end",c==="user"),s.setAttribute("data-message-role",c),s.setAttribute("data-message-width",v),s.style.setProperty("--persona-message-row-max-width",M)},yr=(s,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${s}`,f.setAttribute("data-wrapper-id",s),Ba(f,c),f},Gb=(s,c,f)=>{let m=document.createElement("div"),M=(()=>{let _=a.find(ke=>ke.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),j=(_,ke)=>ke==null?!1:typeof ke=="string"?(_.textContent=ke,!0):(_.appendChild(ke),!0),F=new Set,Y=new Map,U=new Set,te=a.some(_=>_.renderAskUserQuestion),ie=[],ge=[],Ve=o.enableComponentStreaming!==!1,gt=o.approval!==!1,Ut=[];if(c.forEach(_=>{F.add(_.id),Y.set(_.id,_.role);let ke=te&&Pr(_),Le=gt&&_.variant==="approval"&&!!_.approval,Ae=!ke&&_.role==="assistant"&&!_.variant&&Ve&&ru(_);!Le&&Bo.has(_.id)&&(s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Bo.delete(_.id)),!Ae&&ur.has(_.id)&&(s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),ur.delete(_.id));let At=Pr(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",at=Wh(_,Rc)+At,Vt=ke||Le||Ae?null:Dh(Cn,_.id,at);if(Vt){m.appendChild(Vt.cloneNode(!0)),Pr(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(U.add(_.toolCall.id),Cl(_,o,Q.composerOverlay));return}let st=null,sn=a.find(Ie=>!!(_.variant==="reasoning"&&Ie.renderReasoning||_.variant==="tool"&&Ie.renderToolCall||!_.variant&&Ie.renderMessage)),Kt=o.layout?.messages;if(Pr(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){Xr.delete(_.id),s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ri(_)&&Yo(o).enabled)return;if(Pr(_)&&o.features?.askUserQuestion?.enabled!==!1){let Ie=a.find(an=>typeof an.renderAskUserQuestion=="function");if(Ie&&tt.current){let an=Xr.get(_.id),$t=an!==at,Te=null;if($t){let{payload:$e,complete:Rt}=ys(_),Mt=_.id,Zt=()=>tt.current?.getMessages().find(_n=>_n.id===Mt);Te=Ie.renderAskUserQuestion({message:_,payload:$e,complete:Rt,resolve:_n=>{let je=Zt();je&&tt.current?.resolveAskUserQuestion(je,_n)},dismiss:()=>{let _n=Zt();_n?.agentMetadata?.awaitingLocalTool&&(tt.current?.markAskUserQuestionResolved(_n),tt.current?.resolveAskUserQuestion(_n,"(dismissed)"))},config:o})}let Ht=an!=null;if($t&&Te===null&&!Ht){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(U.add(_.toolCall.id),Cl(_,o,Q.composerOverlay));return}let lt=yr(_.id,_.role);lt.setAttribute("data-ask-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),m.appendChild(lt),ie.push({messageId:_.id,fingerprint:at,bubble:Te});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(U.add(_.toolCall.id),Cl(_,o,Q.composerOverlay));return}}else if(Le){let Ie=a.find(Ht=>typeof Ht.renderApproval=="function")??g,$t=Bo.get(_.id)!==at,Te=null;if($t&&Ie?.renderApproval){let Ht=_.id,lt=($e,Rt)=>{let Mt=tt.current?.getMessages().find(Zt=>Zt.id===Ht);Mt?.approval&&(Mt.approval.toolType==="webmcp"?tt.current?.resolveWebMcpApproval(Mt.id,$e):tt.current?.resolveApproval(Mt.approval,$e,Rt))};Te=Ie.renderApproval({message:_,defaultRenderer:()=>mc(_,o),config:o,approve:$e=>lt("approved",$e),deny:$e=>lt("denied",$e)})}if($t&&Te===null)s.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Bo.delete(_.id),st=mc(_,o);else{let Ht=yr(_.id,_.role);Ht.setAttribute("data-approval-plugin-stub","true"),Ht.setAttribute("data-preserve-runtime","true"),m.appendChild(Ht),Ut.push({messageId:_.id,fingerprint:at,bubble:Te});return}}else if(sn)if(_.variant==="reasoning"&&_.reasoning&&sn.renderReasoning){if(!ve)return;st=sn.renderReasoning({message:_,defaultRenderer:()=>Np(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&sn.renderToolCall){if(!xe)return;st=sn.renderToolCall({message:_,defaultRenderer:()=>$p(_,o),config:o})}else sn.renderMessage&&(st=sn.renderMessage({message:_,defaultRenderer:()=>{let Ie=Lp(_,f,Kt,o.messageActions,O,{loadingIndicatorRenderer:M,widgetConfig:o});return _.role!=="user"&&Yp(Ie,_,o,D),Ie},config:o}));if(!st&&Ae){let Ie=Yy(_);if(Ie){let an=ur.get(_.id),$t=an!==at,Te=o.wrapComponentDirectiveInBubble!==!1&&Po.getOptions(Ie.component)?.bubbleChrome!==!1,Ht=null;if($t){let lt=Ky(Ie,{config:o,message:_,transform:f});if(lt&&Ie.component==="PersonaArtifactInline"){let $e=lt.hasAttribute("data-artifact-inline")?lt:lt.querySelector("[data-artifact-inline]"),Rt=$e?.getAttribute("data-artifact-inline")??"",Mt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Rt):Rt,Zt=Rt?s.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${Mt}"]`)??null:null;$e&&Zt&&Zt!==$e&&Ph(Zt)&&($e===lt?lt=Zt:$e.replaceWith(Zt))}if(lt)if(Te){let $e=document.createElement("div");if($e.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$e.id=`bubble-${_.id}`,$e.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let Rt=document.createElement("div");Rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rt.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),$e.appendChild(Rt)}$e.appendChild(lt),Ht=$e}else{let $e=document.createElement("div");if($e.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$e.id=`bubble-${_.id}`,$e.setAttribute("data-message-id",_.id),$e.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let Rt=document.createElement("div");Rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rt.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),$e.appendChild(Rt)}$e.appendChild(lt),Ht=$e}}if(Ht||an!=null){let lt=yr(_.id,_.role);lt.setAttribute("data-component-directive-stub","true"),lt.setAttribute("data-preserve-runtime","true"),m.appendChild(lt),ge.push({messageId:_.id,fingerprint:at,bubble:Ht});return}}}if(!st)if(_.variant==="reasoning"&&_.reasoning){if(!ve)return;st=Np(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!xe)return;st=$p(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;st=mc(_,o)}else{let Ie=o.layout?.messages;Ie?.renderUserMessage&&_.role==="user"?st=Ie.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):Ie?.renderAssistantMessage&&_.role==="assistant"?st=Ie.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):st=Lp(_,f,Ie,o.messageActions,O,{loadingIndicatorRenderer:M,widgetConfig:o}),_.role!=="user"&&st&&Yp(st,_,o,D)}let Ft=yr(_.id,_.role);Ft.appendChild(st),_h(Cn,_.id,at,Ft),m.appendChild(Ft)}),Q.composerOverlay&&Q.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let Le=ke.getAttribute("data-persona-ask-sheet-for");Le&&!U.has(Le)&&vs(Q.composerOverlay,Le)}),o.features?.toolCallDisplay?.grouped){let _=[],ke=[],Le=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&xe){ke.push(Ae);return}Ae.variant==="reasoning"&&!ve||((ke.length>1||Le&&ke.length>0)&&_.push(ke),ke=[])}),(ke.length>1||Le&&ke.length>0)&&_.push(ke),_.forEach(Ae=>{let At=Ae.map(Ie=>Array.from(m.children).find(an=>an instanceof HTMLElement&&an.getAttribute("data-wrapper-id")===Ie.id)).filter(Ie=>!!Ie);if(At.length<(Le?1:2))return;let at=yr(`tool-group-${Ae[0].id}`,"assistant");at.setAttribute("data-persona-tool-group-row","true");let Vt=document.createElement("div");Vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Vt.setAttribute("data-persona-tool-group","true");let st=document.createElement("div");st.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",st.id=`tool-group-summary-${Ae[0].id}`;let sn=`Called ${Ae.length} ${Ae.length===1?"tool":"tools"}`,Kt=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Ie=>Ie.toolCall).filter(Ie=>!!Ie),defaultSummary:sn,config:o});j(st,Kt)||(st.textContent=sn);let Ft=document.createElement("div");Ft.className="persona-tool-group-stack persona-flex persona-flex-col",Ft.id=`tool-group-stack-${Ae[0].id}`,Ft.setAttribute("data-persona-tool-group-stack","true"),Vt.appendChild(st),Le||Vt.appendChild(Ft),at.appendChild(Vt),At[0].before(at),At.forEach((Ie,an)=>{if(Le){Ie.remove();return}Ie.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),an<At.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Ie),Ft.appendChild($t)})})}Oh(Cn,F);let hn=c.some(_=>_.role==="assistant"&&_.streaming),xt=c[c.length-1],Tt=xt?.role==="assistant"&&!xt.streaming&&xt.variant!=="approval";if(wn&&c.some(_=>_.role==="user")&&!hn&&!Tt){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:la},ke=a.find(Ae=>Ae.renderLoadingIndicator),Le=null;if(ke?.renderLoadingIndicator&&(Le=ke.renderLoadingIndicator(_)),Le===null&&o.loadingIndicator?.render&&(Le=o.loadingIndicator.render(_)),Le===null&&(Le=la()),Le){let Ae=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1,at=o.layout?.messages?.layout??"bubble";Ae.className=At?ca("assistant",at).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ae.setAttribute("data-typing-indicator","true"),At&&(Ae.style.color="var(--persona-message-assistant-text, var(--persona-text))",at!=="flat"&&(Ae.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ae.appendChild(Le);let Vt=yr("typing-indicator","assistant");Vt.appendChild(Ae),m.appendChild(Vt)}}if(!wn&&c.length>0){let _=c[c.length-1],ke={config:o,lastMessage:_,messageCount:c.length},Le=a.find(At=>At.renderIdleIndicator),Ae=null;if(Le?.renderIdleIndicator&&(Ae=Le.renderIdleIndicator(ke)),Ae===null&&o.loadingIndicator?.renderIdle&&(Ae=o.loadingIndicator.renderIdle(ke)),Ae){let At=document.createElement("div"),at=o.loadingIndicator?.showBubble!==!1;At.className=at?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Ae);let Vt=yr("idle-indicator","assistant");Vt.appendChild(At),m.appendChild(Vt)}}if(Kg(m),Ql(s,m),zd(s),ie.length>0)for(let{messageId:_,fingerprint:ke,bubble:Le}of ie){let Ae=s.querySelector(`#wrapper-${_}`);Ae&&(Ba(Ae,Y.get(_)??"assistant"),Le!==null&&(Ae.replaceChildren(Le),Ae.setAttribute("data-bubble-fp",ke),Xr.set(_,ke)))}if(Xr.size>0)for(let _ of Xr.keys())F.has(_)||Xr.delete(_);if(ge.length>0)for(let{messageId:_,fingerprint:ke,bubble:Le}of ge){let Ae=s.querySelector(`#wrapper-${_}`);Ae&&(Ba(Ae,Y.get(_)??"assistant"),Le!==null&&(Ae.replaceChildren(Le),Ae.setAttribute("data-bubble-fp",ke),ur.set(_,ke)))}if(ur.size>0)for(let _ of ur.keys())F.has(_)||ur.delete(_);if(Ut.length>0)for(let{messageId:_,fingerprint:ke,bubble:Le}of Ut){let Ae=s.querySelector(`#wrapper-${_}`);Ae&&(Ba(Ae,Y.get(_)??"assistant"),Le!==null&&(Ae.replaceChildren(Le),Ae.setAttribute("data-bubble-fp",ke),Bo.set(_,ke)))}if(Bo.size>0)for(let _ of Bo.keys())F.has(_)||Bo.delete(_)},ti=(s,c,f)=>{Gb(s,c,f),Iu()},ni=null,Yb=()=>{if(ni)return;let s=f=>{let m=f.composedPath();m.includes(E)||G&&m.includes(G)||rt(!1,"user")};ni=s,(t.ownerDocument??document).addEventListener("pointerdown",s,!0)},af=()=>{if(!ni)return;(t.ownerDocument??document).removeEventListener("pointerdown",ni,!0),ni=null};Ee.push(()=>af());let oi=null,Xb=()=>{if(oi)return;let s=f=>{f.key==="Escape"&&(f.isComposing||rt(!1,"user"))};oi=s,(t.ownerDocument??document).addEventListener("keydown",s,!0)},lf=()=>{if(!oi)return;(t.ownerDocument??document).removeEventListener("keydown",oi,!0),oi=null};Ee.push(()=>lf());let ri=!1,cf=new Set,Qb=()=>{let s=o.launcher?.composerBar?.peek?.streamAnimation;return s||o.features?.streamAnimation},ts=()=>{if(!re())return;let s=Q.peekBanner,c=Q.peekTextNode;if(!s||!c)return;if(T){s.classList.remove("persona-pill-peek--visible");return}let f=D?.getMessages()??[],m;for(let xt=f.length-1;xt>=0;xt--){let Tt=f[xt];if(Tt.role==="assistant"&&Tt.content){m=Tt;break}}if(!m){s.classList.remove("persona-pill-peek--visible");return}let v=m.content,M=!!m.streaming,j=Qb(),F=Jl(j),Y=F.type!=="none"?Hs(F.type,j?.plugins):null,U=Y?.isAnimating?.(m)===!0,te=Y!==null&&(M||U);te&&Y&&!cf.has(Y.name)&&(tc(Y,t),cf.add(Y.name));let ie=te&&Y?.containerClass?Y.containerClass:null,ge=c.dataset.personaPeekStreamClass??null;ge&&ge!==ie&&(c.classList.remove(ge),delete c.dataset.personaPeekStreamClass),ie&&ge!==ie&&(c.classList.add(ie),c.dataset.personaPeekStreamClass=ie),te?(c.style.setProperty("--persona-stream-step",`${F.speed}ms`),c.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Ve=te?Zl(v,F.buffer,Y,m,M):v;if(te&&F.placeholder==="skeleton"&&M&&(!Ve||!Ve.trim())){let xt=document.createElement("div"),Tt=ta();Tt.classList.add("persona-pill-peek__skeleton"),xt.appendChild(Tt),Ql(c,xt)}else{let xt=Math.max(0,Ve.length-100),Tt=Ve.length>100?Ve.slice(-100):Ve,_=Vo(Tt);if(!te||!Y){let ke=Ve.length>100?`\u2026${Tt}`:Tt;c.textContent!==ke&&(c.textContent=ke)}else{let ke=_;(Y.wrap==="char"||Y.wrap==="word")&&(ke=ea(_,Y.wrap,`peek-${m.id}`,{skipTags:Y.skipTags,startIndex:xt}));let Le=document.createElement("div");if(Le.innerHTML=ke,Y.useCaret&&Tt.length>0){let Ae=ec(),At=Le.querySelectorAll(".persona-stream-char, .persona-stream-word"),at=At[At.length-1];at?.parentNode?at.parentNode.insertBefore(Ae,at.nextSibling):Le.appendChild(Ae)}Ql(c,Le),Y.onAfterRender?.({container:c,bubble:s,messageId:m.id,message:m,speed:F.speed,duration:F.duration})}}let hn=wn||ri;s.classList.toggle("persona-pill-peek--visible",hn)};if(re()){let s=Q.peekBanner;if(s){let m=v=>{v.preventDefault(),v.stopPropagation(),rt(!0,"user")};s.addEventListener("pointerdown",m),Ee.push(()=>{s.removeEventListener("pointerdown",m)})}let c=()=>{ri||(ri=!0,ts())},f=()=>{ri&&(ri=!1,ts())};B.addEventListener("pointerenter",c),B.addEventListener("pointerleave",f),Ee.push(()=>{B.removeEventListener("pointerenter",c),B.removeEventListener("pointerleave",f)}),G&&(G.addEventListener("pointerenter",c),G.addEventListener("pointerleave",f),Ee.push(()=>{G.removeEventListener("pointerenter",c),G.removeEventListener("pointerleave",f)}))}let Jb=s=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",m=c.bottomOffset??"16px",v=c.collapsedMaxWidth,M=c.expandedMaxWidth??"880px",j=c.expandedTopOffset??"5vh",F=c.modalMaxWidth??"880px",Y=c.modalMaxHeight??"min(90vh, 800px)",U="calc(100vw - 32px)",te="var(--persona-pill-area-height, 80px)",ie=E.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",G){let ge=G.style;ge.bottom=m,ge.width=v??""}if(s&&f!=="fullscreen"){if(f==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=F,ie.maxWidth=U,ie.maxHeight=Y,ie.height=Y;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${m} + ${te})`,ie.top=j,ie.width=M,ie.maxWidth=U}},si=()=>{if(!ae())return;if(re()){let U=(o.launcher?.composerBar??{}).expandedSize??"anchored",te=T?"expanded":"collapsed";E.dataset.state=te,E.dataset.expandedSize=U,G&&(G.dataset.state=te,G.dataset.expandedSize=U),E.style.removeProperty("display"),E.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Jb(T),K.style.display=T?"flex":"none",ir(),T?(Yb(),Xb()):(af(),lf()),ts();return}let s=Pt(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,m=o.launcher?.mobileFullscreen??!0,v=c.innerWidth<=f,M=m&&v&&$,j=$n(o).reveal;T?(E.style.removeProperty("display"),E.style.display=s?"flex":"",E.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-95","persona-opacity-0"),B.classList.add("persona-scale-100","persona-opacity-100"),wt?(wt.setPanelOpen(!0),wt.element.style.display="none"):rn&&(rn.style.display="none")):(s?s&&(j==="overlay"||j==="push")&&!M?(E.style.removeProperty("display"),E.style.display="flex",E.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(E.style.setProperty("display","none","important"),E.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(E.style.display="",E.classList.add("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-100","persona-opacity-100"),B.classList.add("persona-scale-95","persona-opacity-0")),wt?(wt.setPanelOpen(!1),wt.element.style.display=s?"none":""):rn&&(rn.style.display=s?"none":""))},rt=(s,c="user")=>{if(!ae()||T===s)return;let f=T;T=s,si();let m=(()=>{let M=o.launcher?.sidebarMode??!1,j=t.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,U=j.innerWidth<=Y,te=Pt(o)&&F&&U,ie=re()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return M||F&&U&&$||te||ie})();if(T&&m){if(!Qn){let M=t.getRootNode(),j=M instanceof ShadowRoot?M.host:t.closest(".persona-host");j&&(Qn=xp(j,o.launcher?.zIndex??Yt))}Jn||(Jn=Ap(t.ownerDocument))}else T||(Qn?.(),Qn=null,Jn?.(),Jn=null);T&&(Ai(),$c()||(vn()==="follow"?Oo(!0):Ia()));let v={open:T,source:c,timestamp:Date.now()};T&&!f?h.emit("widget:opened",v):!T&&f&&h.emit("widget:closed",v),h.emit("widget:state",{open:T,launcherEnabled:$,voiceActive:_e.active,streaming:D.isStreaming()})},ii=s=>{uu(s?"stop":"send"),oe&&(oe.disabled=s),cr.forEach(c=>{c.elements.forEach(f=>{f.toggleAttribute("data-disabled",s),f instanceof HTMLButtonElement||f.setAttribute("aria-disabled",s?"true":"false")}),c.buttons.forEach(f=>{f.disabled=s})}),qc.forEach(c=>{c.toggleAttribute("data-disabled",s),c instanceof HTMLButtonElement?c.disabled=s:c.setAttribute("aria-disabled",s?"true":"false"),c.querySelectorAll("button").forEach(f=>{f.disabled=s})}),De.dataset.personaComposerStreaming=s?"true":"false",De.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(c=>{(c instanceof HTMLButtonElement||c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)&&(c.disabled=s)})},br=()=>{_e.active||me&&me.focus()};h.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>br(),200)});let vr=null,ai=!1,zc=!un.hidden,No=null,df=!N,pf=null,uf,ff=null,ns=null,Uc=!1,li=s=>{let c=_r(o),f=`${c.variant}|${c.dismiss}|${c.title}|${c.subtitle}`;(f!==pf||c.icon!==uf)&&(pf=f,uf=c.icon,uc({host:un,iconHolder:fb,title:gb,subtitle:mb,starterSuggestions:it},c));let m=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;m!==ff&&(ff=m,fc(bn,c.message,o));let v=s??(D?D.getMessages():o.initialMessages),M=ai,j=!M&&Ds(c,v),F=j!==zc;if(zc=j,ns){No?.cancel(),No=null,M!==Uc&&(Uc=M,M?Rp(q,un,null):Hp(q,un,ns)),Bs(q,un,!M);return}if(F&&!j&&!M&&c.dismiss==="on-first-message"&&df){No=Zh(un,U=>{No===U&&(No=null),!zc&&!ns&&(Bs(q,un,!1),ho()),U?.cancel()});return}if(No){if(!j&&!M)return;No.cancel(),No=null}let Y=!un.hidden;Bs(q,un,j),!j&&Y&&ho()},Vc=[],qc=[],Kc=!1,gf=null,mf,hf=()=>{qc.length=0;let s=Vc.splice(0,Vc.length);for(let c of s)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};Ee.push(hf);let Zb=(s,c)=>{let f=Tp(s,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),C("span");let m=o.suggestions?.starters,v=Mp({item:{...f,behavior:f.behavior??m?.behavior??"send"},index:c,surface:"starter",source:"config",variant:m?.variant??"card",streaming:u?D.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:D,getTextarea:()=>me,eventTarget:un});return qc.push(v),v},Gc=()=>{if(Kc)return;Kc=!0;let s=_r(o);gf=`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`,mf=s.icon;try{hf(),Rp(q,un,ns),ns=null,Uc=!1;let c=D?D.getMessages():o.initialMessages,f=Ds(s,c),m=0,v=null;for(let M of a)if(M.renderWelcome&&(v=M.renderWelcome({config:s,variant:s.variant,visible:f,defaultRenderer:()=>un,sendMessage:j=>{if(!D||D.isStreaming())return;let F=j.trim();F&&D.sendMessage(F)},requestRender:()=>Gc(),renderStarter:j=>Zb(j,m++),storage:p(M.id),onCleanup:j=>{Vc.push(j)}}),v))break;v&&v!==un&&(ns=v,Hp(q,un,v))}finally{Kc=!1}li()},ev=()=>{let s=_r(o);`${s.variant}|${s.dismiss}|${s.title}|${s.subtitle}|${s.message??""}`===gf&&s.icon===mf||Gc()},Yc=()=>{li(),Ks||(me.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!D?.isStreaming()&&(ye.textContent=o.copy?.sendButtonLabel??"Send")),me.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',me.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},tv=!!o.setStoredConversationId,ci=s=>H(c=>{let f={...c};return delete f[s],f}),Da=s=>{let c=k[s];return typeof c=="string"?c:null};o.clientToken&&(o={...o,getStoredSessionId:()=>Da("sessionId"),setStoredSessionId:s=>{H(c=>({...c,sessionId:s}))},clearStoredSessionId:o.clearStoredSessionId??(()=>ci("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>Da("conversationId")),setStoredConversationId:o.setStoredConversationId??(s=>{H(c=>({...c,conversationId:s}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>ci("conversationId"))});let yf=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,bf=s=>$y(s,We(),o.persistState===!1),vf=yf(),yo=vf?bf(vf):null,wr={...yo?{visitorStore:yo}:{},historyBootstrapReady:P,getStoredMessageCursor:()=>Da("historyMessageCursor"),setStoredMessageCursor:s=>{if(s===null){ci("historyMessageCursor");return}H(c=>({...c,historyMessageCursor:s}))},getPendingDisplayProjections:()=>{let s=k.pendingDisplayProjections;if(!s||typeof s!="object")return null;let c=s;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:s=>{if(!s){ci("pendingDisplayProjections");return}H(c=>({...c,pendingDisplayProjections:s}))},...tv?{}:{getStoredConversationRevision:()=>Da("conversationRevision"),setStoredConversationRevision:s=>{if(s===null){ci("conversationRevision");return}H(c=>({...c,conversationRevision:s}))}}},nv=()=>{let s=yf();if(s&&yo?.matches(s,We(),o.persistState===!1)||!s&&!yo)return;yo?.destroy(),yo=s?bf(s):null;let c={...wr};yo?c.visitorStore=yo:delete c.visitorStore,wr=c,D.setHistoryInternals(wr)},Cr=null,ov=()=>{Cr==null&&(Cr=setInterval(()=>{let s=le.querySelectorAll("[data-tool-elapsed]");if(s.length===0){clearInterval(Cr),Cr=null;return}let c=Date.now();s.forEach(f=>{let m=Number(f.getAttribute("data-tool-elapsed"));m&&(f.textContent=Sl(c-m))})},100))},Xc=(s,c)=>{if(Object.is(s,c))return!0;if(s===null||c===null||typeof s!="object"||typeof c!="object")return!1;if(Array.isArray(s)||Array.isArray(c))return!Array.isArray(s)||!Array.isArray(c)||s.length!==c.length?!1:s.every((j,F)=>Xc(j,c[F]));let f=s,m=c,v=Object.keys(f),M=Object.keys(m);return v.length===M.length&&v.every(j=>Object.prototype.hasOwnProperty.call(m,j)&&Xc(f[j],m[j]))},wf=s=>{let{content:c,rawContent:f,llmContent:m,...v}=s;return v},Qc=s=>s.role==="assistant"&&s.streaming===!0&&!s.variant&&!s.toolCall&&!s.tools&&!s.approval&&!s.reasoning&&!s.contentParts&&!s.stopReason&&!ru(s),rv=(s,c,f)=>{if(s.length!==c.length)return!1;let m=s[f.index],v=c[f.index];return!m||!v||m.id!==f.id||v.id!==f.id?!1:(!Object.is(m.content,v.content)||!Object.is(m.rawContent,v.rawContent)||!Object.is(m.llmContent,v.llmContent))&&Qc(m)&&Qc(v)&&Xc(wf(m),wf(v))},Jc=null,os=null,xr=null,bo=null,_a=s=>{Jc=s;let c,f;os=null;for(let v=s.length-1;v>=0;v-=1){let M=s[v];if(!c&&M.role==="user"&&(c=M),!f&&M.role==="assistant"&&(f=M),!os&&Qc(M)&&(os={index:v,id:M.id}),c&&f&&os)break}ti(le,s,he),hp(le,Vn.artifacts,{suppressTransition:wn}),ov(),li(s),Yr(s),Oo(!wn),Kb(s),s.length===0&&(Gn(),Zs=!0,Ea=!1,Jr=null,ka=!1),!Wc||Qr?(Wc=!0,gr=c?.id??null,Bc=f?.id??null):c&&c.id!==gr?(gr=c.id,jb(c.id)):f&&f.id!==Bc&&zb(),f&&(Bc=f.id),qb(s);let m=_e.lastUserMessageId;c&&c.id!==m&&(_e.lastUserMessageId=c.id,h.emit("user:message",c)),_e.lastUserMessageWasVoice=!!c?.viaVoice,_c(s),ts()},Zc=()=>{bo!==null&&(cancelAnimationFrame(bo),bo=null);let s=xr;xr=null,s&&_a(s)},Cf=()=>{bo!==null&&cancelAnimationFrame(bo),bo=null,xr=null},sv=s=>{let c=xr??Jc;if(wn&&c&&os&&rv(c,s,os)){xr=s,bo===null&&(bo=requestAnimationFrame(()=>{bo=null;let f=xr;xr=null,f&&_a(f)}));return}if(s.length===0){Cf(),_a(s);return}Zc(),_a(s)};D=new Hl(o,{onMessagesChanged(s){sv(s)},onStatusChanged(s){let c=o.statusIndicator??{};x(tn,(m=>m==="idle"?c.idleText??Dt.idle:m==="connecting"?c.connectingText??Dt.connecting:m==="connected"?c.connectedText??Dt.connected:m==="error"?c.errorText??Dt.error:m==="paused"?c.pausedText??Dt.paused:m==="resuming"?c.resumingText??Dt.resuming:Dt[m])(s),c,s),Ho()},onStreamingChanged(s){s||(D?.getMessages().length===0?Cf():Zc()),wn=s,ii(s),Ho(),D&&ti(le,D.getMessages(),he),s||(Oo(!0),Fb(),Gu=!0,D&&Yu(D.getMessages(),Yo(o))),Nt(),hu(s?"Responding\u2026":"Response complete."),ts()},onVoiceStatusChanged(s){if(h.emit("voice:status",{status:s,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(s){case"listening":xo(),ds();break;case"processing":xo(),Qv();break;case"speaking":xo(),Jv();break;default:s==="idle"&&D.isBargeInActive()?(xo(),ds(),oe?.setAttribute("aria-label","End voice session")):(_e.active=!1,xo(),mo("system"),Kn());break}},onArtifactsState(s){Vn=s,s.artifacts.length===0&&(qr=!1),hp(le,s.artifacts,{suppressTransition:wn}),po(),_c()},onHistoryStateChanged(s){io(s)},onHistoryNotice(s){Lt(s)},onReconnect(s){let{executionId:c,lastEventId:f}=s.handle;s.phase==="paused"?h.emit("stream:paused",{executionId:c,after:f}):s.phase==="resuming"?h.emit("stream:resuming",{executionId:c,after:f,attempt:s.attempt??1}):h.emit("stream:resumed",{executionId:c,after:f})}},wr),tt.current=D,Ee.push(()=>D.cancel()),Ee.push(()=>{D.destroy(),yo?.destroy()});let ed=null;if(D.onReadAloudChange((s,c)=>{Pu=s,Lu=c,Iu();let f=s??ed;s&&(ed=s);let m=f?D.getMessages().find(v=>v.id===f)??null:null;h.emit("message:read-aloud",{messageId:f,message:m,state:c,timestamp:Date.now()}),c==="idle"&&(ed=null)}),u=!0,Wc=!0,o.voiceRecognition?.provider?.type==="runtype")try{D.setupVoice()}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",s)}let iv=720,av=250,Fe=Fd(o.features?.history?.copy),Sn=null,td=!1,Ge=null,Oa=null,Na="conversation",nd=null,on=null,Zn=null,Fa=D.getHistoryState(),od=null,$a=0,rd=null,ja=null,za=null,sd=`persona-history-${Math.random().toString(36).slice(2,8)}`,id=()=>o.features?.history?.enabled===!0,eo=()=>id()&&!!Sn&&!td,xf=()=>{let s=D.getStatus();return wn||s==="paused"||s==="resuming"},ad=()=>{let s=o.features?.history?.scope;if(s)return s;let c=o.getIdentityProof?"verified-user":"browser",f=Sn?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},rs=()=>Oa?.scope??ad(),Af=()=>D.getClientSession()?.targetId??null,Sf=s=>`${s.state}:${"reason"in s?s.reason:""}`,lv=s=>{let c=Sf(s);c!==od&&(od=c,h.emit("history:identityStatusChanged",{status:s,timestamp:Date.now()}))},Ua=s=>{s&&(lo.textContent="",lo.textContent=s)},Tf=null,Mf=null,cv=()=>{if(!id())return null;let s=Vy();if(s)return s();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Tf!==c&&(Tf=c,Mf=c()),Mf):D.isClientTokenMode()?qy({client:D.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>D.bindActivatedSession(f),getClient:()=>D.getClient()}):null},Ef=()=>{ja?.(),ja=null,za?.(),za=null,td=!1,Sn=cv();let s={...wr};Sn?s.historyProvider=Sn:delete s.historyProvider,wr=s,D.setHistoryInternals(wr),Sn&&(ja=Sn.subscribeAvailability?.(c=>{td=!c,c||mn({restoreFocus:!1}),$o()})??null,za=Sn.subscribeIdentityStatus(c=>lv(c)),od=Sf(Sn.getIdentityStatus()))},ld=()=>{let s=o.features?.history?.presentation??"panel";if(s==="panel"||s==="auto"&&!(!$||Pt(o)))return"panel";let c=Xn??K;return(c.getBoundingClientRect().width||c.clientWidth)>=iv?"rail":"panel"},Hn=(s,c)=>{c?(s.setAttribute("aria-hidden","true"),s.setAttribute("inert","")):(s.removeAttribute("aria-hidden"),s.removeAttribute("inert"))},Va="data-persona-history-suppressed",Tn=null,Fo=null,Ar=null,di=null,cd=null,kf="",Pf=()=>Se===cd?kf:o.layout?.showHeader===!1?"none":"",dv=()=>Je==="panel"&&!!Ar&&di===Ar.element&&o.layout?.showHeader!==!1&&Pf()!=="none",pv=()=>{for(let s of Array.from(Se.children))s!==Tn&&s.setAttribute(Va,"")},uv=()=>{for(let s of Array.from(K.querySelectorAll(`[${Va}]`)))s.removeAttribute(Va)},fv=()=>{let s=Ar;if(!s)return;if(Array.from(Se.children).some(m=>m!==Tn&&!m.hasAttribute(Va))){Fo&&Fo!==Se&&(Fo.style.removeProperty("min-height"),Fo=null);let m=Se.offsetHeight;m>0&&(Se.style.minHeight=`${m}px`,Fo=Se)}Tn||(Tn=C("div","persona-history-header-host")),s.setHeaderPlacement("external");let f=s.getHeaderElement();f.parentNode!==Tn&&Tn.replaceChildren(f),Tn.parentNode!==Se&&Se.appendChild(Tn),pv()},Lf=()=>{Fo&&(Fo.style.removeProperty("min-height"),Fo=null),Tn&&(Ar?.setHeaderPlacement("inline"),Tn.remove(),Tn=null,uv())},qa=null,dd=()=>{if(qa){if(q.style.display="none",Hn(q,!0),De.hidden=!0,Hn(De,!0),dv()){fv(),Se.style.display=Pf(),Hn(Se,!1);return}Lf(),Se.style.display="none",Hn(Se,!0)}};ht=dd;let gv=s=>{let c=q.style.display,f=De.hidden,m=De,v=Se,M=Se.style.display;cd=v,kf=M,qa=()=>{qa=null,Lf(),cd=null,q.style.display=c,Hn(q,!1),m.hidden=f,Hn(m,!1),De!==m&&(De.hidden=!1,Hn(De,!1)),v.style.display=M,Hn(v,!1),Se!==v&&(Se.style.display=o.layout?.showHeader===!1?"none":"",Hn(Se,!1))},De.parentNode?.insertBefore(s,De),dd()},pi=null,ss=null,ui=null,If=()=>[Se,Q.closeButtonWrapper,Q.clearChatButtonWrapper,q,De],mv=52,Ka=()=>o.features?.history?.rail?.collapsible!==!1,is=()=>o.features?.history?.rail?.side==="right"?"right":"left",pd=200,ud=400,fd=s=>Math.min(ud,Math.max(pd,Math.round(s))),hv=()=>o.features?.history?.rail?.resizable===!0,fi,yv=()=>{if(fi===void 0&&(fi=null,o.persistState!==!1))try{let s=Number(window.localStorage.getItem(`${We()}rail-width`));s&&(fi=s)}catch{}return fi},gi=()=>fd(yv()??o.features?.history?.rail?.width??260),bv=s=>{if(fi=s,o.persistState!==!1)try{window.localStorage.setItem(`${We()}rail-width`,String(s))}catch{}},Ga=()=>Ka()&&o.features?.history?.rail?.collapsedBehavior==="overlay",zt=!1,Hf=s=>{let c=C("img");return c.src=s,c.alt="",c.setAttribute("aria-hidden","true"),c},vv=()=>{let s=o.features?.history?.rail?.brand;if(!s)return;let c=!1,f;return m=>{if(s.render)try{return s.render({collapsed:m})??null}catch(v){return c||(c=!0,console.warn("[persona] history rail brand threw",v)),null}return f===void 0&&(s.iconUrl?f=Hf(s.iconUrl):f=s.icon?ce(s.icon,20):null),f?f.cloneNode(!0):null}},wv=()=>o.features?.history?.rail?.sections?.map(s=>{let c=!1,f=m=>{c||(c=!0,console.warn("[persona] history rail section threw",s.id,m))};return{id:s.id,title:s.title,placement:s.placement??"above-conversations",items:s.items.map(m=>{let v;return{id:m.id,label:m.label,badge:m.badge,iconNode:()=>{if(v!==void 0)return v;try{m.renderIcon?v=m.renderIcon()??null:m.iconUrl?v=Hf(m.iconUrl):v=m.icon?ce(m.icon,20):null}catch(M){f(M),v=null}return v},onSelect:()=>{try{m.onSelect()}catch(M){f(M)}}}})}})??[],Cv=s=>{let c=wv();for(let f of s)c.some(m=>m.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},mi=null,Rf=()=>`${We()}rail-collapsed`,gd=()=>{if(mi===null&&(mi=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let s=window.localStorage.getItem(Rf());s&&(mi=s==="1")}catch{}return mi},md=s=>{if(mi=s,o.persistState!==!1)try{window.localStorage.setItem(Rf(),s?"1":"0")}catch{}},hi=()=>Je==="rail"&&Ka()&&!Ga()&&gd(),hd=()=>{},Wf=()=>{if(Ga()){hd();return}md(!gd()),Ge?.view.setCollapsed(hi()),Qt(),ho()},yd=()=>{let s=o.features?.history?.rail?.collapseShortcut;return!s||!Fl(s)?null:{combo:s,hint:$l(s),aria:Gi(s)}},Bf=()=>{d.forEach(c=>c()),d=[];let s=yd();s&&d.push(l.register({id:"history-rail-collapse",combo:s.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ye&&Je==="rail"&&Ka()||yi(),run:()=>Ga()?hd():Wf()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};Bf();let xv=300,Ya="var(--persona-history-overlay-margin,8px)",Rn=null,vo=null,wo=null,as=null,Sr=!1,bd=0,Df=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,yi=()=>eo()&&Ga()&&(Je??ld())==="rail",Av=()=>Ye&&!zt,bi=()=>{as!==null&&clearTimeout(as),as=null},Sv=()=>{tu().catch(()=>{})},_f=()=>{bi(),zt&&(as=setTimeout(()=>{as=null,!(Sr||!zt)&&(wo?.contains(document.activeElement)||mn({restoreFocus:!1}))},xv))},Tv=(s,c)=>{let f=wo?.getBoundingClientRect();if(!f)return!1;let m=Rn?.getBoundingClientRect(),v=m?Math.min(m.top,f.top):f.top;return s>=f.left&&s<=f.right&&c>=v&&c<=f.bottom||!!m&&s>=m.left&&s<=m.right&&c>=m.top&&c<=m.bottom},vd=s=>{zt&&(Sr=Tv(s.clientX,s.clientY),Sr?bi():as===null&&_f())},Of=s=>{Ye||!yi()||(zt=!0,vi({invoker:Rn,keyboard:s?.keyboard===!0}).then(()=>{Ye?!Sr&&document.activeElement!==Rn&&mn():zt=!1}))},Nf=()=>{let s=di?.querySelector('[data-persona-history-focus="collapse"]');s&&(s.setAttribute("aria-label",zt?Fe.expandLabel:Fe.collapseLabel),s.setAttribute("aria-expanded",zt?"false":"true"))},Ff=()=>{md(!1);let s=Ge;if(!zt||!s){vi({invoker:Rn});return}let c=document.activeElement===Rn;zt=!1,xd(),s.element.remove(),Ad(s.element),Nf(),c&&Qa(),ho(),$o()},Mv=()=>{md(!0),mn()};hd=()=>{!Ye||zt?Ff():Mv()};let Ev=()=>{let s=yd(),c=Br({ariaLabel:Fe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":sd,...s?{"aria-keyshortcuts":s.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Sr=!0,bi(),!(Df()||Date.now()<bd)&&Of()}),f.addEventListener("mouseleave",()=>{Sr=!1,bd=0,_f()}),f.addEventListener("focus",()=>{Ye||Sv()}),f.addEventListener("click",m=>{eo()&&(m.detail!==0&&Df()&&!Ye?Of():Ff())}),Rn=f,vo=c.wrapper},wd=()=>{if(vo&&!vo.isConnected&&(vo=null,Rn=null),!yi()){vo?.remove(),vo=null,Rn=null;return}Rn||Ev();let s=vo,c=Rn;if(!s||!c)return;let f=is()!=="right"?Se.firstChild:null;(f??Se.lastChild)!==s&&Se.insertBefore(s,f),s.style.display=Av()?"none":"",c.setAttribute("aria-label",Fe.expandLabel),c.setAttribute("aria-expanded",Ye?"true":"false"),wo&&Qt()},$f=s=>{if(!zt)return;let c=s.target;c instanceof Node&&(wo?.contains(c)||vo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||mn({restoreFocus:!1}))};document.addEventListener("pointerdown",$f,!0),Ee.push(()=>{document.removeEventListener("pointerdown",$f,!0),document.removeEventListener("pointermove",vd),ls?.(),bi()});let Cd=null,ls=null,jf=16,zf=s=>{bv(fd(s)),Qt(),ho()},kv=()=>{let s=C("div","persona-rail-resizer");return s.tabIndex=0,s.setAttribute("role","separator"),s.setAttribute("aria-orientation","vertical"),s.setAttribute("aria-valuemin",String(pd)),s.setAttribute("aria-valuemax",String(ud)),s.addEventListener("pointerdown",c=>{let f=ss;if(!f||c.button!==0)return;c.preventDefault(),ls?.();let m=c.clientX,v=f.getBoundingClientRect().width||gi(),M=is()==="right"?-1:1,j=v,F=t.ownerDocument;f.style.transition="none";let Y=te=>{j=fd(v+M*(te.clientX-m)),f.style.flex=`0 0 ${j}px`,s.setAttribute("aria-valuenow",String(j))},U=()=>{ls=null,F.removeEventListener("pointermove",Y),F.removeEventListener("pointerup",U),F.removeEventListener("pointercancel",U),f.style.removeProperty("transition");try{s.releasePointerCapture(c.pointerId)}catch{}zf(j)};ls=U,F.addEventListener("pointermove",Y),F.addEventListener("pointerup",U),F.addEventListener("pointercancel",U);try{s.setPointerCapture(c.pointerId)}catch{}}),s.addEventListener("keydown",c=>{let f=is()==="right"?-jf:jf,m=gi(),v=c.key==="ArrowRight"?m+f:c.key==="ArrowLeft"?m-f:c.key==="Home"?pd:c.key==="End"?ud:null;v!==null&&(c.preventDefault(),zf(v))}),s},Pv=(s,c)=>{if(!hv()||hi()){ls?.(),Cd?.remove();return}let f=Cd??kv();Cd=f,f.setAttribute("aria-label",Fe.resizeLabel),f.setAttribute("aria-valuenow",String(gi())),f.nextElementSibling!==c&&s.insertBefore(f,c)};Qt=()=>{Ge?.view.setRailSide(is());let s=is()==="right",c=wo;if(c){let F=Rn?Rn.getBoundingClientRect().bottom-K.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(F))}px + ${Ya})`,c.style.width=`${gi()}px`,c.style.left=s?"":Ya,c.style.right=s?Ya:""}let f=ss,m=pi,v=ui;if(!f||!m||!v)return;f.style.flex=`0 0 ${hi()?mv:gi()}px`;let M="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=s?"":M,f.style.borderLeft=s?M:"";let j=s?v:f;m.firstElementChild!==j&&m.append(j,s?f:v),Pv(m,s?f:v)};let Lv=s=>{let c=C("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=C("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let m=C("div","persona-history-rail-host");m.style.cssText="display:flex;min-height:0;overflow:hidden",K.insertBefore(c,Se.parentNode===K?Se:q);for(let v of If())v?.parentNode===K&&f.appendChild(v);c.append(m,f),m.appendChild(s),pi=c,ss=m,ui=f,Qt()},Iv=s=>{let c=C("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Ya};display:flex;overflow:hidden;z-index:${Ts-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,K.style.position="relative",K.appendChild(c),c.appendChild(s),document.addEventListener("pointermove",vd),wo=c,Qt(),Nf()},xd=()=>{qa?.(),wo&&(Sr&&(bd=Date.now()+150),document.removeEventListener("pointermove",vd),wo.remove(),wo=null);let s=pi;if(s){ls?.();for(let c of If())c&&s.contains(c)&&K.insertBefore(c,s);s.remove(),pi=null,ss=null,ui=null}},Uf=s=>{di=s,s.id=sd,s.style.flex="1 1 auto",s.style.minHeight="0"},Ad=s=>{Uf(s),Je!=="rail"?gv(s):zt?Iv(s):Lv(s)},Xa=()=>{if(wd(),tg(),!Ye||!Ge)return;let s=ld();if(s===Je)return;let c=document.activeElement,f=c instanceof HTMLElement&&(Ge.element.contains(c)||Tn?.contains(c)===!0)?c:null;xd(),Ge.element.remove(),Ge.view.setHeaderPlacement("inline"),Je=s,Ge.view.setPresentation(s),Ge.view.setCollapsed(hi()),Ge.requestRender(),Ge.element.isConnected||Ad(Ge.element),f?.isConnected?f.focus():Qa(),Nt(),ho(),$o()},Vf=(s,c)=>Tn?.querySelector(c)??s.querySelector(c),Qa=()=>{let s=Ge?.element??di;if(!s)return;let c=Vf(s,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=Vf(s,".persona-history-title")??s;f.tabIndex=-1,f.focus()},vi=async s=>{if(!eo()||Ye)return;let c=Sn;if(!c)return;if(!zt&&yi()&&gd()){wd();return}Ja();let f=++$a;Na=s?.returnSurface??"conversation",nd=s?.invoker??on;let m;try{m=await tu()}catch{Ua(Fe.openHistoryLabel);return}if(f!==$a||Ye)return;Oa={scope:ad()},Je=ld(),Ye=!0;let v=Je==="panel"&&o.layout?.showHeader!==!1&&Se.style.display!=="none"?"external":"inline",M=o.features?.history?.rowAvatar,j=yd(),F=j?{hint:j.hint,aria:j.aria}:null,Y={provider:c,context:Oa,targetId:Af(),presentation:Je,collapsible:Ka(),collapsed:hi(),railSide:is(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:vv(),onToggleCollapse:Wf,...F?{collapseShortcut:F}:{},headerPlacement:v,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:M===!1?!1:typeof M=="string"?M:o.launcher?.iconUrl,activeConversationId:D.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:U=>Td(U,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:U=>Tr(U),attachTooltip:Xt,onStartNew:()=>Md({focusComposer:!0}),onClose:()=>mn(),onRequestDeleteConversation:U=>eg(U),onRequestClearHistory:()=>_v(),...c.resetDevice?{onRequestResetIdentity:()=>Ov()}:{}};Ge=Uy({plugins:a,config:o,getPresentation:()=>Je??"panel",getReturnSurface:()=>Na,close:()=>mn(),createView:({slots:U,renderDom:te,onModelChange:ie,railSections:ge})=>(Ar=m.createHistoryView({...Y,railSections:Cv(ge),slots:U,renderDom:te,onModelChange:ie,onAnnounce:Ua}),Ar),onElementChanged:(U,te)=>{if(!te?.isConnected)return Ad(U);Uf(U),te.replaceWith(U),dd()}}),Ge.view.setNewConversationRequired(Fa.recovery==="new_conversation_required"),s?.focus!==!1&&(Je!=="rail"||s?.keyboard===!0)&&Qa(),Nt(),ho(),$o(),h.emit("history:opened",{presentation:Je,returnSurface:Na,timestamp:Date.now()})},Ja=()=>{},mn=s=>{if(!Ye)return;$a+=1;let c=Na,f=nd,m=Ge,v=s?.restoreFocus!==!1;Ye=!1;let M=!1,j=null,F=()=>{if(!M){if(M=!0,Ja=()=>{},j!==null&&clearTimeout(j),zt=!1,bi(),xd(),m?.dispose(),m?.view.destroy(),m?.element.remove(),Ge===m&&(Ge=null,Ar=null,di=null,Je=null,Oa=null,nd=null),Nt(),ho(),$o(),v){let U=f??on;U?.isConnected?U.focus():br()}h.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},Y=m&&m.element===m.view.element?m.view.playExit():null;if(!Y){F();return}Ja=F,j=setTimeout(F,av),Y.then(F)},qf=s=>{if(!(s.key!=="Escape"||!Ye||!Ge)){if(Je==="rail"){let c=s.target;if(!(c instanceof Node)||!(Ge.element.contains(c)||zt&&vo?.contains(c)===!0))return}s.preventDefault(),s.stopPropagation(),mn()}};K.addEventListener("keydown",qf),Ee.push(()=>K.removeEventListener("keydown",qf));let Za=null,Kf=!1,wi=()=>{if(!Ro)return;let s=o.layout?.header?.titleSource==="conversation",c=s&&Za?.trim()||null;Ro.textContent=c??o.launcher?.title??"Chat Assistant";let f=Ro.closest(".persona-combo-btn");if(!f)return;let m=!s||D.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",m?"false":"true"),f.setAttribute("aria-haspopup",m?"true":"false"),m||f.setAttribute("aria-expanded","false"),f.style.cursor=m?"pointer":"default";let v=f.querySelector("svg");v&&(v.style.display=m?"":"none")},Hv=s=>{s!==Za&&(Za=s,wi())},Tr=s=>{Kf=s?.starred===!0,Hv(s&&s.title.trim()||null),wi()};wi(),K.addEventListener("persona:title-menu-builtin",s=>{let c=s.detail?.actionId,f=D.getActiveConversationId();f&&(c==="delete"?eg(f):c==="star"&&D.canUpdateConversations()&&Ed(f,{starred:!Kf}).catch(()=>{}))});let el=0,Rv=250,tl=null,nl=()=>{tl&&clearTimeout(tl),tl=null};Ee.push(nl);let Gf=()=>{nl();let s=vr;s&&(ai=!0,s.hidden=!1,le.style.display="none",li())},ol=()=>{el+=1,nl(),vr&&(vr.remove(),vr=null,ai=!1,le.style.removeProperty("display"),Hn(De,!1),li())},Wv=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;le.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Sd=(s,c)=>fe("div",{className:On("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:s}}),Yf=()=>fe("div",{className:"persona-conversation-loading-body"},Sd("58%",!1),Sd("72%",!0),Sd("44%",!1)),Xf=s=>{vr?.remove(),vr=s,s.hidden=!ai,q.insertBefore(s,le),nl(),ai||(tl=setTimeout(Gf,Rv)),Hn(De,!0)},Bv=()=>{let s={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Yf},c=null,f=a.find(m=>m.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(s)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(s)),Xf(fe("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Fe.openConversationLoadingLabel}},c??Yf()))},Dv=s=>{let c=()=>{Td(s,{focusComposer:!0}).catch(()=>{})},f=eo()?()=>{ol(),vi()}:void 0,m=(F,Y)=>{let U=fe("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:F});return U.addEventListener("click",Y),U},v=()=>fe("div",{className:"persona-conversation-loading-error-body"},fe("p",{className:"persona-conversation-loading-error-title",text:Fe.openConversationErrorTitle}),fe("div",{className:"persona-conversation-loading-error-actions"},m(Fe.openConversationRetryLabel,c),f?m(Fe.openConversationBackLabel,f):null)),M=Object.freeze({conversationId:s,config:o,copy:Object.freeze({title:Fe.openConversationErrorTitle,retryLabel:Fe.openConversationRetryLabel,backLabel:Fe.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:v}),j=null;for(let F of a)if(F.renderHistoryOpenError){try{j=F.renderHistoryOpenError(M)}catch(Y){console.warn("[persona] renderHistoryOpenError threw",Y),j=null}if(j)break}Xf(fe("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},j??v())),Gf()};h.on("history:closed",()=>{vr&&Hn(De,!0)});let Td=async(s,{focusComposer:c=!1}={})=>{let f=rs(),m=!!Ge;Ge?.view.setActiveConversationId(s),ol();let v=el;Bv(),Ye&&(Je==="panel"||zt)&&mn({restoreFocus:!1}),Qr=!0;try{await D.openConversation(s,{scope:f})}catch(M){throw v===el&&Dv(s),M}finally{Qr=!1}v===el&&(ol(),Cn.clear(),Gn(),gn(),$c()||Ia(),Wv(),Co(),m||Tr(null),h.emit("history:conversationOpened",{conversationId:s,title:Za,scope:f,timestamp:Date.now()}),c&&br())},Md=async({focusComposer:s=!1}={})=>{ol(),await D.startNewConversation({scope:rs()}),Tr(null),Cn.clear(),Gn(),gn(),Ia(),Co();let c=D.getActiveConversationId();Ge?.view.setActiveConversationId(c),h.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Ye&&(Je==="panel"||zt)&&mn({restoreFocus:!1}),s&&br()},Ed=async(s,c)=>{let f=await D.updateConversation(s,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Ge?.view.applyConversationSummary(f),!Ge&&s===D.getActiveConversationId()&&Tr(f),f},Qf=async s=>{let c=rs(),f=D.getActiveConversationId()===s;await D.deleteConversation(s,{scope:c}),Ge?.view.removeConversationSummary(s),f&&(Tr(null),Cn.clear(),Gn(),gn(),Co()),h.emit("history:conversationDeleted",{conversationId:s,scope:c,wasActive:f,timestamp:Date.now()})},Jf=async s=>{let c=s?.scope??rs(),f=s?.allTargets?null:s?.targetId??Af(),m=await D.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Tr(null),Cn.clear(),Gn(),gn(),Co(),h.emit("history:cleared",{deleted:m.deleted,scope:c,targetId:f,timestamp:Date.now()}),m},Zf=async()=>{if(!Sn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let s=!1;try{s=(await D.resetHistoryDevice()).remoteRevocationConfirmed}finally{Tr(null),D.clearArtifacts(),Cn.clear(),Jc=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),k={},ne.syncFromMetadata(),A?.clear&&La(()=>A.clear(),"[AgentWidget] Failed to clear storage adapter:"),Gn(),gn(),Co(),mn({restoreFocus:!1}),br(),T||wt?.launcher.element.focus()}return Ua(s?Fe.identityResetNotice:Fe.identityResetUnconfirmedNotice),h.emit("history:identityReset",{remoteRevocationConfirmed:s,timestamp:Date.now()}),{remoteRevocationConfirmed:s}},kd=()=>Xn?B:K,eg=async s=>await vc({host:kd(),title:Fe.deleteConversationConfirmTitle,description:Fe.deleteConversationConfirm,confirmLabel:Fe.deleteConversationConfirmLabel,cancelLabel:Fe.confirmCancelLabel})?(await Qf(s),"deleted"):"cancelled",_v=async()=>{let s=rs()==="verified-user";return await vc({host:kd(),title:Fe.clearHistoryConfirmTitle,description:s?Fe.clearHistoryVerifiedConfirm:Fe.clearHistoryConfirm,confirmLabel:Fe.clearHistoryConfirmLabel,cancelLabel:Fe.confirmCancelLabel})?(await Jf(),"cleared"):"cancelled"},Ov=async()=>{if(!await vc({host:kd(),title:Fe.resetIdentityConfirmTitle,description:Fe.resetIdentityConfirm,confirmLabel:Fe.resetIdentityConfirmLabel,cancelLabel:Fe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Zf();return{outcome:"reset",remoteRevocationConfirmed:c}},Wn=C("button","persona-history-earlier");Wn.type="button",Wn.textContent=Fe.showEarlierMessagesLabel,Wn.setAttribute("data-persona-history-earlier",""),Object.assign(Wn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Co=()=>{if(!(eo()&&!!Fa.nextMessageCursor&&!!D.getActiveConversationId())){Wn.remove();return}Wn.textContent=Fe.showEarlierMessagesLabel,Wn.parentNode!==q&&q.insertBefore(Wn,q.firstChild)};Wn.addEventListener("click",()=>{let s=D.getActiveConversationId(),c=Fa.nextMessageCursor;if(!s||!c||Wn.disabled)return;Wn.disabled=!0;let f=q.scrollHeight,m=q.scrollTop;D.loadOlderMessages(s,c,{scope:rs()}).then(()=>{q.scrollTop=m+(q.scrollHeight-f),ho()}).catch(()=>{}).finally(()=>{Wn.disabled=!1,Co()})});let Nv=()=>{let s=Br({ariaLabel:Fe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return s.button.addEventListener("click",c=>{if(!(!eo()||xf())){if(Ye){mn();return}vi({invoker:s.button,keyboard:c.detail===0})}}),s},tg=()=>{if(!eo()){Zn?.remove(),on=null,Zn=null;return}if(Zn&&!Zn.isConnected&&(on=null,Zn=null),!on&&Se){let m=Nv();on=m.button,Zn=m.wrapper;let v=Q.clearChatButtonWrapper||Q.closeButtonWrapper;v?.parentNode&&Se.contains(v)?v.parentNode.insertBefore(Zn,v):Se.appendChild(Zn)}if(!on||!Zn)return;let s=yi()||Ye&&Je==="rail";if(Zn.style.display=s?"none":"",s){document.activeElement===on&&Qa();return}let c=xf();on.disabled=c,on.setAttribute("aria-disabled",c?"true":"false");let f=c?Fe.openHistoryBusyLabel:Fe.openHistoryLabel;on.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(on.removeAttribute("aria-expanded"),on.removeAttribute("aria-controls")):(on.setAttribute("aria-expanded",Ye?"true":"false"),on.setAttribute("aria-controls",sd))},rl=!1,Fv=()=>{let s=Q.clearChatButton;if(s){if(eo()){rl||(rd=s.getAttribute("aria-label")??"",rl=!0),s.setAttribute("aria-label",Fe.newConversationLabel),s.removeAttribute("title");return}rl&&(rl=!1,rd&&s.setAttribute("aria-label",rd))}},$o=()=>{Fe=Fd(o.features?.history?.copy),tg(),wd(),Fv(),Co()};Ho=$o,io=s=>{Fa=s,Ge?.view.setNewConversationRequired(s.recovery==="new_conversation_required"),ii(s.sendBlocked||wn),Co()},Lt=s=>{(s.code==="history_continuity_reset"||s.code==="conversation_deleted_recovered")&&(Cn.clear(),Gn(),gn()),Ua(s.message),Ge?.view.refresh()},Ef(),$o(),Ee.push(()=>{ja?.(),za?.(),$a+=1,Ja(),Ge?.dispose(),Ge?.view.destroy(),Ge=null}),o.clientToken&&D.initClientSession().then(()=>{if(eo())return D.reconcileBootConversation({scope:ad()})}).then(()=>{Co()}).catch(s=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",s)}),(Me||o.onSSEEvent)&&D.setSSEEventCallback((s,c)=>{o.onSSEEvent?.(s,c),Ke?.processEvent(s,c),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s,timestamp:Date.now(),payload:JSON.stringify(c)})});let ng=()=>{o.resume&&typeof o.reconnectStream=="function"&&D.resumeFromHandle(o.resume)};N?N.then(s=>{if(s){if(s.metadata&&(k=su(s.metadata),ne.syncFromMetadata()),s.messages?.length){Qr=!0;try{D.hydrateMessages(s.messages)}finally{Qr=!1}}s.artifacts?.length&&D.hydrateArtifacts(s.artifacts,s.selectedArtifactId??null)}}).catch(s=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",s)}).finally(()=>{df=!0,I(),ng()}):ng();let og=()=>{!re()||T||!(o.launcher?.composerBar?.expandOnSubmit??!0)||rt(!0,"auto")},$v=(s,c)=>s?c?{refs:[...s.refs,...c.refs],finalize:async()=>{let[f,m]=await Promise.allSettled([s.finalize(),c.finalize()]),v=[];return f.status==="fulfilled"?v.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),m.status==="fulfilled"?v.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),QS(v)}}:s:c,jv=()=>{let c=me.getInlineMessageFields?.();return c&&c.contentSegments.some(m=>m.kind==="mention")?c.contentSegments:void 0},Ci=!1,zv=async s=>{let c=me.value.trim(),f=pt?.hasAttachments()??!1,m=c?await(nn?.takeInlineCommand(c)??Promise.resolve(null)):null;if(m?.kind==="action"){me.value="",me.style.height="auto",xi(),nn?.clear();return}let v=nn?.collectForSubmit()??null,M=m?.kind==="server"?m.mentions:null,j=$v(v,M),F=m?.kind==="prompt"?m.sendText:c,Y=!!v&&v.refs.length>0;if(!F&&!f&&!Y&&!M)return;og();let U;f&&(U=[],U.push(...pt.getContentParts()),F&&U.push(Qo(F)));let te=m?.kind==="prompt"?void 0:jv();me.value="",me.style.height="auto",xi(),D.sendMessage(F,{contentParts:U,mentions:j??void 0,contentSegments:te,viaVoice:s?.viaVoice}),f&&pt.clearAttachments(),v&&nn?.clear()},Pd=async s=>{if(!Ci){Ci=!0;try{await zv(s)}finally{Ci=!1}}},sl=s=>{if(s.preventDefault(),D.isStreaming()){D.cancel(),Ke?.reset(),ot?.update();return}Ci||Pd()},Uv=()=>o.features?.composerHistory!==!1,Ld={...vp},Id=!1,xi=()=>{Ld={...vp}},Vv=()=>D.getMessages().filter(s=>s.role==="user").map(s=>s.content??"").filter(s=>s.length>0),qv=s=>{if(!me)return;Id=!0,me.value=s,me.dispatchEvent(new Event("input",{bubbles:!0})),Id=!1;let c=me.value.length;me.setSelectionRange(c,c)},Kv=s=>{Id||(s.isComposing||nn?.handleInput(s.inputType??void 0),xi())},Gv=s=>{if(me&&!(!s.isComposing&&nn?.handleKeydown(s))){if(Uv()&&(s.key==="ArrowUp"||s.key==="ArrowDown")&&!s.shiftKey&&!s.metaKey&&!s.ctrlKey&&!s.altKey&&!s.isComposing){let c=me.selectionStart===0&&me.selectionEnd===0,f=Rh({direction:s.key==="ArrowUp"?"up":"down",history:Vv(),currentValue:me.value,atStart:c,state:Ld});if(Ld=f.state,f.handled){s.preventDefault(),f.value!==void 0&&qv(f.value);return}}if(s.key==="Enter"&&!s.shiftKey){if(D.isStreaming()){s.preventDefault();return}if(Ci){s.preventDefault();return}xi(),s.preventDefault(),ye.click()}}},rg=s=>{s.key!=="Escape"||s.isComposing||D.isStreaming()&&s.composedPath().includes(K)&&(D.cancel(),Ke?.reset(),ot?.update(),xi(),s.preventDefault(),s.stopImmediatePropagation())},Yv=async s=>{if(o.attachments?.enabled!==!0||!pt)return;let c=KS(s.clipboardData);c.length!==0&&(s.preventDefault(),await pt.handleFiles(c))},Bn=null,to=!1,cs=null,ft=null,sg=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,il=(s="user")=>{if(to||D.isStreaming())return;let c=sg();if(!c)return;Bn=new c;let m=(o.voiceRecognition??{}).pauseDuration??2e3;Bn.continuous=!0,Bn.interimResults=!0,Bn.lang="en-US";let v=me.value;Bn.onresult=M=>{let j="",F="";for(let U=0;U<M.results.length;U++){let te=M.results[U],ie=te[0].transcript;te.isFinal?j+=ie+" ":F=ie}let Y=v+j+F;me.value=Y,cs&&clearTimeout(cs),(j||F)&&(cs=window.setTimeout(()=>{me.value.trim()&&Bn&&to&&(jo(),Pd({viaVoice:!0}))},m))},Bn.onerror=M=>{M.error!=="no-speech"&&jo()},Bn.onend=()=>{if(to){let M=me.value.trim();M&&M!==v.trim()&&Pd({viaVoice:!0}),jo()}};try{if(Bn.start(),to=!0,_e.active=!0,s!=="system"&&(_e.manuallyDeactivated=!1),mo(s),Kn(),oe){let M=o.voiceRecognition??{};ft={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:M.iconName??"mic",iconSize:parseFloat(M.iconSize??o.sendButton?.size??"40")||24};let j=M.recordingBackgroundColor,F=M.recordingIconColor,Y=M.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=j??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let U=oe.querySelector("svg");U&&U.setAttribute("stroke",F)}Y&&(oe.style.borderColor=Y),oe.setAttribute("aria-label","Stop voice recognition")}}catch{jo("system")}},jo=(s="user")=>{if(to){if(to=!1,cs&&(clearTimeout(cs),cs=null),Bn){try{Bn.stop()}catch{}Bn=null}if(_e.active=!1,mo(s),Kn(),oe){if(oe.classList.remove("persona-voice-recording"),ft){oe.style.backgroundColor=ft.backgroundColor,oe.style.color=ft.color,oe.style.borderColor=ft.borderColor;let c=oe.querySelector("svg");c&&c.setAttribute("stroke",ft.color||"currentColor"),ft=null}oe.setAttribute("aria-label","Start voice recognition")}}},Xv=(s,c)=>{let f=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),m=s?.provider?.type==="runtype",v=s?.provider?.type==="custom";if(!(f||m||v))return null;let j=C("div","persona-send-button-wrapper"),F=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button";let Y=s?.tooltipText??"Start voice recognition";F.setAttribute("aria-label",Y);let U=s?.iconName??"mic",te=c?.size??"40px",ie=s?.iconSize??te,ge=parseFloat(ie)||24,Ve=s?.backgroundColor??c?.backgroundColor,gt=s?.iconColor??c?.textColor;F.style.width=ie,F.style.height=ie,F.style.minWidth=ie,F.style.minHeight=ie,F.style.fontSize="18px",F.style.lineHeight="1",gt?F.style.color=gt:F.style.color="var(--persona-text, #111827)";let hn=ce(U,ge,gt||"currentColor",1.5);hn?F.appendChild(hn):F.textContent="\u{1F3A4}",Ve?F.style.backgroundColor=Ve:F.style.backgroundColor="",s?.borderWidth&&(F.style.borderWidth=s.borderWidth,F.style.borderStyle="solid"),s?.borderColor&&(F.style.borderColor=s.borderColor),s?.paddingX&&(F.style.paddingLeft=s.paddingX,F.style.paddingRight=s.paddingX),s?.paddingY&&(F.style.paddingTop=s.paddingY,F.style.paddingBottom=s.paddingY),j.appendChild(F);let xt=s?.showTooltip??!1;return Xt({anchor:F,trigger:j,text:()=>F.getAttribute("aria-label")??Y,enabled:xt}),{micButton:F,micButtonWrapper:j}},Hd=()=>{if(!oe||ft)return;let s=o.voiceRecognition??{};ft={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:s.iconName??"mic",iconSize:parseFloat(s.iconSize??o.sendButton?.size??"40")||24}},Rd=(s,c)=>{if(!oe)return;let f=oe.querySelector("svg");f&&f.remove();let m=ft?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),v=ce(s,m,c,1.5);v&&oe.appendChild(v)},al=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ds=()=>{if(!oe)return;Hd();let s=o.voiceRecognition??{},c=s.recordingBackgroundColor,f=s.recordingIconColor,m=s.recordingBorderColor;if(al(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let v=oe.querySelector("svg");v&&v.setAttribute("stroke",f)}m&&(oe.style.borderColor=m),oe.setAttribute("aria-label","Stop voice recognition")},Qv=()=>{if(!oe)return;Hd();let s=o.voiceRecognition??{},c=D.getVoiceInterruptionMode(),f=s.processingIconName??"loader",m=s.processingIconColor??ft?.color??"",v=s.processingBackgroundColor??ft?.backgroundColor??"",M=s.processingBorderColor??ft?.borderColor??"";al(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=v,oe.style.borderColor=M;let j=m||"currentColor";oe.style.color=j,Rd(f,j),oe.setAttribute("aria-label","Processing voice input"),c==="none"&&(oe.style.cursor="default")},Jv=()=>{if(!oe)return;Hd();let s=o.voiceRecognition??{},c=D.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",m=s.speakingIconName??f,v=s.speakingIconColor??(c==="barge-in"?s.recordingIconColor??ft?.color??"":ft?.color??""),M=s.speakingBackgroundColor??(c==="barge-in"?s.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":ft?.backgroundColor??""),j=s.speakingBorderColor??(c==="barge-in"?s.recordingBorderColor??"":ft?.borderColor??"");al(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=M,oe.style.borderColor=j;let F=v||"currentColor";oe.style.color=F,Rd(m,F);let Y=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",Y),c==="none"&&(oe.style.cursor="default"),c==="barge-in"&&oe.classList.add("persona-voice-recording")},xo=()=>{oe&&(al(),ft&&(oe.style.backgroundColor=ft.backgroundColor??"",oe.style.color=ft.color??"",oe.style.borderColor=ft.borderColor??"",Rd(ft.iconName,ft.color||"currentColor"),ft=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},ps=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let s=D.getVoiceStatus(),c=D.getVoiceInterruptionMode();if(c==="none"&&(s==="processing"||s==="speaking"))return;if(c==="cancel"&&(s==="processing"||s==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{_e.active=!1,_e.manuallyDeactivated=!0,Kn(),mo("user"),xo()});return}D.toggleVoice().then(()=>{_e.active=D.isVoiceActive(),_e.manuallyDeactivated=!D.isVoiceActive(),Kn(),mo("user"),D.isVoiceActive()?ds():xo()});return}if(to){let s=me.value.trim();_e.manuallyDeactivated=!0,Kn(),jo("user"),s&&(me.value="",me.style.height="auto",D.sendMessage(s))}else _e.manuallyDeactivated=!1,Kn(),il("user")};bu=ps,oe&&(oe.addEventListener("click",ps),Ee.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),xo()):jo("system"),oe&&oe.removeEventListener("click",ps)}));let Zv=h.on("assistant:complete",()=>{Ju&&(_e.active||_e.manuallyDeactivated||Ju==="assistant"&&!_e.lastUserMessageWasVoice||setTimeout(()=>{!_e.active&&!_e.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?D.toggleVoice().then(()=>{_e.active=D.isVoiceActive(),mo("auto"),D.isVoiceActive()&&ds()}):il("auto"))},600))});Ee.push(Zv);let ew=h.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});Ee.push(ew);let ig=()=>{rt(!T,"user")},wt=null,rn=null;if($&&!re()){let{instance:s,element:c}=Op({config:o,plugins:a,onToggle:ig});wt=s,s||(rn=c)}wt?t.appendChild(wt.element):rn&&t.appendChild(rn),si(),Yr(),Yc(),Gc(),ii(D.isStreaming()),$c()||(vn()==="follow"?Oo(!0):Ia()),Wb(),ue&&(!$||re()?setTimeout(()=>br(),0):T&&setTimeout(()=>br(),200));let Ai=()=>{if(re()){sr(),si();return}let s=Pt(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,v=o.launcher?.mobileBreakpoint??640,M=f.innerWidth<=v,j=m&&M&&$;try{if(j){ir(),Xs=Sa();return}let F=!1;J&&(J=!1,ir(),F=!0);let Y=Sa();if(!F&&Y!==Xs&&(ir(),F=!0),Xs=Y,F&&Pc(),!$&&!s){B.style.height="",B.style.width="";return}if(!c&&!s){let te=o?.launcher?.width??o?.launcherWidth??ko;B.style.width=te,B.style.maxWidth=te}Aa(),_u()}finally{if(sr(),si(),T&&$){let Y=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),U=o.launcher?.sidebarMode??!1,te=o.launcher?.mobileFullscreen??!0,ie=Pt(o)&&te&&Y,ge=U||te&&Y&&$||ie;if(ge&&!Jn){let Ve=t.getRootNode(),gt=Ve instanceof ShadowRoot?Ve.host:t.closest(".persona-host");gt&&!Qn&&(Qn=xp(gt,o.launcher?.zIndex??Yt)),Jn=Ap(t.ownerDocument)}else ge||(Qn?.(),Qn=null,Jn?.(),Jn=null)}}};Ai();let ll=t.ownerDocument.defaultView??window;if(ll.addEventListener("resize",Ai),Ee.push(()=>ll.removeEventListener("resize",Ai)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{sr()});s.observe(De),Ee.push(()=>s.disconnect());let c=new ResizeObserver(()=>{Xa()});c.observe(K),Ee.push(()=>c.disconnect())}ll.addEventListener("resize",Xa),Ee.push(()=>ll.removeEventListener("resize",Xa)),An=q.scrollTop;let ag=Ao(q),lg=()=>{let s=q.scrollTop,c=Ao(q),f=c<ag;if(ag=c,!Wo()){An=s,Nt();return}let{action:m,nextLastScrollTop:v}=Dg({following:xn.isFollowing(),currentScrollTop:s,lastScrollTop:An,nearBottom:kr(q,fo),userScrollThreshold:Lb,isAutoScrolling:fn||Ma||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=v,m==="resume"){Ha()||gn();return}m==="pause"&&ei()};if(q.addEventListener("scroll",lg,{passive:!0}),Ee.push(()=>q.removeEventListener("scroll",lg)),typeof ResizeObserver<"u"){let s=new ResizeObserver(()=>{$b(),zd(le)});s.observe(le),s.observe(q),Ee.push(()=>s.disconnect())}let cg=()=>{Wo()&&xn.isFollowing()&&Ha()&&ei()},dg=q.ownerDocument;dg.addEventListener("selectionchange",cg),Ee.push(()=>{dg.removeEventListener("selectionchange",cg)});let tw=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),pg=s=>{tw.has(s.key)&&(mr(),fu()&&Wo()&&xn.isFollowing()&&ei())},ug=s=>{s.target?.closest("a, button, [tabindex], input, textarea, select")&&(mr(),fu()&&Wo()&&xn.isFollowing()&&ei())};q.addEventListener("keydown",pg),q.addEventListener("focusin",ug),Ee.push(()=>{q.removeEventListener("keydown",pg),q.removeEventListener("focusin",ug)});let fg=s=>{if(s.deltaY!==0&&mr(),!Wo())return;let c=_g({following:xn.isFollowing(),deltaY:s.deltaY,nearBottom:kr(q,fo),resumeWhenNearBottom:!0});c==="pause"?ei():c==="resume"&&!Ha()&&gn()};q.addEventListener("wheel",fg,{passive:!0}),q.addEventListener("touchmove",mr,{passive:!0}),q.addEventListener("pointerdown",mr,{passive:!0}),Ee.push(()=>{q.removeEventListener("touchmove",mr),q.removeEventListener("pointerdown",mr)}),Ee.push(()=>q.removeEventListener("wheel",fg)),It.addEventListener("click",()=>{Gn(),q.scrollTop=q.scrollHeight,An=q.scrollTop,gn(),Oo(!0),Nt()}),Ee.push(()=>It.remove()),Ee.push(()=>{tf(),Gn()});let gg=()=>{He&&(dr&&(He.removeEventListener("click",dr),dr=null),ae()?(He.style.display="",dr=()=>{rt(!1,"user")},He.addEventListener("click",dr)):He.style.display="none")};gg(),(()=>{let{clearChatButton:s}=Q;s&&s.addEventListener("click",()=>{if(eo()){Md({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}D.clearMessages(),Cn.clear(),gn(),vs(Q.composerOverlay);try{localStorage.removeItem($s),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${$s}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==$s)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),A?.clear&&La(()=>A.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},ne.syncFromMetadata(),Me?.clear(),Ke?.reset(),ot?.update()})})(),Ne&&Ne.addEventListener("submit",sl);let mg=[["keydown",Gv],["input",Kv],["paste",Yv],["focus",xb]],Wd=s=>{if(s)for(let[c,f]of mg)s.addEventListener(c,f)},Bd=s=>{if(s)for(let[c,f]of mg)s.removeEventListener(c,f)};Wd(me);let hg=()=>{nn?.onComposerSwap((s,c)=>{Bd(c),me=s,Wd(s)})};hg();let Dd=!1;function nw(){if(!Dd){Dd=!0;try{let s=me?.value??"",c=De.ownerDocument??document,f=me?c.activeElement===me:!1;Bd(me),Ne?.removeEventListener("submit",sl),oe?.removeEventListener("click",ps),nn?.destroy(),nn=null;let m=null,v=()=>(m=re()?dc({config:o}):aa({config:o}),m.footer),M=xu(v)??v();L.replaceComposer(M),De=L.composer.footer;let j=m!==null&&M===m.footer;Ks=!j,uu=j?m.setSendButtonMode:()=>{},Cu(De),Su(De),Tu(),Mu(),Eu(),hg(),Ne&&Ne.addEventListener("submit",sl),Wd(me),oe?.addEventListener("click",ps);let F=cr.indexOf(uo);uo.destroy(),uo=sa(yt),F>=0&&(cr[F]=uo),me&&(me.value=s),Yc(),Yr(),ii(D.isStreaming()),ir(),sr(),f&&me?.focus()}finally{Dd=!1}}}let yg=t.ownerDocument??document;yg.addEventListener("keydown",rg,!0);let bg="persona-attachment-drop-active",Si=0,_d=()=>{Si=0,K.classList.remove(bg)},us=()=>o.attachments?.enabled===!0&&pt!==null,vg=s=>{!wc(s.dataTransfer)||!us()||(Si++,Si===1&&K.classList.add(bg))},wg=s=>{!wc(s.dataTransfer)||!us()||(Si--,Si<=0&&_d())},Cg=s=>{!wc(s.dataTransfer)||!us()||(s.preventDefault(),s.dataTransfer.dropEffect="copy")},xg=s=>{if(!wc(s.dataTransfer)||!us())return;s.preventDefault(),s.stopPropagation(),_d();let c=Array.from(s.dataTransfer.files??[]);c.length!==0&&pt.handleFiles(c)},zo=!0;K.addEventListener("dragenter",vg,zo),K.addEventListener("dragleave",wg,zo),t.addEventListener("dragover",Cg,zo),t.addEventListener("drop",xg,zo);let cl=t.ownerDocument,Ag=s=>{us()&&s.preventDefault()},Sg=s=>{us()&&s.preventDefault()};cl.addEventListener("dragover",Ag),cl.addEventListener("drop",Sg),Ee.push(()=>{Ne&&Ne.removeEventListener("submit",sl),Bd(me),yg.removeEventListener("keydown",rg,!0),nn?.destroy()}),Ee.push(()=>{K.removeEventListener("dragenter",vg,zo),K.removeEventListener("dragleave",wg,zo),t.removeEventListener("dragover",Cg,zo),t.removeEventListener("drop",xg,zo),cl.removeEventListener("dragover",Ag),cl.removeEventListener("drop",Sg),_d()}),Ee.push(()=>{D.cancel()}),wt?Ee.push(()=>{wt?.destroy()}):rn&&Ee.push(()=>{rn?.remove()});let Ct={update(s){let c=o.toolCall,f=o.messageActions,m=o.layout?.messages,v=o.colorScheme,M=o.loadingIndicator,j=o.iterationDisplay,F=o.features?.showReasoning,Y=o.features?.showToolCalls,U=o.features?.toolCallDisplay,te=o.features?.reasoningDisplay,ie=o.features?.streamAnimation?.type,ge=o.features?.history?.enabled===!0,Ve=o.features?.history?.provider,gt=o.getIdentityProof,Ut=o.clientToken;o=Dy({...o,features:i},s),i=o.features,o=Kp(o),r(),Ic(),Ki(t,o),fa(t,o),ga(t,o),Qt(),po(),o.colorScheme!==v&&Ou();let hn=Qp.getForInstance(o.plugins);a.length=0,a.push(...hn),Bf(),$=o.launcher?.enabled??!0,X=o.launcher?.autoExpand??!1,ve=o.features?.showReasoning??!0,xe=o.features?.showToolCalls??!0,Xe=o.features?.scrollToBottom??{};let xt=vn();Qe=o.features?.scrollBehavior??{},xt!==vn()&&(Gn(),gn()),Qu(),yu(),Nt();let Tt=Pe;if(Pe=o.features?.showEventStreamToggle??!1,Pe&&!Tt){if(Me||(mt=new pa(bt),Me=new da(Pn,mt),Ke=Ke??new ua,mt.open().then(()=>Me?.restore()).catch(()=>{}),D.setSSEEventCallback((se,Oe)=>{o.onSSEEvent?.(se,Oe),Ke?.processEvent(se,Oe),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify(Oe)})})),!Ue&&Se){let se=o.features?.eventStream?.classNames,Oe="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(se?.toggleButton?" "+se.toggleButton:"");Ue=C("button",Oe),Ue.style.width="28px",Ue.style.height="28px",Ue.style.color=dn.actionIconColor,Ue.type="button",Ue.setAttribute("aria-label","Event Stream"),Ue.title="Event Stream";let ze=ce("activity","18px","currentColor",1.5);ze&&Ue.appendChild(ze);let ct=Q.clearChatButtonWrapper,Ze=Q.closeButtonWrapper,Gt=ct||Ze;Gt&&Gt.parentNode===Se?Se.insertBefore(Ue,Gt):Se.appendChild(Ue),Ue.addEventListener("click",()=>{qt?Vr():Sc()})}}else!Pe&&Tt&&(Vr(),Ue&&(Ue.remove(),Ue=null),Me?.clear(),mt?.destroy(),Me=null,mt=null,Ke?.reset(),Ke=null);if(o.launcher?.enabled===!1&&wt&&(wt.destroy(),wt=null),o.launcher?.enabled===!1&&rn&&(rn.remove(),rn=null),o.launcher?.enabled!==!1&&!wt&&!rn){let{instance:se,element:Oe}=Op({config:o,plugins:a,onToggle:ig});wt=se,se||(rn=Oe),t.appendChild(Oe)}wt&&wt.update(o),wi(),or&&o.launcher?.subtitle!==void 0&&(or.textContent=o.launcher.subtitle);let _=o.layout?.header;if(_?.layout!==pe&&Se){let se=_?oc(o,_,{showClose:ae(),onClose:()=>rt(!1,"user")}):Dr({config:o,showClose:ae(),onClose:()=>rt(!1,"user")});L.replaceHeader(se),Se=L.header.element,vt=L.header.iconHolder,Ro=L.header.headerTitle,or=L.header.headerSubtitle,He=L.header.closeButton,pe=_?.layout,wi()}else if(_){if(vt&&(vt.style.display=_.showIcon===!1?"none":""),Ro&&(Ro.style.display=_.showTitle===!1?"none":""),or&&(or.style.display=_.showSubtitle===!1?"none":""),He){let se=ae()&&_.showCloseButton!==!1;He.style.display=se?"":"none"}if(Q.clearChatButtonWrapper){let se=_.showClearChat;if(se!==void 0){Q.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:Oe}=Q;Oe&&!Oe.classList.contains("persona-absolute")&&(se?Oe.classList.remove("persona-ml-auto"):Oe.classList.add("persona-ml-auto"))}}}let Le=o.layout?.showHeader!==!1;Se&&(Se.style.display=Le?"":"none");let Ae=o.layout?.showFooter!==!1;De&&(De.style.display=Ae?"":"none"),sr(),Nt(),$!==be?$?rt(X,"auto"):(T=!0,si()):X!==we&&rt(X,"auto"),we=X,be=$,Ai(),gg();let Vt=JSON.stringify(o.toolCall)!==JSON.stringify(c),st=JSON.stringify(o.messageActions)!==JSON.stringify(f),sn=JSON.stringify(o.layout?.messages)!==JSON.stringify(m),Kt=o.loadingIndicator?.render!==M?.render||o.loadingIndicator?.renderIdle!==M?.renderIdle||o.loadingIndicator?.showBubble!==M?.showBubble,Ft=o.iterationDisplay!==j,Ie=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(Y??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(U)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(te);(Vt||st||sn||Kt||Ft||Ie)&&D&&(Rc++,ti(le,D.getMessages(),he));let $t=o.features?.streamAnimation?.type;if($t!==ie&&$t&&$t!=="none"){let se=Hs($t,o.features?.streamAnimation?.plugins);se&&tc(se,t)}let Te=o.launcher??{},Ht=Te.headerIconHidden??!1,lt=o.layout?.header?.showIcon,$e=Ht||lt===!1,Rt=Te.headerIconName,Mt=Te.headerIconSize??"48px";if(vt){let se=Se,Oe=se?.querySelector(".persona-flex-col");if($e)vt.style.display="none",se&&Oe&&!se.contains(Oe)&&se.insertBefore(Oe,se.firstChild);else{if(vt.style.display="",vt.style.height=Mt,vt.style.width=Mt,se&&Oe&&(se.contains(vt)?vt.nextSibling!==Oe&&(vt.remove(),se.insertBefore(vt,Oe)):se.insertBefore(vt,Oe)),Rt){let ct=parseFloat(Mt)||24,Ze=ce(Rt,ct*.6,"currentColor",1);Ze?vt.replaceChildren(Ze):vt.textContent=Te.agentIconText??"\u{1F4AC}"}else if(Te.iconUrl){let ct=vt.querySelector("img");if(ct)ct.src=Te.iconUrl,ct.style.height=Mt,ct.style.width=Mt;else{let Ze=document.createElement("img");Ze.src=Te.iconUrl,Ze.alt="",Ze.className="persona-rounded-xl persona-object-cover",Ze.style.height=Mt,Ze.style.width=Mt,vt.replaceChildren(Ze)}}else{let ct=vt.querySelector("svg"),Ze=vt.querySelector("img");(ct||Ze)&&vt.replaceChildren(),vt.textContent=Te.agentIconText??"\u{1F4AC}"}let ze=vt.querySelector("img");ze&&(ze.style.height=Mt,ze.style.width=Mt)}}let Zt=o.layout?.header?.showTitle,_n=o.layout?.header?.showSubtitle;if(Ro&&(Ro.style.display=Zt===!1?"none":""),or&&(or.style.display=_n===!1?"none":""),He){let se=ae()&&o.layout?.header?.showCloseButton!==!1;if(He.style.display=se?"":"none",!re()){let kt=Te.closeButtonSize??"";He.style.height=kt,He.style.width=kt,He.style.minWidth=kt,He.style.minHeight=kt}let Oe=Te.closeButtonPlacement??"inline",{closeButtonWrapper:ze}=Q,ct=Oe==="top-right",Ze=ze?.classList.contains("persona-absolute");if(ze&&ct!==Ze)if(ze.remove(),ct){ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let kt=ui??K;kt.style.position="relative",kt.appendChild(ze)}else{let kt=Te.clearChat?.placement??"inline",Bt=Te.clearChat?.enabled??!0;ze.className=Bt&&kt==="inline"?"":"persona-ml-auto",Se&&Se.appendChild(ze)}if(He.style.color=Te.closeButtonColor||dn.actionIconColor,Te.closeButtonBackgroundColor?(He.style.backgroundColor=Te.closeButtonBackgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),Te.closeButtonBorderWidth||Te.closeButtonBorderColor){let kt=Te.closeButtonBorderWidth||"0px",Bt=Te.closeButtonBorderColor||"transparent";He.style.border=`${kt} solid ${Bt}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");Te.closeButtonBorderRadius?(He.style.borderRadius=Te.closeButtonBorderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),Te.closeButtonPaddingX?(He.style.paddingLeft=Te.closeButtonPaddingX,He.style.paddingRight=Te.closeButtonPaddingX):(He.style.paddingLeft="",He.style.paddingRight=""),Te.closeButtonPaddingY?(He.style.paddingTop=Te.closeButtonPaddingY,He.style.paddingBottom=Te.closeButtonPaddingY):(He.style.paddingTop="",He.style.paddingBottom=""),nc(He,Te.closeButtonIconName??"x",{iconSize:re()?Wp:void 0,iconText:Te.closeButtonIconText??"\xD7"});let Gt=Te.closeButtonTooltipText??"Close chat",yn=Te.closeButtonShowTooltip??!0;He.setAttribute("aria-label",Gt),ze&&Xt({anchor:He,trigger:ze,text:()=>He?.getAttribute("aria-label")??Gt,enabled:yn})}let{clearChatButton:je,clearChatButtonWrapper:en}=Q;if(je){let se=Te.clearChat??{},Oe=se.enabled??!0,ze=o.layout?.header?.showClearChat,ct=ze!==void 0?ze:Oe,Ze=se.placement??"inline";if(en){en.style.display=ct?"":"none";let{closeButtonWrapper:Gt}=Q;!re()&&Gt&&!Gt.classList.contains("persona-absolute")&&(ct?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let yn=Ze==="top-right",kt=en.classList.contains("persona-absolute");if(!re()&&yn!==kt&&ct){if(en.remove(),yn){en.className="persona-absolute persona-top-4 persona-z-50",en.style.right="48px";let Mn=ui??K;Mn.style.position="relative",Mn.appendChild(en)}else{en.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",en.style.right="";let Mn=Q.closeButtonWrapper;Se&&Mn&&Mn.parentElement===Se?Se.insertBefore(en,Mn):Se&&Se.appendChild(en)}let Bt=Q.closeButtonWrapper;Bt&&!Bt.classList.contains("persona-absolute")&&(yn?Bt.classList.add("persona-ml-auto"):Bt.classList.remove("persona-ml-auto"))}}if(ct){if(!re()){let Bt=se.size??"";je.style.height=Bt,je.style.width=Bt,je.style.minWidth=Bt,je.style.minHeight=Bt}let Gt=se.iconColor??"";if(je.style.color=Gt||dn.actionIconColor,nc(je,se.iconName??"refresh-cw",{iconSize:re()?Bp:void 0}),se.backgroundColor?(je.style.backgroundColor=se.backgroundColor,je.classList.remove("hover:persona-bg-gray-100")):(je.style.backgroundColor="",je.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let Bt=se.borderWidth||"0px",Mn=se.borderColor||"transparent";je.style.border=`${Bt} solid ${Mn}`,je.classList.remove("persona-border-none")}else je.style.border="",je.classList.add("persona-border-none");se.borderRadius?(je.style.borderRadius=se.borderRadius,je.classList.remove("persona-rounded-full")):(je.style.borderRadius="",je.classList.add("persona-rounded-full")),se.paddingX?(je.style.paddingLeft=se.paddingX,je.style.paddingRight=se.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),se.paddingY?(je.style.paddingTop=se.paddingY,je.style.paddingBottom=se.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let yn=se.tooltipText??"Clear chat",kt=se.showTooltip??!0;je.setAttribute("aria-label",yn),en&&Xt({anchor:je,trigger:en,text:()=>je?.getAttribute("aria-label")??yn,enabled:kt})}}let Et=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Zp],ln=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[ma.message,ma.messageAndClick];ne=eu({parsers:Et,handlers:ln,getSessionMetadata:R,updateSessionMetadata:H,emit:h.emit,documentRef:typeof document<"u"?document:null}),he=Zy(o,ne,Ce),nv(),D.updateConfig(o),(o.features?.history?.enabled===!0!==ge||o.features?.history?.provider!==Ve||o.getIdentityProof!==gt||o.clientToken!==Ut)&&(mn({restoreFocus:!1}),Ef()),$o(),Xa(),ti(le,D.getMessages(),he),Yr(),Yc(),ev(),ii(D.isStreaming());let Ti=o.voiceRecognition?.enabled===!0,Tg=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mi=o.voiceRecognition?.provider?.type==="runtype";if(Ti&&(Tg||Mi))if(!oe||!ao){let se=Xv(o.voiceRecognition,o.sendButton);se&&(oe=se.micButton,ao=se.micButtonWrapper,yb.insertBefore(ao,Jt),oe.addEventListener("click",ps),oe.disabled=D.isStreaming())}else{let se=o.voiceRecognition??{},Oe=o.sendButton??{},ze=se.iconName??"mic",ct=Oe.size??"40px",Ze=se.iconSize??ct,Gt=parseFloat(Ze)||24;oe.style.width=Ze,oe.style.height=Ze,oe.style.minWidth=Ze,oe.style.minHeight=Ze;let yn=se.iconColor??Oe.textColor;oe.innerHTML="";let kt=ce(ze,Gt,yn||"currentColor",1.5);kt?oe.appendChild(kt):oe.textContent="\u{1F3A4}";let Bt=se.backgroundColor??Oe.backgroundColor;Bt?oe.style.backgroundColor=Bt:oe.style.backgroundColor="",yn?oe.style.color=yn:oe.style.color="var(--persona-text, #111827)",se.borderWidth?(oe.style.borderWidth=se.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),se.borderColor?oe.style.borderColor=se.borderColor:oe.style.borderColor="",se.paddingX?(oe.style.paddingLeft=se.paddingX,oe.style.paddingRight=se.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),se.paddingY?(oe.style.paddingTop=se.paddingY,oe.style.paddingBottom=se.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Mn=se.tooltipText??"Start voice recognition",iw=se.showTooltip??!1;oe.setAttribute("aria-label",Mn),ao&&Xt({anchor:oe,trigger:ao,text:()=>oe?.getAttribute("aria-label")??Mn,enabled:iw}),ao.style.display="",oe.disabled=D.isStreaming()}else oe&&ao&&(ao.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?D.isVoiceActive()&&D.toggleVoice():to&&jo());if(o.attachments?.enabled===!0){if(!Ln||!dt){let se=o.attachments??{},ze=(o.sendButton??{}).size??"40px";Un||(Un=C("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Un.style.display="none",Ne.insertBefore(Un,me)),St||(St=document.createElement("input"),St.type="file",St.accept=(se.allowedTypes??Eo).join(","),St.multiple=(se.maxFiles??4)>1,St.style.display="none",St.setAttribute("aria-label","Attach files"),Ne.insertBefore(St,me)),Ln=C("div","persona-send-button-wrapper"),dt=C("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),dt.type="button",dt.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let ct=se.buttonIconName??"paperclip",Ze=ze,Gt=parseFloat(Ze)||40,yn=Math.round(Gt*.6);dt.style.width=Ze,dt.style.height=Ze,dt.style.minWidth=Ze,dt.style.minHeight=Ze,dt.style.fontSize="18px",dt.style.lineHeight="1";let kt=ce(ct,yn,"currentColor",1.5);kt?dt.appendChild(kt):dt.textContent="\u{1F4CE}",dt.addEventListener("click",Mn=>{Mn.preventDefault(),St?.click()}),Ln.appendChild(dt);let Bt=se.buttonTooltipText??"Attach file";Xt({anchor:dt,trigger:Ln,text:()=>dt?.getAttribute("aria-label")??Bt}),Ur?Ur.append(Ln):Ne.appendChild(Ln),!pt&&St&&Un&&(pt=zi.fromConfig(se),pt.setPreviewsContainer(Un),St.addEventListener("change",async()=>{pt&&St?.files&&(await pt.handleFileSelect(St.files),St.value="")}))}else{Ln.style.display="";let se=o.attachments??{};St&&(St.accept=(se.allowedTypes??Eo).join(","),St.multiple=(se.maxFiles??4)>1),pt&&pt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(K.querySelector(".persona-attachment-drop-overlay")?.remove(),K.appendChild(eb(o.attachments?.dropOverlay)),dt){let se=o.attachments??{},Oe=se.buttonTooltipText??"Attach file";dt.setAttribute("aria-label",Oe),dt.textContent="";let ze=parseFloat(o.sendButton?.size??"40px")||40,ct=ce(se.buttonIconName??"paperclip",Math.round(ze*.6),"currentColor",1.5);ct?dt.appendChild(ct):dt.textContent="\u{1F4CE}",Ln&&Xt({anchor:dt,trigger:Ln,text:()=>dt?.getAttribute("aria-label")??Oe})}}else Ln&&(Ln.style.display="none"),pt&&pt.clearAttachments(),K.querySelector(".persona-attachment-drop-overlay")?.remove();let Wt=o.sendButton??{},Od=Wt.useIcon??!1,pl=Wt.iconText??"\u2191",Mr=Wt.iconName,ul=Wt.tooltipText??"Send message",ow=Wt.showTooltip??!1,Ei=Wt.size??"40px",fl=Wt.backgroundColor,ki=Wt.textColor;if(Od){if(ye.style.width=Ei,ye.style.height=Ei,ye.style.minWidth=Ei,ye.style.minHeight=Ei,ye.style.fontSize="18px",ye.style.lineHeight="1",ki?ye.style.color=ki:ye.style.color="var(--persona-button-primary-fg, #ffffff)",!D.isStreaming())if(ye.innerHTML="",Mr){let se=parseFloat(Ei)||24,Oe=ki?.trim()||"currentColor",ze=ce(Mr,se,Oe,2);ze?ye.appendChild(ze):ye.textContent=pl}else ye.textContent=pl;ye.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",fl?(ye.style.backgroundColor=fl,ye.classList.remove("persona-bg-persona-primary")):(ye.style.backgroundColor="",ye.classList.add("persona-bg-persona-primary"))}else ye.textContent=o.copy?.sendButtonLabel??"Send",ye.style.width="",ye.style.height="",ye.style.minWidth="",ye.style.minHeight="",ye.style.fontSize="",ye.style.lineHeight="",ye.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",fl?(ye.style.backgroundColor=fl,ye.classList.remove("persona-bg-persona-accent")):ye.classList.add("persona-bg-persona-accent"),ki?ye.style.color=ki:ye.classList.add("persona-text-white");Wt.borderWidth?(ye.style.borderWidth=Wt.borderWidth,ye.style.borderStyle="solid"):(ye.style.borderWidth="",ye.style.borderStyle=""),Wt.borderColor?ye.style.borderColor=Wt.borderColor:ye.style.borderColor="",Wt.paddingX?(ye.style.paddingLeft=Wt.paddingX,ye.style.paddingRight=Wt.paddingX):(ye.style.paddingLeft="",ye.style.paddingRight=""),Wt.paddingY?(ye.style.paddingTop=Wt.paddingY,ye.style.paddingBottom=Wt.paddingY):(ye.style.paddingTop="",ye.style.paddingBottom=""),D.isStreaming()||ye.setAttribute("aria-label",ul),Jt&&Xt({anchor:ye,trigger:Jt,text:()=>ye.getAttribute("aria-label")??ul,enabled:ow});let fs=Jo(o,re());Hc(),fs?(le.style.maxWidth=fs,le.style.marginLeft="auto",le.style.marginRight="auto",le.style.width="100%",bn.style.maxWidth=fs,bn.style.marginLeft="auto",bn.style.marginRight="auto",bn.style.width="100%",Ne&&(Ne.style.maxWidth=fs,Ne.style.marginLeft="auto",Ne.style.marginRight="auto"),yt&&(yt.style.maxWidth=fs,yt.style.marginLeft="auto",yt.style.marginRight="auto"),tn.style.maxWidth=fs,tn.style.marginLeft="auto",tn.style.marginRight="auto"):(le.style.maxWidth="",le.style.marginLeft="",le.style.marginRight="",le.style.width="",bn.style.maxWidth="",bn.style.marginLeft="",bn.style.marginRight="",bn.style.width="",Ne&&(Ne.style.maxWidth="",Ne.style.marginLeft="",Ne.style.marginRight=""),yt&&(yt.style.maxWidth="",yt.style.marginLeft="",yt.style.marginRight=""),tn.style.maxWidth="",tn.style.marginLeft="",tn.style.marginRight="");let Uo=o.statusIndicator??{},rw=Uo.visible??!0;if(tn.style.display=rw?"":"none",D){let se=D.getStatus();x(tn,(ze=>ze==="idle"?Uo.idleText??Dt.idle:ze==="connecting"?Uo.connectingText??Dt.connecting:ze==="connected"?Uo.connectedText??Dt.connected:ze==="error"?Uo.errorText??Dt.error:Dt[ze])(se),Uo,se)}tn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let sw=Uo.align==="left"?"persona-text-left":Uo.align==="center"?"persona-text-center":"persona-text-right";tn.classList.add(sw),ht()},open(){ae()&&rt(!0,"api")},close(){ae()&&rt(!1,"api")},toggle(){ae()&&rt(!T,"api")},reconnect(){D.reconnectNow()},clearChat(){co=!1,D.clearMessages(),Cn.clear(),gn();try{localStorage.removeItem($s),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${$s}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==$s)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let s=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(s),A?.clear&&La(()=>A.clear(),"[AgentWidget] Failed to clear storage adapter:"),k={},ne.syncFromMetadata(),Me?.clear(),Ke?.reset(),ot?.update()},setMessage(s){return!me||D.isStreaming()?!1:(!T&&ae()&&rt(!0,"system"),me.value=s,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(s){if(D.isStreaming())return!1;let c=s?.trim()||me.value.trim();return c?(!T&&ae()&&rt(!0,"system"),me.value="",me.style.height="auto",D.sendMessage(c),!0):!1},startVoiceRecognition(){return D.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(D.isVoiceActive()||(!T&&ae()&&rt(!0,"system"),_e.manuallyDeactivated=!1,Kn(),D.toggleVoice().then(()=>{_e.active=D.isVoiceActive(),mo("user"),D.isVoiceActive()&&ds()})),!0):to?!0:sg()?(!T&&ae()&&rt(!0,"system"),_e.manuallyDeactivated=!1,Kn(),il("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{_e.active=!1,_e.manuallyDeactivated=!0,Kn(),mo("user"),xo()}),!0):!1:to?(_e.manuallyDeactivated=!0,Kn(),jo("user"),!0):!1},injectMessage(s){return!T&&ae()&&rt(!0,"system"),D.injectMessage(s)},injectAssistantMessage(s){!T&&ae()&&rt(!0,"system");let c=D.injectAssistantMessage(s);return Z&&(Z=!1,de&&(clearTimeout(de),de=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),c},injectUserMessage(s){return!T&&ae()&&rt(!0,"system"),D.injectUserMessage(s)},injectSystemMessage(s){return!T&&ae()&&rt(!0,"system"),D.injectSystemMessage(s)},injectMessageBatch(s){return!T&&ae()&&rt(!0,"system"),D.injectMessageBatch(s)},injectComponentDirective(s){return!T&&ae()&&rt(!0,"system"),D.injectComponentDirective(s)},injectTestMessage(s){!T&&ae()&&rt(!0,"system"),D.injectTestEvent(s)},async connectStream(s,c){return D.connectStream(s,c)},__pushEventStreamEvent(s){Me&&(Ke?.processEvent(s.type,s.payload),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:s.type,timestamp:Date.now(),payload:JSON.stringify(s.payload)}))},showEventStream(){!Pe||!Me||Sc()},hideEventStream(){qt&&Vr()},isEventStreamVisible(){return qt},listConversations(s){return D.listConversations(s)},getActiveConversationId(){return D.getActiveConversationId()},openConversation(s,c){return Td(s,{focusComposer:c?.focus===!0})},startNewConversation(s){return Md({focusComposer:s?.focus===!0})},deleteConversation(s){return Qf(s)},renameConversation(s,c){return Ed(s,{title:c})},setConversationStarred(s,c){return Ed(s,{starred:c})},clearConversationHistory(s){return Jf(s)},resetHistoryIdentity(){return Zf()},getHistoryIdentityStatus(){return Sn?Sn.getIdentityStatus():id()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(s){return vi({...s?.returnSurface?{returnSurface:s.returnSurface}:{},...s?.focus!==void 0?{focus:s.focus}:{}})},hideHistory(s){mn(s?.restoreFocus!==void 0?{restoreFocus:s.restoreFocus}:void 0)},isHistoryVisible(){return Ye},showArtifacts(){pn(o)&&(co=!1,qr=!0,po(),Be?.setMobileOpen(!0))},hideArtifacts(){pn(o)&&(co=!0,po())},upsertArtifact(s){return pn(o)?(qo(o.features?.artifacts,{artifactType:s.artifactType,...s.artifactType==="markdown"&&s.file?{file:s.file}:{},...s.presentation?{presentation:s.presentation}:{}})==="panel"&&(co=!1,qr=!0),D.upsertArtifact(s)):null},selectArtifact(s){pn(o)&&D.selectArtifact(s)},clearArtifacts(){pn(o)&&D.clearArtifacts()},getArtifacts(){return D?.getArtifacts()??[]},getSelectedArtifactId(){return D?.getSelectedArtifactId()??null},focusInput(){return $&&!T&&!re()||!me?!1:(me.focus(),!0)},async resolveApproval(s,c,f){let v=D.getMessages().find(M=>M.variant==="approval"&&M.approval?.id===s);if(!v?.approval)throw new Error(`Approval not found: ${s}`);if(v.approval.toolType==="webmcp"){D.resolveWebMcpApproval(v.id,c);return}return D.resolveApproval(v.approval,c,f)},setFollowUpSuggestions(s){kb(s)},clearFollowUpSuggestions(){Xu()},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...k}},updatePersistentMetadata(s){H(s)},on(s,c){return h.on(s,c)},off(s,c){h.off(s,c)},isOpen(){return ae()&&T},isVoiceActive(){return _e.active},toggleReadAloud(s){D.toggleReadAloud(s)},stopReadAloud(){D.stopSpeaking()},getReadAloudState(s){return D.getReadAloudState(s)},onReadAloudChange(s){return D.onReadAloudChange(s)},getState(){return{open:ae()&&T,launcherEnabled:$,voiceActive:_e.active,streaming:D.isStreaming()}},showCSATFeedback(s){!T&&ae()&&rt(!0,"system");let c=le.querySelector(".persona-feedback-container");c&&c.remove();let f=Xy({onSubmit:async(m,v)=>{D.isClientTokenMode()&&await D.submitCSATFeedback(m,v),s?.onSubmit?.(m,v)},onDismiss:s?.onDismiss,...s});le.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(s){!T&&ae()&&rt(!0,"system");let c=le.querySelector(".persona-feedback-container");c&&c.remove();let f=Qy({onSubmit:async(m,v)=>{D.isClientTokenMode()&&await D.submitNPSFeedback(m,v),s?.onSubmit?.(m,v)},onDismiss:s?.onDismiss,...s});le.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(s,c){return D.submitCSATFeedback(s,c)},async submitNPSFeedback(s,c){return D.submitNPSFeedback(s,c)},destroy(){Zc(),Cr!=null&&(clearInterval(Cr),Cr=null),Ee.forEach(s=>s()),E.remove(),G?.remove(),wt?.destroy(),rn?.remove(),dr&&He.removeEventListener("click",dr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let s=window.AgentWidgetBrowser,c={controller:Ct,getMessages:Ct.getMessages,getStatus:Ct.getStatus,getMetadata:Ct.getPersistentMetadata,updateMetadata:Ct.updatePersistentMetadata,clearHistory:()=>Ct.clearChat(),setVoiceActive:f=>f?Ct.startVoiceRecognition():Ct.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Ee.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=s)})}if(typeof window<"u"){let s=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),c=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===s)&&Ct.focusInput()};if(window.addEventListener("persona:focusInput",c),Ee.push(()=>{window.removeEventListener("persona:focusInput",c)}),Pe){let U=ie=>{let ge=ie.detail;(!ge?.instanceId||ge.instanceId===s)&&Ct.showEventStream()},te=ie=>{let ge=ie.detail;(!ge?.instanceId||ge.instanceId===s)&&Ct.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",te),Ee.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",te)})}let f=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===s)&&Ct.showHistory()},m=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===s)&&Ct.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",m),Ee.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",m)});let v=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===s)&&Ct.showArtifacts()},M=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===s)&&Ct.hideArtifacts()},j=U=>{let te=U.detail;te?.instanceId&&te.instanceId!==s||te?.artifact&&Ct.upsertArtifact(te.artifact)},F=U=>{let te=U.detail;te?.instanceId&&te.instanceId!==s||typeof te?.id=="string"&&Ct.selectArtifact(te.id)},Y=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===s)&&Ct.clearArtifacts()};window.addEventListener("persona:showArtifacts",v),window.addEventListener("persona:hideArtifacts",M),window.addEventListener("persona:upsertArtifact",j),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",Y),Ee.push(()=>{window.removeEventListener("persona:showArtifacts",v),window.removeEventListener("persona:hideArtifacts",M),window.removeEventListener("persona:upsertArtifact",j),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",Y)})}let Dn=GS(o.persistState);if(Dn&&ae()){let s=YS(Dn.storage),c=`${Dn.keyPrefix}widget-open`,f=`${Dn.keyPrefix}widget-voice`,m=`${Dn.keyPrefix}widget-voice-mode`;if(s){let v=Dn.persist?.openState&&s.getItem(c)==="true",M=Dn.persist?.voiceState&&s.getItem(f)==="true",j=Dn.persist?.voiceState&&s.getItem(m)==="true";if(v&&(wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ct.open(),setTimeout(()=>{if(M||j)Ct.startVoiceRecognition();else if(Dn.persist?.focusInput){let F=t.querySelector("textarea");F&&F.focus()}},100)},0)),Dn.persist?.openState&&(h.on("widget:opened",()=>{s.setItem(c,"true")}),h.on("widget:closed",()=>{s.setItem(c,"false")})),Dn.persist?.voiceState&&(h.on("voice:state",F=>{s.setItem(f,F.active?"true":"false")}),h.on("user:message",F=>{s.setItem(m,F.viaVoice?"true":"false")})),Dn.clearOnChatClear){let F=()=>{s.removeItem(c),s.removeItem(f),s.removeItem(m)},Y=()=>F();window.addEventListener("persona:clear-chat",Y),Ee.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(S&&ae()&&(wt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Ct.open()},0)),ts(),!Pb){let s=ml(()=>{D&&(Rc++,Cn.clear(),ti(le,D.getMessages(),he))});Ee.push(s)}return Ct};var nb=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},JS=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},ZS=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},eT=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let i=o.offsetHeight>0;o.remove(),!(!r||i)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ob=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},cu=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},rb=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",cu(t)},iu=t=>{t.style.transition=""},au=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},lu=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Cc=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},tT=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},nT=(t,e,n,o,r,i)=>{let a=i?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},oT=t=>{let e=ks(t),n=e.components?.panel,o=(r,i)=>r==null||r===""?i:cn(e,r)??r;return{inset:o(n?.inset,Dl),canvasBackground:o(n?.canvasBackground,_l)}},sb=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},rT=(t,e,n,o,r,i,a,l)=>{let d=$n(i),u=d.reveal==="push",p=l!=null,g=l?.inset??"",y=l?.canvasBackground??"";tT(t,e,n,o,u),nT(t,e,n,o,d.side,u),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let h=t.ownerDocument.defaultView,b=i?.launcher?.mobileFullscreen??!0,A=i?.launcher?.mobileBreakpoint??640,k=h!=null?h.innerWidth<=A:!1;if(b&&k&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),au(e),iu(o),rb(o),lu(n),Cc(r,o),sb(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(i?.launcher?.zIndex??Yt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),rb(o),JS(o,d.maxHeight),sb(o,p&&a,g,y),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",au(e),iu(o),lu(n),Cc(r,o);let I=d.animate?"transform 180ms ease":"none",P=d.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":P;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=I,o.style.transform=S,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",iu(o),cu(o),Cc(r,o);let I=nb(d.width,t.clientWidth),P=Math.max(0,t.clientWidth),S=d.animate?"margin-left 180ms ease":"none",W=d.side==="right"?a?-I:0:a?0:-I;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${P+I}px`,e.style.transition=S,e.style.marginLeft=`${W}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",au(e),cu(o),lu(n),Cc(r,o);let I=d.reveal==="emerge";I?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let P=a?d.width:"0px",S=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",W=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${P}`,o.style.width=P,o.style.maxWidth=P,o.style.minWidth=P,o.style.minHeight="0",ZS(o,d.maxHeight),o.style.overflow=I||W?"hidden":"visible",o.style.transition=S,I){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let R=p?`calc(${nb(d.width,t.clientWidth)}px - (2 * ${g}))`:d.width;r.style.width=R,r.style.minWidth=R,r.style.maxWidth=R,r.style.boxSizing="border-box"}}},sT=(t,e)=>{let n=t.ownerDocument.createElement("div");return ob(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){ob(n,o)},destroy(){n.remove()}}},iT=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let i=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),u=n.createElement("aside"),p=n.createElement("div"),g=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),o.insertBefore(a,t),d.appendChild(t);let y=null,h=()=>{y?.disconnect(),y=null},b=null,A=()=>{b=e?.launcher?.detachedPanel===!0?oT(e):null};A();let k=()=>{rT(a,l,d,u,p,e,g,b)},N=null,I=()=>{N?.(),N=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(N=Ol(()=>{A(),k()}))},P=()=>{h(),$n(e).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{k()}),y.observe(a)))},S=!1,W=()=>{k(),P(),g&&!S&&a.dataset.personaDockMobileFullscreen!=="true"&&(S=!0,eT(a,$n(e)))},R=a.ownerDocument.defaultView,H=()=>{W()};return R?.addEventListener("resize",H),$n(e).reveal==="push"?(l.appendChild(d),l.appendChild(u),a.appendChild(l)):(a.appendChild(d),a.appendChild(u)),W(),I(),{mode:"docked",host:p,shell:a,syncWidgetState(z){let V=z.launcherEnabled?z.open:!0;g!==V&&(g=V,W())},updateConfig(z){e=z,(e?.launcher?.enabled??!0)===!1&&(g=!0),A(),W(),I()},destroy(){R?.removeEventListener("resize",H),N?.(),N=null,h(),o.isConnected&&(i&&i.parentNode===o?o.insertBefore(t,i):o.appendChild(t)),a.remove()}}},ib=(t,e)=>Pt(e)?iT(t,e):sT(t,e);var ha={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ab=.15,lb=1.5,du="persona-preview-shell-theme",aT={load:()=>null,save:()=>{},clear:()=>{}},lT=["How do I get started?","Pricing & plans","Talk to support"];function pu(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function cT(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function cb(t){let e=cT(t);return`* { box-sizing: border-box; }
|
|
141
141
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
142
|
-
html { color-scheme: ${
|
|
143
|
-
body { font-family: system-ui, sans-serif; background: ${
|
|
142
|
+
html { color-scheme: ${t}; }
|
|
143
|
+
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
144
144
|
.preview-iframe-mock { min-height: 100%; }
|
|
145
|
-
.preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${
|
|
146
|
-
.preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${
|
|
145
|
+
.preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
|
|
146
|
+
.preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${e.dot}; }
|
|
147
147
|
.preview-iframe-copy { padding: 32px; }
|
|
148
|
-
.preview-iframe-line { border-radius: 999px; background: ${
|
|
148
|
+
.preview-iframe-line { border-radius: 999px; background: ${e.skeleton}; margin-bottom: 12px; }
|
|
149
149
|
.preview-iframe-line.hero { width: 48%; height: 16px; }
|
|
150
150
|
.preview-iframe-line.body { width: 72%; height: 10px; }
|
|
151
151
|
.preview-iframe-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 24px 0; }
|
|
152
|
-
.preview-iframe-card { height: 84px; border-radius: 14px; background: ${
|
|
152
|
+
.preview-iframe-card { height: 84px; border-radius: 14px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
153
153
|
.preview-workspace-shell { height: 100%; min-height: 100%; display: flex; flex-direction: column; }
|
|
154
|
-
.preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${
|
|
154
|
+
.preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
|
|
155
155
|
.preview-workspace-topbar-left { display: flex; align-items: center; gap: 12px; }
|
|
156
|
-
.preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${
|
|
157
|
-
.preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${
|
|
158
|
-
.preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${
|
|
156
|
+
.preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
157
|
+
.preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${e.skeleton}; }
|
|
158
|
+
.preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
159
159
|
.preview-workspace-body { flex: 1; min-height: 0; display: flex; padding: 20px; }
|
|
160
|
-
.preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${
|
|
160
|
+
.preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
161
161
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
162
162
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
163
|
-
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${
|
|
164
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
163
|
+
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
164
|
+
.preview-workspace-card.short { height: 96px; }`}function db(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(du);o||(o=n.createElement("style"),o.id=du,n.head.appendChild(o)),o.textContent=cb(e)}var dT=`
|
|
165
165
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
166
166
|
<div class="preview-iframe-chrome">
|
|
167
167
|
<span class="preview-iframe-dot"></span>
|
|
@@ -180,7 +180,7 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
180
180
|
<div class="preview-iframe-line body"></div>
|
|
181
181
|
<div class="preview-iframe-line body"></div>
|
|
182
182
|
</div>
|
|
183
|
-
</div>`,
|
|
183
|
+
</div>`,pT=`
|
|
184
184
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
185
185
|
<div class="preview-iframe-line hero"></div>
|
|
186
186
|
<div class="preview-iframe-line body"></div>
|
|
@@ -193,9 +193,9 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
193
193
|
<div class="preview-workspace-card short"></div>
|
|
194
194
|
<div class="preview-workspace-card short"></div>
|
|
195
195
|
</div>
|
|
196
|
-
</div>`;function
|
|
197
|
-
${
|
|
198
|
-
<div style="position:fixed;inset:0;z-index:9999;"><div id="${
|
|
196
|
+
</div>`;function pb(t,e,n,o){let r=`
|
|
197
|
+
${dT}
|
|
198
|
+
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,i=`
|
|
199
199
|
<div class="preview-workspace-shell">
|
|
200
200
|
<div class="preview-workspace-topbar">
|
|
201
201
|
<div class="preview-workspace-topbar-left">
|
|
@@ -205,8 +205,8 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
205
205
|
<span class="preview-workspace-topbar-pill"></span>
|
|
206
206
|
</div>
|
|
207
207
|
<div class="preview-workspace-body">
|
|
208
|
-
<div id="preview-content-${
|
|
209
|
-
${
|
|
208
|
+
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
209
|
+
${pT}
|
|
210
210
|
</div>
|
|
211
211
|
</div>
|
|
212
212
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -214,16 +214,16 @@ _Details: ${n.message}_`:o}var Ws=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
214
214
|
<head>
|
|
215
215
|
<meta charset="UTF-8">
|
|
216
216
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
217
|
-
<link rel="stylesheet" href="${
|
|
218
|
-
<style id="${
|
|
217
|
+
<link rel="stylesheet" href="${pu(o)}">
|
|
218
|
+
<style id="${du}">${cb(e)}</style>
|
|
219
219
|
</head>
|
|
220
220
|
<body>
|
|
221
|
-
${n?
|
|
221
|
+
${n?i:r}
|
|
222
222
|
</body>
|
|
223
|
-
</html>`}var
|
|
224
|
-
${
|
|
225
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
226
|
-
</div
|
|
223
|
+
</html>`}var uT=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],fT=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function gT(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&fT(e)?[...uT(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function mT(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:lT:t.suggestionChips,initialMessages:gT(e,t,n),storageAdapter:aT};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),e==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function hT(t,e){let n=t.theme?Es(t.theme,{validate:!1}):Es();return{...qe,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function js(t,e){let n=t.scene??"conversation";return mT(hT(t,e),n,t.appendedMessages??[])}function ub(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:js(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:js(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:js(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:js(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:js(t,n),shellMode:n}]}function yT(t,e){let n={...e},o=[],r=[],i=null,a=!1,l=1,d=1,u=0;function p(){return n.device??"desktop"}function g(){return n.zoom??l}function y(){let I=getComputedStyle(t),P=parseFloat(I.paddingLeft)+parseFloat(I.paddingRight),S=parseFloat(I.paddingTop)+parseFloat(I.paddingBottom),W=40,R=(n.compareMode??"off")!=="off",H=(t.clientWidth-P-W)/(R?2:1),z=t.clientHeight-S-W;if(H<=0||z<=0)return 1;let V=ha[p()]??ha.desktop;return Math.min(H/V.w,z/V.h,1)}function h(){l=y();let I=Math.max(ab,Math.min(lb,g()));d=I;let P=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let S of P){let W=S.dataset.device??"desktop",R=ha[W]??ha.desktop;S.style.width=`${R.w*I}px`,S.style.height=`${R.h*I}px`,W==="mobile"&&(S.style.borderRadius=`${32*I}px`);let H=S.querySelector("iframe");H&&(H.style.width=`${R.w}px`,H.style.height=`${R.h}px`,H.style.transformOrigin="top left",H.style.transition="none",H.style.transform=`scale(${I})`)}n.onScaleChange?.(I)}function b(){n.onBeforeDestroy?.();for(let I of o)I.destroy();for(let I of r)I();o=[],r=[]}function A(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function k(){if(a)return;b();let I=++u,P=ub(n),S=p(),W=(n.compareMode??"off")!=="off",R=(n.scene??"conversation")==="minimized",H=n.widgetCssPath??"/widget-dist/widget.css",z=n.buildSrcdoc??pb,V=S==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",ne=pe=>`<div class="${V}" data-mount-id="${pe.mountId}" data-device="${S}" data-shell-mode="${pe.shellMode}">
|
|
224
|
+
${W?`<div class="preview-frame-meta"><span class="preview-frame-label">${pu(pe.label)}</span></div>`:""}
|
|
225
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${pe.mountId}"></iframe>
|
|
226
|
+
</div>`,$=W?`<div class="preview-compare-grid">${P.map(pe=>`<div class="preview-compare-cell">${ne(pe)}</div>`).join("")}</div>`:`<div class="preview-single">${ne(P[0])}</div>`;n.morphContainer?n.morphContainer(t,$):t.innerHTML=$,h();let X=A(),ue=0,we=X.length,be=()=>{if(a||I!==u)return;for(let J of X){let re=J.dataset.mountId;if(!re||!J.contentDocument)continue;let ae=P.find(he=>he.mountId===re);if(!ae)continue;let T=()=>{},Z=Pt(ae.config),de=Z?(()=>{let he=J.contentDocument?.getElementById(`preview-content-${re}`);if(!he)return null;let ve=ib(he,ae.config),xe=J.contentDocument.createElement("div");xe.id=re,xe.style.height="100%",xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1",xe.style.minHeight="0",ve.host.appendChild(xe);let Pe=()=>ve.syncWidgetState(Ce.getState()),Xe=T;return T=()=>{ve.destroy(),Xe()},xe.__syncDock=Pe,xe.__hostLayout=ve,xe})():J.contentDocument.getElementById(re);if(!de)continue;let Ce=tb(de,ae.config);if(o.push(Ce),Z&&de.__syncDock){let he=de.__syncDock,ve=Ce.on("widget:opened",he),xe=Ce.on("widget:closed",he),Pe=T;T=()=>{ve(),xe(),Pe()},he()}r.push(T),R&&Ce.close()}let pe=n.scene??"conversation";if(pe==="messages")for(let J of o)J.showHistory({focus:!1});if(pe==="artifact"||n.config?.features?.artifacts?.enabled)for(let J of o)J.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
227
227
|
|
|
228
228
|
This is a preview of the artifact sidebar.
|
|
229
229
|
|
|
@@ -231,4 +231,4 @@ This is a preview of the artifact sidebar.
|
|
|
231
231
|
|
|
232
232
|
- Markdown rendering
|
|
233
233
|
- Document toolbar
|
|
234
|
-
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:
|
|
234
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:X,controllers:[...o]})};for(let pe of X){let J=pe.dataset.mountId;if(!J)continue;let re=P.find(ae=>ae.mountId===J);re&&(pe.addEventListener("load",()=>{ue++,ue>=we&&be()},{once:!0}),pe.srcdoc=z(J,re.shellMode,Pt(re.config),H))}we===0&&be()}function N(){if(a)return;let I=ub(n);if(o.length!==I.length){k();return}if(I.some(S=>{let W=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${S.mountId}"]`);return!W||W.dataset.shellMode!==S.shellMode})){k();return}o.forEach((S,W)=>{S.update(I[W].config),(n.scene??"conversation")==="minimized"&&S.close()});for(let S of I){let W=t.querySelector(`iframe[data-mount-id="${S.mountId}"]`);W&&db(W,S.shellMode)}n.onAfterUpdate?.({iframes:A(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>{a||h()}),i.observe(t)),k(),{update(I){if(a)return;let P=I.device!==void 0&&I.device!==n.device||I.scene!==void 0&&I.scene!==n.scene||I.compareMode!==void 0&&I.compareMode!==n.compareMode||I.widgetCssPath!==void 0&&I.widgetCssPath!==n.widgetCssPath;n={...n,...I},P?k():N()},destroy(){a||(a=!0,b(),i?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},h())},getIframes(){return A()},getScale(){return d},setZoom(I){a||(n={...n,zoom:I},h())}}}export{yT as createThemePreview};
|