@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.cjs
CHANGED
|
@@ -5,7 +5,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
5
5
|
`).replace(/\\r/g,`\r`).replace(/\\t/g,` `).replace(/\\"/g,`"`).replace(/\\\\/g,`\\`),Qe=()=>{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 Ze(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()=>{}}},$e=e=>{try{let t=JSON.parse(e);if(t&&typeof t==`object`&&typeof t.text==`string`)return t.text}catch{return null}return null},et=()=>{let e={processChunk:e=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},tt=()=>Qe(),nt=()=>{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=(0,p.parse)(n,p.STR|p.OBJ);t&&typeof t==`object`&&(t.component&&typeof t.component==`string`?e=typeof t.text==`string`?Ze(t.text):``:t.type===`init`&&t.form?e=``:typeof t.text==`string`&&(e=Ze(t.text)))}catch{}return t=n.length,e===null?null:{text:e,raw:n}},close:()=>{}}},rt=e=>{let t=null,n=0,r=e||(e=>{if(!e||typeof e!=`object`)return null;let t=e=>typeof e==`string`?Ze(e):null;if(e.component&&typeof e.component==`string`)return typeof e.text==`string`?Ze(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=(0,p.parse)(e,p.STR|p.OBJ),i=r(n);i!==null&&(t=i)}catch{}return n=e.length,{text:t||``,raw:e}},close:()=>{}}},it=()=>{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 ot(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]=st(t)&&st(r)?ot(t,r):r}return n}var st,ct=o((()=>{st=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),lt,ut,dt,ft,pt,mt,ht,I=o((()=>{ct(),lt=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},ut=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),dt=e=>`#`+e.map(e=>Math.round(e).toString(16).padStart(2,`0`)).join(``),ft=(e,t,n)=>dt(e.map(e=>e+(t-e)*n)),pt=e=>ut(e)>.179?`#000000`:`#ffffff`,mt=e=>{let t=lt(e?.neutral);return t?ut(t)<.18?`dark`:`light`:void 0},ht=(e,t=`light`,n,r=!1)=>{let i={};if(!e)return i;let a=lt(e.accent);if(a){let e={};for(let[t,n]of[[50,.96],[100,.9],[200,.75],[300,.55],[400,.25]])e[t]=ft(a,255,n);e[500]=dt(a);for(let[t,n]of[[600,.15],[700,.3],[800,.45],[900,.6],[950,.75]])e[t]=ft(a,0,n);let t=pt(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=lt(e.neutral);if(o){let e=t===`dark`,n=e===ut(o)<.18?o:lt(ft(o,e?0:255,.9)),r=dt(n),a=ft(n,e?255:0,e?.06:.025),s=ft(n,e?255:0,e?.2:.16),c=pt(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]=ft(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:ft(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=lt(i.semantic?.colors?.surface)??(t===`dark`?[15,15,16]:[255,255,255]),n=dt(a),r=pt(e)===`#ffffff`?255:0;for(let t=0;t<=1;t+=.1){n=ft(a,r,t);let i=ut(lt(n)),o=ut(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=ot(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 L(e,t=``){return Object.entries(e).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return yt(n)?L(n,r):[r]})}function gt(e,t){let n=t.split(`.`);for(let t=0;t<n.length;t++){let r=n[t];if(!yt(e)||!Object.prototype.hasOwnProperty.call(e,r))return`absent`;if(e=e[r],e===void 0||t<n.length-1&&!yt(e))return`clear`}return`explicit`}function R(e,t){return e?.[vt]??t.filter(t=>gt(e,t)===`explicit`)}function z(e,t){return Object.defineProperty(e,vt,{value:t,enumerable:!0,configurable:!0}),e}function B(e,t,n){return z(e,R(t,L(n)))}function V(e,t,n){let r=t[vt];if(r)return r;let i=new Set(R(e,n));for(let e of n){let n=gt(t,e);n===`clear`&&i.delete(e),n===`explicit`&&i.add(e)}return[...i]}function _t(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(!yt(t)){i=void 0;break}i[e]={...t},i=i[e]}i&&delete i[t[t.length-1]]}return r}var vt,yt,H=o((()=>{vt=Symbol.for(`persona.defaultsProvenance`),yt=e=>typeof e==`object`&&!!e&&!Array.isArray(e)})),bt,xt,U,St,Ct,wt,Tt,Et,Dt,Ot,kt,At,jt,Mt,W=o((()=>{I(),H(),bt=(e,t)=>t.split(` `).map(t=>`${e}.${t}`),xt=[...bt(`launcher`,`closeButtonSize closeButtonColor closeButtonBackgroundColor closeButtonBorderWidth closeButtonBorderColor closeButtonBorderRadius closeButtonPaddingX closeButtonPaddingY`),...bt(`launcher.clearChat`,`size iconColor backgroundColor borderWidth borderColor borderRadius paddingX paddingY`),...bt(`sendButton`,`size iconSize iconStrokeWidth backgroundColor textColor borderWidth borderColor paddingX paddingY`),...bt(`voiceRecognition`,`iconSize iconColor backgroundColor borderColor borderWidth paddingX paddingY recordingIconColor recordingBackgroundColor recordingBorderColor processingIconColor processingBackgroundColor processingBorderColor speakingIconColor speakingBackgroundColor speakingBorderColor`),...bt(`toolCall`,`shadow backgroundColor borderColor borderWidth borderRadius headerBackgroundColor headerTextColor headerPaddingX headerPaddingY contentBackgroundColor contentTextColor contentPaddingX contentPaddingY codeBlockBackgroundColor codeBlockBorderColor codeBlockTextColor toggleTextColor labelTextColor loadingAnimationColor loadingAnimationSecondaryColor loadingAnimationDuration`),...bt(`approval`,`backgroundColor borderColor shadow titleColor descriptionColor reasonColor approveButtonColor approveButtonTextColor denyButtonColor denyButtonTextColor parameterBackgroundColor parameterTextColor`),...bt(`features.askUserQuestion.styles`,`sheetBackground sheetBorder sheetShadow pillBackground pillBackgroundSelected pillTextColor pillTextColorSelected pillBorderRadius customInputBackground`),...bt(`features.artifacts.layout`,`paneBackground panePadding paneBorderRadius paneShadow chatShadow paneBorder paneBorderLeft unifiedSplitOuterRadius documentToolbarIconColor documentToolbarToggleActiveBackground documentToolbarToggleActiveBorderColor documentToolbarToggleActiveColor tabFadeSize`),...bt(`suggestionChipsConfig`,`fontWeight paddingX paddingY`)],U=[`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`],St=[...xt,`suggestionChips`,`copy.welcomeTitle`,`copy.welcomeSubtitle`,`copy.showWelcomeCard`,`features.suggestReplies.enabled`,`features.suggestReplies.expose`,...[`theme`,`darkTheme`].flatMap(e=>U.map(t=>`${e}.components.${t}`))],Ct=Symbol.for(`persona.styleProvenance`),wt=e=>e[Ct]!==void 0,Tt=(e,t)=>{for(let n of t.split(`.`)){if(typeof e!=`object`||!e)return;e=e[n]}return e},Et=e=>{let t=e?.[Ct];if(!t)return St.filter(t=>gt(e,t)===`explicit`);let n=new Set(t.explicit);return St.forEach(r=>{Tt(e,r)!==t.values[r]&&(gt(e,r)===`explicit`?n.add(r):n.delete(r))}),[...n]},Dt=(e,t)=>(Object.defineProperty(e,Ct,{value:{explicit:t,values:Object.fromEntries(St.map(t=>[t,Tt(e,t)]))},enumerable:!0,configurable:!0}),e),Ot=(e,t)=>Dt(e,Et(t)),kt=(e,t)=>{if(t[Ct])return Et(t);let n=new Set(Et(e));for(let e of St){let r=gt(t,e);r===`clear`&&n.delete(e),r===`explicit`&&n.add(e)}return[...n]},At=(e,t)=>{let n=e?.[Ct];return!n||!Object.prototype.hasOwnProperty.call(n.values,t)||Tt(e,t)!==n.values[t]?gt(e,t)===`explicit`:n.explicit.includes(t)},jt=(e,t)=>At(e,t)?Tt(e,t):void 0,Mt=(e,t,n)=>{let r=e,i=n??r?.colorScheme??mt(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 At(e,`theme.components.${t}`)||a&&At(e,`darkTheme.components.${t}`)}})),G,K,Nt,Pt=o((()=>{G=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},K=(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},Nt=(...e)=>e.filter(Boolean).join(` `)})),Ft,It,Lt,Rt,zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt,Zt,Qt,$t,en,tn,nn,rn,an,on,sn,cn,ln,un,dn,fn,pn,mn,hn,gn,_n,vn,yn,bn,q,J,Y,xn,Sn,Cn,wn,Tn,En,Dn,On,kn,An,jn,Mn,Nn,Pn=o((()=>{W(),Pt(),Ft=`ask_user_question`,It=`data-persona-ask-sheet-for`,Lt=`Other`,Rt=`Other…`,zt=`Type your own answer here`,Bt=`Send`,Vt=`Next`,Ht=`Back`,Ut=`Submit all`,Wt=`Skip`,Gt=3,Kt=`data-ask-current-index`,qt=`data-ask-question-count`,Jt=`data-ask-answers`,Yt=`data-ask-grouped`,Xt=`data-ask-layout`,Zt=e=>e.layout===`pills`?`pills`:`rows`,Qt=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`,$t=!1,en=e=>e.replace(/["\\]/g,`\\$&`),tn=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,nn=e=>e?.features?.askUserQuestion??{},rn=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=(0,p.parse)(e,p.STR|p.OBJ|p.ARR);if(t&&typeof t==`object`)return{payload:t,complete:n}}catch{}return{payload:null,complete:n}},an=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!$t&&($t=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},on=e=>an(e)[0]??null,sn=(e,t)=>an(e)[t]??null,cn={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`},ln=(e,t)=>{Object.entries(cn).forEach(([n,r])=>{let i=jt(t,`features.askUserQuestion.styles.${n}`);typeof i==`string`&&i?e.style.setProperty(r,i):e.style.removeProperty(r)})},un=(e,t,n)=>{if(e!==`rows`)return null;let r=G(`span`,`persona-ask-row-affordance`);if(r.setAttribute(`aria-hidden`,`true`),t){let e=G(`span`,`persona-ask-row-check`);r.appendChild(e)}else{let e=G(`span`,`persona-ask-row-badge`);e.textContent=String(n+1),r.appendChild(e)}return r},dn=(e,t,n,r)=>{let i=G(`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=G(`span`,`persona-ask-row-content`),o=G(`span`,`persona-ask-row-label`);if(o.textContent=e.label,a.appendChild(o),e.description){let t=G(`span`,`persona-ask-row-description`);t.textContent=e.description,a.appendChild(t)}i.appendChild(a);let s=un(n,r,t);s&&i.appendChild(s)}else i.textContent=e.label,e.description&&(i.title=e.description);return i},fn=e=>{let t=G(`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},pn=(e,t,n,r)=>{let i=G(`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<Gt;e++)i.appendChild(fn(r));return i}if(o.forEach((e,t)=>{i.appendChild(dn(e,t,r,a))}),e?.allowFreeText!==!1){let e=r===`rows`?Lt:Rt;if(r===`rows`){let n=G(`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=G(`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??zt,c.setAttribute(`data-ask-free-text-input`,`true`),c.setAttribute(`aria-label`,t.freeTextLabel??e),s.appendChild(c),n.appendChild(s);let l=un(r,a,o.length);l&&n.appendChild(l),i.appendChild(n)}else{let n=G(`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},mn=(e,t)=>{let n=G(`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??zt,r.setAttribute(`data-ask-free-text-input`,`true`),n.appendChild(r),t!==`rows`){let t=G(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);t.type=`button`,t.textContent=e.submitLabel??Bt,t.setAttribute(`data-ask-user-action`,`submit-free-text`),n.appendChild(t)}return n},hn=e=>{let t=G(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);t.setAttribute(`data-ask-multi-actions`,`true`);let n=G(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return n.type=`button`,n.textContent=e.submitLabel??Bt,n.setAttribute(`data-ask-user-action`,`submit-multi`),n.disabled=!0,t.appendChild(n),t},gn=(e,t,n)=>{let r=G(`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=G(`button`,`persona-ask-nav-back persona-pointer-events-auto`);i.type=`button`,i.textContent=n.backLabel??Ht,i.setAttribute(`data-ask-user-action`,`back`),i.disabled=e===0,r.appendChild(i);let a=G(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),o=G(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);o.type=`button`,o.textContent=n.skipLabel??Wt,o.setAttribute(`data-ask-user-action`,`skip`),a.appendChild(o);let s=G(`button`,`persona-ask-nav-next persona-pointer-events-auto`);s.type=`button`;let c=e===t-1;return s.textContent=c?n.submitAllLabel??Ut:n.nextLabel??Vt,s.setAttribute(`data-ask-user-action`,c?`submit-all`:`next`),s.disabled=!0,a.appendChild(s),r.appendChild(a),r},_n=e=>{let t=e.getAttribute(Jt);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},vn=(e,t)=>{e.setAttribute(Jt,JSON.stringify(t))},yn=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},bn=(e,t)=>{e.setAttribute(Kt,String(Math.max(0,Math.floor(t))))},q=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},J=e=>e.getAttribute(Yt)===`true`,Y=(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},xn=(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)))},Sn=(e,t)=>{let{payload:n}=rn(t),r=an(n),i=_n(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},Cn=e=>{let t=_n(e)[yn(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=``)},wn=e=>{if(!J(e))return;let t=_n(e)[yn(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)},Tn=(e,t,n)=>{let r=nn(n),i=Qt(e),{payload:a,complete:o}=rn(t),s=J(e),c=yn(e),l=q(e),u=s?sn(a,c):on(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=pn(u,r,o,i);h.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(mn(r,i))}let g=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!g?e.appendChild(hn(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=gn(c,l,r);_?_.replaceWith(t):e.appendChild(t)}else _&&_.remove();Cn(e),wn(e)},En=(e,t,n)=>{let r=nn(t),i=Zt(r),a=e.toolCall.id,o=an(n),s=Math.max(1,o.length),c=s>1,l=Y(e,o),u=c?xn(e,s):0,d=G(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${i}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));d.setAttribute(It,a),d.setAttribute(`data-tool-call-id`,a),d.setAttribute(`data-message-id`,e.id),d.setAttribute(qt,String(s)),d.setAttribute(Kt,String(u)),d.setAttribute(Yt,c?`true`:`false`),d.setAttribute(Xt,i),vn(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`),ln(d,t);let f=G(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),p=G(`div`,`persona-ask-sheet-question persona-flex-1`);p.setAttribute(`data-ask-question`,`true`),p.textContent=``,f.appendChild(p);let m=G(`span`,`persona-ask-sheet-step-inline`);m.setAttribute(`data-ask-step-inline`,`true`),m.textContent=``,f.appendChild(m),d.appendChild(f);let h=G(`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(mn(r,i)),Tn(d,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>d.classList.remove(`persona-ask-sheet-enter`))}),d},Dn=(e,t,n)=>{ln(e,n);let{payload:r}=rn(t),i=Math.max(1,an(r).length);i>q(e)&&(e.setAttribute(qt,String(i)),i>1&&!J(e)&&e.setAttribute(Yt,`true`)),Tn(e,t,n)},On=(e,t)=>{let n=G(`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`),ln(n,t);let r=G(`span`,`persona-ask-stub-label`),{complete:i}=rn(e);return r.textContent=i?`Awaiting your response…`:`Preparing options…`,n.appendChild(r),n},kn=(e,t,n)=>{if(!n||!tn(e)||nn(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${It}]`).forEach(e=>{e.getAttribute(It)!==r&&e.remove()});let i=n.querySelector(`[${It}="${en(r)}"]`);if(i){Dn(i,e,t);return}let{payload:a}=rn(e),o=En(e,t,a);n.appendChild(o)},An=(e,t)=>{if(!e)return;let n=t?`[${It}="${en(t)}"]`:`[${It}]`;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)})},jn=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),Mn=(e,t)=>{let n=_n(e),r=yn(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,vn(e,n),Cn(e),wn(e)},Nn=(e,t,n,r)=>{let i=q(e),a=Math.max(0,Math.min(i-1,r));bn(e,a),Tn(e,t,n)}})),Fn,In,Ln,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn=o((()=>{Fn=`suggest_replies`,In={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},Ln={name:Fn,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:In,origin:`sdk`,annotations:{readOnlyHint:!0}},Rn=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?Ln:{...Ln,parametersSchema:{...In,properties:{suggestions:{...In.properties.suggestions,maxItems:n,description:`1-${n} short, distinct follow-up replies, phrased in the user's voice.`}}}}},zn=()=>({content:[{type:`text`,text:`Suggestions shown to the user.`}]}),Bn=e=>e.variant===`tool`&&e.toolCall?.name===`suggest_replies`,Vn=(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},Hn=(e,t=4)=>{for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role===`user`)return null;if(!Bn(r))continue;let i=Vn(r.toolCall?.args,t);return i.length>0?i:null}return null},Un=/* @__PURE__ */ new Set,Wn=(e,t,n)=>{let r=`${e}:${t}:${n}`;Un.has(r)||(Un.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Gn=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&&Wn(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}}})),qn,Jn,Yn,Xn=o((()=>{Pn(),Kn(),qn={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},Jn={name:Ft,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:qn,origin:`sdk`,annotations:{readOnlyHint:!0}},Yn=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Jn),Gn(e).expose&&t.push(Rn(e)),t}})),Zn,Qn,$n,er=o((()=>{Zn={idle:`Online`,connecting:`Connecting…`,connected:`Streaming…`,error:`Offline`,paused:`Connection lost…`,resuming:`Reconnecting…`},Qn=1e5,$n=100001}));async function tr(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 nr(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=[...Yn(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 rr=o((()=>{Xn(),er()})),X=/* @__PURE__ */ s({preferFinalStructuredContent:()=>ar,resolveApproval:()=>tr,resumeFlow:()=>nr,streamResponse:()=>sr});function ir(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 ar(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(!n)return t;if(!r)return e;let i=lr(n);if(!lr(r))return e;if(!i||r.startsWith(n))return t;let a=$e(e);return $e(t)!==null&&a===null?t:e}async function or(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 sr(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),D=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,te=/* @__PURE__ */ new Map,ne=/* @__PURE__ */ new Map,re=/* @__PURE__ */ new Map,k=r,ie=!1,ae=o?.find(e=>e.id===r);ae&&(x=v(ae),x.streaming=s?.openAssistant??!0,ie=!0,w=ae.agentMetadata?.textBlockId??null,T=ae.rawContent??ae.content,S=x,s&&!s.openAssistant&&(x=null)),s&&(w=s.textBlockId,T=s.rawText,s.nestedParents.forEach(([e,t])=>D.set(e,t)),s.nestedRaw.forEach(([e,t])=>te.set(e,t)));for(let e of o??[]){e.variant===`tool`&&e.toolCall?.id&&re.set(e.toolCall.id,v(e)),e.variant===`reasoning`&&e.reasoning?.id&&ne.set(e.reasoning.id,v(e));let t=e.agentMetadata?.textBlockId;t&&(O.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&&(D.set(t,n),te.set(t,e.rawContent??e.content))}let A=()=>{if(x)return x;let e,t=``,n=w;return!ie&&k?(e=k,ie=!0,t=i??``):e=k&&n?`${k}_${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},oe=(e,t)=>{let n=ne.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 ne.set(e,r),b(r),r},j=/* @__PURE__ */ new Set,se=/* @__PURE__ */ new Map,ce=/* @__PURE__ */ new Set;for(let e of o??[])if(e.id.startsWith(`artifact-ref-`)){let t=e.id.slice(13);ce.add(t),se.set(t,v(e))}s?.artifactTools.forEach(e=>j.add(e));let le=/* @__PURE__ */ new Map;s?.artifactContent.forEach(([e,t])=>le.set(e,{...t}));let ue=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},de=(e,t,n)=>{let r=re.get(e),i={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(we||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 re.set(e,a),b(a),a},fe=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()},pe=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},me=/* @__PURE__ */ new Map,M=/* @__PURE__ */ new Map,he=(e,t)=>{let n=pe(t),r=ar(M.get(e.id),n);e.rawContent=r;let i=me.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(()=>{}),me.delete(e.id),M.delete(e.id),e.streaming=!1,b(e)};if(!i){a(n),o();return}let s=$e(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())},ge=null,_e=o?.find(e=>e.id===s?.sealedFlowMessageId);_e&&(ge=v(_e));let ve=(t,n,r)=>{t.rawContent=n,me.has(t.id)||me.set(t.id,e.createStreamParser());let i=me.get(t.id),a=/^[{[]/.test(n.trim());a&&M.set(t.id,n);let o=()=>{t.content+=r,M.delete(t.id),me.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)},ye=(e,t)=>{let n=t??e.content;if(n==null||n===``){e.streaming=!1,b(e);return}let r=M.get(e.id)??pe(n);e.rawContent=r;let i=me.get(e.id),a=null,o=!1;if(i&&(a=i.getExtractedText(),a===null&&(a=$e(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,me.delete(e.id),M.delete(e.id),b(e))}).catch(()=>{})):a=typeof t==`string`?t:t?.text??null}if(!o){a!==null&&a.trim()!==``?e.content=a:M.has(e.id)||(e.content=pe(n));let t=me.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),me.delete(e.id)}M.delete(e.id),e.streaming=!1,b(e)}},be=(e,t,n,r)=>{let i=O.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 O.set(e,a),b(a),a},xe=[],Se,Ce=/* @__PURE__ */ new Map;s?.media.forEach(([e,t])=>Ce.set(e,{...t,parts:[...t.parts]}));let we=s?.iteration??0,N=s?.executionKind??`agent`,Te=s?.executionKindResolved??!1,P=s?.turnId??null,Ee=null,De=e.config().iterationDisplay??`separate`;Se=()=>{for(let t=0;t<xe.length;t++){let r=xe[t];if(!Te&&N!==`flow`&&typeof r.stepType==`string`&&(N=`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){D.set(e,t),be(e,t,`reasoning`,r.executionId);continue}let n=r.id,i=oe(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&&D.has(e)&&O.has(e)){let t=O.get(e),n=r.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=r.id,n=oe(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&&D.has(e)&&O.has(e)){let t=O.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)}D.delete(e),O.delete(e);continue}let t=r.id,n=typeof r.text==`string`?r.text:``;!ne.get(t)&&(n||r.scope===`loop`)&&oe(t,r.executionId);let i=ne.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`&&(we=r.iteration);let e=r.toolCallId,t=r.toolName;if(ue(t)){j.add(e);continue}let n=de(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??fe(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(j.has(e))continue;let t=de(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(j.has(e)){j.delete(e);continue}let t=de(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=de(t,r.executionId),i=r.toolName,a=r.origin===`webmcp`&&!ze(i)?`webmcp:${i}`:i,o=ze(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??fe(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=cr(r.phase);t?E.set(e,t):E.delete(e)}let t=typeof r.parentToolCallId==`string`&&r.parentToolCallId?r.parentToolCallId:null;if(e&&t){D.set(e,t);continue}let n=x;n&&(N===`flow`?(ye(n),ge=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?D.get(e):void 0;if(e&&t){let n=typeof r.delta==`string`?r.delta:``,i=(te.get(e)??``)+n;if(te.set(e,i),i.trim()===``)continue;let a=be(e,t,void 0,r.executionId);ve(a,i,n);continue}w=e??w;let n=typeof r.delta==`string`?r.delta:``;if(T+=n,N===`flow`&&T.trim()===``)continue;let i=A();i.agentMetadata={textBlockId:w??void 0,phase:E.get(w??``),executionId:r.executionId,iteration:we,...N===`flow`?{}:{turnId:P??void 0,agentName:Ee?.agentName}},w&&O.set(w,i),ve(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?O.get(e):x,n=cr(r.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&D.has(e)){let t=O.get(e);t&&ye(t),D.delete(e),te.delete(e),O.delete(e);continue}if(e&&t!==x){t&&(t.streaming=!1,b(t));continue}let i=x;i&&(N===`flow`?(ye(i),ge=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=ge;ge=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&&(me.delete(e.id),M.delete(e.id),e.streaming=!1,b(e)):he(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=A();t&&(r.stopReason=t),e?ye(r,n):(r.streaming=!1,b(r))}}continue}}else if(r.type===`execution_start`)N=r.kind===`flow`?`flow`:`agent`,Te=!0,e.config().backgroundConversations&&n({type:`status`,status:`connected`,executionId:r.executionId}),N===`agent`&&(Ee={executionId:r.executionId,agentId:r.agentId??`virtual`,agentName:r.agentName??``});else if(r.type===`turn_start`){let e=typeof r.iteration==`number`?r.iteration:we;if(e!==we){if(De===`separate`&&e>1){let e=x;e&&(e.streaming=!1,b(e),x=null)}we=e}P=typeof r.id==`string`?r.id:null,S=null}else if(r.type===`tool_input_delta`){let e=r.toolCallId;if(e){let t=re.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(j.has(r.toolCallId))continue;let e=de(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))}P===r.id&&(P=null)}else if(r.type===`media_start`){let e=String(r.id);Ce.set(e,{mediaType:typeof r.mediaType==`string`?r.mediaType:void 0,toolCallId:r.toolCallId,parts:[]})}else if(r.type===`media_delta`){let e=Ce.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=Ce.get(e);Ce.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:ir(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:we}};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?ye(e):(e.streaming=!1,b(e)),x=null),w=null,T=``,ge=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:Ee?.agentId??`virtual`,executionId:r.executionId??Ee?.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:Ee?.agentId??`virtual`,executionId:r.executionId??Ee?.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}:{}}),le.set(i,{markdown:``,title:a,file:s}),!ce.has(i)){ce.add(i);let n=Ke(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:qe(n,{artifactId:i,title:a,artifactType:t,status:`streaming`,...s?{file:s}:{},...o?{component:o}:{}})};se.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=le.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=le.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=se.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=le.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{}le.delete(e),b(t),se.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`})}}}xe.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:ge?.id??null,rawText:T,executionKind:N,executionKindResolved:Te,turnId:P,iteration:we,textPhases:[...E],nestedParents:[...D],nestedRaw:[...te],media:[...Ce].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...le].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...j]}}:{}})};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 or(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&&(xe.push({...d,type:f}),Se()),l()}}Se()}finally{e.streamReaders.delete(l),a?.removeEventListener(`abort`,d),l.releaseLock()}}var cr,lr,ur=o((()=>{Ve(),Je(),at(),rr(),cr=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0,lr=e=>/^[{[<]/.test(e)}));ur(),g();const{setLoader:dr,load:fr,provide:pr,getSync:mr}=h({fallbackImport:()=>Promise.resolve().then(()=>(ur(),X))}),hr=fr,gr=pr,_r=mr;gr(X);var vr=`4.32.1`,yr,br=o((()=>{yr=vr})),xr=/* @__PURE__ */ s({deleteAllConversations:()=>Ir,deleteConversation:()=>Fr,finalizeDisplayProjections:()=>Pr,getConversation:()=>Nr,historyErrorFor:()=>Or,listConversations:()=>Mr,readErrorCode:()=>Er,recoverFromUnauthorized:()=>Dr,resetVisitor:()=>Lr});function Sr(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 Cr(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function wr(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 Tr(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`,Vr);return i}async function Er(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function Dr(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`,Hr);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,Ur);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`,Wr);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 Or(e,t,n){let r=await Er(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`,Vr);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`,Hr)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,Ur):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,Wr):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function kr(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 Ar(e,t,n){jr(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Cr(e,n.scope)===`verified-user`&&(a=await wr(e,i,r),a&&(i=await Tr(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(Sr(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":yr,...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 Dr(e,await Er(e,u),a,r);continue}if(!u.ok)throw await Or(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 kr(e,d,a!==null,r),f}}function jr(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 Mr(e,t){let n=await Ar(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(Br),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Nr(e,t,n){let r=await Ar(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Br(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 Pr(e,t,n){jr(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Rr)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Rr} character limit`);r+=n}if(r>zr)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${zr} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ar(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=zr,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 Fr(e,t,n){let r=await Ar(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function Ir(e,t){let n=await Ar(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 Lr(e){jr(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ar(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Rr,zr,Br,Vr,Hr,Ur,Wr,Gr=o((()=>{br(),Rr=32768,zr=49152,Br=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:``}},Vr=`The identity proof was not admitted; account history is unavailable`,Hr=`The identity proof was rejected`,Ur=`The request carried no visitor credential`,Wr=`The stored visitor belongs to a different signed-in user`}));Gr(),g();const{setLoader:Kr,load:qr,provide:Jr}=h({fallbackImport:()=>Promise.resolve().then(()=>(Gr(),xr))}),Yr=qr;Jr(xr);var Xr,Zr=o((()=>{Pn(),Xr=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})),An(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:Sn(e,i),currentIndex:yn(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=yn(t);if(n>=q(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Nn(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})),An(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=J(u);if(n&&t){let t=_n(u)[yn(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Mn(u,Array.from(n)),a(u);return}if(n){Mn(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=jn(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=jn(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(J(u)){Mn(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=_n(u)[yn(u)];(typeof e!=`string`||e!==i)&&Mn(u,i)}let o=d===`next`?1:-1,s=yn(u)+o;Nn(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&&Mn(u,n);let a=Sn(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:yn(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=J(u),d=yn(u),f=d>=q(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:s},bubbles:!0,composed:!0})),An(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Mn(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Sn(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Nn(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()&&(J(n)?(Mn(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function Qr(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:ge?.id??null,rawText:T,executionKind:N,executionKindResolved:Te,turnId:P,iteration:we,textPhases:[...E],nestedParents:[...D],nestedRaw:[...te],media:[...Ce].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...le].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...j]}}:{}})};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 or(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&&(xe.push({...d,type:f}),Se()),l()}}Se()}finally{e.streamReaders.delete(l),a?.removeEventListener(`abort`,d),l.releaseLock()}}var cr,lr,ur=o((()=>{Ve(),Je(),at(),rr(),cr=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0,lr=e=>/^[{[<]/.test(e)}));ur(),g();const{setLoader:dr,load:fr,provide:pr,getSync:mr}=h({fallbackImport:()=>Promise.resolve().then(()=>(ur(),X))}),hr=fr,gr=pr,_r=mr;gr(X);var vr=`4.32.2`,yr,br=o((()=>{yr=vr})),xr=/* @__PURE__ */ s({deleteAllConversations:()=>Ir,deleteConversation:()=>Fr,finalizeDisplayProjections:()=>Pr,getConversation:()=>Nr,historyErrorFor:()=>Or,listConversations:()=>Mr,readErrorCode:()=>Er,recoverFromUnauthorized:()=>Dr,resetVisitor:()=>Lr});function Sr(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 Cr(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function wr(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 Tr(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`,Vr);return i}async function Er(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function Dr(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`,Hr);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,Ur);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`,Wr);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 Or(e,t,n){let r=await Er(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`,Vr);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`,Hr)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,Ur):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,Wr):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function kr(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 Ar(e,t,n){jr(e);let r=n.trackIdentity!==!1,i=await e.initSession(),a=null;Cr(e,n.scope)===`verified-user`&&(a=await wr(e,i,r),a&&(i=await Tr(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(Sr(e,t,{...n.query,sessionId:i.sessionId}),{method:n.method,headers:{"X-Persona-Version":yr,...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 Dr(e,await Er(e,u),a,r);continue}if(!u.ok)throw await Or(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 kr(e,d,a!==null,r),f}}function jr(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 Mr(e,t){let n=await Ar(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(Br),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function Nr(e,t,n){let r=await Ar(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:Br(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 Pr(e,t,n){jr(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>Rr)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${Rr} character limit`);r+=n}if(r>zr)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${zr} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await Ar(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=zr,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 Fr(e,t,n){let r=await Ar(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function Ir(e,t){let n=await Ar(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 Lr(e){jr(e),e.setHistoryIdentityStatus({state:`resetting`});try{await Ar(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var Rr,zr,Br,Vr,Hr,Ur,Wr,Gr=o((()=>{br(),Rr=32768,zr=49152,Br=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:``}},Vr=`The identity proof was not admitted; account history is unavailable`,Hr=`The identity proof was rejected`,Ur=`The request carried no visitor credential`,Wr=`The stored visitor belongs to a different signed-in user`}));Gr(),g();const{setLoader:Kr,load:qr,provide:Jr}=h({fallbackImport:()=>Promise.resolve().then(()=>(Gr(),xr))}),Yr=qr;Jr(xr);var Xr,Zr=o((()=>{Pn(),Xr=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})),An(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:Sn(e,i),currentIndex:yn(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=yn(t);if(n>=q(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(Nn(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})),An(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=J(u);if(n&&t){let t=_n(u)[yn(u)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),Mn(u,Array.from(n)),a(u);return}if(n){Mn(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=jn(u).length===0);return}i(u,e,{source:`pick`,values:[e]})}else if(d===`submit-multi`){let e=jn(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(J(u)){Mn(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=_n(u)[yn(u)];(typeof e!=`string`||e!==i)&&Mn(u,i)}let o=d===`next`?1:-1,s=yn(u)+o;Nn(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&&Mn(u,n);let a=Sn(u,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:yn(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=J(u),d=yn(u),f=d>=q(u)-1;if(!l){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:s},bubbles:!0,composed:!0})),An(n,s),c.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(c),r.current.resolveAskUserQuestion(c,`(dismissed)`));return}Mn(u,``);let p=u.querySelector(`[data-ask-free-text-input="true"]`);if(p&&(p.value=``),f){let e=Sn(u,c),t=o(e);i(u,t||`(skipped)`,{source:`submit-all`,structured:e});return}Nn(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()&&(J(n)?(Mn(n,r.trim()),a(n),s(n)):i(n,r,{source:`free-text`}))}}}}));function Qr(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===``||ni.test(r)}function $r(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 Qr(e,a,r)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(o===`
|
|
10
10
|
`||o===``||!i&&ni.test(o))return null;a--}return null}function ei(e,t,n){for(let r of n){let n=$r(e,t,r.trigger,r.position??`anywhere`,r.allowSpaces??!1);if(n)return{channel:r,match:n}}return null}function ti(e){return!e||e!==`insertFromPaste`&&e!==`insertFromDrop`}var ni,ri=o((()=>{ni=/\s/}));function ii(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 ai=o((()=>{})),oi=o((()=>{})),si=o((()=>{}));function ci(e){e.delayMs!==void 0&&(mi=_i(e.delayMs)),e.skipDelayMs!==void 0&&(hi=_i(e.skipDelayMs))}function li(e){bi.get(e)?.hide()}function ui(e){bi.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=di,viewportPadding:s=fi}=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=()=>_i(e.delayMs??mi),x=()=>_i(e.skipDelayMs??hi),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&&yi(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=wi(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=wi(v,s,y),x=r.left+r.width/2,S=Math.max(pi,i.width-pi),C=wi(x-m,pi,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||xi(t))return;let e=v(),n=Ci(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($n);let o=i.getComputedStyle?.(t);if(o){for(let e of Ti){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=Ci(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=Si(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||vi()?w():m=l().setTimeout(()=>{m=void 0,w()},b()))},E=()=>{h||g?T(g):C()},D=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(h=!0,E())},O=()=>{h=!1,E()},te=()=>{try{g=t.matches(`:focus-visible`)}catch{g=!0}E()},ne=()=>{g=!1,E()},re=()=>{h=!1,g=!1,C()},k=e=>{e.key===`Escape`&&re()};n.addEventListener(`mouseenter`,D),n.addEventListener(`mouseleave`,O),t.addEventListener(`focus`,te),t.addEventListener(`blur`,ne),t.addEventListener(`keydown`,k),t.addEventListener(`click`,re);let ie={get isOpen(){return u!==null},show:w,hide:C,reposition:ee,destroy:()=>{_||(_=!0,C(),n.removeEventListener(`mouseenter`,D),n.removeEventListener(`mouseleave`,O),t.removeEventListener(`focus`,te),t.removeEventListener(`blur`,ne),t.removeEventListener(`keydown`,k),t.removeEventListener(`click`,re),bi.delete(t))}};return bi.set(t,ie),ie}var di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei=o((()=>{er(),oi(),si(),di=8,fi=8,pi=10,mi=400,hi=300,gi=0,_i=e=>Math.max(0,e),vi=()=>Date.now()<gi,yi=e=>{gi=e>0?Date.now()+e:0},bi=/* @__PURE__ */ new WeakMap,xi=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null,Si=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,Ci=e=>{let t=e.getRootNode?.();return Si(t)?t:e.closest(`dialog[open]`)??e.ownerDocument.body},wi=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),Ti=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`]})),Di,Oi,ki,Ai,ji=o((()=>{W(),Di=(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},Oi=(e,t)=>{let n=e&&jt(e,t);return typeof n==`string`&&n?n:void 0},ki=(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)},Ai=(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??``}})),Mi,Ni,Pi,Fi=o((()=>{Mi=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Ni=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Mi(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Pi=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))}})),Z,Ii,Li,Ri,zi=o((()=>{Z={collapsedMode:`tool-call`,activePreview:!1,grouped:!1,groupedMode:`stack`,groupBoundary:`adjacent`,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Ii={activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:`none`},Li={layout:`row`,variant:`row`,iconVisibility:`active`,autoExpand:!1,grouped:!0,groupedMode:`collapsible`,groupAppearance:`inset`,loadingAnimation:`shimmer`},Ri={appearance:`inset`,layout:`row`,variant:`row`,iconVisibility:`active`,autoExpand:!1,loadingAnimation:`shimmer`}})),Bi,Vi=o((()=>{Bi={resolvedDisplay:`row`,primaryAction:`allow-once`,keyboardShortcuts:`focused`}})),Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Q=o((()=>{Hi=Symbol(`persona.panelAliasProvenance`),Ui=(e,t)=>e!=null&&Object.prototype.hasOwnProperty.call(e,t),Wi=(e,t)=>Ui(e,t)&&e[t]!==void 0,Gi=e=>({launcherWidth:Wi(e?.launcher,`width`),legacyLauncherWidth:Wi(e,`launcherWidth`),sidebarWidth:Wi(e?.launcher,`sidebarWidth`),dockWidth:Wi(e?.launcher?.dock,`width`)}),Ki=e=>{let t=e?.[Hi];return t?{...t}:Gi(e)},qi=(e,t)=>(Object.defineProperty(e,Hi,{value:t,enumerable:!0,configurable:!0}),e),Ji=(e,t)=>qi(e,Ki(t)),Yi=(e,t)=>{let n=t[Hi];if(n)return{...n};let r=Ki(e);return Ui(t,`launcherWidth`)&&(r.legacyLauncherWidth=t.launcherWidth!==void 0),Ui(t,`launcher`)&&t.launcher===void 0?(r.launcherWidth=!1,r.sidebarWidth=!1,r.dockWidth=!1,r):(Ui(t.launcher,`width`)&&(r.launcherWidth=t.launcher?.width!==void 0),Ui(t.launcher,`sidebarWidth`)&&(r.sidebarWidth=t.launcher?.sidebarWidth!==void 0),Ui(t.launcher,`dock`)&&t.launcher?.dock===void 0?r.dockWidth=!1:Ui(t.launcher?.dock,`width`)&&(r.dockWidth=t.launcher?.dock?.width!==void 0),r)},Xi=e=>e?.layout?.embedded===!0&&e.launcher?.enabled===!1&&!e.launcher.sidebarMode&&(e.launcher.mountMode??`floating`)===`floating`,Zi=e=>e?.layout?.showHeader??!Xi(e)}));function Qi(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function $i(e){let t=Qi(e)===`v5`?ua:ca;return ot(sa,t)}function ea(e,t){if(e||t)return e?t?ot(e,t):e:t}function ta(e){let t=$i(e);return e?Ot(B(Ji({...t,...e,colorScheme:R(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:ea(t.theme,e.theme),darkTheme:ea(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,ua),e):Ot(B(Ji(t),void 0,ua))}var na,ra,ia,aa,oa,sa,ca,la,ua,da,fa=o((()=>{zi(),ct(),Vi(),H(),Q(),W(),oi(),na=`min(440px, calc(100vw - 24px))`,ra=`440px`,ia=`40px`,aa=`How can I help...`,oa={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:na,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:ia,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)`},sa={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:oa,copy:{inputPlaceholder:aa,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:Z,reasoningDisplay:Ii,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},ca={},la={variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},ua={colorScheme:`light`,errorDisplay:`block`,messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:Bi,loadingIndicator:{variant:`label`},launcher:la,features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:`dots`,transition:`fade`,scrollBehavior:`smooth`},toolCallDisplay:Li,reasoningDisplay:Ri},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`}}}},da=$i()}));function pa(e){return typeof e==`string`?[{type:`text`,text:e}]:e}function ma(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function ha(e){return typeof e!=`string`&&e.some(e=>e.type===`image`)}function ga(e){return typeof e==`string`?[]:e.filter(e=>e.type===`image`)}function _a(e){return{type:`text`,text:e}}function va(e,t){return{type:`image`,image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function ya(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 ba(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 xa(e){return Oa.includes(e)||e.startsWith(`image/`)}function Sa(e){return xa(e.type)}async function Ca(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result;Sa(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 wa(e,t=Aa,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 Ta(e){let t=e.split(`.`);return t.length>1?t.pop().toLowerCase():``}function Ea(e,t){let n=Ta(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 Da,Oa,ka,Aa,ja=o((()=>{Da=`[Image]`,Oa=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],ka=[`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`],Aa=[...Oa,...ka]}));function Ma(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 Na(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function Pa(e,t){e.style.maxHeight=`${t*Ma(e)}px`,e.style.overflowY=`auto`}function Fa(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 Ia(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function La(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||!Ia(t)}function Ra(e){return(e.submitKey??`enter`)===`enter`?Ia(e)?`enter`:`send`:`enter`}function za(e,t){e.setAttribute(`enterkeyhint`,Ra(t))}function Ba(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 Va(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 Ha=o((()=>{})),Ua,Wa,Ga=o((()=>{Ua=`persona-composer-control`,Wa=`persona-composer-control--glyph`})),Ka,qa,Ja,Ya,Xa,Za,Qa,$a,eo,to,no,ro=o((()=>{ji(),Fi(),Pt(),ke(),fa(),ja(),Ei(),Ha(),Ga(),Ga(),Ka=(e,t)=>{let n=G(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,za(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:Fa(n)}),Ba(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=Na(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*Ma(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}},qa=`[data-persona-glyph-stack]`,Ja=(e,t,n=`send`)=>{let r=K(`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},Ya=/* @__PURE__ */ new WeakMap,Xa=(e,t,n=!0)=>{Ya.set(e,t);let r=t?.sendButton??{},i=r.useIcon??!1,a=e.getAttribute(`data-persona-send-mode`)===`stop`?`stop`:`send`,o=e=>Oi(t,`sendButton.${e}`),s=(e,n)=>Di(t,`composer.send`,e,n),c=o(`size`)||r.size;e.style.fontSize=i?`18px`:``,e.style.lineHeight=i?`1`:``,e.className=Nt(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,i?`persona-flex persona-items-center persona-justify-center ${Ua}`:`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`),Ai(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))`):``,ki(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?F(r.iconName,f,`currentColor`,t):null,i=F(r.stopIconName??`square`,f,`currentColor`,t);n&&i?e.appendChild(Ja(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)}},Za=e=>{let t=e?.sendButton,n=G(`div`,`persona-send-button-wrapper`),r=K(`button`,{attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`}});return Xa(r,e),r.setAttribute(`aria-label`,t?.tooltipText??`Send message`),n.appendChild(r),ui({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=Ya.get(r);Xa(r,n,!1),r.querySelector(qa)?.setAttribute(`data-mode`,e),(n?.sendButton?.useIcon??!1)||(r.textContent=e===`stop`?n?.copy?.stopButtonLabel??`Stop`:n?.copy?.sendButtonLabel??`Send`)},glyphStack:r.querySelector(qa)}},Qa=(e,t,n=`idle`,r=`none`)=>{let i=t?.voiceRecognition??{},a=e=>Oi(t,`voiceRecognition.${e}`),o=(e,n)=>Di(t,`voice.control`,e,n),s=a(`iconSize`)||i.iconSize;Ai(e,s||(o(`size`,``)?o(`size`,`var(--persona-composer-control-size, 40px)`):``),s),e.classList.add(Ua),e.classList.toggle(Wa,!s&&!o(`size`,``)),e.style.fontSize=`18px`,e.style.lineHeight=`1`;let c=a(`iconColor`)||Oi(t,`sendButton.textColor`)||o(`foreground`,`var(--persona-text, #111827)`),l=a(`backgroundColor`)||Oi(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)`):``,ki(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=F(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=`🎤`},$a=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=G(`div`,`persona-send-button-wrapper`),o=K(`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`}});Qa(o,e),a.appendChild(o);let s=t.tooltipText??`Start voice recognition`;return ui({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??s,enabled:t.showTooltip??!1}),{button:o,wrapper:a}},eo=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=G(`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=G(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??Aa).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=G(`div`,`persona-send-button-wrapper`),o=K(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${Ua} ${Wa}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=F(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 ui({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},to=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=G(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Ni(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=G(`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},no=()=>K(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}})}));function io(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=G(`div`,`persona-send-button-wrapper`),o=K(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${Ua} ${Wa}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=F(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),ui({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}var ao=o((()=>{Pt(),ke(),Ei(),ro()})),oo,so,co,lo=o((()=>{g(),{setLoader:oo,load:so}=h({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions`)}),co=so})),uo,fo,po,mo=o((()=>{g(),{setLoader:uo,load:fo}=h({fallbackImport:()=>import(`@runtypelabs/persona/context-mentions-inline`),resetOnSetLoader:!0}),po=fo}));function ho(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=K(`span`,{className:Nt(`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=F(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=G(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(K(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var go=o((()=>{Pt(),ke()}));function _o(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??vo,a=e.config.contextMentions;if(!a?.enabled)return null;let o=ii(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 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
14
14
|
|
|
15
15
|
`)}:{}}function Ll(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Rl(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 zl(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 Bl(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 zl(e,n.id)?n.id:null}return null}function Vl(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 Hl(e){if(!e||typeof e!=`object`||!(`component`in e))return!1;let t=e.component;return typeof t==`string`&&t.length>0}function Ul(e,t){if(!Hl(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 Wl(){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=Ul((0,p.parse)(n,p.STR|p.OBJ),n);t&&(e=t)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Gl(e){return typeof e==`object`&&!!e&&`component`in e&&typeof e.component==`string`&&`props`in e&&typeof e.props==`object`}Pt();function Kl(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Rs(n,e.component);if(!a){if(Bs.includes(e.component)){Js().catch(()=>{});let e=G(`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 ql(){let e=Wl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Jl(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 Yl(e){let t=Jl(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 Xl(e){let t=Jl(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 Zl(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 Ql=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):Zl(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()}},$l=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)}},eu=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 tu(e){if(!e)return``;let t=nu(e);return ru(t===null?e:t)}function nu(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 ru(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 iu,au=o((()=>{iu=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 ou(e){return e.replace(/\/+$/,``)}async function su(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 cu,lu=o((()=>{au(),cu=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 iu(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=`${ou(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 su(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}}})),uu,du=o((()=>{uu=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?.()}}})),fu=/* @__PURE__ */ s({FallbackSpeechEngine:()=>uu,RuntypeSpeechEngine:()=>cu}),pu=o((()=>{lu(),du()}));const mu=()=>Promise.resolve().then(()=>(pu(),fu));g();const{setLoader:hu,load:gu}=h({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),_u=gu;Ve(),Kn(),Mo(),ja(),Je(),Zc();const vu=/* @__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 yu(e,t){return vu.some(n=>e[n]!==t[n])}var bu=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function xu(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 Su=e=>ze(e)||e===`suggest_replies`;var Cu=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${Ao()}`,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 eu,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new $l(()=>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)&&Xo().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(ze(i.name)||i.name===`suggest_replies`&&Gn(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=>({...Sc(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new wl(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&&ec().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&&mu().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 ac(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=Ql.isSupported()?new Ql({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 mu().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=ec().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(!rc(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 eu,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 bu(`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 Tl(`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 bu(`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 bu(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new bu(`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 bu(`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 bu(`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=Xc(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&&xc(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 Sc(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 bu(`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 bu(`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 bu(`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 bu(`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 bu(`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=Xc(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=Yc(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=Yc(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 xl&&(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 xl?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 xl&&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=nc(this.config,n),i=yu(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&oc(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 wl(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`?ko():t===`assistant`?Ao():`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&&Xl(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||!Xl(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 iu,au=o((()=>{iu=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 ou(e){return e.replace(/\/+$/,``)}async function su(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 cu,lu=o((()=>{au(),cu=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 iu(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=`${ou(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 su(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}}})),uu,du=o((()=>{uu=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?.()}}})),fu=/* @__PURE__ */ s({FallbackSpeechEngine:()=>uu,RuntypeSpeechEngine:()=>cu}),pu=o((()=>{lu(),du()}));const mu=()=>Promise.resolve().then(()=>(pu(),fu));g();const{setLoader:hu,load:gu}=h({fallbackImport:()=>import(`@runtypelabs/persona/session-reconnect`)}),_u=gu;Ve(),Kn(),Mo(),ja(),Je(),Zc();const vu=/* @__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 yu(e,t){return vu.some(n=>e[n]!==t[n])}var bu=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function xu(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 Su=e=>ze(e)||e===`suggest_replies`;var Cu=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${Ao()}`,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 eu,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new $l(()=>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)&&Xo().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(ze(i.name)||i.name===`suggest_replies`&&Gn(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=>({...Sc(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new wl(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&&ec().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&&mu().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 ac(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=Ql.isSupported()?new Ql({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 mu().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=ec().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(!rc(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 eu,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 bu(`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 Tl(`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 bu(`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 bu(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new bu(`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 bu(`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 bu(`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=Xc(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&&xc(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 Sc(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 bu(`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 bu(`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 bu(`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 bu(`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 bu(`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=Xc(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=Yc(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=Yc(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 xl&&(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 xl?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 xl&&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=nc(this.config,n),i=yu(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&oc(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 wl(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`?ko():t===`assistant`?Ao():`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&&Xl(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||!Xl(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
|
|