@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
|
@@ -176,7 +176,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
176
176
|
`?0:1);return{doc:{blocks:l},caret:u}}function hp(e,t){let n=0,r=0,i=!1;for(let a of e.blocks)a.kind===`mention`&&a.id===t&&(n=r,i=!0),r+=ap(a);return i?{doc:{blocks:op(e.blocks.filter(e=>e.kind!==`mention`||e.id!==t))},caret:n}:{doc:e,caret:r}}function gp(e,t,n,r){let i=dp(e),a=Math.max(0,Math.min(t,n,i)),o=Math.min(i,Math.max(t,n,0)),s=pp(e.blocks,a).left,c=pp(e.blocks,o).right;return{doc:{blocks:op([...s,{kind:`text`,value:r},...c])},caret:a+r.length}}function _p(e){let t=[];for(let n of e.blocks)n.kind===`text`?n.value.length>0&&t.push({kind:`text`,text:n.value}):t.push({kind:`mention`,ref:n.ref});return{content:lp(e),contextMentions:fp(e).map(e=>e.ref),contentSegments:t}}var vp,yp=o((()=>{Tu(),vp=`@`}));function bp(e){return e.nodeType===1&&e.hasAttribute(kp)}function xp(e){return e.nodeType===1&&e.tagName===`BR`}function Sp(e){return e.nodeType===3?e.data.length:bp(e)||xp(e)?1:e.textContent?.length??0}function Cp(e,t,n){let r=0;for(let i of Array.from(e.childNodes)){if(i===t)return i.nodeType===3?r+n:r+(n>0?Sp(i):0);if(i.contains(t))return bp(i)?r+1:r+wp(i,t,n);r+=Sp(i)}if(t===e){let t=0,r=Array.from(e.childNodes);for(let e=0;e<Math.min(n,r.length);e++)t+=Sp(r[e]);return t}return r}function wp(e,t,n){let r=0,i=e=>{if(e===t)return r+=e.nodeType===3?n:0,!0;if(e.nodeType===3)return r+=e.data.length,!1;for(let t of Array.from(e.childNodes))if(i(t))return!0;return!1};return i(e),r}function Tp(e,t){let n=0,r=Array.from(e.childNodes);for(let i=0;i<r.length;i++){let a=r[i],o=Sp(a);if(t<=n+o)return a.nodeType===3?{node:a,offset:t-n}:{node:e,offset:t<=n?i:i+1};n+=o}return{node:e,offset:r.length}}function Ep(e,t){let n=[];for(let r of Array.from(e.childNodes))if(bp(r)){let e=r.getAttribute(kp),i=t.get(e);i&&n.push({kind:`mention`,id:e,ref:i})}else if(xp(r))n.push({kind:`text`,value:Mp});else if(r.nodeType===3)n.push({kind:`text`,value:r.data});else{let e=r.textContent??``;e&&n.push({kind:`text`,value:e})}return n.length===0&&n.push({kind:`text`,value:``}),{blocks:n}}function Dp(e){let t=e.renderToken,n=/* @__PURE__ */ new Map,r=e.element??document.createElement(`div`);r.setAttribute(`contenteditable`,`true`),r.setAttribute(`data-persona-composer-input`,``),r.setAttribute(`role`,`textbox`),r.setAttribute(`aria-multiline`,`true`),r.setAttribute(`dir`,`auto`),r.classList.add(`persona-composer-contenteditable`),e.placeholder!=null&&r.setAttribute(`data-placeholder`,e.placeholder);let i=!1,a=0,o=()=>Ep(r,n),s=e=>{r.replaceChildren();for(let i of e.blocks)if(i.kind===`text`)i.value.length>0&&r.appendChild(document.createTextNode(i.value));else{n.set(i.id,i.ref);let e=t(i.ref);e.setAttribute(`contenteditable`,`false`),e.setAttribute(kp,i.id),r.appendChild(e)}},c=()=>{let e=r.getRootNode().activeElement;return e===r||e!=null&&r.contains(e)},l=(e,t)=>{if(a=e,!t?.focus&&!c())return;let n=typeof window<`u`?window.getSelection():null;if(!n)return;let i=Tp(r,e);try{let e=document.createRange();e.setStart(i.node,i.offset),e.collapse(!0),n.removeAllRanges(),n.addRange(e)}catch{}},u=()=>{r.dispatchEvent(new Event(`input`,{bubbles:!0}))},d=()=>{let e={start:a,end:a},t=typeof window<`u`?window.getSelection():null;if(!t||t.rangeCount===0)return e;let n=t.getRangeAt(0);if(!r.contains(n.startContainer))return e;let i=Cp(r,n.startContainer,n.startOffset),o=n.collapsed?i:Cp(r,n.endContainer,n.endOffset);return{start:Math.min(i,o),end:Math.max(i,o)}},f=()=>{let t=/* @__PURE__ */ new Set;for(let e of Array.from(r.childNodes))bp(e)&&t.add(e.getAttribute(kp));for(let r of Array.from(n.keys()))t.has(r)||(n.delete(r),e.onMentionRemoved?.(r))},p=()=>{i||n.size!==0&&f()},m=()=>{i=!0},h=()=>{i=!1,f()},g=e=>{e.preventDefault();let t=e.clipboardData?.getData(`text/plain`)??``;if(typeof document.execCommand==`function`)document.execCommand(`insertText`,!1,t);else{let{start:e,end:n}=d(),r=gp(o(),e,n,t);s(r.doc),l(r.caret,{focus:!0}),f()}u()},_=e=>{if(i)return;let t=e.inputType;if(t===`insertParagraph`){e.preventDefault();let{start:t,end:r}=d(),i=gp(o(),t,r,Mp);s(i.doc),l(i.caret,{focus:!0}),n.size>0&&f(),u();return}if(t!==`deleteContentBackward`&&t!==`deleteContentForward`||n.size===0)return;let{start:r,end:a}=d();if(r!==a)return;let c=o(),p=up(c),m=t===`deleteContentBackward`?r-1:r;if(m<0||m>=p.length||p[m]!==``)return;let h=0,g=null;for(let e of c.blocks){let t=e.kind===`text`?e.value.length:1;if(e.kind===`mention`&&m>=h&&m<h+t){g=e.id;break}h+=t}if(!g)return;e.preventDefault();let _=hp(c,g);s(_.doc),l(_.caret,{focus:!0}),f(),u()};return r.addEventListener(`input`,p),r.addEventListener(`compositionstart`,m),r.addEventListener(`compositionend`,h),r.addEventListener(`paste`,g),r.addEventListener(`beforeinput`,_),s(sp()),{element:r,getValue:()=>lp(o()),getLogicalText:()=>up(o()),getDocument:o,setDocument:e=>{s(e),l(up(e).length)},getSelection:d,setSelection:(e,t=e)=>{let n=typeof window<`u`?window.getSelection():null;if(n)try{let i=Tp(r,e),a=Tp(r,t),o=document.createRange();o.setStart(i.node,i.offset),o.setEnd(a.node,a.offset),n.removeAllRanges(),n.addRange(o)}catch{}},setValueWithCaret:(e,t)=>{s(cp(e)),l(t)},getLogicalRangeRect:(e,t)=>{if(!Number.isFinite(e)||!Number.isFinite(t)||t<=e)return null;try{let n=Tp(r,e),i=Tp(r,t),a=document.createRange();a.setStart(n.node,n.offset),a.setEnd(i.node,i.offset);let o=a.getBoundingClientRect();return o.width===0&&o.height===0?null:o}catch{return null}},setValue:e=>{s(cp(e)),r.focus(),l(e.length,{focus:!0}),u()},replaceLogicalRange:(e,t,n)=>{let r=gp(o(),e,t,n);s(r.doc),l(r.caret,{focus:!0})},insertMentionAtTrigger:(t,n)=>{let r=o(),i=up(r),a=n.triggerIndex,c=n.triggerIndex+1+n.query.length;if(a<0||c>i.length||i.slice(a+1,c)!==n.query)return null;let d=e.generateId(),f=mp(r,{start:a,end:c},t,d);return s(f.doc),l(f.caret,{focus:!0}),e.onMentionInserted?.(d,t),u(),d},insertMentionAtSelection:t=>{let n=o(),i=d(),a=typeof window<`u`&&window.getSelection()?.rangeCount&&r.contains(window.getSelection().getRangeAt(0).startContainer)?{start:i.start,end:i.end}:{start:dp(n),end:dp(n)},c=e.generateId(),f=mp(n,a,t,c);return s(f.doc),l(f.caret,{focus:!0}),e.onMentionInserted?.(c,t),u(),c},setMentionStatus:(e,t)=>{for(let i of Array.from(r.childNodes))if(bp(i)&&i.getAttribute(kp)===e){let r=t===`error`;if(i.classList.toggle(Op,r),r){i.hasAttribute(Ap)||(i.setAttribute(Ap,i.getAttribute(`aria-label`)??``),i.setAttribute(jp,i.getAttribute(`title`)??``));let t=n.get(e)?.label??``;i.setAttribute(`title`,`${t}: failed to attach context`),i.setAttribute(`aria-label`,`${t}, failed to attach context`)}else if(i.hasAttribute(Ap)){let e=i.getAttribute(Ap),t=i.getAttribute(jp);e?i.setAttribute(`aria-label`,e):i.removeAttribute(`aria-label`),t?i.setAttribute(`title`,t):i.removeAttribute(`title`),i.removeAttribute(Ap),i.removeAttribute(jp)}return}},submit:()=>Gf(r.closest(`form`)),dispatchInput:u,focus:()=>r.focus(),destroy:()=>{r.removeEventListener(`input`,p),r.removeEventListener(`compositionstart`,m),r.removeEventListener(`compositionend`,h),r.removeEventListener(`paste`,g),r.removeEventListener(`beforeinput`,_)}}}var Op,kp,Ap,jp,Mp,Np=o((()=>{yp(),qf(),Op=`persona-mention-token-error`,kp=`data-mention-id`,Ap=`data-mention-prev-label`,jp=`data-mention-prev-title`,Mp=`
|
|
177
177
|
`}));function Pp(e,t){t.className=`${e.className} persona-composer-contenteditable`.trim();for(let n=0;n<e.style.length;n++){let r=e.style.item(n);r!==`height`&&t.style.setProperty(r,e.style.getPropertyValue(r),e.style.getPropertyPriority(r))}let n=e.getAttribute(`placeholder`);n&&(t.setAttribute(`data-placeholder`,n),t.setAttribute(`aria-placeholder`,n));let r=e.getAttribute(`aria-label`)??n;r&&t.setAttribute(`aria-label`,r)}function Fp(e,t,n){Object.defineProperty(e,"value",{configurable:!0,get:()=>t.getValue(),set:e=>{t.setValueWithCaret(e,e.length),t.dispatchInput()}}),Object.defineProperty(e,"placeholder",{configurable:!0,get:()=>e.getAttribute(`data-placeholder`)??``,set:t=>{t?(e.setAttribute(`data-placeholder`,t),e.setAttribute(`aria-placeholder`,t),n||e.setAttribute(`aria-label`,t)):(e.removeAttribute(`data-placeholder`),e.removeAttribute(`aria-placeholder`),n||e.removeAttribute(`aria-label`))}}),Object.defineProperty(e,"selectionStart",{configurable:!0,get:()=>t.getSelection().start}),Object.defineProperty(e,"selectionEnd",{configurable:!0,get:()=>t.getSelection().end}),e.setSelectionRange=(e,n)=>t.setSelection(e??0,n??e??0)}function Ip(e){let{textarea:t}=e,n=Dp({generateId:Rp,renderToken:e.renderToken,onMentionRemoved:e.onMentionRemoved,placeholder:t.getAttribute(`placeholder`)??void 0}),r=n.element,i=t.getAttribute(`aria-label`)!=null;Pp(t,r),Fp(r,n,i),r.getInlineMessageFields=()=>_p(n.getDocument?.()??{blocks:[]});let a=t.selectionStart??t.value.length;return n.setValueWithCaret(t.value,a),{input:n,element:r,destroy:n.destroy}}var Lp,Rp,zp=o((()=>{Np(),yp(),Lp=0,Rp=()=>`pmention-${++Lp}`})),Bp=/* @__PURE__ */ s({mountInlineComposer:()=>Ip}),Vp=o((()=>{zp()})),Hp,Up,Wp,Gp=o((()=>{B(),{setLoader:Hp,load:Up}=z({fallbackImport:()=>Promise.resolve().then(()=>(Vp(),Bp)),resetOnSetLoader:!0}),Wp=Up}));function Kp(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=J(`span`,{className:ht(`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=mr(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=q(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(J(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}var qp=o((()=>{Y(),hr()}));function Jp(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:r,createMentionButton:i}=e.deps??Yp,a=e.config.contextMentions;if(!a?.enabled)return null;let o=Eu(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(`
|
|
178
178
|
`).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
|
|
179
|
-
`)[0]).startsWith(t.trigger):!1),l=(t,n)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${t}`,{detail:{...n,instanceId:e.textarea.closest(`[data-persona-instance]`)?.dataset.personaInstance}}))}catch{}},u=!e.chipRow,d=e.chipRow??J(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Kp(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!Su(e))return;let t=m,n=t.selectionStart??0;xu(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],captureDraft:()=>f?.captureDraft()??[],restoreDraft:e=>f?.restoreDraft(e),getInlineInput:()=>h,collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Yp,Xp=o((()=>{Y(),Tu(),Du(),_f(),ip(),hr(),Gp(),qp(),Yp={loadContextMentions:()=>rp(),loadContextMentionsInline:()=>Wp(),renderLucideIcon:(...e)=>mr(...e),createMentionButton:(...e)=>gf(...e)}})),Zp=/* @__PURE__ */ s({createAskUserSheetHandlers:()=>_u,createContextMentionOrchestrator:()=>Jp}),Qp=o((()=>{vu(),Xp()}));B();const{setLoader:$p,load:em,provide:tm,getSync:nm}=z({fallbackImport:()=>Promise.resolve().then(()=>(Qp(),Zp))}),rm=em,im=nm;var am,om=o((()=>{am=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}}})),sm=`4.32.
|
|
179
|
+
`)[0]).startsWith(t.trigger):!1),l=(t,n)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${t}`,{detail:{...n,instanceId:e.textarea.closest(`[data-persona-instance]`)?.dataset.personaInstance}}))}catch{}},u=!e.chipRow,d=e.chipRow??J(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),f=null,p=null,m=e.textarea,h=null,g=null,_=null,v=null,y=()=>{if(f)return Promise.resolve(f);if(p)return p;let n=t().then(t=>(t.setMentionIconRenderer(r),f=t.mountContextMentions({mentionConfig:a,textarea:e.textarea,composerInput:h??void 0,anchor:e.anchor,contextRow:d,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:S,emit:l}),f)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),p===n&&(p=null),null));return p=n,n};a.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>Kp(e,{render:a.renderMentionToken}),onMentionRemoved:e=>f?.untrackMention(e)});h=n.input,g=n.destroy;let r=m;r.replaceWith(n.element),m=n.element,v={next:n.element,prev:r},_?.(n.element,r),f?f.rebindComposer(n.input):p&&p.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let b=[],x=/* @__PURE__ */ new Map;for(let e of o){if(!e.showButton)continue;let t=i({config:{...a,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{y().then(t=>t?.openMenu(e.trigger))}});b.push(t),x.set(e.trigger,t.button)}let S=(e,t,n)=>{let r=x.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:b.map(e=>e.wrapper),contextRow:d,handleInput:e=>{if(f){f.handleInput();return}if(!Su(e))return;let t=m,n=t.selectionStart??0;xu(t.value,n,o)&&y().then(e=>e?.handleInput())},handleKeydown:e=>{if(f?.isMenuOpen())return f.handleKeydown(e);if(e.key===`Backspace`&&f?.hasMentions()&&!v){let t=m,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&f.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>f?.isMenuOpen()??!1,hasMentions:()=>f?.hasMentions()??!1,getMentionRefs:()=>f?.getMentionRefs()??[],captureDraft:()=>f?.captureDraft()??[],restoreDraft:e=>f?.restoreDraft(e),getInlineInput:()=>h,collectForSubmit:()=>f?.collectForSubmit()??null,takeInlineCommand:async e=>c(e)?(f??await y())?.dispatchInlineCommand(e)??null:null,clear:()=>f?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{_=e,v&&e(v.next,v.prev)},destroy:()=>{f?.destroy(),g?.();for(let e of b)e.wrapper.remove();u&&d.remove()}}}var Yp,Xp=o((()=>{Y(),Tu(),Du(),_f(),ip(),hr(),Gp(),qp(),Yp={loadContextMentions:()=>rp(),loadContextMentionsInline:()=>Wp(),renderLucideIcon:(...e)=>mr(...e),createMentionButton:(...e)=>gf(...e)}})),Zp=/* @__PURE__ */ s({createAskUserSheetHandlers:()=>_u,createContextMentionOrchestrator:()=>Jp}),Qp=o((()=>{vu(),Xp()}));B();const{setLoader:$p,load:em,provide:tm,getSync:nm}=z({fallbackImport:()=>Promise.resolve().then(()=>(Qp(),Zp))}),rm=em,im=nm;var am,om=o((()=>{am=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}}})),sm=`4.32.2`,cm,lm=o((()=>{cm=sm}));function um(e,t){let n=t.slice(0,Rm).trim(),r=Lm-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>zm&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
|
|
180
180
|
`)}`]:[];return n&&a.push(n),a.join(`
|
|
181
181
|
|
|
182
182
|
`)}function dm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===bm?new Uint8Array(e,44):new Uint8Array(e)}function fm(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function pm(e){return fm(e).replace(/^ws/i,`http`)}function mm(e){return typeof e!=`number`||!Number.isFinite(e)?wm:Math.min(Em,Math.max(Tm,Math.round(e)))}var hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm=o((()=>{om(),lm(),hm=16e3,gm=24e3,_m=4096,vm=hm*2*8,ym=4,bm=1380533830,xm=3e4,Sm=1e3,Cm=5e3,wm=3e4,Tm=3e4,Em=6e5,Dm=`full-duplex-v1`,Om=300,km=2e3,Am=2e3,jm=`runtype-browser-v1`,Mm=54e4,Nm=`You're talking to an AI assistant. Voice is processed by OpenAI.`,Pm=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),Fm=[`provider_error`,`server_restart`],Im=`Voice connection lost.`,Lm=8e3,Rm=4e3,zm=2e3,Bm=class{#e;#t;#n;#r;#i;#a;#o;#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){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<xm)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${pm(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=mm(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,Cm)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(e,t,n){let r=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(r+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(r+=`,client_tools,prior_tool_results`)),n&&(r=`attach,${r}`);let i=new URLSearchParams({voiceProtocol:jm,clientVersion:`persona/${cm}`,voiceCapabilities:Dm,clientCapabilities:r});return n?.forEach((e,t)=>i.set(t,e)),`${fm(e)}/ws/agents/${encodeURIComponent(t)}/voice?${i}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let t=this.config?.agentId,n=this.config?.clientToken,r=this.config?.host;if(!t)throw Error(`Runtype voice requires an agentId`);if(!n)throw Error(`Runtype voice requires a clientToken`);if(!r)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let i=++this.#d;this.#f=!1,this.#l=!0;try{let a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:hm,channelCount:1,echoCancellation:!0}});if(i!==this.#d){a.getTracks().forEach(e=>e.stop());return}this.#r=a;let o=new(window.AudioContext||window.webkitAudioContext)({sampleRate:hm});if(this.#t=o,o.state===`suspended`){if(await Promise.race([o.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:Sm))]),i!==this.#d)return;if(o.state!==`running`)throw Error(e?this.#D=`${Im} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let s=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new am(gm);if(i!==this.#d){s.destroy(),a.getTracks().forEach(e=>e.stop()),o.close().catch(()=>{});return}this.#c=s,this.#he(),this.#ie(o,a,i);let c=await this.#ee();if(i!==this.#d){c?.ws.close(1e3,`client ended call`);return}if(c){let{ws:e}=c;this.#e=e,this.#ne(e,i),c.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let l=new WebSocket(this.#te(r,t),[`runtype.bearer`,n]);l.binaryType=`arraybuffer`,this.#e=l,l.onopen=()=>{i===this.#d&&(this.#ae(l),this.#be(`listening`))},this.#ne(l,i)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=Fm.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${Im} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(Fm.includes(e))return this.#D=Im,this.#xe(/* @__PURE__ */ Error(Im)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||Pm.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||Nm:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+km,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(_m,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>vm;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*ym));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return um(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),Am)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,Mm),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=dm(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+Om)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}}})),Hm,Um=o((()=>{Hm=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}}}));function Wm(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new Bm(e.runtype);case`browser`:if(!Hm.isSupported())throw Error(`Browser speech recognition not supported`);return new Hm(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function Gm(e){if(e?.type===`custom`&&e.custom)return Wm({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return Wm({type:`runtype`,runtype:e.runtype});if(Hm.isSupported())return Wm({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function Km(e){try{return Gm(e),!0}catch{return!1}}var qm=o((()=>{Vm(),Um()})),Jm,Ym,Xm=o((()=>{Jm=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``),Ym=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=Jm(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:Jm(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}}}));function Zm(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(rh.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*Qm(e,t){let n=new RegExp(ih.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&Zm(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function $m(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function eh(e){let t=0;for(let n of Qm(e.slice(0,220),!0))t=n;if(t)return t;let n=$m(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var th,nh,rh,ih,ah,oh=o((()=>{th=30,nh=6,rh=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),ih=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g,ah=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?eh(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?eh(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=Qm(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=th||t>=nh){let t=$m(e,220);if(t)return t}}return e.length>220?eh(e):0}}}));function sh(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>sh(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=sh(n,t+1);return r&&(t?`${Sh(e)} ${r}`:`${Sh(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function ch(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=mh-t.length-119-2;return`${t}\n${e.map(t=>{let r=[Sh(t.toolName)];t.description&&r.push(`(${xh(t.description.trim(),160)})`);let i=sh(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${xh(t.reason.trim(),160)}`),xh(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
|
|
@@ -193,7 +193,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
193
193
|
|
|
194
194
|
`)}:{}}function Jy(e,t=140){let n=e.replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Yy(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 Xy(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 Zy(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 Xy(e,n.id)?n.id:null}return null}function Qy(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}Ao(),Y();function $y(e,t){let{config:n,message:r,onPropsUpdate:i}=t,a=Eo(n,e.component);if(!a){if(al.includes(e.component)){pl().catch(()=>{});let e=q(`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 eb(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 tb(e){let t=eb(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 nb(e){let t=eb(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 rb(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 ib=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):rb(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()}},ab=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)}},ob=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 sb(e){if(!e)return``;let t=cb(e);return lb(t===null?e:t)}function cb(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 lb(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,`
|
|
195
195
|
`),t=t.replace(/\n{2,}/g,`
|
|
196
|
-
`),t.trim()}function ub(e){return e.replace(/\/+$/,``)}async function db(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 fb,pb=o((()=>{om(),fb=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 am(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=`${ub(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 db(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}}})),mb,hb=o((()=>{mb=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?.()}}})),gb=/* @__PURE__ */ s({FallbackSpeechEngine:()=>mb,RuntypeSpeechEngine:()=>fb}),_b=o((()=>{pb(),hb()}));const vb=()=>Promise.resolve().then(()=>(_b(),gb));var yb=/* @__PURE__ */ s({createReconnectController:()=>bb});function bb(e){let t=0,n=null,r=null,i=!1,a=()=>{if(r&&=(clearTimeout(r),null),n){let e=n;n=null,e()}},o=()=>{let t=e.getStatus();(t===`resuming`||t===`paused`)&&a()},s=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&o()},c=()=>{o()},l=()=>{i||=(typeof document<`u`&&document.addEventListener(`visibilitychange`,s),typeof window<`u`&&window.addEventListener(`online`,c),!0)},u=()=>{i&&=(typeof document<`u`&&document.removeEventListener(`visibilitychange`,s),typeof window<`u`&&window.removeEventListener(`online`,c),!1)},d=e=>new Promise(t=>{n=t,r=setTimeout(()=>{r=null,n=null,t()},e)}),f=()=>{let n=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,u(),e.setAbortController(null);let r=!1;for(let t of e.getMessages())t.streaming&&(t.streaming=!1,r=!0);let i=e.buildErrorContent(`Connection lost and the response could not be resumed.`);i?e.appendMessage({dispatchError:!0,id:`${M_}${n?.executionId??e.nextSequence()}`,role:`assistant`,content:i,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}):r&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus(`idle`),e.onError(/* @__PURE__ */ Error(`Durable session reconnect failed.`))},p=async()=>{let n=e.config.reconnect?.backoffMs??xb,r=e.config.reconnect?.maxAttempts??n.length,i=e.config.reconnectStream;if(!i)e.setReconnecting(!1);else{for(;e.getResumable()&&t<r;){t+=1,e.setStatus(`resuming`);let a=e.getResumable(),o=a.lastEventId,s=new AbortController;e.setAbortController(s),e.emitReconnect({phase:`resuming`,handle:a,attempt:t});let c=null;try{let e=await i({executionId:a.executionId,after:a.lastEventId,signal:s.signal});e&&e.ok&&e.body&&(c=e.body)}catch{c=null}if(s.signal.aborted)return;if(c){let n=e.getMessages().find(e=>e.id===a.assistantMessageId)?.content,r=typeof n==`string`?n:``;try{await e.resumeConnect(c,a.assistantMessageId,r)}catch{}if(s.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,u(),e.emitReconnect({phase:`resumed`,handle:a});return}if(e.isAwaitPending?.()){e.setReconnecting(!1),t=0,u();return}e.getResumable().lastEventId!==o&&(t=0)}if(c&&e.getResumable()&&e.settleParked(a.executionId)){t=0,u();return}if(e.getResumable()&&t<r&&(e.setStatus(`paused`),await d(n[Math.min(t-1,n.length-1)]??1e3),s.signal.aborted))return}e.getResumable()&&f()}};return{begin(){t=0,l(),p()},teardown(){r&&=(clearTimeout(r),null),n=null,t=0,u()},wake:a}}var xb,Sb=o((()=>{P_(),xb=[1e3,2e3,4e3,8e3,8e3]}));B();const{setLoader:Cb,load:wb}=z({fallbackImport:()=>Promise.resolve().then(()=>(Sb(),yb))}),Tb=wb;pg(),Yg(),Nv(),Gd(),kg(),j_();const Eb=/* @__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 Db(e,t){return Eb.some(n=>e[n]!==t[n])}var Ob=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function kb(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 Ab=e=>dg(e)||e===`suggest_replies`;var jb=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${jv()}`,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 ob,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new ab(()=>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)&&Vy().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(dg(i.name)||i.name===`suggest_replies`&&Jg(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=>({...hg(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new fy(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&&Ph().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&&vb().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 zh(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=ib.isSupported()?new ib({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 vb().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=Ph().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(!Lh(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 ob,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 Ob(`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 my(`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 Ob(`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 Ob(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new Ob(`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 Ob(`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 Ob(`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=O_(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&&mg(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 hg(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 Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`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=O_(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=D_(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=D_(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 ly&&(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 ly?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 ly&&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=Ih(this.config,n),i=Db(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Bh(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 fy(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`?Av():t===`assistant`?jv():`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&&nb(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||!nb(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(`
|
|
196
|
+
`),t.trim()}function ub(e){return e.replace(/\/+$/,``)}async function db(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 fb,pb=o((()=>{om(),fb=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 am(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=`${ub(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 db(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}}})),mb,hb=o((()=>{mb=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?.()}}})),gb=/* @__PURE__ */ s({FallbackSpeechEngine:()=>mb,RuntypeSpeechEngine:()=>fb}),_b=o((()=>{pb(),hb()}));const vb=()=>Promise.resolve().then(()=>(_b(),gb));var yb=/* @__PURE__ */ s({createReconnectController:()=>bb});function bb(e){let t=0,n=null,r=null,i=!1,a=()=>{if(r&&=(clearTimeout(r),null),n){let e=n;n=null,e()}},o=()=>{let t=e.getStatus();(t===`resuming`||t===`paused`)&&a()},s=()=>{(typeof document>`u`||document.visibilityState!==`hidden`)&&o()},c=()=>{o()},l=()=>{i||=(typeof document<`u`&&document.addEventListener(`visibilitychange`,s),typeof window<`u`&&window.addEventListener(`online`,c),!0)},u=()=>{i&&=(typeof document<`u`&&document.removeEventListener(`visibilitychange`,s),typeof window<`u`&&window.removeEventListener(`online`,c),!1)},d=e=>new Promise(t=>{n=t,r=setTimeout(()=>{r=null,n=null,t()},e)}),f=()=>{let n=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,u(),e.setAbortController(null);let r=!1;for(let t of e.getMessages())t.streaming&&(t.streaming=!1,r=!0);let i=e.buildErrorContent(`Connection lost and the response could not be resumed.`);i?e.appendMessage({dispatchError:!0,id:`${M_}${n?.executionId??e.nextSequence()}`,role:`assistant`,content:i,localOnly:!0,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e.nextSequence()}):r&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus(`idle`),e.onError(/* @__PURE__ */ Error(`Durable session reconnect failed.`))},p=async()=>{let n=e.config.reconnect?.backoffMs??xb,r=e.config.reconnect?.maxAttempts??n.length,i=e.config.reconnectStream;if(!i)e.setReconnecting(!1);else{for(;e.getResumable()&&t<r;){t+=1,e.setStatus(`resuming`);let a=e.getResumable(),o=a.lastEventId,s=new AbortController;e.setAbortController(s),e.emitReconnect({phase:`resuming`,handle:a,attempt:t});let c=null;try{let e=await i({executionId:a.executionId,after:a.lastEventId,signal:s.signal});e&&e.ok&&e.body&&(c=e.body)}catch{c=null}if(s.signal.aborted)return;if(c){let n=e.getMessages().find(e=>e.id===a.assistantMessageId)?.content,r=typeof n==`string`?n:``;try{await e.resumeConnect(c,a.assistantMessageId,r)}catch{}if(s.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,u(),e.emitReconnect({phase:`resumed`,handle:a});return}if(e.isAwaitPending?.()){e.setReconnecting(!1),t=0,u();return}e.getResumable().lastEventId!==o&&(t=0)}if(c&&e.getResumable()&&e.settleParked(a.executionId)){t=0,u();return}if(e.getResumable()&&t<r&&(e.setStatus(`paused`),await d(n[Math.min(t-1,n.length-1)]??1e3),s.signal.aborted))return}e.getResumable()&&f()}};return{begin(){t=0,l(),p()},teardown(){r&&=(clearTimeout(r),null),n=null,t=0,u()},wake:a}}var xb,Sb=o((()=>{P_(),xb=[1e3,2e3,4e3,8e3,8e3]}));B();const{setLoader:Cb,load:wb}=z({fallbackImport:()=>Promise.resolve().then(()=>(Sb(),yb))}),Tb=wb;pg(),Yg(),Nv(),Gd(),kg(),j_();const Eb=/* @__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 Db(e,t){return Eb.some(n=>e[n]!==t[n])}var Ob=class extends Error{constructor(e,t){super(t),this.name=`SessionHistoryError`,this.code=e}};function kb(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 Ab=e=>dg(e)||e===`suggest_replies`;var jb=class e{#e;#t;#n;#r;#i(e){if(this.#a(`cancel`),this.#n=!1,this.#e={runId:`run-${jv()}`,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 ob,this.#te=Promise.resolve(),this.#ne=null,this.#re=null,this.ttsSpokenMessageIds=/* @__PURE__ */ new Set,this.readAloud=new ab(()=>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)&&Vy().catch(()=>{});let i=e.message.toolCall,a=!!i?.name&&(dg(i.name)||i.name===`suggest_replies`&&Jg(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=>({...hg(e),sequence:e.sequence??this.#It()})),this.messages=this.#Rt(this.messages),this.client=new fy(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&&Ph().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&&vb().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 zh(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=ib.isSupported()?new ib({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 vb().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=Ph().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(!Lh(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 ob,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 Ob(`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 my(`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 Ob(`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 Ob(`superseded`,`A later selection won`);let o=await n.getPage(e,{context:r});if(i!==this.#M)throw new Ob(`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 Ob(`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 Ob(`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=O_(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&&mg(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 hg(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 Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`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=O_(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=D_(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=D_(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 ly&&(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 ly?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 ly&&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=Ih(this.config,n),i=Db(this.config,n);i&&(this.cancel(),this.#ut()),this.config=n,r&&(this.cleanupVoice(),n.voiceRecognition?.enabled===!0&&Bh(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 fy(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`?Av():t===`assistant`?jv():`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&&nb(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||!nb(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(`
|
|
197
197
|
|
|
198
198
|
`),a=[i,t].filter(Boolean).join(`
|
|
199
199
|
|