@vanira/sdk 0.0.95 → 0.0.96

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.
@@ -22192,7 +22192,7 @@ class nm {
22192
22192
  }
22193
22193
  }
22194
22194
  let hn = "https://inboxapi.vanira.io";
22195
- const Qf = "https://coredb.travelr.club/v1/graphql";
22195
+ const Qf = "https://coredb.vanira.io/v1/graphql";
22196
22196
  class im {
22197
22197
  static setChatUrl(e) {
22198
22198
  hn = e;
@@ -22270,7 +22270,7 @@ class QT {
22270
22270
  }
22271
22271
  }
22272
22272
  let vA = "https://inboxapi.vanira.io";
22273
- const PT = "https://coredb.travelr.club/v1/graphql";
22273
+ const PT = "https://coredb.vanira.io/v1/graphql";
22274
22274
  class Bs {
22275
22275
  static setChatUrl(e) {
22276
22276
  vA = e;
@@ -49578,7 +49578,9 @@ class V5 {
49578
49578
  mode: e,
49579
49579
  presetId: a,
49580
49580
  title: String(t.clientFields.title ?? t.args.title ?? l),
49581
- description: String(t.clientFields.description ?? t.args.description ?? d),
49581
+ description: String(
49582
+ t.clientFields.description ?? t.args.description ?? t.clientFields.instructions ?? t.args.instructions ?? d
49583
+ ),
49582
49584
  reason: u,
49583
49585
  documentSide: c,
49584
49586
  toolCallId: t.toolCallId,
@@ -49619,7 +49621,7 @@ class V5 {
49619
49621
  presetId: s,
49620
49622
  title: String(e.clientFields.title ?? e.args.title ?? "Sign here"),
49621
49623
  description: String(
49622
- e.clientFields.description ?? e.args.description ?? "Draw your signature in the box below, then submit."
49624
+ e.clientFields.description ?? e.args.description ?? e.clientFields.instructions ?? e.args.instructions ?? "Draw your signature in the box below, then submit."
49623
49625
  ),
49624
49626
  reason: A,
49625
49627
  host: {
@@ -51849,7 +51851,7 @@ const fo = class fo extends DT {
51849
51851
  try {
51850
51852
  if (this.callActive = !0, this.micMuted = !1, this.syncMicMuteUi(), this.updateViewCallState(!0), this.updateViewStatus("connecting"), this.updateLauncherVisibility(), this.isPanelOpen && this.minimizePanel(), !this.pkKey)
51851
51853
  throw new Error("[VaniraAI Widget] pk-key is required for voice calls");
51852
- const o = ((s = this.config) == null ? void 0 : s.serverUrl) || ((a = this.config) == null ? void 0 : a.chatServerUrl), A = o && !o.includes("travelr.club") ? o : Eu, c = t === "continue" ? Id(this.agentId) : null, l = new gc({
51854
+ const A = ((s = this.config) == null ? void 0 : s.serverUrl) || ((a = this.config) == null ? void 0 : a.chatServerUrl) || Eu, c = t === "continue" ? Id(this.agentId) : null, l = new gc({
51853
51855
  agentId: this.agentId,
51854
51856
  apiKey: this.pkKey,
51855
51857
  sessionBehavior: t,
@@ -1,4 +1,4 @@
1
- var ZS=Object.defineProperty;var $S=(sr,hA,Ln)=>hA in sr?ZS(sr,hA,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):sr[hA]=Ln;var y=(sr,hA,Ln)=>$S(sr,typeof hA!="symbol"?hA+"":hA,Ln);(function(){"use strict";var sr=typeof document<"u"?document.currentScript:null;const hA="https://api.vanira.io";class Ln{static async fetchWidgetConfig(e,A){var n;const r={"Content-Type":"application/json"};A&&(r["X-API-Key"]=A);try{const i=await fetch(`${hA}/assistant/widget/${e}/config`,{method:"GET",headers:r});if(!i.ok)throw new Error(`Widget config fetch failed: HTTP ${i.status}`);const s=await i.json();return(n=s.agent)!=null&&n.client&&(s.client=s.agent.client),s}catch(i){throw i}}}let Hi="https://inboxapi.vanira.io";const _w="https://coredb.travelr.club/v1/graphql";class Lr{static setChatUrl(e){Hi=e}static async createChatProspect(e){var r,n;const A=`
1
+ var ZS=Object.defineProperty;var $S=(sr,hA,Ln)=>hA in sr?ZS(sr,hA,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):sr[hA]=Ln;var y=(sr,hA,Ln)=>$S(sr,typeof hA!="symbol"?hA+"":hA,Ln);(function(){"use strict";var sr=typeof document<"u"?document.currentScript:null;const hA="https://api.vanira.io";class Ln{static async fetchWidgetConfig(e,A){var n;const r={"Content-Type":"application/json"};A&&(r["X-API-Key"]=A);try{const i=await fetch(`${hA}/assistant/widget/${e}/config`,{method:"GET",headers:r});if(!i.ok)throw new Error(`Widget config fetch failed: HTTP ${i.status}`);const s=await i.json();return(n=s.agent)!=null&&n.client&&(s.client=s.agent.client),s}catch(i){throw i}}}let Hi="https://inboxapi.vanira.io";const _w="https://coredb.vanira.io/v1/graphql";class Lr{static setChatUrl(e){Hi=e}static async createChatProspect(e){var r,n;const A=`
2
2
  mutation CreateChatProspect($prospectGroupId: uuid!, $name: String!) {
3
3
  insert_prospects_one(object: {prospect_group_id: $prospectGroupId, name: $name, source: WEBSITE_WIDGET}) {
4
4
  id
@@ -3417,7 +3417,7 @@ l0,-`+(A+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
3417
3417
  <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
3418
3418
  Submit
3419
3419
  </button>
3420
- `,f.appendChild(C);const S=C.querySelector(".vnr-confirm-btn"),x=new Set,F=()=>{S.disabled=x.size===0},T=()=>{v.querySelectorAll(".vnr-mcq-option").forEach(k=>{const M=k.dataset.optionId;k.classList.toggle("vnr-mcq-sel",!!M&&x.has(M))}),F(),b.style.display="none"};a.forEach(k=>{const M=document.createElement("button");M.type="button",M.className="vnr-mcq-option",M.dataset.optionId=k.id;const H=document.createElement("span");H.className="vnr-mcq-option-id",H.textContent=`${k.id}.`;const D=document.createElement("span");D.className="vnr-mcq-option-label",D.textContent=k.label,M.appendChild(H),M.appendChild(D),M.addEventListener("click",()=>{o?x.has(k.id)?x.delete(k.id):x.add(k.id):(x.clear(),x.add(k.id)),T()}),v.appendChild(M)}),C.querySelector(".vnr-cancel-btn").addEventListener("click",()=>{this.dismiss(),i("User cancelled")}),S.addEventListener("click",()=>{if(x.size===0){b.textContent="Please select an answer.",b.style.display="block";return}S.disabled=!0,S.innerHTML='<div class="vnr-spinner"></div>';const k=qw(s,a,[...x],{allow_multiple:o,image_url:l,question_id:c});setTimeout(()=>{this.dismiss(),n(k)},200)})}renderKycCapture(e,A,r,n,i){const s=e==="document"?I.KycDocumentCapture:I.KycSelfieCapture;this.bindActiveModalPreset(A,s,r,n);const a=w=>{this.clearActiveModalPreset(),r({status:"success",preset_id:s,...w})},o=(w,v="cancelled")=>{this.clearActiveModalPreset(),n(w,{status:v})},l=String(A.args.document_side??A.clientFields.document_side??"front").toLowerCase()==="back"?"back":"front",c=e==="document"?l==="back"?"Scan back of ID":"Scan your ID":"Verify it's you",d=e==="document"?l==="back"?"Hold the back of your ID in the frame. We'll capture automatically when edges are clear.":"Hold your ID in the frame. On desktop, use your webcam; on mobile, we use the rear camera.":"Center your face in the oval. Blink or turn slightly when prompted — we'll capture automatically.",p=String(A.args.reason??A.clientFields.reason??(e==="document"?"kyc_document":"kyc_selfie")).trim();this.stopCaptureCamera();const g=this,f=_E({mode:e,presetId:s,title:String(A.clientFields.title??A.args.title??c),description:String(A.clientFields.description??A.args.description??d),reason:p,documentSide:l,toolCallId:A.toolCallId,host:{setCaptureActive:w=>{g.captureActive=w},setCaptureStream:w=>{g.captureStream=w},createOverlay:()=>g.createOverlay(),dismiss:()=>g.dismiss(),getBrowserPermissionHint:()=>g.getBrowserPermissionHint(),fillCameraPermissionPrompt:(w,v)=>g.fillCameraPermissionPrompt(w,v),notifyCameraPermissionDenied:(w,v)=>g.notifyCameraPermissionDenied(w,v)},client:i,onComplete:w=>{g.kycCaptureStop=null,a(w)},onCancel:w=>{g.kycCaptureStop=null,o(w)},isActive:()=>g.captureActive});this.kycCaptureStop=f.stop}renderKycSignatureCapture(e,A,r,n){const i=I.KycSignatureCapture;this.bindActiveModalPreset(e,i,A,r);const s=c=>{this.clearActiveModalPreset(),A({status:"success",preset_id:i,...c})},a=(c,d="cancelled")=>{this.clearActiveModalPreset(),r(c,{status:d})},o=String(e.args.reason??e.clientFields.reason??"kyc_signature").trim(),l=GE({presetId:i,title:String(e.clientFields.title??e.args.title??"Sign here"),description:String(e.clientFields.description??e.args.description??"Draw your signature in the box below, then submit."),reason:o,host:{createOverlay:()=>this.createOverlay(),dismiss:()=>this.dismiss()},client:n,onComplete:s,onCancel:c=>a(c)});this.kycCaptureStop=l.stop}renderCamera(e,A,r,n){this.bindActiveModalPreset(e,I.Camera,A,r);const i=te=>{this.clearActiveModalPreset(),A({status:"success",preset_id:I.Camera,...te})},s=(te,pe="cancelled")=>{this.clearActiveModalPreset(),r(te,{status:pe})},a=this,o=e.clientFields.title||"Take a Photo",l=e.clientFields.description||"Point your camera at the subject, then tap capture.";let c=om(e.clientFields.facing_mode||e.args.facing_mode,"environment");const d=cm(e.clientFields,e.args),p=e.clientFields.reason||"camera_capture",g=e.clientFields.liveness_check===!0||e.clientFields.liveness_check==="true"||e.args.liveness_check===!0||e.args.liveness_check==="true";let f=null,w=null;this.stopCaptureCamera(),this.captureActive=!0;const v=this.createOverlay(),b=document.createElement("div");b.className="vnr-modal",b.style.cssText="position:relative;max-width:480px;width:100%",b.innerHTML=`
3420
+ `,f.appendChild(C);const S=C.querySelector(".vnr-confirm-btn"),x=new Set,F=()=>{S.disabled=x.size===0},T=()=>{v.querySelectorAll(".vnr-mcq-option").forEach(k=>{const M=k.dataset.optionId;k.classList.toggle("vnr-mcq-sel",!!M&&x.has(M))}),F(),b.style.display="none"};a.forEach(k=>{const M=document.createElement("button");M.type="button",M.className="vnr-mcq-option",M.dataset.optionId=k.id;const H=document.createElement("span");H.className="vnr-mcq-option-id",H.textContent=`${k.id}.`;const D=document.createElement("span");D.className="vnr-mcq-option-label",D.textContent=k.label,M.appendChild(H),M.appendChild(D),M.addEventListener("click",()=>{o?x.has(k.id)?x.delete(k.id):x.add(k.id):(x.clear(),x.add(k.id)),T()}),v.appendChild(M)}),C.querySelector(".vnr-cancel-btn").addEventListener("click",()=>{this.dismiss(),i("User cancelled")}),S.addEventListener("click",()=>{if(x.size===0){b.textContent="Please select an answer.",b.style.display="block";return}S.disabled=!0,S.innerHTML='<div class="vnr-spinner"></div>';const k=qw(s,a,[...x],{allow_multiple:o,image_url:l,question_id:c});setTimeout(()=>{this.dismiss(),n(k)},200)})}renderKycCapture(e,A,r,n,i){const s=e==="document"?I.KycDocumentCapture:I.KycSelfieCapture;this.bindActiveModalPreset(A,s,r,n);const a=w=>{this.clearActiveModalPreset(),r({status:"success",preset_id:s,...w})},o=(w,v="cancelled")=>{this.clearActiveModalPreset(),n(w,{status:v})},l=String(A.args.document_side??A.clientFields.document_side??"front").toLowerCase()==="back"?"back":"front",c=e==="document"?l==="back"?"Scan back of ID":"Scan your ID":"Verify it's you",d=e==="document"?l==="back"?"Hold the back of your ID in the frame. We'll capture automatically when edges are clear.":"Hold your ID in the frame. On desktop, use your webcam; on mobile, we use the rear camera.":"Center your face in the oval. Blink or turn slightly when prompted — we'll capture automatically.",p=String(A.args.reason??A.clientFields.reason??(e==="document"?"kyc_document":"kyc_selfie")).trim();this.stopCaptureCamera();const g=this,f=_E({mode:e,presetId:s,title:String(A.clientFields.title??A.args.title??c),description:String(A.clientFields.description??A.args.description??A.clientFields.instructions??A.args.instructions??d),reason:p,documentSide:l,toolCallId:A.toolCallId,host:{setCaptureActive:w=>{g.captureActive=w},setCaptureStream:w=>{g.captureStream=w},createOverlay:()=>g.createOverlay(),dismiss:()=>g.dismiss(),getBrowserPermissionHint:()=>g.getBrowserPermissionHint(),fillCameraPermissionPrompt:(w,v)=>g.fillCameraPermissionPrompt(w,v),notifyCameraPermissionDenied:(w,v)=>g.notifyCameraPermissionDenied(w,v)},client:i,onComplete:w=>{g.kycCaptureStop=null,a(w)},onCancel:w=>{g.kycCaptureStop=null,o(w)},isActive:()=>g.captureActive});this.kycCaptureStop=f.stop}renderKycSignatureCapture(e,A,r,n){const i=I.KycSignatureCapture;this.bindActiveModalPreset(e,i,A,r);const s=c=>{this.clearActiveModalPreset(),A({status:"success",preset_id:i,...c})},a=(c,d="cancelled")=>{this.clearActiveModalPreset(),r(c,{status:d})},o=String(e.args.reason??e.clientFields.reason??"kyc_signature").trim(),l=GE({presetId:i,title:String(e.clientFields.title??e.args.title??"Sign here"),description:String(e.clientFields.description??e.args.description??e.clientFields.instructions??e.args.instructions??"Draw your signature in the box below, then submit."),reason:o,host:{createOverlay:()=>this.createOverlay(),dismiss:()=>this.dismiss()},client:n,onComplete:s,onCancel:c=>a(c)});this.kycCaptureStop=l.stop}renderCamera(e,A,r,n){this.bindActiveModalPreset(e,I.Camera,A,r);const i=te=>{this.clearActiveModalPreset(),A({status:"success",preset_id:I.Camera,...te})},s=(te,pe="cancelled")=>{this.clearActiveModalPreset(),r(te,{status:pe})},a=this,o=e.clientFields.title||"Take a Photo",l=e.clientFields.description||"Point your camera at the subject, then tap capture.";let c=om(e.clientFields.facing_mode||e.args.facing_mode,"environment");const d=cm(e.clientFields,e.args),p=e.clientFields.reason||"camera_capture",g=e.clientFields.liveness_check===!0||e.clientFields.liveness_check==="true"||e.args.liveness_check===!0||e.args.liveness_check==="true";let f=null,w=null;this.stopCaptureCamera(),this.captureActive=!0;const v=this.createOverlay(),b=document.createElement("div");b.className="vnr-modal",b.style.cssText="position:relative;max-width:480px;width:100%",b.innerHTML=`
3421
3421
  <button class="vnr-close-btn" aria-label="Close">
3422
3422
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
3423
3423
  </button>
@@ -3621,7 +3621,7 @@ ${D}`:D,q=X+R,V=this.activePresetGeneration,ne=p<=0,Ce=()=>{this.chalkboardConte
3621
3621
  object-fit: contain;
3622
3622
  display: block;
3623
3623
  }
3624
- `,document.head.appendChild(t)}function hQ(t,e,A){dQ();const r=document.createElement("figure");r.className="vnr-diagram-host-viewer vnr-diagram-host-viewer--minimal",r.setAttribute("aria-label",e.title);const n=document.createElement("div");n.className="vnr-diagram-host-viewer__body";const i=document.createElement("img");i.className="vnr-diagram-host-viewer__img",i.src=e.image_url,i.alt=e.title,i.referrerPolicy="no-referrer",n.appendChild(i),r.appendChild(n),t.innerHTML="",t.dataset.vnrDiagramHost="true",t.appendChild(r)}const uQ="vanira:diagram_search_result";function Im(t){if(!t||typeof t!="object")return null;const e=t;if(e.found!==!0)return null;const A=e.image;if(!A||typeof A!="object")return null;const r=A,n=String(r.image_url??"").trim();return n?{image_url:n,title:String(r.title??"Educational diagram").trim()||"Educational diagram",page_url:String(r.page_url??"").trim(),file_type:r.file_type!=null?String(r.file_type):void 0,width:typeof r.width=="number"?r.width:void 0,height:typeof r.height=="number"?r.height:void 0}:null}function pQ(t){return Im(t)!==null}function km(t){typeof window>"u"||window.dispatchEvent(new CustomEvent(uQ,{detail:t}))}function Po(t){return t.data??t}const gQ="http://127.0.0.1:8000/diagram-search";function fQ(){return typeof window<"u"?`${window.location.origin}/vanira-api/diagram-search`:gQ}function Mm(t){const A=Po(t).client_fields??t.client_fields,r=A&&typeof A=="object"?{...A}:{};if(typeof window>"u")return r;const n=window.__vaniraDiagramSearchClientFields;if(!n||typeof n!="object")return r;const i={...r};for(const o of["element_id","css_selector","route"]){const l=n[o];l!=null&&String(l).trim()&&(i[o]=l)}const s=String(i.element_id??"").trim(),a=String(i.css_selector??"").trim();return s?delete i.css_selector:a||delete i.css_selector,i}function mQ(t){const e=Po(t),A=e.arguments??e.args??t.arguments??t.args??{};if(typeof A=="string")try{return JSON.parse(A)}catch{return{}}return typeof A=="object"&&A!==null?A:{}}function Tm(t){return String(t??"").trim().toLowerCase()==="diagram_search"}function wQ(t){const e=Po(t);return String(e.tool_call_id??e.call_id??t.tool_call_id??"")}async function vQ(t,e){const A=Sm(Mm(t)),r=Im(e);if(!A||!r)return null;const{idOrSelector:n,route:i,target:s}=A;let a=!1;const o=async()=>{const l=await sd(s);l&&(hQ(l,r,e.query),a=!0)};if(i){if(!await cQ(i,s,()=>o(),{toolName:"diagram_search"})||!a)return null}else if(await o(),!a)return null;return{...e,render_target:n,rendered_in_dom:!0}}async function BQ(t,e){const A=Po(t),r=String(A.name??A.tool_name??t.name??"");if(!Tm(r))return!1;const n=wQ(t);if(!n)return!0;const i=mQ(t),s=String(i.query??"").trim();if(!s){const a={found:!1,error:"query is required"};return e.sendToolResult(n,a),!0}try{const a=await fetch(fQ(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:s})});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`diagram-search HTTP ${a.status}${l?`: ${l.slice(0,200)}`:""}`)}const o=await a.json();if(pQ(o)){const l=await vQ(t,o);if(l)return km(l),e.sendToolResult(n,l),!0;const c={...o,render_fallback:Sm(Mm(t))?"Host element not found — showing floating diagram viewer.":void 0};return km(c),e.sendToolResult(n,c),!0}e.sendToolResult(n,o)}catch(a){const o=a instanceof Error?a.message:String(a);typeof e.sendToolError=="function"?e.sendToolError(n,o):e.sendToolResult(n,{found:!1,error:o})}return!0}const Ti=class Ti extends Kw{constructor(A){super(A);y(this,"vaniraClient",null);y(this,"currentView",null);y(this,"presetRenderer",null);y(this,"boardAbortHandler",null);y(this,"clipRegionHandler",null);y(this,"isPanelOpen",!1);y(this,"callActive",!1);y(this,"callStatus","disconnected");y(this,"micMuted",!1);y(this,"eventSource",null);y(this,"pillAudioCtx",null);y(this,"pillAgentAnalyser",null);y(this,"pillAgentData",null);y(this,"pillActivityRaf",null);y(this,"pillLastTranscriptionAt",0);y(this,"pillActivityState","idle");y(this,"floatingButton",null);y(this,"floatingWelcomeChips",null);y(this,"voiceChatPill",null);y(this,"cleanCardLauncher",null);y(this,"humanPresenceLauncher",null);y(this,"panel",null);y(this,"welcomeChipsData",[]);y(this,"chatAdapter");y(this,"sessionManager",null);y(this,"sessionActive",!1);y(this,"widgetMode","voice_only");y(this,"agentId","");y(this,"prospectGroupId","");y(this,"chatServerUrl","");y(this,"prospectId","");y(this,"chatId",null);y(this,"conversationId",null);y(this,"widgetId","");y(this,"pkKey","");y(this,"chatInitialized",!1);y(this,"primaryColor","#000000");y(this,"secondaryColor","#111111");y(this,"gradient",null);y(this,"positionType","fixed");y(this,"position","bottom-right");y(this,"widgetIcon",null);y(this,"iconConfig",null);y(this,"chatWelcomeMessage",null);this.chatAdapter=new H3,this.processConfig(A)}initSessionManager(){const A=this.widgetId||this.agentId||"default";this.sessionManager=new Vl(A),this.sessionManager.on("tab_took_over",()=>{this.sessionActive=!1,this.showTabConflictBanner("taken_over")}),this.sessionManager.on("session_cleared",()=>{});const r=this.sessionManager.claimSession();return this.sessionActive=r,r}restoreSessionMessages(){var o,l,c;const A=(o=this.sessionManager)==null?void 0:o.getSession();if(!A)return;const r=(c=(l=this.currentView)==null?void 0:l.getChatWindow)==null?void 0:c.call(l);if(!r)return;const n=A.messages.filter(d=>d.content.trim()!==""),i=`vanira_calls_${this.widgetId||this.agentId}`,s=JSON.parse(localStorage.getItem(i)||"[]");if(n.length===0&&s.length===0)return;r.clearMessages();const a=[...n.map((d,p)=>({type:"msg",role:d.role,content:d.content,ts:d.timestamp??p})),...s.map(d=>({type:"call",durationMs:d.durationMs,startedAt:d.startedAt,ts:d.startedAt}))];a.sort((d,p)=>d.ts-p.ts),a.forEach(d=>{d.type==="msg"?r.addMessage(d.role,d.content,d.ts):r.addCallRecord(d.durationMs,d.startedAt)})}showTabConflictBanner(A){var r,n;this.root&&((r=this.root.querySelector(".vanira-tab-conflict-banner"))==null||r.remove(),A==="conflict"&&((n=this.sessionManager)==null||n.forceClaimSession(),this.sessionActive=!0,this.widgetMode.includes("chat")&&this.initializeChatSession(!1)))}playMessageSound(A){try{if(!Ti.audioContext){const a=window.AudioContext||window.webkitAudioContext;if(!a)return;Ti.audioContext=new a}const r=Ti.audioContext;r.state==="suspended"&&r.resume().catch(()=>{});const n=r.createOscillator(),i=r.createGain();n.connect(i),i.connect(r.destination);const s=r.currentTime;A==="send"?(n.type="sine",n.frequency.setValueAtTime(300,s),n.frequency.exponentialRampToValueAtTime(500,s+.05),i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.1,s+.01),i.gain.exponentialRampToValueAtTime(.001,s+.1),n.start(s),n.stop(s+.1)):(n.type="sine",n.frequency.setValueAtTime(500,s),n.frequency.exponentialRampToValueAtTime(800,s+.1),i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.15,s+.02),i.gain.exponentialRampToValueAtTime(.001,s+.2),n.start(s),n.stop(s+.2))}catch{}}handleWelcomePayload(A,r="assistant"){var s,a,o,l,c,d,p,g;if(!A||this.widgetMode==="voice_only")return;A.buttons&&Array.isArray(A.buttons)?this.welcomeChipsData=A.buttons:((s=A.widget)==null?void 0:s.type)==="button_list"&&((a=A.widget.data)!=null&&a.buttons)&&(this.welcomeChipsData=A.widget.data.buttons),this.updateWelcomeChipsVisibility();const n=(l=(o=this.currentView)==null?void 0:o.getChatWindow)==null?void 0:l.call(o);let i=A.text||A.response||A.content||A.message||"";if(!i&&!this.welcomeChipsData.length&&(i="Hey! how can I help you ?"),!i&&typeof A=="string"&&A.trim().startsWith("{"))try{const f=JSON.parse(A);i=f.text||f.response||f.content||f.message||"",((c=f.widget)==null?void 0:c.type)==="button_list"&&((d=f.widget.data)!=null&&d.buttons)&&(this.welcomeChipsData=f.widget.data.buttons)}catch{}if(n){if(!i&&this.welcomeChipsData.length===0)return;const f=(p=this.sessionManager)==null?void 0:p.getSession();(f==null?void 0:f.messages.some(v=>v.content===i&&v.role===r))||(i&&(n.addMessage(r,i),(g=this.sessionManager)==null||g.pushMessage(r,i)),this.welcomeChipsData.length>0&&n.addButtons(this.welcomeChipsData))}}async initializeChatSession(A=!1){var r,n,i,s,a;if(this.sessionActive&&!this.chatInitialized){this.chatInitialized=!0;try{Lr.setChatUrl(this.chatServerUrl);const o=(r=this.sessionManager)==null?void 0:r.getSession();if(!A&&(o!=null&&o.prospectId)){this.prospectId=o.prospectId,this.chatId=o.chatId,this.conversationId=o.conversationId||null,this.restoreSessionMessages(),this.chatId&&!this.eventSource&&(this.eventSource=Lr.listenForAdminReplies(this.chatId,this.prospectId,c=>{var d,p,g;(p=(d=this.currentView)==null?void 0:d.getChatWindow)==null||p.call(d).addMessage("assistant",c),(g=this.sessionManager)==null||g.pushMessage("assistant",c),this.playMessageSound("receive")}));return}this.prospectId||(this.prospectGroupId?this.prospectId=await Lr.createChatProspect(this.prospectGroupId):this.prospectId=`anon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`);const l=await Lr.fetchWelcomeMessage(this.agentId,this.prospectId,this.widgetId||void 0,this.pkKey||void 0);l&&(this.handleWelcomePayload(l),l.chatId&&!this.chatId&&(this.chatId=l.chatId,this.eventSource||(this.eventSource=Lr.listenForAdminReplies(this.chatId,this.prospectId,c=>{var d,p,g;(p=(d=this.currentView)==null?void 0:d.getChatWindow)==null||p.call(d).addMessage("assistant",c),(g=this.sessionManager)==null||g.pushMessage("assistant",c),this.playMessageSound("receive")}))),l.conversationId&&(this.conversationId=l.conversationId)),(n=this.sessionManager)==null||n.saveIds(this.prospectId,this.chatId,this.conversationId)}catch{const l="Hey! how can I help you ?";(s=(i=this.currentView)==null?void 0:i.getChatWindow)==null||s.call(i).addMessage("assistant",l),(a=this.sessionManager)==null||a.pushMessage("assistant",l)}}}async initialize(A,r){await super.initialize(A),this.processConfig(A),r&&(this.root=r),this.root&&this.ui_renderer(this.root)}processConfig(A){var r,n;if(this.widgetId=A.widgetId||A.widget_id||this.widgetId||"",this.agentId=A.agentId||A.agent_id||this.agentId||"",this.prospectGroupId=A.prospectGroupId||((r=A.client)==null?void 0:r.base_prospect_group_id)||this.prospectGroupId||"",this.widgetMode=A.widgetMode||A.mode||this.widgetMode||"voice_only",this.pkKey=A.pkKey||A.pk_key||A.publicKey||A.public_key||this.pkKey||"",this.primaryColor=A.primaryColor||A.primary_color||"#000000",this.secondaryColor=A.secondaryColor||A.secondary_color||"#111111",this.gradient=A.gradient||null,this.position=A.position||"bottom-right",this.positionType=A.positionType||"fixed",this.widgetIcon=A.widgetIcon||A.icon||null,this.iconConfig=A.iconConfig||A.icon_config||null,this.chatWelcomeMessage=A.chatWelcomeMessage||A.chat_welcome_message||((n=A.agent)==null?void 0:n.chat_welcome_message)||null,typeof this.chatWelcomeMessage=="string")try{this.chatWelcomeMessage=JSON.parse(this.chatWelcomeMessage)}catch{}this.chatServerUrl=A.serverUrl||A.chatServerUrl||"https://inboxapi.vanira.io",this.updateWelcomeChipsVisibility()}async create_call(A="continue"){var r,n,i,s;if(!(this.callActive||!this.agentId)){this.sessionActive||((r=this.sessionManager)==null||r.forceClaimSession(),this.sessionActive=!0),A==="new"&&((n=this.presetRenderer)==null||n.resetBoardSession());try{if(this.callActive=!0,this.micMuted=!1,this.syncMicMuteUi(),this.updateViewCallState(!0),this.updateViewStatus("connecting"),this.updateLauncherVisibility(),this.isPanelOpen&&this.minimizePanel(),!this.pkKey)throw new Error("[VaniraAI Widget] pk-key is required for voice calls");const a=((i=this.config)==null?void 0:i.serverUrl)||((s=this.config)==null?void 0:s.chatServerUrl),o=a&&!a.includes("travelr.club")?a:hA,l=A==="continue"?Js(this.agentId):null,c=new Hn({agentId:this.agentId,apiKey:this.pkKey,sessionBehavior:A,prospectId:this.prospectId||(l==null?void 0:l.prospectId)||void 0,callId:A==="continue"?l==null?void 0:l.callId:void 0,backendUrl:o});c.on("session_started",({prospectId:d,callId:p})=>{var g;d&&(this.prospectId=d,(g=this.sessionManager)==null||g.saveIds(d,this.chatId)),p&&iu(this.agentId,p,d)}),c.on("connected",()=>this.updateViewStatus("connected")).on("disconnected",()=>this.end_call()).on("error",d=>{this.updateViewStatus("error",d)}).on("transcription",({text:d,isFinal:p})=>{var g,f;d.trim()&&(this.pillLastTranscriptionAt=Date.now()),(f=(g=this.currentView)==null?void 0:g.setTranscription)==null||f.call(g,d,p)}).on("track",({track:d})=>{var p;d.kind==="audio"&&this.setupPillAgentAudio(d),this.widgetMode.includes("avatar")&&d.kind==="video"&&((p=this.currentView)!=null&&p.setVideoTrack)&&this.currentView.setVideoTrack(d)}).on("tool_call",d=>{var f,w,v;if((f=this.presetRenderer)==null?void 0:f.handle(d,b=>{const C=Ws(d.client_fields,d.arguments||d.args,d.name),S=d.tool_call_id;if($h(C)&&S){const x=typeof b=="object"&&b!==null?b:{response:b};if(x.status==="cancelled")return;if(C===I.WriteLatexText&&x.latex_render_ok===!1)try{c.triggerActionInterrupt(),c.sendActionTrigger("latex_format_error",x)}catch{}try{c.sendToolResult(S,x)}catch{}return}if(!(b&&(b.media_id||b.url)&&Nl(C))){if(Ol(C)&&C){const x=typeof b=="object"&&b!==null?b:{response:b};if(x.status==="cancelled")return;const F=Zh(C,d.name,d.client_fields);c.triggerActionInterrupt(),c.sendActionTrigger(F,x);return}if(C){const x=Zh(C,d.name,d.client_fields);c.triggerInterrupt(x,b)}}},(b,C)=>{var F,T,k;const S=Ws(d.client_fields,d.arguments||d.args,d.name),x=d.tool_call_id;if($h(S)&&x){const M=(C==null?void 0:C.status)??"cancelled",H=String(((F=d.client_fields)==null?void 0:F.target_url)||(d.arguments||d.args||{}).target_url||"");try{const D=S===I.Navigate?((T=this.presetRenderer)==null?void 0:T.getNavigateTerminalResult(M,b,H||void 0))??{status:M,reason:b||"Navigation cancelled",preset_id:S,target_url:H||void 0}:((k=this.presetRenderer)==null?void 0:k.getBoardTerminalResult(M,b,S))??{status:M,reason:b||"User dismissed",preset_id:S};c.sendToolResult(x,D)}catch{}return}if(Nl(S)&&x){try{c.sendToolResult(x,{status:"cancelled",reason:b||"User dismissed",preset_id:S})}catch{}return}if(Ol(S)&&x){try{c.sendToolResult(x,{status:"cancelled",reason:b||"User dismissed",preset_id:S})}catch{}return}try{c.sendToolResult(x,{status:"cancelled",reason:"User dismissed"})}catch{}},c))return;if(Tm(d.name)){BQ(d,c);return}const g=new CustomEvent("vaniraai:tool_call",{detail:d,bubbles:!0,composed:!0});(v=(w=this.root)==null?void 0:w.host)==null||v.dispatchEvent(g)}),this.vaniraClient=c,await c.start(),this.boardAbortHandler=d=>{var g;const p=d.detail||{};(g=this.presetRenderer)==null||g.abortBoardTools(p.reason||"Server interrupted",p.toolCallId,p.presetId)},window.addEventListener(vm,this.boardAbortHandler)}catch(a){this.updateViewStatus("error",(a==null?void 0:a.message)||String(a))}}}isCallActive(){var A;return this.callActive&&!!((A=this.vaniraClient)!=null&&A.isConnected)}updateContext(A){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.updateContext(A),!0}catch{return!1}}triggerInterrupt(A,r={}){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.triggerInterrupt(A,r),!0}catch{return!1}}sendToolResult(A,r){var n;if(!((n=this.vaniraClient)!=null&&n.isConnected)||!A)return!1;try{return this.vaniraClient.sendToolResult(A,r),!0}catch{return!1}}end_call(){var n,i;this.boardAbortHandler&&(window.removeEventListener(vm,this.boardAbortHandler),this.boardAbortHandler=null),this.clipRegionHandler&&(window.removeEventListener($s,this.clipRegionHandler),this.clipRegionHandler=null);const A=(n=this.root)==null?void 0:n.host;A==null||A.classList.remove("vanira-clip-suppressed"),this.callActive=!1,this.callStatus="disconnected",this.micMuted=!1,this.syncMicMuteUi(),this.stopPillActivityMonitor();const r=this.vaniraClient;this.vaniraClient=null,r&&r.stop(),(i=this.presetRenderer)==null||i.teardownSession(),this.updateViewCallState(!1),this.updateLauncherVisibility()}updateViewCallState(A){var r;(r=this.currentView)!=null&&r.setCallActive&&this.currentView.setCallActive(A)}toggleMicMute(){return this.vaniraClient?(this.micMuted=this.vaniraClient.toggleMicrophoneMuted(),this.syncMicMuteUi(),this.micMuted):this.micMuted}syncMicMuteUi(){var A,r,n;(A=this.voiceChatPill)==null||A.setMicMuted(this.micMuted),(n=(r=this.currentView)==null?void 0:r.setMicMuted)==null||n.call(r,this.micMuted)}wireMicMuteControls(){var r,n,i;const A=()=>this.toggleMicMute();(r=this.voiceChatPill)==null||r.bindMicMuteToggle(A),(i=(n=this.currentView)==null?void 0:n.bindMicMuteToggle)==null||i.call(n,A)}updateViewStatus(A,r){var n,i,s,a,o;A==="connecting"?this.callStatus="connecting":A==="connected"?this.callStatus="connected":A==="error"?this.callStatus="error":this.callStatus="disconnected",(n=this.currentView)!=null&&n.setStatus&&this.currentView.setStatus(A,r),this.voiceChatPill&&this.callActive&&!this.isPanelOpen?A==="connected"?(this.pillActivityState="listening",this.voiceChatPill.setActivity("listening"),(s=(i=this.currentView)==null?void 0:i.setActivity)==null||s.call(i,"listening"),this.startPillActivityLoop()):this.voiceChatPill.setStatus(this.callStatus):A==="connected"&&(this.pillActivityState="listening",(o=(a=this.currentView)==null?void 0:a.setActivity)==null||o.call(a,"listening"),this.startPillActivityLoop())}setupPillAgentAudio(A){try{this.pillAudioCtx||(this.pillAudioCtx=new AudioContext),this.pillAudioCtx.state==="suspended"&&this.pillAudioCtx.resume();const r=new MediaStream([A]),n=this.pillAudioCtx.createMediaStreamSource(r);this.pillAgentAnalyser=this.pillAudioCtx.createAnalyser(),this.pillAgentAnalyser.fftSize=256,n.connect(this.pillAgentAnalyser),this.pillAgentData=new Uint8Array(this.pillAgentAnalyser.frequencyBinCount),this.startPillActivityLoop()}catch{}}readPillAgentLevel(){if(!this.pillAgentAnalyser||!this.pillAgentData)return 0;this.pillAgentAnalyser.getByteFrequencyData(this.pillAgentData);let A=0;const r=Math.min(48,this.pillAgentData.length);for(let n=0;n<r;n++)A+=this.pillAgentData[n];return r>0?A/r/255:0}startPillActivityLoop(){if(this.pillActivityRaf!==null)return;const A=()=>{var a,o;if(this.pillActivityRaf=requestAnimationFrame(A),!this.callActive||this.callStatus!=="connected")return;const r=this.readPillAgentLevel(),n=Date.now()-this.pillLastTranscriptionAt<1200,s=r>.06||n?"speaking":"listening";s!==this.pillActivityState&&(this.pillActivityState=s,this.voiceChatPill&&!this.isPanelOpen&&this.voiceChatPill.setActivity(s),(o=(a=this.currentView)==null?void 0:a.setActivity)==null||o.call(a,s))};this.pillActivityRaf=requestAnimationFrame(A)}stopPillActivityMonitor(){this.pillActivityRaf!==null&&(cancelAnimationFrame(this.pillActivityRaf),this.pillActivityRaf=null),this.pillAgentAnalyser=null,this.pillAgentData=null,this.pillLastTranscriptionAt=0,this.pillActivityState="idle",this.pillAudioCtx&&(this.pillAudioCtx.close().catch(()=>{}),this.pillAudioCtx=null)}ui_renderer(A){var l,c,d,p,g;this.root=A,this.root.innerHTML="",this.presetRenderer=new iQ(A),this.root.host&&(this.positionType==="fixed"?this.root.host.classList.add("vanira-portal"):this.root.host.classList.remove("vanira-portal")),this.clipRegionHandler&&window.removeEventListener($s,this.clipRegionHandler),this.clipRegionHandler=f=>{var b,C;const w=!!((b=f.detail)!=null&&b.active),v=(C=this.root)==null?void 0:C.host;v&&v.classList.toggle("vanira-clip-suppressed",w)},window.addEventListener($s,this.clipRegionHandler);const r=document.createElement("style");r.textContent=`@keyframes vanira-slide-up {
3624
+ `,document.head.appendChild(t)}function hQ(t,e,A){dQ();const r=document.createElement("figure");r.className="vnr-diagram-host-viewer vnr-diagram-host-viewer--minimal",r.setAttribute("aria-label",e.title);const n=document.createElement("div");n.className="vnr-diagram-host-viewer__body";const i=document.createElement("img");i.className="vnr-diagram-host-viewer__img",i.src=e.image_url,i.alt=e.title,i.referrerPolicy="no-referrer",n.appendChild(i),r.appendChild(n),t.innerHTML="",t.dataset.vnrDiagramHost="true",t.appendChild(r)}const uQ="vanira:diagram_search_result";function Im(t){if(!t||typeof t!="object")return null;const e=t;if(e.found!==!0)return null;const A=e.image;if(!A||typeof A!="object")return null;const r=A,n=String(r.image_url??"").trim();return n?{image_url:n,title:String(r.title??"Educational diagram").trim()||"Educational diagram",page_url:String(r.page_url??"").trim(),file_type:r.file_type!=null?String(r.file_type):void 0,width:typeof r.width=="number"?r.width:void 0,height:typeof r.height=="number"?r.height:void 0}:null}function pQ(t){return Im(t)!==null}function km(t){typeof window>"u"||window.dispatchEvent(new CustomEvent(uQ,{detail:t}))}function Po(t){return t.data??t}const gQ="http://127.0.0.1:8000/diagram-search";function fQ(){return typeof window<"u"?`${window.location.origin}/vanira-api/diagram-search`:gQ}function Mm(t){const A=Po(t).client_fields??t.client_fields,r=A&&typeof A=="object"?{...A}:{};if(typeof window>"u")return r;const n=window.__vaniraDiagramSearchClientFields;if(!n||typeof n!="object")return r;const i={...r};for(const o of["element_id","css_selector","route"]){const l=n[o];l!=null&&String(l).trim()&&(i[o]=l)}const s=String(i.element_id??"").trim(),a=String(i.css_selector??"").trim();return s?delete i.css_selector:a||delete i.css_selector,i}function mQ(t){const e=Po(t),A=e.arguments??e.args??t.arguments??t.args??{};if(typeof A=="string")try{return JSON.parse(A)}catch{return{}}return typeof A=="object"&&A!==null?A:{}}function Tm(t){return String(t??"").trim().toLowerCase()==="diagram_search"}function wQ(t){const e=Po(t);return String(e.tool_call_id??e.call_id??t.tool_call_id??"")}async function vQ(t,e){const A=Sm(Mm(t)),r=Im(e);if(!A||!r)return null;const{idOrSelector:n,route:i,target:s}=A;let a=!1;const o=async()=>{const l=await sd(s);l&&(hQ(l,r,e.query),a=!0)};if(i){if(!await cQ(i,s,()=>o(),{toolName:"diagram_search"})||!a)return null}else if(await o(),!a)return null;return{...e,render_target:n,rendered_in_dom:!0}}async function BQ(t,e){const A=Po(t),r=String(A.name??A.tool_name??t.name??"");if(!Tm(r))return!1;const n=wQ(t);if(!n)return!0;const i=mQ(t),s=String(i.query??"").trim();if(!s){const a={found:!1,error:"query is required"};return e.sendToolResult(n,a),!0}try{const a=await fetch(fQ(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:s})});if(!a.ok){const l=await a.text().catch(()=>"");throw new Error(`diagram-search HTTP ${a.status}${l?`: ${l.slice(0,200)}`:""}`)}const o=await a.json();if(pQ(o)){const l=await vQ(t,o);if(l)return km(l),e.sendToolResult(n,l),!0;const c={...o,render_fallback:Sm(Mm(t))?"Host element not found — showing floating diagram viewer.":void 0};return km(c),e.sendToolResult(n,c),!0}e.sendToolResult(n,o)}catch(a){const o=a instanceof Error?a.message:String(a);typeof e.sendToolError=="function"?e.sendToolError(n,o):e.sendToolResult(n,{found:!1,error:o})}return!0}const Ti=class Ti extends Kw{constructor(A){super(A);y(this,"vaniraClient",null);y(this,"currentView",null);y(this,"presetRenderer",null);y(this,"boardAbortHandler",null);y(this,"clipRegionHandler",null);y(this,"isPanelOpen",!1);y(this,"callActive",!1);y(this,"callStatus","disconnected");y(this,"micMuted",!1);y(this,"eventSource",null);y(this,"pillAudioCtx",null);y(this,"pillAgentAnalyser",null);y(this,"pillAgentData",null);y(this,"pillActivityRaf",null);y(this,"pillLastTranscriptionAt",0);y(this,"pillActivityState","idle");y(this,"floatingButton",null);y(this,"floatingWelcomeChips",null);y(this,"voiceChatPill",null);y(this,"cleanCardLauncher",null);y(this,"humanPresenceLauncher",null);y(this,"panel",null);y(this,"welcomeChipsData",[]);y(this,"chatAdapter");y(this,"sessionManager",null);y(this,"sessionActive",!1);y(this,"widgetMode","voice_only");y(this,"agentId","");y(this,"prospectGroupId","");y(this,"chatServerUrl","");y(this,"prospectId","");y(this,"chatId",null);y(this,"conversationId",null);y(this,"widgetId","");y(this,"pkKey","");y(this,"chatInitialized",!1);y(this,"primaryColor","#000000");y(this,"secondaryColor","#111111");y(this,"gradient",null);y(this,"positionType","fixed");y(this,"position","bottom-right");y(this,"widgetIcon",null);y(this,"iconConfig",null);y(this,"chatWelcomeMessage",null);this.chatAdapter=new H3,this.processConfig(A)}initSessionManager(){const A=this.widgetId||this.agentId||"default";this.sessionManager=new Vl(A),this.sessionManager.on("tab_took_over",()=>{this.sessionActive=!1,this.showTabConflictBanner("taken_over")}),this.sessionManager.on("session_cleared",()=>{});const r=this.sessionManager.claimSession();return this.sessionActive=r,r}restoreSessionMessages(){var o,l,c;const A=(o=this.sessionManager)==null?void 0:o.getSession();if(!A)return;const r=(c=(l=this.currentView)==null?void 0:l.getChatWindow)==null?void 0:c.call(l);if(!r)return;const n=A.messages.filter(d=>d.content.trim()!==""),i=`vanira_calls_${this.widgetId||this.agentId}`,s=JSON.parse(localStorage.getItem(i)||"[]");if(n.length===0&&s.length===0)return;r.clearMessages();const a=[...n.map((d,p)=>({type:"msg",role:d.role,content:d.content,ts:d.timestamp??p})),...s.map(d=>({type:"call",durationMs:d.durationMs,startedAt:d.startedAt,ts:d.startedAt}))];a.sort((d,p)=>d.ts-p.ts),a.forEach(d=>{d.type==="msg"?r.addMessage(d.role,d.content,d.ts):r.addCallRecord(d.durationMs,d.startedAt)})}showTabConflictBanner(A){var r,n;this.root&&((r=this.root.querySelector(".vanira-tab-conflict-banner"))==null||r.remove(),A==="conflict"&&((n=this.sessionManager)==null||n.forceClaimSession(),this.sessionActive=!0,this.widgetMode.includes("chat")&&this.initializeChatSession(!1)))}playMessageSound(A){try{if(!Ti.audioContext){const a=window.AudioContext||window.webkitAudioContext;if(!a)return;Ti.audioContext=new a}const r=Ti.audioContext;r.state==="suspended"&&r.resume().catch(()=>{});const n=r.createOscillator(),i=r.createGain();n.connect(i),i.connect(r.destination);const s=r.currentTime;A==="send"?(n.type="sine",n.frequency.setValueAtTime(300,s),n.frequency.exponentialRampToValueAtTime(500,s+.05),i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.1,s+.01),i.gain.exponentialRampToValueAtTime(.001,s+.1),n.start(s),n.stop(s+.1)):(n.type="sine",n.frequency.setValueAtTime(500,s),n.frequency.exponentialRampToValueAtTime(800,s+.1),i.gain.setValueAtTime(0,s),i.gain.linearRampToValueAtTime(.15,s+.02),i.gain.exponentialRampToValueAtTime(.001,s+.2),n.start(s),n.stop(s+.2))}catch{}}handleWelcomePayload(A,r="assistant"){var s,a,o,l,c,d,p,g;if(!A||this.widgetMode==="voice_only")return;A.buttons&&Array.isArray(A.buttons)?this.welcomeChipsData=A.buttons:((s=A.widget)==null?void 0:s.type)==="button_list"&&((a=A.widget.data)!=null&&a.buttons)&&(this.welcomeChipsData=A.widget.data.buttons),this.updateWelcomeChipsVisibility();const n=(l=(o=this.currentView)==null?void 0:o.getChatWindow)==null?void 0:l.call(o);let i=A.text||A.response||A.content||A.message||"";if(!i&&!this.welcomeChipsData.length&&(i="Hey! how can I help you ?"),!i&&typeof A=="string"&&A.trim().startsWith("{"))try{const f=JSON.parse(A);i=f.text||f.response||f.content||f.message||"",((c=f.widget)==null?void 0:c.type)==="button_list"&&((d=f.widget.data)!=null&&d.buttons)&&(this.welcomeChipsData=f.widget.data.buttons)}catch{}if(n){if(!i&&this.welcomeChipsData.length===0)return;const f=(p=this.sessionManager)==null?void 0:p.getSession();(f==null?void 0:f.messages.some(v=>v.content===i&&v.role===r))||(i&&(n.addMessage(r,i),(g=this.sessionManager)==null||g.pushMessage(r,i)),this.welcomeChipsData.length>0&&n.addButtons(this.welcomeChipsData))}}async initializeChatSession(A=!1){var r,n,i,s,a;if(this.sessionActive&&!this.chatInitialized){this.chatInitialized=!0;try{Lr.setChatUrl(this.chatServerUrl);const o=(r=this.sessionManager)==null?void 0:r.getSession();if(!A&&(o!=null&&o.prospectId)){this.prospectId=o.prospectId,this.chatId=o.chatId,this.conversationId=o.conversationId||null,this.restoreSessionMessages(),this.chatId&&!this.eventSource&&(this.eventSource=Lr.listenForAdminReplies(this.chatId,this.prospectId,c=>{var d,p,g;(p=(d=this.currentView)==null?void 0:d.getChatWindow)==null||p.call(d).addMessage("assistant",c),(g=this.sessionManager)==null||g.pushMessage("assistant",c),this.playMessageSound("receive")}));return}this.prospectId||(this.prospectGroupId?this.prospectId=await Lr.createChatProspect(this.prospectGroupId):this.prospectId=`anon_${Date.now()}_${Math.random().toString(36).substr(2,9)}`);const l=await Lr.fetchWelcomeMessage(this.agentId,this.prospectId,this.widgetId||void 0,this.pkKey||void 0);l&&(this.handleWelcomePayload(l),l.chatId&&!this.chatId&&(this.chatId=l.chatId,this.eventSource||(this.eventSource=Lr.listenForAdminReplies(this.chatId,this.prospectId,c=>{var d,p,g;(p=(d=this.currentView)==null?void 0:d.getChatWindow)==null||p.call(d).addMessage("assistant",c),(g=this.sessionManager)==null||g.pushMessage("assistant",c),this.playMessageSound("receive")}))),l.conversationId&&(this.conversationId=l.conversationId)),(n=this.sessionManager)==null||n.saveIds(this.prospectId,this.chatId,this.conversationId)}catch{const l="Hey! how can I help you ?";(s=(i=this.currentView)==null?void 0:i.getChatWindow)==null||s.call(i).addMessage("assistant",l),(a=this.sessionManager)==null||a.pushMessage("assistant",l)}}}async initialize(A,r){await super.initialize(A),this.processConfig(A),r&&(this.root=r),this.root&&this.ui_renderer(this.root)}processConfig(A){var r,n;if(this.widgetId=A.widgetId||A.widget_id||this.widgetId||"",this.agentId=A.agentId||A.agent_id||this.agentId||"",this.prospectGroupId=A.prospectGroupId||((r=A.client)==null?void 0:r.base_prospect_group_id)||this.prospectGroupId||"",this.widgetMode=A.widgetMode||A.mode||this.widgetMode||"voice_only",this.pkKey=A.pkKey||A.pk_key||A.publicKey||A.public_key||this.pkKey||"",this.primaryColor=A.primaryColor||A.primary_color||"#000000",this.secondaryColor=A.secondaryColor||A.secondary_color||"#111111",this.gradient=A.gradient||null,this.position=A.position||"bottom-right",this.positionType=A.positionType||"fixed",this.widgetIcon=A.widgetIcon||A.icon||null,this.iconConfig=A.iconConfig||A.icon_config||null,this.chatWelcomeMessage=A.chatWelcomeMessage||A.chat_welcome_message||((n=A.agent)==null?void 0:n.chat_welcome_message)||null,typeof this.chatWelcomeMessage=="string")try{this.chatWelcomeMessage=JSON.parse(this.chatWelcomeMessage)}catch{}this.chatServerUrl=A.serverUrl||A.chatServerUrl||"https://inboxapi.vanira.io",this.updateWelcomeChipsVisibility()}async create_call(A="continue"){var r,n,i,s;if(!(this.callActive||!this.agentId)){this.sessionActive||((r=this.sessionManager)==null||r.forceClaimSession(),this.sessionActive=!0),A==="new"&&((n=this.presetRenderer)==null||n.resetBoardSession());try{if(this.callActive=!0,this.micMuted=!1,this.syncMicMuteUi(),this.updateViewCallState(!0),this.updateViewStatus("connecting"),this.updateLauncherVisibility(),this.isPanelOpen&&this.minimizePanel(),!this.pkKey)throw new Error("[VaniraAI Widget] pk-key is required for voice calls");const o=((i=this.config)==null?void 0:i.serverUrl)||((s=this.config)==null?void 0:s.chatServerUrl)||hA,l=A==="continue"?Js(this.agentId):null,c=new Hn({agentId:this.agentId,apiKey:this.pkKey,sessionBehavior:A,prospectId:this.prospectId||(l==null?void 0:l.prospectId)||void 0,callId:A==="continue"?l==null?void 0:l.callId:void 0,backendUrl:o});c.on("session_started",({prospectId:d,callId:p})=>{var g;d&&(this.prospectId=d,(g=this.sessionManager)==null||g.saveIds(d,this.chatId)),p&&iu(this.agentId,p,d)}),c.on("connected",()=>this.updateViewStatus("connected")).on("disconnected",()=>this.end_call()).on("error",d=>{this.updateViewStatus("error",d)}).on("transcription",({text:d,isFinal:p})=>{var g,f;d.trim()&&(this.pillLastTranscriptionAt=Date.now()),(f=(g=this.currentView)==null?void 0:g.setTranscription)==null||f.call(g,d,p)}).on("track",({track:d})=>{var p;d.kind==="audio"&&this.setupPillAgentAudio(d),this.widgetMode.includes("avatar")&&d.kind==="video"&&((p=this.currentView)!=null&&p.setVideoTrack)&&this.currentView.setVideoTrack(d)}).on("tool_call",d=>{var f,w,v;if((f=this.presetRenderer)==null?void 0:f.handle(d,b=>{const C=Ws(d.client_fields,d.arguments||d.args,d.name),S=d.tool_call_id;if($h(C)&&S){const x=typeof b=="object"&&b!==null?b:{response:b};if(x.status==="cancelled")return;if(C===I.WriteLatexText&&x.latex_render_ok===!1)try{c.triggerActionInterrupt(),c.sendActionTrigger("latex_format_error",x)}catch{}try{c.sendToolResult(S,x)}catch{}return}if(!(b&&(b.media_id||b.url)&&Nl(C))){if(Ol(C)&&C){const x=typeof b=="object"&&b!==null?b:{response:b};if(x.status==="cancelled")return;const F=Zh(C,d.name,d.client_fields);c.triggerActionInterrupt(),c.sendActionTrigger(F,x);return}if(C){const x=Zh(C,d.name,d.client_fields);c.triggerInterrupt(x,b)}}},(b,C)=>{var F,T,k;const S=Ws(d.client_fields,d.arguments||d.args,d.name),x=d.tool_call_id;if($h(S)&&x){const M=(C==null?void 0:C.status)??"cancelled",H=String(((F=d.client_fields)==null?void 0:F.target_url)||(d.arguments||d.args||{}).target_url||"");try{const D=S===I.Navigate?((T=this.presetRenderer)==null?void 0:T.getNavigateTerminalResult(M,b,H||void 0))??{status:M,reason:b||"Navigation cancelled",preset_id:S,target_url:H||void 0}:((k=this.presetRenderer)==null?void 0:k.getBoardTerminalResult(M,b,S))??{status:M,reason:b||"User dismissed",preset_id:S};c.sendToolResult(x,D)}catch{}return}if(Nl(S)&&x){try{c.sendToolResult(x,{status:"cancelled",reason:b||"User dismissed",preset_id:S})}catch{}return}if(Ol(S)&&x){try{c.sendToolResult(x,{status:"cancelled",reason:b||"User dismissed",preset_id:S})}catch{}return}try{c.sendToolResult(x,{status:"cancelled",reason:"User dismissed"})}catch{}},c))return;if(Tm(d.name)){BQ(d,c);return}const g=new CustomEvent("vaniraai:tool_call",{detail:d,bubbles:!0,composed:!0});(v=(w=this.root)==null?void 0:w.host)==null||v.dispatchEvent(g)}),this.vaniraClient=c,await c.start(),this.boardAbortHandler=d=>{var g;const p=d.detail||{};(g=this.presetRenderer)==null||g.abortBoardTools(p.reason||"Server interrupted",p.toolCallId,p.presetId)},window.addEventListener(vm,this.boardAbortHandler)}catch(a){this.updateViewStatus("error",(a==null?void 0:a.message)||String(a))}}}isCallActive(){var A;return this.callActive&&!!((A=this.vaniraClient)!=null&&A.isConnected)}updateContext(A){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.updateContext(A),!0}catch{return!1}}triggerInterrupt(A,r={}){if(!this.isCallActive()||!this.vaniraClient)return!1;try{return this.vaniraClient.triggerInterrupt(A,r),!0}catch{return!1}}sendToolResult(A,r){var n;if(!((n=this.vaniraClient)!=null&&n.isConnected)||!A)return!1;try{return this.vaniraClient.sendToolResult(A,r),!0}catch{return!1}}end_call(){var n,i;this.boardAbortHandler&&(window.removeEventListener(vm,this.boardAbortHandler),this.boardAbortHandler=null),this.clipRegionHandler&&(window.removeEventListener($s,this.clipRegionHandler),this.clipRegionHandler=null);const A=(n=this.root)==null?void 0:n.host;A==null||A.classList.remove("vanira-clip-suppressed"),this.callActive=!1,this.callStatus="disconnected",this.micMuted=!1,this.syncMicMuteUi(),this.stopPillActivityMonitor();const r=this.vaniraClient;this.vaniraClient=null,r&&r.stop(),(i=this.presetRenderer)==null||i.teardownSession(),this.updateViewCallState(!1),this.updateLauncherVisibility()}updateViewCallState(A){var r;(r=this.currentView)!=null&&r.setCallActive&&this.currentView.setCallActive(A)}toggleMicMute(){return this.vaniraClient?(this.micMuted=this.vaniraClient.toggleMicrophoneMuted(),this.syncMicMuteUi(),this.micMuted):this.micMuted}syncMicMuteUi(){var A,r,n;(A=this.voiceChatPill)==null||A.setMicMuted(this.micMuted),(n=(r=this.currentView)==null?void 0:r.setMicMuted)==null||n.call(r,this.micMuted)}wireMicMuteControls(){var r,n,i;const A=()=>this.toggleMicMute();(r=this.voiceChatPill)==null||r.bindMicMuteToggle(A),(i=(n=this.currentView)==null?void 0:n.bindMicMuteToggle)==null||i.call(n,A)}updateViewStatus(A,r){var n,i,s,a,o;A==="connecting"?this.callStatus="connecting":A==="connected"?this.callStatus="connected":A==="error"?this.callStatus="error":this.callStatus="disconnected",(n=this.currentView)!=null&&n.setStatus&&this.currentView.setStatus(A,r),this.voiceChatPill&&this.callActive&&!this.isPanelOpen?A==="connected"?(this.pillActivityState="listening",this.voiceChatPill.setActivity("listening"),(s=(i=this.currentView)==null?void 0:i.setActivity)==null||s.call(i,"listening"),this.startPillActivityLoop()):this.voiceChatPill.setStatus(this.callStatus):A==="connected"&&(this.pillActivityState="listening",(o=(a=this.currentView)==null?void 0:a.setActivity)==null||o.call(a,"listening"),this.startPillActivityLoop())}setupPillAgentAudio(A){try{this.pillAudioCtx||(this.pillAudioCtx=new AudioContext),this.pillAudioCtx.state==="suspended"&&this.pillAudioCtx.resume();const r=new MediaStream([A]),n=this.pillAudioCtx.createMediaStreamSource(r);this.pillAgentAnalyser=this.pillAudioCtx.createAnalyser(),this.pillAgentAnalyser.fftSize=256,n.connect(this.pillAgentAnalyser),this.pillAgentData=new Uint8Array(this.pillAgentAnalyser.frequencyBinCount),this.startPillActivityLoop()}catch{}}readPillAgentLevel(){if(!this.pillAgentAnalyser||!this.pillAgentData)return 0;this.pillAgentAnalyser.getByteFrequencyData(this.pillAgentData);let A=0;const r=Math.min(48,this.pillAgentData.length);for(let n=0;n<r;n++)A+=this.pillAgentData[n];return r>0?A/r/255:0}startPillActivityLoop(){if(this.pillActivityRaf!==null)return;const A=()=>{var a,o;if(this.pillActivityRaf=requestAnimationFrame(A),!this.callActive||this.callStatus!=="connected")return;const r=this.readPillAgentLevel(),n=Date.now()-this.pillLastTranscriptionAt<1200,s=r>.06||n?"speaking":"listening";s!==this.pillActivityState&&(this.pillActivityState=s,this.voiceChatPill&&!this.isPanelOpen&&this.voiceChatPill.setActivity(s),(o=(a=this.currentView)==null?void 0:a.setActivity)==null||o.call(a,s))};this.pillActivityRaf=requestAnimationFrame(A)}stopPillActivityMonitor(){this.pillActivityRaf!==null&&(cancelAnimationFrame(this.pillActivityRaf),this.pillActivityRaf=null),this.pillAgentAnalyser=null,this.pillAgentData=null,this.pillLastTranscriptionAt=0,this.pillActivityState="idle",this.pillAudioCtx&&(this.pillAudioCtx.close().catch(()=>{}),this.pillAudioCtx=null)}ui_renderer(A){var l,c,d,p,g;this.root=A,this.root.innerHTML="",this.presetRenderer=new iQ(A),this.root.host&&(this.positionType==="fixed"?this.root.host.classList.add("vanira-portal"):this.root.host.classList.remove("vanira-portal")),this.clipRegionHandler&&window.removeEventListener($s,this.clipRegionHandler),this.clipRegionHandler=f=>{var b,C;const w=!!((b=f.detail)!=null&&b.active),v=(C=this.root)==null?void 0:C.host;v&&v.classList.toggle("vanira-clip-suppressed",w)},window.addEventListener($s,this.clipRegionHandler);const r=document.createElement("style");r.textContent=`@keyframes vanira-slide-up {
3625
3625
  from { opacity:0; transform:translateY(16px); }
3626
3626
  to { opacity:1; transform:translateY(0); }
3627
3627
  }`,this.root.appendChild(r);const n=document.createElement("style");n.textContent=`