@runtypelabs/persona 4.32.1 → 4.32.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-C9uOhfk5.js → chunk-B9Zu-wrk.js} +1 -1
- package/dist/chunk-BNE40cEG.js +1 -0
- package/dist/{chunk-DM-OJt5q.js → chunk-CjkechxR.js} +1 -1
- package/dist/{chunk-CumoXK3u.js → chunk-D0tcIZJM.js} +1 -1
- package/dist/client-dispatch.js +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/theme-editor-preview.cjs +2 -2
- package/dist/theme-editor-preview.js +2 -2
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.js +1 -1
- package/package.json +1 -1
- package/src/index-global.ts +2 -1
- package/src/install.test.ts +6 -5
- package/src/install.ts +2 -2
- package/src/launcher-global.ts +2 -1
- package/src/session.test.ts +41 -0
- package/src/session.ts +14 -7
- package/src/utils/cdn-release.test.ts +20 -0
- package/src/utils/cdn-release.ts +14 -0
- package/dist/chunk-BkOYJ11B.js +0 -1
package/dist/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
5
5
|
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),tr=()=>{let e=null,t=0,n=e=>{let t=e.match(/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/)?.[1]||e.match(/"text"\s*:\s*"((?:[^"\\]|\\.)*)/)?.[1];if(!t)return null;try{return er(t)}catch{return t}};return{getExtractedText:()=>e,processChunk:async r=>{let i=r.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(r.length<=t)return e===null?null:{text:e,raw:r};let a=n(r);return a!==null&&(e=a),t=r.length,e===null?null:{text:e,raw:r}},close:async()=>{}}},nr=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},rr=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ir=()=>tr(),ar=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e!==null||e===``?{text:e||``,raw:n}:null;try{let t=Rt(n,Lt|It);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?er(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=er(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},or=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?er(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?er(e.text):``;if(e.type===`init`&&e.form)return``;if(e.action)switch(e.action){case`nav_then_click`:return t(e.on_load_text)||t(e.text)||null;case`message`:case`message_and_click`:case`checkout`:return t(e.text)||null;default:return t(e.text)||t(e.display_text)||t(e.message)||null}return t(e.text)||t(e.display_text)||t(e.message)||t(e.content)||null});return{getExtractedText:()=>t,processChunk:e=>{let i=e.trim();if(!i.startsWith(`{`)&&!i.startsWith(`[`))return null;if(e.length<=n)return t===null?null:{text:t,raw:e};try{let n=Rt(e,Lt|It),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},sr=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith(`<`))return null;let n=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:t}):null},getExtractedText:()=>e}}}));function lr(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=ur(t)&&ur(r)?lr(t,r):r}return n}var ur,dr=B((()=>{ur=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),fr,pr,mr,hr,gr,_r,vr,yr=B((()=>{dr(),fr=e=>{if(typeof e!=`string`)return;let t=e.trim(),n=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(t)?.[1];if(n){let e=n.length===3?[...n].map(e=>e+e).join(``):n;return[0,2,4].map(t=>parseInt(e.slice(t,t+2),16))}let r=/^rgba?\(\s*([^)]*)\)$/i.exec(t);if(!r)return;let i=r[1].trim().split(/\s*[,/]\s*|\s+/);if(i.length===4&&/^(?:1(?:\.0+)?|100%)$/.test(i[3])&&i.pop(),i.length!==3)return;let a=i.map(e=>/^\d+(?:\.\d+)?%?$/.test(e)?Number.parseFloat(e)*(e.endsWith(`%`)?2.55:1):NaN);if(!a.some(e=>!Number.isFinite(e)||e<0||e>255))return a},pr=e=>e.reduce((e,t,n)=>{let r=t/255;return e+(r<=.04045?r/12.92:((r+.055)/1.055)**2.4)*[.2126,.7152,.0722][n]},0),mr=e=>`#`+e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``),hr=(e,t,n)=>mr(e.map(e=>e+(t-e)*n)),gr=e=>pr(e)>.179?`#000000`:`#ffffff`,_r=e=>{let t=fr(e?.neutral);return t?pr(t)<.18?`dark`:`light`:void 0},vr=(e,t=`light`,n,r=!1)=>{let i={};if(!e)return i;let a=fr(e.accent);if(a){let e={};for(let[t,n]of[[50,.96],[100,.9],[200,.75],[300,.55],[400,.25]])e[t]=hr(a,255,n);e[500]=mr(a);for(let[t,n]of[[600,.15],[700,.3],[800,.45],[900,.6],[950,.75]])e[t]=hr(a,0,n);let t=gr(a);i.palette={colors:{primary:e,accent:e}},i.semantic={colors:{primary:e[500],accent:e[500],interactive:{default:e[500],hover:e[600],focus:e[500],active:e[700]}}},i.components={button:{primary:{background:e[500],foreground:t}},launcher:{background:e[500],foreground:t},header:r?{background:`semantic.colors.container`,foreground:`semantic.colors.text`,iconBackground:`transparent`,iconForeground:`semantic.colors.text`}:{background:e[500],foreground:t,iconBackground:e[500],iconForeground:t},approval:{approve:{foreground:t}},message:{user:r?{background:`color-mix(in srgb, var(--persona-primary) 12%, var(--persona-container))`,text:`semantic.colors.text`}:{background:e[500],text:t}}}}let o=fr(e.neutral);if(o){let e=t===`dark`,n=e===pr(o)<.18?o:fr(hr(o,e?0:255,.9)),r=mr(n),a=hr(n,e?255:0,e?.06:.025),s=hr(n,e?255:0,e?.2:.16),c=gr(n),l={};for(let[e,t]of[[50,0],[100,.06],[200,.16],[300,.28],[400,.45],[500,.65],[600,.72],[700,.8],[800,.9],[900,.97],[950,1]])l[e]=hr(n,c===`#ffffff`?255:0,t);i.palette={...i.palette,colors:{...i.palette?.colors,gray:l}},i.semantic={...i.semantic,colors:{...i.semantic?.colors,surface:r,background:r,container:a,border:s,divider:s,text:c,textMuted:hr(n,c===`#ffffff`?255:0,.65)}},i.components={...i.components,panel:{background:r},header:{...i.components?.header,background:r,foreground:c},composer:{footerBackground:r}}}if(a){let e=fr(i.semantic?.colors?.surface)??(t===`dark`?[15,15,16]:[255,255,255]),n=mr(a),r=gr(e)===`#ffffff`?255:0;for(let t=0;t<=1;t+=.1){n=hr(a,r,t);let i=pr(fr(n)),o=pr(e);if((Math.max(i,o)+.05)/(Math.min(i,o)+.05)>=4.5)break}i.components={...i.components,markdown:{link:{foreground:n}},input:{focus:{border:n,ring:n}}}}e.font?.trim()&&(i.semantic={...i.semantic,typography:{fontFamily:e.font}});let s={none:`0px`,sm:`4px`,md:`8px`,lg:`16px`}[e.radius??`none`];e.radius&&s&&(i.palette={...i.palette,radius:{none:`0px`,sm:s,md:s,lg:s,xl:s,"2xl":s}},i.components={...i.components,input:{...i.components?.input,borderRadius:s},header:{...i.components?.header,controlBorderRadius:s}});let c={compact:[13,44,8],comfortable:[14,48,12],spacious:[15,52,16]}[e.density??`comfortable`];if(e.density&&c){let[e,t,n]=c;i.semantic={...i.semantic,typography:{...i.semantic?.typography,fontSize:`${e}px`}},i.components={...i.components,header:{...i.components?.header,minHeight:`${t}px`,padding:`${n}px 16px`,minimalPadding:`${n}px 16px`},history:{railHeader:{minHeight:`${t}px`}},composer:{...i.components?.composer,fontSize:`${e}px`,padding:`${n}px`,gap:`${n/2}px`},message:{...i.components?.message,gap:`${n}px`,user:{...i.components?.message?.user,fontSize:`${e}px`},assistant:{fontSize:`${e}px`}}}}if(e.elevation&&[`flat`,`subtle`,`raised`].includes(e.elevation)){let t=e.elevation===`flat`,a=t?`none`:e.elevation===`subtle`?`0 2px 8px rgba(0, 0, 0, 0.08)`:`0 12px 32px rgba(0, 0, 0, 0.18)`,o=t?`1px solid var(--persona-border)`:`1px solid color-mix(in srgb, var(--persona-border) 65%, transparent)`;i.palette={...i.palette,shadows:{sm:a,md:a,lg:a,xl:a,"2xl":a}};let s=(e,n=``)=>{let i={};if(r&&n===`message.assistant`)return i;for(let[r,c]of Object.entries(e))if(r.toLowerCase().endsWith(`shadow`)){i[r]=a;let n=r===`shadow`?`border`:r.replace(/Shadow$/,`Border`);n in e&&(i[n]=typeof e[n]==`string`&&e[n].includes(`solid`)?o:t?`semantic.colors.border`:`color-mix(in srgb, var(--persona-border) 65%, transparent)`)}else if(c&&typeof c==`object`){let e=s(c,n?`${n}.${r}`:r);Object.keys(e).length&&(i[r]=e)}return i},c=n?s(n):{};i.components=lr(i.components,c),i.components={...i.components,panel:{...i.components?.panel,shadow:a,modes:{floating:{shadow:a,border:o},inline:{shadow:a,border:o},docked:{shadow:a,border:o},sidebar:{shadow:a,border:o},mobile:{shadow:a,border:o}}},launcher:{...i.components?.launcher,shadow:a,border:`semantic.colors.border`},composer:{...i.components?.composer,shadow:a,borderColor:`semantic.colors.border`},toolBubble:{shadow:a},reasoningBubble:{shadow:a}}}return i}}));function br(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return Or(n)?br(n,r):[r]})}function xr(e,t){let n=t.split(`.`);for(let t=0;t<n.length;t++){let r=n[t];if(!Or(e)||!Object.prototype.hasOwnProperty.call(e,r))return`absent`;if(e=e[r],e===void 0||t<n.length-1&&!Or(e))return`clear`}return`explicit`}function Sr(e,t){return e?.[Dr]??t.filter(t=>xr(e,t)===`explicit`)}function Cr(e,t){return Object.defineProperty(e,Dr,{value:t,enumerable:!0,configurable:!0}),e}function wr(e,t,n){return Cr(e,Sr(t,br(n)))}function Tr(e,t,n){let r=t[Dr];if(r)return r;let i=new Set(Sr(e,n));for(let e of n){let n=xr(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function Er(e,t,n){let r={...e};for(let e of t){if(n.includes(e))continue;let t=e.split(`.`),i=r;for(let e of t.slice(0,-1)){let t=i[e];if(!Or(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var Dr,Or,kr=B((()=>{Dr=Symbol.for(`persona.defaultsProvenance`),Or=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr=B((()=>{yr(),kr(),Ar=(e,t)=>t.split(` `).map(t=>`${e}.${t}`),jr=[...Ar(`launcher`,`closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY`),...Ar(`launcher.clearChat`,`size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY`),...Ar(`sendButton`,`size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY`),...Ar(`voiceRecognition`,`iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor`),...Ar(`toolCall`,`shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration`),...Ar(`approval`,`backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor`),...Ar(`features.askUserQuestion.styles`,`sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground`),...Ar(`features.artifacts.layout`,`paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize`),...Ar(`suggestionChipsConfig`,`fontWeight paddingX paddingY`)],Mr=[`voice.recording.border`,`voice.processing.icon`,`voice.processing.background`,`voice.speaking.icon`,`approval.requested.text`,`approval.approve.foreground`,`approval.deny.foreground`,`approval.deny.background`,`reasoningBubble.shadow`,`toolBubble.shadow`],Nr=[...jr,`suggestionChips`,`copy.welcomeTitle`,`copy.welcomeSubtitle`,`copy.showWelcomeCard`,`features.suggestReplies.enabled`,`features.suggestReplies.expose`,...[`theme`,`darkTheme`].flatMap(e=>Mr.map(t=>`${e}.components.${t}`))],Pr=Symbol.for(`persona.styleProvenance`),Fr=e=>e[Pr]!==void 0,Ir=(e,t)=>{for(let n of t.split(`.`)){if(typeof e!=`object`||!e)return;e=e[n]}return e},Lr=e=>{let t=e?.[Pr];if(!t)return Nr.filter(t=>xr(e,t)===`explicit`);let n=new Set(t.explicit);return Nr.forEach(r=>{Ir(e,r)!==t.values[r]&&(xr(e,r)===`explicit`?n.add(r):n.delete(r))}),[...n]},Rr=(e,t)=>(Object.defineProperty(e,Pr,{value:{explicit:t,values:Object.fromEntries(Nr.map(t=>[t,Ir(e,t)]))},enumerable:!0,configurable:!0}),e),zr=(e,t)=>Rr(e,Lr(t)),Br=(e,t)=>{if(t[Pr])return Lr(t);let n=new Set(Lr(e));for(let e of Nr){let r=xr(t,e);r===`clear`&&n.delete(e),r===`explicit`&&n.add(e)}return[...n]},Vr=(e,t)=>{let n=e?.[Pr];return!n||!Object.prototype.hasOwnProperty.call(n.values,t)||Ir(e,t)!==n.values[t]?xr(e,t)===`explicit`:n.explicit.includes(t)},Hr=(e,t)=>Vr(e,t)?Ir(e,t):void 0,Ur=(e,t,n)=>{let r=e,i=n??r?.colorScheme??_r(r?.brand)??`light`,a=i===`dark`||i===`auto`&&(typeof document<`u`&&document.documentElement.classList.contains(`dark`)||typeof window<`u`&&window.matchMedia?.(`(prefers-color-scheme: dark)`).matches);return Vr(e,`theme.components.${t}`)||a&&Vr(e,`darkTheme.components.${t}`)}})),J,Y,Gr,X=B((()=>{J=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Y=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[e,n]of Object.entries(t.attrs))r.setAttribute(e,n);if(t.style){let e=r.style,n=t.style;for(let t of Object.keys(n)){let r=n[t];r!=null&&(e[t]=r)}}let i=n.filter(e=>e!=null);return i.length>0&&r.append(...i),r},Gr=(...e)=>e.filter(Boolean).join(` `)})),Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Z,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,Q,zi,Bi,Vi,Hi,Ui,Wi,Gi=B((()=>{Wr(),X(),Kr=`ask_user_question`,qr=`data-persona-ask-sheet-for`,Jr=`Other`,Yr=`Other…`,Xr=`Type your own answer here`,Zr=`Send`,Qr=`Next`,$r=`Back`,ei=`Submit all`,ti=`Skip`,ni=3,ri=`data-ask-current-index`,ii=`data-ask-question-count`,ai=`data-ask-answers`,oi=`data-ask-grouped`,si=`data-ask-layout`,ci=e=>e.layout===`pills`?`pills`:`rows`,li=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,ui=!1,di=e=>e.replace(/["\\]/g,`\\$&`),fi=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,pi=e=>e?.features?.askUserQuestion??{},mi=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let e=r.join(``),t=Rt(e,Lt|It|Ft);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},hi=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!ui&&(ui=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},gi=e=>hi(e)[0]??null,_i=(e,t)=>hi(e)[t]??null,vi={sheetBackground:`--persona-ask-sheet-bg`,sheetBorder:`--persona-ask-sheet-border`,sheetShadow:`--persona-ask-sheet-shadow`,pillBackground:`--persona-ask-pill-bg`,pillBackgroundSelected:`--persona-ask-pill-bg-selected`,pillTextColor:`--persona-ask-pill-fg`,pillTextColorSelected:`--persona-ask-pill-fg-selected`,pillBorderRadius:`--persona-ask-pill-radius`,customInputBackground:`--persona-ask-input-bg`},yi=(e,t)=>{Object.entries(vi).forEach(([n,r])=>{let i=Hr(t,`features.askUserQuestion.styles.${n}`);typeof i==`string`&&i?e.style.setProperty(r,i):e.style.removeProperty(r)})},bi=(e,t,n)=>{if(e!==`rows`)return null;let r=J(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=J(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=J(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},xi=(e,t,n,r)=>{let i=J(`button`,n===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(i.type=`button`,i.setAttribute(`role`,r?`checkbox`:`button`),i.setAttribute(`aria-pressed`,`false`),i.setAttribute(`data-ask-user-action`,`pick`),i.setAttribute(`data-option-index`,String(t)),i.setAttribute(`data-option-label`,e.label),n===`rows`){let a=J(`span`,`persona-ask-row-content`),o=J(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=J(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=bi(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},Si=e=>{let t=J(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return t.setAttribute(`aria-hidden`,`true`),t},Ci=(e,t,n,r)=>{let i=J(`div`,r===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);i.setAttribute(`role`,`group`),i.setAttribute(`data-ask-pill-list`,`true`);let a=!!e?.multiSelect,o=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(o.length===0&&!n){for(let e=0;e<ni;e++)i.appendChild(Si(r));return i}if(o.forEach((e,t)=>{i.appendChild(xi(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?Jr:Yr;if(r===`rows`){let n=J(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);n.setAttribute(`data-ask-user-action`,`focus-free-text`),n.setAttribute(`data-option-index`,String(o.length)),n.setAttribute(`data-ask-other-row`,`true`);let s=J(`span`,`persona-ask-row-content`),c=document.createElement(`input`);c.type=`text`,c.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,c.placeholder=t.freeTextPlaceholder??Xr,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=bi(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=J(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);n.type=`button`,n.setAttribute(`data-ask-user-action`,`open-free-text`),n.textContent=t.freeTextLabel??e,i.appendChild(n)}}return i},wi=(e,t)=>{let n=J(`div`,t===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);n.setAttribute(`data-ask-free-text-row`,`true`);let r=document.createElement(`input`);if(r.type=`text`,r.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,r.placeholder=e.freeTextPlaceholder??Xr,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=J(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??Zr,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},Ti=e=>{let t=J(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=J(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??Zr,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},Z=(e,t,n)=>{let r=J(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-nav-row`,`true`);let i=J(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??$r,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=J(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=J(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??ti,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=J(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??ei:n.nextLabel??Qr,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},Ei=e=>{let t=e.getAttribute(ai);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},Di=(e,t)=>{e.setAttribute(ai,JSON.stringify(t))},Oi=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ki=(e,t)=>{e.setAttribute(ri,String(Math.max(0,Math.floor(t))))},Ai=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ji=e=>e.getAttribute(oi)===`true`,Mi=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},Ni=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!=`number`||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Pi=(e,t)=>{let{payload:n}=mi(t),r=hi(n),i=Ei(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},Fi=e=>{let t=Ei(e)[Oi(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},Ii=e=>{if(!ji(e))return;let t=Ei(e)[Oi(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},Li=(e,t,n)=>{let r=pi(n),i=li(e),{payload:a,complete:o}=mi(t),s=ji(e),c=Oi(e),l=Ai(e),u=s?_i(a,c):gi(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let h=e.querySelector(`[data-ask-pill-list="true"]`);if(h){let e=Ci(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(wi(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(Ti(r)):(!d||s)&&g&&g.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let _=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=Z(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Fi(e),Ii(e)},Ri=(e,t,n)=>{let r=pi(t),i=ci(r),a=e.toolCall.id,o=hi(n),s=Math.max(1,o.length),c=s>1,l=Mi(e,o),u=c?Ni(e,s):0,d=J(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(qr,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(ii,String(s)),d.setAttribute(ri,String(u)),d.setAttribute(oi,c?`true`:`false`),d.setAttribute(si,i),Di(d,l),d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,`Suggested answers`),r.slideInMs!==void 0&&d.style.setProperty(`--persona-ask-sheet-duration`,`${r.slideInMs}ms`),yi(d,t);let f=J(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=J(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=J(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=J(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return h.setAttribute(`data-ask-pill-list`,`true`),h.setAttribute(`role`,`group`),d.appendChild(h),i!==`rows`&&d.appendChild(wi(r,i)),Li(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Q=(e,t,n)=>{yi(e,n);let{payload:r}=mi(t),i=Math.max(1,hi(r).length);i>Ai(e)&&(e.setAttribute(ii,String(i)),i>1&&!ji(e)&&e.setAttribute(oi,`true`)),Li(e,t,n)},zi=(e,t)=>{let n=J(`div`,`persona-ask-stub persona-inline-flex persona-items-center persona-gap-2`);n.id=`bubble-${e.id}`,n.setAttribute(`data-message-id`,e.id),n.setAttribute(`data-bubble-type`,`ask-user-question`),yi(n,t);let r=J(`span`,`persona-ask-stub-label`),{complete:i}=mi(e);return r.textContent=i?`Awaiting your response…`:`Preparing options…`,n.appendChild(r),n},Bi=(e,t,n)=>{if(!n||!fi(e)||pi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${qr}]`).forEach(e=>{e.getAttribute(qr)!==r&&e.remove()});let i=n.querySelector(`[${qr}="${di(r)}"]`);if(i){Q(i,e,t);return}let{payload:a}=mi(e),o=Ri(e,t,a);n.appendChild(o)},Vi=(e,t)=>{if(!e)return;let n=t?`[${qr}="${di(t)}"]`:`[${qr}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Hi=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),Ui=(e,t)=>{let n=Ei(e),r=Oi(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Di(e,n),Fi(e),Ii(e)},Wi=(e,t,n,r)=>{let i=Ai(e),a=Math.max(0,Math.min(i-1,r));ki(e,a),Li(e,t,n)}})),Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra=B((()=>{Ki=`suggest_replies`,qi={type:`object`,properties:{suggestions:{type:`array`,minItems:1,maxItems:4,description:`1-4 short, distinct follow-up replies, phrased in the user's voice.`,items:{type:`object`,properties:{label:{type:`string`,minLength:1,maxLength:80},prompt:{type:`string`,minLength:1,maxLength:500},description:{type:`string`,minLength:1,maxLength:160}},required:[`label`],additionalProperties:!1}}},required:[`suggestions`],additionalProperties:!1},Ji={name:Ki,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:qi,origin:`sdk`,annotations:{readOnlyHint:!0}},Yi=e=>{let t=e?.suggestions?.followUps?.maxItems,n=typeof t==`number`&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return n===4?Ji:{...Ji,parametersSchema:{...qi,properties:{suggestions:{...qi.properties.suggestions,maxItems:n,description:`1-${n} short, distinct follow-up replies, phrased in the user's voice.`}}}}},Xi=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Zi=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Qi=(e,t=4)=>{let n=e;if(typeof n==`string`)try{n=JSON.parse(n)}catch{return[]}let r=n?.suggestions;if(!Array.isArray(r))return[];let i=r.flatMap(e=>{if(typeof e==`string`){let t=e.trim();return t?[t]:[]}if(!e||typeof e!=`object`)return[];let t=e;if(typeof t.label!=`string`||!t.label.trim())return[];let n={label:t.label.trim()};return typeof t.prompt==`string`&&t.prompt.trim()&&(n.prompt=t.prompt.trim()),typeof t.description==`string`&&t.description.trim()&&(n.description=t.description.trim()),[n]});return i.length>t?(console.warn(`[persona] suggest_replies: ${i.length} suggestions exceeds the cap of ${t}; extra suggestions dropped.`),i.slice(0,t)):i},$i=(e,t=4)=>{for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role===`user`)return null;if(!Zi(r))continue;let i=Qi(r.toolCall?.args,t);return i.length>0?i:null}return null},ea=/* @__PURE__ */ new Set,ta=(e,t,n)=>{let r=`${e}:${t}:${n}`;ea.has(r)||(ea.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},na=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],i=n?.[e];r!==void 0&&i!==void 0&&r!==i&&ta(e,i,r)};e&&(r(`enabled`),r(`expose`));let i=t?.enabled??n?.enabled??!0;return{enabled:i,expose:i?t?.expose??n?.expose??!1:!1}}})),ia,aa,oa,sa=B((()=>{Gi(),ra(),ia={type:`object`,properties:{questions:{type:`array`,minItems:1,maxItems:8,description:`Questions to ask the user. Prefer a single question.`,items:{type:`object`,properties:{question:{type:`string`,description:`The complete question, ending with a question mark.`},header:{type:`string`,maxLength:12,description:`Short topic label, e.g. "Auth method".`},options:{type:`array`,minItems:2,maxItems:4,description:`2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.`,items:{type:`object`,properties:{label:{type:`string`,description:`Concise choice text (1-5 words).`},description:{type:`string`,description:`What the option means or implies.`}},required:[`label`],additionalProperties:!1}},multiSelect:{type:`boolean`,description:`Allow selecting multiple options. Default false.`},allowFreeText:{type:`boolean`,description:`Show a free-text input. Default true.`}},required:[`question`,`options`],additionalProperties:!1}}},required:[`questions`],additionalProperties:!1},aa={name:Kr,description:`Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.`,parametersSchema:ia,origin:`sdk`,annotations:{readOnlyHint:!0}},oa=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(aa),na(e).expose&&t.push(Yi(e)),t}})),ca,la,ua,da=B((()=>{ca={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},la=1e5,ua=100001}));async function fa(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function pa(e,t,n,r){let i=e.isClientTokenMode(),a=i?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,o,s=null;if(i){let t=await e.initSession();o=t.sessionId,t.durableRecovery?.enabled===!0&&(s=await e.readVisitorToken())}let c={"Content-Type":`application/json`,...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(c,await e.getHeaders());let l={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(o&&(l.sessionId=o,r?.assistantMessageId&&(l.assistantMessageId=r.assistantMessageId)),i&&o){let t=[...oa(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(o,t,t=>{let n={...l,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(a,{method:`POST`,headers:c,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&i(),n}return fetch(a,{method:`POST`,headers:c,body:JSON.stringify(l),signal:r?.signal})}var ma=B((()=>{sa(),da()})),ha=/* @__PURE__ */ Vt({preferFinalStructuredContent:()=>_a,resolveApproval:()=>fa,resumeFlow:()=>pa,streamResponse:()=>ya});function ga(e){let t=e.toLowerCase(),n=t===`text/plain`?`txt`:t===`text/markdown`?`md`:void 0;if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}function _a(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(!n)return t;if(!r)return e;let i=xa(n);if(!xa(r))return e;if(!i||r.startsWith(n))return t;let a=nr(e);return nr(t)!==null&&a===null?t:e}async function va(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function ya(e,t,n,r,i,a,o,s){let c=e.streamGeneration(),l=t.getReader();e.streamReaders.add(l);let u=!!e.config().backgroundConversations,d=()=>{u&&l.cancel().catch(()=>{})};a?.addEventListener(`abort`,d,{once:!0});let f=new TextDecoder,p=``,m=Date.now(),h=0,g=()=>m+h++,_=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),v=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?_(e.toolCall):void 0,tools:e.tools?.map(_)}),y=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},b=t=>{!a?.aborted&&c===e.streamGeneration()&&y(t)&&n({type:`message`,message:v(t)})},x=null,S=null,C={current:null},ee={current:null},w=null,T=``,E=new Map(s?.textPhases),te=/* @__PURE__ */ new Map,D=/* @__PURE__ */ new Map,ne=/* @__PURE__ */ new Map,re=/* @__PURE__ */ new Map,ie=/* @__PURE__ */ new Map,ae=r,oe=!1,O=o?.find(e=>e.id===r);O&&(x=v(O),x.streaming=s?.openAssistant??!0,oe=!0,w=O.agentMetadata?.textBlockId??null,T=O.rawContent??O.content,S=x,s&&!s.openAssistant&&(x=null)),s&&(w=s.textBlockId,T=s.rawText,s.nestedParents.forEach(([e,t])=>te.set(e,t)),s.nestedRaw.forEach(([e,t])=>ne.set(e,t)));for(let e of o??[]){e.variant===`tool`&&e.toolCall?.id&&ie.set(e.toolCall.id,v(e)),e.variant===`reasoning`&&e.reasoning?.id&&re.set(e.reasoning.id,v(e));let t=e.agentMetadata?.textBlockId;t&&(D.set(t,e.id===x?.id?x:v(e)),e.agentMetadata?.phase&&E.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&(te.set(t,n),ne.set(t,e.rawContent??e.content))}let se=()=>{if(x)return x;let e,t=``,n=w;return!oe&&ae?(e=ae,oe=!0,t=i??``):e=ae&&n?`${ae}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g()},b(x),x},ce=(e,t)=>{let n=re.get(e);if(n)return n;let r={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,agentMetadata:{executionId:t},sequence:g(),reasoning:{id:e,status:`streaming`,chunks:[]}};return re.set(e,r),b(r),r},k=/* @__PURE__ */ new Set,le=/* @__PURE__ */ new Map,ue=/* @__PURE__ */ new Set;for(let e of o??[])if(e.id.startsWith(`artifact-ref-`)){let t=e.id.slice(13);ue.add(t),le.set(t,v(e))}s?.artifactTools.forEach(e=>k.add(e));let de=/* @__PURE__ */ new Map;s?.artifactContent.forEach(([e,t])=>de.set(e,{...t}));let fe=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},pe=(e,t,n)=>{let r=ie.get(e),i={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(Ee||void 0)};if(r)return r.agentMetadata=i,r;let a={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,agentMetadata:i,sequence:g(),toolCall:{id:e,status:`pending`}};return ie.set(e,a),b(a),a},me=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},he=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},A=/* @__PURE__ */ new Map,ge=/* @__PURE__ */ new Map,_e=(e,t)=>{let n=he(t),r=_a(ge.get(e.id),n);e.rawContent=r;let i=A.get(e.id),a=t=>{let n=e.content??``;t.trim()!==``&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{let t=i?.close?.();t instanceof Promise&&t.catch(()=>{}),A.delete(e.id),ge.delete(e.id),e.streaming=!1,b(e)};if(!i){a(n),o();return}let s=nr(r);if(s!==null&&s.trim()!==``){a(s),o();return}let c=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let r=i.getExtractedText();return r!==null&&r.trim()!==``?r:n},l;try{l=i.processChunk(r)}catch{a(n),o();return}l instanceof Promise?l.then(e=>{a(c(e)),o()}).catch(()=>{a(n),o()}):(a(c(l)),o())},ve=null,ye=o?.find(e=>e.id===s?.sealedFlowMessageId);ye&&(ve=v(ye));let be=(t,n,r)=>{t.rawContent=n,A.has(t.id)||A.set(t.id,e.createStreamParser());let i=A.get(t.id),a=/^[{[]/.test(n.trim());a&&ge.set(t.id,n);let o=()=>{t.content+=r,ge.delete(t.id),A.delete(t.id),t.rawContent=void 0,b(t)};if(i.__isPlainTextParser===!0){o();return}let s=e=>{let r=typeof e==`string`?e:e?.text??null;r!==null&&r.trim()!==``?(t.content=r,b(t)):!a&&!n.trim().startsWith(`<`)&&o()},c=i.processChunk(n);c instanceof Promise?c.then(s).catch(o):s(c)},xe=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,b(e);return}let r=ge.get(e.id)??he(n);e.rawContent=r;let i=A.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=nr(r)),a===null)){let t=i.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,A.delete(e.id),ge.delete(e.id),b(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:ge.has(e.id)||(e.content=he(n));let t=A.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),A.delete(e.id)}ge.delete(e.id),e.streaming=!1,b(e)}},Se=(e,t,n,r)=>{let i=D.get(e);if(i)return i;let a={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:E.get(e)}};return D.set(e,a),b(a),a},Ce=[],we,Te=/* @__PURE__ */ new Map;s?.media.forEach(([e,t])=>Te.set(e,{...t,parts:[...t.parts]}));let Ee=s?.iteration??0,De=s?.executionKind??`agent`,j=s?.executionKindResolved??!1,Oe=s?.turnId??null,M=null,ke=e.config().iterationDisplay??`separate`;we=()=>{for(let t=0;t<Ce.length;t++){let r=Ce[t];if(!j&&De!==`flow`&&typeof r.stepType==`string`&&(De=`flow`),r.type===`reasoning_start`){let e=typeof r.id==`string`?r.id:null,t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){te.set(e,t),Se(e,t,`reasoning`,r.executionId);continue}let n=r.id,i=ce(n,r.executionId);i.reasoning=i.reasoning??{id:n,status:`streaming`,chunks:[]},i.reasoning.startedAt=i.reasoning.startedAt??Date.now(),i.reasoning.completedAt=void 0,i.reasoning.durationMs=void 0,(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),i.streaming=!0,i.reasoning.status=`streaming`,b(i)}else if(r.type===`reasoning_delta`){let e=typeof r.id==`string`?r.id:null;if(e&&te.has(e)&&D.has(e)){let t=D.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=r.id,n=ce(t,r.executionId);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),r.delta&&n.reasoning.chunks.push(r.delta),n.reasoning.status=`streaming`,n.streaming=!0,b(n)}else if(r.type===`reasoning_complete`){let e=typeof r.id==`string`?r.id:null;if(e&&te.has(e)&&D.has(e)){let t=D.get(e);if(t.reasoning){let e=typeof r.text==`string`?r.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,b(t)}te.delete(e),D.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!re.get(t)&&(n||r.scope===`loop`)&&ce(t,r.executionId);let i=re.get(t);if(i?.reasoning){(r.scope===`loop`||r.scope===`turn`)&&(i.reasoning.scope=r.scope),n&&i.reasoning.chunks.length===0&&i.reasoning.chunks.push(n),i.reasoning.status=`complete`,i.reasoning.completedAt=Date.now();let e=i.reasoning.startedAt??Date.now();i.reasoning.durationMs=Math.max(0,(i.reasoning.completedAt??Date.now())-e),i.streaming=!1,b(i)}}else if(r.type===`tool_start`){x&&=(x.streaming=!1,b(x),null),typeof r.iteration==`number`&&(Ee=r.iteration);let e=r.toolCallId,t=r.toolName;if(fe(t)){k.add(e);continue}let n=pe(e,r.executionId,r.iteration),i=n.toolCall??{id:e,status:`pending`};i.name=t??i.name,i.status=`running`,i.success=void 0,i.error=void 0,i.duration=void 0,r.parameters!==void 0&&(i.args=r.parameters),i.startedAt=i.startedAt??me(r.startedAt),i.completedAt=void 0,i.durationMs=void 0,n.toolCall=i,n.streaming=!0,b(n)}else if(r.type===`tool_output_delta`){let e=r.toolCallId;if(k.has(e))continue;let t=pe(e,r.executionId),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let i=r.delta;i&&(n.chunks=n.chunks??[],n.chunks.push(String(i))),n.status=`running`,t.toolCall=n,t.streaming=!0,b(t)}else if(r.type===`tool_complete`){let e=r.toolCallId;if(k.has(e)){k.delete(e);continue}let t=pe(e,r.executionId,r.iteration),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,r.result!==void 0&&(n.result=r.result),n.name=r.toolName??n.name,n.success=r.success,n.error=r.error,n.completedAt=Date.now();let i=r.executionTime;if(typeof i==`number`)n.durationMs=i,n.duration=i;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,b(t)}else if(r.type===`await`&&r.toolName){let e=typeof r.toolCallId==`string`&&r.toolCallId.length>0?r.toolCallId:void 0,t=e??r.toolId??`local-${g()}`,n=pe(t,r.executionId),i=r.toolName,a=r.origin===`webmcp`&&!Wn(i)?`webmcp:${i}`:i,o=Wn(a),s=n.toolCall??{id:t,status:`pending`};s.name=a,s.args=r.parameters,s.status=o?`running`:`complete`,s.chunks=s.chunks??[],s.startedAt=s.startedAt??me(r.awaitedAt),o?(s.completedAt=void 0,s.duration=void 0,s.durationMs=void 0):s.completedAt=s.completedAt??s.startedAt,n.toolCall=s,n.streaming=!1,n.agentMetadata={...n.agentMetadata,executionId:r.executionId??n.agentMetadata?.executionId,awaitingLocalTool:!0,...e?{webMcpToolCallId:e}:{}},b(n)}else if(r.type===`text_start`){let e=typeof r.id==`string`?r.id:null;if(e){let t=ba(r.phase);t?E.set(e,t):E.delete(e)}let t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){te.set(e,t);continue}let n=x;n&&(De===`flow`?(xe(n),ve=n):(n.streaming=!1,b(n)),x=null),w=e??w,T=``}else if(r.type===`text_delta`){let e=typeof r.id==`string`?r.id:null,t=e?te.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(ne.get(e)??``)+n;if(ne.set(e,i),i.trim()===``)continue;let a=Se(e,t,void 0,r.executionId);be(a,i,n);continue}w=e??w;let n=typeof r.delta==`string`?r.delta:``;if(T+=n,De===`flow`&&T.trim()===``)continue;let i=se();i.agentMetadata={textBlockId:w??void 0,phase:E.get(w??``),executionId:r.executionId,iteration:Ee,...De===`flow`?{}:{turnId:Oe??void 0,agentName:M?.agentName}},w&&D.set(w,i),be(i,T,n),S=i}else if(r.type===`text_complete`){let e=typeof r.id==`string`?r.id:null;e&&E.delete(e);let t=e?D.get(e):x,n=ba(r.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&te.has(e)){let t=D.get(e);t&&xe(t),te.delete(e),ne.delete(e),D.delete(e);continue}if(e&&t!==x){t&&(t.streaming=!1,b(t));continue}let i=x;i&&(De===`flow`?(xe(i),ve=i):((i.content??``)===``&&typeof r.text==`string`&&(i.content=r.text),i.streaming=!1,b(i)),x=null),w=null,T=``}else if(r.type===`step_complete`){if(r.stepType===`tool`)continue;if(r.success===!1){let e=r.error||`Step failed`;n({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),n({type:`status`,status:`idle`});continue}{let e=ve;ve=null;let t=r.stopReason,n=(r.result&&typeof r.result==`object`?r.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(A.delete(e.id),ge.delete(e.id),e.streaming=!1,b(e)):_e(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=se();t&&(r.stopReason=t),e?xe(r,n):(r.streaming=!1,b(r))}}continue}}else if(r.type===`execution_start`)De=r.kind===`flow`?`flow`:`agent`,j=!0,e.config().backgroundConversations&&n({type:`status`,status:`connected`,executionId:r.executionId}),De===`agent`&&(M={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:Ee;if(e!==Ee){if(ke===`separate`&&e>1){let e=x;e&&(e.streaming=!1,b(e),x=null)}Ee=e}Oe=typeof r.id==`string`?r.id:null,S=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=ie.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(r.delta??``),b(t))}}else if(r.type===`tool_input_complete`){if(k.has(r.toolCallId))continue;let e=pe(r.toolCallId,r.executionId),t=e.toolCall;t.args=r.parameters,t.name=r.toolName??t.name,b(e)}else if(r.type===`turn_complete`){let e=r.stopReason,t=x??S;if(e&&t!==null){let n=r.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,b(t))}Oe===r.id&&(Oe=null)}else if(r.type===`media_start`){let e=String(r.id);Te.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=Te.get(String(r.id));e&&typeof r.delta==`string`&&e.parts.push(r.delta)}else if(r.type===`media_complete`){let e=String(r.id),t=Te.get(e);Te.delete(e);let n=(typeof r.mediaType==`string`?r.mediaType:void 0)??t?.mediaType??`application/octet-stream`,i=typeof r.data==`string`?r.data:void 0,a=typeof r.url==`string`?r.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(i)o={type:`media`,data:i,mediaType:n};else if(a){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:a,mediaType:n}}let s=r.toolCallId??t?.toolCallId,c=o?[o]:[],l=[];for(let e of c){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))l.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))l.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))l.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;l.push({type:`file`,data:i,mimeType:e,filename:ga(e)})}}}if(l.length>0){let e=g(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:l,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:r.executionId,iteration:Ee}};b(n);let i=x;i&&(i.streaming=!1,b(i)),x=null,C.current=null}}else if(r.type===`execution_complete`){let e=x;e&&(r.kind===`flow`&&e.streaming!==!1?xe(e):(e.streaming=!1,b(e)),x=null),w=null,T=``,ve=null,n({type:`status`,status:r.success===!1?`error`:`idle`,terminal:!0})}else if(r.type===`execution_error`){let e=typeof r.error==`string`?r.error:r.error?.message??`Execution error`;n({type:`error`,error:Error(e)})}else if(r.type!==`ping`){if(r.type===`approval_start`){let e=r.approvalId??`approval-${g()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:g(),approval:{id:e,status:`pending`,agentId:M?.agentId??`virtual`,executionId:r.executionId??M?.executionId??``,toolName:r.toolName??``,toolType:r.toolType,description:r.description??`Execute ${r.toolName??`tool`}`,...typeof r.reason==`string`&&r.reason?{reason:r.reason}:{},parameters:r.parameters,...typeof r.toolCallId==`string`&&r.toolCallId?{toolCallId:r.toolCallId}:{}}};b(t)}else if(r.type===`approval_complete`){let e=r.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:g(),approval:{id:e,status:r.decision??`approved`,agentId:M?.agentId??`virtual`,executionId:r.executionId??M?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};b(t)}}else if(r.type===`artifact_start`||r.type===`artifact_delta`||r.type===`artifact_update`||r.type===`artifact_complete`){if(r.type===`artifact_start`){let t=r.artifactType,i=String(r.id),a=typeof r.title==`string`?r.title:void 0,o=r.file,s;if(o&&typeof o==`object`&&!Array.isArray(o)&&typeof o.path==`string`&&typeof o.mimeType==`string`&&(s={path:o.path,mimeType:o.mimeType,...typeof o.language==`string`?{language:o.language}:{}}),n({type:`artifact_start`,id:i,artifactType:t,title:a,component:typeof r.component==`string`?r.component:void 0,...s?{file:s}:{}}),de.set(i,{markdown:``,title:a,file:s}),!ue.has(i)){ue.add(i);let n=Xn(e.config().features?.artifacts,{artifactType:t,...s?{file:s}:{}}),o=typeof r.component==`string`?r.component:void 0,c={id:`artifact-ref-${i}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:g(),rawContent:Zn(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};le.set(i,c),b(c)}}else if(r.type===`artifact_delta`){let e=String(r.id),t=typeof r.delta==`string`?r.delta:String(r.delta??``);n({type:`artifact_delta`,id:e,artDelta:t});let i=de.get(e);i&&(i.markdown+=t)}else if(r.type===`artifact_update`){let e=r.props&&typeof r.props==`object`&&!Array.isArray(r.props)?r.props:{};n({type:`artifact_update`,id:String(r.id),props:e,component:typeof r.component==`string`?r.component:void 0});let t=de.get(String(r.id));t&&(t.props={...t.props??{},...e})}else if(r.type===`artifact_complete`){let e=String(r.id);n({type:`artifact_complete`,id:e});let t=le.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=de.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}de.delete(e),b(t),le.delete(e)}}}else if(r.type===`error`&&r.recoverable===!1&&r.error!=null&&r.error!==``){let e=typeof r.error==`string`?r.error:r.error?.message==null?`Execution error`:String(r.error.message);n({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),n({type:`status`,status:`idle`})}}}Ce.length=0};try{for(;;){if(c!==e.streamGeneration())return;a?.throwIfAborted();let{done:t,value:r}=await l.read();if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),t)break;p+=f.decode(r,{stream:!0});let i=p.split(`
|
|
6
6
|
|
|
7
7
|
`);p=i.pop()??``;for(let t of i){if(c!==e.streamGeneration())return;a?.throwIfAborted();let r=t.split(`
|
|
8
|
-
`),i=`message`,o=``,s=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?o+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(s=e.slice(3).trim());let l=()=>{s!==null&&s!==``&&n({type:`cursor`,id:s,...e.config().backgroundConversations?{checkpoint:{textBlockId:w,openAssistant:x!==null,sealedFlowMessageId:ve?.id??null,rawText:T,executionKind:De,executionKindResolved:j,turnId:Oe,iteration:Ee,textPhases:[...E],nestedParents:[...te],nestedRaw:[...ne],media:[...Te].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...de].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...k]}}:{}})};if(!o){l();continue}let u;try{u=JSON.parse(o)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let d=typeof u==`object`&&u&&!Array.isArray(u)?u:null,f=i===`message`?typeof d?.type==`string`?d.type:`message`:i;if(e.onSSEEvent?.(f,u),e.parseSSEEvent){C.current=x;let t=await va(e,u,n,C,b,g,ee);if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),C.current&&C.current!==x&&(x=C.current),t){l();continue}}d&&(Ce.push({...d,type:f}),we()),l()}}we()}finally{e.streamReaders.delete(l),a?.removeEventListener(`abort`,d),l.releaseLock()}}var ba,xa,Sa=B((()=>{Kn(),q(),cr(),ma(),ba=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0,xa=e=>/^[{[<]/.test(e)}));Sa(),H();const{setLoader:Ca,load:wa,provide:Ta,getSync:Ea}=V({fallbackImport:()=>Promise.resolve().then(()=>(Sa(),ha))}),Da=wa,Oa=Ta,ka=Ea;Oa(ha);var Aa=`4.32.1`,ja,Ma=B((()=>{ja=Aa})),Na=/* @__PURE__ */ Vt({deleteAllConversations:()=>$,deleteConversation:()=>qa,finalizeDisplayProjections:()=>Ka,getConversation:()=>Ga,historyErrorFor:()=>Ba,listConversations:()=>Wa,readErrorCode:()=>Ra,recoverFromUnauthorized:()=>za,resetVisitor:()=>Ja});function Pa(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Fa(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Ia(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function La(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);return i}async function Ra(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function za(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,eo);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,to);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Ba(e,t,n){let r=await Ra(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,eo):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,to):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function Va(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Ha(e,t,n){Ua(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Fa(e,n.scope)===`verified-user`&&(a=await Ia(e,i,r),a&&(i=await La(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Pa(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":ja,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await za(e,await Ra(e,u),a,r);continue}if(!u.ok)throw await Ba(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return Va(e,d,a!==null,r),f}}function Ua(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function Wa(e,t){let n=await Ha(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Za),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Ga(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Za(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Ka(e,t,n){Ua(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Ya)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Ya} character limit`);r+=n}if(r>Xa)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${Xa} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ha(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=Xa,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function qa(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function $(e,t){let n=await Ha(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function Ja(e){Ua(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ha(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Ya,Xa,Za,Qa,$a,eo,to,no=B((()=>{Ma(),Ya=32768,Xa=49152,Za=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},Qa=`The identity proof was not admitted; account history is unavailable`,$a=`The identity proof was rejected`,eo=`The request carried no visitor credential`,to=`The stored visitor belongs to a different signed-in user`}));no(),H();const{setLoader:ro,load:io,provide:ao}=V({fallbackImport:()=>Promise.resolve().then(()=>(no(),Na))}),oo=io;ao(Na);var so,co=B((()=>{Gi(),so=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(i,a,o)=>{let s=a.trim();if(!s||!r.current)return;let c=i.getAttribute(`data-tool-call-id`)??``,l=o.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{instanceId:e.instanceId,toolUseId:c,answer:s,answers:o.structured,values:o.values??(o.source===`multi`?s.split(`, `):[s]),isFreeText:l,source:o.source},bubbles:!0,composed:!0})),Vi(n,c);let u=r.current.getMessages().find(e=>e.toolCall?.id===c);u?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(u,o.structured??s):r.current.sendMessage(s)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Pi(e,i),currentIndex:Oi(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Oi(t);if(n>=Ai(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Wi(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let i=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:i},bubbles:!0,composed:!0})),Vi(n,i);let a=r.current?.getMessages().find(e=>e.toolCall?.id===i);a?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(a),r.current?.resolveAskUserQuestion(a,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=ji(u);if(n&&t){let t=Ei(u)[Oi(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Ui(u,Array.from(n)),a(u);return}if(n){Ui(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Hi(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Hi(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(ji(u)){Ui(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Ei(u)[Oi(u)];(typeof e!=`string`||e!==i)&&Ui(u,i)}let o=d===`next`?1:-1,s=Oi(u)+o;Wi(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Ui(u,n);let a=Pi(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Oi(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=ji(u),d=Oi(u),f=d>=Ai(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:s},bubbles:!0,composed:!0})),Vi(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Ui(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Pi(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Wi(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(ji(n)?(Ui(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function lo(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
|
|
8
|
+
`),i=`message`,o=``,s=null;for(let e of r)e.startsWith(`event:`)?i=e.replace(`event:`,``).trim():e.startsWith(`data:`)?o+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(s=e.slice(3).trim());let l=()=>{s!==null&&s!==``&&n({type:`cursor`,id:s,...e.config().backgroundConversations?{checkpoint:{textBlockId:w,openAssistant:x!==null,sealedFlowMessageId:ve?.id??null,rawText:T,executionKind:De,executionKindResolved:j,turnId:Oe,iteration:Ee,textPhases:[...E],nestedParents:[...te],nestedRaw:[...ne],media:[...Te].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...de].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...k]}}:{}})};if(!o){l();continue}let u;try{u=JSON.parse(o)}catch(e){n({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let d=typeof u==`object`&&u&&!Array.isArray(u)?u:null,f=i===`message`?typeof d?.type==`string`?d.type:`message`:i;if(e.onSSEEvent?.(f,u),e.parseSSEEvent){C.current=x;let t=await va(e,u,n,C,b,g,ee);if(c!==e.streamGeneration())return;if(a?.throwIfAborted(),C.current&&C.current!==x&&(x=C.current),t){l();continue}}d&&(Ce.push({...d,type:f}),we()),l()}}we()}finally{e.streamReaders.delete(l),a?.removeEventListener(`abort`,d),l.releaseLock()}}var ba,xa,Sa=B((()=>{Kn(),q(),cr(),ma(),ba=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0,xa=e=>/^[{[<]/.test(e)}));Sa(),H();const{setLoader:Ca,load:wa,provide:Ta,getSync:Ea}=V({fallbackImport:()=>Promise.resolve().then(()=>(Sa(),ha))}),Da=wa,Oa=Ta,ka=Ea;Oa(ha);var Aa=`4.32.2`,ja,Ma=B((()=>{ja=Aa})),Na=/* @__PURE__ */ Vt({deleteAllConversations:()=>$,deleteConversation:()=>qa,finalizeDisplayProjections:()=>Ka,getConversation:()=>Ga,historyErrorFor:()=>Ba,listConversations:()=>Wa,readErrorCode:()=>Ra,recoverFromUnauthorized:()=>za,resetVisitor:()=>Ja});function Pa(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function Fa(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function Ia(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function La(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);return i}async function Ra(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function za(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,eo);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,to);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function Ba(e,t,n){let r=await Ra(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,Qa);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,$a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,eo):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,to):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function Va(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function Ha(e,t,n){Ua(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Fa(e,n.scope)===`verified-user`&&(a=await Ia(e,i,r),a&&(i=await La(e,i,a,r)));let o=e.historyInternals.visitorStore,s=!1;for(;;){let c=o?.revision()??0,l=await e.readVisitorToken();if(!l&&!n.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let u=await fetch(Pa(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":ja,...l?{"X-Visitor-Token":l}:{},...a?{"X-Identity-Proof":a}:{},...n.body===void 0?{}:{"Content-Type":`application/json`}},...n.body===void 0?{}:{body:JSON.stringify(n.body)},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!s){s=!0,i=await za(e,await Ra(e,u),a,r);continue}if(!u.ok)throw await Ba(e,u,r);let d=u.headers.get(`X-History-Identity-Status`),f=await u.json().catch(()=>void 0);if(o&&o.revision()!==c)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return Va(e,d,a!==null,r),f}}function Ua(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function Wa(e,t){let n=await Ha(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Za),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Ga(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Za(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function Ka(e,t,n){Ua(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Ya)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Ya} character limit`);r+=n}if(r>Xa)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${Xa} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ha(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=Xa,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function qa(e,t,n){let r=await Ha(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function $(e,t){let n=await Ha(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function Ja(e){Ua(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ha(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Ya,Xa,Za,Qa,$a,eo,to,no=B((()=>{Ma(),Ya=32768,Xa=49152,Za=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},Qa=`The identity proof was not admitted; account history is unavailable`,$a=`The identity proof was rejected`,eo=`The request carried no visitor credential`,to=`The stored visitor belongs to a different signed-in user`}));no(),H();const{setLoader:ro,load:io,provide:ao}=V({fallbackImport:()=>Promise.resolve().then(()=>(no(),Na))}),oo=io;ao(Na);var so,co=B((()=>{Gi(),so=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(i,a,o)=>{let s=a.trim();if(!s||!r.current)return;let c=i.getAttribute(`data-tool-call-id`)??``,l=o.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{instanceId:e.instanceId,toolUseId:c,answer:s,answers:o.structured,values:o.values??(o.source===`multi`?s.split(`, `):[s]),isFreeText:l,source:o.source},bubbles:!0,composed:!0})),Vi(n,c);let u=r.current.getMessages().find(e=>e.toolCall?.id===c);u?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(u,o.structured??s):r.current.sendMessage(s)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:Pi(e,i),currentIndex:Oi(e)})},o=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),s=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=Oi(t);if(n>=Ai(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Wi(t,i,e.config(),n+1),a(t))};return{click:c=>{let l=c.target.closest(`[data-ask-user-action]`);if(!l)return;let u=l.closest(`[data-persona-ask-sheet-for]`);if(!u)return;let d=l.getAttribute(`data-ask-user-action`);if(c.preventDefault(),c.stopPropagation(),d===`dismiss`){let i=u.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:i},bubbles:!0,composed:!0})),Vi(n,i);let a=r.current?.getMessages().find(e=>e.toolCall?.id===i);a?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(a),r.current?.resolveAskUserQuestion(a,`(dismissed)`))}else if(d===`pick`){let e=l.getAttribute(`data-option-label`);if(!e)return;let t=u.getAttribute(`data-multi-select`)===`true`,n=ji(u);if(n&&t){let t=Ei(u)[Oi(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Ui(u,Array.from(n)),a(u);return}if(n){Ui(u,e),a(u),s(u);return}if(t){let e=l.getAttribute(`aria-pressed`)===`true`;l.setAttribute(`aria-pressed`,e?`false`:`true`),l.classList.toggle(`persona-ask-pill-selected`,!e);let t=u.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=Hi(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=Hi(u);if(e.length===0)return;i(u,e.join(`, `),{source:`multi`,values:e})}else if(d===`open-free-text`){let e=u.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(d===`focus-free-text`)u.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(d===`submit-free-text`){let e=u.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(ji(u)){Ui(u,e.trim()),a(u),s(u);return}i(u,e,{source:`free-text`})}else if(d===`next`||d===`back`){if(!r.current)return;let t=u.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=Ei(u)[Oi(u)];(typeof e!=`string`||e!==i)&&Ui(u,i)}let o=d===`next`?1:-1,s=Oi(u)+o;Wi(u,n,e.config(),s),a(u)}else if(d===`submit-all`){if(!r.current)return;let e=u.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=u.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&Ui(u,n);let a=Pi(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:Oi(u)});let s=o(a);i(u,s||`(submitted)`,{source:`submit-all`,structured:a})}else if(d===`skip`){if(!r.current)return;let s=u.getAttribute(`data-tool-call-id`)??``,c=r.current.getMessages().find(e=>e.toolCall?.id===s);if(!c)return;let l=ji(u),d=Oi(u),f=d>=Ai(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:s},bubbles:!0,composed:!0})),Vi(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Ui(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Pi(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Wi(u,c,e.config(),d+1),a(u)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(ji(n)?(Ui(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function lo(e,t,n){if(n===`input-start`)return t===0;let r=t>0?e[t-1]:``;return n===`line-start`?r===``||r===`
|
|
9
9
|
`:r===``||mo.test(r)}function uo(e,t,n=`@`,r=`anywhere`,i=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let o=e[a];if(o===n)return lo(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
|
|
10
10
|
`||o===``||!i&&mo.test(o))return null;a--}return null}function fo(e,t,n){for(let r of n){let n=uo(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function po(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var mo,ho=B((()=>{mo=/\s/}));function go(e){return[{trigger:e.trigger??`@`,position:e.triggerPosition??`anywhere`,allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},...(e.triggers??[]).map(e=>({trigger:e.trigger,position:e.triggerPosition??`anywhere`,allowSpaces:e.allowSpaces??!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton===!0,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText}))]}var _o=B((()=>{})),vo=B((()=>{})),yo=B((()=>{}));function bo(e){e.delayMs!==void 0&&(Eo=ko(e.delayMs)),e.skipDelayMs!==void 0&&(Do=ko(e.skipDelayMs))}function xo(e){Mo.get(e)?.hide()}function So(e){Mo.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=Co,viewportPadding:s=wo}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,d=null,f=null,p=null,m,h=!1,g=!1,_=!1,v=()=>(typeof r==`function`?r():r).trim(),y=()=>(typeof i==`function`?i():i??``).trim(),b=()=>ko(e.delayMs??Eo),x=()=>ko(e.skipDelayMs??Do),S=()=>{m!==void 0&&(l().clearTimeout(m),m=void 0)},C=()=>{S();let e=u!==null;p?.(),p=null,u?.remove(),u=null,d=null,f=null,e&&jo(x())},ee=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=Io(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=Io(v,s,y),x=r.left+r.width/2,S=Math.max(To,i.width-To),C=Io(x-m,To,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},w=()=>{if(_||!a||u||!t.isConnected||No(t))return;let e=v(),n=Fo(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(ua);let o=i.getComputedStyle?.(t);if(o){for(let e of Lo){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}d=r.createElement(`span`),d.className=`persona-control-tooltip__label`,d.textContent=e,u.appendChild(d);let s=y();s&&(f=r.createElement(`span`),f.className=`persona-control-tooltip__hint`,f.textContent=s,u.appendChild(f));let m=r.createElement(`span`);m.className=`persona-control-tooltip__arrow`,u.appendChild(m),n.appendChild(u),ee(),u.dataset.state=`open`;let h=()=>{if(!t.isConnected){C();return}d&&(d.textContent=v()),f&&(f.textContent=y());let e=Fo(t);u&&e&&u.parentNode!==e&&e.appendChild(u),ee()};i.addEventListener(`scroll`,h,!0),i.addEventListener(`resize`,h);let g=t.closest(`[data-persona-root]`);g?.addEventListener(`persona:internal:host-moved`,h);let b=t.getRootNode(),x=Po(b)?b:r.documentElement,S=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||C()});S?.observe(x,{childList:!0,subtree:!0}),p=()=>{i.removeEventListener(`scroll`,h,!0),i.removeEventListener(`resize`,h),g?.removeEventListener(`persona:internal:host-moved`,h),S?.disconnect()}},T=e=>{_||u||(S(),e||b()<=0||Ao()?w():m=l().setTimeout(()=>{m=void 0,w()},b()))},E=()=>{h||g?T(g):C()},te=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,E())},D=()=>{h=!1,E()},ne=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}E()},re=()=>{g=!1,E()},ie=()=>{h=!1,g=!1,C()},ae=e=>{e.key===`Escape`&&ie()};n.addEventListener(`mouseenter`,te),n.addEventListener(`mouseleave`,D),t.addEventListener(`focus`,ne),t.addEventListener(`blur`,re),t.addEventListener(`keydown`,ae),t.addEventListener(`click`,ie);let oe={get isOpen(){return u!==null},show:w,hide:C,reposition:ee,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,te),n.removeEventListener(`mouseleave`,D),t.removeEventListener(`focus`,ne),t.removeEventListener(`blur`,re),t.removeEventListener(`keydown`,ae),t.removeEventListener(`click`,ie),Mo.delete(t))}};return Mo.set(t,oe),oe}var Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro=B((()=>{da(),vo(),yo(),Co=8,wo=8,To=10,Eo=400,Do=300,Oo=0,ko=e=>Math.max(0,e),Ao=()=>Date.now()<Oo,jo=e=>{Oo=e>0?Date.now()+e:0},Mo=/* @__PURE__ */ new WeakMap,No=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Po=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Fo=e=>{let t=e.getRootNode?.();return Po(t)?t:e.closest(`dialog[open]`)??e.ownerDocument.body},Io=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Lo=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),zo,Bo,Vo,Ho,Uo=B((()=>{Wr(),zo=(e,t,n,r)=>{let[i,a]=t.split(`.`);return[e?.theme,e?.darkTheme].some(e=>e?.components?.[i]?.[a]?.[n]!==void 0)?`var(--persona-components-${t.replace(`.`,`-`)}-${n}, ${r})`:r},Bo=(e,t)=>{let n=e&&Hr(e,t);return typeof n==`string`&&n?n:void 0},Vo=(e,t,n,r)=>{let i=t.startsWith(`var(`);e.classList.toggle(`persona-theme-padding`,i),e.style.padding=i?``:t,i?e.style.setProperty(`--persona-theme-padding`,t):e.style.removeProperty(`--persona-theme-padding`),n&&(e.style.paddingLeft=e.style.paddingRight=n),r&&(e.style.paddingTop=e.style.paddingBottom=r)},Ho=(e,t,n)=>{let r=t.startsWith(`var(`)&&t.includes(`--persona-components-`);e.classList.toggle(`persona-control-size`,r),r?e.style.setProperty(`--persona-control-size`,t):e.style.removeProperty(`--persona-control-size`),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=n??``}})),Wo,Go,Ko,qo=B((()=>{Wo=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Go=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Wo(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Ko=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}})),Jo,Yo,Xo,Zo,Qo=B((()=>{Jo={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,groupBoundary:`adjacent`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Yo={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Xo={layout:`row`,variant:`row`,iconVisibility:`active`,autoExpand:!1,grouped:!0,groupedMode:`collapsible`,groupAppearance:`inset`,loadingAnimation:`shimmer`},Zo={appearance:`inset`,layout:`row`,variant:`row`,iconVisibility:`active`,autoExpand:!1,loadingAnimation:`shimmer`}})),$o,es=B((()=>{$o={resolvedDisplay:`row`,primaryAction:`allow-once`,keyboardShortcuts:`focused`}})),ts,ns,rs,is,as,os,ss,cs,ls,us,ds=B((()=>{ts=Symbol(`persona.panelAliasProvenance`),ns=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),rs=(e,t)=>ns(e,t)&&e[t]!==void 0,is=e=>({launcherWidth:rs(e?.launcher,`width`),legacyLauncherWidth:rs(e,`launcherWidth`),sidebarWidth:rs(e?.launcher,`sidebarWidth`),dockWidth:rs(e?.launcher?.dock,`width`)}),as=e=>{let t=e?.[ts];return t?{...t}:is(e)},os=(e,t)=>(Object.defineProperty(e,ts,{value:t,enumerable:!0,configurable:!0}),e),ss=(e,t)=>os(e,as(t)),cs=(e,t)=>{let n=t[ts];if(n)return{...n};let r=as(e);return ns(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),ns(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(ns(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),ns(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),ns(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:ns(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)},ls=e=>e?.layout?.embedded===!0&&e.launcher?.enabled===!1&&!e.launcher.sidebarMode&&(e.launcher.mountMode??`floating`)===`floating`,us=e=>e?.layout?.showHeader??!ls(e)}));function fs(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function ps(e){let t=fs(e)===`v5`?ws:Ss;return lr(xs,t)}function ms(e,t){if(e||t)return e?t?lr(e,t):e:t}function hs(e){let t=ps(e);return e?zr(wr(ss({...t,...e,colorScheme:Sr(e,[`colorScheme`]).includes(`colorScheme`)?e.colorScheme:e.brand?void 0:t.colorScheme,...t.approval||e.approval!==void 0?{approval:e.approval!==!1&&{...t.approval||{},...e.approval}}:{},theme:ms(t.theme,e.theme),darkTheme:ms(t.darkTheme,e.darkTheme),launcher:{...t.launcher,...e.launcher,dock:{...t.launcher?.dock,...e.launcher?.dock},clearChat:{...t.launcher?.clearChat,...e.launcher?.clearChat}},...t.composer||e.composer?{composer:{...t.composer,...e.composer}}:{},tooltip:{...t.tooltip,...e.tooltip},copy:{...t.copy,...e.copy},sendButton:{...t.sendButton,...e.sendButton},statusIndicator:{...t.statusIndicator,...e.statusIndicator},voiceRecognition:{...t.voiceRecognition,...e.voiceRecognition},features:(()=>{let n=t.features?.artifacts,r=e.features?.artifacts,i=t.features?.scrollToBottom,a=e.features?.scrollToBottom,o=t.features?.scrollBehavior,s=e.features?.scrollBehavior,c=t.features?.streamAnimation,l=e.features?.streamAnimation,u=t.features?.askUserQuestion,d=e.features?.askUserQuestion,f=t.features?.history,p=e.features?.history,m=n===void 0&&r===void 0?void 0:{...n,...r,layout:{...n?.layout,...r?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...t.features,...e.features,toolCallDisplay:{...t.features?.toolCallDisplay,...e.features?.toolCallDisplay,...e.features?.toolCallDisplay?.layout===void 0&&e.features?.toolCallDisplay?.variant!==void 0?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...t.features?.reasoningDisplay,...e.features?.reasoningDisplay,...e.features?.reasoningDisplay?.layout===void 0&&e.features?.reasoningDisplay?.variant!==void 0?{layout:e.features.reasoningDisplay.variant}:{}},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??t.suggestionChips,suggestionChipsConfig:{...t.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...t.layout,...e.layout,header:{...t.layout?.header,...e.layout?.header},messages:{...t.layout?.messages,...e.layout?.messages,...t.layout?.messages?.user||e.layout?.messages?.user?{user:{...t.layout?.messages?.user,...e.layout?.messages?.user}}:{},...t.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...t.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...t.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...t.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...t.layout?.slots,...e.layout?.slots}},markdown:{...t.markdown,...e.markdown,options:{...t.markdown?.options,...e.markdown?.options}},messageActions:{...t.messageActions,...e.messageActions}},e),e,ws),e):zr(wr(ss(t),void 0,ws))}var gs,_s,vs,ys,bs,xs,Ss,Cs,ws,Ts,Es=B((()=>{Qo(),dr(),es(),kr(),ds(),Wr(),vo(),gs=`min(440px, calc(100vw - 24px))`,_s=`440px`,vs=`40px`,ys=`How can I help...`,bs={enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:gs,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:vs,closeButtonPaddingX:`0px`,closeButtonPaddingY:`0px`,callToActionIconName:`arrow-up-right`,callToActionIconText:``,callToActionIconSize:`32px`,callToActionIconPadding:`5px`,callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:`transparent`,clearChat:{backgroundColor:`transparent`,borderColor:`transparent`,enabled:!0,placement:`inline`,iconName:`refresh-cw`,showTooltip:!0,tooltipText:`Clear chat`,paddingX:`0px`,paddingY:`0px`},headerIconHidden:!1,border:void 0,shadow:`0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`},xs={apiUrl:`https://api.runtype.com/api/chat/dispatch`,clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:`light`,tooltip:{delayMs:400,skipDelayMs:300},launcher:bs,copy:{inputPlaceholder:ys,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``,streamingIndicator:`arrow`,scrollBehavior:`instant`,scrollDurationMs:220,transition:`none`},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:Jo,reasoningDisplay:Yo,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},Ss={},Cs={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},ws={colorScheme:`light`,errorDisplay:`block`,messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:$o,loadingIndicator:{variant:`label`},launcher:Cs,features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:`dots`,transition:`fade`,scrollBehavior:`smooth`},toolCallDisplay:Xo,reasoningDisplay:Zo},composer:{layout:`single-row`,placement:`overlay`},sendButton:{iconName:`arrow-up`},statusIndicator:{mode:`transient`},layout:{contentMaxWidth:`768px`,topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:`full`}}}},Ts=ps()}));function Ds(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function Os(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function ks(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function As(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function js(e){return{type:`text`,text:e}}function Ms(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Ns(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;t({type:`image`,image:n,mimeType:e.type,alt:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Ps(e,t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(`, `)}`}}function Fs(e){return Hs.includes(e)||e.startsWith(`image/`)}function Is(e){return Fs(e.type)}async function Ls(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Is(e)?t({type:`image`,image:n,mimeType:e.type,alt:e.name}):t({type:`file`,data:n,mimeType:e.type,filename:e.name})},r.onerror=()=>n(/* @__PURE__ */ Error(`Failed to read file`)),r.readAsDataURL(e)})}function Rs(e,t=Ws,n=10485760){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(`, `)}`}}function zs(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Bs(e,t){let n=zs(t).toUpperCase();return{"application/pdf":`PDF`,"text/plain":`TXT`,"text/markdown":`MD`,"text/csv":`CSV`,"application/msword":`DOC`,"application/vnd.openxmlformats-officedocument.wordprocessingml.document":`DOCX`,"application/vnd.ms-excel":`XLS`,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":`XLSX`,"application/json":`JSON`}[e]||n||`FILE`}var Vs,Hs,Us,Ws,Gs=B((()=>{Vs=`[Image]`,Hs=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],Us=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],Ws=[...Hs,...Us]}));function Ks(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function qs(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function Js(e,t){e.style.maxHeight=`${t*Ks(e)}px`,e.style.overflowY=`auto`}function Ys(e){let t=e?.ownerDocument?.defaultView??(typeof window<`u`?window:null);if(!t||typeof t.matchMedia!=`function`)return!1;try{return t.matchMedia(`(pointer: coarse)`).matches===!0}catch{return!1}}function Xs(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function Zs(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!Xs(t)}function Qs(e){return(e.submitKey??`enter`)===`enter`?Xs(e)?`enter`:`send`:`enter`}function $s(e,t){e.setAttribute(`enterkeyhint`,Qs(t))}function ec(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function tc(e){return e===!0?{disabled:!0}:!e||typeof e!=`object`?{disabled:!1}:{disabled:!0,reason:typeof e.reason==`string`&&e.reason?e.reason:void 0}}var nc=B((()=>{})),rc,ic,ac=B((()=>{rc=`persona-composer-control`,ic=`persona-composer-control--glyph`})),oc,sc,cc,lc,uc,dc,fc,pc,mc,hc,gc,_c=B((()=>{Uo(),qo(),X(),Pn(),Es(),Gs(),Ro(),nc(),ac(),ac(),oc=(e,t)=>{let n=J(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,$s(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Ys(n)}),ec(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=qs(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*Ks(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},sc=`[data-persona-glyph-stack]`,cc=(e,t,n=`send`)=>{let r=Y(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},lc=/* @__PURE__ */ new WeakMap,uc=(e,t,n=!0)=>{lc.set(e,t);let r=t?.sendButton??{},i=r.useIcon??!1,a=e.getAttribute(`data-persona-send-mode`)===`stop`?`stop`:`send`,o=e=>Bo(t,`sendButton.${e}`),s=(e,n)=>zo(t,`composer.send`,e,n),c=o(`size`)||r.size;e.style.fontSize=i?`18px`:``,e.style.lineHeight=i?`1`:``,e.className=Gr(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,i?`persona-flex persona-items-center persona-justify-center ${rc}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,i&&!o(`backgroundColor`)&&`persona-bg-persona-primary`,!i&&!o(`textColor`)&&`persona-text-white`),Ho(e,i?c||(s(`size`,``)?s(`size`,`var(--persona-composer-control-size, 40px)`):``):``,i?c:void 0);let l=s(`foreground`,i?`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:`#ffffff`),u=s(`background`,i?`var(--persona-button-primary-bg, var(--persona-primary, #111827))`:`var(--persona-accent, #0f0f0f)`);e.style.color=o(`textColor`)||(a===`stop`&&s(`foreground`,``)?`var(--persona-button-stop-fg, ${l})`:s(`foreground`,``)||(i?l:``)),e.style.backgroundColor=(i?o(`backgroundColor`):void 0)||(s(`background`,``)?a===`stop`?`var(--persona-button-stop-bg, ${u})`:u:``);let d=o(`borderWidth`)||(s(`borderWidth`,``)?s(`borderWidth`,r.borderWidth||`0px`):r.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderColor=o(`borderColor`)||(s(`borderColor`,``)?s(`borderColor`,r.borderColor||`transparent`):r.borderColor||``),e.style.borderRadius=s(`borderRadius`,``)?s(`borderRadius`,`var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))`):``,Vo(e,s(`padding`,i?`0`:`8px 16px`),i?void 0:o(`paddingX`)||(s(`padding`,``)?void 0:r.paddingX),i?void 0:o(`paddingY`)||(s(`padding`,``)?void 0:r.paddingY));let f=parseFloat(r.iconSize??``)||Math.round((parseFloat(r.size??``)||40)*.5);if(n){if(e.replaceChildren(),i){let t=r.iconStrokeWidth??2,n=r.iconName?G(r.iconName,f,`currentColor`,t):null,i=G(r.stopIconName??`square`,f,`currentColor`,t);n&&i?e.appendChild(cc(n,i,a)):n?e.appendChild(n):e.textContent=r.iconText??`↑`}else e.textContent=a===`stop`?t?.copy?.stopButtonLabel??`Stop`:t?.copy?.sendButtonLabel??`Send`}for(let n of Array.from(e.querySelectorAll(`svg`))){n.style.width=n.style.height=o(`iconSize`)?``:s(`iconSize`,`var(--persona-components-composer-sendIconSize, ${f}px)`);let e=t?.sendButton?.iconStrokeWidth;n.style.strokeWidth=e===void 0?s(`iconStrokeWidth`,``):String(e)}},dc=e=>{let t=e?.sendButton,n=J(`div`,`persona-send-button-wrapper`),r=Y(`button`,{attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`}});return uc(r,e),r.setAttribute(`aria-label`,t?.tooltipText??`Send message`),n.appendChild(r),So({anchor:r,trigger:n,text:()=>r.getAttribute(`aria-label`)??``,enabled:t?.showTooltip??!1}),{button:r,wrapper:n,setMode:e=>{if(r.getAttribute(`data-persona-send-mode`)===e)return;r.setAttribute(`data-persona-send-mode`,e),r.setAttribute(`aria-label`,e===`stop`?t?.stopTooltipText??`Stop generating`:t?.tooltipText??`Send message`);let n=lc.get(r);uc(r,n,!1),r.querySelector(sc)?.setAttribute(`data-mode`,e),(n?.sendButton?.useIcon??!1)||(r.textContent=e===`stop`?n?.copy?.stopButtonLabel??`Stop`:n?.copy?.sendButtonLabel??`Send`)},glyphStack:r.querySelector(sc)}},fc=(e,t,n=`idle`,r=`none`)=>{let i=t?.voiceRecognition??{},a=e=>Bo(t,`voiceRecognition.${e}`),o=(e,n)=>zo(t,`voice.control`,e,n),s=a(`iconSize`)||i.iconSize;Ho(e,s||(o(`size`,``)?o(`size`,`var(--persona-composer-control-size, 40px)`):``),s),e.classList.add(rc),e.classList.toggle(ic,!s&&!o(`size`,``)),e.style.fontSize=`18px`,e.style.lineHeight=`1`;let c=a(`iconColor`)||Bo(t,`sendButton.textColor`)||o(`foreground`,`var(--persona-text, #111827)`),l=a(`backgroundColor`)||Bo(t,`sendButton.backgroundColor`)||o(`background`,i.backgroundColor||`transparent`),u=a(`borderColor`)||o(`borderColor`,i.borderColor||`transparent`),d=a(`borderWidth`)||o(`borderWidth`,i.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderRadius=o(`borderRadius`,``)?o(`borderRadius`,`var(--persona-button-radius)`):``,Vo(e,o(`padding`,``)?o(`padding`,`0px`):``,a(`paddingX`)||(o(`padding`,``)?void 0:i.paddingX),a(`paddingY`)||(o(`padding`,``)?void 0:i.paddingY));let f=a(`recordingBackgroundColor`)||`var(--persona-voice-recording-bg, #ef4444)`,p=a(`recordingIconColor`)||`var(--persona-voice-recording-indicator, #ffffff)`,m=a(`recordingBorderColor`)||`var(--persona-consumer-voice-recording-border, ${i.recordingBorderColor||u})`,h=c,g=l,_=u,v=i.iconName??`mic`;if(n===`recording`)h=p,g=f,_=m;else if(n===`processing`)h=a(`processingIconColor`)||`var(--persona-consumer-voice-processing-icon, ${c})`,g=a(`processingBackgroundColor`)||`var(--persona-consumer-voice-processing-background, ${l})`,_=a(`processingBorderColor`)||`var(--persona-components-voice-processing-border, ${u})`,v=i.processingIconName??`loader`;else if(n===`speaking`){let e=r===`barge-in`;h=a(`speakingIconColor`)||`var(--persona-consumer-voice-speaking-icon, ${e&&a(`recordingIconColor`)||c})`,g=a(`speakingBackgroundColor`)||`var(--persona-components-voice-speaking-background, ${e?f:l})`,_=a(`speakingBorderColor`)||`var(--persona-components-voice-speaking-border, ${e?m:u})`,v=i.speakingIconName??(r===`cancel`?`square`:e?`mic`:`volume-2`)}e.style.color=h,e.style.backgroundColor=g,e.style.borderColor=_,e.setAttribute(`data-state`,n);let y=parseFloat(i.iconSize??``)||24,b=G(v,y,`currentColor`,1.5);if(e.replaceChildren(),b){let t=s||(o(`iconSize`,``)?o(`iconSize`,`var(--persona-composer-control-icon-size, 24px)`):``);b.style.width=b.style.height=t,!s&&o(`iconSize`,``)&&(b.style.flexBasis=t),b.style.strokeWidth=o(`iconStrokeWidth`,`1.5`),e.appendChild(b)}else e.textContent=`🎤`},pc=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0||t.showButton===!1)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`||t.dictation?.provider?.type===`custom`;if(!(n||r||i))return null;let a=J(`div`,`persona-send-button-wrapper`),o=Y(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control`,attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`}});fc(o,e),a.appendChild(o);let s=t.tooltipText??`Start voice recognition`;return So({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??s,enabled:t.showTooltip??!1}),{button:o,wrapper:a}},mc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=J(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=J(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Ws).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=J(`div`,`persona-send-button-wrapper`),o=Y(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${rc} ${ic}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=G(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return So({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},hc=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=J(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Go(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=J(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},gc=()=>Y(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function vc(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=J(`div`,`persona-send-button-wrapper`),o=Y(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${rc} ${ic}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=G(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),So({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var yc=B((()=>{X(),Pn(),Ro(),_c()})),bc,xc,Sc,Cc=B((()=>{H(),{setLoader:bc,load:xc}=V({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),Sc=xc})),wc,Tc,Ec,Dc=B((()=>{H(),{setLoader:wc,load:Tc}=V({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),Ec=Tc}));function Oc(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Y(`span`,{className:Gr(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=G(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=J(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(Y(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var kc=B((()=>{X(),Pn()}));function Ac(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??jc,a=e.config.contextMentions;if(!a?.enabled)return null;let o=go(a).filter(e=>e.sources.length>0);if(o.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let s=o.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),c=e=>s.some(t=>t.trigger?t.position===`line-start`?e.split(`
|
|
11
11
|
`).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
|
|
@@ -14,7 +14,7 @@ import{Marked as e,Marked as t}from"marked";import n,{default as r}from"dompurif
|
|
|
14
14
|
|
|
15
15
|
`)}:{}}function Zd(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Qd(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1||e[n].role!==`user`)return null;let r=n+1;for(;r<e.length&&e[r].role!==`user`;)r+=1;return{start:n,end:r}}function $d(e,t){let n=e.findIndex(e=>e.id===t);if(n<=0)return null;for(let t=n-1;t>=0;--t)if(e[t].role===`user`)return e[t].id;return null}function ef(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`||n.streaming)return null;if(!(n.role!==`assistant`||n.variant))return $d(e,n.id)?n.id:null}return null}function tf(e){return e.role!==`user`||e.variant||e.streaming||e.contentParts?.length||e.contextMentions?.length||e.contentSegments?.length||e.mentionContext&&Object.keys(e.mentionContext).length>0||e.rawContent!==void 0||e.llmContent!==void 0&&e.llmContent!==e.content||e.quote?!1:typeof e.content==`string`&&e.content.length>0}function nf(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function rf(e,t){if(!nf(e))return null;let n=e.props&&typeof e.props==`object`&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function af(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith(`{`)&&!r.startsWith(`[`))return null;if(n.length<=t)return e;try{let t=rf(Rt(n,Lt|It),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function of(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}X();function sf(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Ql(n,e.component);if(!a){if(eu.includes(e.component)){cu().catch(()=>{});let e=J(`div`,`persona-w-full`);return e.setAttribute(`data-persona-artifact-pending`,`true`),e}return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null}let o=t.context??{message:r,config:n,signal:t.signal??new AbortController().signal,updateProps:e=>{i&&i(e)}};try{return a(e.props,o)}catch(t){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,t),null}}function cf(){let e=af();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function lf(e){if(typeof e.rawContent==`string`&&e.rawContent.length>0)return e.rawContent;if(typeof e.content==`string`){let t=e.content.trim();if(t.startsWith(`{`)||t.startsWith(`[`))return e.content}return null}function uf(e){let t=lf(e);if(!t)return!1;try{let e=JSON.parse(t);return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`}catch{return!1}}function df(e){let t=lf(e);if(!t)return null;try{let e=JSON.parse(t);if(typeof e==`object`&&e&&`component`in e&&typeof e.component==`string`){let n=e;return{component:n.component,props:n.props&&typeof n.props==`object`&&n.props!==null?n.props:{},raw:t}}}catch{}return null}function ff(e){for(let t of[`Microsoft Jenny Online (Natural) - English (United States)`,`Microsoft Aria Online (Natural) - English (United States)`,`Microsoft Guy Online (Natural) - English (United States)`,`Google US English`,`Google UK English Female`,`Ava (Premium)`,`Evan (Enhanced)`,`Samantha (Enhanced)`,`Samantha`,`Daniel`,`Karen`,`Microsoft David Desktop - English (United States)`,`Microsoft Zira Desktop - English (United States)`]){let n=e.find(e=>e.name===t);if(n)return n}return e.find(e=>e.lang.startsWith(`en`))??e[0]}var pf=class e{constructor(e={}){this.options=e,this.id=`browser`,this.supportsPause=!0}static isSupported(){return typeof window<`u`&&`speechSynthesis`in window}speak(t,n){if(!e.isSupported()){n.onError?.(/* @__PURE__ */ Error(`Web Speech API is unavailable`));return}let r=window.speechSynthesis;r.cancel();let i=new SpeechSynthesisUtterance(t.text),a=r.getVoices();if(t.voice){let e=a.find(e=>e.name===t.voice);e&&(i.voice=e)}else a.length>0&&(i.voice=this.options.pickVoice?this.options.pickVoice(a):ff(a));t.rate!==void 0&&(i.rate=t.rate),t.pitch!==void 0&&(i.pitch=t.pitch),i.onend=()=>n.onEnd?.(),i.onerror=e=>{let t=e.error;t===`canceled`||t===`interrupted`?n.onEnd?.():n.onError?.(Error(t||`Speech synthesis failed`))},setTimeout(()=>{r.speak(i),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}},mf=class{#e=null;#t=null;#n=`idle`;#r=/* @__PURE__ */ new Set;#i=0;#a;constructor(e){this.#a=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#t===e?this.#n:`idle`}activeMessageId(){return this.#t}onChange(e){return this.#r.add(e),()=>this.#r.delete(e)}toggle(e,t){if(this.#t===e){if(this.#n===`playing`){this.#e?.supportsPause?(this.#e.pause(),this.#o(e,`paused`)):this.stop();return}if(this.#n===`paused`){this.#e?.resume(),this.#o(e,`playing`);return}if(this.#n===`loading`){this.stop();return}}this.play(e,t)}async play(e,t){let n=++this.#i;this.#e?.stop(),this.#o(e,`loading`);try{if(!this.#e){let e=await this.#a();if(n!==this.#i)return;if(!e){this.#o(null,`idle`);return}this.#e=e}this.#e.speak(t,{onStart:()=>{n===this.#i&&this.#o(e,`playing`)},onEnd:()=>{n===this.#i&&this.#o(null,`idle`)},onError:()=>{n===this.#i&&this.#o(null,`idle`)}})}catch{n===this.#i&&this.#o(null,`idle`)}}stop(){this.#i++,this.#e?.stop(),this.#o(null,`idle`)}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#r.clear()}#o(e,t){this.#t=t===`idle`?null:e,this.#n=t;for(let e of this.#r)e(this.#t,this.#n)}},hf=class{#e;#t=!1;start(e){this.#e=e,this.#t=!1}cancel(){this.#t=!0}accepts(e){return!this.#t&&(!e||!this.#e||e===this.#e)}};function gf(e){if(!e)return``;let t=_f(e);return vf(t===null?e:t)}function _f(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith(`{`))return null;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&typeof e.text==`string`)return e.text}catch{}return null}function vf(e){if(!e)return``;let t=e;return t=t.replace(/```[\s\S]*?```/g,` `),t=t.replace(/~~~[\s\S]*?~~~/g,` `),t=t.replace(/`([^`]+)`/g,`$1`),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,`$1`),t=t.replace(/<\/?[a-zA-Z][^>]*>/g,` `),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,``),t=t.replace(/^[ \t]*>[ \t]?/gm,``),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,``),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,``),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm,` `),t=t.replace(/(\*\*|__)(.*?)\1/g,`$2`),t=t.replace(/(\*|_)(.*?)\1/g,`$2`),t=t.replace(/~~(.*?)~~/g,`$1`),t=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/ /g,` `),t=t.replace(/[ \t]+/g,` `),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
16
16
|
`),t=t.replace(/\n{2,}/g,`
|
|
17
|
-
`),t.trim()}var yf,bf=B((()=>{yf=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function xf(e){return e.replace(/\/+$/,``)}async function Sf(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Cf,wf=B((()=>{bf(),Cf=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new yf(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${xf(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Sf(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}})),Tf,Ef=B((()=>{Tf=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),Df=/* @__PURE__ */ Vt({FallbackSpeechEngine:()=>Tf,RuntypeSpeechEngine:()=>Cf}),Of=B((()=>{wf(),Ef()}));const kf=()=>Promise.resolve().then(()=>(Of(),Df));H();const{setLoader:Af,load:jf}=V({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),Mf=jf;Kn(),ra(),Kc(),Gs(),q(),dd();const Nf=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Pf(e,t){return Nf.some(n=>e[n]!==t[n])}var Ff=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function If(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=`Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.`;return n.message?`${r}\n\n_Details: ${n.message}_`:r}const Lf=e=>Wn(e)||e===`suggest_replies`;var Rf=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${Wc()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:/* @__PURE__ */ new Set},e)for(let t of this.messages)t.role===`assistant`&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;this.#r!==null&&clearTimeout(this.#r),this.#r=null;let n=this.#e;if(this.#e=null,n){let t=n;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#o(){if(!this.#e||this.#r!==null)return;let e=this.#e;this.#r=setTimeout(()=>{this.#r=null,this.#e===e&&(!this.#n&&(this.streaming||this.#f||this.#_t()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#n?`error`:`success`))},0)}#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.#e=null,this.#n=!1,this.#r=null,this.streaming=!1,this.#s=/* @__PURE__ */ new Map,this.abortController=null,this.#l=Date.now(),this.clientSession=null,this.agentExecution=null,this.#u=null,this.#d=null,this.#f=!1,this.#m=null,this.#h=null,this.#g=null,this.#_=null,this.#v=null,this.#y=null,this.artifacts=/* @__PURE__ */ new Map,this.#b=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#x=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#S=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#C=null,this.#w=null,this.#T=0,this.#E=0,this.#D=!1,this.#O=`disconnected`,this.#k=null,this.#A=null,this.#j=null,this.#M=0,this.#N=0,this.#P=null,this.#F=Promise.resolve(),this.#I=!1,this.#L=null,this.#R=!1,this.#z=null,this.#B=/* @__PURE__ */ new Map,this.#V=null,this.#H=/* @__PURE__ */ new Map,this.#U=null,this.#W=null,this.#G=!1,this.#K=null,this.#q=null,this.#J=!1,this.#Y=null,this.#Q=null,this.#$=null,this.#ee=new hf,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new mf(()=>this.#ie()),this.#Ze=null,this.#Qe=0,this.handleEvent=(e,t=!1)=>{if(this.#m){this.#m.push({event:e,readOnlyReplay:t});return}let n=this.#re,r=!1;if(n&&(e.type===`error`||e.type===`status`&&e.status===`error`?n.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),r=!0)),e.type===`message`){this.#e&&!t&&e.message.role===`assistant`&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||e.message.variant===`approval`&&e.message.approval?.status===`pending`)&&this.#dt(`needs-attention`),r&&n.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#s.set(e.message.id,this.#c),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#d=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&ul().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(Wn(i.name)||i.name===`suggest_replies`&&na(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&a&&!t&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#et(e.message),e.message.agentMetadata?.executionId&&(!this.agentExecution||this.agentExecution.executionId!==e.message.agentMetadata.executionId?this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0}:e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration))}else if(e.type===`cursor`)this.#p=e.checkpoint,this.#ht(e.id);else if(e.type===`status`){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#dt(`running`)),e.status===`idle`&&!e.terminal&&this.#gt()){this.#vt();return}if(e.status===`error`?this.#dt(`failed`):e.terminal&&e.status===`idle`&&this.#dt(`completed`),this.#Ot(e.status),e.status===`connecting`)this.#kt(!0);else if(e.status===`idle`||e.status===`error`){this.#_t()||this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null,this.#He(),this.#Le());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#tt()}}else e.type===`error`?(this.#dt(`failed`),this.#Ot(`error`),this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#ct(e)},this.historyInternals=this.#ue(n),this.messages=[...e.initialMessages??[]].map(e=>({...Iu(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new Rd(e,this.historyInternals),this.#Oe(),this.#Xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#b=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#st(),this.callbacks.onStatusChanged(this.status),this.#Z(),this.#X()}#X(){this.config.voiceRecognition?.provider&&mu().catch(()=>{})}#Z(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&kf().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return yu(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#O}getVoiceNotice(){return this.#C?.takeNotice?.()??null}getVoiceDisclosure(){return this.#C?.getDisclosure?.()??null}getVoiceLevel(){return this.#C?.onLevel?this.#E:null}getVoiceInterruptionMode(){return this.#C?.getInterruptionMode?this.#C.getInterruptionMode():`none`}stopVoicePlayback(){this.#C?.stopPlayback&&(this.#ee.cancel(),this.#ne?.cancel(),this.#C.stopPlayback())}isBargeInActive(){return this.#C?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#C?.deactivateBargeIn&&await this.#C.deactivateBargeIn()}#Q;#$;#ee;#te;#ne;#re;#ie(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=pf.isSupported()?new pf({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return kf().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#te,r=++this.#T;this.#w=mu().then(async e=>{await n,r===this.#T&&this.#ae(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#T&&(this.#w=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#ae(e,t){this.#C=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#C,generation:()=>n.#T,get keyed(){return n.#ne},set keyed(e){n.#ne=e},get pendingUser(){return n.#Q},set pendingUser(e){n.#Q=e},get pendingAssistant(){return n.#$},set pendingAssistant(e){n.#$=e},turns:()=>n.#ee,busy:()=>n.#oe(),setStreaming:e=>n.#kt(e),setDelegation:e=>{n.#re=e},setLevel:e=>{n.#E=e},setStatus:e=>{n.#O=e,n.#D=e===`listening`},settlePending:e=>n.#ce(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#T;if(!this.#C&&this.#w&&await this.#w,e===this.#T){if(!this.#C)console.error(`Voice not configured`);else if(this.#D)await this.#C.stopListening();else{this.stopSpeaking();try{await this.#C.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}}prewarmVoice(){if(!_u(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#T,t=()=>{let t=this.#C;t?.prewarm&&e===this.#T&&(this.#D||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#C&&this.#w?this.#w.then(t,()=>{}):t()}#oe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||this.status===`resuming`}cleanupVoice(){let e=this.#C!==null;if(this.#T++,this.#w=null,this.#C){let e=this.#C;this.#C=null,this.#te=this.#se(e)}this.#D=!1,this.#O=`disconnected`,this.#ce(!0),this.#ne?.settle(),this.#ne=null,this.#ee=new hf,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#se(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#ce(e){let t=e?this.#Q:null,n=this.#$;(t||n)&&(n&&this.#ee.cancel(),e&&(this.#Q=null),this.#$=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#kt(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#W=this.historyInternals.getStoredConversationRevision?.()??null,this.#G=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#le(e,t)}#le(e,t=!this.messages.length){if(this.#I||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#It()};this.#Pt(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){e.historyProvider!==this.historyInternals.historyProvider&&(this.#M+=1,this.#N+=1,this.config.backgroundConversations&&this.cancel(),this.#ut()),this.historyInternals=this.#ue(e),this.client.setHistoryInternals(this.historyInternals),this.#Oe()}destroy(){this.#ut(),this.#M+=1,this.#N+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#K?.(),this.#K=null,this.#q=null}#ue(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#De(e),t?.(e)}}}get#de(){return this.historyInternals.historyProvider??null}#fe(){let e=this.#de;if(!e)throw new Ff(`history_unavailable`,`No conversation history provider is installed`);return e}#pe(e){let t=this.#fe(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new zd(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#k,conversationRevision:this.#A,nextMessageCursor:this.#j,recovery:this.#L,sendBlocked:this.#R}}getActiveConversationId(){return this.#k}#me(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#he(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#z;e&&await e.catch(()=>{});let t=this.#V;t&&await t.catch(()=>{})}#ge(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Ff(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#fe().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#pe(e?.scope)})}async openConversation(e,t){let n=this.#fe();t?.busy===`background`&&this.assertBackgroundSwitchable(),t?.busy===`stop`&&this.cancel(),t?.busy!==`background`&&this.#ge();let r=this.#pe(t?.scope),i=++this.#M,a=this.#N;if(t?.busy===`background`&&await this.#lt(),await this.awaitHistorySettled(),i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let s=await n.prepareOpen(e,{context:r}),c=this.#F.then(async()=>{if(i!==this.#M)throw s.discard(),new Ff(`superseded`,`A later selection won`);t?.busy===`stop`&&this.cancel();try{t?.busy===`background`?this.assertBackgroundSwitchable():this.#ge()}catch(e){throw s.discard(),e}let r=this.#k,c=this.#e;t?.onBeforeCommit?.(),t?.busy===`background`&&(this.#m=[]),this.#I=!0,this.#P=a;try{if(await this.#Ce(s),a!==this.#N||n!==this.#de)throw new Ff(`superseded`,`The history identity changed`);if(t?.busy===`background`&&r&&this.#u){let e={conversationId:r,handle:this.#u,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#b,streamCheckpoint:this.#p};this.#h?.save(e)}this.#k=s.conversationId||e,this.#A=s.conversationRevision||o.conversationRevision||null,this.#j=o.nextCursor,this.#L=null,this.#R=!1,this.#Te();for(let e of o.messages)this.#H.set(e.id,e.content);this.#we();let i=this.#h?.take(this.#k);return this.hydrateMessages(i?.messages??o.messages),i&&(this.hydrateArtifacts(i.artifacts,i.selectedArtifactId,!0),this.#mt(i)),t?.onCommitted?.(),this.#me(),{summary:o.summary,nextMessageCursor:o.nextCursor}}finally{this.#I=!1,this.#P=null;let e=this.#m;if(this.#m=null,e&&this.#e===c&&this.#k===r)for(let{event:t,readOnlyReplay:n}of e)this.handleEvent(t,n)}}),l=c.then(()=>{},()=>{});this.#F=l,this.#z=l;try{return await c}finally{this.#z===l&&(this.#z=null)}}loadOlderMessages(e,t,n){let r=this.#fe(),i=this.#pe(n?.scope),a=t??this.#j;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#B.get(o);if(s)return s;let c=this.#_e(r,e,a,i).finally(()=>{this.#B.delete(o)});return this.#B.set(o,c),c}async#_e(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#k&&this.#k!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ve(a.messages),s=ud(this.messages,o);this.messages=this.#Rt(s.map(e=>this.#Ft(e))),this.#j=a.nextCursor;for(let e of a.messages)this.#H.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#me(),{messages:o,nextMessageCursor:a.nextCursor}}#ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&Fu(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return Iu(e)})}async startNewConversation(e){let t=this.#fe(),n=this.#pe(e?.scope),r=++this.#M,i=this.#N;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:n}),o=this.#F.then(async()=>{if(r!==this.#M)throw a.discard(),new Ff(`superseded`,`A later action won`);e?.onBeforeCommit?.(),this.#I=!0,this.#P=i;try{await this.#Ce(a)}finally{this.#I=!1,this.#P=null}if(i!==this.#N||t!==this.#de)throw new Ff(`superseded`,`The history identity changed`);this.#Ee(!1,!0),this.#k=a.conversationId||null,this.#A=a.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.clientSession&&this.#le(this.clientSession),e?.onCommitted?.(),this.#me()}),s=o.then(()=>{},()=>{});this.#F=s,this.#z=s;try{await o}finally{this.#z===s&&(this.#z=null)}}async#ye(e,t=!1){this.#Ee(t),await this.#Ce(e),this.#k=e.conversationId||null,this.#A=e.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.#me()}async deleteConversation(e,t){let n=this.#fe(),r=this.#pe(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),this.#h?.clear(e),e===this.#k&&await this.#be(r)}async updateConversation(e,t,n){let r=this.#fe();if(!r.update)throw new Ff(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#pe(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#de?.update==`function`}async clearConversationHistory(e){let t=this.#fe(),n=this.#pe(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return this.#ut(),await this.#be(n),r}async resetHistoryDevice(){let e=this.#fe();if(!e.resetDevice)throw new Ff(`history_unavailable`,`This history provider cannot reset the device`);this.#ut(),this.#M+=1,this.#N+=1,this.#V=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#R=!1,this.#me()}}async#be(e){this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#R=!0,this.#L=null,this.#me(),await this.#xe(e)}async#xe(e){let t=this.#de;if(!t)this.#R=!1,this.#me();else try{let n=await t.prepareStartNew({context:e});await this.#ye(n)}catch{this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#Se(){if(this.#L===`new_conversation_required`&&this.#de&&(this.#L=null,await this.#xe(this.#pe()),this.#L===`new_conversation_required`))throw new Ff(`new_conversation_required`,`A new conversation is required before sending`)}async#Ce(e){if(await e.commit(),this.#P!==null&&this.#P!==this.#N)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(this.#P===null||this.#P===this.#N)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#k=e.conversationId,this.#A=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#I||this.#le(e))}#we(){this.#k?this.config.setStoredConversationId?.(this.#k):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#A),this.historyInternals.setStoredMessageCursor?.(this.#j)}#Te(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H.clear(),this.#Pe(null)}#Ee(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.messages=[],this.#Te(),this.#B.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a(`cancel`)}#De(e){this.#ut(),this.#M+=1,this.#N+=1,this.#V=null,this.#R=!0,this.#Ee(),this.#k=e.conversationId,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.#he(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#z=Promise.resolve().then(()=>{this.#R=!1,this.#z=null,this.#me()})}#Oe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#K?.(),this.#K=null,this.#q=e,e&&(this.#K=e.subscribe(e=>this.#ke(e))))}#ke(e){if(e.source!==`external`||e.previousToken===null)return;this.#ut(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#M+=1,this.#N+=1,this.#V=null,this.#J=!0,this.#Y=null;let t=this.messages.length>0;t||this.#k!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#B.clear(),this.#Pe(null)),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#he(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#Ae(){return this.#J?(this.#Y||=this.#je().finally(()=>{this.#Y=null}),this.#Y):Promise.resolve()}async#je(){if(!this.isClientTokenMode())this.#J=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#J=!1}catch{}}reconcileBootConversation(e){let t=this.#de,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#k;if(!t||!n)return Promise.resolve();let r=this.#pe(e?.scope);this.#R=!0,this.#me();let i=this.#Me(t,n,r).finally(()=>{this.#R=this.#L!==null,this.#z===i&&(this.#z=null),this.#me()});return this.#z=i,i}async#Me(e,t,n){this.#k=t;let r=this.clientSession?.conversationRevision??this.#A??null,i=this.#G?this.#W:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#G=!1,this.#j=this.historyInternals.getStoredMessageCursor?.()??this.#j,await this.replayPendingProjections(),r&&i&&r===i){this.#A=r;return}let a=await e.getPage(t,{context:n}),o=this.#ve(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#Ft(e));else{let e=this.#u?this.#d:null;u=ud(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#Ft(e))}this.#j=a.nextCursor,this.#A=a.conversationRevision||r||null,this.#H.clear();for(let e of a.messages)this.#H.set(e.id,e.content);this.#we(),this.#t=void 0,this.messages=this.#Rt(u),this.callbacks.onMessagesChanged([...this.messages])}#Ne(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Pe(e){this.#U=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Fe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Ie(e){if(this.#Ne())for(let t of e){let e=ld(t);e!==void 0&&this.#H.set(t.id,e)}}#Le(){if(!this.#Ne())return;let e=this.#k;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=ld(e);n!==void 0&&this.#H.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#Pe({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Re(e,t))}#Re(e,t){let n=(this.#V??Promise.resolve()).catch(()=>{}).then(()=>this.#ze(e,t,!1)).finally(()=>{this.#V===n&&(this.#V=null)});this.#V=n}async#ze(e,t,n){if(this.#k!==e)return;let r=t.filter(e=>this.#H.get(e.id)!==e.displayContent);if(r.length===0)this.#Ve(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#H.set(e.id,e.displayContent);this.#k===e&&n&&(this.#A=n),this.#Ve(e,t)}catch(i){if(!n&&this.#Be(i)){await this.#ze(e,r,!0);return}if(i instanceof Fd&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ve(e,t);return}this.#he(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Be(e){return e instanceof Fd?e.code===`request_failed`:e instanceof Error}#Ve(e,t){let n=this.#Fe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#Pe(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#Ne())return;let e=this.#Fe();if(!e)return;if(this.#k&&e.conversationId!==this.#k){this.#Pe(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#Pe(null):(this.#Re(e.conversationId,t),await this.#V?.catch(()=>{}))}#He(){this.#k&&(this.#A=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ue(){await this.awaitHistorySettled(),await this.#Ae(),this.#L===`new_conversation_required`&&await this.#Se()}static#We(e){return e instanceof Fd&&e.code===`conversation_deleted`}async#Ge(t,n,r,i,a){let o=this.#e,s=e=>{this.#e===o&&this.handleEvent(e)};this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s);return}catch(t){if(n.signal.aborted||this.#e!==o||!e.#We(t))throw t;let c=await this.#Ke(i);if(!c)throw t;this.#Ie([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s)}}async#Ke(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(!0),this.#k=null,this.#A=null,this.#j=null,this.#I=!0;try{let e=this.#de;if(e){let t=await e.prepareStartNew({context:this.#pe()});await this.#ye(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#I=!1}return this.#Pt(n),this.#kt(!0),this.#he(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=gu(this.config,n),i=Pf(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&bu(n)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#at();return}this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.#M+=1,this.#N+=1,this.client=new Rd(this.config,this.historyInternals),a&&this.#at(),this.#Xe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#qe(e);return this.upsertMessage(t),t}#qe(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e;return{id:a??(t===`user`?Uc():t===`assistant`?Wc():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#It(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d},...e.dispatchError!==void 0&&{dispatchError:e.dispatchError}}}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=e.map(e=>this.#qe(e));return this.messages=this.#Rt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}updateComponentProps(e,t){let n=this.messages.find(t=>t.id===e),r=n&&df(n);return!n||n.role!==`assistant`||n.variant||!r?!1:(this.upsertMessage({...n,rawContent:JSON.stringify({text:n.content,component:r.component,props:t})}),!0)}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!t||t.role!==`assistant`||t.variant||!df(t)?!1:(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),!0)}async#Je(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
17
|
+
`),t.trim()}var yf,bf=B((()=>{yf=class{#e=null;#t=0;#n=[];#r=[];#i=[];#a=!1;#o=!1;#s=0;#c=!1;#l=!1;#u;#d=[];#f=0;#p=!1;#m;#h;#g;#_=null;constructor(e=24e3,t={}){this.#h=e;let n=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*n/1e3),this.#u=this.#g>0}#v(){if(!this.#e){let e=typeof window<`u`?window:void 0;if(!e)throw Error(`AudioPlaybackManager requires a browser environment`);let t=e.AudioContext||e.webkitAudioContext;this.#e=new t({sampleRate:this.#h})}let e=this.#e;return e.state===`suspended`&&!this.#l&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#_){let n=new Uint8Array(this.#_.length+e.length);n.set(this.#_),n.set(e,this.#_.length),t=n,this.#_=null}if(t.length%2!=0&&(this.#_=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.#S(t);n.length!==0&&(this.#u?(this.#d.push(n),this.#f+=n.length,clearTimeout(this.#m),this.#f>=this.#g?this.#y():this.#p&&(this.#m=setTimeout(()=>this.#y(),this.#g/this.#h*1e3))):this.#b(n))}markStreamEnd(){this.#d.length>0&&this.#y(),this.#o=!0,this.#x()}flush(){for(let e of this.#n){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#n=[],this.#s=0,this.#t=0,this.#a=!1,this.#o=!1,this.#r=[],this.#i=[],this.#_=null,this.#d=[],this.#f=0,this.#u=this.#g>0,this.#c=!1,clearTimeout(this.#m)}setContinuousMode(e){this.#p=e}isPlaying(){return this.#a}onFinished(e){this.#r.push(e)}onStarted(e){this.#i.push(e)}pause(){this.#l=!0,this.#e&&this.#e.state===`running`&&this.#e.suspend()}resume(){this.#l=!1,this.#e&&this.#e.state===`suspended`&&this.#e.resume()}async destroy(){this.flush(),this.#e&&=(await this.#e.close(),null)}#y(){this.#u=!1;let e=this.#d;this.#d=[],this.#f=0;for(let t of e)this.#b(t)}#b(e){if(e.length===0)return;let t=this.#v(),n=t.createBuffer(1,e.length,this.#h);n.getChannelData(0).set(e);let r=t.createBufferSource();r.buffer=n,r.connect(t.destination);let i=t.currentTime;if(this.#t===0?this.#t=i:this.#t<i&&(this.#t=i,this.#g>0&&(this.#u=!0)),r.start(this.#t),this.#t+=n.duration,this.#n.push(r),this.#s++,this.#a=!0,!this.#c){this.#c=!0;let e=this.#i.slice();this.#i=[];for(let t of e)t()}r.onended=()=>{let e=this.#n.indexOf(r);e!==-1&&(this.#n.splice(e,1),this.#s--,this.#x())}}#x(){if(this.#o&&this.#s<=0&&this.#d.length===0){this.#a=!1,this.#o=!1;let e=this.#r.slice();this.#r=[];for(let t of e)t()}}#S(e){let t=Math.floor(e.length/2),n=new Float32Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let e=0;e<t;e++){let t=r.getInt16(e*2,!0);n[e]=t/32768}return n}}}));function xf(e){return e.replace(/\/+$/,``)}async function Sf(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Cf,wf=B((()=>{bf(),Cf=class{#e;#t;#n;#r;constructor(e){this.id=`runtype-tts`,this.supportsPause=!0,this.#e=null,this.#t=null,this.#n=0,this.#r=e}#i(){return this.#t??=Promise.resolve(this.#r.createPlaybackEngine?this.#r.createPlaybackEngine():new yf(24e3,{prebufferMs:this.#r.prebufferMs??200})).then(e=>this.#e=e)}speak(e,t){let n=++this.#n;this.#a(n,e,t)}async#a(e,t,n){try{let r=await this.#i();if(e!==this.#n)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.#n&&n.onStart?.()}),r.onFinished(()=>{e===this.#n&&n.onEnd?.()});let i=`${xf(this.#r.host)}/v1/agents/${encodeURIComponent(this.#r.agentId)}/speak`,a=await fetch(i,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.#r.clientToken}`},body:JSON.stringify({text:t.text,voice:t.voice??this.#r.voice,format:`pcm`})});if(e!==this.#n)return;if(!a.ok||!a.body)throw Error(await Sf(a));let o=a.body.getReader();for(;;){let{done:t,value:n}=await o.read();if(e!==this.#n){await o.cancel().catch(()=>{});return}if(t)break;n&&n.byteLength>0&&r.enqueue(n)}r.markStreamEnd()}catch(t){if(e!==this.#n)return;let r=t instanceof Error?t:Error(String(t));this.#r.onError?.(r),n.onError?.(r)}}pause(){this.#e?.pause()}resume(){this.#e?.resume()}stop(){this.#n++,this.#e?.flush()}destroy(){this.#n++,this.#e?.destroy(),this.#e=null,this.#t=null}}})),Tf,Ef=B((()=>{Tf=class{#e;#t;#n;#r;constructor(e,t,n={}){this.id=`fallback`,this.#t=e,this.#n=t,this.#r=n,this.#e=e}get supportsPause(){return this.#e.supportsPause}speak(e,t){this.#e=this.#t;let n=!1;this.#t.speak(e,{onStart:()=>{n=!0,t.onStart?.()},onEnd:()=>t.onEnd?.(),onError:r=>{n?t.onError?.(r):(this.#r.onFallback?.(r),this.#e=this.#n,this.#n.speak(e,t))}})}pause(){this.#e.pause()}resume(){this.#e.resume()}stop(){this.#e.stop()}destroy(){this.#t.destroy?.(),this.#n.destroy?.()}}})),Df=/* @__PURE__ */ Vt({FallbackSpeechEngine:()=>Tf,RuntypeSpeechEngine:()=>Cf}),Of=B((()=>{wf(),Ef()}));const kf=()=>Promise.resolve().then(()=>(Of(),Df));H();const{setLoader:Af,load:jf}=V({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),Mf=jf;Kn(),ra(),Kc(),Gs(),q(),dd();const Nf=/* @__PURE__ */ `apiUrl.clientToken.flowId.agentId.target.targetProviders.agent.agentOptions.headers.getHeaders.webmcp.streamParser.parserType.contextProviders.requestMiddleware.customFetch.backgroundConversations.parseSSEEvent.onSessionInit.onSessionExpired.getStoredSessionId.setStoredSessionId.getIdentityProof.identityProvider.getStoredConversationId.setStoredConversationId.clearStoredConversationId.clearStoredSessionId`.split(`.`);function Pf(e,t){return Nf.some(n=>e[n]!==t[n])}var Ff=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function If(e,t){let n=e instanceof Error?e:Error(String(e));if(typeof t==`string`)return t;if(typeof t==`function`)return t(n);let r=n.message.trim(),i=/^(Failed to fetch|fetch failed|Load failed|NetworkError when attempting to fetch resource\.?)$/i.test(r),a=/^(Chat backend|Agent execution) request failed: \d{3}\b/.test(r),o=i?`Sorry: I couldn't reach the assistant. Please check your connection and try again.`:a?`Sorry: the chat service couldn't complete the request. Please try again.`:`Sorry: the chat encountered an unexpected error. Please reload the page and try again.`;return r?`${o}\n\n_Details: ${r}_`:o}const Lf=e=>Wn(e)||e===`suggest_replies`;var Rf=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${Wc()}`,timestamp:Date.now()},this.#t={run:this.#e,messageIds:/* @__PURE__ */ new Set},e)for(let t of this.messages)t.role===`assistant`&&t.agentMetadata?.executionId===e&&this.#t.messageIds.add(t.id);this.callbacks.onRunStarted?.({...this.#e})}#a(e,t=this.#e){if(t!==this.#e)return;this.#r!==null&&clearTimeout(this.#r),this.#r=null;let n=this.#e;if(this.#e=null,n){let t=n;t.timestamp=Date.now(),t.outcome=e,this.callbacks.onRunFinished?.(t)}}#o(){if(!this.#e||this.#r!==null)return;let e=this.#e;this.#r=setTimeout(()=>{this.#r=null,this.#e===e&&(!this.#n&&(this.streaming||this.#f||this.#_t()||this.webMcpAwaitBatches.size||this.webMcpResolveControllers.size)||this.#a(this.#n?`error`:`success`))},0)}#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e={},t,n={}){this.config=e,this.callbacks=t,this.historyInternals=n,this.status=`idle`,this.#e=null,this.#n=!1,this.#r=null,this.streaming=!1,this.#s=/* @__PURE__ */ new Map,this.abortController=null,this.#l=Date.now(),this.clientSession=null,this.agentExecution=null,this.#u=null,this.#d=null,this.#f=!1,this.#m=null,this.#h=null,this.#g=null,this.#_=null,this.#v=null,this.#y=null,this.artifacts=/* @__PURE__ */ new Map,this.#b=null,this.webMcpInflightKeys=/* @__PURE__ */ new Set,this.webMcpResolvedKeys=/* @__PURE__ */ new Set,this.webMcpResolveControllers=/* @__PURE__ */ new Set,this.#x=0,this.webMcpApprovalResolvers=/* @__PURE__ */ new Map,this.#S=0,this.approvalTokens=/* @__PURE__ */ new Map,this.webMcpAwaitBatches=/* @__PURE__ */ new Map,this.#C=null,this.#w=null,this.#T=0,this.#E=0,this.#D=!1,this.#O=`disconnected`,this.#k=null,this.#A=null,this.#j=null,this.#M=0,this.#N=0,this.#P=null,this.#F=Promise.resolve(),this.#I=!1,this.#L=null,this.#R=!1,this.#z=null,this.#B=/* @__PURE__ */ new Map,this.#V=null,this.#H=/* @__PURE__ */ new Map,this.#U=null,this.#W=null,this.#G=!1,this.#K=null,this.#q=null,this.#J=!1,this.#Y=null,this.#Q=null,this.#$=null,this.#ee=new hf,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new mf(()=>this.#ie()),this.#Ze=null,this.#Qe=0,this.handleEvent=(e,t=!1)=>{if(this.#m){this.#m.push({event:e,readOnlyReplay:t});return}let n=this.#re,r=!1;if(n&&(e.type===`error`||e.type===`status`&&e.status===`error`?n.failed=!0:e.type===`message`&&e.message.role===`assistant`&&(n.dropped||this.ttsSpokenMessageIds.add(e.message.id),n.ids.includes(e.message.id)||n.ids.push(e.message.id),r=!0)),e.type===`message`){this.#e&&!t&&e.message.role===`assistant`&&this.#t?.messageIds.add(e.message.id),this.upsertMessage(e.message),(e.message.agentMetadata?.awaitingLocalTool||e.message.variant===`approval`&&e.message.approval?.status===`pending`)&&this.#dt(`needs-attention`),r&&n.onUpdate?.(),e.message.variant===`approval`&&e.message.approval&&e.message.approval.status!==`pending`&&this.#s.set(e.message.id,this.#c),e.message.role===`assistant`&&!e.message.variant&&e.message.streaming&&(this.#d=e.message.id),(e.message.variant===`approval`||e.message.agentMetadata?.awaitingLocalTool===!0)&&ul().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(Wn(i.name)||i.name===`suggest_replies`&&na(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&a&&!t&&this.messages.find(t=>t.id===e.message.id)?.agentMetadata?.awaitingLocalTool===!0&&this.#et(e.message),e.message.agentMetadata?.executionId&&(!this.agentExecution||this.agentExecution.executionId!==e.message.agentMetadata.executionId?this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:``,agentName:e.message.agentMetadata.agentName??``,status:`running`,currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0}:e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration))}else if(e.type===`cursor`)this.#p=e.checkpoint,this.#ht(e.id);else if(e.type===`status`){if(e.executionId&&(this.agentExecution={executionId:e.executionId,agentId:``,agentName:``,status:`running`,currentIteration:0,maxTurns:0},this.#dt(`running`)),e.status===`idle`&&!e.terminal&&this.#gt()){this.#vt();return}if(e.status===`error`?this.#dt(`failed`):e.terminal&&e.status===`idle`&&this.#dt(`completed`),this.#Ot(e.status),e.status===`connecting`)this.#kt(!0);else if(e.status===`idle`||e.status===`error`){this.#_t()||this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null,this.#He(),this.#Le());let t=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status===`running`&&(e.status===`error`?this.agentExecution.status=`error`:t||(this.agentExecution.status=`complete`)),this.#tt()}}else e.type===`error`?(this.#dt(`failed`),this.#Ot(`error`),this.#Et(),this.webMcpResolveControllers.size===0&&(this.#kt(!1),this.abortController=null),this.agentExecution?.status===`running`&&(this.agentExecution.status=`error`),this.callbacks.onError?.(e.error)):(e.type===`artifact_start`||e.type===`artifact_delta`||e.type===`artifact_update`||e.type===`artifact_complete`)&&this.#ct(e)},this.historyInternals=this.#ue(n),this.messages=[...e.initialMessages??[]].map(e=>({...Iu(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new Rd(e,this.historyInternals),this.#Oe(),this.#Xe();for(let t of e.initialArtifacts??[])this.artifacts.set(t.id,{...t,status:`complete`});e.initialSelectedArtifactId!=null&&(this.#b=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.#st(),this.callbacks.onStatusChanged(this.status),this.#Z(),this.#X()}#X(){this.config.voiceRecognition?.provider&&mu().catch(()=>{})}#Z(){let e=this.config.textToSpeech;if(e?.provider!==`runtype`||e.createEngine)return;let t=e.host??this.config.apiUrl,n=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;t&&n&&this.config.clientToken&&kf().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status===`running`}isVoiceSupported(){return yu(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.#D}getVoiceStatus(){return this.#O}getVoiceNotice(){return this.#C?.takeNotice?.()??null}getVoiceDisclosure(){return this.#C?.getDisclosure?.()??null}getVoiceLevel(){return this.#C?.onLevel?this.#E:null}getVoiceInterruptionMode(){return this.#C?.getInterruptionMode?this.#C.getInterruptionMode():`none`}stopVoicePlayback(){this.#C?.stopPlayback&&(this.#ee.cancel(),this.#ne?.cancel(),this.#C.stopPlayback())}isBargeInActive(){return this.#C?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.#C?.deactivateBargeIn&&await this.#C.deactivateBargeIn()}#Q;#$;#ee;#te;#ne;#re;#ie(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let t=pf.isSupported()?new pf({pickVoice:e?.pickVoice}):null;if(e?.provider===`runtype`){let n=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,i=this.config.clientToken,a=e.browserFallback!==!1;if(n&&r&&i)return kf().then(({RuntypeSpeechEngine:o,FallbackSpeechEngine:s})=>{let c=new o({host:n,agentId:r,clientToken:i,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&t?new s(c,t,{onFallback:e=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${e.message}`)}):c});if(a&&t)return i&&console.warn(`[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId).`),t}return t}setupVoice(e){try{let t=e||this.getVoiceConfigFromConfig();if(!t)throw Error(`Voice configuration not provided`);this.cleanupVoice();let n=this.#te,r=++this.#T;this.#w=mu().then(async e=>{await n,r===this.#T&&this.#ae(e,e.createVoiceProvider(t))}).catch(e=>{console.error(`Failed to setup voice:`,e)}).finally(()=>{r===this.#T&&(this.#w=null)})}catch(e){console.error(`Failed to setup voice:`,e)}}#ae(e,t){this.#C=t;let n=this;e.wireSessionVoice({session:this,provider:()=>n.#C,generation:()=>n.#T,get keyed(){return n.#ne},set keyed(e){n.#ne=e},get pendingUser(){return n.#Q},set pendingUser(e){n.#Q=e},get pendingAssistant(){return n.#$},set pendingAssistant(e){n.#$=e},turns:()=>n.#ee,busy:()=>n.#oe(),setStreaming:e=>n.#kt(e),setDelegation:e=>{n.#re=e},setLevel:e=>{n.#E=e},setStatus:e=>{n.#O=e,n.#D=e===`listening`},settlePending:e=>n.#ce(e)},t,e.KeyedVoiceTranscript,e.createVoiceSessionBridge)}async toggleVoice(){let e=this.#T;if(!this.#C&&this.#w&&await this.#w,e===this.#T){if(!this.#C)console.error(`Voice not configured`);else if(this.#D)await this.#C.stopListening();else{this.stopSpeaking();try{await this.#C.startListening()}catch(e){console.error(`Failed to start voice:`,e)}}}}prewarmVoice(){if(!_u(this.config.voiceRecognition?.provider)){this.warmClientSession();return}let e=this.#T,t=()=>{let t=this.#C;t?.prewarm&&e===this.#T&&(this.#D||this.isBargeInActive()||Promise.resolve().then(()=>t.prewarm?.()).catch(()=>{}))};!this.#C&&this.#w?this.#w.then(t,()=>{}):t()}#oe(){return!!this.abortController||this.webMcpResolveControllers.size>0||this.webMcpAwaitBatches.size>0||this.#f||this.status===`resuming`}cleanupVoice(){let e=this.#C!==null;if(this.#T++,this.#w=null,this.#C){let e=this.#C;this.#C=null,this.#te=this.#se(e)}this.#D=!1,this.#O=`disconnected`,this.#ce(!0),this.#ne?.settle(),this.#ne=null,this.#ee=new hf,e&&this.callbacks.onVoiceStatusChanged?.(`disconnected`)}async#se(e){try{await e.disconnect()}catch(e){console.error(`Failed to disconnect voice:`,e)}}#ce(e){let t=e?this.#Q:null,n=this.#$;(t||n)&&(n&&this.#ee.cancel(),e&&(this.#Q=null),this.#$=null,n&&this.ttsSpokenMessageIds.add(n),this.messages=this.messages.flatMap(e=>e.id!==t&&e.id!==n?[e]:e.id===n&&!e.content.trim()?[]:[{...e,streaming:!1,voiceProcessing:!1}]),this.callbacks.onMessagesChanged([...this.messages]),n&&this.#kt(!1))}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case`runtype`:return{type:`runtype`,runtype:{agentId:e.runtype?.agentId??this.config.agentId??``,clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine,prewarmMode:e.runtype?.prewarmMode,attachIdleMs:e.runtype?.attachIdleMs,clientDelegation:e.runtype?.clientDelegation,callContext:e.runtype?.callContext,approvalTimeoutMs:e.runtype?.approvalTimeoutMs,disclosureText:e.runtype?.disclosureText}};case`browser`:return{type:`browser`,browser:{language:e.browser?.language||`en-US`,continuous:e.browser?.continuous}};case`custom`:return{type:`custom`,custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.#W=this.historyInternals.getStoredConversationRevision?.()??null,this.#G=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:Error(String(e))),null}}warmClientSession(){let e=!this.messages.length;this.client.warmSession().then(t=>{t&&this.client.getClientSession()===t&&this.setClientSession(t,e)})}setClientSession(e,t){this.clientSession=e,this.#le(e,t)}#le(e,t=!this.messages.length){if(this.#I||!e.config.welcomeMessage||!t)return;let n=this.messages[0],r={id:`welcome-${Date.now()}`,role:`assistant`,content:e.config.welcomeMessage,createdAt:n?.createdAt??(/* @__PURE__ */ new Date()).toISOString(),sequence:n?(n.sequence??0)-1:this.#It()};this.#Pt(r)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?/* @__PURE__ */ new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}setHistoryInternals(e){e.historyProvider!==this.historyInternals.historyProvider&&(this.#M+=1,this.#N+=1,this.config.backgroundConversations&&this.cancel(),this.#ut()),this.historyInternals=this.#ue(e),this.client.setHistoryInternals(this.historyInternals),this.#Oe()}destroy(){this.#ut(),this.#M+=1,this.#N+=1,this.cancel(),this.#t=void 0,this.cleanupVoice(),this.#K?.(),this.#K=null,this.#q=null}#ue(e){let t=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:e=>{this.#De(e),t?.(e)}}}get#de(){return this.historyInternals.historyProvider??null}#fe(){let e=this.#de;if(!e)throw new Ff(`history_unavailable`,`No conversation history provider is installed`);return e}#pe(e){let t=this.#fe(),n=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?`verified-user`:`browser`,i=n??(t.capabilities.scopes.includes(r)?r:t.capabilities.scopes[0]??r);if(!t.capabilities.scopes.includes(i))throw new zd(`unsupported_scope`,`This history scope is not supported.`);return{scope:i}}getHistoryState(){return{activeConversationId:this.#k,conversationRevision:this.#A,nextMessageCursor:this.#j,recovery:this.#L,sendBlocked:this.#R}}getActiveConversationId(){return this.#k}#me(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}#he(e,t){this.callbacks.onHistoryNotice?.({code:e,message:t})}async awaitHistorySettled(){let e=this.#z;e&&await e.catch(()=>{});let t=this.#V;t&&await t.catch(()=>{})}#ge(){if(this.streaming||this.status===`paused`||this.status===`resuming`)throw new Ff(`conversation_busy`,`Finish or stop the current turn before switching conversations`)}listConversations(e){return this.#fe().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit===void 0?{}:{limit:e.limit},...e?.targetId===void 0?{}:{targetId:e.targetId},context:this.#pe(e?.scope)})}async openConversation(e,t){let n=this.#fe();t?.busy===`background`&&this.assertBackgroundSwitchable(),t?.busy===`stop`&&this.cancel(),t?.busy!==`background`&&this.#ge();let r=this.#pe(t?.scope),i=++this.#M,a=this.#N;if(t?.busy===`background`&&await this.#lt(),await this.awaitHistorySettled(),i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new Ff(`superseded`,`A later selection won`);let s=await n.prepareOpen(e,{context:r}),c=this.#F.then(async()=>{if(i!==this.#M)throw s.discard(),new Ff(`superseded`,`A later selection won`);t?.busy===`stop`&&this.cancel();try{t?.busy===`background`?this.assertBackgroundSwitchable():this.#ge()}catch(e){throw s.discard(),e}let r=this.#k,c=this.#e;t?.onBeforeCommit?.(),t?.busy===`background`&&(this.#m=[]),this.#I=!0,this.#P=a;try{if(await this.#Ce(s),a!==this.#N||n!==this.#de)throw new Ff(`superseded`,`The history identity changed`);if(t?.busy===`background`&&r&&this.#u){let e={conversationId:r,handle:this.#u,messages:this.messages,artifacts:this.getArtifacts(),selectedArtifactId:this.#b,streamCheckpoint:this.#p};this.#h?.save(e)}this.#k=s.conversationId||e,this.#A=s.conversationRevision||o.conversationRevision||null,this.#j=o.nextCursor,this.#L=null,this.#R=!1,this.#Te();for(let e of o.messages)this.#H.set(e.id,e.content);this.#we();let i=this.#h?.take(this.#k);return this.hydrateMessages(i?.messages??o.messages),i&&(this.hydrateArtifacts(i.artifacts,i.selectedArtifactId,!0),this.#mt(i)),t?.onCommitted?.(),this.#me(),{summary:o.summary,nextMessageCursor:o.nextCursor}}finally{this.#I=!1,this.#P=null;let e=this.#m;if(this.#m=null,e&&this.#e===c&&this.#k===r)for(let{event:t,readOnlyReplay:n}of e)this.handleEvent(t,n)}}),l=c.then(()=>{},()=>{});this.#F=l,this.#z=l;try{return await c}finally{this.#z===l&&(this.#z=null)}}loadOlderMessages(e,t,n){let r=this.#fe(),i=this.#pe(n?.scope),a=t??this.#j;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let o=`${e} ${a}`,s=this.#B.get(o);if(s)return s;let c=this.#_e(r,e,a,i).finally(()=>{this.#B.delete(o)});return this.#B.set(o,c),c}async#_e(e,t,n,r){let i=this.messages[0]?.createdAt,a=await e.getPage(t,{cursor:n,...i?{beforeCreatedAt:i}:{},context:r});if(this.#k&&this.#k!==t)return{messages:[],nextMessageCursor:a.nextCursor};let o=this.#ve(a.messages),s=ud(this.messages,o);this.messages=this.#Rt(s.map(e=>this.#Ft(e))),this.#j=a.nextCursor;for(let e of a.messages)this.#H.set(e.id,e.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.#me(),{messages:o,nextMessageCursor:a.nextCursor}}#ve(e){let t=new Map(this.messages.map(e=>[e.id,e]));return e.map(e=>{let n=t.get(e.id);if(n){if(this.webMcpApprovalResolvers.has(n.id)||n.approval&&Fu(n.approval)&&n.approval.id===e.approval?.id&&n.approval.status!==`pending`&&e.approval?.status===`pending`)return n;let t=n.agentMetadata?.executionId,r=[...n.toolCall?[n.toolCall]:[],...n.tools??[]];if(t&&r.some(e=>this.webMcpInflightKeys.has(`${t}:${e.id}`)||this.webMcpResolvedKeys.has(`${t}:${e.id}`)))return n}return Iu(e)})}async startNewConversation(e){let t=this.#fe(),n=this.#pe(e?.scope),r=++this.#M,i=this.#N;await this.awaitHistorySettled();let a=await t.prepareStartNew({context:n}),o=this.#F.then(async()=>{if(r!==this.#M)throw a.discard(),new Ff(`superseded`,`A later action won`);e?.onBeforeCommit?.(),this.#I=!0,this.#P=i;try{await this.#Ce(a)}finally{this.#I=!1,this.#P=null}if(i!==this.#N||t!==this.#de)throw new Ff(`superseded`,`The history identity changed`);this.#Ee(!1,!0),this.#k=a.conversationId||null,this.#A=a.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.clientSession&&this.#le(this.clientSession),e?.onCommitted?.(),this.#me()}),s=o.then(()=>{},()=>{});this.#F=s,this.#z=s;try{await o}finally{this.#z===s&&(this.#z=null)}}async#ye(e,t=!1){this.#Ee(t),await this.#Ce(e),this.#k=e.conversationId||null,this.#A=e.conversationRevision||null,this.#j=null,this.#L=null,this.#R=!1,this.#we(),this.#me()}async deleteConversation(e,t){let n=this.#fe(),r=this.#pe(t?.scope);await this.awaitHistorySettled(),await n.delete(e,{context:r}),this.#h?.clear(e),e===this.#k&&await this.#be(r)}async updateConversation(e,t,n){let r=this.#fe();if(!r.update)throw new Ff(`history_unavailable`,`This history provider cannot update conversations`);let i=this.#pe(n?.scope);return await this.awaitHistorySettled(),r.update(e,t,{context:i})}canUpdateConversations(){return typeof this.#de?.update==`function`}async clearConversationHistory(e){let t=this.#fe(),n=this.#pe(e?.scope);await this.awaitHistorySettled();let r=await t.deleteAll({...e?.targetId===void 0?{}:{targetId:e.targetId},context:n});return this.#ut(),await this.#be(n),r}async resetHistoryDevice(){let e=this.#fe();if(!e.resetDevice)throw new Ff(`history_unavailable`,`This history provider cannot reset the device`);this.#ut(),this.#M+=1,this.#N+=1,this.#V=null;try{return await e.resetDevice()}finally{this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#R=!1,this.#me()}}async#be(e){this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(),this.#k=null,this.#A=null,this.#j=null,this.#R=!0,this.#L=null,this.#me(),await this.#xe(e)}async#xe(e){let t=this.#de;if(!t)this.#R=!1,this.#me();else try{let n=await t.prepareStartNew({context:e});await this.#ye(n)}catch{this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`)}}async#Se(){if(this.#L===`new_conversation_required`&&this.#de&&(this.#L=null,await this.#xe(this.#pe()),this.#L===`new_conversation_required`))throw new Ff(`new_conversation_required`,`A new conversation is required before sending`)}async#Ce(e){if(await e.commit(),this.#P!==null&&this.#P!==this.#N)return;let t=this.client.getClientSession();t&&t.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(t)}bindActivatedSession(e){(this.#P===null||this.#P===this.#N)&&(this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.#k=e.conversationId,this.#A=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.#I||this.#le(e))}#we(){this.#k?this.config.setStoredConversationId?.(this.#k):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.#A),this.historyInternals.setStoredMessageCursor?.(this.#j)}#Te(){this.#t=void 0,this.historyInternals.setStoredResumableHandle?.(null),this.agentExecution=null,this.#ot(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.#H.clear(),this.#Pe(null)}#Ee(e=!1,t=!1){this.client.cancelStreams(),this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.#Tt(),this.#rt(),this.#Qe++,this.messages=[],this.#Te(),this.#B.clear(),t||this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),e||this.#kt(!1),this.#Ot(`idle`),this.callbacks.onMessagesChanged([...this.messages]),e||this.#a(`cancel`)}#De(e){this.#ut(),this.#M+=1,this.#N+=1,this.#V=null,this.#R=!0,this.#Ee(),this.#k=e.conversationId,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.#he(`history_continuity_reset`,`This browser was reconnected to a different conversation, so the previous messages were cleared.`),this.#z=Promise.resolve().then(()=>{this.#R=!1,this.#z=null,this.#me()})}#Oe(){let e=this.historyInternals.visitorStore??null;e!==this.#q&&(this.#K?.(),this.#K=null,this.#q=e,e&&(this.#K=e.subscribe(e=>this.#ke(e))))}#ke(e){if(e.source!==`external`||e.previousToken===null)return;this.#ut(),this.clientSession=null,this.client.handleExternalCredentialChange(),this.#M+=1,this.#N+=1,this.#V=null,this.#J=!0,this.#Y=null;let t=this.messages.length>0;t||this.#k!==null||(this.config.getStoredConversationId?.()??null)!==null?this.#Ee():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.#B.clear(),this.#Pe(null)),this.#k=null,this.#A=null,this.#j=null,this.#L=null,this.#me(),this.callbacks.onHistoryScopeInvalidated?.(),t&&this.#he(`history_continuity_reset`,`This browser's conversation history was reset in another tab, so the previous messages were cleared.`)}#Ae(){return this.#J?(this.#Y||=this.#je().finally(()=>{this.#Y=null}),this.#Y):Promise.resolve()}async#je(){if(!this.isClientTokenMode())this.#J=!1;else try{this.bindActivatedSession(await this.client.initSession()),this.#J=!1}catch{}}reconcileBootConversation(e){let t=this.#de,n=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.#k;if(!t||!n)return Promise.resolve();let r=this.#pe(e?.scope);this.#R=!0,this.#me();let i=this.#Me(t,n,r).finally(()=>{this.#R=this.#L!==null,this.#z===i&&(this.#z=null),this.#me()});return this.#z=i,i}async#Me(e,t,n){this.#k=t;let r=this.clientSession?.conversationRevision??this.#A??null,i=this.#G?this.#W:this.historyInternals.getStoredConversationRevision?.()??null;if(this.#G=!1,this.#j=this.historyInternals.getStoredMessageCursor?.()??this.#j,await this.replayPendingProjections(),r&&i&&r===i){this.#A=r;return}let a=await e.getPage(t,{context:n}),o=this.#ve(a.messages),s=new Set(a.messages.map(e=>e.id)),c=this.messages.some(e=>s.has(e.id)),l=a.messages[0]?.createdAt,u;if(!c)u=o.map(e=>this.#Ft(e));else{let e=this.#u?this.#d:null;u=ud(this.messages.filter(t=>s.has(t.id)||t.id===e?!0:l!==void 0&&t.createdAt<l),o).map(e=>this.#Ft(e))}this.#j=a.nextCursor,this.#A=a.conversationRevision||r||null,this.#H.clear();for(let e of a.messages)this.#H.set(e.id,e.content);this.#we(),this.#t=void 0,this.messages=this.#Rt(u),this.callbacks.onMessagesChanged([...this.messages])}#Ne(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}#Pe(e){this.#U=e,this.historyInternals.setPendingDisplayProjections?.(e)}#Fe(){return this.historyInternals.getPendingDisplayProjections?.()??this.#U}#Ie(e){if(this.#Ne())for(let t of e){let e=ld(t);e!==void 0&&this.#H.set(t.id,e)}}#Le(){if(!this.#Ne())return;let e=this.#k;if(!e)return;let t=[];for(let e of this.messages){if(e.role!==`assistant`||e.streaming)continue;let n=ld(e);n!==void 0&&this.#H.get(e.id)!==n&&t.push({id:e.id,displayContent:n})}t.length!==0&&(this.#Pe({conversationId:e,messageIds:t.map(e=>e.id)}),this.#Re(e,t))}#Re(e,t){let n=(this.#V??Promise.resolve()).catch(()=>{}).then(()=>this.#ze(e,t,!1)).finally(()=>{this.#V===n&&(this.#V=null)});this.#V=n}async#ze(e,t,n){if(this.#k!==e)return;let r=t.filter(e=>this.#H.get(e.id)!==e.displayContent);if(r.length===0)this.#Ve(e,t);else try{let{conversationRevision:n}=await this.client.finalizeDisplayProjections(e,r);for(let e of r)this.#H.set(e.id,e.displayContent);this.#k===e&&n&&(this.#A=n),this.#Ve(e,t)}catch(i){if(!n&&this.#Be(i)){await this.#ze(e,r,!0);return}if(i instanceof Fd&&(i.code===`not_found`||i.code===`conversation_deleted`)){this.#Ve(e,t);return}this.#he(`projection_finalization_failed`,`Some message formatting could not be saved for history; it will be retried.`)}}#Be(e){return e instanceof Fd?e.code===`request_failed`:e instanceof Error}#Ve(e,t){let n=this.#Fe();if(!n||n.conversationId!==e)return;let r=new Set(t.map(e=>e.id)),i=n.messageIds.filter(e=>!r.has(e));this.#Pe(i.length?{conversationId:e,messageIds:i}:null)}async replayPendingProjections(){if(!this.#Ne())return;let e=this.#Fe();if(!e)return;if(this.#k&&e.conversationId!==this.#k){this.#Pe(null);return}let t=[];for(let n of e.messageIds){let e=this.messages.find(e=>e.id===n);e&&typeof e.content==`string`&&t.push({id:n,displayContent:e.content})}t.length===0?this.#Pe(null):(this.#Re(e.conversationId,t),await this.#V?.catch(()=>{}))}#He(){this.#k&&(this.#A=null,this.historyInternals.setStoredConversationRevision?.(null))}async#Ue(){await this.awaitHistorySettled(),await this.#Ae(),this.#L===`new_conversation_required`&&await this.#Se()}static#We(e){return e instanceof Fd&&e.code===`conversation_deleted`}async#Ge(t,n,r,i,a){let o=this.#e,s=e=>{this.#e===o&&this.handleEvent(e)};this.#Ie(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,interrupt:a?.interrupt,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s);return}catch(t){if(n.signal.aborted||this.#e!==o||!e.#We(t))throw t;let c=await this.#Ke(i);if(!c)throw t;this.#Ie([c]),await this.client.dispatch({messages:[c],signal:n.signal,assistantMessageId:r,composerOptions:a?.composerOptions,voiceSpoken:a?.voiceSpoken,voicePriorToolResults:a?.voicePriorToolResults},s)}}async#Ke(e){let t=this.messages.find(t=>t.id===e);if(!t)return null;let n={...t};this.#M+=1,this.#N+=1,this.#V=null,this.#Ee(!0),this.#k=null,this.#A=null,this.#j=null,this.#I=!0;try{let e=this.#de;if(e){let t=await e.prepareStartNew({context:this.#pe()});await this.#ye(t,!0)}else{this.client.clearClientSession();let e=await this.client.initSession();this.bindActivatedSession(e)}}catch{return this.#R=!0,this.#L=`new_conversation_required`,this.#me(),this.#he(`new_conversation_required`,`That conversation was deleted. Start a new conversation to continue.`),null}finally{this.#I=!1}return this.#Pt(n),this.#kt(!0),this.#he(`conversation_deleted_recovered`,`That conversation was deleted. Started a new conversation.`),this.messages.find(e=>e.id===n.id)??n}updateConfig(e){let t=this.config.features?.artifacts?.display,n={...this.config,...e},r=gu(this.config,n),i=Pf(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&bu(n)&&this.setupVoice());let a=JSON.stringify(t)!==JSON.stringify(n.features?.artifacts?.display);if(!i){this.client.updateConfig(n),a&&this.#at();return}this.#rt(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.#M+=1,this.#N+=1,this.client=new Rd(this.config,this.historyInternals),a&&this.#at(),this.#Xe(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}getRunActivity(){return this.#t}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let t=this.#qe(e);return this.upsertMessage(t),t}#qe(e){let{role:t,content:n,llmContent:r,contentParts:i,id:a,createdAt:o,sequence:s,streaming:c=!1,voiceProcessing:l,voiceCaption:u,rawContent:d}=e;return{id:a??(t===`user`?Uc():t===`assistant`?Wc():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:t,content:n,createdAt:o??(/* @__PURE__ */ new Date()).toISOString(),sequence:s??this.#It(),streaming:c,...r!==void 0&&{llmContent:r},...i!==void 0&&{contentParts:i},...l!==void 0&&{voiceProcessing:l},...u&&{voiceCaption:u},...d!==void 0&&{rawContent:d},...e.dispatchError!==void 0&&{dispatchError:e.dispatchError}}}injectAssistantMessage(e){return this.injectMessage({...e,role:`assistant`})}injectUserMessage(e){return this.injectMessage({...e,role:`user`})}injectSystemMessage(e){return this.injectMessage({...e,role:`system`})}injectMessageBatch(e){let t=e.map(e=>this.#qe(e));return this.messages=this.#Rt([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:n={},text:r=``,llmContent:i,id:a,createdAt:o,sequence:s}=e,c={text:r,component:t,props:n};return this.injectMessage({role:`assistant`,content:r,rawContent:JSON.stringify(c),...i!==void 0&&{llmContent:i},...a!==void 0&&{id:a},...o!==void 0&&{createdAt:o},...s!==void 0&&{sequence:s}})}updateComponentProps(e,t){let n=this.messages.find(t=>t.id===e),r=n&&df(n);return!n||n.role!==`assistant`||n.variant||!r?!1:(this.upsertMessage({...n,rawContent:JSON.stringify({text:n.content,component:r.component,props:t})}),!0)}removeComponentMessage(e){let t=this.messages.find(t=>t.id===e);return!t||t.role!==`assistant`||t.variant||!df(t)?!1:(this.messages=this.messages.filter(t=>t.id!==e),this.callbacks.onMessagesChanged([...this.messages]),!0)}async#Je(e,t,n){let r;try{r=await n()}catch{return}let i=r.blocks.join(`
|
|
18
18
|
|
|
19
19
|
`),a=[i,t].filter(Boolean).join(`
|
|
20
20
|
|