holostaff-widget 3.0.4 → 3.0.5
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/{CanvasRenderer-DtJMGjQ-.js → CanvasRenderer-Cvzvuw_n.js} +5 -5
- package/dist/{CanvasRenderer-DtJMGjQ-.js.map → CanvasRenderer-Cvzvuw_n.js.map} +1 -1
- package/dist/{Filter-BZ0p_cLc.js → Filter-B12vZysJ.js} +2 -2
- package/dist/{Filter-BZ0p_cLc.js.map → Filter-B12vZysJ.js.map} +1 -1
- package/dist/{GpuStencilModesToPixi-BhdxrQzF.js → GpuStencilModesToPixi-BTCb-hJl.js} +3 -3
- package/dist/{GpuStencilModesToPixi-BhdxrQzF.js.map → GpuStencilModesToPixi-BTCb-hJl.js.map} +1 -1
- package/dist/{RenderTargetSystem-Cbru8Ci0.js → RenderTargetSystem-BST_Il7Z.js} +3 -3
- package/dist/{RenderTargetSystem-Cbru8Ci0.js.map → RenderTargetSystem-BST_Il7Z.js.map} +1 -1
- package/dist/{WebGLRenderer--845IaSu.js → WebGLRenderer-DeH8DHPV.js} +5 -5
- package/dist/{WebGLRenderer--845IaSu.js.map → WebGLRenderer-DeH8DHPV.js.map} +1 -1
- package/dist/{WebGPURenderer-DBDzoMAw.js → WebGPURenderer-DbVqU5ig.js} +6 -6
- package/dist/{WebGPURenderer-DBDzoMAw.js.map → WebGPURenderer-DbVqU5ig.js.map} +1 -1
- package/dist/{browserAll-CIOBMh08.js → browserAll-CTsPT1oC.js} +3 -3
- package/dist/{browserAll-CIOBMh08.js.map → browserAll-CTsPT1oC.js.map} +1 -1
- package/dist/{getTextureBatchBindGroup-DCKtteRk.js → getTextureBatchBindGroup-CvtFkiCg.js} +3 -3
- package/dist/{getTextureBatchBindGroup-DCKtteRk.js.map → getTextureBatchBindGroup-CvtFkiCg.js.map} +1 -1
- package/dist/hs-widget.es.js +1 -1
- package/dist/hs-widget.umd.js +3 -3
- package/dist/hs-widget.umd.js.map +1 -1
- package/dist/{index-BbQvHSpa.js → index-BI6e3Gpf.js} +10 -10
- package/dist/index-BI6e3Gpf.js.map +1 -0
- package/dist/{webworkerAll-EB5JX-2r.js → webworkerAll-tY-BahNg.js} +3 -3
- package/dist/{webworkerAll-EB5JX-2r.js.map → webworkerAll-tY-BahNg.js.map} +1 -1
- package/package.json +1 -1
- package/dist/index-BbQvHSpa.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { B as p } from "./Filter-
|
|
2
|
-
import { T as a } from "./index-
|
|
1
|
+
import { B as p } from "./Filter-B12vZysJ.js";
|
|
2
|
+
import { T as a } from "./index-BI6e3Gpf.js";
|
|
3
3
|
const d = {};
|
|
4
4
|
function G(t, o, u) {
|
|
5
5
|
let e = 2166136261;
|
|
@@ -20,4 +20,4 @@ function f(t, o, u, e) {
|
|
|
20
20
|
export {
|
|
21
21
|
G as g
|
|
22
22
|
};
|
|
23
|
-
//# sourceMappingURL=getTextureBatchBindGroup-
|
|
23
|
+
//# sourceMappingURL=getTextureBatchBindGroup-CvtFkiCg.js.map
|
package/dist/{getTextureBatchBindGroup-DCKtteRk.js.map → getTextureBatchBindGroup-CvtFkiCg.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTextureBatchBindGroup-
|
|
1
|
+
{"version":3,"file":"getTextureBatchBindGroup-CvtFkiCg.js","sources":["../node_modules/pixi.js/lib/rendering/batcher/gpu/getTextureBatchBindGroup.mjs"],"sourcesContent":["import { BindGroup } from '../../renderers/gpu/shader/BindGroup.mjs';\nimport { Texture } from '../../renderers/shared/texture/Texture.mjs';\n\n\"use strict\";\nconst cachedGroups = {};\nfunction getTextureBatchBindGroup(textures, size, maxTextures) {\n let uid = 2166136261;\n for (let i = 0; i < size; i++) {\n uid ^= textures[i].uid;\n uid = Math.imul(uid, 16777619);\n uid >>>= 0;\n }\n return cachedGroups[uid] || generateTextureBatchBindGroup(textures, size, uid, maxTextures);\n}\nfunction generateTextureBatchBindGroup(textures, size, key, maxTextures) {\n const bindGroupResources = {};\n let bindIndex = 0;\n for (let i = 0; i < maxTextures; i++) {\n const texture = i < size ? textures[i] : Texture.EMPTY.source;\n bindGroupResources[bindIndex++] = texture.source;\n bindGroupResources[bindIndex++] = texture.style;\n }\n const bindGroup = new BindGroup(bindGroupResources);\n cachedGroups[key] = bindGroup;\n return bindGroup;\n}\n\nexport { getTextureBatchBindGroup };\n//# sourceMappingURL=getTextureBatchBindGroup.mjs.map\n"],"names":["cachedGroups","getTextureBatchBindGroup","textures","size","maxTextures","uid","i","generateTextureBatchBindGroup","key","bindGroupResources","bindIndex","texture","Texture","bindGroup","BindGroup"],"mappings":";;AAIA,MAAMA,IAAe,CAAA;AACrB,SAASC,EAAyBC,GAAUC,GAAMC,GAAa;AAC7D,MAAIC,IAAM;AACV,WAASC,IAAI,GAAGA,IAAIH,GAAMG;AACxB,IAAAD,KAAOH,EAASI,CAAC,EAAE,KACnBD,IAAM,KAAK,KAAKA,GAAK,QAAQ,GAC7BA,OAAS;AAEX,SAAOL,EAAaK,CAAG,KAAKE,EAA8BL,GAAUC,GAAME,GAAKD,CAAW;AAC5F;AACA,SAASG,EAA8BL,GAAUC,GAAMK,GAAKJ,GAAa;AACvE,QAAMK,IAAqB,CAAA;AAC3B,MAAIC,IAAY;AAChB,WAASJ,IAAI,GAAGA,IAAIF,GAAaE,KAAK;AACpC,UAAMK,IAAUL,IAAIH,IAAOD,EAASI,CAAC,IAAIM,EAAQ,MAAM;AACvD,IAAAH,EAAmBC,GAAW,IAAIC,EAAQ,QAC1CF,EAAmBC,GAAW,IAAIC,EAAQ;AAAA,EAC5C;AACA,QAAME,IAAY,IAAIC,EAAUL,CAAkB;AAClD,SAAAT,EAAaQ,CAAG,IAAIK,GACbA;AACT;","x_google_ignoreList":[0]}
|
package/dist/hs-widget.es.js
CHANGED
package/dist/hs-widget.umd.js
CHANGED
|
@@ -894,7 +894,7 @@ fn mainFragment(
|
|
|
894
894
|
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
895
895
|
return textureSample(img, imgSampler, texCoord);
|
|
896
896
|
}
|
|
897
|
-
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const f=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:f,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=f}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class nx{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Eu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Su,buffer:Qb,video:sx,compressed:tx};this._uploads={...t,cube:ix(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=vu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new nx(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new rx(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Gt({0:t,1:t.style,2:new ht({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=pe.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:pe.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=so.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return so.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Eu.extension={type:[A.WebGPUSystem],name:"texture"};class Tu{constructor(){this._maxTextures=0}contextChange(e){const t=new ht({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=Gn({name:"graphics",bits:[vc,Sc(this._maxTextures),_y,Vn]});this.shader=new Mt({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const f=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=f[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=Nn(b.textures,b.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Tu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Au{init(){const e=Gn({name:"mesh",bits:[ur,vy,Vn]});this._shader=new Mt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){se("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Au.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const ox=[...Ao,qr,fu,Oo,pu,uu,Eu,yu,bu,xu,_u,du,mu,hu],ax=[...Fh,gu],lx=[yh,Au,Tu],wu=[],Iu=[],Ru=[];Q.handleByNamedList(A.WebGPUSystem,wu),Q.handleByNamedList(A.WebGPUPipes,Iu),Q.handleByNamedList(A.WebGPUPipesAdaptor,Ru),Q.add(...ox,...ax,...lx);class cx extends vi{constructor(){const e={name:"webgpu",type:bt.WEBGPU,systems:wu,renderPipes:Iu,renderPipeAdaptors:Ru};super(e)}}const hx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:cx},Symbol.toStringTag,{value:"Module"}));Q.add(Rm,Mm);const Bi=480,xs=480;class ux{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new nc}async init(e="floating",t){this.mode=e,e==="inline"&&t&&(this.targetEl=document.querySelector(t),this.targetEl||(console.warn(`[HolostaffWidget] Container "${t}" not found, falling back to floating mode`),this.mode="floating")),await this.app.init({width:Bi,height:xs,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,preference:"webgl"}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",this.mode==="inline"&&this.targetEl?(Object.assign(this.container.style,{position:"relative",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"}),this.targetEl.style.position="relative",this.targetEl.style.cursor="pointer",this.targetEl.appendChild(this.container)):(Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Bi}px`,height:`${xs}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.body.appendChild(this.container));const i=this.app.canvas;return Object.assign(i.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(i),this.setupResize(),i}setupResize(){const e=()=>{if(this.mode==="inline"&&this.targetEl){const t=this.targetEl.getBoundingClientRect();this.container&&(this.container.style.width=`${t.width}px`,this.container.style.height=`${t.height}px`)}else{const t=window.innerWidth,i=Math.min(Bi,t),r=i/Bi,n=xs*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Bi,xs)};window.addEventListener("resize",e),this.mode==="inline"&&this.targetEl&&(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.targetEl)),e()}get isInline(){return this.mode==="inline"&&this.targetEl!==null}get inlineTarget(){return this.targetEl}get rootElement(){return this.container}get stageWidth(){return Bi}get stageHeight(){return xs}getInlineRect(){var e;return((e=this.targetEl)==null?void 0:e.getBoundingClientRect())??null}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function dx(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const vs={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function gr(s){const{target:e,props:t,duration:i,easing:r=vs.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(dx()){for(const f of Object.keys(t))e[f]=t[f];return o==null||o(),()=>{}}const l={};for(const f of Object.keys(t))l[f]=e[f];let c=-n,h=!1;const u=f=>{if(h||(c+=f.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Cs=200,Vt=Cs*(480/854),Mu=280;class fx{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new Ve,this.container.visible=!1,this.container.x=e/2,this.container.y=t+Vt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Cs}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new Ve,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}async loadIdleImage(e){const t=j.from(e),i=new Ft(t);i.width=Cs,i.height=Vt,i.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Vt,this.cancelEntrance=gr({target:this.container,props:{y:t},duration:700,easing:vs.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,gr({target:this.container,props:{y:this.stageHeight+Vt},duration:450,easing:vs.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new Se(-Cs/2,-Vt,Cs,Vt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=j.from(e);this.liveSprite=new Ft(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Mu/n;this.liveSprite.width=Mu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,gr({target:this.liveSprite,props:{alpha:1},duration:500,easing:vs.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&gr({target:this.liveSprite,props:{alpha:0},duration:400,easing:vs.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const px=[{urls:"stun:stun.l.google.com:19302"}],mx=3e3,gx="oai-events";class _x{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:px}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(gx),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,mx)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=t.includes("?")?"&":"?",a=`${t}${o}model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`SDP exchange failed (${l.status}): ${c}`)}return l.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const yx=24e3,bx=`
|
|
897
|
+
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let i=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};i=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const f=i.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),d=o.beginRenderPass({colorAttachments:[{view:f,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),g=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});d.setPipeline(t),d.setBindGroup(0,g),d.draw(3,1,0,0),d.end(),c=f}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:i,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||i.destroy(),e}}class nx{constructor(e){this.textureView=null,this.gpuTexture=e}destroy(){this.gpuTexture.destroy(),this.textureView=null,this.gpuTexture=null}}class Eu{constructor(e){this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._renderer=e,e.gc.addCollection(this,"_bindGroupHash","hash"),this._managedTextures=new kt({renderer:e,type:"resource",onUnload:this.onSourceUnload.bind(this),name:"gpuTextureSource"});const t={image:Su,buffer:Qb,video:sx,compressed:tx};this._uploads={...t,cube:ix(t)}}get managedTextures(){return Object.values(this._managedTextures.items)}contextChange(e){this._gpu=e}initSource(e){var t;return((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const c=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(c))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const i=vu[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/i.blockWidth)*i.blockWidth,n=Math.ceil(e.pixelHeight/i.blockHeight)*i.blockHeight,o={label:e.label,size:{width:r,height:n,depthOrArrayLayers:e.arrayLayerCount},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpu.device.createTexture(o);return e._gpuData[this._renderer.uid]=new nx(a),this._managedTextures.add(e)&&(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("updateMipmaps",this.onUpdateMipmaps,this)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new rx(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceUnload(e){e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this)}onSourceResize(e){e._gcLastUsed=this._renderer.gc.now;const t=e._gpuData[this._renderer.uid],i=t==null?void 0:t.gpuTexture;i?(i.width!==e.pixelWidth||i.height!==e.pixelHeight)&&(t.destroy(),this._bindGroupHash[e.uid]=null,e._gpuData[this._renderer.uid]=null,this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){var t;return e._gcLastUsed=this._renderer.gc.now,((t=e._gpuData[this._renderer.uid])==null?void 0:t.gpuTexture)||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]||this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Gt({0:t,1:t.style,2:new ht({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;t._gcLastUsed=this._renderer.gc.now;let i=t._gpuData[this._renderer.uid];return i||(this.initSource(t),i=t._gpuData[this._renderer.uid]),i.textureView||(i.textureView=i.gpuTexture.createView({dimension:t.viewDimension})),i.textureView}generateCanvas(e){const t=this._renderer,i=t.gpu.device.createCommandEncoder(),r=pe.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:pe.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),i.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([i.finish()]),r}getPixels(e){const t=this.generateCanvas(e),i=so.getOptimalCanvasAndContext(t.width,t.height),r=i.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return so.returnCanvasAndContext(i),{pixels:l,width:n,height:o}}destroy(){this._managedTextures.destroy();for(const e of Object.keys(this._bindGroupHash)){const t=Number(e),i=this._bindGroupHash[t];i==null||i.destroy()}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSamplers=null,this._bindGroupHash=null}}Eu.extension={type:[A.WebGPUSystem],name:"texture"};class Tu{constructor(){this._maxTextures=0}contextChange(e){const t=new ht({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const i=Gn({name:"graphics",bits:[vc,Sc(this._maxTextures),_y,Vn]});this.shader=new Mt({gpuProgram:i,resources:{localUniforms:t}})}execute(e,t){const i=t.context,r=i.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(i),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const f=l.instructions;let d=null;for(let g=0;g<l.instructionSize;g++){const _=f[g];if(_.topology!==d&&(d=_.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,_.topology)),r.groups[1]=_.bindGroup,!_.gpuBindGroup){const b=_.textures;_.bindGroup=Nn(b.textures,b.count,this._maxTextures),_.gpuBindGroup=n.bindGroup.getBindGroup(_.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,_.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(_.size,1,_.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Tu.extension={type:[A.WebGPUPipesAdaptor],name:"graphics"};class Au{init(){const e=Gn({name:"mesh",bits:[ur,vy,Vn]});this._shader=new Mt({gpuProgram:e,resources:{uTexture:j.EMPTY._source,uSampler:j.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new H}}}})}execute(e,t){const i=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=i.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){se("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=i.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=i.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}i.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Au.extension={type:[A.WebGPUPipesAdaptor],name:"mesh"};const ox=[...Ao,qr,fu,Oo,pu,uu,Eu,yu,bu,xu,_u,du,mu,hu],ax=[...Fh,gu],lx=[yh,Au,Tu],wu=[],Iu=[],Ru=[];Q.handleByNamedList(A.WebGPUSystem,wu),Q.handleByNamedList(A.WebGPUPipes,Iu),Q.handleByNamedList(A.WebGPUPipesAdaptor,Ru),Q.add(...ox,...ax,...lx);class cx extends vi{constructor(){const e={name:"webgpu",type:bt.WEBGPU,systems:wu,renderPipes:Iu,renderPipeAdaptors:Ru};super(e)}}const hx=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:cx},Symbol.toStringTag,{value:"Module"}));Q.add(Rm,Mm);const Bi=480,xs=480;class ux{constructor(){this.container=null,this.resizeObserver=null,this.mode="floating",this.targetEl=null,this.app=new nc}async init(e="floating",t){this.mode=e,e==="inline"&&t&&(this.targetEl=document.querySelector(t),this.targetEl||(console.warn(`[HolostaffWidget] Container "${t}" not found, falling back to floating mode`),this.mode="floating")),await this.app.init({width:Bi,height:xs,backgroundAlpha:0,antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0,preference:"webgl"}),this.container=document.createElement("div"),this.container.id="holostaff-widget-root",this.mode==="inline"&&this.targetEl?(Object.assign(this.container.style,{position:"relative",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"}),this.targetEl.style.position="relative",this.targetEl.style.cursor="pointer",this.targetEl.appendChild(this.container)):(Object.assign(this.container.style,{position:"fixed",bottom:"0",left:"50%",transform:"translateX(-50%)",width:`${Bi}px`,height:`${xs}px`,zIndex:"2147483646",pointerEvents:"none",overflow:"visible"}),document.documentElement.appendChild(this.container));const i=this.app.canvas;return Object.assign(i.style,{width:"100%",height:"100%",display:"block",pointerEvents:"auto"}),this.container.appendChild(i),this.setupResize(),i}setupResize(){const e=()=>{if(this.mode==="inline"&&this.targetEl){const t=this.targetEl.getBoundingClientRect();this.container&&(this.container.style.width=`${t.width}px`,this.container.style.height=`${t.height}px`)}else{const t=window.innerWidth,i=Math.min(Bi,t),r=i/Bi,n=xs*r;this.container&&(this.container.style.width=`${i}px`,this.container.style.height=`${n}px`)}this.app.renderer.resize(Bi,xs)};window.addEventListener("resize",e),this.mode==="inline"&&this.targetEl&&(this.resizeObserver=new ResizeObserver(e),this.resizeObserver.observe(this.targetEl)),e()}get isInline(){return this.mode==="inline"&&this.targetEl!==null}get inlineTarget(){return this.targetEl}get rootElement(){return this.container}get stageWidth(){return Bi}get stageHeight(){return xs}getInlineRect(){var e;return((e=this.targetEl)==null?void 0:e.getBoundingClientRect())??null}destroy(){var e,t;window.removeEventListener("resize",this.setupResize),(e=this.resizeObserver)==null||e.disconnect(),(t=this.container)==null||t.remove(),this.app.destroy(!0)}}function dx(){var s,e;return((e=(s=globalThis.matchMedia)==null?void 0:s.call(globalThis,"(prefers-reduced-motion: reduce)"))==null?void 0:e.matches)??!1}const vs={easeOutCubic:s=>1-Math.pow(1-s,3),easeInCubic:s=>s*s*s,easeOutBack:s=>1+2.70158*Math.pow(s-1,3)+1.70158*Math.pow(s-1,2),easeInOutSine:s=>-(Math.cos(Math.PI*s)-1)/2};function gr(s){const{target:e,props:t,duration:i,easing:r=vs.easeOutCubic,delay:n=0,onComplete:o,ticker:a}=s;if(dx()){for(const f of Object.keys(t))e[f]=t[f];return o==null||o(),()=>{}}const l={};for(const f of Object.keys(t))l[f]=e[f];let c=-n,h=!1;const u=f=>{if(h||(c+=f.deltaMS,c<0))return;const d=Math.min(c/i,1),g=r(d);for(const _ of Object.keys(t))e[_]=l[_]+(t[_]-l[_])*g;d>=1&&(a.remove(u),o==null||o())};return a.add(u),()=>{h=!0,a.remove(u)}}const Cs=200,Vt=Cs*(480/854),Mu=280;class fx{constructor(e,t){this.idleVideoEl=null,this.idleGroup=null,this.liveSprite=null,this.cancelGlow=null,this.cancelEntrance=null,this.visible=!1,this.widgetRoot=null,this.stageWidth=e,this.stageHeight=t,this.container=new Ve,this.container.visible=!1,this.container.x=e/2,this.container.y=t+Vt}async loadIdleVideo(e,t){this.widgetRoot=t,this.idleVideoEl=document.createElement("video"),this.idleVideoEl.src=e,this.idleVideoEl.loop=!0,this.idleVideoEl.muted=!0,this.idleVideoEl.playsInline=!0,this.idleVideoEl.crossOrigin="anonymous",Object.assign(this.idleVideoEl.style,{position:"absolute",bottom:"10px",left:"50%",transform:"translateX(-50%) translateY(100%)",width:`${Cs}px`,height:"auto",pointerEvents:"none",zIndex:"0",transition:"none"}),t.insertBefore(this.idleVideoEl,t.firstChild),await this.idleVideoEl.play(),this.idleGroup=new Ve,this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}async loadIdleImage(e){const t=j.from(e),i=new Ft(t);i.width=Cs,i.height=Vt,i.anchor.set(.5,1),this.idleGroup=new Ve,this.idleGroup.addChild(i),this.container.addChild(this.idleGroup),this.container.x=this.stageWidth/2,this.container.y=this.stageHeight+Vt}slideIn(e){if(this.visible)return;this.visible=!0;const t=this.stageHeight-10;this.container.alpha=1,this.container.visible=!0,this.container.y=this.stageHeight+Vt,this.cancelEntrance=gr({target:this.container,props:{y:t},duration:700,easing:vs.easeOutBack,ticker:e}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.7s cubic-bezier(0.34, 1.56, 0.64, 1)",this.idleVideoEl.style.transform="translateX(-50%) translateY(0)")}slideOut(e){var t;this.visible&&(this.visible=!1,(t=this.cancelGlow)==null||t.call(this),this.cancelGlow=null,gr({target:this.container,props:{y:this.stageHeight+Vt},duration:450,easing:vs.easeInCubic,ticker:e,onComplete:()=>{this.container.visible=!1}}),this.idleVideoEl&&(this.idleVideoEl.style.transition="transform 0.45s cubic-bezier(0.32, 0, 0.67, 0)",this.idleVideoEl.style.transform="translateX(-50%) translateY(100%)"))}get isVisible(){return this.visible}setInteractive(e){this.container.eventMode="static",this.container.cursor="pointer",this.container.hitArea=new Se(-Cs/2,-Vt,Cs,Vt),this.container.on("pointertap",e),this.idleVideoEl&&(this.idleVideoEl.style.pointerEvents="auto",this.idleVideoEl.style.cursor="pointer",this.idleVideoEl.addEventListener("click",e))}setLiveVideo(e,t){const i=()=>{var l;const r=j.from(e);this.liveSprite=new Ft(r);const n=e.videoWidth||1,o=e.videoHeight||1,a=Mu/n;this.liveSprite.width=Mu,this.liveSprite.height=o*a,this.liveSprite.anchor.set(.5,1),this.liveSprite.alpha=0,this.container.addChild(this.liveSprite),this.idleVideoEl&&(this.idleVideoEl.style.display="none"),this.idleGroup&&(this.idleGroup.visible=!1),(l=this.cancelGlow)==null||l.call(this),this.cancelGlow=null,gr({target:this.liveSprite,props:{alpha:1},duration:500,easing:vs.easeInOutSine,ticker:t})};if(e.videoWidth>0&&e.videoHeight>0)i();else{const r=()=>{e.removeEventListener("loadeddata",r),e.removeEventListener("resize",r),i()};e.addEventListener("loadeddata",r),e.addEventListener("resize",r)}}clearLiveVideo(e){this.liveSprite&&gr({target:this.liveSprite,props:{alpha:0},duration:400,easing:vs.easeInCubic,ticker:e,onComplete:()=>{var t;(t=this.liveSprite)==null||t.destroy(),this.liveSprite=null}}),this.idleVideoEl&&(this.idleVideoEl.style.display=""),this.idleGroup&&(this.idleGroup.visible=!0)}destroy(){var e,t;(e=this.cancelGlow)==null||e.call(this),(t=this.cancelEntrance)==null||t.call(this),this.idleVideoEl&&(this.idleVideoEl.pause(),this.idleVideoEl.remove()),this.container.destroy({children:!0})}}const px=[{urls:"stun:stun.l.google.com:19302"}],mx=3e3,gx="oai-events";class _x{constructor(e){this.onConnected=null,this.onDisconnected=null,this.onRemoteTrack=null,this.onDataMessage=null,this.onError=null,this.pc=null,this.dc=null,this.micStream=null,this._remoteAudioStream=null,this._connected=!1,this.opts={model:"gpt-4o-realtime-preview",voice:"verse",instructions:"",tools:[],...e}}get isConnected(){return this._connected}get dataChannel(){return this.dc}get remoteAudioStream(){return this._remoteAudioStream}async connect(){var e,t;try{console.log("[RealtimeSession] Requesting microphone..."),this.micStream=await navigator.mediaDevices.getUserMedia({audio:!0}),console.log("[RealtimeSession] Microphone granted"),this.pc=new RTCPeerConnection({iceServers:px}),this.setupPeerConnectionHandlers();for(const o of this.micStream.getAudioTracks())this.pc.addTrack(o,this.micStream);this.dc=this.pc.createDataChannel(gx),this.setupDataChannelHandlers();const i=await this.pc.createOffer();await this.pc.setLocalDescription(i),await this.waitForIceGathering();const r=(e=this.pc.localDescription)==null?void 0:e.sdp;if(!r)throw new Error("No local SDP after ICE gathering");console.log("[RealtimeSession] Exchanging SDP...");const n=await this.exchangeSDP(r);await this.pc.setRemoteDescription({type:"answer",sdp:n}),console.log("[RealtimeSession] Remote description set")}catch(i){const r=i instanceof Error?i:new Error(String(i));throw console.error("[RealtimeSession] Connection failed:",r.message),(t=this.onError)==null||t.call(this,r),this.close(),r}}sendJSON(e){if(!this.dc||this.dc.readyState!=="open"){console.warn("[RealtimeSession] Data channel not open, cannot send:",e);return}this.dc.send(JSON.stringify(e))}close(){var e;if(console.log("[RealtimeSession] Closing..."),this.dc){try{this.dc.close()}catch{}this.dc=null}if(this.pc){try{this.pc.close()}catch{}this.pc=null}if(this.micStream){for(const t of this.micStream.getTracks())t.stop();this.micStream=null}this._remoteAudioStream=null,this._connected&&(this._connected=!1,(e=this.onDisconnected)==null||e.call(this))}setupPeerConnectionHandlers(){this.pc&&(this.pc.ontrack=e=>{var t;console.log("[RealtimeSession] Remote audio track received"),this._remoteAudioStream=e.streams[0]??new MediaStream([e.track]),(t=this.onRemoteTrack)==null||t.call(this,this._remoteAudioStream)},this.pc.onconnectionstatechange=()=>{var t,i,r,n;const e=(t=this.pc)==null?void 0:t.connectionState;console.log("[RealtimeSession] Connection state:",e),e==="connected"?(this._connected=!0,(i=this.onConnected)==null||i.call(this)):(e==="failed"||e==="closed"||e==="disconnected")&&(this._connected&&(this._connected=!1,(r=this.onDisconnected)==null||r.call(this)),e==="failed"&&((n=this.onError)==null||n.call(this,new Error("WebRTC connection failed"))))})}waitForIceGathering(){return!this.pc||this.pc.iceGatheringState==="complete"?Promise.resolve():new Promise(e=>{const t=this.pc;let i;const r=()=>{clearTimeout(i);try{t.removeEventListener("icegatheringstatechange",n)}catch{}e()},n=()=>{t.iceGatheringState==="complete"&&r()};t.addEventListener("icegatheringstatechange",n),i=setTimeout(r,mx)})}async exchangeSDP(e){const{webrtcUrl:t,ephemeralKey:i,model:r,voice:n}=this.opts,o=t.includes("?")?"&":"?",a=`${t}${o}model=${encodeURIComponent(r)}&voice=${encodeURIComponent(n)}`,l=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/sdp",Accept:"application/sdp"},body:e});if(!l.ok){const c=await l.text().catch(()=>"");throw new Error(`SDP exchange failed (${l.status}): ${c}`)}return l.text()}setupDataChannelHandlers(){this.dc&&(this.dc.onopen=()=>{console.log("[RealtimeSession] Data channel open"),this.sendSessionUpdate(),this.sendJSON({type:"response.create"})},this.dc.onmessage=e=>{var t;try{const i=JSON.parse(e.data);(t=this.onDataMessage)==null||t.call(this,i)}catch(i){console.warn("[RealtimeSession] Failed to parse data channel message:",i)}},this.dc.onclose=()=>{console.log("[RealtimeSession] Data channel closed")},this.dc.onerror=e=>{console.error("[RealtimeSession] Data channel error:",e)})}sendSessionUpdate(){const e={instructions:this.opts.instructions,modalities:["audio","text"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:700,create_response:!0}};this.opts.tools&&this.opts.tools.length>0&&(e.tools=this.opts.tools),this.sendJSON({type:"session.update",session:e})}}const yx=24e3,bx=`
|
|
898
898
|
class PcmBufferProcessor extends AudioWorkletProcessor {
|
|
899
899
|
constructor() {
|
|
900
900
|
super()
|
|
@@ -1056,12 +1056,12 @@ Continue the conversation naturally from this context.`,i=e.actionId;this.cleanu
|
|
|
1056
1056
|
0%, 100% { box-shadow: 0 0 0 0 var(--hs-accent-glow); }
|
|
1057
1057
|
50% { box-shadow: 0 0 14px 5px var(--hs-accent-glow); }
|
|
1058
1058
|
}
|
|
1059
|
-
`;class of{constructor(){this.el=null,this.avatarWrap=null,this.avatarImg=null,this.avatarVideo=null,this.nameEl=null,this.suggestionArea=null,this.suggestionText=null,this.currentAnim=null,this._state="hidden",this.pulseStyleInjected=!1,this.avatarUrl=null,this.videoUrl=null,this.staffName="",this.onClick=null,this.onSuggestionAccept=null,this.onSuggestionDismiss=null}init(e,t,i){if(this.el)return;if(St(),this.avatarUrl=e,this.videoUrl=t,this.staffName=i,this.el=Kt({radius:"pill",elevation:"elevated",interactive:!0,className:"hs-chat-pill"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-5)",left:"0",right:"0",margin:"0 auto",width:"fit-content",maxWidth:"min(90vw, 600px)",display:"none",alignItems:"center",gap:"0px",padding:"5px",zIndex:W.zControls,cursor:"pointer",userSelect:"none",opacity:"0",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.18)",transition:"gap 0.3s ease, padding 0.3s ease, box-shadow 0.2s ease",overflow:"hidden"}),$i(this.el),this.el.addEventListener("mouseenter",()=>{this.el&&(this.el.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.24)")}),this.el.addEventListener("mouseleave",()=>{this.el&&(this.el.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.18)")}),this.avatarWrap=document.createElement("div"),Object.assign(this.avatarWrap.style,{width:"36px",height:"36px",borderRadius:"50%",overflow:"hidden",flexShrink:"0",position:"relative",border:"1.5px solid var(--hs-glass-border)",transition:"box-shadow 0.3s ease, width 0.3s ease, height 0.3s ease"}),e)this.avatarImg=document.createElement("img"),this.avatarImg.src=e,this.avatarImg.alt=i,Object.assign(this.avatarImg.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),this.avatarWrap.appendChild(this.avatarImg);else{const a=document.createElement("div");Object.assign(a.style,{width:"100%",height:"100%",background:"var(--hs-accent)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"var(--hs-text-sm)",fontWeight:"var(--hs-weight-semibold)",color:"var(--hs-accent-text)"}),a.textContent=i.charAt(0).toUpperCase(),this.avatarWrap.appendChild(a)}t&&(this.avatarVideo=document.createElement("video"),this.avatarVideo.src=t,this.avatarVideo.muted=!0,this.avatarVideo.loop=!0,this.avatarVideo.playsInline=!0,this.avatarVideo.setAttribute("playsinline",""),Object.assign(this.avatarVideo.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"cover",display:"none"}),this.avatarWrap.appendChild(this.avatarVideo)),this.el.appendChild(this.avatarWrap),this.nameEl=document.createElement("span"),vt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=i,Object.assign(this.nameEl.style,{whiteSpace:"nowrap",overflow:"hidden",maxWidth:"0",opacity:"0",transition:"max-width 0.3s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"}),this.el.appendChild(this.nameEl),this.suggestionArea=document.createElement("div"),Object.assign(this.suggestionArea.style,{display:"flex",alignItems:"center",gap:"var(--hs-space-2)",maxWidth:"0",opacity:"0",overflow:"hidden",transition:"max-width 0.35s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"});const r=document.createElement("span");Object.assign(r.style,{width:"1px",height:"20px",background:"var(--hs-divider)",flexShrink:"0"}),this.suggestionArea.appendChild(r),this.suggestionText=document.createElement("span"),vt(this.suggestionText,"secondary","sm","normal"),Object.assign(this.suggestionText.style,{whiteSpace:"normal",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",overflow:"hidden"}),this.suggestionArea.appendChild(this.suggestionText);const n=Ct({label:"Let's talk",variant:"accent",size:"sm",onClick:a=>{var l;a.stopPropagation(),(l=this.onSuggestionAccept)==null||l.call(this)}});n.style.flexShrink="0",this.suggestionArea.appendChild(n);const o=document.createElement("button");o.textContent="✕",Object.assign(o.style,{background:"none",border:"none",color:"var(--hs-text-tertiary)",fontSize:"12px",cursor:"pointer",padding:"4px",flexShrink:"0",lineHeight:"1",transition:"color 0.15s ease"}),o.addEventListener("mouseenter",()=>{o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.color="var(--hs-text-tertiary)"}),o.addEventListener("click",a=>{var l;a.stopPropagation(),(l=this.onSuggestionDismiss)==null||l.call(this),this.clearSuggestion()}),this.suggestionArea.appendChild(o),this.el.appendChild(this.suggestionArea),this.el.addEventListener("click",a=>{var l;a.target.closest("button")||(l=this.onClick)==null||l.call(this)}),document.body.appendChild(this.el)}showAmbient(){var e;!this.el||this._state==="ambient"||(this._state="ambient",this.collapseName(),this.collapseSuggestion(),this.stopAvatarVideo(),this.el.style.display="flex",this.el.style.gap="0px",this.el.style.padding="5px",(e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.8,y:12}}))}showNamed(){var t;if(!this.el||this._state==="named")return;const e=this._state==="hidden";this._state="named",this.collapseSuggestion(),this.stopAvatarVideo(),this.expandName(),this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",e&&((t=this.currentAnim)==null||t.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.85,y:16}}))}showSuggestion(e){var i;if(!this.el||!this.suggestionText)return;const t=this._state==="hidden";this._state="suggestion",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="10px 16px 10px 10px",this.el.style.borderRadius="var(--hs-radius-lg)",this.collapseName(),t&&((i=this.currentAnim)==null||i.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.9,y:12}})),this.startAvatarVideo(),this.startAvatarPulse(),this.suggestionText.textContent=e,this.suggestionText.title=e,requestAnimationFrame(()=>{this.suggestionArea&&(this.suggestionArea.style.maxWidth="500px",this.suggestionArea.style.opacity="1",this.suggestionArea.style.marginLeft="var(--hs-space-2)")})}clearSuggestion(){this.el&&(this._state="named",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.el.style.padding="8px 20px 8px 8px",this.el.style.borderRadius="var(--hs-radius-pill)")}showConnecting(){var e;!this.el||!this.nameEl||(this._state="connecting",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.nameEl.textContent="Connecting...",this.nameEl.style.opacity="0.6",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",this.el.style.opacity==="0"&&((e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})))}restoreName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1")}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;this._state="hidden",this.stopAvatarPulse(),this.stopAvatarVideo();const e=this.el;this.currentAnim=Nt(e,{remove:!1,preset:"smooth",to:{opacity:0,scale:.9,y:12},onComplete:()=>{e.style.display="none"}})}destroy(){var e,t;(e=this.currentAnim)==null||e.stop(),this.stopAvatarPulse(),this.stopAvatarVideo(),(t=this.el)==null||t.remove(),this.el=null,this._state="hidden"}get state(){return this._state}get isVisible(){return this._state!=="hidden"}expandName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1",this.nameEl.style.maxWidth="150px",this.nameEl.style.marginLeft="var(--hs-space-2)")}collapseName(){this.nameEl&&(this.nameEl.style.maxWidth="0",this.nameEl.style.opacity="0",this.nameEl.style.marginLeft="0")}collapseSuggestion(){this.suggestionArea&&(this.suggestionArea.style.maxWidth="0",this.suggestionArea.style.opacity="0",this.suggestionArea.style.marginLeft="0")}startAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.style.display="block",this.avatarVideo.currentTime=0,this.avatarVideo.play().catch(()=>{}),this.avatarImg.style.opacity="0")}stopAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.pause(),this.avatarVideo.style.display="none",this.avatarImg.style.opacity="1")}startAvatarPulse(){this.avatarWrap&&(this.injectPulseStyle(),this.avatarWrap.style.animation="hs-pill-pulse 1.5s ease-in-out infinite")}stopAvatarPulse(){this.avatarWrap&&(this.avatarWrap.style.animation="")}injectPulseStyle(){if(this.pulseStyleInjected)return;this.pulseStyleInjected=!0;const e=document.createElement("style");e.textContent=UC,document.head.appendChild(e)}}const FC=15e3,GC=320;class LC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",i.el.appendChild(n),this.mountCard(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t||"",Object.assign(r.style,{width:"100%",borderRadius:"var(--hs-radius-sm)",display:"block",marginBottom:t?"var(--hs-space-2)":"0"}),i.el.appendChild(r),t){const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,i.el.appendChild(n)}this.mountCard(i)}showBulletList(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("ul");Object.assign(n.style,{margin:"0",paddingLeft:"var(--hs-space-5)",listStyleType:"none"}),t.forEach(o=>{const a=document.createElement("li");Object.assign(a.style,{marginBottom:"var(--hs-space-1)",position:"relative",paddingLeft:"0"});const l=document.createElement("span");Object.assign(l.style,{position:"absolute",left:"-16px",top:"6px",width:"5px",height:"5px",borderRadius:"50%",background:"var(--hs-accent)"}),a.appendChild(l);const c=document.createElement("span");vt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),i.el.appendChild(n),this.mountCard(i)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){St();const e=Kt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(GC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>this.dismiss(r)});Object.assign(t.style,{position:"absolute",top:"var(--hs-space-2)",right:"var(--hs-space-2)",minWidth:"0",padding:"2px 6px",fontSize:"var(--hs-text-xs)"}),e.appendChild(t);const i=setTimeout(()=>this.dismiss(r),FC),r={el:e,timer:i,anim:null};return r}mountCard(e){document.body.appendChild(e.el),this.positionCard(e.el,this.cards.length),this.cards.push(e),e.anim=rt(e.el,{preset:"snappy"})}positionCard(e,t){const i=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${i+t*(r+8)}px`,left:"50%",transform:"translateX(-50%)"})}dismiss(e){const t=this.cards.indexOf(e);t>=0&&this.cards.splice(t,1),this.removeCard(e)}removeCard(e){var t;clearTimeout(e.timer),(t=e.anim)==null||t.stop(),e.anim=Nt(e.el,{remove:!0,preset:"smooth"})}}class WC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){St(),this.hide(),this.el=Kt({radius:"pill",elevation:"elevated",className:"hs-controls"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-3)",left:"0",right:"0",margin:"0 auto",width:"fit-content",display:"flex",alignItems:"center",gap:"var(--hs-space-1)",padding:"4px",zIndex:W.zControls,opacity:"0"}),$i(this.el);const e=Ct({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var i,r;this.minimized?(this.minimized=!1,e.textContent="—",(i=this.onRestore)==null||i.call(this)):(this.minimized=!0,e.textContent="▲",(r=this.onMinimize)==null||r.call(this))}});Object.assign(e.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(e);const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var i;return(i=this.onClose)==null?void 0:i.call(this)}});Object.assign(t.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(t),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;const e=this.el;this.el=null,this.minimized=!1,this.currentAnim=Nt(e,{remove:!0,preset:"smooth"})}}const HC=1e4;class VC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return St(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Kt({radius:"lg",elevation:"elevated",role:"alertdialog",className:"hs-confirm-prompt"}),Object.assign(this.el.style,{position:"fixed",bottom:"320px",left:"50%",transform:"translateX(-50%)",padding:"var(--hs-space-5)",maxWidth:"340px",minWidth:"240px",zIndex:W.zTop,opacity:"0",textAlign:"center"}),this.el.setAttribute("aria-label","Action confirmation"),$i(this.el);const i=document.createElement("p");vt(i,"primary","base","normal"),i.textContent=e,i.style.marginBottom="var(--hs-space-4)",this.el.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(Ct({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(Ct({label:"No",variant:"default",size:"md",onClick:()=>this.resolve(!1)})),this.el.appendChild(r),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy"}),this.autoTimer=setTimeout(()=>this.resolve(!1),HC)})}dismiss(){this.resolver&&(this.resolver(!1),this.resolver=null),this.cleanup()}resolve(e){var t;(t=this.resolver)==null||t.call(this,e),this.resolver=null,this.cleanup()}cleanup(){var e;if(this.autoTimer&&(clearTimeout(this.autoTimer),this.autoTimer=null),(e=this.currentAnim)==null||e.stop(),this.el){const t=this.el;this.el=null,this.currentAnim=Nt(t,{remove:!0,preset:"smooth"})}}}const zC=520,$C=340,ra=12;class jC{constructor(){this.currentAnim=null,St(),this.el=Kt({radius:"lg",elevation:"elevated",className:"hs-stage-backdrop"}),Object.assign(this.el.style,{position:"fixed",bottom:"0",left:"0",right:"0",margin:"0 auto",width:`${zC}px`,height:`${$C}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${ra}px ${ra}px 0 ${ra}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),$i(this.el),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",position:"relative",overflow:"hidden",borderRadius:"var(--hs-radius-md) var(--hs-radius-md) 0 0"}),this.el.appendChild(this.contentArea)}appendContent(e){Object.assign(e.style,{width:"100%",height:"100%",objectFit:"cover",display:"block",borderRadius:"inherit"}),this.contentArea.appendChild(e)}show(){document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.95,y:24}})}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.currentAnim=Nt(this.el,{remove:!0,preset:"smooth",to:{opacity:0,scale:.95,y:16}})}get contentElement(){return this.contentArea}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.el.remove()}}const XC=`
|
|
1059
|
+
`;class of{constructor(){this.el=null,this.avatarWrap=null,this.avatarImg=null,this.avatarVideo=null,this.nameEl=null,this.suggestionArea=null,this.suggestionText=null,this.currentAnim=null,this._state="hidden",this.pulseStyleInjected=!1,this.avatarUrl=null,this.videoUrl=null,this.staffName="",this.onClick=null,this.onSuggestionAccept=null,this.onSuggestionDismiss=null}init(e,t,i){if(this.el)return;if(St(),this.avatarUrl=e,this.videoUrl=t,this.staffName=i,this.el=Kt({radius:"pill",elevation:"elevated",interactive:!0,className:"hs-chat-pill"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-5)",left:"0",right:"0",margin:"0 auto",width:"fit-content",maxWidth:"min(90vw, 600px)",display:"none",alignItems:"center",gap:"0px",padding:"5px",zIndex:W.zControls,cursor:"pointer",userSelect:"none",opacity:"0",boxShadow:"0 4px 24px rgba(0, 0, 0, 0.18)",transition:"gap 0.3s ease, padding 0.3s ease, box-shadow 0.2s ease",overflow:"hidden"}),$i(this.el),this.el.addEventListener("mouseenter",()=>{this.el&&(this.el.style.boxShadow="0 6px 32px rgba(0, 0, 0, 0.24)")}),this.el.addEventListener("mouseleave",()=>{this.el&&(this.el.style.boxShadow="0 4px 24px rgba(0, 0, 0, 0.18)")}),this.avatarWrap=document.createElement("div"),Object.assign(this.avatarWrap.style,{width:"36px",height:"36px",borderRadius:"50%",overflow:"hidden",flexShrink:"0",position:"relative",border:"1.5px solid var(--hs-glass-border)",transition:"box-shadow 0.3s ease, width 0.3s ease, height 0.3s ease"}),e)this.avatarImg=document.createElement("img"),this.avatarImg.src=e,this.avatarImg.alt=i,Object.assign(this.avatarImg.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),this.avatarWrap.appendChild(this.avatarImg);else{const a=document.createElement("div");Object.assign(a.style,{width:"100%",height:"100%",background:"var(--hs-accent)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"var(--hs-text-sm)",fontWeight:"var(--hs-weight-semibold)",color:"var(--hs-accent-text)"}),a.textContent=i.charAt(0).toUpperCase(),this.avatarWrap.appendChild(a)}t&&(this.avatarVideo=document.createElement("video"),this.avatarVideo.src=t,this.avatarVideo.muted=!0,this.avatarVideo.loop=!0,this.avatarVideo.playsInline=!0,this.avatarVideo.setAttribute("playsinline",""),Object.assign(this.avatarVideo.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"cover",display:"none"}),this.avatarWrap.appendChild(this.avatarVideo)),this.el.appendChild(this.avatarWrap),this.nameEl=document.createElement("span"),vt(this.nameEl,"primary","base","medium"),this.nameEl.textContent=i,Object.assign(this.nameEl.style,{whiteSpace:"nowrap",overflow:"hidden",maxWidth:"0",opacity:"0",transition:"max-width 0.3s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"}),this.el.appendChild(this.nameEl),this.suggestionArea=document.createElement("div"),Object.assign(this.suggestionArea.style,{display:"flex",alignItems:"center",gap:"var(--hs-space-2)",maxWidth:"0",opacity:"0",overflow:"hidden",transition:"max-width 0.35s ease, opacity 0.25s ease, margin 0.3s ease",marginLeft:"0"});const r=document.createElement("span");Object.assign(r.style,{width:"1px",height:"20px",background:"var(--hs-divider)",flexShrink:"0"}),this.suggestionArea.appendChild(r),this.suggestionText=document.createElement("span"),vt(this.suggestionText,"secondary","sm","normal"),Object.assign(this.suggestionText.style,{whiteSpace:"normal",lineHeight:"1.4",display:"-webkit-box",WebkitLineClamp:"2",WebkitBoxOrient:"vertical",overflow:"hidden"}),this.suggestionArea.appendChild(this.suggestionText);const n=Ct({label:"Let's talk",variant:"accent",size:"sm",onClick:a=>{var l;a.stopPropagation(),(l=this.onSuggestionAccept)==null||l.call(this)}});n.style.flexShrink="0",this.suggestionArea.appendChild(n);const o=document.createElement("button");o.textContent="✕",Object.assign(o.style,{background:"none",border:"none",color:"var(--hs-text-tertiary)",fontSize:"12px",cursor:"pointer",padding:"4px",flexShrink:"0",lineHeight:"1",transition:"color 0.15s ease"}),o.addEventListener("mouseenter",()=>{o.style.color="var(--hs-text-primary)"}),o.addEventListener("mouseleave",()=>{o.style.color="var(--hs-text-tertiary)"}),o.addEventListener("click",a=>{var l;a.stopPropagation(),(l=this.onSuggestionDismiss)==null||l.call(this),this.clearSuggestion()}),this.suggestionArea.appendChild(o),this.el.appendChild(this.suggestionArea),this.el.addEventListener("click",a=>{var l;a.target.closest("button")||(l=this.onClick)==null||l.call(this)}),document.documentElement.appendChild(this.el)}showAmbient(){var e;!this.el||this._state==="ambient"||(this._state="ambient",this.collapseName(),this.collapseSuggestion(),this.stopAvatarVideo(),this.el.style.display="flex",this.el.style.gap="0px",this.el.style.padding="5px",(e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.8,y:12}}))}showNamed(){var t;if(!this.el||this._state==="named")return;const e=this._state==="hidden";this._state="named",this.collapseSuggestion(),this.stopAvatarVideo(),this.expandName(),this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",e&&((t=this.currentAnim)==null||t.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.85,y:16}}))}showSuggestion(e){var i;if(!this.el||!this.suggestionText)return;const t=this._state==="hidden";this._state="suggestion",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="10px 16px 10px 10px",this.el.style.borderRadius="var(--hs-radius-lg)",this.collapseName(),t&&((i=this.currentAnim)==null||i.stop(),this.el.style.opacity="0",this.currentAnim=rt(this.el,{preset:"bouncy",from:{opacity:0,scale:.9,y:12}})),this.startAvatarVideo(),this.startAvatarPulse(),this.suggestionText.textContent=e,this.suggestionText.title=e,requestAnimationFrame(()=>{this.suggestionArea&&(this.suggestionArea.style.maxWidth="500px",this.suggestionArea.style.opacity="1",this.suggestionArea.style.marginLeft="var(--hs-space-2)")})}clearSuggestion(){this.el&&(this._state="named",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.el.style.padding="8px 20px 8px 8px",this.el.style.borderRadius="var(--hs-radius-pill)")}showConnecting(){var e;!this.el||!this.nameEl||(this._state="connecting",this.stopAvatarPulse(),this.stopAvatarVideo(),this.collapseSuggestion(),this.expandName(),this.nameEl.textContent="Connecting...",this.nameEl.style.opacity="0.6",this.el.style.display="flex",this.el.style.gap="var(--hs-space-3)",this.el.style.padding="8px 20px 8px 8px",this.el.style.opacity==="0"&&((e=this.currentAnim)==null||e.stop(),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})))}restoreName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1")}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;this._state="hidden",this.stopAvatarPulse(),this.stopAvatarVideo();const e=this.el;this.currentAnim=Nt(e,{remove:!1,preset:"smooth",to:{opacity:0,scale:.9,y:12},onComplete:()=>{e.style.display="none"}})}destroy(){var e,t;(e=this.currentAnim)==null||e.stop(),this.stopAvatarPulse(),this.stopAvatarVideo(),(t=this.el)==null||t.remove(),this.el=null,this._state="hidden"}get state(){return this._state}get isVisible(){return this._state!=="hidden"}expandName(){this.nameEl&&(this.nameEl.textContent=this.staffName,this.nameEl.style.opacity="1",this.nameEl.style.maxWidth="150px",this.nameEl.style.marginLeft="var(--hs-space-2)")}collapseName(){this.nameEl&&(this.nameEl.style.maxWidth="0",this.nameEl.style.opacity="0",this.nameEl.style.marginLeft="0")}collapseSuggestion(){this.suggestionArea&&(this.suggestionArea.style.maxWidth="0",this.suggestionArea.style.opacity="0",this.suggestionArea.style.marginLeft="0")}startAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.style.display="block",this.avatarVideo.currentTime=0,this.avatarVideo.play().catch(()=>{}),this.avatarImg.style.opacity="0")}stopAvatarVideo(){!this.avatarVideo||!this.avatarImg||(this.avatarVideo.pause(),this.avatarVideo.style.display="none",this.avatarImg.style.opacity="1")}startAvatarPulse(){this.avatarWrap&&(this.injectPulseStyle(),this.avatarWrap.style.animation="hs-pill-pulse 1.5s ease-in-out infinite")}stopAvatarPulse(){this.avatarWrap&&(this.avatarWrap.style.animation="")}injectPulseStyle(){if(this.pulseStyleInjected)return;this.pulseStyleInjected=!0;const e=document.createElement("style");e.textContent=UC,document.head.appendChild(e)}}const FC=15e3,GC=320;class LC{constructor(){this.cards=[],this.anchor=null}setAnchor(e){this.anchor=e}showTextCard(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,n.style.whiteSpace="pre-wrap",i.el.appendChild(n),this.mountCard(i)}showImageCard(e,t){const i=this.createCard(),r=document.createElement("img");if(r.src=e,r.alt=t||"",Object.assign(r.style,{width:"100%",borderRadius:"var(--hs-radius-sm)",display:"block",marginBottom:t?"var(--hs-space-2)":"0"}),i.el.appendChild(r),t){const n=document.createElement("div");vt(n,"secondary","sm","normal"),n.textContent=t,i.el.appendChild(n)}this.mountCard(i)}showBulletList(e,t){const i=this.createCard(),r=document.createElement("div");vt(r,"primary","base","semibold"),r.textContent=e,r.style.marginBottom="var(--hs-space-2)",i.el.appendChild(r);const n=document.createElement("ul");Object.assign(n.style,{margin:"0",paddingLeft:"var(--hs-space-5)",listStyleType:"none"}),t.forEach(o=>{const a=document.createElement("li");Object.assign(a.style,{marginBottom:"var(--hs-space-1)",position:"relative",paddingLeft:"0"});const l=document.createElement("span");Object.assign(l.style,{position:"absolute",left:"-16px",top:"6px",width:"5px",height:"5px",borderRadius:"50%",background:"var(--hs-accent)"}),a.appendChild(l);const c=document.createElement("span");vt(c,"secondary","sm","normal"),c.textContent=o,a.appendChild(c),n.appendChild(a)}),i.el.appendChild(n),this.mountCard(i)}dismissAll(){this.cards.forEach(e=>this.removeCard(e)),this.cards=[]}createCard(){St();const e=Kt({radius:"md",elevation:"elevated",className:"hs-overlay-card"});Object.assign(e.style,{position:"fixed",maxWidth:`${Math.min(GC,window.innerWidth-32)}px`,padding:"var(--hs-space-4)",zIndex:W.zOverlay,opacity:"0",pointerEvents:"auto"});const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>this.dismiss(r)});Object.assign(t.style,{position:"absolute",top:"var(--hs-space-2)",right:"var(--hs-space-2)",minWidth:"0",padding:"2px 6px",fontSize:"var(--hs-text-xs)"}),e.appendChild(t);const i=setTimeout(()=>this.dismiss(r),FC),r={el:e,timer:i,anim:null};return r}mountCard(e){document.body.appendChild(e.el),this.positionCard(e.el,this.cards.length),this.cards.push(e),e.anim=rt(e.el,{preset:"snappy"})}positionCard(e,t){const i=500+t*10,r=e.offsetHeight||80;Object.assign(e.style,{bottom:`${i+t*(r+8)}px`,left:"50%",transform:"translateX(-50%)"})}dismiss(e){const t=this.cards.indexOf(e);t>=0&&this.cards.splice(t,1),this.removeCard(e)}removeCard(e){var t;clearTimeout(e.timer),(t=e.anim)==null||t.stop(),e.anim=Nt(e.el,{remove:!0,preset:"smooth"})}}class WC{constructor(){this.el=null,this.currentAnim=null,this.minimized=!1,this.onMinimize=null,this.onRestore=null,this.onClose=null}show(){St(),this.hide(),this.el=Kt({radius:"pill",elevation:"elevated",className:"hs-controls"}),Object.assign(this.el.style,{position:"fixed",bottom:"var(--hs-space-3)",left:"0",right:"0",margin:"0 auto",width:"fit-content",display:"flex",alignItems:"center",gap:"var(--hs-space-1)",padding:"4px",zIndex:W.zControls,opacity:"0"}),$i(this.el);const e=Ct({label:this.minimized?"▲":"—",variant:"ghost",size:"sm",onClick:()=>{var i,r;this.minimized?(this.minimized=!1,e.textContent="—",(i=this.onRestore)==null||i.call(this)):(this.minimized=!0,e.textContent="▲",(r=this.onMinimize)==null||r.call(this))}});Object.assign(e.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(e);const t=Ct({label:"✕",variant:"ghost",size:"sm",onClick:()=>{var i;return(i=this.onClose)==null?void 0:i.call(this)}});Object.assign(t.style,{minWidth:"32px",height:"32px",padding:"0",fontSize:"14px",borderRadius:"50%"}),this.el.appendChild(t),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy",from:{opacity:0,scale:.9,y:8}})}hide(){var t;if((t=this.currentAnim)==null||t.stop(),!this.el)return;const e=this.el;this.el=null,this.minimized=!1,this.currentAnim=Nt(e,{remove:!0,preset:"smooth"})}}const HC=1e4;class VC{constructor(){this.el=null,this.currentAnim=null,this.autoTimer=null,this.resolver=null}ask(e){return St(),this.dismiss(),new Promise(t=>{this.resolver=t,this.el=Kt({radius:"lg",elevation:"elevated",role:"alertdialog",className:"hs-confirm-prompt"}),Object.assign(this.el.style,{position:"fixed",bottom:"320px",left:"50%",transform:"translateX(-50%)",padding:"var(--hs-space-5)",maxWidth:"340px",minWidth:"240px",zIndex:W.zTop,opacity:"0",textAlign:"center"}),this.el.setAttribute("aria-label","Action confirmation"),$i(this.el);const i=document.createElement("p");vt(i,"primary","base","normal"),i.textContent=e,i.style.marginBottom="var(--hs-space-4)",this.el.appendChild(i);const r=document.createElement("div");Object.assign(r.style,{display:"flex",gap:"var(--hs-space-3)",justifyContent:"center"}),r.appendChild(Ct({label:"Yes",variant:"accent",size:"md",onClick:()=>this.resolve(!0)})),r.appendChild(Ct({label:"No",variant:"default",size:"md",onClick:()=>this.resolve(!1)})),this.el.appendChild(r),document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"snappy"}),this.autoTimer=setTimeout(()=>this.resolve(!1),HC)})}dismiss(){this.resolver&&(this.resolver(!1),this.resolver=null),this.cleanup()}resolve(e){var t;(t=this.resolver)==null||t.call(this,e),this.resolver=null,this.cleanup()}cleanup(){var e;if(this.autoTimer&&(clearTimeout(this.autoTimer),this.autoTimer=null),(e=this.currentAnim)==null||e.stop(),this.el){const t=this.el;this.el=null,this.currentAnim=Nt(t,{remove:!0,preset:"smooth"})}}}const zC=520,$C=340,ra=12;class jC{constructor(){this.currentAnim=null,St(),this.el=Kt({radius:"lg",elevation:"elevated",className:"hs-stage-backdrop"}),Object.assign(this.el.style,{position:"fixed",bottom:"0",left:"0",right:"0",margin:"0 auto",width:`${zC}px`,height:`${$C}px`,zIndex:W.zOverlay,overflow:"hidden",display:"flex",flexDirection:"column",opacity:"0",padding:`${ra}px ${ra}px 0 ${ra}px`,borderRadius:"var(--hs-radius-lg) var(--hs-radius-lg) 0 0",borderBottom:"none"}),$i(this.el),this.contentArea=document.createElement("div"),Object.assign(this.contentArea.style,{flex:"1",position:"relative",overflow:"hidden",borderRadius:"var(--hs-radius-md) var(--hs-radius-md) 0 0"}),this.el.appendChild(this.contentArea)}appendContent(e){Object.assign(e.style,{width:"100%",height:"100%",objectFit:"cover",display:"block",borderRadius:"inherit"}),this.contentArea.appendChild(e)}show(){document.body.appendChild(this.el),this.currentAnim=rt(this.el,{preset:"gentle",from:{opacity:0,scale:.95,y:24}})}hide(){var e;(e=this.currentAnim)==null||e.stop(),this.currentAnim=Nt(this.el,{remove:!0,preset:"smooth",to:{opacity:0,scale:.95,y:16}})}get contentElement(){return this.contentArea}destroy(){var e;(e=this.currentAnim)==null||e.stop(),this.el.remove()}}const XC=`
|
|
1060
1060
|
@keyframes hs-highlight-glow {
|
|
1061
1061
|
0%, 100% { box-shadow: 0 0 8px var(--hs-accent-glow), inset 0 0 4px var(--hs-accent-glow); }
|
|
1062
1062
|
50% { box-shadow: 0 0 20px var(--hs-accent-glow), inset 0 0 8px var(--hs-accent-glow); }
|
|
1063
1063
|
}
|
|
1064
|
-
`;let af=!1;class YC{constructor(){this.highlights=[]}highlight(e,t=3e3){St(),this.injectPulseStyle();const i=document.createElement("div");i.className="hs-highlight-overlay",i.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(i.style,{position:"fixed",top:`${l.top-3}px`,left:`${l.left-3}px`,width:`${l.width+6}px`,height:`${l.height+6}px`,border:"2px solid var(--hs-accent)",borderRadius:"var(--hs-radius-sm)",animation:"hs-highlight-glow 1.5s ease-in-out infinite",pointerEvents:"none",zIndex:W.zOverlay,boxSizing:"border-box"})};r(),document.body.appendChild(i);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:i,timer:o,scrollHandler:n,anim:null};this.highlights.push(a)}clearAll(){this.highlights.forEach(e=>this.removeHighlight(e)),this.highlights=[]}removeHighlight(e){clearTimeout(e.timer),window.removeEventListener("scroll",e.scrollHandler),e.anim=EC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(af)return;af=!0;const e=document.createElement("style");e.textContent=XC,document.head.appendChild(e)}}const qC=800,KC=600*1e3,ZC=540*1e3,lf=60*1e3,JC=90*1e3,QC=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}}];class cf{constructor(e,t){this.stage=null,this.avatar=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.externalObserver=!1,this.actionExecutor=null,this.visionContext=null,this.staffDisplayName="Assistant",this.staffAvatarUrl=null,this.hasHadConversation=!1,this.avatarFrame=null,this.bubble=null,this.chatPill=null,this.overlayRenderer=null,this.controls=null,this.confirmationPrompt=null,this.highlightRenderer=null,this.stageBackdrop=null,this.stageEl=null,this.homePlaceholder=null,this.homeObserver=null,this.homeVisible=!0,this.homeEverSeen=!1,this.pillProtected=!1,this.paused=!1,this.config=e,this.widgetPrompts=t??null,this.visitorId=this.getOrCreateVisitorId()}get isInline(){return this.config.mode==="inline"&&!!this.config.container}get activeContainer(){return this.config.container}async init(){St(),this.stage=new ux,await this.stage.init(this.config.mode,this.config.container),this.avatar=new fx(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new OC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new NC(this.widgetPrompts??void 0),this.bubble.onClick=()=>this.onAvatarClick(),this.stage.rootElement&&(this.stage.rootElement.style.position="relative",this.stage.rootElement.appendChild(this.bubble.el)),this.avatar.setInteractive(()=>this.onAvatarClick()),this.isInline&&(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick(),setTimeout(()=>{var t;(this.state==="idle"||this.state==="teasing")&&!this.homeVisible&&((t=this.chatPill)==null?void 0:t.state)==="hidden"&&this.chatPill.showNamed()},5e3),this.startHomeObserver()),this.setupTrigger(),this.startVisionLoop(),window.addEventListener("beforeunload",()=>{var e;(this.state==="active"||this.state==="connecting")&&((e=this.logger)==null||e.flush())}),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{if(this.isInline&&this.stage.inlineTarget){const e=this.stage.inlineTarget;e.style.position="relative";const t=document.createElement("div");t.className="hs-inline-card",t.setAttribute("data-hs-theme","dark"),Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",borderRadius:"var(--hs-radius-lg)",overflow:"hidden",background:"var(--hs-glass-bg)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",boxShadow:"var(--hs-glass-shadow)",cursor:"pointer",padding:"var(--hs-space-3)",boxSizing:"border-box"});const i=document.createElement("div");Object.assign(i.style,{flex:"1",overflow:"hidden",position:"relative",borderRadius:"var(--hs-radius-md)",border:"1px solid var(--hs-glass-border)"});const r=document.createElement("video");r.src=this.idleVideoUrl,r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.setAttribute("playsinline",""),Object.assign(r.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),i.appendChild(r),t.appendChild(i);const n=document.createElement("div");Object.assign(n.style,{padding:"var(--hs-space-3) var(--hs-space-4)",textAlign:"center"});const o=document.createElement("div");Object.assign(o.style,{color:"var(--hs-text-primary)",fontSize:"var(--hs-text-base)",fontWeight:"var(--hs-weight-semibold)",fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)"}),o.textContent=`${this.staffDisplayName}, your AI copilot`,n.appendChild(o);const a=document.createElement("div");Object.assign(a.style,{color:"var(--hs-text-tertiary)",fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",marginTop:"2px"}),a.textContent="Powered by Holostaff",n.appendChild(a),t.appendChild(n),t.addEventListener("click",()=>this.onAvatarClick()),e.appendChild(t),this.stage.rootElement&&(this.stage.rootElement.style.display="none")}else{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e)}return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setObserver(e,t){this.rrwebRecorder=e,this.visionWs=t,this.externalObserver=!0}setStaffInfo(e,t){this.staffDisplayName=e,this.staffAvatarUrl=t}setupTrigger(){if(this.isInline){this.showAvatarOnly();return}if(this.config.visionWsUrl){this.showAvatarOnly();return}switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showAvatarOnly(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker))}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},qC))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r,n,o,a,l,c,h,u,f;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null,this.isInline){(r=this.chatPill)==null||r.showConnecting();const d=(o=(n=this.stage)==null?void 0:n.inlineTarget)==null?void 0:o.querySelector(".hs-inline-card video");d&&d.pause()}else{(a=this.stage)!=null&&a.rootElement&&(this.stage.rootElement.style.display="");const d=document.querySelector("#holostaff-widget-root video");d&&d.pause(),(l=this.bubble)==null||l.showStatic("Connecting...")}console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Bf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new uv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),(c=this.bubble)==null||c.hideStatic(),this.showControls(),this.startSessionTimers(),(h=this.visionWs)==null||h.sendConversationStarted(),(u=this.rrwebRecorder)==null||u.pause(),console.log("[HolostaffWidget] Conversation active")}catch(d){console.error("[HolostaffWidget] Failed to start conversation:",d),(f=this.bubble)==null||f.hideStatic(),this.endConversation()}}}moveToStage(){var t;if(!this.isInline||!((t=this.stage)!=null&&t.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display="none"),this.stage.inlineTarget.querySelectorAll("video").forEach(i=>{i instanceof HTMLVideoElement&&i.pause()}),this.homePlaceholder=document.createElement("div"),this.homePlaceholder.setAttribute("data-hs-theme","dark"),Object.assign(this.homePlaceholder.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"var(--hs-text-secondary)",fontSize:"var(--hs-text-sm)",fontFamily:"var(--hs-font)",textAlign:"center",padding:"var(--hs-space-4)",boxSizing:"border-box"}),this.homePlaceholder.innerHTML="Agent is active below ↓",this.stage.inlineTarget.appendChild(this.homePlaceholder),this.stageBackdrop=new jC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,i,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(i=this.homePlaceholder)==null||i.remove(),this.homePlaceholder=null,!((r=this.stage)!=null&&r.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display=""),this.stage.inlineTarget.querySelectorAll(".hs-inline-card video").forEach(n=>{n.style.display="",n instanceof HTMLVideoElement&&n.play()}),console.log("[HolostaffWidget] Returned to home (inline container)")}startHomeObserver(){var i;this.stopHomeObserver();const e=(i=this.stage)==null?void 0:i.inlineTarget;if(!e)return;const t=e.getBoundingClientRect();this.homeVisible=t.top<window.innerHeight&&t.bottom>0,this.homeObserver=new IntersectionObserver(([r])=>{const n=this.homeVisible;if(this.homeVisible=r.isIntersecting,this.homeVisible&&!this.homeEverSeen&&(this.homeEverSeen=!0),(this.state==="idle"||this.state==="teasing")&&this.chatPill)if(this.homeVisible){if(this.pillProtected){this.pillProtected=!1;return}this.chatPill.hide()}else!this.homeVisible&&n&&this.homeEverSeen?this.chatPill.showNamed():!this.homeVisible&&!this.homeEverSeen&&this.chatPill.state==="hidden"&&this.chatPill.showNamed()},{threshold:.1}),this.homeObserver.observe(e)}stopHomeObserver(){var e;(e=this.homeObserver)==null||e.disconnect(),this.homeObserver=null}async connectAnam(){this.sessionResponse&&(this.anamSession=new ev({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,i,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(i=this.chatPill)==null||i.hide(),this.isInline?(this.moveToStage(),(r=this.stageBackdrop)==null||r.appendContent(e)):this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){var o;if(!this.sessionResponse)return;const e=document.title||"",t=location.href,i=((o=document.querySelector('meta[name="description"]'))==null?void 0:o.getAttribute("content"))||"",r=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,10).map(a=>{var l;return(l=a.textContent)==null?void 0:l.trim()}).filter(Boolean).join(" | ");let n=(this.sessionResponse.staff.instructions??"")+`
|
|
1064
|
+
`;let af=!1;class YC{constructor(){this.highlights=[]}highlight(e,t=3e3){St(),this.injectPulseStyle();const i=document.createElement("div");i.className="hs-highlight-overlay",i.setAttribute("data-hs-theme","dark");const r=()=>{const l=e.getBoundingClientRect();Object.assign(i.style,{position:"fixed",top:`${l.top-3}px`,left:`${l.left-3}px`,width:`${l.width+6}px`,height:`${l.height+6}px`,border:"2px solid var(--hs-accent)",borderRadius:"var(--hs-radius-sm)",animation:"hs-highlight-glow 1.5s ease-in-out infinite",pointerEvents:"none",zIndex:W.zOverlay,boxSizing:"border-box"})};r(),document.body.appendChild(i);const n=()=>r();window.addEventListener("scroll",n,{passive:!0});const o=setTimeout(()=>this.removeHighlight(a),t),a={overlay:i,timer:o,scrollHandler:n,anim:null};this.highlights.push(a)}clearAll(){this.highlights.forEach(e=>this.removeHighlight(e)),this.highlights=[]}removeHighlight(e){clearTimeout(e.timer),window.removeEventListener("scroll",e.scrollHandler),e.anim=EC(e.overlay,1,0,"smooth",()=>{e.overlay.remove()});const t=this.highlights.indexOf(e);t>=0&&this.highlights.splice(t,1)}injectPulseStyle(){if(af)return;af=!0;const e=document.createElement("style");e.textContent=XC,document.head.appendChild(e)}}const qC=800,KC=600*1e3,ZC=540*1e3,lf=60*1e3,JC=90*1e3,QC=[{type:"function",name:"page_action",description:"Interact with the webpage the visitor is viewing. You can scroll to elements, highlight elements, click buttons/links, fill form fields, or read the page content. Describe what you want to do in natural language. Call this to understand the page, guide the visitor, or take actions on their behalf.",parameters:{type:"object",properties:{instruction:{type:"string",description:"What to do on the page, e.g. 'scroll to pricing section', 'highlight the sign-up button', 'fill the email field with test@example.com', 'read the page to understand what it contains'"}},required:["instruction"]}},{type:"function",name:"show_text_card",description:"Display a floating text card overlay near the avatar with additional information for the visitor. Use for key points, explanations, or summaries that benefit from visual display.",parameters:{type:"object",properties:{title:{type:"string",description:"Card title"},body:{type:"string",description:"Card body text"}},required:["title","body"]}},{type:"function",name:"show_image_card",description:"Display a floating image card overlay with an optional caption.",parameters:{type:"object",properties:{image_url:{type:"string",description:"URL of the image to display"},caption:{type:"string",description:"Optional caption below the image"}},required:["image_url"]}},{type:"function",name:"show_bullet_list",description:"Display a styled list of key points as a floating overlay card.",parameters:{type:"object",properties:{title:{type:"string",description:"List title"},items:{type:"array",items:{type:"string"},description:"List items"}},required:["title","items"]}},{type:"function",name:"dismiss_overlays",description:"Dismiss all currently visible overlay cards.",parameters:{type:"object",properties:{},required:[]}}];class cf{constructor(e,t){this.stage=null,this.avatar=null,this.state="idle",this.avatarState="idle",this.scrollHandler=null,this.idleVideoUrl=null,this.idleImageUrl=null,this.bubbleTimer=null,this.realtimeSession=null,this.audioForwarder=null,this.anamSession=null,this.sessionResponse=null,this.domAnalyzer=null,this.toolHandler=null,this.maxDurationTimer=null,this.maxDurationWarnTimer=null,this.inactivityTimer=null,this.inactivityCloseTimer=null,this.sessionStartTime=0,this.logger=null,this.rrwebRecorder=null,this.visionWs=null,this.externalObserver=!1,this.actionExecutor=null,this.visionContext=null,this.staffDisplayName="Assistant",this.staffAvatarUrl=null,this.hasHadConversation=!1,this.avatarFrame=null,this.bubble=null,this.chatPill=null,this.overlayRenderer=null,this.controls=null,this.confirmationPrompt=null,this.highlightRenderer=null,this.stageBackdrop=null,this.stageEl=null,this.homePlaceholder=null,this.homeObserver=null,this.homeVisible=!0,this.homeEverSeen=!1,this.pillProtected=!1,this.paused=!1,this.config=e,this.widgetPrompts=t??null,this.visitorId=this.getOrCreateVisitorId()}get isInline(){return this.config.mode==="inline"&&!!this.config.container}get activeContainer(){return this.config.container}async init(){St(),this.stage=new ux,await this.stage.init(this.config.mode,this.config.container),this.avatar=new fx(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new OC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new NC(this.widgetPrompts??void 0),this.bubble.onClick=()=>this.onAvatarClick(),this.stage.rootElement&&(this.stage.rootElement.style.position="relative",this.stage.rootElement.appendChild(this.bubble.el)),this.avatar.setInteractive(()=>this.onAvatarClick()),this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick(),this.isInline?(setTimeout(()=>{var t;(this.state==="idle"||this.state==="teasing")&&!this.homeVisible&&((t=this.chatPill)==null?void 0:t.state)==="hidden"&&this.chatPill.showNamed()},5e3),this.startHomeObserver()):this.homeVisible=!1,this.setupTrigger(),this.startVisionLoop(),window.addEventListener("beforeunload",()=>{var e;(this.state==="active"||this.state==="connecting")&&((e=this.logger)==null||e.flush())}),console.log("[HolostaffWidget] Initialized",{staffId:this.config.staffId,trigger:this.config.trigger,visionEnabled:!!this.config.visionWsUrl})}async loadIdleAsset(){if(!(!this.avatar||!this.stage)){if(this.idleVideoUrl)try{if(this.isInline&&this.stage.inlineTarget){const e=this.stage.inlineTarget;e.style.position="relative";const t=document.createElement("div");t.className="hs-inline-card",t.setAttribute("data-hs-theme","dark"),Object.assign(t.style,{position:"absolute",inset:"0",display:"flex",flexDirection:"column",borderRadius:"var(--hs-radius-lg)",overflow:"hidden",background:"var(--hs-glass-bg)",backdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",WebkitBackdropFilter:"blur(var(--hs-glass-blur)) saturate(var(--hs-glass-saturate))",border:"1px solid var(--hs-glass-border)",boxShadow:"var(--hs-glass-shadow)",cursor:"pointer",padding:"var(--hs-space-3)",boxSizing:"border-box"});const i=document.createElement("div");Object.assign(i.style,{flex:"1",overflow:"hidden",position:"relative",borderRadius:"var(--hs-radius-md)",border:"1px solid var(--hs-glass-border)"});const r=document.createElement("video");r.src=this.idleVideoUrl,r.autoplay=!0,r.loop=!0,r.muted=!0,r.playsInline=!0,r.setAttribute("playsinline",""),Object.assign(r.style,{width:"100%",height:"100%",objectFit:"cover",display:"block"}),i.appendChild(r),t.appendChild(i);const n=document.createElement("div");Object.assign(n.style,{padding:"var(--hs-space-3) var(--hs-space-4)",textAlign:"center"});const o=document.createElement("div");Object.assign(o.style,{color:"var(--hs-text-primary)",fontSize:"var(--hs-text-base)",fontWeight:"var(--hs-weight-semibold)",fontFamily:"var(--hs-font)",lineHeight:"var(--hs-line-height)"}),o.textContent=`${this.staffDisplayName}, your AI copilot`,n.appendChild(o);const a=document.createElement("div");Object.assign(a.style,{color:"var(--hs-text-tertiary)",fontSize:"var(--hs-text-xs)",fontFamily:"var(--hs-font)",marginTop:"2px"}),a.textContent="Powered by Holostaff",n.appendChild(a),t.appendChild(n),t.addEventListener("click",()=>this.onAvatarClick()),e.appendChild(t),this.stage.rootElement&&(this.stage.rootElement.style.display="none")}else{const e=this.stage.rootElement;if(!e)throw new Error("Widget root not available");await this.avatar.loadIdleVideo(this.idleVideoUrl,e)}return}catch{console.warn("[HolostaffWidget] Failed to load idle video, trying image fallback")}this.idleImageUrl?await this.avatar.loadIdleImage(this.idleImageUrl):console.warn("[HolostaffWidget] No idle video or image configured")}}setIdleVideo(e){this.idleVideoUrl=e}setIdleImage(e){this.idleImageUrl=e}setObserver(e,t){this.rrwebRecorder=e,this.visionWs=t,this.externalObserver=!0}setStaffInfo(e,t){this.staffDisplayName=e,this.staffAvatarUrl=t}setupTrigger(){if(this.isInline){this.showAvatarOnly();return}if(this.config.visionWsUrl){this.showAvatarOnly();return}switch(this.config.trigger){case"scroll":this.setupScrollTrigger();break;case"delay":setTimeout(()=>this.showTeaser(),this.config.delayMs);break;case"immediate":this.showTeaser();break}}setupScrollTrigger(){this.scrollHandler=()=>{const e=window.scrollY,t=document.documentElement.scrollHeight-window.innerHeight,i=t>0?e/t:0;i>=this.config.scrollThreshold&&this.state==="idle"?this.showTeaser():i<this.config.scrollThreshold*.5&&this.state==="teasing"&&this.hideTeaser()},window.addEventListener("scroll",this.scrollHandler,{passive:!0})}showAvatarOnly(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker))}showTeaser(){this.state!=="idle"||!this.avatar||!this.stage||(this.state="teasing",this.avatar.slideIn(this.stage.app.ticker),this.bubbleTimer=setTimeout(()=>{var e;return(e=this.bubble)==null?void 0:e.start()},qC))}hideTeaser(){var e;this.state!=="teasing"||!this.avatar||!this.stage||(this.state="idle",this.bubbleTimer&&(clearTimeout(this.bubbleTimer),this.bubbleTimer=null),(e=this.bubble)==null||e.stop(),this.avatar.slideOut(this.stage.app.ticker))}async onAvatarClick(){var e,t,i,r,n,o,a,l,c,h,u,f;if(!(this.state!=="teasing"&&this.state!=="idle")){if(this.state="connecting",(e=this.bubble)==null||e.stop(),(t=this.bubble)==null||t.hideStatic(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null,this.isInline){(r=this.chatPill)==null||r.showConnecting();const d=(o=(n=this.stage)==null?void 0:n.inlineTarget)==null?void 0:o.querySelector(".hs-inline-card video");d&&d.pause()}else{(a=this.stage)!=null&&a.rootElement&&(this.stage.rootElement.style.display="");const d=document.querySelector("#holostaff-widget-root video");d&&d.pause(),(l=this.bubble)==null||l.showStatic("Connecting...")}console.log("[HolostaffWidget] Starting conversation...");try{this.sessionResponse=await Bf(this.config.staffId,this.config.backendUrl),console.log("[HolostaffWidget] Session tokens received"),this.logger=new uv({staffId:this.config.staffId,staffName:this.sessionResponse.staff.name,backendUrl:this.config.backendUrl}),await this.connectAnam(),await this.connectRealtimeApi(),this.state="active",this.setAvatarState("listening"),this.sessionStartTime=Date.now(),(c=this.bubble)==null||c.hideStatic(),this.showControls(),this.startSessionTimers(),(h=this.visionWs)==null||h.sendConversationStarted(),(u=this.rrwebRecorder)==null||u.pause(),console.log("[HolostaffWidget] Conversation active")}catch(d){console.error("[HolostaffWidget] Failed to start conversation:",d),(f=this.bubble)==null||f.hideStatic(),this.endConversation()}}}moveToStage(){var t;if(!this.isInline||!((t=this.stage)!=null&&t.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display="none"),this.stage.inlineTarget.querySelectorAll("video").forEach(i=>{i instanceof HTMLVideoElement&&i.pause()}),this.homePlaceholder=document.createElement("div"),this.homePlaceholder.setAttribute("data-hs-theme","dark"),Object.assign(this.homePlaceholder.style,{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",color:"var(--hs-text-secondary)",fontSize:"var(--hs-text-sm)",fontFamily:"var(--hs-font)",textAlign:"center",padding:"var(--hs-space-4)",boxSizing:"border-box"}),this.homePlaceholder.innerHTML="Agent is active below ↓",this.stage.inlineTarget.appendChild(this.homePlaceholder),this.stageBackdrop=new jC,this.stageEl=this.stageBackdrop.el,this.stageBackdrop.show(),console.log("[HolostaffWidget] Moved to glass stage (bottom-center)")}returnToHome(){var t,i,r;if((t=this.stageBackdrop)==null||t.destroy(),this.stageBackdrop=null,this.stageEl=null,(i=this.homePlaceholder)==null||i.remove(),this.homePlaceholder=null,!((r=this.stage)!=null&&r.inlineTarget))return;const e=this.stage.inlineTarget.querySelector(".hs-inline-card");e&&(e.style.display=""),this.stage.inlineTarget.querySelectorAll(".hs-inline-card video").forEach(n=>{n.style.display="",n instanceof HTMLVideoElement&&n.play()}),console.log("[HolostaffWidget] Returned to home (inline container)")}startHomeObserver(){var i;this.stopHomeObserver();const e=(i=this.stage)==null?void 0:i.inlineTarget;if(!e)return;const t=e.getBoundingClientRect();this.homeVisible=t.top<window.innerHeight&&t.bottom>0,this.homeObserver=new IntersectionObserver(([r])=>{const n=this.homeVisible;if(this.homeVisible=r.isIntersecting,this.homeVisible&&!this.homeEverSeen&&(this.homeEverSeen=!0),(this.state==="idle"||this.state==="teasing")&&this.chatPill)if(this.homeVisible){if(this.pillProtected){this.pillProtected=!1;return}this.chatPill.hide()}else!this.homeVisible&&n&&this.homeEverSeen?this.chatPill.showNamed():!this.homeVisible&&!this.homeEverSeen&&this.chatPill.state==="hidden"&&this.chatPill.showNamed()},{threshold:.1}),this.homeObserver.observe(e)}stopHomeObserver(){var e;(e=this.homeObserver)==null||e.disconnect(),this.homeObserver=null}async connectAnam(){this.sessionResponse&&(this.anamSession=new ev({sessionToken:this.sessionResponse.anamSessionToken,inlineMode:this.isInline&&!!this.stageBackdrop}),this.anamSession.onConnected=()=>{console.log("[HolostaffWidget] Anam connected")},this.anamSession.onVideoReady=e=>{var t,i,r;console.log("[HolostaffWidget] Anam avatar video ready"),(t=this.bubble)==null||t.hideStatic(),(i=this.chatPill)==null||i.hide(),this.isInline?(this.moveToStage(),(r=this.stageBackdrop)==null||r.appendContent(e)):this.avatar&&this.stage&&this.avatar.setLiveVideo(e,this.stage.app.ticker)},this.anamSession.onTalkStreamInterrupted=()=>{console.log("[HolostaffWidget] Anam talk stream interrupted")},this.anamSession.onDisconnected=e=>{console.log("[HolostaffWidget] Anam disconnected:",e),this.endConversation()},this.anamSession.onError=e=>{console.error("[HolostaffWidget] Anam error:",e.message)},await this.anamSession.connect(),console.log("[HolostaffWidget] Anam session ready"))}async connectRealtimeApi(){var o;if(!this.sessionResponse)return;const e=document.title||"",t=location.href,i=((o=document.querySelector('meta[name="description"]'))==null?void 0:o.getAttribute("content"))||"",r=Array.from(document.querySelectorAll("h1, h2, h3")).slice(0,10).map(a=>{var l;return(l=a.textContent)==null?void 0:l.trim()}).filter(Boolean).join(" | ");let n=(this.sessionResponse.staff.instructions??"")+`
|
|
1065
1065
|
|
|
1066
1066
|
## Current Page
|
|
1067
1067
|
Title: ${e}
|