holostaff-widget 3.0.12 → 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.
Files changed (24) hide show
  1. package/dist/{CanvasRenderer-Cz4YJgbF.js → CanvasRenderer-C30ld-J9.js} +5 -5
  2. package/dist/{CanvasRenderer-Cz4YJgbF.js.map → CanvasRenderer-C30ld-J9.js.map} +1 -1
  3. package/dist/{Filter-r_wRj921.js → Filter-rHFmf-mF.js} +2 -2
  4. package/dist/{Filter-r_wRj921.js.map → Filter-rHFmf-mF.js.map} +1 -1
  5. package/dist/{GpuStencilModesToPixi-C4z4dtLL.js → GpuStencilModesToPixi-DkQwsHZu.js} +3 -3
  6. package/dist/{GpuStencilModesToPixi-C4z4dtLL.js.map → GpuStencilModesToPixi-DkQwsHZu.js.map} +1 -1
  7. package/dist/{RenderTargetSystem-DqFlSDxk.js → RenderTargetSystem-C3h95MeA.js} +3 -3
  8. package/dist/{RenderTargetSystem-DqFlSDxk.js.map → RenderTargetSystem-C3h95MeA.js.map} +1 -1
  9. package/dist/{WebGLRenderer-DeUC_ifJ.js → WebGLRenderer-DGYwXxXn.js} +5 -5
  10. package/dist/{WebGLRenderer-DeUC_ifJ.js.map → WebGLRenderer-DGYwXxXn.js.map} +1 -1
  11. package/dist/{WebGPURenderer-aCCkwhoj.js → WebGPURenderer-GJ4lXiuS.js} +6 -6
  12. package/dist/{WebGPURenderer-aCCkwhoj.js.map → WebGPURenderer-GJ4lXiuS.js.map} +1 -1
  13. package/dist/{browserAll-6XH0ST9E.js → browserAll-CFx0IGil.js} +3 -3
  14. package/dist/{browserAll-6XH0ST9E.js.map → browserAll-CFx0IGil.js.map} +1 -1
  15. package/dist/{getTextureBatchBindGroup-r8tDtgr9.js → getTextureBatchBindGroup-CZE-jmnF.js} +3 -3
  16. package/dist/{getTextureBatchBindGroup-r8tDtgr9.js.map → getTextureBatchBindGroup-CZE-jmnF.js.map} +1 -1
  17. package/dist/hs-widget.es.js +1 -1
  18. package/dist/hs-widget.umd.js +1 -1
  19. package/dist/hs-widget.umd.js.map +1 -1
  20. package/dist/{index-jYI_9I27.js → index-DCygieG8.js} +19 -12
  21. package/dist/{index-jYI_9I27.js.map → index-DCygieG8.js.map} +1 -1
  22. package/dist/{webworkerAll-Cb_C1p1P.js → webworkerAll-DeyQs7Px.js} +3 -3
  23. package/dist/{webworkerAll-Cb_C1p1P.js.map → webworkerAll-DeyQs7Px.js.map} +1 -1
  24. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
- import { B as p } from "./Filter-r_wRj921.js";
2
- import { T as a } from "./index-jYI_9I27.js";
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-r8tDtgr9.js.map
23
+ //# sourceMappingURL=getTextureBatchBindGroup-CZE-jmnF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"getTextureBatchBindGroup-r8tDtgr9.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]}
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]}
@@ -1,4 +1,4 @@
1
- import { a7 as f } from "./index-jYI_9I27.js";
1
+ import { a7 as f } from "./index-DCygieG8.js";
2
2
  export {
3
3
  f as HolostaffWidget
4
4
  };
@@ -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