holostaff-widget 3.0.11 → 3.0.13
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-Bs-lFIBH.js → CanvasRenderer-C30ld-J9.js} +5 -5
- package/dist/{CanvasRenderer-Bs-lFIBH.js.map → CanvasRenderer-C30ld-J9.js.map} +1 -1
- package/dist/{Filter-u3cO1RLf.js → Filter-rHFmf-mF.js} +2 -2
- package/dist/{Filter-u3cO1RLf.js.map → Filter-rHFmf-mF.js.map} +1 -1
- package/dist/{GpuStencilModesToPixi-CvK8tsvK.js → GpuStencilModesToPixi-DkQwsHZu.js} +3 -3
- package/dist/{GpuStencilModesToPixi-CvK8tsvK.js.map → GpuStencilModesToPixi-DkQwsHZu.js.map} +1 -1
- package/dist/{RenderTargetSystem-D0UXSH3i.js → RenderTargetSystem-C3h95MeA.js} +3 -3
- package/dist/{RenderTargetSystem-D0UXSH3i.js.map → RenderTargetSystem-C3h95MeA.js.map} +1 -1
- package/dist/{WebGLRenderer-C4i0snFE.js → WebGLRenderer-DGYwXxXn.js} +5 -5
- package/dist/{WebGLRenderer-C4i0snFE.js.map → WebGLRenderer-DGYwXxXn.js.map} +1 -1
- package/dist/{WebGPURenderer-5XhUvJYL.js → WebGPURenderer-GJ4lXiuS.js} +6 -6
- package/dist/{WebGPURenderer-5XhUvJYL.js.map → WebGPURenderer-GJ4lXiuS.js.map} +1 -1
- package/dist/{browserAll-C8-HGWQr.js → browserAll-CFx0IGil.js} +3 -3
- package/dist/{browserAll-C8-HGWQr.js.map → browserAll-CFx0IGil.js.map} +1 -1
- package/dist/{getTextureBatchBindGroup-Drt1kYWV.js → getTextureBatchBindGroup-CZE-jmnF.js} +3 -3
- package/dist/{getTextureBatchBindGroup-Drt1kYWV.js.map → getTextureBatchBindGroup-CZE-jmnF.js.map} +1 -1
- package/dist/hs-widget.es.js +1 -1
- package/dist/hs-widget.umd.js +2 -2
- package/dist/hs-widget.umd.js.map +1 -1
- package/dist/{index-Bh9xbhFo.js → index-DCygieG8.js} +23 -13
- package/dist/{index-Bh9xbhFo.js.map → index-DCygieG8.js.map} +1 -1
- package/dist/{webworkerAll-D2tTDfqq.js → webworkerAll-DeyQs7Px.js} +3 -3
- package/dist/{webworkerAll-D2tTDfqq.js.map → webworkerAll-DeyQs7Px.js.map} +1 -1
- package/package.json +1 -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-rHFmf-mF.js";
|
|
2
|
+
import { T as a } from "./index-DCygieG8.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-CZE-jmnF.js.map
|
package/dist/{getTextureBatchBindGroup-Drt1kYWV.js.map → getTextureBatchBindGroup-CZE-jmnF.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTextureBatchBindGroup-
|
|
1
|
+
{"version":3,"file":"getTextureBatchBindGroup-CZE-jmnF.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
|
@@ -1061,7 +1061,7 @@ Continue the conversation naturally from this context.`,i=e.actionId;this.cleanu
|
|
|
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 qC{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=TC(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=YC,document.head.appendChild(e)}}const KC=800,ZC=600*1e3,JC=540*1e3,lf=60*1e3,QC=90*1e3,eS=[{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:[]}},{type:"function",name:"get_skill_instructions",description:'Retrieve the full playbook for one of your configured skills. Call this when you determine a skill is relevant to the current conversation — it returns detailed guidance on what to say, tone, and what to avoid. Use the skill name exactly as listed in the "Your Skills" section of your instructions.',parameters:{type:"object",properties:{skill_name:{type:"string",description:'The exact skill name as listed in Your Skills (e.g. "Convert Visitor", "Get Started").'}},required:["skill_name"]}},{type:"function",name:"end_conversation",description:"Gracefully end the current conversation. Call this after two failed attempts to steer an off-topic visitor back to the platform's purpose. Before calling, deliver your exit message naturally in speech — do not include it as a parameter. Set flag=true to mark this visitor as non-serious so they are not interrupted by the agent on future visits.",parameters:{type:"object",properties:{flag:{type:"boolean",description:"If true, flag this visitor as non-serious. The widget will be fully suppressed on their future visits."},reason:{type:"string",description:'Short reason for logging. E.g. "visitor not interested in platform".'}},required:["flag"]}}];class cf{constructor(e,t,i){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.pendingEndAfterResponse=null,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.evalMode=i??!1,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 dx,await this.stage.init(this.config.mode,this.config.container),this.avatar=new px(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new BC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new UC(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}updateEvalState(e){if(!this.evalMode)return;const t=window.__HS_EVAL_STATE__;t&&Object.assign(t,e)}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()},KC))}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 dv({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.updateEvalState({conversationStarted:!0}),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 XC,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 tv({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 qC{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=TC(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=YC,document.head.appendChild(e)}}const KC=800,ZC=600*1e3,JC=540*1e3,lf=60*1e3,QC=90*1e3,eS=[{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:[]}},{type:"function",name:"get_skill_instructions",description:'Retrieve the full playbook for one of your configured skills. Call this when you determine a skill is relevant to the current conversation — it returns detailed guidance on what to say, tone, and what to avoid. Use the skill name exactly as listed in the "Your Skills" section of your instructions.',parameters:{type:"object",properties:{skill_name:{type:"string",description:'The exact skill name as listed in Your Skills (e.g. "Convert Visitor", "Get Started").'}},required:["skill_name"]}},{type:"function",name:"end_conversation",description:"Gracefully end the current conversation. Call this after two failed attempts to steer an off-topic visitor back to the platform's purpose. Before calling, deliver your exit message naturally in speech — do not include it as a parameter. Set flag=true to mark this visitor as non-serious so they are not interrupted by the agent on future visits.",parameters:{type:"object",properties:{flag:{type:"boolean",description:"If true, flag this visitor as non-serious. The widget will be fully suppressed on their future visits."},reason:{type:"string",description:'Short reason for logging. E.g. "visitor not interested in platform".'}},required:["flag"]}}];class cf{constructor(e,t,i){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.pendingEndAfterResponse=null,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.evalMode=i??!1,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 dx,await this.stage.init(this.config.mode,this.config.container),this.avatar=new px(this.stage.stageWidth,this.stage.stageHeight),this.stage.app.stage.addChild(this.avatar.container),await this.loadIdleAsset(),this.avatarFrame=new BC,this.stage.rootElement&&$i(this.stage.rootElement),this.bubble=new UC(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}updateEvalState(e){if(!this.evalMode)return;const t=window.__HS_EVAL_STATE__;t&&Object.assign(t,e)}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()},KC))}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 dv({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.updateEvalState({conversationStarted:!0}),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),this.updateEvalState({conversationError:(d==null?void 0:d.message)??String(d),conversationErrorAt:new Date().toISOString()}),(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 XC,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 tv({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}
|
|
@@ -1076,5 +1076,5 @@ Then you can scroll to elements, highlight them, click links/buttons, or fill fo
|
|
|
1076
1076
|
All actions except form filling require the visitor to confirm before executing.`;this.visionContext&&(n+=`
|
|
1077
1077
|
|
|
1078
1078
|
## Context from observing the user's session
|
|
1079
|
-
`+this.visionContext,this.visionContext=null),this.realtimeSession=new yx({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:eS}),this.domAnalyzer=new ov,this.highlightRenderer=new qC,this.confirmationPrompt=new zC,this.realtimeSession.onConnected=()=>{var l,c,h,u;console.log("[HolostaffWidget] Realtime API connected");const a=(l=this.sessionResponse)==null?void 0:l.staff.openingText;a!=null&&a.trim()&&((c=this.realtimeSession)==null||c.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(h=this.realtimeSession)==null||h.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:a}]}}),(u=this.realtimeSession)==null||u.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async a=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new Cx,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new WC,this.toolHandler=new lv({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new cv(this.domAnalyzer,this.highlightRenderer),overlayActions:new hv(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl,skills:this.sessionResponse.skills??{}}),this.toolHandler.onToolCall=(a,l)=>{var c;(c=this.logger)==null||c.addAction(a,l)},this.toolHandler.onEndConversation=(a,l)=>{console.log(`[HolostaffWidget] end_conversation requested (flag=${a})`),this.pendingEndAfterResponse={flag:a,reason:l}},this.realtimeSession.onDataMessage=a=>{this.handleDataChannelMessage(a)},this.realtimeSession.onError=a=>{console.error("[HolostaffWidget] Realtime error:",a.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":if(console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.extractAiTranscript(e.response),this.pendingEndAfterResponse){const{flag:u,reason:f}=this.pendingEndAfterResponse;this.pendingEndAfterResponse=null,u&&Uf(this.config.staffId,this.visitorId,f,this.config.backendUrl),this.endConversation()}else this.resetInactivityTimer();break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){if(!(!(e!=null&&e.output)||!this.logger)){for(const t of e.output)if(t.type==="message"&&t.content)for(const i of t.content)i.transcript?this.logger.addStaffMessage(i.transcript):i.text&&this.logger.addStaffMessage(i.text)}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new HC,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},JC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},ZC),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},QC-lf))},lf)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,i,r,n,o,a,l,c,h,u,f,d,g;this.updateEvalState({conversationEnded:!0}),(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(i=this.controls)==null||i.hide(),this.controls=null,(r=this.audioForwarder)==null||r.stop(),this.audioForwarder=null,(n=this.anamSession)==null||n.close(),this.anamSession=null,(o=this.realtimeSession)==null||o.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.pendingEndAfterResponse=null,this.toolHandler=null,this.domAnalyzer=null,(a=this.highlightRenderer)==null||a.clearAll(),this.highlightRenderer=null,(l=this.confirmationPrompt)==null||l.dismiss(),this.confirmationPrompt=null,(c=this.overlayRenderer)==null||c.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker);const e=this.buildConversationSummary();(h=this.visionWs)==null||h.sendConversationEnded(e),(u=this.rrwebRecorder)==null||u.resume(),this.hasHadConversation=!0,this.state="idle",document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(_=>_.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(_=>_.remove()),this.isInline?(this.returnToHome(),this.pillProtected=!0,(f=this.chatPill)==null||f.restoreName(),(d=this.chatPill)==null||d.showNamed(),this.attachActionExecutor()):(this.avatar&&(this.avatar.container.visible=!1),(g=this.stage)!=null&&g.rootElement&&(this.stage.rootElement.style.display="none"),this.showChatPill()),console.log("[HolostaffWidget] Conversation ended")}showChatPill(){this.chatPill||(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick()),this.chatPill.showNamed()}hideChatPill(){var e;(e=this.chatPill)==null||e.hide()}startVisionLoop(){if(this.externalObserver&&this.visionWs){this.attachActionExecutor(),console.log("[HolostaffWidget] Action executor attached to external observer");return}const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new Ad,this.visionWs=new Id(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.attachActionExecutor(),this.visionWs.connect(),this.config.visionConsent==="required"?console.log("[HolostaffWidget] Vision loop started (recording deferred — consent required)"):(this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId})))}attachActionExecutor(){var e;this.visionWs&&(this.actionExecutor=new wC({wsClient:this.visionWs,getWidgetState:()=>this.state,getHomeVisible:()=>this.homeVisible,inlineTarget:((e=this.stage)==null?void 0:e.inlineTarget)??null,pill:this.chatPill,disableAutoDismiss:this.evalMode}),this.actionExecutor.onInterventionShown=(t,i)=>{this.updateEvalState({interventionFired:!0,skillId:t,openingMessage:i}),this.evalMode&&(window.__HS_EVAL_ACCEPT__=()=>{var r;(r=this.actionExecutor)==null||r.accept()})},this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()})}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null)}buildConversationSummary(){var e;return((e=this.logger)==null?void 0:e.getSummary())??"Conversation ended (no transcript available)."}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}pause(){var e,t,i;this.paused||(this.paused=!0,console.log("[HolostaffWidget] Presenter paused (page not targeted — observer continues)"),(this.state==="active"||this.state==="connecting")&&this.endConversation(),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display="none"),this.hideChatPill(),(t=this.bubble)==null||t.stop(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null)}resume(){var e;this.paused&&(this.paused=!1,console.log("[HolostaffWidget] Presenter resumed (page targeted)"),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display=""),this.attachActionExecutor(),(this.state==="idle"||this.state==="teasing")&&(this.state="idle",this.setupTrigger()))}updateContainer(e){var r,n;const t=e?"inline":"floating";(this.config.container!==e||this.config.mode!==t)&&(console.log("[HolostaffWidget] Updating container:",e??"(floating)"),this.config={...this.config,mode:t,container:e},this.stage&&((this.state==="active"||this.state==="connecting")&&this.endConversation(),(r=this.bubble)==null||r.destroy(),(n=this.avatar)==null||n.destroy(),this.stage.destroy(),this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.init()))}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.hideChatPill(),this.stopHomeObserver(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function tS(s){return!s||s.length===0?[{pattern:"*"}]:s.map(e=>typeof e=="string"?{pattern:e}:e)}function iS(s,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=s.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),i=s.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return i===r||i.startsWith(r+"/")}function hf(s,e){for(const t of e)if(iS(s,t.pattern))return t;return null}class sS{constructor(e){this.currentPath=location.pathname,this.onChange=e,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this.origPushState(...t),this.check()},history.replaceState=(...t)=>{this.origReplaceState(...t),this.check()},window.addEventListener("popstate",()=>this.check())}check(){const e=location.pathname;e!==this.currentPath&&(this.currentPath=e,this.onChange(e))}destroy(){history.pushState=this.origPushState,history.replaceState=this.origReplaceState}}function rS(){var i;const s="hs_visitor_id",e=(i=document.cookie.split("; ").find(r=>r.startsWith(`${s}=`)))==null?void 0:i.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${s}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function nS(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{let e=function(r,n,o,a,l){const c=new cf(r,o,n==null?void 0:n.evalMode);return a&&l&&c.setObserver(a,l),n!=null&&n.idleVideoUrl?c.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&c.setIdleImage(n.avatarImageUrl),n&&c.setStaffInfo(n.name,n.avatarImageUrl),c};const t=Rf(s);async function i(){let r=t,n=null,o=null,a=window.__HS_EVAL__;if(!a)try{const _=location.hash.match(/(?:^#|&)__hs_eval=([^&]+)/);if(_){a=JSON.parse(decodeURIComponent(_[1])),window.__HS_EVAL__=a;try{const y=location.hash.replace(/(?:^#|&)__hs_eval=[^&]+/,"").replace(/^&/,"#"),x=location.pathname+location.search+(y==="#"||y===""?"":y);history.replaceState(null,"",x)}catch{}console.log("[HolostaffWidget] Eval config read from URL hash",a)}}catch{}const l=(a==null?void 0:a.visitorId)??rS();try{if(o=await Nf(t.staffId,t.backendUrl,l),o.blocked){console.log("[HolostaffWidget] Visitor blocked — widget suppressed.");return}r=Of(t,s,o),n=o.widgetPrompts,o.evalMode&&(window.__HS_EVAL_STATE__={interventionFired:!1,skillId:null,openingMessage:null,conversationStarted:!1,conversationEnded:!1},console.log("[HolostaffWidget] Eval mode active — __HS_EVAL_STATE__ initialized"))}catch(_){if(_.name==="WidgetDisabledError"){console.log("[HolostaffWidget] Agent is not active — widget suppressed");return}console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",_)}const c=tS(o==null?void 0:o.pagePatterns);let h=null,u=null;r.visionWsUrl&&(h=new Ad,u=new Id(r.visionWsUrl,{staffId:r.staffId,visitorId:l,pageUrl:location.href,pageTitle:document.title,pagePatterns:c.map(_=>{const y={pattern:_.pattern};return _.container&&(y.container=_.container),y})}),h.onEvent=_=>{u==null||u.sendRRWebEvent(_)},u.connect(),r.visionConsent==="required"?console.log("[HolostaffWidget] Observer started (recording deferred — consent required)"):(h.start(),console.log("[HolostaffWidget] Observer started on all pages",{visitorId:l})));let f=hf(location.pathname,c),d=null;if(f){let _=r;f.container&&(_={...r,mode:"inline",container:f.container}),d=e(_,o,n,h,u),window.holostaffWidget=d,d.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const g=new sS(_=>{u==null||u.sendPageChanged(location.href,_,document.title);const y=hf(_,c);if(y&&!d){console.log("[HolostaffWidget] SPA navigated to matching page:",_);let x=r;y.container&&(x={...r,mode:"inline",container:y.container}),d=e(x,o,n,h,u),window.holostaffWidget=d,d.init()}else if(y&&d){const x=y.container??null;x!==d.activeContainer&&d.updateContainer(x),d.resume()}else!y&&d&&d.pause()});window.__holostaffSPARouter=g}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i()):i()}catch(e){console.error("[HolostaffWidget]",e)}}nS(),Q.add(eg),Q.mixin(Ve,tg),Q.add(sh),Q.add(rh),Q.mixin(Ve,ry),Q.add(lh),Q.add(oh);const oS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),aS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));fi.HolostaffWidget=cf,Object.defineProperty(fi,Symbol.toStringTag,{value:"Module"})}));
|
|
1079
|
+
`+this.visionContext,this.visionContext=null),this.realtimeSession=new yx({ephemeralKey:this.sessionResponse.realtimeEphemeralKey,webrtcUrl:this.sessionResponse.realtimeWebrtcUrl,voice:this.sessionResponse.staff.voiceId,instructions:n,tools:eS}),this.domAnalyzer=new ov,this.highlightRenderer=new qC,this.confirmationPrompt=new zC,this.realtimeSession.onConnected=()=>{var l,c,h,u;console.log("[HolostaffWidget] Realtime API connected");const a=(l=this.sessionResponse)==null?void 0:l.staff.openingText;a!=null&&a.trim()&&((c=this.realtimeSession)==null||c.sendJSON({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:"(conversation started — greet the visitor now)"}]}}),(h=this.realtimeSession)==null||h.sendJSON({type:"conversation.item.create",item:{type:"message",role:"assistant",content:[{type:"text",text:a}]}}),(u=this.realtimeSession)==null||u.sendJSON({type:"response.create"}))},this.realtimeSession.onDisconnected=()=>{console.log("[HolostaffWidget] Realtime API disconnected"),(this.state==="active"||this.state==="connecting")&&this.endConversation()},this.realtimeSession.onRemoteTrack=async a=>{console.log("[HolostaffWidget] Remote audio track → starting audio forwarder"),this.audioForwarder=new Cx,this.audioForwarder.onAudioChunk=l=>{var c;(c=this.anamSession)==null||c.sendAudioChunk(l)},await this.audioForwarder.start(a)},this.overlayRenderer=new WC,this.toolHandler=new lv({realtimeSession:this.realtimeSession,domAnalyzer:this.domAnalyzer,pageActions:new cv(this.domAnalyzer,this.highlightRenderer),overlayActions:new hv(this.overlayRenderer),confirmationPrompt:this.confirmationPrompt,staffId:this.config.staffId,backendUrl:this.config.backendUrl,skills:this.sessionResponse.skills??{}}),this.toolHandler.onToolCall=(a,l)=>{var c;(c=this.logger)==null||c.addAction(a,l)},this.toolHandler.onEndConversation=(a,l)=>{console.log(`[HolostaffWidget] end_conversation requested (flag=${a})`),this.pendingEndAfterResponse={flag:a,reason:l}},this.realtimeSession.onDataMessage=a=>{this.handleDataChannelMessage(a)},this.realtimeSession.onError=a=>{console.error("[HolostaffWidget] Realtime error:",a.message),this.endConversation()},await this.realtimeSession.connect()}handleDataChannelMessage(e){var i,r,n,o,a,l,c,h;if((i=this.toolHandler)!=null&&i.handleMessage(e))return;const t=e.type;switch(t){case"session.created":case"session.updated":console.log("[HolostaffWidget] Data:",t);break;case"input_audio_buffer.speech_started":console.log("[HolostaffWidget] User started speaking"),(r=this.anamSession)==null||r.interrupt(),(n=this.audioForwarder)==null||n.pause(),this.setAvatarState("listening"),this.resetInactivityTimer();break;case"input_audio_buffer.speech_stopped":console.log("[HolostaffWidget] User stopped speaking"),this.setAvatarState("thinking");break;case"response.created":console.log("[HolostaffWidget] AI response started"),(o=this.audioForwarder)==null||o.resume(),this.setAvatarState("speaking");break;case"response.done":if(console.log("[HolostaffWidget] AI response done"),(a=this.anamSession)==null||a.endSequence(),this.setAvatarState("listening"),this.extractAiTranscript(e.response),this.pendingEndAfterResponse){const{flag:u,reason:f}=this.pendingEndAfterResponse;this.pendingEndAfterResponse=null,u&&Uf(this.config.staffId,this.visitorId,f,this.config.backendUrl),this.endConversation()}else this.resetInactivityTimer();break;case"conversation.item.input_audio_transcription.completed":console.log("[HolostaffWidget] User said:",e.transcript),(l=this.logger)==null||l.addUserMessage(e.transcript??"");break;case"error":console.error("[HolostaffWidget] Realtime error event:",e.error);break;case"response.cancelled":case"response.canceled":case"response.failed":console.warn("[HolostaffWidget] Response ended:",t),(c=this.anamSession)==null||c.endSequence(),(h=this.audioForwarder)==null||h.pause(),this.setAvatarState("listening");break}}extractAiTranscript(e){var t;if(e!=null&&e.output){for(const i of e.output)if(i.type==="message"&&i.content)for(const r of i.content){const n=r.transcript??r.text;if(n&&((t=this.logger)==null||t.addStaffMessage(n),this.evalMode)){const o=window.__HS_EVAL_STATE__;o&&(Array.isArray(o.avatarTranscripts)||(o.avatarTranscripts=[]),o.avatarTranscripts.push(n))}}}}setAvatarState(e){if(this.avatarState===e)return;const t=this.avatarState;this.avatarState=e,console.log(`[HolostaffWidget] Avatar: ${t} → ${e}`)}showControls(){this.controls=new HC,this.controls.onMinimize=()=>{var e;this.state="minimized",this.avatar&&this.stage&&this.avatar.slideOut(this.stage.app.ticker),(e=this.overlayRenderer)==null||e.dismissAll(),console.log("[HolostaffWidget] Minimized")},this.controls.onRestore=()=>{this.state="active",this.avatar&&this.stage&&this.avatar.slideIn(this.stage.app.ticker),console.log("[HolostaffWidget] Restored")},this.controls.onClose=()=>{console.log("[HolostaffWidget] Close button clicked"),this.endConversation()},this.controls.show()}startSessionTimers(){this.maxDurationWarnTimer=setTimeout(()=>{var e,t;console.log("[HolostaffWidget] Session approaching max duration"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:"The session will end in about one minute. Please wrap up the conversation gracefully."}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"})},JC),this.maxDurationTimer=setTimeout(()=>{console.log("[HolostaffWidget] Max session duration reached"),this.endConversation()},ZC),this.resetInactivityTimer()}resetInactivityTimer(){this.inactivityTimer&&clearTimeout(this.inactivityTimer),this.inactivityCloseTimer&&clearTimeout(this.inactivityCloseTimer),this.inactivityTimer=setTimeout(()=>{var e,t;this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — prompting user"),(e=this.realtimeSession)==null||e.sendJSON({type:"conversation.item.create",item:{type:"message",role:"system",content:[{type:"input_text",text:'The visitor has been silent for a while. Ask them "Still there?" in a friendly way.'}]}}),(t=this.realtimeSession)==null||t.sendJSON({type:"response.create"}),this.inactivityCloseTimer=setTimeout(()=>{this.state==="active"&&(console.log("[HolostaffWidget] Inactivity — auto-closing"),this.endConversation())},QC-lf))},lf)}clearSessionTimers(){this.maxDurationTimer&&(clearTimeout(this.maxDurationTimer),this.maxDurationTimer=null),this.maxDurationWarnTimer&&(clearTimeout(this.maxDurationWarnTimer),this.maxDurationWarnTimer=null),this.inactivityTimer&&(clearTimeout(this.inactivityTimer),this.inactivityTimer=null),this.inactivityCloseTimer&&(clearTimeout(this.inactivityCloseTimer),this.inactivityCloseTimer=null)}endConversation(){var t,i,r,n,o,a,l,c,h,u,f,d,g;this.updateEvalState({conversationEnded:!0}),(t=this.logger)==null||t.flush(),this.logger=null,this.clearSessionTimers(),(i=this.controls)==null||i.hide(),this.controls=null,(r=this.audioForwarder)==null||r.stop(),this.audioForwarder=null,(n=this.anamSession)==null||n.close(),this.anamSession=null,(o=this.realtimeSession)==null||o.close(),this.realtimeSession=null,this.sessionResponse=null,this.avatarState="idle",this.pendingEndAfterResponse=null,this.toolHandler=null,this.domAnalyzer=null,(a=this.highlightRenderer)==null||a.clearAll(),this.highlightRenderer=null,(l=this.confirmationPrompt)==null||l.dismiss(),this.confirmationPrompt=null,(c=this.overlayRenderer)==null||c.dismissAll(),this.overlayRenderer=null,this.avatar&&this.stage&&this.avatar.clearLiveVideo(this.stage.app.ticker);const e=this.buildConversationSummary();(h=this.visionWs)==null||h.sendConversationEnded(e),(u=this.rrwebRecorder)==null||u.resume(),this.hasHadConversation=!0,this.state="idle",document.querySelectorAll('[id^="anam-avatar-wrapper"]').forEach(_=>_.remove()),document.querySelectorAll('video[id^="anam-avatar-video"]').forEach(_=>_.remove()),this.isInline?(this.returnToHome(),this.pillProtected=!0,(f=this.chatPill)==null||f.restoreName(),(d=this.chatPill)==null||d.showNamed(),this.attachActionExecutor()):(this.avatar&&(this.avatar.container.visible=!1),(g=this.stage)!=null&&g.rootElement&&(this.stage.rootElement.style.display="none"),this.showChatPill()),console.log("[HolostaffWidget] Conversation ended")}showChatPill(){this.chatPill||(this.chatPill=new of,this.chatPill.init(this.staffAvatarUrl,this.idleVideoUrl,this.staffDisplayName),this.chatPill.onClick=()=>this.onAvatarClick()),this.chatPill.showNamed()}hideChatPill(){var e;(e=this.chatPill)==null||e.hide()}startVisionLoop(){if(this.externalObserver&&this.visionWs){this.attachActionExecutor(),console.log("[HolostaffWidget] Action executor attached to external observer");return}const e=this.config.visionWsUrl;e&&(this.rrwebRecorder=new Ad,this.visionWs=new Id(e,{staffId:this.config.staffId,visitorId:this.visitorId,pageUrl:location.href,pageTitle:document.title}),this.rrwebRecorder.onEvent=t=>{var i;(i=this.visionWs)==null||i.sendRRWebEvent(t)},this.attachActionExecutor(),this.visionWs.connect(),this.config.visionConsent==="required"?console.log("[HolostaffWidget] Vision loop started (recording deferred — consent required)"):(this.rrwebRecorder.start(),console.log("[HolostaffWidget] Vision loop started",{visitorId:this.visitorId})))}attachActionExecutor(){var e;this.visionWs&&(this.actionExecutor=new wC({wsClient:this.visionWs,getWidgetState:()=>this.state,getHomeVisible:()=>this.homeVisible,inlineTarget:((e=this.stage)==null?void 0:e.inlineTarget)??null,pill:this.chatPill,disableAutoDismiss:this.evalMode}),this.actionExecutor.onInterventionShown=(t,i)=>{this.updateEvalState({interventionFired:!0,skillId:t,openingMessage:i}),this.evalMode&&(window.__HS_EVAL_ACCEPT__=()=>{var r;(r=this.actionExecutor)==null||r.accept()})},this.actionExecutor.onAccept=t=>{console.log("[HolostaffWidget] Suggestion accepted — starting conversation with vision context"),this.visionContext=t,this.onAvatarClick()})}stopVisionLoop(){var e,t,i;(e=this.actionExecutor)==null||e.destroy(),this.actionExecutor=null,this.externalObserver||((t=this.rrwebRecorder)==null||t.stop(),this.rrwebRecorder=null,(i=this.visionWs)==null||i.close(),this.visionWs=null)}buildConversationSummary(){var e;return((e=this.logger)==null?void 0:e.getSummary())??"Conversation ended (no transcript available)."}getOrCreateVisitorId(){var r;const e="hs_visitor_id",t=(r=document.cookie.split("; ").find(n=>n.startsWith(`${e}=`)))==null?void 0:r.split("=")[1];if(t)return t;const i=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${e}=${i}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,i}pause(){var e,t,i;this.paused||(this.paused=!0,console.log("[HolostaffWidget] Presenter paused (page not targeted — observer continues)"),(this.state==="active"||this.state==="connecting")&&this.endConversation(),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display="none"),this.hideChatPill(),(t=this.bubble)==null||t.stop(),(i=this.actionExecutor)==null||i.destroy(),this.actionExecutor=null)}resume(){var e;this.paused&&(this.paused=!1,console.log("[HolostaffWidget] Presenter resumed (page targeted)"),(e=this.stage)!=null&&e.rootElement&&(this.stage.rootElement.style.display=""),this.attachActionExecutor(),(this.state==="idle"||this.state==="teasing")&&(this.state="idle",this.setupTrigger()))}updateContainer(e){var r,n;const t=e?"inline":"floating";(this.config.container!==e||this.config.mode!==t)&&(console.log("[HolostaffWidget] Updating container:",e??"(floating)"),this.config={...this.config,mode:t,container:e},this.stage&&((this.state==="active"||this.state==="connecting")&&this.endConversation(),(r=this.bubble)==null||r.destroy(),(n=this.avatar)==null||n.destroy(),this.stage.destroy(),this.stage=null,this.avatar=null,this.bubble=null,this.state="idle",this.init()))}destroy(){var e,t,i;this.state="destroyed",this.endConversation(),this.hideChatPill(),this.stopHomeObserver(),this.stopVisionLoop(),this.scrollHandler&&window.removeEventListener("scroll",this.scrollHandler),this.bubbleTimer&&clearTimeout(this.bubbleTimer),(e=this.bubble)==null||e.destroy(),(t=this.avatar)==null||t.destroy(),(i=this.stage)==null||i.destroy(),this.bubble=null,this.avatar=null,this.stage=null}}function tS(s){return!s||s.length===0?[{pattern:"*"}]:s.map(e=>typeof e=="string"?{pattern:e}:e)}function iS(s,e){if(e==="*")return!0;if(!e.endsWith("/*")){const n=s.replace(/\/+$/,"")||"/",o=e.replace(/\/+$/,"")||"/";return n===o}const t=e.slice(0,-2),i=s.replace(/\/+$/,"")||"/",r=t.replace(/\/+$/,"")||"/";return i===r||i.startsWith(r+"/")}function hf(s,e){for(const t of e)if(iS(s,t.pattern))return t;return null}class sS{constructor(e){this.currentPath=location.pathname,this.onChange=e,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history),history.pushState=(...t)=>{this.origPushState(...t),this.check()},history.replaceState=(...t)=>{this.origReplaceState(...t),this.check()},window.addEventListener("popstate",()=>this.check())}check(){const e=location.pathname;e!==this.currentPath&&(this.currentPath=e,this.onChange(e))}destroy(){history.pushState=this.origPushState,history.replaceState=this.origReplaceState}}function rS(){var i;const s="hs_visitor_id",e=(i=document.cookie.split("; ").find(r=>r.startsWith(`${s}=`)))==null?void 0:i.split("=")[1];if(e)return e;const t=`v_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`;return document.cookie=`${s}=${t}; max-age=${365*24*60*60}; path=/; SameSite=Lax`,t}function nS(){const s=document.currentScript??document.querySelector("script[data-staff-id]");if(!s){console.error("[HolostaffWidget] Could not find script tag with data-staff-id");return}try{let e=function(r,n,o,a,l){const c=new cf(r,o,n==null?void 0:n.evalMode);return a&&l&&c.setObserver(a,l),n!=null&&n.idleVideoUrl?c.setIdleVideo(n.idleVideoUrl):n!=null&&n.avatarImageUrl&&c.setIdleImage(n.avatarImageUrl),n&&c.setStaffInfo(n.name,n.avatarImageUrl),c};const t=Rf(s);async function i(){let r=t,n=null,o=null,a=window.__HS_EVAL__;if(!a)try{const _=location.hash.match(/(?:^#|&)__hs_eval=([^&]+)/);if(_){a=JSON.parse(decodeURIComponent(_[1])),window.__HS_EVAL__=a;try{const y=location.hash.replace(/(?:^#|&)__hs_eval=[^&]+/,"").replace(/^&/,"#"),x=location.pathname+location.search+(y==="#"||y===""?"":y);history.replaceState(null,"",x)}catch{}console.log("[HolostaffWidget] Eval config read from URL hash",a)}}catch{}const l=(a==null?void 0:a.visitorId)??rS();try{if(o=await Nf(t.staffId,t.backendUrl,l),o.blocked){console.log("[HolostaffWidget] Visitor blocked — widget suppressed.");return}r=Of(t,s,o),n=o.widgetPrompts,o.evalMode&&(window.__HS_EVAL_STATE__={interventionFired:!1,skillId:null,openingMessage:null,conversationStarted:!1,conversationEnded:!1,avatarTranscripts:[]},console.log("[HolostaffWidget] Eval mode active — __HS_EVAL_STATE__ initialized"))}catch(_){if(_.name==="WidgetDisabledError"){console.log("[HolostaffWidget] Agent is not active — widget suppressed");return}console.warn("[HolostaffWidget] Failed to fetch server config, using embed defaults:",_)}const c=tS(o==null?void 0:o.pagePatterns);let h=null,u=null;r.visionWsUrl&&(h=new Ad,u=new Id(r.visionWsUrl,{staffId:r.staffId,visitorId:l,pageUrl:location.href,pageTitle:document.title,pagePatterns:c.map(_=>{const y={pattern:_.pattern};return _.container&&(y.container=_.container),y})}),h.onEvent=_=>{u==null||u.sendRRWebEvent(_)},u.connect(),r.visionConsent==="required"?console.log("[HolostaffWidget] Observer started (recording deferred — consent required)"):(h.start(),console.log("[HolostaffWidget] Observer started on all pages",{visitorId:l})));let f=hf(location.pathname,c),d=null;if(f){let _=r;f.container&&(_={...r,mode:"inline",container:f.container}),d=e(_,o,n,h,u),window.holostaffWidget=d,d.init()}else console.log("[HolostaffWidget] No matching page pattern for",location.pathname,"— presenter not loaded (observer active)");const g=new sS(_=>{u==null||u.sendPageChanged(location.href,_,document.title);const y=hf(_,c);if(y&&!d){console.log("[HolostaffWidget] SPA navigated to matching page:",_);let x=r;y.container&&(x={...r,mode:"inline",container:y.container}),d=e(x,o,n,h,u),window.holostaffWidget=d,d.init()}else if(y&&d){const x=y.container??null;x!==d.activeContainer&&d.updateContainer(x),d.resume()}else!y&&d&&d.pause()});window.__holostaffSPARouter=g}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>i()):i()}catch(e){console.error("[HolostaffWidget]",e)}}nS(),Q.add(eg),Q.mixin(Ve,tg),Q.add(sh),Q.add(rh),Q.mixin(Ve,ry),Q.add(lh),Q.add(oh);const oS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),aS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));fi.HolostaffWidget=cf,Object.defineProperty(fi,Symbol.toStringTag,{value:"Module"})}));
|
|
1080
1080
|
//# sourceMappingURL=hs-widget.umd.js.map
|