@vanira/sdk 0.0.82

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.
@@ -0,0 +1,489 @@
1
+ "use strict";var wr=Object.defineProperty;var _r=(n,e,t)=>e in n?wr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var _=(n,e,t)=>_r(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("react");var Ue=typeof document<"u"?document.currentScript:null;const xr="https://api.vanira.io",m={Form:"vanira_form",Calendar:"vanira_calendar",Navigate:"vanira_navigate",Upload:"vanira_upload",Camera:"vanira_camera",HighlightElement:"vanira_highlight_element",ClickElement:"vanira_click_element",SelectOption:"vanira_select_option",SetDate:"vanira_set_date",TypeText:"vanira_type_text",EraseText:"vanira_erase_text",Draw:"vanira_draw",EraseDraw:"vanira_erase_draw",LiveVision:"vanira_live_vision",CloseLiveCamera:"vanira_close_live_camera",LiveScreen:"vanira_live_screen",CloseLiveScreen:"vanira_close_live_screen",ClipRegion:"vanira_clip_region",TabScreenshot:"vanira_tab_screenshot",ScreenInk:"vanira_screen_ink",ScreenCursor:"vanira_screen_cursor",ScreenClick:"vanira_screen_click",ClearScreenOverlay:"vanira_clear_screen_overlay",PageScan:"vanira_page_scan",PointAt:"vanira_point_at",OutlineTargets:"vanira_outline_targets",ClearGuide:"vanira_clear_guide"},Sr=Object.values(m),Cr=new Set(Sr),kr=new Set([m.Camera,m.LiveVision,m.LiveScreen]),Er=new Set([m.Navigate,m.HighlightElement,m.ClickElement,m.SelectOption,m.SetDate,m.TypeText,m.EraseText,m.Draw,m.EraseDraw,m.LiveVision,m.CloseLiveCamera,m.LiveScreen,m.CloseLiveScreen,m.TabScreenshot,m.ScreenInk,m.ScreenCursor,m.ScreenClick,m.ClearScreenOverlay,m.PageScan,m.PointAt,m.OutlineTargets,m.ClearGuide]),Tr=new Set([m.TypeText,m.EraseText,m.Draw,m.EraseDraw]);function Y(n){return!!n&&Cr.has(n)}function Ar(n){return Y(n)&&Er.has(n)}function pt(n){return Y(n)&&Tr.has(n)}function Ge(n){return Y(n)&&kr.has(n)}const Ir=new Set([m.Form,m.Calendar]);function Je(n){return Y(n)&&Ir.has(n)}function ft(n,e,t){return t!=null&&t.action_name?String(t.action_name):n===m.Calendar?"calendar_slot_selected":`user_submitted_${e||"collect_user_data"}`}function mt(n){return Y(n)&&!Ge(n)&&!Je(n)}const zt=new Set([m.ScreenInk,m.ScreenCursor,m.ScreenClick,m.ClearScreenOverlay,m.PointAt,m.OutlineTargets,m.ClearGuide]),Lr=new Set([...zt,m.PageScan,m.TabScreenshot]);function Pr(n){return Y(n)&&zt.has(n)}function Mr(n){return Y(n)&&Lr.has(n)}function Vt(n){if(typeof n=="string")try{return JSON.parse(n)}catch{return{}}return n&&typeof n=="object"?n:{}}const vt={type_on_whiteboard:m.TypeText,write_on_whiteboard:m.TypeText,write_on_white_board:m.TypeText,dom_typing_simulation:m.TypeText,erase_text:m.EraseText,dom_erase:m.EraseText,draw_on_board:m.Draw,erase_drawing_board:m.EraseDraw,open_live_camera:m.LiveVision,live_vision:m.LiveVision,close_live_camera:m.CloseLiveCamera,stop_live_camera:m.CloseLiveCamera,open_live_screen:m.LiveScreen,close_live_screen:m.CloseLiveScreen,screen_ink:m.ScreenInk,screen_cursor:m.ScreenCursor,screen_click:m.ScreenClick,clear_screen_overlay:m.ClearScreenOverlay,tab_screenshot:m.TabScreenshot,capture_tab:m.TabScreenshot,capture_tab_screenshot:m.TabScreenshot,screenshot_tab:m.TabScreenshot,page_scan:m.PageScan,scan_page:m.PageScan,point_at:m.PointAt,outline_targets:m.OutlineTargets,outline_elements:m.OutlineTargets,clear_guide:m.ClearGuide};function yt(n,e){const t=n.text_to_type??(e==null?void 0:e.text_to_type)??n.text??(e==null?void 0:e.text)??n.value??(e==null?void 0:e.value);return typeof t=="string"&&t.trim().length>0}function Nr(n,e){const t=n.fields??(e==null?void 0:e.fields);return Array.isArray(t)?t.length>0:typeof t=="string"?t.split(",").map(r=>r.trim()).filter(Boolean).length>0:!1}function Dr(n,e){const t=n==null?void 0:n.preset_id;if(typeof t=="string"&&Y(t))return t;const s=Vt(e).preset_id;if(typeof s=="string"&&Y(s))return s}function ot(n,e,t){const r=Vt(e);let s=Dr(n,r);if(s===m.Form&&yt(r,n)&&!Nr(r,n))return m.TypeText;if(s)return s;const i=String(t??"").trim().toLowerCase();if(i&&vt[i])return vt[i];if(yt(r,n))return m.TypeText}const Ee="vanira_latest_call_id",Qe="vanira_prospect_id";function Te(n){return`vanira_latest_call_id_${n}`}function Ae(n){return`vanira_prospect_id_${n}`}function qt(n){return`vanira_call_meta_${n}`}function Q(n,e){if(!n)return null;try{return n.getItem(e)}catch{return null}}function Ie(n){if(typeof window>"u"||!n)return null;const e=[],t=Q(window.localStorage,qt(n));if(t)try{const a=JSON.parse(t);a!=null&&a.callId&&e.push({callId:a.callId,prospectId:a.prospectId,updatedAt:a.updatedAt||0})}catch{}const r=(a,l,c)=>{a&&e.push({callId:a,prospectId:l||void 0,updatedAt:c})},s=Q(window.localStorage,Ae(n)),i=Q(window.sessionStorage,Ae(n)),o=Q(window.localStorage,Qe);return r(Q(window.localStorage,Te(n)),s||o,2),r(Q(window.sessionStorage,Te(n)),i||o,1),r(Q(window.localStorage,Ee),o,0),r(Q(window.sessionStorage,Ee),o,0),e.length?(e.sort((a,l)=>l.updatedAt-a.updatedAt),e[0]):null}function Ht(n,e,t){var s,i,o,a,l,c,u,d,p;if(typeof window>"u"||!n||!e)return;const r={callId:e,prospectId:t,updatedAt:Date.now()};try{(s=window.localStorage)==null||s.setItem(qt(n),JSON.stringify(r)),(i=window.localStorage)==null||i.setItem(Te(n),e),(o=window.sessionStorage)==null||o.setItem(Te(n),e),t&&((a=window.localStorage)==null||a.setItem(Ae(n),t),(l=window.sessionStorage)==null||l.setItem(Ae(n),t)),(c=window.localStorage)==null||c.setItem(Ee,e),(u=window.sessionStorage)==null||u.setItem(Ee,e),t&&((d=window.localStorage)==null||d.setItem(Qe,t),(p=window.sessionStorage)==null||p.setItem(Qe,t))}catch{}}function Br(n){var e;return!!((e=Ie(n))!=null&&e.callId)}const $r=new Set(["client_tool_call","clearAudio","client_tool_cancel"]);function jt(n){if(!n||typeof n!="object")return!1;const e=n.event;return typeof e=="string"&&$r.has(e)}const Oe=16*1024,Rr=256*1024;function Fe(n,e){return(n==null?void 0:n.readyState)==="open"&&(e==null?void 0:e.readyState)==="open"}function Ur(n,e){return{control:(n==null?void 0:n.readyState)??"missing",mediaBytes:(e==null?void 0:e.readyState)??"missing"}}async function Or(n,e,t=8e3){if(Fe(n,e))return!0;const r=Date.now()+t;for(;Date.now()<r;){if(Fe(n,e))return!0;await new Promise(s=>setTimeout(s,50))}return Fe(n,e)}async function gt(n){for(;n.bufferedAmount>Rr;)await new Promise(e=>setTimeout(e,10))}async function Fr(n){const{bytes:e,filename:t,contentType:r,reason:s,message:i,callId:o,mediaBytesChannel:a,sendControlEvent:l,uploadId:c=crypto.randomUUID(),uploadKind:u="media"}=n,d=e.byteLength,p=d===0?0:Math.ceil(d/Oe);l("client_media_upload_start",{data:{upload_id:c,call_id:o,reason:s,message:i,filename:t,content_type:r,size:d,chunk_count:p,upload_kind:u}});const h=new Uint8Array(e);for(let f=0;f<d;f+=Oe){await gt(a);const y=Math.min(f+Oe,d);a.send(h.subarray(f,y))}return await gt(a),l("client_media_upload_complete",{data:{upload_id:c,call_id:o,reason:s,message:i,chunk_count:p,upload_kind:u}}),{media_id:c,url:"",content_type:r}}async function zr(n){return typeof n.arrayBuffer=="function"?n.arrayBuffer():new Response(n).arrayBuffer()}let ee=null;const Vr=4e3;function at(n){if(typeof window>"u")return n||"/";const e=(n||"/").trim();if(!e)return"/";try{const t=new URL(e,window.location.origin);return t.origin!==window.location.origin?e:`${t.pathname}${t.search}${t.hash}`||"/"}catch{return e.startsWith("/")?e:`/${e}`}}function Wt(n,e){ee={targetRoute:at(n),presetId:e==null?void 0:e.presetId,toolName:e==null?void 0:e.toolName,expiresAt:Date.now()+Vr}}function qr(n){if(!ee)return null;if(Date.now()>ee.expiresAt)return ee=null,null;const e=at(n),t=ee.targetRoute;if(!(e===t||e.startsWith(t.split("#")[0])||t.startsWith(e.split("#")[0])))return null;const s=ee;return ee=null,s}function he(){return typeof window>"u"?"/":`${window.location.pathname}${window.location.search}${window.location.hash}`||"/"}class Yt{constructor(e){_(this,"active",!1);_(this,"initialSent",!1);_(this,"lastRoute","");_(this,"sendContext");_(this,"isReady");_(this,"cleanupFns",[]);_(this,"initialRetryTimer",null);_(this,"routePollTimer",null);_(this,"originalPushState",null);_(this,"originalReplaceState",null);this.sendContext=e.sendContext,this.isReady=e.isReady??(()=>!0)}start(){typeof window>"u"||this.active||(this.active=!0,this.initialSent=!1,this.lastRoute=he(),this.attachListeners(),this.scheduleInitialContextSend())}stop(){if(!(!this.active&&this.cleanupFns.length===0)){this.active=!1,this.initialSent=!1,this.initialRetryTimer!==null&&(clearTimeout(this.initialRetryTimer),this.initialRetryTimer=null),this.routePollTimer!==null&&(clearInterval(this.routePollTimer),this.routePollTimer=null);for(const e of this.cleanupFns)try{e()}catch{}this.cleanupFns.length=0,this.originalPushState&&(history.pushState=this.originalPushState,this.originalPushState=null),this.originalReplaceState&&(history.replaceState=this.originalReplaceState,this.originalReplaceState=null)}}onChannelReady(){this.scheduleInitialContextSend()}scheduleInitialContextSend(e=0){if(!(!this.active||this.initialSent)){if(this.isReady()){this.sendRouteContext("call_started"),this.initialSent=!0;return}e>=30||(this.initialRetryTimer=window.setTimeout(()=>this.scheduleInitialContextSend(e+1),100))}}attachListeners(){const e=(i,o=0)=>{const a=()=>{const l=he();l!==this.lastRoute&&this.handleRouteChange(l,i)};o>0?window.setTimeout(a,o):queueMicrotask(a)},t=()=>e("popstate"),r=()=>e("hashchange"),s=i=>{const o=i.detail;if((o==null?void 0:o.initiated_by)==="agent"){e("vanira_navigate_agent",120);return}e("vanira_navigate",120)};window.addEventListener("popstate",t),window.addEventListener("hashchange",r),window.addEventListener("vanira:navigate",s),this.cleanupFns.push(()=>window.removeEventListener("popstate",t),()=>window.removeEventListener("hashchange",r),()=>window.removeEventListener("vanira:navigate",s)),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history),history.pushState=(...i)=>{this.originalPushState(...i),e("pushState")},history.replaceState=(...i)=>{this.originalReplaceState(...i),e("replaceState")},this.routePollTimer=window.setInterval(()=>{if(!this.active)return;const i=he();i!==this.lastRoute&&this.handleRouteChange(i,"location_poll")},1e3)}handleRouteChange(e,t){if(!this.active)return;const r=this.lastRoute;if(r===e)return;if(this.lastRoute=e,!this.initialSent){this.scheduleInitialContextSend();return}!this.isReady()||qr(e)||this.sendRouteContext("route_changed",r,t,"user")}sendRouteContext(e,t,r,s="user"){const i=he();this.lastRoute=i;const o={ui_state:"page_navigation",navigation_led_by:s,current_route:i,current_page:i,user_action:e==="call_started"?"call_started_on_page":"user_navigated"};e==="call_started"?o.message=`User started the call while viewing ${i}.`:(o.previous_route=t??"",o.message=`User navigated from ${t||"(unknown)"} to ${i}.`,r&&(o.navigation_source=r));try{this.sendContext(o)}catch{}}}const G=class G{constructor(e){_(this,"serverUrl");_(this,"agentId");_(this,"callId");_(this,"prospectId");_(this,"apiKey");_(this,"backendUrl");_(this,"token");_(this,"onConnected");_(this,"onDisconnected");_(this,"onError");_(this,"onTranscription");_(this,"onLocalStream");_(this,"onRemoteTrack");_(this,"onClientToolCall");_(this,"onSessionStarted");_(this,"sessionStartedEmitted",!1);_(this,"pc",null);_(this,"dataChannel",null);_(this,"mediaBytesChannel",null);_(this,"audioElement",null);_(this,"localStream",null);_(this,"micMuted",!1);_(this,"connected",!1);_(this,"icePollInterval",null);_(this,"appliedRemoteCandidates",new Set);_(this,"iceServers");_(this,"callSessionLoaded",!1);_(this,"connectGeneration",0);_(this,"runtime");_(this,"sessionBehavior");_(this,"routeTracker",null);_(this,"_status","idle");_(this,"listeners",new Map);_(this,"liveVision");_(this,"liveVisionAutoStarted",!1);if(!e.agentId)throw new Error("agentId is required");const t=!!(e.apiKey||e.token),r=!!(e.serverUrl&&e.callId),s=G.normalizeIceServers(e.iceServers);if(!t&&!r)throw new Error("apiKey or token is required — or pass serverUrl and callId from a prior POST /calls/create");this.agentId=e.agentId,this.sessionBehavior=e.sessionBehavior,this.serverUrl=(e.serverUrl||"").replace(/\/$/,""),this.apiKey=e.apiKey,this.token=e.token,this.backendUrl=(e.backendUrl||xr).replace(/\/$/,""),s.length&&(this.iceServers=s),r&&(this.callSessionLoaded=!0);const i=typeof window<"u";this.prospectId=e.prospectId;const o=e.sessionBehavior==="continue";if(o&&i&&!e.callId){const l=Ie(this.agentId);l&&(e.callId||(this.callId=l.callId),!this.prospectId&&l.prospectId&&(this.prospectId=l.prospectId))}if(!this.prospectId&&i)try{const l=Ie(this.agentId);this.prospectId=(l==null?void 0:l.prospectId)||window.sessionStorage&&window.sessionStorage.getItem("vanira_prospect_id")||window.localStorage&&window.localStorage.getItem("vanira_prospect_id")||void 0}catch{}e.callId?this.callId=e.callId:o||(this.callId=void 0);const a=e.onSessionStarted;this.onSessionStarted=l=>{a==null||a(l),this.emit("session_started",l)},this.liveVision=e.liveVision,this.onConnected=()=>{var l;this._status="connected",(l=e.onConnected)==null||l.call(e),this.emit("connected"),this.maybeAutoStartLiveCamera()},this.onDisconnected=()=>{var l;this._status="disconnected",(l=e.onDisconnected)==null||l.call(e),this.emit("disconnected")},this.onError=l=>{var u;this._status="error";const c=typeof l=="string"?l:(l==null?void 0:l.message)||"Connection error";(u=e.onError)==null||u.call(e,l),this.emit("error",c)},this.onTranscription=(l,c)=>{var u;(u=e.onTranscription)==null||u.call(e,l,c),this.emit("transcription",{text:l,isFinal:c})},this.onLocalStream=e.onLocalStream||(()=>{}),this.onRemoteTrack=(l,c)=>{var u;(u=e.onRemoteTrack)==null||u.call(e,l,c),this.emit("track",{track:l,stream:c})},this.onClientToolCall=l=>{var d;(d=e.onClientToolCall)==null||d.call(e,l);const c=(l==null?void 0:l.data)||l,u={name:String(c.name||c.tool_name||""),arguments:c.arguments||c.args||{},tool_call_id:String(c.tool_call_id||c.call_id||""),execution_mode:c.execution_mode==="blocking"?"blocking":"fire_and_forget",client_fields:c.client_fields||{}};u.name&&u.tool_call_id&&this.emit("tool_call",u)},this.runtime=e.runtime,typeof window<"u"&&e.trackRouteContext!==!1&&(this.routeTracker=new Yt({sendContext:l=>this.sendContextUpdate(l),isReady:()=>{var l;return((l=this.dataChannel)==null?void 0:l.readyState)==="open"}}))}async createCall(){return this.connect()}async connect(){var t;this._status="connecting";const e=++this.connectGeneration;if(await this.loadCallSession(),!this.isConnectCancelled(e)){if(!this.serverUrl)throw new Error("[VaniraClient] worker_url missing from /calls/create");if(!this.callId)throw new Error("[VaniraClient] call_id missing — must come from POST /calls/create");if(this.onSessionStarted&&this.prospectId&&this.callId&&!this.sessionStartedEmitted)try{this.onSessionStarted({prospectId:this.prospectId,callId:this.callId,serverUrl:this.serverUrl}),this.sessionStartedEmitted=!0}catch{}try{this.appliedRemoteCandidates.clear(),this.stopRemoteIcePolling();const r=this.getIceServers();this.pc=new RTCPeerConnection({iceServers:r,iceTransportPolicy:"all"});let s;try{s=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:{ideal:16e3},channelCount:1}})}catch(d){if(d.name==="NotAllowedError"||d.name==="PermissionDeniedError"||(t=d.message)!=null&&t.includes("Permission denied")){const p=navigator.userAgent,h=/iPad|iPhone|iPod/.test(p)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;let f="Microphone access denied. Please allow microphone access in your browser settings.";h&&(p.includes("CriOS")?f="Microphone access blocked. Please enable it in iOS Settings > Chrome > Microphone, then reload the page.":p.includes("FxiOS")?f="Microphone access blocked. Please enable it in iOS Settings > Firefox > Microphone, then reload the page.":f="Microphone access blocked. Please enable it in iOS Settings > Safari > Microphone (or tap 'aA' > Website Settings > Allow Microphone).");const y=new Error(f);throw y.name=d.name,y}throw d}if(this.isConnectCancelled(e)){s.getTracks().forEach(d=>d.stop());return}if(this.localStream=s,!this.pc||this.isConnectCancelled(e)){s.getTracks().forEach(d=>d.stop());return}if(this.onLocalStream(s),s.getTracks().forEach(d=>{var p;(p=this.pc)==null||p.addTrack(d,s)}),!this.pc)throw new Error("RTCPeerConnection was closed unexpectedly");this.dataChannel=this.pc.createDataChannel("control"),this.dataChannel.onopen=()=>{var d;(d=this.routeTracker)==null||d.onChannelReady()},this.dataChannel.onmessage=d=>{if(typeof d.data=="string")try{this.handleControlEvent(JSON.parse(d.data))}catch{}else if(d.data instanceof ArrayBuffer)try{const p=new TextDecoder().decode(d.data);try{const h=JSON.parse(p);jt(h)&&this.handleControlEvent(h)}catch{}}catch{}else d.data instanceof Blob&&d.data.text().then(p=>{try{this.handleControlEvent(JSON.parse(p))}catch{}})},this.dataChannel.onerror=d=>{},this.mediaBytesChannel=this.pc.createDataChannel("media-bytes",{ordered:!0}),this.mediaBytesChannel.binaryType="arraybuffer",this.mediaBytesChannel.onopen=()=>{},this.mediaBytesChannel.onerror=d=>{},this.pc.ontrack=d=>{const p=d.track,h=d.streams[0];p.kind==="audio"?(this.audioElement=new Audio,this.audioElement.srcObject=h,this.audioElement.play().catch(f=>{}),this.audioElement.onended=()=>{this.sendEvent("playedStream"),typeof window<"u"&&window.dispatchEvent(new CustomEvent("vanira:agent-playback-ended"))},this.onRemoteTrack(p,h)):p.kind==="video"&&this.onRemoteTrack(p,h)};const i=()=>{var h,f,y,v,g,b,S,w,x,C,k;const d=((h=this.pc)==null?void 0:h.connectionState)==="connected"||((f=this.pc)==null?void 0:f.iceConnectionState)==="connected"||((y=this.pc)==null?void 0:y.iceConnectionState)==="completed",p=((v=this.pc)==null?void 0:v.connectionState)==="failed"||((g=this.pc)==null?void 0:g.iceConnectionState)==="failed"||((b=this.pc)==null?void 0:b.connectionState)==="closed"||((S=this.pc)==null?void 0:S.iceConnectionState)==="closed"||((w=this.pc)==null?void 0:w.connectionState)==="disconnected"||((x=this.pc)==null?void 0:x.iceConnectionState)==="disconnected";((C=this.pc)==null?void 0:C.connectionState)==="connected"&&this.stopRemoteIcePolling(),d&&!this.connected?(this.connected=!0,(k=this.routeTracker)==null||k.start(),this.onConnected()):p&&this.connected&&(this.connected=!1,this.liveVisionAutoStarted=!1,this.onDisconnected())};this.pc.onconnectionstatechange=i,this.pc.oniceconnectionstatechange=i;const o=this.getIceTrickleUrl();this.pc.onicecandidate=d=>{d.candidate&&fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({candidate:d.candidate.toJSON()})}).catch(p=>{})};const a=await this.pc.createOffer();if(this.isConnectCancelled(e)||(await this.pc.setLocalDescription(a),this.isConnectCancelled(e)))return;const l=this.serverUrl.includes("?")?this.serverUrl:`${this.serverUrl}/webrtc?agent=${this.agentId}_${this.callId}`,c=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({offer:this.pc.localDescription,agentId:this.agentId,callId:this.callId})});if(this.isConnectCancelled(e))return;if(!c.ok){const d=await c.json();throw new Error(d.error||`HTTP ${c.status}`)}const{answer:u}=await c.json();if(this.isConnectCancelled(e)||!this.pc||(await this.pc.setRemoteDescription(u),this.isConnectCancelled(e)))return;this.startRemoteIcePolling(o)}catch(r){if(this.isConnectCancelled(e))return;throw this.disconnect(),this.onError(r.message||r),r}}}createCallCacheKey(e,t){const r=this.apiKey?`key:${this.apiKey.slice(0,16)}`:`token:${(this.token||"").slice(-16)}`;return[this.backendUrl,this.agentId,e,t||"",this.prospectId||"",r].join("|")}async postCreateCall(e,t,r){var a,l,c;const s=await fetch(`${this.backendUrl}/calls/create`,{method:"POST",headers:e,body:JSON.stringify({agent_id:this.agentId,type:((a=this.runtime)==null?void 0:a.callType)||"web",mode:t,...(l=this.runtime)!=null&&l.runtimeName?{runtime:this.runtime.runtimeName}:{},prospect_id:this.prospectId,...r?{call_id:r}:{}})});if(!s.ok){const u=await s.json().catch(()=>({}));throw new Error(`[VaniraClient] createCall failed (${s.status}): ${((c=u==null?void 0:u.detail)==null?void 0:c.message)||(u==null?void 0:u.message)||s.statusText}`)}const i=await s.json();if(!i.call_id||!i.worker_url)throw new Error("[VaniraClient] /calls/create response missing call_id or worker_url");const o=G.normalizeIceServers(i.ice_servers);if(!o.length)throw new Error("[VaniraClient] /calls/create response missing ice_servers");return{callId:i.call_id,prospectId:i.prospect_id||this.prospectId,serverUrl:i.worker_url.replace(/\/$/,""),iceServers:o}}applyCreateCallSession(e){if(this.callId=e.callId,this.prospectId=e.prospectId||this.prospectId,this.serverUrl=e.serverUrl,this.iceServers=e.iceServers,this.callSessionLoaded=!0,Ht(this.agentId,this.callId||"",this.prospectId),this.onSessionStarted&&this.prospectId&&this.callId&&!this.sessionStartedEmitted)try{this.onSessionStarted({prospectId:this.prospectId,callId:this.callId,serverUrl:this.serverUrl}),this.sessionStartedEmitted=!0}catch{}}async loadCallSession(){if(this.callSessionLoaded)return;if(this.serverUrl&&this.callId){this.callSessionLoaded=!0;return}if(!this.apiKey&&!this.token)throw new Error("[VaniraClient] apiKey or token is required to create a call session");const e={"Content-Type":"application/json"};this.apiKey?e["X-API-Key"]=this.apiKey:this.token&&(e.Authorization=this.token.startsWith("Bearer ")?this.token:`Bearer ${this.token}`);const t=this.sessionBehavior==="continue"?this.callId:void 0,r=this.sessionBehavior==="continue"?"continue":"new",s=this.createCallCacheKey(r,t);let i=G.inflightCreates.get(s);i||(i=this.postCreateCall(e,r,t),G.inflightCreates.set(s,i),i.finally(()=>{G.inflightCreates.get(s)===i&&G.inflightCreates.delete(s)}));const o=await i;this.applyCreateCallSession(o)}getIceServers(){var e;if((e=this.iceServers)!=null&&e.length)return this.iceServers;throw new Error("[VaniraClient] ice_servers missing — pass iceServers from POST /calls/create")}static normalizeIceServers(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const s=r==null?void 0:r.urls,i=Array.isArray(s)?s.filter(Boolean):typeof s=="string"&&s.trim()?[s.trim()]:[];if(!i.length)continue;const o={urls:i.length===1?i[0]:i},a=r.username,l=r.credential;a&&(o.username=a),l&&(o.credential=l),t.push(o)}return t}getWorkerOrigin(){var e;if(!((e=this.serverUrl)!=null&&e.trim()))return"";try{return new URL(this.serverUrl).origin}catch{return this.serverUrl.replace(/\/webrtc.*$/,"").replace(/\/$/,"")}}getIceTrickleUrl(){try{const e=new URL(this.serverUrl);return e.pathname.endsWith("/webrtc")?e.pathname=`${e.pathname}/ice`:e.pathname="/webrtc/ice",e.toString()}catch{return`${this.getWorkerOrigin()}/webrtc/ice?agent_id=${this.agentId}&call_id=${this.callId}`}}startRemoteIcePolling(e){this.stopRemoteIcePolling(),this.icePollInterval=setInterval(async()=>{if(!this.pc){this.stopRemoteIcePolling();return}if(this.pc.connectionState==="connected"){this.stopRemoteIcePolling();return}try{const t=await fetch(e);if(!t.ok)return;const{candidates:r}=await t.json();for(const s of r||[]){const i=JSON.stringify(s);if(!this.appliedRemoteCandidates.has(i)){this.appliedRemoteCandidates.add(i);try{await this.pc.addIceCandidate(s)}catch{}}}}catch{}},150)}stopRemoteIcePolling(){this.icePollInterval!==null&&(clearInterval(this.icePollInterval),this.icePollInterval=null)}sendEvent(e,t={}){var r;if(((r=this.dataChannel)==null?void 0:r.readyState)==="open"){const s={event:e,...t};this.dataChannel.send(JSON.stringify(s))}}async sendEventWhenReady(e,t={},r=1e4){var i;const s=Date.now()+r;for(;Date.now()<s;){if(((i=this.dataChannel)==null?void 0:i.readyState)==="open")return this.sendEvent(e,t),!0;await new Promise(o=>setTimeout(o,50))}return!1}startLiveCamera(e={}){const t={...this.liveVision,...e};this.emit("tool_call",this.buildOpenLiveCameraToolCall(t))}buildOpenLiveCameraToolCall(e={}){const t=e.scope??"until_call_end";return{name:"open_live_camera",tool_call_id:`lv_${crypto.randomUUID()}`,execution_mode:"fire_and_forget",client_fields:{preset_id:m.LiveVision},arguments:{mode:"live",scope:t,target_fps:e.target_fps??1,max_fps:e.max_fps??3,max_width:e.max_width??640,reason:e.reason??"camera_capture",facing_mode:e.facing_mode??"environment",show_preview:e.show_preview??!0,...t==="timed"&&e.duration_sec?{duration_sec:e.duration_sec}:{}}}}maybeAutoStartLiveCamera(){const e=this.liveVision;!(e!=null&&e.enabled)||e.scope!=="full_call"||this.liveVisionAutoStarted||(this.liveVisionAutoStarted=!0,this.emit("tool_call",this.buildOpenLiveCameraToolCall(e)))}handleControlEvent(e){var t;switch(e.event){case"clearAudio":break;case"transcription":this.onTranscription(e.text,e.isFinal);break;case"mark":break;case"client_tool_cancel":{const s=(e.data||e).tool_call_id||e.tool_call_id;this.dispatchBoardAbort("Tool cancelled by server",s);break}case"client_tool_call":{const r=e.tool_call||e.data||e,s=(r==null?void 0:r.tool_call_id)||(r==null?void 0:r.call_id)||e.tool_call_id||"";s&&((t=this.dataChannel)==null?void 0:t.readyState)==="open"&&this.dataChannel.send(JSON.stringify({event:"client_tool_ack",data:{tool_call_id:s}}));const i=(r==null?void 0:r.arguments)||(r==null?void 0:r.args)||{},o=(r==null?void 0:r.client_fields)||{},a=(r==null?void 0:r.name)||(r==null?void 0:r.tool_name)||"",l=ot(o,i,a);if(a==="end_call"){s&&this.sendToolResult(s,{status:"client_ack_end_call",message:"Ending call."}),window.setTimeout(()=>this.disconnect(),120);break}if(l){window.dispatchEvent(new CustomEvent("vanira:preset",{detail:{toolCall:r,client:this}})),this.onClientToolCall(r);break}this.onClientToolCall(r);break}}}disconnect(){var e;this.connectGeneration++,this.stopRemoteIcePolling(),this.appliedRemoteCandidates.clear(),this.audioElement&&(this.audioElement.pause(),this.audioElement.srcObject=null),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.mediaBytesChannel&&(this.mediaBytesChannel.close(),this.mediaBytesChannel=null),this.pc&&(this.pc.getSenders().forEach(t=>{t.track&&t.track.stop()}),this.pc.close(),this.pc=null),this.localStream&&(this.localStream.getTracks().forEach(t=>{try{t.stop()}catch{}}),this.localStream=null),this.connected=!1,(e=this.routeTracker)==null||e.stop(),this.callSessionLoaded=!1,this.sessionStartedEmitted=!1,this.serverUrl="",this.callId=void 0,this.micMuted=!1,this.iceServers=void 0,this.onDisconnected()}setMicrophoneMuted(e){var t,r;this.micMuted=e,(t=this.localStream)==null||t.getAudioTracks().forEach(s=>{s.enabled=!e}),(r=this.pc)==null||r.getSenders().forEach(s=>{var i;((i=s.track)==null?void 0:i.kind)==="audio"&&(s.track.enabled=!e)})}isMicrophoneMuted(){return this.micMuted}toggleMicrophoneMuted(){return this.setMicrophoneMuted(!this.micMuted),this.micMuted}isConnectCancelled(e){return e!==this.connectGeneration}dispatchBoardAbort(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent("vanira:board_abort",{detail:{reason:e,toolCallId:t}}))}sendToolResult(e,t){this.callId,this.sendEvent("client_tool_result",{call_id:this.callId,data:{tool_call_id:e,result:t},result:t})}sendToolAck(e){var t;((t=this.dataChannel)==null?void 0:t.readyState)==="open"&&this.dataChannel.send(JSON.stringify({event:"client_tool_ack",data:{tool_call_id:e}}))}sendContextUpdate(e){this.sendEvent("client_context_update",{data:{context:e}})}sendActionTrigger(e,t={}){this.sendEvent("client_action_trigger",{data:{action_name:e,data:t}})}triggerActionInterrupt(){this.sendEvent("action_interrupt")}async uploadMediaForToolResult(e,t="general"){return this._postMediaUpload(e,t)}async uploadMedia(e,t="general",r=""){return await Or(this.dataChannel,this.mediaBytesChannel)?this._uploadMediaViaDataChannel(e,t,r):(Ur(this.dataChannel,this.mediaBytesChannel),this._uploadMediaViaHTTP(e,t,r))}async uploadMediaFrame(e,t="camera_capture",r){const s=r&&!(e instanceof File)?new File([e],r,{type:e.type||"image/jpeg"}):e,{media_id:i,url:o,contentType:a}=await this._postMediaUpload(s,t,!0);if(!i||!o)throw new Error("Frame upload failed: server response missing media_id or url");return{media_id:i,url:o,content_type:a}}async _uploadBytesViaDataChannel(e,t,r,s,i){if(!this.callId||!this.mediaBytesChannel)throw new Error("Upload failed: call not ready for WebRTC media upload.");const o=i||(e instanceof File?e.name:s==="frame"?"frame.jpg":"upload.bin"),a=e.type||(s==="frame"?"image/jpeg":"application/octet-stream"),l=await zr(e);return Fr({bytes:l,filename:o,contentType:a,reason:t,message:r,callId:this.callId,mediaBytesChannel:this.mediaBytesChannel,sendControlEvent:(c,u)=>this.sendEvent(c,u),uploadKind:s})}async _uploadMediaViaDataChannel(e,t,r){const s=await this._uploadBytesViaDataChannel(e,t,r,"media");return{media_id:s.media_id,url:s.url}}async _uploadMediaViaHTTP(e,t="general",r=""){const{media_id:s,url:i,contentType:o}=await this._postMediaUpload(e,t,!0);if(this.dataChannel&&this.dataChannel.readyState==="open"){const a={event:"client_media_update",data:{media_id:s,media_url:i,content_type:o,reason:t,message:r}};this.dataChannel.send(JSON.stringify(a))}return{media_id:s,url:i}}async _postMediaUpload(e,t,r=!1){if(!this.serverUrl)throw new Error("Upload failed: serverUrl is not set. Connect the VaniraClient first.");if(!this.callId)throw new Error("Upload failed: callId is missing.");const s=this.getWorkerOrigin();if(!s)throw new Error("Upload failed: worker_url is not set. Connect the call before uploading media.");const i=`${s}/media/upload`,o=new FormData;o.append("file",e),o.append("call_id",this.callId),o.append("reason",t);const a=await fetch(i,{method:"POST",body:o});if(!a.ok){let p=`HTTP ${a.status}`;try{p=(await a.json()).error||p}catch{}throw new Error(`Upload failed: ${p}`)}const l=await a.json(),c=l.media_id,u=l.url,d=l.content_type||e.type;if(!c||!u)throw new Error("Upload failed: server response missing media_id or url");return r?{media_id:c,url:u,contentType:d}:{media_id:c,url:u,contentType:d}}get status(){return this._status}get isConnected(){return this._status==="connected"}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this}off(e,t){var r;return(r=this.listeners.get(e))==null||r.delete(t),this}emit(e,t){var r;(r=this.listeners.get(e))==null||r.forEach(s=>s(t))}async start(){return await this.connect(),{callId:this.callId||"",prospectId:this.prospectId||"",serverUrl:this.serverUrl||""}}stop(){this.disconnect(),this._status="disconnected"}sendToolError(e,t){this.sendToolResult(e,{status:"error",error:t})}updateContext(e){this.sendContextUpdate(e)}triggerInterrupt(e,t={}){this.triggerActionInterrupt(),this.sendActionTrigger(e,t)}interruptAudioOnly(){this.triggerActionInterrupt()}};_(G,"inflightCreates",new Map);let Le=G;const Hr="vnr-clip-overlay";function jr(n){var e;return((e=n.classList)==null?void 0:e.contains(Hr))??!1}function Wr(n){var t;return((t=n.tagName)==null?void 0:t.toLowerCase())==="vanira-convai"?!0:typeof n.closest=="function"&&!!n.closest("vanira-convai")}function Gt(n){var e;return jr(n)||Wr(n)||(e=n.classList)!=null&&e.contains("vnr-screen-overlay-root")?!0:typeof n.closest=="function"&&!!n.closest(".vnr-screen-overlay-root")}async function Jt(){const n=document.documentElement.clientWidth,e=document.documentElement.clientHeight;return Kt({left:0,top:0,width:n,height:e})}function Qt(n,e){if(n.width<=e)return n;const t=e/n.width,r=document.createElement("canvas");r.width=e,r.height=Math.round(n.height*t);const s=r.getContext("2d");return s?(s.drawImage(n,0,0,r.width,r.height),r):n}async function Kt(n){const{default:e}=await Promise.resolve().then(()=>require("../chunks/html2canvas.js")),t=window.devicePixelRatio||1,r=window.scrollX+n.left,s=window.scrollY+n.top;return e(document.body,{x:r,y:s,width:n.width,height:n.height,windowWidth:document.documentElement.clientWidth,windowHeight:document.documentElement.clientHeight,scrollX:-window.scrollX,scrollY:-window.scrollY,useCORS:!0,allowTaint:!1,scale:t,ignoreElements:i=>Gt(i),logging:!1})}async function lt(n,e=.88){try{const t=await new Promise(r=>n.toBlob(s=>r(s),"image/jpeg",e));if(!t)throw new Error("Failed to encode clip as JPEG");return t}catch(t){const r=t instanceof Error?t.message:String(t);throw/tainted|security|cross-origin/i.test(r)?new Error("Could not export this page region (cross-origin content). Try selecting a simpler area."):t}}const Yr="vanira:clip-region-active";function Ke(n){typeof window>"u"||window.dispatchEvent(new CustomEvent(Yr,{detail:{active:n}}))}const _e="vnr-clip-overlay",bt="2147483647",Gr="rgba(0, 0, 0, 0.28)";function Jr(n={}){const e=n.minSizePx??24,t=n.hint??"Drag to select an area — release to clip.";return new Promise(r=>{let s=!1,i=!1,o=0,a=0,l=!1,c={left:0,top:0,width:0,height:0},u=!1,d=null;const p=A=>{s||(s=!0,O(),r(A))},h=document.createElement("div");h.className=_e,h.style.cssText=["position:fixed","inset:0",`z-index:${bt}`,"cursor:crosshair","user-select:none","touch-action:none","background:transparent","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"].join(";");const f=document.createElement("div");f.style.cssText=["position:absolute","display:none","pointer-events:none","border:2px solid #6366f1","border-radius:2px","background:transparent","box-shadow:none"].join(";");const y=document.createElement("div");y.style.cssText=["position:absolute","display:none","pointer-events:none","padding:2px 6px","border-radius:4px","font-size:11px","font-weight:600","color:#fff","background:rgba(15,23,42,0.82)","white-space:nowrap"].join(";");const v=document.createElement("div");v.className=_e,v.style.cssText=["position:fixed","top:16px","left:50%","transform:translateX(-50%)",`z-index:${bt}`,"display:flex","align-items:center","gap:10px","padding:10px 14px","border-radius:14px","background:#0f172a","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 8px 24px rgba(0,0,0,0.25)","max-width:min(520px,calc(100vw - 32px))"].join(";");const g=document.createElement("span");g.style.cssText="flex:1;font-size:13px;color:#e2e8f0;line-height:1.4",g.textContent=t;const b=document.createElement("button");b.type="button",b.textContent="Cancel",b.style.cssText=["padding:8px 12px","border:1px solid rgba(255,255,255,0.15)","border-radius:10px","background:transparent","color:#e2e8f0","font-size:13px","font-weight:600","cursor:pointer"].join(";"),v.appendChild(g),v.appendChild(b);const S=A=>{A.key==="Escape"&&!i&&p(null)},w=()=>u&&c.width>=e&&c.height>=e,x=()=>{u=!1,c={left:0,top:0,width:0,height:0},C()},C=()=>{if(!u||c.width<1||c.height<1){f.style.display="none",y.style.display="none";return}f.style.display="block",f.style.left=`${c.left}px`,f.style.top=`${c.top}px`,f.style.width=`${c.width}px`,f.style.height=`${c.height}px`,f.style.boxShadow=`0 0 0 9999px ${Gr}`,y.style.display="block",y.textContent=`${Math.round(c.width)} × ${Math.round(c.height)}`,y.style.left=`${c.left}px`,y.style.top=`${Math.max(8,c.top-26)}px`},k=A=>{const T=A instanceof Error?A.message:"Capture failed";g.textContent=T.length>120?`${T.slice(0,117)}…`:T,g.style.color="#fca5a5",window.setTimeout(()=>{g.textContent=t,g.style.color="#e2e8f0"},4500)},E=async A=>{if(!(i||s)){i=!0,b.disabled=!0,g.textContent="Clipping…",g.style.color="#e2e8f0",h.style.visibility="hidden",v.style.visibility="hidden";try{const T=await Kt(A),M=await lt(T),R=document.documentElement.clientWidth,U=document.documentElement.clientHeight;p({blob:M,region:{x:A.left/R,y:A.top/U,w:A.width/R,h:A.height/U},viewport:{width:R,height:U},pixelSize:{width:T.width,height:T.height}})}catch(T){i=!1,b.disabled=!1,h.style.visibility="visible",v.style.visibility="visible",k(T),x()}}},I=A=>{const T=A??d;if(T!==null)try{h.releasePointerCapture(T)}catch{}d=null},L=A=>{if(!(!l||i)){if(l=!1,I(A==null?void 0:A.pointerId),w()){E({...c});return}x()}},$=A=>{i||A.target.closest(`.${_e}`)!==v&&(l=!0,u=!0,o=A.clientX,a=A.clientY,c={left:o,top:a,width:0,height:0},d=A.pointerId,h.setPointerCapture(A.pointerId),C())},D=A=>{if(!l||i)return;const T=Math.min(o,A.clientX),M=Math.min(a,A.clientY),R=Math.max(o,A.clientX),U=Math.max(a,A.clientY);c={left:T,top:M,width:R-T,height:U-M},C()},O=()=>{Ke(!1),document.removeEventListener("keydown",S),window.removeEventListener("pointerup",F,!0),window.removeEventListener("pointercancel",F,!0),h.removeEventListener("pointerdown",$),h.removeEventListener("pointermove",D),h.removeEventListener("pointerup",L),h.removeEventListener("pointercancel",L),I(),h.remove(),v.remove()},F=A=>L(A);b.addEventListener("click",()=>p(null)),Ke(!0),h.appendChild(f),h.appendChild(y),document.body.appendChild(h),document.body.appendChild(v),document.addEventListener("keydown",S),window.addEventListener("pointerup",F,!0),window.addEventListener("pointercancel",F,!0),h.addEventListener("pointerdown",$),h.addEventListener("pointermove",D),h.addEventListener("pointerup",L),h.addEventListener("pointercancel",L)})}function ze(){document.querySelectorAll(`.${_e}`).forEach(n=>n.remove()),Ke(!1)}const Qr=["a[href]","button:not([disabled])",'input:not([type="hidden"]):not([disabled])',"select:not([disabled])","textarea:not([disabled])",'[role="button"]','[role="link"]','[role="tab"]','[role="menuitem"]','[role="checkbox"]','[role="radio"]',"label","h1","h2","h3","h4","h5","h6","img[alt]","[data-testid]","[aria-label]","[onclick]"].join(", "),Kr='[id]:not([id=""]), svg[id], polygon[id]',Zr="svg[id], polygon[id], svg[data-vanira-static-diagram], svg[data-vanira-static-diagram] polygon",Zt=new Set(["root","app","__next"]);function wt(n,e,t){const r=n.getScreenCTM(),s=n.ownerSVGElement;if(!r||!s)return[];const i=[];for(let o=0;o<n.points.length;o++){const a=n.points.getItem(o),l=s.createSVGPoint();l.x=a.x,l.y=a.y;const c=l.matrixTransform(r);i.push({x:c.x/e,y:c.y/t})}return i}function Xt(n,e,t){if(n instanceof SVGPolygonElement){const r=wt(n,e,t);return r.length>=2?r:void 0}if(n instanceof SVGSVGElement){const r=n.querySelector("polygon");if(!r)return;const s=wt(r,e,t);return s.length>=2?s:void 0}}function Xr(n,e=40){return n.elements.slice(0,e).map(t=>{var s;let r=`${t.css_selector} (${t.tag}) "${t.label.slice(0,48)}" center=(${t.center_x.toFixed(3)},${t.center_y.toFixed(3)}) bbox=(${t.x.toFixed(3)},${t.y.toFixed(3)},${t.width.toFixed(3)},${t.height.toFixed(3)})`;if((s=t.stroke_points)!=null&&s.length){const i=t.stroke_points.map(o=>[Number(o.x.toFixed(3)),Number(o.y.toFixed(3))]);r+=` stroke_points=${JSON.stringify(i)} close=true`}return r}).join(`
2
+ `)}function _t(n,e="#f97316"){const t=document.querySelector(n);if(!t)return null;const r=document.documentElement.clientWidth,s=document.documentElement.clientHeight,i=Xt(t,r,s);if(i!=null&&i.length)return{points:i.map(a=>[a.x,a.y]),close:!0,color:e};const o=t.getBoundingClientRect();return o.width<1||o.height<1?null:{points:[[o.left/r,o.top/s],[(o.left+o.width)/r,o.top/s],[(o.left+o.width)/r,(o.top+o.height)/s],[o.left/r,(o.top+o.height)/s]],close:!0,color:e}}function xt(n){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([^\w-])/g,"\\$1")}function en(n){if(n.id){const s=`#${xt(n.id)}`;try{if(document.querySelectorAll(s).length===1)return s}catch{}}const e=n.getAttribute("data-testid");if(e){const s=`[data-testid="${e.replace(/"/g,'\\"')}"]`;try{if(document.querySelectorAll(s).length===1)return s}catch{}}const t=[];let r=n;for(;r&&r!==document.body&&r!==document.documentElement;){let s=r.tagName.toLowerCase();if(r.classList.length>0){const o=[...r.classList].filter(a=>!a.startsWith("vnr-")).slice(0,2).map(a=>`.${xt(a)}`).join("");s+=o}const i=r.parentElement;if(i){const o=[...i.children].filter(a=>a.tagName===r.tagName);o.length>1&&(s+=`:nth-of-type(${o.indexOf(r)+1})`)}t.unshift(s);try{const o=t.join(" > ");if(document.querySelectorAll(o).length===1)return o}catch{}if(r=r.parentElement,t.length>=8)break}return t.join(" > ")||n.tagName.toLowerCase()}function er(n,e,t){const r=n.getBoundingClientRect();if(r.width<2||r.height<2||r.bottom<=0||r.right<=0||r.top>=t||r.left>=e)return!1;if(n instanceof SVGElement||n instanceof HTMLElement){const s=window.getComputedStyle(n);if(s.display==="none"||s.visibility==="hidden"||Number(s.opacity)===0)return!1}else return!1;return n.getAttribute("aria-hidden")!=="true"}function tn(n,e,t){var a;const r=((a=n.id)==null?void 0:a.toLowerCase())??"";if(Zt.has(r)||n===document.body||n===document.documentElement)return!0;const s=n.tagName.toLowerCase();if(s!=="div"&&s!=="main")return!1;const i=n.getBoundingClientRect();return i.width*i.height/Math.max(1,e*t)>.9}function tr(n){return Gt(n)?!0:typeof n.closest!="function"?!1:!!n.closest("script, style, noscript, template, head")}function rn(n,e){const t=n.tagName.toLowerCase();return t==="svg"||t==="polygon"?"diagram":t==="button"||e==="button"?"button":t==="a"||e==="link"?"link":t==="input"||t==="select"||t==="textarea"?"input":/^h[1-6]$/.test(t)?"heading":t==="img"?"image":t==="label"?"label":e?"interactive":"text"}function nn(n){const e=n.getAttribute("aria-label")||n.getAttribute("title")||"";if(e.trim())return e.trim().replace(/\s+/g," ").slice(0,240);if(n instanceof SVGPolygonElement&&n.id)return n.id.replace(/-/g," ").slice(0,240);if(n instanceof SVGSVGElement&&n.id)return(e.trim()||n.id.replace(/-/g," ")).slice(0,240);if(!(n instanceof HTMLElement))return n.id?n.id.replace(/-/g," ").slice(0,240):"";if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement){const r=n.getAttribute("placeholder")||n.getAttribute("name")||"";if(r.trim())return r.trim().slice(0,240)}return n instanceof HTMLImageElement&&n.alt.trim()?n.alt.trim().slice(0,240):(n.innerText||n.textContent||"").replace(/\s+/g," ").trim().slice(0,240)}function sn(n){var e,t;if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){const r=(e=n.value)==null?void 0:e.trim();return r?r.slice(0,240):void 0}if(n instanceof HTMLAnchorElement){const r=(t=n.getAttribute("href"))==null?void 0:t.trim();return r?r.slice(0,240):void 0}}function on(n,e,t){const r=Math.round(n.left),s=Math.round(n.top),i=Math.round(n.width),o=Math.round(n.height),a=r+i/2,l=s+o/2;return{x:n.left/e,y:n.top/t,width:n.width/e,height:n.height/t,center_x:a/e,center_y:l/t,px:{left:r,top:s,width:i,height:o,center_x:Math.round(a),center_y:Math.round(l)}}}function St(n){var t;let e=n.label?2:0;switch(n.kind){case"diagram":e+=22;break;case"button":case"link":case"input":e+=12;break;case"heading":e+=9;break;case"interactive":e+=8;break;case"image":case"label":e+=5;break;default:e+=3}return n.kind!=="text"&&(e+=Math.min(4,n.px.width*n.px.height/12e3)),(t=n.stroke_points)!=null&&t.length&&(e+=18),n.id&&Zt.has(n.id.toLowerCase())&&(e-=50),e}function Pe(n,e,t,r,s){if(tr(n)||tn(n,r,s)||!er(n,r,s))return;const i=nn(n),o=sn(n),a=Xt(n,r,s),l=n.id||void 0;if(!i&&!o&&!l&&!a&&n.tagName.toLowerCase()!=="input")return;const c=(n.getAttribute("role")||"").trim()||void 0,u=en(n);if(t.has(u))return;t.add(u);const d=on(n.getBoundingClientRect(),r,s);e.push({tag:n.tagName.toLowerCase(),kind:rn(n,c??""),role:c,label:i||o||l||u,value:o,id:l,css_selector:u,stroke_points:a,...d})}function an(n,e,t,r){for(const s of document.querySelectorAll(Zr))Pe(s,n,e,t,r);for(const s of document.querySelectorAll("svg"))if(!(tr(s)||!er(s,t,r)))for(const i of s.querySelectorAll("polygon"))Pe(i,n,e,t,r)}function rr(n){const e=Math.max(1,Math.min(200,(n==null?void 0:n.maxElements)??80)),t=document.documentElement.clientWidth,r=document.documentElement.clientHeight,s=new Set,i=[];an(i,s,t,r);for(const a of document.querySelectorAll(Qr))Pe(a,i,s,t,r);for(const a of document.querySelectorAll(Kr))Pe(a,i,s,t,r);i.sort((a,l)=>St(l)-St(a));const o=i.slice(0,e).map((a,l)=>({...a,element_id:`e${l+1}`}));return{url:window.location.href,title:document.title,viewport:{width:t,height:r},scroll:{x:window.scrollX,y:window.scrollY},coordinate_system:"normalized_viewport",elements:o}}function ln(n){if(n instanceof SVGPathElement&&typeof n.getTotalLength=="function"){const e=n.getTotalLength();if(e>0)return e}if(n instanceof SVGLineElement){const e=Number(n.getAttribute("x1")),t=Number(n.getAttribute("y1")),r=Number(n.getAttribute("x2")),s=Number(n.getAttribute("y2"));return Math.hypot(r-e,s-t)}if(n instanceof SVGCircleElement){const e=Number(n.getAttribute("r"));return 2*Math.PI*e}if(n instanceof SVGEllipseElement){const e=Number(n.getAttribute("rx")),t=Number(n.getAttribute("ry"));return Math.PI*(3*(e+t)-Math.sqrt((3*e+t)*(e+3*t)))}if(n instanceof SVGRectElement){const e=Number(n.getAttribute("width")),t=Number(n.getAttribute("height"));return 2*(e+t)}return 100}function Ct(n){n.style.strokeDasharray="",n.style.strokeDashoffset="",n.style.transition="",n.removeAttribute("stroke-dasharray"),n.removeAttribute("stroke-dashoffset")}function Ze(n,e){if(e<=0)return Ct(n),Promise.resolve();n instanceof SVGLineElement&&(n.style.vectorEffect="none");const t=Math.max(1,ln(n));return n.setAttribute("stroke-dasharray",String(t)),n.setAttribute("stroke-dashoffset",String(t)),n.getBoundingClientRect(),new Promise(r=>{requestAnimationFrame(()=>{n.style.transition=`stroke-dashoffset ${e}ms ease-out`,n.setAttribute("stroke-dashoffset","0"),setTimeout(()=>{Ct(n),r()},e+30)})})}function ct(n){return new Promise(e=>setTimeout(e,n))}const ae=4,Ve=750,kt=90,cn="2147483647";let Et=!1;function dn(){if(Et||typeof document>"u")return;Et=!0;const n=document.createElement("style");n.id="vnr-screen-overlay-styles",n.textContent=`
3
+ @keyframes vnr-screen-ripple {
4
+ 0% { transform: translate(-50%, -50%) scale(0.35); opacity: 0.95; }
5
+ 100% { transform: translate(-50%, -50%) scale(2.4); opacity: 0; }
6
+ }
7
+ @keyframes vnr-screen-cursor-pulse {
8
+ 0%, 100% { transform: translate(0, 0) scale(1); }
9
+ 50% { transform: translate(0, 0) scale(1.08); }
10
+ }
11
+ .vnr-screen-overlay-root {
12
+ position: fixed;
13
+ inset: 0;
14
+ z-index: ${cn};
15
+ pointer-events: none;
16
+ overflow: hidden;
17
+ }
18
+ .vnr-screen-overlay-root.vnr-screen-overlay-interactive {
19
+ pointer-events: auto;
20
+ cursor: crosshair;
21
+ touch-action: none;
22
+ }
23
+ .vnr-screen-ink-svg {
24
+ position: absolute;
25
+ inset: 0;
26
+ width: 100%;
27
+ height: 100%;
28
+ overflow: visible;
29
+ }
30
+ .vnr-screen-ink-stroke {
31
+ fill: none;
32
+ stroke-linecap: round;
33
+ stroke-linejoin: round;
34
+ }
35
+ .vnr-screen-cursor {
36
+ position: absolute;
37
+ width: 28px;
38
+ height: 28px;
39
+ margin-left: -2px;
40
+ margin-top: -2px;
41
+ filter: drop-shadow(0 1px 3px rgba(0,0,0,0.45));
42
+ animation: vnr-screen-cursor-pulse 1.2s ease-in-out infinite;
43
+ }
44
+ .vnr-screen-cursor.vnr-screen-cursor-flying {
45
+ animation: none;
46
+ }
47
+ .vnr-screen-cursor-label {
48
+ position: absolute;
49
+ margin-top: 22px;
50
+ margin-left: 8px;
51
+ padding: 4px 8px;
52
+ border-radius: 6px;
53
+ font-size: 12px;
54
+ font-weight: 600;
55
+ color: #fff;
56
+ white-space: nowrap;
57
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
58
+ }
59
+ .vnr-screen-click-ripple {
60
+ position: absolute;
61
+ width: 48px;
62
+ height: 48px;
63
+ border-radius: 50%;
64
+ border: 3px solid currentColor;
65
+ animation: vnr-screen-ripple 650ms ease-out forwards;
66
+ }
67
+ .vnr-screen-labels-layer {
68
+ position: absolute;
69
+ inset: 0;
70
+ pointer-events: none;
71
+ }
72
+ .vnr-screen-ink-label {
73
+ position: absolute;
74
+ transform: translate(-50%, -50%);
75
+ font-family: Georgia, "Times New Roman", serif;
76
+ font-weight: 600;
77
+ line-height: 1;
78
+ text-shadow: 1px 1px 0 rgba(0,0,0,0.35);
79
+ white-space: nowrap;
80
+ pointer-events: none;
81
+ }
82
+ `,document.head.appendChild(n)}function N(n,e){const t=Number(n);return Number.isFinite(t)?t:e}function P(n,e=""){return typeof n=="string"?n:e}function q(n){if(n===!0||n===1)return!0;if(typeof n=="string"){const e=n.trim().toLowerCase();return e==="true"||e==="1"||e==="yes"}return!1}function Tt(n){if(n===!1||n===0)return!0;if(typeof n=="string"){const e=n.trim().toLowerCase();return e==="false"||e==="0"||e==="no"}return!1}function W(n,e){return n>=0&&n<=1?n*e:n}function re(n,e){const t=window.innerWidth,r=window.innerHeight;return{px:W(n,t),py:W(e,r)}}function Xe(n){const e=document.querySelector(n);if(!e)return null;const t=e.getBoundingClientRect();return{px:t.left+t.width/2,py:t.top+t.height/2}}function un(n){const e=P(n.css_selector||n.selector);if(e){const s=Xe(e);if(s)return s}const t=n.x??n.client_x,r=n.y??n.client_y;return t==null||r==null?null:re(N(t,NaN),N(r,NaN))}function At(n){if(Array.isArray(n))return n;if(typeof n=="string"){const e=n.trim();if(!e)return[];try{const r=JSON.parse(e);if(Array.isArray(r))return r.length>0&&Array.isArray(r[0])?[{points:r,close:!0}]:r}catch{}const t=e.split(/\s+/).map(r=>{const[s,i]=r.split(","),o=Number(s),a=Number(i);return Number.isFinite(o)&&Number.isFinite(a)?[o,a]:null}).filter(r=>r!=null);if(t.length>=2)return[{points:t,close:!0}]}return[]}function hn(n){if(Array.isArray(n))return n;if(typeof n=="string"){const e=n.trim();if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return[]}function et(n,e){const t=P(n,e).trim().toLowerCase();return!t||t==="#000"||t==="#000000"||t==="black"?"#ece6d9":P(n,e)}function nr(n,e){if(!n||typeof n!="object")return null;const t=n,r=P(t.text??t.label??t.annotation??(typeof t.annotations=="string"?t.annotations:"")).trim();if(!r)return null;let s=t.x??t.client_x,i=t.y??t.client_y;if((s==null||i==null)&&Array.isArray(t.points)&&t.points.length>0){const l=dt(t.points[0]);if(l){const c=window.innerWidth,u=window.innerHeight;s=l.px/c,i=l.py/u}}if(s==null||i==null)return null;const o=Number(s),a=Number(i);return!Number.isFinite(o)||!Number.isFinite(a)?null:{x:o,y:a,text:r,color:et(t.color,e),font_size:t.font_size!=null?N(t.font_size,18):void 0}}function pn(n,e){if(!n||typeof n!="object")return null;const t=n;return t.text!=null||t.label!=null||t.annotation!=null||typeof t.annotations=="string"?nr(n,e):null}function fn(n){return Array.isArray(n)&&n.length>0&&Array.isArray(n[0])?{points:n,close:!0}:n}function mn(n){return W(n,Math.min(window.innerWidth,window.innerHeight))}function vn(n){if(n.length<2)return null;const e=window.innerWidth,t=window.innerHeight,r=n.map(c=>c.px),s=n.map(c=>c.py),i=(Math.min(...r)+Math.max(...r))/2,o=(Math.min(...s)+Math.max(...s))/2,a=Math.max(...n.map(c=>Math.hypot(c.px-i,c.py-o))),l=Math.min(e,t);return{cx:i/e,cy:o/t,r:a/l}}function yn(n,e,t,r){const s=P(n.kind||n.shape).toLowerCase(),i=s==="circle"||s==="ellipse"||n.r!=null||n.radius!=null||n.rx!=null||n.ry!=null;let o=n.cx??n.center_x??n.x,a=n.cy??n.center_y??n.y,l=n.r??n.radius;const c=n.rx,u=n.ry;if(Array.isArray(r)&&r.length>=3){const f=[];for(const v of r){const g=dt(v);g&&f.push(g)}const y=vn(f);y&&(i||q(n.close)&&f.length>=8)&&(o=o??y.cx,a=a??y.cy,l=l??y.r)}if(o==null||a==null)return null;const d=Number(o),p=Number(a);if(!Number.isFinite(d)||!Number.isFinite(p))return null;const h={kind:s==="ellipse"||c!=null||u!=null?"ellipse":"circle",cx:d,cy:p,color:P(n.color,e),stroke_width:n.stroke_width!=null?N(n.stroke_width,t):t};return c!=null||u!=null?(h.rx=Number(c??u),h.ry=Number(u??c),h):l!=null&&Number.isFinite(Number(l))?(h.r=Number(l),h):null}function It(n,e,t){if(!n||typeof n!="object")return null;const r=n,s=P(r.path_d||r.path||r.d),i=P(r.color,e),o=r.stroke_width!=null?N(r.stroke_width,t):t;if(s)return{path_d:s,close:q(r.close),color:i,stroke_width:o,css_selector:P(r.css_selector)||void 0};const a=P(r.css_selector||r.selector),l=r.points,c=yn(r,e,t,l);if(c)return c;if(a&&!Array.isArray(l))return{css_selector:a,color:i,stroke_width:o};let u=l;if(!Array.isArray(u)){const d=r.from_x,p=r.from_y,h=r.to_x,f=r.to_y;d!=null&&p!=null&&h!=null&&f!=null&&(u=[[d,p],[h,f]])}if(Array.isArray(u)&&u.length>=2){const d=P(r.kind),p=q(r.close)||d==="triangle"||d==="polygon";return{points:u,close:p,color:i,stroke_width:o,css_selector:a||void 0}}return a?{css_selector:a,color:i,stroke_width:o}:null}function dt(n){if(Array.isArray(n)&&n.length>=2){const e=Number(n[0]),t=Number(n[1]);return!Number.isFinite(e)||!Number.isFinite(t)?null:re(e,t)}if(n&&typeof n=="object"&&"x"in n&&"y"in n){const e=Number(n.x),t=Number(n.y);return!Number.isFinite(e)||!Number.isFinite(t)?null:re(e,t)}return null}function gn(n){const e=n.points;if(!Array.isArray(e))return[];const t=[];for(const r of e){const s=dt(r);s&&t.push(s)}return t}function le(n,e){return{class:"vnr-screen-ink-stroke",fill:"none",stroke:n,"stroke-width":String(e),"stroke-linecap":"round","stroke-linejoin":"round"}}function ce(n,e){for(const[t,r]of Object.entries(e))n.setAttribute(t,r)}function bn(n,e){if(n.length===0)return"";const t=n.map((r,s)=>`${s===0?"M":"L"} ${r.px} ${r.py}`).join(" ");return e&&n.length>=3?`${t} Z`:t}function wn(n){return`<svg class="vnr-screen-cursor" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
83
+ <path d="M4 4L4 19L9 14L13 20L15 19L11 13L17 13L4 4Z" fill="${n}" stroke="#fff" stroke-width="1.2"/>
84
+ </svg>`}class _n{constructor(){_(this,"root",null);_(this,"inkSvg",null);_(this,"labelsLayer",null);_(this,"cursorEl",null);_(this,"cursorTimer",null);_(this,"lastCursorPoint",null);_(this,"flyFrameId",null);_(this,"userDrawActive",!1);_(this,"userDrawColor","#f97316");_(this,"userStrokeWidth",ae);_(this,"userDrawPath",null);_(this,"userDrawPoints",[]);_(this,"userDrawBound",!1);_(this,"userDrawLayer",null);_(this,"onUserPointerDown",e=>this.handleUserPointerDown(e));_(this,"onUserPointerMove",e=>this.handleUserPointerMove(e));_(this,"onUserPointerUp",e=>this.handleUserPointerUp(e))}ensureRoot(){var e;return dn(),(e=this.root)!=null&&e.isConnected?this.root:(this.root=document.createElement("div"),this.root.className="vnr-screen-overlay-root",this.root.setAttribute("aria-hidden","true"),document.body.appendChild(this.root),this.root)}clear(){this.disableUserDrawing(),this.cursorTimer&&(clearTimeout(this.cursorTimer),this.cursorTimer=null),this.root&&(this.root.remove(),this.root=null),this.inkSvg=null,this.cursorEl=null,this.labelsLayer=null}clearInk(){this.inkSvg&&(this.inkSvg.remove(),this.inkSvg=null),this.labelsLayer&&(this.labelsLayer.remove(),this.labelsLayer=null)}addTextLabels(e,t="#ece6d9"){var i;if(e.length===0)return 0;const r=this.ensureRoot();(i=this.labelsLayer)!=null&&i.isConnected||(this.labelsLayer=document.createElement("div"),this.labelsLayer.className="vnr-screen-labels-layer",r.appendChild(this.labelsLayer));const s=this.labelsLayer;for(const o of e){const a=re(o.x,o.y),l=document.createElement("div");l.className="vnr-screen-ink-label",l.textContent=o.text;const c=et(o.color,t),u=o.font_size??20;l.style.cssText=`left:${a.px}px;top:${a.py}px;color:${c};font-size:${u}px;`,s.appendChild(l)}return e.length}hideCursor(){this.cancelFly(),this.cursorTimer&&(clearTimeout(this.cursorTimer),this.cursorTimer=null),this.cursorEl&&(this.cursorEl.remove(),this.cursorEl=null)}getLastCursorPoint(){return this.lastCursorPoint}cancelFly(){this.flyFrameId!=null&&(cancelAnimationFrame(this.flyFrameId),this.flyFrameId=null)}defaultFlyStart(){if(this.lastCursorPoint)return this.lastCursorPoint;const e=window.innerWidth,t=window.innerHeight;return{px:e*.82,py:t*.86}}placeCursorWrap(e,t,r,s){if(e.style.cssText=`position:absolute;left:${t.px}px;top:${t.py}px;`,e.innerHTML=wn(r),s){const i=document.createElement("div");i.className="vnr-screen-cursor-label",i.style.background=r,i.textContent=s,e.appendChild(i)}}async flyCursorTo(e,t={}){this.cancelFly(),this.cursorTimer&&(clearTimeout(this.cursorTimer),this.cursorTimer=null);const r=t.from??this.defaultFlyStart(),s=P(t.color,"#f97316"),i=N(t.fly_duration_ms,680),o=this.ensureRoot();this.hideCursor();const a=document.createElement("div");this.placeCursorWrap(a,r,s);const l=a.querySelector(".vnr-screen-cursor");l&&l.classList.add("vnr-screen-cursor-flying"),o.appendChild(a),this.cursorEl=a;const c=Math.max(72,Math.abs(r.py-e.py)*.38),u={px:(r.px+e.px)/2,py:Math.min(r.py,e.py)-c};await new Promise(h=>{const f=performance.now(),y=v=>{const g=Math.min(1,(v-f)/i),b=g<.5?2*g*g:1-Math.pow(-2*g+2,2)/2,S=1-b,w=S*S*r.px+2*S*b*u.px+b*b*e.px,x=S*S*r.py+2*S*b*u.py+b*b*e.py;a.style.left=`${w}px`,a.style.top=`${x}px`;const C=e.px-w,k=e.py-x;if(l&&Math.hypot(C,k)>6){const E=Math.atan2(k,C)*180/Math.PI;l.style.transform=`rotate(${E-45}deg)`,l.style.transformOrigin="2px 2px"}g<1?this.flyFrameId=requestAnimationFrame(y):(a.style.left=`${e.px}px`,a.style.top=`${e.py}px`,this.flyFrameId=null,h())};this.flyFrameId=requestAnimationFrame(y)}),l&&l.classList.remove("vnr-screen-cursor-flying");const d=P(t.label);if(d){let h=a.querySelector(".vnr-screen-cursor-label");h||(h=document.createElement("div"),h.className="vnr-screen-cursor-label",a.appendChild(h)),h.style.background=s,h.textContent=d}this.lastCursorPoint=e;const p=N(t.duration_ms,0);return p>0&&(this.cursorTimer=setTimeout(()=>this.hideCursor(),p)),e}async outlineSelectors(e,t="#f97316",r={}){const s=e.map(i=>({css_selector:i,close:!0,color:t})).filter(i=>!!i.css_selector);return s.length===0?0:this.addStrokes(s,t,{animate:r.animate!==!1,duration_ms:r.duration_ms??600,gap_ms:r.gap_ms??60,stroke_width:r.stroke_width??ae})}syncInkSvgViewport(e){const t=window.innerWidth,r=window.innerHeight;e.setAttribute("width",String(t)),e.setAttribute("height",String(r)),e.setAttribute("viewBox",`0 0 ${t} ${r}`)}ensureInkSvg(){var r;const e=this.ensureRoot();if((r=this.inkSvg)!=null&&r.isConnected)return this.syncInkSvgViewport(this.inkSvg),this.inkSvg;const t=document.createElementNS("http://www.w3.org/2000/svg","svg");return t.setAttribute("class","vnr-screen-ink-svg"),t.setAttribute("xmlns","http://www.w3.org/2000/svg"),t.setAttribute("preserveAspectRatio","none"),this.syncInkSvgViewport(t),e.appendChild(t),this.inkSvg=t,t}createCircleElement(e,t,r){if(e.cx==null||e.cy==null)return null;const s=window.innerWidth,i=window.innerHeight,o=W(e.cx,s),a=W(e.cy,i),l="http://www.w3.org/2000/svg";if(e.kind==="ellipse"||e.rx!=null||e.ry!=null){const u=e.rx??e.r,d=e.ry??e.r;if(u==null||d==null)return null;const p=document.createElementNS(l,"ellipse");return p.setAttribute("cx",String(o)),p.setAttribute("cy",String(a)),p.setAttribute("rx",String(W(Number(u),s))),p.setAttribute("ry",String(W(Number(d),i))),ce(p,le(t,r)),p}if(e.r==null)return null;const c=document.createElementNS(l,"circle");return c.setAttribute("cx",String(o)),c.setAttribute("cy",String(a)),c.setAttribute("r",String(mn(Number(e.r)))),ce(c,le(t,r)),c}createFreeformElement(e,t,r){const s=P(e.color,t),i=e.stroke_width!=null?N(e.stroke_width,r):r;if(e.kind==="circle"||e.kind==="ellipse"||e.r!=null||e.rx!=null||e.ry!=null)return this.createCircleElement(e,s,i);const a=document.createElementNS("http://www.w3.org/2000/svg","path"),l=P(e.path_d);if(l)return a.setAttribute("d",l),ce(a,le(s,i)),a;let c=e;if(e.css_selector){const d=_t(e.css_selector,s);d&&(c={...e,points:d.points,close:d.close,color:d.color})}const u=gn(c);return u.length<2?null:(a.setAttribute("d",bn(u,q(c.close))),ce(a,le(s,i)),a)}async addStrokes(e,t="#f97316",r={}){const s=this.ensureInkSvg(),i=r.animate!==!1,o=r.duration_ms??Ve,a=r.gap_ms??kt,l=r.stroke_width??ae;let c=0;for(const u of e){const d=this.createFreeformElement(u,t,l);d&&(s.appendChild(d),c+=1,i&&await Ze(d,o),i&&a>0&&await ct(a))}return c}async addInk(e,t,r){return this.addStrokes(e,t,r)}enableUserDrawing(e){const t=this.ensureRoot();if(this.userDrawActive=!0,this.userDrawColor=P(e==null?void 0:e.color,"#f97316"),this.userStrokeWidth=N(e==null?void 0:e.stroke_width,ae),e!=null&&e.region){const r=window.innerWidth,s=window.innerHeight,i=e.region,o=W(i.x,r),a=W(i.y,s),l=W(i.width,r),c=W(i.height,s),u=document.createElement("div");u.className="vnr-screen-user-draw-layer",u.style.cssText=`position:fixed;left:${o}px;top:${a}px;width:${l}px;height:${c}px;pointer-events:auto;cursor:crosshair;touch-action:none;z-index:1;`,t.appendChild(u),this.userDrawLayer=u,this.bindUserDrawEvents(u)}else t.classList.add("vnr-screen-overlay-interactive"),this.bindUserDrawEvents(t)}bindUserDrawEvents(e){this.userDrawBound||(e.addEventListener("pointerdown",this.onUserPointerDown),e.addEventListener("pointermove",this.onUserPointerMove),e.addEventListener("pointerup",this.onUserPointerUp),e.addEventListener("pointercancel",this.onUserPointerUp),this.userDrawBound=!0)}unbindUserDrawEvents(e){!e||!this.userDrawBound||(e.removeEventListener("pointerdown",this.onUserPointerDown),e.removeEventListener("pointermove",this.onUserPointerMove),e.removeEventListener("pointerup",this.onUserPointerUp),e.removeEventListener("pointercancel",this.onUserPointerUp),this.userDrawBound=!1)}disableUserDrawing(){this.userDrawActive=!1,this.userDrawPath=null,this.userDrawPoints=[],this.userDrawLayer?(this.unbindUserDrawEvents(this.userDrawLayer),this.userDrawLayer.remove(),this.userDrawLayer=null):this.root&&(this.unbindUserDrawEvents(this.root),this.root.classList.remove("vnr-screen-overlay-interactive"))}handleUserPointerDown(e){if(!this.userDrawActive||e.button!==0)return;e.preventDefault(),e.stopPropagation();const t=e.currentTarget??this.root;t==null||t.setPointerCapture(e.pointerId);const r=this.ensureInkSvg(),s=document.createElementNS("http://www.w3.org/2000/svg","path");ce(s,le(this.userDrawColor,this.userStrokeWidth)),this.userDrawPath=s,this.userDrawPoints=[`M ${e.clientX} ${e.clientY}`],s.setAttribute("d",this.userDrawPoints.join(" ")),r.appendChild(s)}handleUserPointerMove(e){!this.userDrawActive||!this.userDrawPath||(e.preventDefault(),this.userDrawPoints.push(`L ${e.clientX} ${e.clientY}`),this.userDrawPath.setAttribute("d",this.userDrawPoints.join(" ")))}async handleUserPointerUp(e){var r;if(!this.userDrawPath)return;e.preventDefault();const t=this.userDrawPath;this.userDrawPath=null,this.userDrawPoints=[];try{(r=e.currentTarget)==null||r.releasePointerCapture(e.pointerId)}catch{}await Ze(t,Ve)}showCursor(e,t="#f97316"){const r=e,s=un(r);if(!s)return null;const i=P(e.color,t),o=P(e.label)||void 0;if(q(e.fly)||q(r.fly))return this.flyCursorTo(s,{color:i,label:o,fly_duration_ms:N(e.fly_duration_ms??r.fly_duration_ms,680),duration_ms:N(e.duration_ms,0)}),s;this.hideCursor();const l=this.ensureRoot(),c=document.createElement("div");this.placeCursorWrap(c,s,i,o),l.appendChild(c),this.cursorEl=c,this.lastCursorPoint=s;const u=N(e.duration_ms,2500);return u>0&&(this.cursorTimer=setTimeout(()=>this.hideCursor(),u)),s}showClickRipple(e,t,r="#f97316"){const s=this.ensureRoot(),i=document.createElement("div");i.className="vnr-screen-click-ripple",i.style.cssText=`left:${e}px;top:${t}px;color:${r};`,s.appendChild(i),setTimeout(()=>i.remove(),700)}async applyInkFromArgs(e,t){const r=P(e.color||t.color,"#f97316"),s=et(e.label_color??t.label_color,"#ece6d9"),i=q(e.clear)||q(e.clear_before)||q(t.clear_before),o=!Tt(e.animate)&&!Tt(t.animate),a=N(e.duration_ms??t.duration_ms,Ve),l=N(e.gap_ms??t.gap_ms,kt),c=N(e.stroke_width??t.stroke_width,ae),u=q(e.interactive)||q(e.user_draw)||q(t.interactive),d=e.interactive_region??t.interactive_region;let p;if(d&&typeof d=="object"){const b=d;p={x:N(b.x,0),y:N(b.y,0),width:N(b.width??b.w,1),height:N(b.height??b.h,1)}}const h=[];for(const b of hn(e.labels??t.labels)){const S=nr(b,s);S&&h.push(S)}let f=At(e.strokes??t.strokes);f.length===0&&(f=At(e.annotations??t.annotations));const y=[];for(const b of f){const S=fn(b),w=pn(S,s);if(w){h.push(w);continue}const x=It(S,r,c);x&&y.push(x)}if(y.length===0){const b=P(e.css_selector??e.selector??t.css_selector??t.selector);if(b){const S=_t(b,r);S&&y.push({css_selector:b,...S,stroke_width:c})}}if(y.length===0){const b=It({kind:e.kind??e.shape??t.kind,cx:e.cx??e.center_x??t.cx,cy:e.cy??e.center_y??t.cy,r:e.r??e.radius??t.r,rx:e.rx??t.rx,ry:e.ry??t.ry,points:e.points??t.points,path_d:e.path_d??e.path??e.d??t.path_d??t.path,close:e.close??t.close,css_selector:e.css_selector??e.selector??t.css_selector??t.selector,from_x:e.from_x??t.from_x,from_y:e.from_y??t.from_y,to_x:e.to_x??t.to_x,to_y:e.to_y??t.to_y,color:r,stroke_width:c},r,c);b&&y.push(b)}i&&this.clearInk();let v=0;y.length>0&&(v=await this.addStrokes(y,r,{animate:o,duration_ms:a,gap_ms:l,stroke_width:c}));const g=this.addTextLabels(h,s);return u&&this.enableUserDrawing({color:r,stroke_width:c,region:p}),{strokes:v,labels:g}}}let se=null;function fe(){return se||(se=new _n),se}function Me(){se==null||se.clear()}function xn(n,e){const t=document.elementsFromPoint(n,e);for(const r of t)if(r instanceof HTMLElement&&!r.closest(".vnr-screen-overlay-root"))return r;return null}function Sn(n){try{n.focus({preventScroll:!0})}catch{}const e=n.tagName.toLowerCase(),t=e==="input"?n.type.toLowerCase():"";if((e==="button"||e==="a"||["submit","button","checkbox","radio","reset"].includes(t))&&typeof n.click=="function"){n.click();return}const s={bubbles:!0,cancelable:!0,view:window,button:0,buttons:1};n.dispatchEvent(new MouseEvent("mousedown",s)),n.dispatchEvent(new MouseEvent("mouseup",s)),n.dispatchEvent(new MouseEvent("click",s))}const tt=new Map,rt=new Map;function de(n,e=""){return typeof n=="string"?n:e}function Cn(n){tt.clear(),rt.clear();for(const e of n.elements)e.element_id&&tt.set(e.element_id,e),rt.set(e.css_selector,e)}function kn(n){return tt.get(n.trim())}function En(n,e=48){return n.elements.slice(0,e).map(t=>{var o;const r=t.element_id??"?",s=t.label.slice(0,56).replace(/\s+/g," ");let i=`${r} ${t.kind} "${s}" center=(${t.center_x.toFixed(3)},${t.center_y.toFixed(3)}) sel=${t.css_selector}`;if((o=t.stroke_points)!=null&&o.length){const a=t.stroke_points.map(l=>[Number(l.x.toFixed(3)),Number(l.y.toFixed(3))]);i+=` stroke_points=${JSON.stringify(a)}`}return i}).join(`
85
+ `)}function Tn(n){if(n.length===0)return null;let e=0,t=0;for(const i of n)e+=i.x,t+=i.y;const r=e/n.length,s=t/n.length;return re(r,s)}function xe(n,e={}){var o;const t=de(n.element_id??n.target??n.element??e.element_id??e.target).trim();if(t){const a=kn(t);if(a){const l=(o=a.stroke_points)!=null&&o.length?Tn(a.stroke_points):null,c=l?null:Xe(a.css_selector),u=l??c??re(a.center_x,a.center_y);return{element_id:a.element_id,css_selector:a.css_selector,point:u,label:de(n.label,a.label),kind:a.kind}}}const r=de(n.css_selector??n.selector??e.css_selector??e.selector).trim();if(r){const a=Xe(r);if(a){const l=rt.get(r);return{css_selector:r,point:a,label:de(n.label,(l==null?void 0:l.label)??""),element_id:l==null?void 0:l.element_id,kind:l==null?void 0:l.kind}}}const s=n.x??n.client_x??e.x,i=n.y??n.client_y??e.y;if(s!=null&&i!=null){const a=Number(s),l=Number(i);if(Number.isFinite(a)&&Number.isFinite(l))return{point:re(a,l),label:de(n.label)}}return null}function An(n,e={}){const t=n.targets??n.element_ids??n.elements??e.targets??e.element_ids;if(Array.isArray(t)){const s=[];for(const i of t)if(typeof i=="string"){const o=xe({element_id:i},e);o&&s.push(o)}else if(i&&typeof i=="object"){const o=xe(i,e);o&&s.push(o)}if(s.length>0)return s}const r=xe(n,e);return r?[r]:[]}function ve(n,e=""){return typeof n=="string"?n:e}function ie(n,e=!0){if(n==null)return e;if(n===!0||n===1)return!0;if(n===!1||n===0)return!1;const t=String(n).trim().toLowerCase();return t==="true"||t==="1"||t==="yes"?!0:t==="false"||t==="0"||t==="no"?!1:e}function In(n,e,t,r){const s=n.args??{},i=n.clientFields??{},o=ve(s.prompt??s.message??i.default_prompt).trim(),a=Number(s.max_elements??i.max_elements??64),l=ie(s.include_image??i.include_image,!1),c=Number(s.max_width??i.max_width??1280),u=ve(s.reason??i.reason,"page_scan");if(typeof document>"u"){t("Page scan is only available in browser environments");return}(async()=>{try{const d=rr({maxElements:Number.isFinite(a)?a:64});Cn(d);const p=En(d),f=`${o?`Page scanned. Context: ${o}`:"Visible page scanned — use element ids below for point_at and outline_targets."}
86
+
87
+ DOM-FIRST GUIDE (better than screenshot-only tutors):
88
+ - Call point_at with element_id (e.g. e3) from this scan — cursor flies to the live element.
89
+ - Call outline_targets with element_ids to draw animated outlines on the real DOM.
90
+ - Prefer element_id or css_selector; raw x/y only as fallback.
91
+
92
+ viewport=${d.viewport.width}x${d.viewport.height} · ${d.elements.length} elements
93
+ coordinate_system=${d.coordinate_system}
94
+
95
+ CATALOG (id kind "label" center sel):
96
+ ${p}`;e({status:"success",preset_id:m.PageScan,viewport:d.viewport,element_count:d.elements.length,catalog:p,elements:d.elements,coordinate_system:d.coordinate_system,message:f,guide:'Next: point_at { element_id: "eN", label: "..." } or outline_targets { targets: ["e1","e5"] }'}),l&&(r!=null&&r.uploadMediaForToolResult)&&(async()=>{try{let y=await Jt();Number.isFinite(c)&&c>0&&(y=Qt(y,c));const v=await lt(y),g=new File([v],`page-scan-${Date.now()}.jpg`,{type:"image/jpeg"});await r.uploadMediaForToolResult(g,u)}catch{}})()}catch(d){const p=d instanceof Error?d.message:"Page scan failed";t(p,{status:"cancelled"})}})()}function Ln(n,e,t){const r=n.args??{},s=n.clientFields??{},i=ve(r.color??s.color,"#f97316"),o=ie(r.fly??s.fly,!0),a=ie(r.outline??s.outline,!0),l=Number(r.fly_duration_ms??s.fly_duration_ms??680),c=Number(r.duration_ms??s.duration_ms??0),u=ie(r.clear_before??s.clear_before,!1),d=xe(r,s);if(!d){t("No valid target — provide element_id from page_scan, css_selector, or x/y");return}const p=ve(r.label,d.label)||void 0,h=fe();(async()=>(u&&h.clearInk(),a&&d.css_selector&&await h.outlineSelectors([d.css_selector],i,{animate:!0,duration_ms:520,gap_ms:0}),o?await h.flyCursorTo(d.point,{color:i,label:p,fly_duration_ms:l,duration_ms:c}):h.showCursor({x:d.point.px/window.innerWidth,y:d.point.py/window.innerHeight,label:p,color:i,duration_ms:c}),e({status:"success",preset_id:m.PointAt,message:p?`Pointing at: ${p}`:"Cursor placed on target",element_id:d.element_id,css_selector:d.css_selector,x:d.point.px,y:d.point.py,label:p})))()}function Pn(n,e,t){const r=n.args??{},s=n.clientFields??{},i=ve(r.color??s.color,"#f97316"),o=ie(r.animate??s.animate,!0),a=Number(r.duration_ms??s.duration_ms??600),l=ie(r.clear_before??s.clear_before,!1),c=An(r,s);if(c.length===0){t('No valid targets — provide targets: ["e1","e3"] or element_id / css_selector');return}const u=c.map(p=>p.css_selector).filter(p=>!!p);if(u.length===0){t("Targets resolved but no live css_selector — run page_scan first");return}const d=fe();(async()=>{l&&d.clearInk();const p=await d.outlineSelectors(u,i,{animate:o,duration_ms:a,gap_ms:50});e({status:"success",preset_id:m.OutlineTargets,message:`Outlined ${p} element(s) on the live page`,outlined_count:p,element_ids:c.map(h=>h.element_id).filter(Boolean),selectors:u})})()}function Mn(n,e){Me(),e({status:"success",preset_id:m.ClearGuide,message:"Guide overlay cleared (cursor, ink, outlines)"})}const Nn="vanira:board-active";function qe(n,e=!1){typeof window>"u"||window.dispatchEvent(new CustomEvent(Nn,{detail:{active:n,reduced:e}}))}const Lt="vanira:agent-playback-ended",Dn="You might have missed the whiteboard — call type_on_whiteboard or draw_on_board so the student can see what you explained. if you are on other task or waiting for user to show something then fine";function Bn(n){return!!(n.has_notes_on_board||n.has_diagram_geometry)}class $n{constructor(e,t){_(this,"active",!1);_(this,"sendContext",null);_(this,"getSnapshot");_(this,"isBoardBusy");_(this,"onAgentTurnEnd");this.getSnapshot=e,this.isBoardBusy=t,this.onAgentTurnEnd=()=>this.checkAfterAgentTurn()}start(e){if(this.active){this.sendContext=e;return}this.active=!0,this.sendContext=e,window.addEventListener(Lt,this.onAgentTurnEnd)}stop(){this.active&&(this.active=!1,this.sendContext=null,window.removeEventListener(Lt,this.onAgentTurnEnd))}checkAfterAgentTurn(){if(!this.active||!this.sendContext||this.isBoardBusy())return;const e=this.getSnapshot();if(Bn(e))return;const t={board_turn_check:{has_whiteboard:!1,...e,message:Dn}};try{this.sendContext(t)}catch{}}}function Rn(){var n;if(typeof window>"u")return!1;try{if(window.__VANIRA_DEBUG__===!0||localStorage.getItem("vanira:debug")==="1"||new URLSearchParams(window.location.search).has("vanira_debug"))return!0}catch{}try{if(((n={url:typeof document>"u"?require("url").pathToFileURL(__filename).href:Ue&&Ue.tagName.toUpperCase()==="SCRIPT"&&Ue.src||new URL("headless/index.cjs",document.baseURI).href}.env)==null?void 0:n.DEV)===!0)return!0}catch{}return!1}let He=null;function sr(){return He===null&&(He=Rn()),He}function ir(n,e,t){if(!(typeof window>"u"))try{const r=window.__VANIRA_DEBUG_LOG__??[];for(r.push({t:Date.now(),tag:n,message:e,data:t});r.length>250;)r.shift();window.__VANIRA_DEBUG_LOG__=r}catch{}}function j(n,e,t){sr()&&ir(n,e,t)}function Un(n,e,t){sr()&&ir(n,`WARN ${e}`,t)}const K=800,Z=500,On="#4A9EFF",ue=2e3,Pt=80;function or(n){if(!document.getElementById("vnr-board-line-styles")){const t=document.createElement("style");t.id="vnr-board-line-styles",t.textContent=`
97
+ .vnr-whiteboard-draw-layer path.vnr-board-stroke,
98
+ .vnr-whiteboard-draw-layer line.vnr-board-stroke,
99
+ .vnr-whiteboard-draw-layer circle.vnr-board-stroke,
100
+ .vnr-whiteboard-draw-layer ellipse.vnr-board-stroke {
101
+ fill: none;
102
+ stroke: #ffffff;
103
+ stroke-width: 6px;
104
+ stroke-linecap: round;
105
+ stroke-linejoin: round;
106
+ vector-effect: non-scaling-stroke;
107
+ }
108
+ .vnr-whiteboard-draw-layer text.vnr-board-label {
109
+ fill: #4A9EFF !important;
110
+ font-family: 'Architects Daughter', 'Caveat', cursive, sans-serif;
111
+ font-size: 28px;
112
+ paint-order: stroke fill;
113
+ }
114
+ `,document.head.appendChild(t)}if(n.querySelector("#vnr-chalk-defs"))return;const e=document.createElementNS("http://www.w3.org/2000/svg","defs");e.id="vnr-chalk-defs",n.appendChild(e)}function X(n){let e=n.querySelector(".vnr-whiteboard-draw-layer");return e||(e=document.createElementNS("http://www.w3.org/2000/svg","svg"),e.setAttribute("class","vnr-whiteboard-draw-layer"),e.setAttribute("viewBox",`0 0 ${K} ${Z}`),e.setAttribute("preserveAspectRatio","xMidYMid meet"),e.style.position="absolute",e.style.inset="0",e.style.width="100%",e.style.height="100%",e.style.pointerEvents="none",e.style.zIndex="0",or(e),n.insertBefore(e,n.firstChild),e)}function Se(n){[...n.childNodes].forEach(e=>{e instanceof SVGDefsElement||e.remove()})}function ar(n){or(n)}const Ne=6,Fn="#ffffff";function B(n,e){if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"&&n.trim()!==""){const t=Number(n);if(Number.isFinite(t))return t}return e}function H(n,e=""){return typeof n=="string"?n:e}function oe(n){if(n===!0||n===1)return!0;if(typeof n=="string"){const e=n.trim().toLowerCase();return e==="true"||e==="1"||e==="yes"}return!1}function Mt(n){if(n===!1||n===0)return!0;if(typeof n=="string"){const e=n.trim().toLowerCase();return e==="false"||e==="0"||e==="no"}return!1}function Nt(n){if(n===!0||n===1)return!0;if(n===!1||n===0||n===null||n===void 0||n==="")return!1;const e=String(n).trim().toLowerCase();return e==="true"||e==="1"||e==="yes"}function te(n,e){return n>=0&&n<=1?n*e:n}function nt(n,e){return{bx:te(n,K),by:te(e,Z)}}function Dt(n){if(Array.isArray(n))return n;if(typeof n=="string"){const e=n.trim();if(!e)return[];try{const r=JSON.parse(e);if(Array.isArray(r))return r.length>0&&Array.isArray(r[0])?[{points:r,close:!0}]:r}catch{}const t=e.split(/\s+/).map(r=>{const[s,i]=r.split(","),o=Number(s),a=Number(i);return Number.isFinite(o)&&Number.isFinite(a)?[o,a]:null}).filter(r=>r!=null);if(t.length>=2)return[{points:t,close:!0}]}return[]}function zn(n){if(Array.isArray(n))return n;if(typeof n=="string"){const e=n.trim();if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}return[]}function lr(n,e){const t=H(n,e).trim().toLowerCase();return!t||t==="#000"||t==="#000000"||t==="black"?e:H(n,e)}function cr(n,e){if(!n||typeof n!="object")return null;const t=n,r=H(t.text??t.label??t.label_text??t.annotation??(typeof t.annotations=="string"?t.annotations:"")).trim();if(!r)return null;const s=t.x??t.label_x??t.client_x,i=t.y??t.label_y??t.client_y;if(s==null||i==null)return null;const o=Number(s),a=Number(i);return!Number.isFinite(o)||!Number.isFinite(a)?null:{x:o,y:a,text:r,color:lr(t.color??t.label_color,e),font_size:t.font_size!=null?B(t.font_size,28):void 0}}function Vn(n,e){if(!n||typeof n!="object")return null;const t=n;return t.text!=null||t.label!=null||t.label_text!=null||t.annotation!=null||typeof t.annotations=="string"?cr(n,e):null}function qn(n){return Array.isArray(n)&&n.length>0&&Array.isArray(n[0])?{points:n,close:!0}:n}function dr(n){if(Array.isArray(n)&&n.length>=2){const e=Number(n[0]),t=Number(n[1]);return!Number.isFinite(e)||!Number.isFinite(t)?null:nt(e,t)}if(n&&typeof n=="object"&&"x"in n&&"y"in n){const e=Number(n.x),t=Number(n.y);return!Number.isFinite(e)||!Number.isFinite(t)?null:nt(e,t)}return null}function Hn(n){return te(n,Math.min(K,Z))}function jn(n,e,t,r){const s=H(n.kind||n.shape).toLowerCase(),i=s==="circle"||s==="ellipse"||n.r!=null||n.radius!=null||n.rx!=null||n.ry!=null;let o=n.cx??n.center_x??n.x,a=n.cy??n.center_y??n.y,l=n.r??n.radius;const c=n.rx,u=n.ry;if(Array.isArray(r)&&r.length>=3){const f=[];for(const y of r){const v=dr(y);v&&f.push(v)}if(f.length>=8&&i){const y=f.map(w=>w.bx),v=f.map(w=>w.by),g=(Math.min(...y)+Math.max(...y))/2,b=(Math.min(...v)+Math.max(...v))/2,S=Math.max(...f.map(w=>Math.hypot(w.bx-g,w.by-b)));o=o??g/K,a=a??b/Z,l=l??S/Math.min(K,Z)}}if(!i||o==null||a==null)return null;const d=Number(o),p=Number(a);if(!Number.isFinite(d)||!Number.isFinite(p))return null;const h={kind:s==="ellipse"||c!=null||u!=null?"ellipse":"circle",cx:d,cy:p,color:H(n.color,e),stroke_width:n.stroke_width!=null?B(n.stroke_width,t):t};return c!=null||u!=null?(h.rx=Number(c??u),h.ry=Number(u??c),h):l!=null&&Number.isFinite(Number(l))?(h.r=Number(l),h):null}function st(n,e,t){if(!n||typeof n!="object")return null;const r=n,s=H(r.path_d||r.path||r.d),i=H(r.color,e),o=r.stroke_width!=null?B(r.stroke_width,t):t;if(s)return{path_d:s,close:oe(r.close),color:i,stroke_width:o};const a=r.points,l=jn(r,e,t,a);if(l)return l;let c=a;if(!Array.isArray(c)){const u=r.from_x??r.p1_x??r.x1,d=r.from_y??r.p1_y??r.y1,p=r.to_x??r.p2_x??r.x2,h=r.to_y??r.p2_y??r.y2;u!=null&&d!=null&&p!=null&&h!=null&&(c=[[u,d],[p,h]])}if(Array.isArray(c)&&c.length>=2){const u=H(r.kind||r.shape_type||r.type).toLowerCase(),d=oe(r.close??r.close_path)||u==="triangle"||u==="polygon"||u==="rectangle";return{points:c,close:d,color:i,stroke_width:o}}return null}function je(n,e,t,r,s){const i=B(n[e])??(r?B(n[r]):void 0),o=B(n[t])??(s?B(n[s]):void 0);return i===void 0||o===void 0?null:[i,o]}function Wn(n,e,t){const r=[],s=[],i=H(n.label_text??n.text).trim(),o=B(n.label_x??n.x),a=B(n.label_y??n.y);i&&o!=null&&a!=null&&s.push({x:o,y:a,text:i,color:t});const l=je(n,"p1_x","p1_y","x1","y1"),c=je(n,"p2_x","p2_y","x2","y2"),u=je(n,"p3_x","p3_y","x3","y3");if(l&&c&&u)return r.push({points:[l,c,u],close:!0,color:e}),{strokes:r,labels:s};if(l&&c)return r.push({points:[l,c],close:!1,color:e}),{strokes:r,labels:s};const d=st({...n,color:n.color??e},e,B(n.stroke_width,Ne)??Ne);if(d)return r.push(d),{strokes:r,labels:s};const p=B(n.rect_x),h=B(n.rect_y),f=B(n.rect_width??n.width),y=B(n.rect_height??n.height);return p!=null&&h!=null&&f!=null&&y!=null&&r.push({points:[[p,h],[p+f,h],[p+f,h+y],[p,h+y]],close:!0,color:e}),{strokes:r,labels:s}}function Yn(n,e={}){const t={...e,...n},r=H(t.color??e.color,Fn),s=lr(t.label_color??e.label_color,On),i=B(t.stroke_width??e.stroke_width,Ne)??Ne,o=Nt(t.clear_old_diagrams_on_board)||Nt(t.clear_drawings)||oe(t.clear)||oe(t.clear_before)||oe(e.clear_before),a=Mt(t.animate)||Mt(e.animate);let l=Math.max(0,B(t.shape_duration_ms??t.duration_ms??e.duration_ms,ue)??ue),c=Math.max(0,B(t.shape_gap_ms??t.gap_ms??e.gap_ms,Pt)??Pt),u=!a;u&&l>0&&l<ue&&(l=ue),l>=ue&&(u=!0);const d=[];for(const y of zn(t.labels??e.labels)){const v=cr(y,s);v&&d.push(v)}let p=Dt(t.strokes??e.strokes);p.length===0&&(p=Dt(t.annotations??e.annotations));const h=[];for(const y of p){const v=qn(y),g=Vn(v,s);if(g){d.push(g);continue}const b=st(v,r,i);b&&h.push(b)}if(h.length===0){const y=t.points??e.points;if(y!=null){const v=st({points:y,close:t.close??t.close_path??!0,color:r},r,i);v&&h.push(v)}}const f=Wn(t,r,s);for(const y of f.labels)d.some(v=>v.text===y.text&&v.x===y.x&&v.y===y.y)||d.push(y);return h.length===0&&h.push(...f.strokes),{strokes:h,labels:d,clearBefore:o,animate:u,durationMs:l,gapMs:c,strokeWidth:i,strokeColor:r,labelColor:s}}function Gn(n){const e=n.points;if(!Array.isArray(e))return[];const t=[];for(const r of e){const s=dr(r);s&&t.push(s)}return t}function Jn(n,e){if(n.length===0)return"";const t=n.map((r,s)=>`${s===0?"M":"L"} ${r.bx} ${r.by}`).join(" ");return e&&n.length>=3?`${t} Z`:t}function De(n,e){return{class:"vnr-board-stroke",fill:"none",stroke:n,"stroke-width":String(e),"stroke-linecap":"round","stroke-linejoin":"round"}}function Be(n,e){for(const[t,r]of Object.entries(e))n.setAttribute(t,r)}function Qn(n,e,t){if(n.cx==null||n.cy==null)return null;const r=te(n.cx,K),s=te(n.cy,Z),i="http://www.w3.org/2000/svg";if(n.kind==="ellipse"||n.rx!=null||n.ry!=null){const a=n.rx??n.r,l=n.ry??n.r;if(a==null||l==null)return null;const c=document.createElementNS(i,"ellipse");return c.setAttribute("cx",String(r)),c.setAttribute("cy",String(s)),c.setAttribute("rx",String(te(Number(a),K))),c.setAttribute("ry",String(te(Number(l),Z))),Be(c,De(e,t)),c}if(n.r==null)return null;const o=document.createElementNS(i,"circle");return o.setAttribute("cx",String(r)),o.setAttribute("cy",String(s)),o.setAttribute("r",String(Hn(Number(n.r)))),Be(o,De(e,t)),o}function ur(n,e,t){const r=H(n.color,e),s=n.stroke_width!=null?B(n.stroke_width,t)??t:t;if(n.kind==="circle"||n.kind==="ellipse"||n.r!=null||n.rx!=null||n.ry!=null)return Qn(n,r,s);const o=document.createElementNS("http://www.w3.org/2000/svg","path"),a=H(n.path_d);if(a)return o.setAttribute("d",a),Be(o,De(r,s)),o;const l=Gn(n);return l.length<2?null:(o.setAttribute("d",Jn(l,oe(n.close))),Be(o,De(r,s)),o)}function hr(n,e){const t="http://www.w3.org/2000/svg",r=nt(n.x,n.y),s=document.createElementNS(t,"text");return s.setAttribute("class","vnr-board-label"),s.setAttribute("x",String(r.bx)),s.setAttribute("y",String(r.by)),s.setAttribute("fill",n.color||e),s.setAttribute("font-size",String(n.font_size??28)),s.setAttribute("font-family","'Architects Daughter', 'Caveat', cursive, sans-serif"),s.setAttribute("text-anchor","middle"),s.setAttribute("dominant-baseline","hanging"),s.textContent=n.text,s}function Kn(n,e){return e<=0?(n.style.opacity="1",Promise.resolve()):(n.style.opacity="0",n.getBoundingClientRect(),n.style.transition=`opacity ${Math.min(e,400)}ms ease-out`,n.style.opacity="1",ct(Math.min(e,400)))}function Bt(n,e,t){ar(n),Se(n);for(const r of e.strokes){const s=ur(r,t.strokeColor,t.strokeWidth);s&&n.appendChild(s)}for(const r of e.labels)n.appendChild(hr(r,t.labelColor))}async function Zn(n,e,t,r){ar(n);let s=0,i=0;for(const o of e){if(r.isAborted())break;const a=ur(o,r.strokeColor,r.strokeWidth);a&&(n.appendChild(a),s+=1,r.animate&&r.durationMs>0&&(await Ze(a,r.durationMs),r.gapMs>0&&await ct(r.gapMs)))}for(const o of t){if(r.isAborted())break;const a=hr(o,r.labelColor);n.appendChild(a),i+=1,r.animate&&r.durationMs>0&&await Kn(a,r.durationMs)}return{strokesDrawn:s,labelsDrawn:i}}function we(){return{strokes:[],labels:[]}}function me(n){return n.toLowerCase().replace(/[^a-z0-9]/g,"_")}function Xn(n){const e=n==null?void 0:n.toLowerCase().trim();if(e){if(e==="tel")return"phone";if(e==="dropdown"||e==="drop_down"||e==="picklist"||e==="combobox")return"select";if(["text","textarea","select","radio","checkbox","email","phone","number","date"].includes(e))return e}}function pr(n,e,t=[]){const r=Xn(e);return r||(t.length>0?"select":n.includes("email")?"email":n.includes("phone")?"phone":n.includes("date")&&!n.includes("update")?"date":"text")}function es(n){return n?Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(e&&typeof e=="object"){const t=e;return{label:String(t.label??t.value??""),value:String(t.value??t.label??"")}}return String(e)}):typeof n=="string"?n.split(",").map(e=>e.trim()).filter(Boolean):[]:[]}function ts(n){const e=n.value??n.default??n.defaultValue??n.prefill;if(!(e==null||e===""))return String(e)}function We(n){const e=String(n.label??n.name??n.title??n.field??n.id??n.key??"").trim();if(!e)return null;const t=String(n.id??n.key??me(e)),r=es(n.options??n.choices??n.values),s=pr(t,String(n.type??""),r);return{id:t,label:e,type:s,required:n.required!==!1,placeholder:n.placeholder?String(n.placeholder):void 0,value:ts(n),options:r}}function $t(n){const e=n.trim(),t=me(e);return{id:t,label:e,type:pr(t),required:!0,placeholder:`Enter your ${e.toLowerCase()}`,options:[]}}function Ce(n){const e=n.trim();return e?e.startsWith("[")||e.startsWith("{")||e.startsWith('"')?!0:e.includes('"type"')||e.includes('"options"')||e.includes('"label"'):!1}function rs(n){let e=n.trim();for(let t=0;t<3&&typeof e=="string";t++){const r=e.trim();if(!Ce(r))break;try{e=JSON.parse(r)}catch{break}}return e}function ke(n){const e=rs(n);if(Array.isArray(e)||e&&typeof e=="object")return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")&&!t.startsWith("["))try{return JSON.parse(`[${t}]`)}catch{return null}}return null}function ns(n){return n.length<2?!1:n.every(e=>typeof e=="string"&&(e.includes('"')||e.includes("{")||e.includes("[")))}function ss(n){return ke(n.map(e=>e.trim()).join(","))}function pe(n){if(n==null)return[];if(typeof n=="string"){const e=n.trim();if(!e)return[];if(Ce(e)){const t=ke(e);return t!==null?pe(t):[]}return e.split(",").map(t=>t.trim()).filter(Boolean).map($t)}if(Array.isArray(n)){if(n.length===1&&typeof n[0]=="string"){const t=n[0].trim();if(Ce(t)){const r=ke(t);if(r!==null)return pe(r)}}if(ns(n)){const t=ss(n);if(t!==null)return pe(t)}const e=[];for(const t of n){if(typeof t=="string"){const r=t.trim();if(r.startsWith("{"))try{const s=We(JSON.parse(r));if(s){e.push(s);continue}}catch{}if(Ce(r)){const s=ke(r);if(s!==null){e.push(...pe(s));continue}}e.push($t(t));continue}if(t&&typeof t=="object"){const r=We(t);r&&e.push(r)}}return e}if(typeof n=="object"){const e=We(n);return e?[e]:[]}return[]}const is=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,os=/^\+?[0-9\s\-().]{7,20}$/,as=/^\d{4}-\d{2}-\d{2}$/;function fr(n,e){const t=n[e.id];return e.type==="checkbox"?t===!0||t==="true"?"true":"false":String(t??"").trim()}function ls(n,e){const t={};for(const r of n){const s=fr(e,r);if(r.type==="checkbox"){r.required&&s!=="true"&&(t[r.id]=`${r.label} is required`);continue}if(r.required&&!s){t[r.id]=`${r.label} is required`;continue}if(!s)continue;const i=cs(r.type,s,r.label);i&&(t[r.id]=i),(r.type==="select"||r.type==="radio")&&r.options.length>0&&(r.options.map(a=>typeof a=="string"?a:a.value).includes(s)||(t[r.id]=`Select a valid ${r.label}`))}return t}function cs(n,e,t){switch(n){case"email":return is.test(e)?null:`Enter a valid ${t}`;case"phone":return os.test(e)?null:`Enter a valid phone number for ${t}`;case"number":return Number.isFinite(Number(e))?null:`${t} must be a number`;case"date":return as.test(e)?Number.isNaN(Date.parse(e))?`Enter a valid ${t}`:null:`${t} must be YYYY-MM-DD`;default:return null}}function ds(n,e){const t={};for(const r of n)t[r.id]=fr(e,r);return t}function mr(n){if(n==null)return{};if(typeof n=="string"){const e=n.trim();if(!e)return{};try{return mr(JSON.parse(e))}catch{return{}}}return typeof n=="object"&&!Array.isArray(n)?n:{}}function us(n,e){const t=n.prefill??n.values??n.initial_values??n.defaults??e.prefill??e.values??e.initial_values??e.defaults;return mr(t)}function it(n,e){if(n.type==="checkbox"){if(typeof e=="boolean")return e;const t=String(e).trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="on"}return String(e??"").trim()}function hs(n,e){const t=[n.id,n.label,n.label.toLowerCase()];for(const s of t){if(!(s in e))continue;const i=e[s];if(!(i==null||i===""))return it(n,i)}const r=me(n.label);for(const[s,i]of Object.entries(e))if(!(i==null||i==="")&&(s===r||me(s)===r||me(s)===n.id))return it(n,i)}function ps(n,e={}){const t={};for(const r of n){if(r.value!==void 0){t[r.id]=it(r,r.value);continue}const s=hs(r,e);t[r.id]=s!==void 0?s:r.type==="checkbox"?!1:""}return t}const Rt="vanira:board_abort";function Ye(n){if(!n)return"";if(typeof n=="string"){if(n.includes("T")||!isNaN(Date.parse(n)))try{return new Date(n).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})}catch{}return n}if(typeof n=="object"){const e=n.start||n.startTime||n.time||n.slot,t=n.end||n.endTime;if(e){let r=String(e),s=t?String(t):"";try{(r.includes("T")||!isNaN(Date.parse(r)))&&(r=new Date(r).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"})),s&&(s.includes("T")||!isNaN(Date.parse(s)))&&(s=new Date(s).toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"}))}catch{}return s?`${r} - ${s}`:r}}return String(n)}function fs(n,e,t,r){let s=Date.UTC(n,e,t,0,0,0,0),i=Date.UTC(n,e,t,23,59,59,999);if(r)try{const o=new Date(Date.UTC(n,e,t,12,0,0)),l=new Intl.DateTimeFormat("en-US",{timeZone:r,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(o),c=S=>{var w;return(w=l.find(x=>x.type===S))==null?void 0:w.value},u=parseInt(c("year")||"0",10),d=parseInt(c("month")||"0",10)-1,p=parseInt(c("day")||"0",10),h=parseInt(c("hour")||"0",10),f=parseInt(c("minute")||"0",10),y=parseInt(c("second")||"0",10),v=h===24?0:h,b=Date.UTC(u,d,p,v,f,y,0)-o.getTime();s=Date.UTC(n,e,t,0,0,0,0)-b,i=Date.UTC(n,e,t,23,59,59,999)-b}catch{}return{start:new Date(s),end:new Date(i)}}function ms(n,e){if(!e){const t=-n.getTimezoneOffset(),r=t>=0?"+":"-",s=o=>String(o).padStart(2,"0"),i=o=>String(o).padStart(3,"0");return n.getFullYear()+"-"+s(n.getMonth()+1)+"-"+s(n.getDate())+"T"+s(n.getHours())+":"+s(n.getMinutes())+":"+s(n.getSeconds())+"."+i(n.getMilliseconds())+r+s(Math.floor(Math.abs(t)/60))+":"+s(Math.abs(t)%60)}try{const r=new Intl.DateTimeFormat("en-US",{timeZone:e,year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!1}).formatToParts(n),s=k=>{var E;return((E=r.find(I=>I.type===k))==null?void 0:E.value)||"0"},i=s("year"),o=s("month").padStart(2,"0"),a=s("day").padStart(2,"0");let l=parseInt(s("hour"),10);l===24&&(l=0);const c=String(l).padStart(2,"0"),u=s("minute").padStart(2,"0"),d=s("second").padStart(2,"0"),p=String(n.getMilliseconds()).padStart(3,"0"),h=parseInt(i,10),f=parseInt(o,10)-1,y=parseInt(a,10),g=Date.UTC(h,f,y,l,parseInt(u,10),parseInt(d,10),n.getMilliseconds())-n.getTime(),b=Math.round(g/6e4),S=b>=0?"+":"-",w=Math.abs(b),x=String(Math.floor(w/60)).padStart(2,"0"),C=String(w%60).padStart(2,"0");return`${i}-${o}-${a}T${c}:${u}:${d}.${p}${S}${x}:${C}`}catch{return n.toISOString()}}const vs=`
115
+ .vnr-overlay {
116
+ position: fixed; inset: 0; z-index: 2147483647;
117
+ background: rgba(0,0,0,0.45);
118
+ backdrop-filter: blur(4px);
119
+ display: flex; align-items: center; justify-content: center; padding: 16px;
120
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
121
+ box-sizing: border-box;
122
+ }
123
+ /* Whiteboard sits below vanira-convai widget (voice pill stays on top) */
124
+ .vnr-overlay.vnr-whiteboard-overlay {
125
+ z-index: 2147483640;
126
+ background: transparent !important;
127
+ backdrop-filter: none !important;
128
+ -webkit-backdrop-filter: none !important;
129
+ pointer-events: none;
130
+ }
131
+ .vnr-overlay.vnr-whiteboard-overlay .vnr-whiteboard-modal {
132
+ pointer-events: auto;
133
+ }
134
+ .vnr-overlay.vnr-whiteboard-overlay-expanded {
135
+ display: flex;
136
+ align-items: center;
137
+ justify-content: center;
138
+ padding: 16px;
139
+ padding-bottom: max(100px, calc(20px + env(safe-area-inset-bottom)));
140
+ }
141
+ .vnr-overlay.vnr-whiteboard-overlay-reduced {
142
+ display: block;
143
+ padding: 0;
144
+ }
145
+ .vnr-modal {
146
+ background: #fff; border-radius: 16px;
147
+ box-shadow: 0 25px 60px rgba(0,0,0,0.25);
148
+ width: 100%; max-width: 400px; max-height: 88vh;
149
+ overflow-y: auto; box-sizing: border-box;
150
+ padding: 20px;
151
+ }
152
+ .vnr-close-btn {
153
+ position: absolute; top: 16px; right: 16px;
154
+ background: none; border: none; cursor: pointer;
155
+ color: #d1d5db; line-height: 1; padding: 4px;
156
+ }
157
+ .vnr-close-btn:hover { color: #6b7280; }
158
+ .vnr-title { margin: 0 0 8px; font-size: 17px; font-weight: 700; color: #111; letter-spacing: -0.02em; }
159
+ .vnr-reason {
160
+ display: flex; align-items: flex-start; gap: 8px;
161
+ padding: 10px 12px; background: #f9fafb; border: 1px solid #f3f4f6;
162
+ border-radius: 10px; font-size: 13px; color: #6b7280; line-height: 1.5; margin-bottom: 14px;
163
+ }
164
+ .vnr-divider { border-top: 1px solid #f3f4f6; margin: 12px 0; }
165
+ .vnr-section-label { font-size: 10px; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 8px; }
166
+ /* Month nav */
167
+ .vnr-month-nav { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
168
+ .vnr-nav-btn {
169
+ width: 30px; height: 30px; display: flex; align-items: center; justify-content: center;
170
+ border: 1px solid #e5e7eb; border-radius: 8px; background: #fff; cursor: pointer; color: #6b7280;
171
+ }
172
+ .vnr-nav-btn:hover:not(:disabled) { border-color: #9ca3af; background: #f9fafb; }
173
+ .vnr-nav-btn:disabled { opacity: 0.25; cursor: not-allowed; }
174
+ .vnr-month-label { font-size: 14px; font-weight: 600; color: #111; }
175
+ /* Calendar grid */
176
+ .vnr-cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px 0; }
177
+ .vnr-wd { text-align: center; font-size: 10px; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.05em; padding-bottom: 6px; }
178
+ .vnr-day-btn {
179
+ display: block; margin: 0 auto; width: 34px; height: 34px; border-radius: 8px;
180
+ background: transparent; border: 1.5px solid transparent;
181
+ font-size: 13px; font-weight: 500; color: #111; cursor: pointer;
182
+ }
183
+ .vnr-day-btn:hover:not(:disabled):not(.vnr-day-sel) { background: #f3f4f6; }
184
+ .vnr-day-past { color: #d1d5db !important; cursor: not-allowed !important; }
185
+ .vnr-day-today { border-color: #111 !important; }
186
+ .vnr-day-sel { background: #111 !important; color: #fff !important; border-color: transparent !important; }
187
+ /* Slots */
188
+ .vnr-slots-grid { display: grid; gap: 6px; }
189
+ .vnr-slot-btn {
190
+ padding: 9px 6px; border-radius: 8px; border: 1px solid #e5e7eb;
191
+ background: #fff; color: #374151; font-size: 12px; font-weight: 500; cursor: pointer; text-align: center;
192
+ }
193
+ .vnr-slot-btn:hover:not(.vnr-slot-sel) { border-color: #9ca3af; }
194
+ .vnr-slot-sel { background: #111 !important; color: #fff !important; border-color: #111 !important; }
195
+ /* Actions */
196
+ .vnr-actions { display: flex; gap: 8px; margin-top: 14px; padding-top: 12px; border-top: 1px solid #f3f4f6; }
197
+ .vnr-cancel-btn {
198
+ flex: 1; padding: 10px; border-radius: 10px; background: #f3f4f6;
199
+ border: none; color: #6b7280; font-size: 13px; font-weight: 500; cursor: pointer;
200
+ }
201
+ .vnr-confirm-btn {
202
+ flex: 1; padding: 10px; border-radius: 10px; background: #111;
203
+ border: none; color: #fff; font-size: 13px; font-weight: 600; cursor: pointer;
204
+ display: flex; align-items: center; justify-content: center; gap: 6px;
205
+ }
206
+ .vnr-confirm-btn:disabled { background: #e5e7eb !important; color: #9ca3af !important; cursor: not-allowed; }
207
+ /* Form */
208
+ .vnr-field-label { display: block; font-size: 10px; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; }
209
+ .vnr-input {
210
+ width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 10px;
211
+ font-size: 13px; color: #111; background: #fff; box-sizing: border-box; outline: none;
212
+ font-family: inherit;
213
+ }
214
+ .vnr-input:focus { border-color: #111; }
215
+ .vnr-input-error { border-color: #dc2626 !important; }
216
+ .vnr-textarea { min-height: 88px; resize: vertical; }
217
+ .vnr-field-error { color: #dc2626; font-size: 12px; margin: 4px 0 0; }
218
+ .vnr-radio-group, .vnr-checkbox-row { display: flex; flex-direction: column; gap: 8px; }
219
+ .vnr-radio-row { display: flex; align-items: center; gap: 8px; font-size: 13px; color: #374151; cursor: pointer; }
220
+ .vnr-fields { display: flex; flex-direction: column; gap: 12px; margin-bottom: 4px; }
221
+ /* Spinner */
222
+ @keyframes vnr-spin { to { transform: rotate(360deg); } }
223
+ .vnr-spinner {
224
+ width: 16px; height: 16px; border-radius: 50%;
225
+ border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff;
226
+ animation: vnr-spin 0.7s linear infinite;
227
+ }
228
+ .vnr-center { text-align: center; padding: 28px 0; color: #9ca3af; font-size: 13px; }
229
+ /* Camera */
230
+ .vnr-video-wrap { width:100%; aspect-ratio:4/3; background:#0f172a; border-radius:12px; overflow:hidden; position:relative; }
231
+ .vnr-video-wrap video { width:100%; height:100%; object-fit:cover; display:block; }
232
+ .vnr-live-badge { position:absolute; top:10px; left:10px; display:flex; align-items:center; gap:6px; padding:3px 9px; border-radius:999px; background:rgba(15,23,42,0.72); border:1px solid rgba(255,255,255,0.1); font-size:11px; font-weight:600; color:#f8fafc; text-transform:uppercase; letter-spacing:.04em; }
233
+ .vnr-live-dot { width:7px; height:7px; border-radius:50%; background:#22c55e; flex-shrink:0; }
234
+ /* Upload dropzone */
235
+ .vnr-dropzone { border:2px dashed #cbd5e1; border-radius:14px; padding:32px 20px; text-align:center; cursor:pointer; background:#fafafa; transition:border-color 0.2s,background 0.2s; }
236
+ .vnr-dropzone:hover, .vnr-dropzone.drag { border-color:#374151; background:#f3f4f6; }
237
+ @keyframes vnr-click-pulse {
238
+ 0% { transform: scale(1); }
239
+ 25% { transform: scale(0.96); }
240
+ 50% { transform: scale(1.04); }
241
+ 100% { transform: scale(1); }
242
+ }
243
+ .vnr-click-pulse {
244
+ animation: vnr-click-pulse 0.45s ease-out;
245
+ outline: 2px solid #6366f1 !important;
246
+ outline-offset: 3px !important;
247
+ }
248
+ /* Whiteboard */
249
+ .vnr-whiteboard-modal {
250
+ display: flex !important;
251
+ flex-direction: column !important;
252
+ padding: 0 !important;
253
+ overflow: hidden !important;
254
+ flex-shrink: 0;
255
+ box-sizing: border-box;
256
+ transition: width 0.2s ease, max-width 0.2s ease, height 0.2s ease, max-height 0.2s ease;
257
+ }
258
+ .vnr-overlay.vnr-whiteboard-overlay-reduced .vnr-whiteboard-modal {
259
+ box-shadow: 0 20px 52px rgba(0,0,0,0.6) !important;
260
+ }
261
+ .vnr-overlay.vnr-whiteboard-overlay-hidden {
262
+ display: none !important;
263
+ }
264
+ .vnr-whiteboard-header {
265
+ flex: 0 0 auto;
266
+ display: flex;
267
+ align-items: center;
268
+ justify-content: flex-end;
269
+ gap: 6px;
270
+ padding: 8px 10px;
271
+ background: linear-gradient(180deg, #1e1e24 0%, #16161c 100%);
272
+ border-bottom: 1px solid rgba(255,255,255,0.1);
273
+ z-index: 30;
274
+ }
275
+ .vnr-overlay.vnr-whiteboard-overlay-reduced .vnr-whiteboard-header {
276
+ cursor: grab;
277
+ user-select: none;
278
+ touch-action: none;
279
+ }
280
+ .vnr-overlay.vnr-whiteboard-overlay-reduced .vnr-whiteboard-header.is-dragging {
281
+ cursor: grabbing;
282
+ }
283
+ .vnr-whiteboard-action-btn {
284
+ width: 32px;
285
+ height: 32px;
286
+ padding: 0;
287
+ display: inline-flex;
288
+ align-items: center;
289
+ justify-content: center;
290
+ border-radius: 8px;
291
+ border: 1px solid rgba(255,255,255,0.15);
292
+ background: rgba(255,255,255,0.08);
293
+ color: #e2e8f0;
294
+ cursor: pointer;
295
+ font-family: inherit;
296
+ line-height: 0;
297
+ }
298
+ .vnr-whiteboard-action-btn:hover { background: rgba(255,255,255,0.14); }
299
+ .vnr-whiteboard-action-btn.is-close {
300
+ border-color: rgba(248,113,113,0.35);
301
+ color: #fecaca;
302
+ }
303
+ .vnr-whiteboard-action-btn.is-close:hover { background: rgba(239,68,68,0.2); }
304
+ `,ys='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 14h6v6"/><path d="M20 10h-6V4"/><path d="M14 10l7-7"/><path d="M3 21l7-7"/></svg>',gs='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>',bs='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',ws="vanira:board-size",_s={small:{maxWidth:"min(440px, 94vw)",height:"min(340px, 58vh)"},medium:{maxWidth:"min(680px, 96vw)",height:"min(520px, 78vh)"},large:{maxWidth:"min(920px, 98vw)",height:"min(680px, 88vh)"}};function xs(){try{const n=localStorage.getItem(ws);if(n==="small"||n==="medium"||n==="large")return n}catch{}return"medium"}function Ut(n,e){return e===1?n:n.replace(/(\d+(?:\.\d+)?)(px|vw|vh)/g,(t,r,s)=>{const i=Number(r)*e;return`${s==="px"?Math.round(i):i}${s}`})}class Ss{constructor(e){_(this,"overlay",null);_(this,"styleInjected",!1);_(this,"chalkboardContent","");_(this,"boardChapterTitle","");_(this,"boardDrawInProgress",!1);_(this,"boardInk",we());_(this,"calViewYear",0);_(this,"calViewMonth",0);_(this,"calSelectedTs",null);_(this,"calSelectedTime",null);_(this,"lvSessionId",null);_(this,"lvStream",null);_(this,"lvCaptureInterval",null);_(this,"lvAutoStopTimeout",null);_(this,"lvFrameSeq",0);_(this,"lvVideo",null);_(this,"lvCanvas",null);_(this,"lvPip",null);_(this,"lvPermissionBanner",null);_(this,"lsSessionId",null);_(this,"lsStream",null);_(this,"lsCaptureInterval",null);_(this,"lsAutoStopTimeout",null);_(this,"lsFrameSeq",0);_(this,"lsVideo",null);_(this,"lsCanvas",null);_(this,"lsPip",null);_(this,"lsPermissionBanner",null);_(this,"captureActive",!1);_(this,"captureStream",null);_(this,"captureLivenessInterval",null);_(this,"activePresetGeneration",0);_(this,"boardQueue",[]);_(this,"boardQueueActive",null);_(this,"boardAnimTimer",null);_(this,"settledBoardToolCallIds",new Set);_(this,"activeNavigate",null);_(this,"settledNavigateToolCallIds",new Set);_(this,"activeModalPreset",null);_(this,"boardClient",null);_(this,"boardTurnMonitor",new $n(()=>this.buildBoardVerification(),()=>this.boardQueueActive!==null||this.boardQueue.length>0||this.boardDrawInProgress||this.activeBoardProgress!==null));_(this,"activeBoardProgress",null);_(this,"boardSizePreset",xs());_(this,"boardViewMode","expanded");_(this,"boardDragPosition",null);_(this,"boardDragWiredModal",null)}resetChalkboard(){this.chalkboardContent="",this.boardChapterTitle=""}resetBoardSession(){this.boardTurnMonitor.stop(),this.boardDragPosition=null,this.boardDragWiredModal=null,this.activePresetGeneration++,qe(!1),this.clearBoardAnimTimer(),this.boardQueue=[],this.boardQueueActive=null,this.settledBoardToolCallIds.clear(),this.activeBoardProgress=null,this.boardClient=null,this.chalkboardContent="",this.boardChapterTitle="",this.boardDrawInProgress=!1,this.boardInk=we(),this.closeBoardUi()}getChalkboardContent(){return this.chalkboardContent}hasActiveBoardSession(){return!!document.querySelector(".vnr-whiteboard-modal")||this.chalkboardContent.length>0||this.boardInk.strokes.length>0||this.boardInk.labels.length>0||this.boardQueue.length>0||this.boardQueueActive!==null}syncChalkboardNotes(){const e=document.querySelector(".vnr-whiteboard-textarea");e&&(e.value.length>this.chalkboardContent.length?this.chalkboardContent=e.value:this.chalkboardContent!==e.value&&(e.value=this.chalkboardContent,e.scrollTop=e.scrollHeight))}buildBoardVerification(){this.syncChalkboardNotes();const e=this.chalkboardContent,t=this.boardInk.strokes.length>0;return{notes_char_count:e.length,notes_preview:e.slice(0,200)||null,has_notes_on_board:e.length>0,has_diagram_geometry:t,strokes_on_board:this.boardInk.strokes.length,labels_on_board:this.boardInk.labels.length,chapter_title:this.boardChapterTitle||null,verification_hint:"Do NOT tell the student notes or diagrams are visible unless has_notes_on_board or has_diagram_geometry is true in this tool result."}}splitChapterHeading(e){const t=e.trim(),r=t.split(`
305
+ `);if(!/^chapter\s*:/i.test(r[0]??""))return{chapterTitle:null,body:t};const s=r[0].replace(/^chapter\s*:\s*/i,"").trim()||r[0].trim(),i=r.slice(1).join(`
306
+ `).trim();return{chapterTitle:s,body:i}}getBoardSnapshot(){this.syncChalkboardNotes();const e=this.boardInk.strokes.length>0||this.boardInk.labels.length>0,t=this.chalkboardContent;return{board_layout:e?"diagram_top_notes_bottom":"notes_full",has_diagram:e,strokes_on_board:this.boardInk.strokes.length,labels_on_board:this.boardInk.labels.length,board_size:{width:K,height:Z},coordinate_system:"board_normalized_or_pixels",notes_content:t,notes_char_count:t.length,chapter_title:this.boardChapterTitle||null,agent_hint:e?"TOP = diagram (800×500), BOTTOM = notes. strokes:[{points,close}] — right △: [[0.15,0.25],[0.15,0.75],[0.55,0.75]]. labels below (y≥0.78). clear_old_diagrams_on_board:true wipes.":'draw_on_board: strokes:[{points:[[0.15,0.25],[0.15,0.75],[0.55,0.75]],close:true}] for right triangle. labels:[{x:0.35,y:0.82,text:"..."}]. NOT bare points string or centered apex.'}}syncDiagramLayer(e){Bt(e,this.boardInk,{strokeColor:"#ffffff",labelColor:"#4A9EFF",strokeWidth:6})}getBoardProgressSnapshot(){const e=this.activeBoardProgress;if(!e||e.plannedUnits<=0)return null;const t=this.chalkboardContent,r=e.mode==="type"?t.slice(e.textAtStart.length):t;return{write_progress_pct:Math.min(100,Math.round(e.unitsDone/e.plannedUnits*100)),characters_written:e.unitsDone,characters_planned:e.plannedUnits,partial_text_this_command:r}}getNavigateTerminalResult(e,t,r){return{status:e,reason:t||(e==="interrupted"?"Server interrupted":"Navigation cancelled"),preset_id:m.Navigate,navigated_to:r,target_url:r}}completeNavigate(e={}){const t=this.activeNavigate;if(!t||t.settled)return;const r=t.ctx.toolCallId;r&&this.settledNavigateToolCallIds.has(r)||(t.settled=!0,r&&this.settledNavigateToolCallIds.add(r),this.activeNavigate=null,t.onComplete({status:"success",preset_id:m.Navigate,navigated_to:t.targetUrl,target_url:t.targetUrl,...e}))}cancelNavigate(e,t){const r=this.activeNavigate;if(!r||r.settled)return;const s=r.ctx.toolCallId;s&&this.settledNavigateToolCallIds.has(s)||(r.settled=!0,s&&this.settledNavigateToolCallIds.add(s),this.activeNavigate=null,r.onCancel(e,{status:t}))}bindActiveModalPreset(e,t,r,s){this.activeModalPreset={ctx:e,presetId:t,onComplete:r,onCancel:s}}clearActiveModalPreset(){this.activeModalPreset&&(this.activeModalPreset.settled=!0,this.activeModalPreset=null)}cancelActiveModalPreset(e,t){const r=this.activeModalPreset;!r||r.settled||(r.settled=!0,this.activeModalPreset=null,this.overlay&&(this.overlay.remove(),this.overlay=null),this.stopCaptureCamera(),r.onCancel(e,{status:t}))}getBoardTerminalResult(e,t,r){const s={status:e,reason:t||(e==="interrupted"?"Server interrupted":"User dismissed"),...r?{preset_id:r}:{}};if(!r||!pt(r))return s;const i=this.chalkboardContent,o=this.getBoardProgressSnapshot();return{...s,text_written:i,whiteboard_content:i,board_snapshot:this.getBoardSnapshot(),...o||{}}}flushBoardContext(e){if(this.boardClient)try{typeof this.boardClient.sendContextUpdate=="function"?this.boardClient.sendContextUpdate(e):typeof this.boardClient.updateContext=="function"&&this.boardClient.updateContext(e)}catch{}}clearActiveBoardProgress(){this.activeBoardProgress=null}syncBoardProgressUnits(e){this.activeBoardProgress&&(this.activeBoardProgress.unitsDone=e)}buildBoardContextPayload(e,t,r){const s=this.activeBoardProgress,i=(s==null?void 0:s.ctx.toolCallId)===e.toolCallId;let o,a,l,c;i&&s&&(a=s.unitsDone,l=s.plannedUnits,o=s.plannedUnits>0?Math.min(100,Math.round(s.unitsDone/s.plannedUnits*100)):100,s.mode==="type"?c=t.slice(s.textAtStart.length):c=t);const u={ui_state:"whiteboard_active",tool_status:"interrupted",visible_preset:e.presetId,tool_call_id:e.toolCallId,interrupted:!0,interrupt_reason:r||"Server interrupted",whiteboard_content:t};if(o!==void 0){u.write_progress_pct=o,u.characters_written=a,u.characters_planned=l,u.partial_text_this_command=c??"";const d=(s==null?void 0:s.mode)==="erase"?"erase":"write",p=(c??"").length>120?`${(c??"").slice(0,120)}…`:c??"",h=(s==null?void 0:s.mode)==="erase"?"The board already reflects this partial erase — continue from here; do not repeat earlier steps.":"The board already contains this content — continue typing from here; do not repeat what is already on the board.";u.message=`Whiteboard ${d} interrupted at ${o}% (${a}/${l} characters this command). Partial text this turn: "${p}". `+h}return u}sendBoardContextUpdate(e,t,r){this.flushBoardContext(this.buildBoardContextPayload(e,t,r))}handle(e,t,r,s){const i=e.data||e;let o={};const a=i.arguments||i.args;if(typeof a=="string")try{o=JSON.parse(a)}catch{o={}}else a&&typeof a=="object"&&(o=a);const l=i.client_fields||{},c=ot(l,a,i.name||i.tool_name);if(!c||!Y(c))return!1;const u={...o,...l},d={toolCallId:i.tool_call_id||i.call_id||"",presetId:c,clientFields:u,args:o,toolCall:i};this.injectStyles();const p=!!document.querySelector(".vnr-whiteboard-modal");switch(pt(c)?p||this.dismissNonBoardUi():Pr(c)||Mr(c)||this.dismiss(),c){case m.Calendar:return this.renderCalendar(d,t,r),!0;case m.Form:return this.renderForm(d,t,r),!0;case m.Camera:return this.renderCamera(d,t,r,s),!0;case m.Upload:return this.renderUpload(d,t,r,s),!0;case m.ClipRegion:return this.renderClipRegion(d,t,r,s),!0;case m.TabScreenshot:return this.renderTabScreenshot(d,t,r,s),!0;case m.Navigate:return this.renderNavigate(d,t,r),!0;case m.HighlightElement:return this.renderHighlight(d,t,r),!0;case m.ClickElement:return this.renderClickElement(d,t,r),!0;case m.SelectOption:return this.renderSelectOption(d,t,r),!0;case m.SetDate:return this.renderSetDate(d,t,r),!0;case m.TypeText:return this.enqueueBoardCommand({ctx:d,presetId:m.TypeText,onComplete:t,onCancel:r},s),!0;case m.EraseText:return this.enqueueBoardCommand({ctx:d,presetId:m.EraseText,onComplete:t,onCancel:r},s),!0;case m.Draw:return this.enqueueBoardCommand({ctx:d,presetId:m.Draw,onComplete:t,onCancel:r},s),!0;case m.EraseDraw:return this.enqueueBoardCommand({ctx:d,presetId:m.EraseDraw,onComplete:t,onCancel:r},s),!0;case m.LiveVision:return this.handleOpenLiveCamera(u,s,d.toolCallId),t({status:"success",preset_id:m.LiveVision,message:"Live camera session started"}),!0;case m.CloseLiveCamera:return this.handleCloseLiveCamera(s),t({status:"success",preset_id:m.CloseLiveCamera,message:"Live camera stopped"}),!0;case m.LiveScreen:return this.handleOpenLiveScreen(u,s,d.toolCallId),t({status:"success",preset_id:m.LiveScreen,message:"Live screen share started"}),!0;case m.CloseLiveScreen:return this.handleCloseLiveScreen(s),t({status:"success",preset_id:m.CloseLiveScreen,message:"Live screen share stopped"}),!0;case m.ScreenInk:return this.renderScreenInk(d,t,r),!0;case m.ScreenCursor:return this.renderScreenCursor(d,t,r),!0;case m.ScreenClick:return this.renderScreenClick(d,t,r),!0;case m.ClearScreenOverlay:return Me(),t({status:"success",preset_id:m.ClearScreenOverlay,message:"Screen overlay cleared"}),!0;case m.PageScan:return In(d,t,r,s),!0;case m.PointAt:return Ln(d,t,r),!0;case m.OutlineTargets:return Pn(d,t,r),!0;case m.ClearGuide:return Mn(d,t),!0;default:return!1}}abortBoardTools(e="Interrupted",t){const r=this.activeNavigate;r&&!r.settled&&(!t||r.ctx.toolCallId===t)&&this.cancelNavigate(e,"interrupted");const s=this.activeModalPreset;s&&!s.settled&&(!t||s.ctx.toolCallId===t)&&this.cancelActiveModalPreset(e,"interrupted");const i=a=>!t||a.ctx.toolCallId===t;if(this.boardQueueActive&&i(this.boardQueueActive)||this.boardQueue.some(i)){if(this.clearBoardAnimTimer(),this.activePresetGeneration++,this.boardQueueActive&&i(this.boardQueueActive)){const a=this.boardQueueActive;this.boardQueueActive=null,this.settleBoardCancel(a,e,"interrupted")}this.boardQueue=this.boardQueue.filter(a=>i(a)?(this.settleBoardCancel(a,e,"interrupted"),!1):!0)}}dismiss(){this.activeNavigate&&!this.activeNavigate.settled&&this.cancelNavigate("Session ended","interrupted"),this.activeModalPreset=null,this.resetBoardSession(),this.stopCaptureCamera(),this.handleCloseLiveCamera(null),this.handleCloseLiveScreen(null),ze(),this.overlay&&(this.overlay.remove(),this.overlay=null)}teardownSession(){this.dismiss(),Me()}enqueueBoardCommand(e,t){var s;t&&(this.boardClient=t),this.boardClient&&document.querySelector(".vnr-whiteboard-modal")&&this.ensureBoardTurnMonitor();const r=e.ctx.toolCallId;r&&(this.settledBoardToolCallIds.has(r)||((s=this.boardQueueActive)==null?void 0:s.ctx.toolCallId)===r||this.boardQueue.some(i=>i.ctx.toolCallId===r))||(this.boardQueue.push(e),j("Board:Queue",`Enqueued ${e.presetId}`,{pending:this.boardQueue.length,toolCallId:e.ctx.toolCallId}),this.processBoardQueue())}processBoardQueue(){if(this.boardQueueActive||this.boardQueue.length===0)return;const e=this.boardQueue.shift();this.boardQueueActive=e,j("Board:Queue",`Running ${e.presetId}`,{toolCallId:e.ctx.toolCallId});const t=(i,o)=>{if(this.boardQueueActive===e){if(e.settled||e.aborted){this.boardQueueActive=null;return}this.boardQueueActive=null,o!==void 0?this.settleBoardCancel(e,o):this.settleBoardComplete(e,i||{}),this.processBoardQueue()}},r=i=>t(i),s=i=>{this.activePresetGeneration++,t(null,i||"Cancelled"),!this.boardQueueActive&&this.boardQueue.length===0&&this.closeBoardUi()};e.presetId===m.TypeText?this.renderTypeText(e.ctx,r,s):e.presetId===m.Draw?this.renderDrawShapes(e.ctx,r,s):e.presetId===m.EraseDraw?this.renderEraseDrawingBoard(e.ctx,r,s):this.renderEraseText(e.ctx,r,s)}closeBoardUi(){this.boardTurnMonitor.stop(),this.boardViewMode="expanded",qe(!1),this.dismissWhiteboard(),this.overlay&&(!document.body.contains(this.overlay)||!this.overlay.childElementCount)&&(this.overlay.remove(),this.overlay=null)}getBoardOverlay(){const e=document.querySelector(".vnr-whiteboard-modal");return(e==null?void 0:e.closest(".vnr-overlay"))??this.overlay}applyBoardLayoutMode(e,t){const r=e??this.getBoardOverlay(),s=t??document.querySelector(".vnr-whiteboard-modal");if(!r||!s)return;const i=this.boardViewMode==="reduced";r.classList.remove("vnr-whiteboard-overlay-hidden"),r.classList.add("vnr-whiteboard-overlay"),r.classList.toggle("vnr-whiteboard-overlay-reduced",i),r.classList.toggle("vnr-whiteboard-overlay-expanded",!i),this.syncBoardResizeButton(s.querySelector(".vnr-whiteboard-resize-btn")),qe(!0,i),this.syncBoardDragLayout(s),this.ensureBoardTurnMonitor()}clearBoardDragStyles(e){e.style.removeProperty("position"),e.style.removeProperty("left"),e.style.removeProperty("top"),e.style.removeProperty("right"),e.style.removeProperty("bottom"),e.style.removeProperty("margin"),e.style.removeProperty("transform")}clampBoardDragPosition(e,t,r){const i=Math.max(8,window.innerWidth-e.offsetWidth-8),o=Math.max(8,window.innerHeight-e.offsetHeight-8);return{x:Math.min(i,Math.max(8,t)),y:Math.min(o,Math.max(8,r))}}applyBoardDragPosition(e,t,r){const s=this.clampBoardDragPosition(e,t,r);e.style.setProperty("position","fixed","important"),e.style.setProperty("left",`${s.x}px`,"important"),e.style.setProperty("top",`${s.y}px`,"important"),e.style.setProperty("right","auto","important"),e.style.setProperty("bottom","auto","important"),e.style.setProperty("margin","0","important"),e.style.setProperty("transform","none","important"),this.boardDragPosition=s}defaultReducedBoardPosition(e){const r=Math.max(96,20+(typeof window<"u"?Number.parseInt(getComputedStyle(document.documentElement).getPropertyValue("env(safe-area-inset-bottom)")||"0",10):0));return this.clampBoardDragPosition(e,window.innerWidth-e.offsetWidth-16,window.innerHeight-e.offsetHeight-r)}syncBoardDragLayout(e){if(this.boardViewMode==="reduced"){const t=this.boardDragPosition??this.defaultReducedBoardPosition(e);this.applyBoardDragPosition(e,t.x,t.y)}else this.clearBoardDragStyles(e)}wireBoardDrag(e,t){if(this.boardDragWiredModal===t)return;this.boardDragWiredModal=t;let r=!1,s=0,i=0,o=0,a=0;const l=d=>{if(this.boardViewMode!=="reduced"||d.target.closest("button"))return;r=!0,e.setPointerCapture(d.pointerId);const p=t.getBoundingClientRect();s=d.clientX,i=d.clientY,o=p.left,a=p.top,e.classList.add("is-dragging"),d.preventDefault()},c=d=>{r&&this.applyBoardDragPosition(t,o+(d.clientX-s),a+(d.clientY-i))},u=d=>{r&&(r=!1,e.classList.remove("is-dragging"),e.hasPointerCapture(d.pointerId)&&e.releasePointerCapture(d.pointerId))};e.addEventListener("pointerdown",l),e.addEventListener("pointermove",c),e.addEventListener("pointerup",u),e.addEventListener("pointercancel",u)}ensureBoardTurnMonitor(){this.boardClient&&this.boardTurnMonitor.start(e=>this.flushBoardContext(e))}revealBoardUi(e){this.applyBoardLayoutMode(this.getBoardOverlay(),e)}dismissNonBoardUi(){this.stopCaptureCamera(),this.handleCloseLiveCamera(null),this.handleCloseLiveScreen(null),ze(),this.overlay&&!this.overlay.querySelector(".vnr-whiteboard-modal")&&(this.overlay.remove(),this.overlay=null)}settleBoardCancel(e,t,r="cancelled"){if(e.settled)return;e.aborted=!0,e.settled=!0;const s=e.ctx.toolCallId;s&&this.settledBoardToolCallIds.add(s);const i=this.chalkboardContent;r==="interrupted"&&this.sendBoardContextUpdate(e.ctx,i,t),e.onCancel(t,{status:r}),this.clearActiveBoardProgress()}settleBoardComplete(e,t){if(e.settled||e.aborted)return;e.settled=!0;const r=e.ctx.toolCallId;r&&this.settledBoardToolCallIds.add(r);const s=this.chalkboardContent;e.onComplete({status:"success",preset_id:e.presetId,tool_call_id:e.ctx.toolCallId,text_written:s,whiteboard_content:s,...this.buildBoardVerification(),...t}),this.clearActiveBoardProgress()}clearBoardAnimTimer(){this.boardAnimTimer&&(clearTimeout(this.boardAnimTimer),this.boardAnimTimer=null)}scheduleBoardAnim(e,t){this.clearBoardAnimTimer(),this.boardAnimTimer=setTimeout(()=>{this.boardAnimTimer=null,e()},t)}dismissWhiteboard(){document.querySelectorAll(".vnr-whiteboard-modal").forEach(e=>{var t;(t=e.closest(".vnr-overlay"))==null||t.remove()}),this.overlay&&!document.body.contains(this.overlay)&&(this.overlay=null)}stopCaptureCamera(){var e;this.captureActive=!1,this.captureLivenessInterval&&(clearInterval(this.captureLivenessInterval),this.captureLivenessInterval=null),(e=this.captureStream)==null||e.getTracks().forEach(t=>t.stop()),this.captureStream=null}getBrowserPermissionHint(){const e=navigator.userAgent;return/iPhone|iPad/i.test(e)?"Open Settings → Safari → Camera and allow access for this site.":/Android/i.test(e)?"Tap the lock icon in the address bar → Permissions → Camera → Allow.":"Click the camera icon in your browser's address bar and allow access."}fillCameraPermissionPrompt(e,t){e.style.display="flex",e.innerHTML=`
307
+ <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center;width:100%;height:100%;box-sizing:border-box">
308
+ <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
309
+ <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
310
+ <line x1="1" y1="1" x2="23" y2="23"/>
311
+ </svg>
312
+ <p style="margin:0;font-size:14px;font-weight:600;color:#f87171">Camera access blocked</p>
313
+ <p style="margin:0;font-size:12px;color:#94a3b8;line-height:1.5;max-width:300px">
314
+ Allow camera access to continue. ${this.getBrowserPermissionHint()}
315
+ </p>
316
+ <div style="display:flex;gap:10px;margin-top:4px;flex-wrap:wrap;justify-content:center">
317
+ <button type="button" id="vnr-cam-perm-retry" class="vnr-confirm-btn" style="padding:10px 18px">Try Again</button>
318
+ ${t.onDismiss?'<button type="button" id="vnr-cam-perm-dismiss" class="vnr-cancel-btn">Cancel</button>':""}
319
+ </div>
320
+ </div>
321
+ `,e.querySelector("#vnr-cam-perm-retry").addEventListener("click",t.onRetry),t.onDismiss&&e.querySelector("#vnr-cam-perm-dismiss").addEventListener("click",t.onDismiss)}notifyCameraPermissionDenied(e,t){const r="Camera permission denied. Please allow camera access in your browser settings.";if(e!=null&&e.sendToolError&&t)try{e.sendToolError(t,r)}catch{}}showLiveCameraPermissionBanner(e,t){var s;(s=this.lvPermissionBanner)==null||s.remove();const r=document.createElement("div");r.id="vnr-live-cam-perm-banner",r.style.cssText=["position:fixed","bottom:24px","left:50%","transform:translateX(-50%)","z-index:2147483647","max-width:360px","width:calc(100% - 32px)","padding:16px 18px","border-radius:16px","background:#0f172a","border:1px solid rgba(248,113,113,0.35)","box-shadow:0 12px 32px rgba(0,0,0,0.35)","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"].join(";"),r.innerHTML=`
322
+ <p style="margin:0 0 6px;font-size:13px;font-weight:700;color:#f87171">Camera access blocked</p>
323
+ <p style="margin:0 0 12px;font-size:12px;color:#94a3b8;line-height:1.5">${this.getBrowserPermissionHint()}</p>
324
+ <div style="display:flex;gap:8px">
325
+ <button type="button" id="vnr-lv-perm-retry" style="flex:1;padding:9px 14px;border:none;border-radius:10px;background:#6366f1;color:#fff;font-size:13px;font-weight:600;cursor:pointer">Try Again</button>
326
+ <button type="button" id="vnr-lv-perm-dismiss" style="padding:9px 14px;border:1px solid rgba(255,255,255,0.15);border-radius:10px;background:transparent;color:#e2e8f0;font-size:13px;font-weight:600;cursor:pointer">Dismiss</button>
327
+ </div>
328
+ `,r.querySelector("#vnr-lv-perm-retry").addEventListener("click",e),r.querySelector("#vnr-lv-perm-dismiss").addEventListener("click",t),document.body.appendChild(r),this.lvPermissionBanner=r}async sendClientEvent(e,t,r){if(typeof(e==null?void 0:e.sendEventWhenReady)=="function"){await e.sendEventWhenReady(t,r);return}if(e!=null&&e.sendEvent){e.sendEvent(t,r);return}}handleOpenLiveCamera(e,t,r){this.handleCloseLiveScreen(t),this.handleCloseLiveCamera(t);const s=e.scope??"until_call_end",i=Math.min(Number(e.target_fps??1),Number(e.max_fps??3)),o=Number(e.max_width??640),a=e.reason??"camera_capture",l=Number(e.duration_sec??0),c=e.facing_mode??"environment",u=e.show_preview!==!1&&e.show_preview!=="false",d=`lv_${crypto.randomUUID()}`;this.lvSessionId=d,this.lvFrameSeq=0;const p=document.createElement("video");p.autoplay=!0,p.playsInline=!0,p.muted=!0,p.style.display="none",document.body.appendChild(p),this.lvVideo=p;const h=document.createElement("canvas");h.style.display="none",document.body.appendChild(h),this.lvCanvas=h,u&&(this.lvPip=this.createLivePip(c,()=>this.handleCloseLiveCamera(t))),(()=>{navigator.mediaDevices.getUserMedia({video:{facingMode:c,width:{ideal:o*2}}}).then(async y=>{var g;if(!this.lvSessionId){y.getTracks().forEach(b=>b.stop());return}if((g=this.lvPermissionBanner)==null||g.remove(),this.lvPermissionBanner=null,this.lvStream=y,p.srcObject=y,this.lvPip){const b=this.lvPip.querySelector("video");b&&(b.srcObject=y)}await this.sendClientEvent(t,"client_live_camera_started",{data:{session_id:d,scope:s,...s==="timed"&&l>0?{duration_sec:l}:{},reason:a,target_fps:i}});const v=Math.round(1e3/i);this.lvCaptureInterval=setInterval(()=>{this.captureAndSendFrame(t,d,o,a)},v),s==="timed"&&l>0&&(this.lvAutoStopTimeout=setTimeout(()=>{this.handleCloseLiveCamera(t)},l*1e3))}).catch(y=>{var v,g;this.lvSessionId=null,(v=this.lvStream)==null||v.getTracks().forEach(b=>b.stop()),this.lvStream=null,(g=this.lvPip)==null||g.remove(),this.lvPip=null,p.remove(),this.lvVideo=null,h.remove(),this.lvCanvas=null,this.notifyCameraPermissionDenied(t,r),this.showLiveCameraPermissionBanner(()=>this.handleOpenLiveCamera(e,t,r),()=>{var b;(b=this.lvPermissionBanner)==null||b.remove(),this.lvPermissionBanner=null})})})()}handleCloseLiveCamera(e){var r,s,i,o,a;const t=this.lvSessionId;this.lvSessionId=null,this.lvCaptureInterval&&(clearInterval(this.lvCaptureInterval),this.lvCaptureInterval=null),this.lvAutoStopTimeout&&(clearTimeout(this.lvAutoStopTimeout),this.lvAutoStopTimeout=null),(r=this.lvStream)==null||r.getTracks().forEach(l=>l.stop()),this.lvStream=null,(s=this.lvVideo)==null||s.remove(),this.lvVideo=null,(i=this.lvCanvas)==null||i.remove(),this.lvCanvas=null,(o=this.lvPip)==null||o.remove(),this.lvPip=null,(a=this.lvPermissionBanner)==null||a.remove(),this.lvPermissionBanner=null,t&&e&&this.sendClientEvent(e,"client_live_camera_stopped",{data:{session_id:t}})}classifyLiveScreenShareFailure(e){if(e instanceof DOMException){if(e.name==="AbortError")return"cancelled";if(e.name==="NotAllowedError"){const r=(e.message||"").toLowerCase();return r.includes("dismiss")||r.includes("cancel")||r.includes("abort")?"cancelled":"denied"}}const t=e instanceof Error?(e.message||"").toLowerCase():"";return t.includes("cancel")||t.includes("dismiss")||t.includes("abort")?"cancelled":"denied"}emitLiveScreenShareFailure(e,t,r,s,i,o){const a=i instanceof DOMException||i instanceof Error?i.name:void 0,l=o??(s==="cancelled"?"User cancelled screen share without selecting a source.":"Screen share permission was not granted."),c=s==="cancelled"?"client_live_screen_cancelled":"client_live_screen_denied";if(e!=null&&e.sendEvent&&e.sendEvent(c,{data:{...t?{session_id:t}:{},...r?{tool_call_id:r}:{},message:l,...a?{error_name:a}:{}}}),e!=null&&e.sendToolError&&r)try{e.sendToolError(r,l)}catch{}}notifyScreenShareUnavailable(e,t){this.emitLiveScreenShareFailure(e,null,t,"denied",void 0,"Screen sharing is not supported in this browser or device.")}showLiveScreenPermissionBanner(e,t,r){var a;(a=this.lsPermissionBanner)==null||a.remove();const s=e==="cancelled"?"Screen share cancelled":"Screen share blocked",i=e==="cancelled"?"You closed the picker without sharing. Try again when you are ready to show your screen.":"Choose a screen, window, or browser tab when prompted to share with the agent.",o=document.createElement("div");o.id="vnr-live-screen-perm-banner",o.style.cssText=["position:fixed","bottom:24px","left:50%","transform:translateX(-50%)","z-index:2147483647","max-width:360px","width:calc(100% - 32px)","padding:16px 18px","border-radius:16px","background:#0f172a","border:1px solid rgba(96,165,250,0.35)","box-shadow:0 12px 32px rgba(0,0,0,0.35)","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"].join(";"),o.innerHTML=`
329
+ <p style="margin:0 0 6px;font-size:13px;font-weight:700;color:#60a5fa">${s}</p>
330
+ <p style="margin:0 0 12px;font-size:12px;color:#94a3b8;line-height:1.5">${i}</p>
331
+ <div style="display:flex;gap:8px">
332
+ <button type="button" id="vnr-ls-perm-retry" style="flex:1;padding:9px 14px;border:none;border-radius:10px;background:#6366f1;color:#fff;font-size:13px;font-weight:600;cursor:pointer">Try Again</button>
333
+ <button type="button" id="vnr-ls-perm-dismiss" style="padding:9px 14px;border:1px solid rgba(255,255,255,0.15);border-radius:10px;background:transparent;color:#e2e8f0;font-size:13px;font-weight:600;cursor:pointer">Dismiss</button>
334
+ </div>
335
+ `,o.querySelector("#vnr-ls-perm-retry").addEventListener("click",t),o.querySelector("#vnr-ls-perm-dismiss").addEventListener("click",r),document.body.appendChild(o),this.lsPermissionBanner=o}handleOpenLiveScreen(e,t,r){var y;if(this.handleCloseLiveScreen(t),this.handleCloseLiveCamera(t),!((y=navigator.mediaDevices)!=null&&y.getDisplayMedia)){this.notifyScreenShareUnavailable(t,r);return}const s=e.scope??"until_call_end",i=Math.min(Number(e.target_fps??1),Number(e.max_fps??3)),o=Number(e.max_width??1280),a=e.reason??"screen_capture",l=Number(e.duration_sec??0),c=e.prefer_current_tab===!0||e.prefer_current_tab==="true",u=e.show_preview!==!1&&e.show_preview!=="false",d=`ls_${crypto.randomUUID()}`;this.lsSessionId=d,this.lsFrameSeq=0;const p=document.createElement("video");p.autoplay=!0,p.playsInline=!0,p.muted=!0,p.style.display="none",document.body.appendChild(p),this.lsVideo=p;const h=document.createElement("canvas");h.style.display="none",document.body.appendChild(h),this.lsCanvas=h,u&&(this.lsPip=this.createLiveScreenPip(()=>this.handleCloseLiveScreen(t))),(()=>{const v=c?{displaySurface:"browser"}:!0;navigator.mediaDevices.getDisplayMedia({video:v,audio:!1}).then(async g=>{var x,C;if(!this.lsSessionId){g.getTracks().forEach(k=>k.stop());return}(x=this.lsPermissionBanner)==null||x.remove(),this.lsPermissionBanner=null,this.lsStream=g,p.srcObject=g;const b=g.getVideoTracks()[0];if(b&&(b.onended=()=>{this.handleCloseLiveScreen(t)}),this.lsPip){const k=this.lsPip.querySelector("video");k&&(k.srcObject=g)}const S=((C=b==null?void 0:b.getSettings)==null?void 0:C.call(b).displaySurface)??"unknown";await this.sendClientEvent(t,"client_live_screen_started",{data:{session_id:d,scope:s,...s==="timed"&&l>0?{duration_sec:l}:{},display_surface:S,reason:a,target_fps:i}});const w=Math.round(1e3/i);this.lsCaptureInterval=setInterval(()=>{this.captureAndSendScreenFrame(t,d,o,a)},w),s==="timed"&&l>0&&(this.lsAutoStopTimeout=setTimeout(()=>{this.handleCloseLiveScreen(t)},l*1e3))}).catch(g=>{var S,w;const b=this.classifyLiveScreenShareFailure(g);this.lsSessionId=null,(S=this.lsStream)==null||S.getTracks().forEach(x=>x.stop()),this.lsStream=null,(w=this.lsPip)==null||w.remove(),this.lsPip=null,p.remove(),this.lsVideo=null,h.remove(),this.lsCanvas=null,this.emitLiveScreenShareFailure(t,d,r,b,g),this.showLiveScreenPermissionBanner(b,()=>this.handleOpenLiveScreen(e,t,r),()=>{var x;(x=this.lsPermissionBanner)==null||x.remove(),this.lsPermissionBanner=null})})})()}handleCloseLiveScreen(e){var r,s,i,o,a;const t=this.lsSessionId;this.lsSessionId=null,this.lsCaptureInterval&&(clearInterval(this.lsCaptureInterval),this.lsCaptureInterval=null),this.lsAutoStopTimeout&&(clearTimeout(this.lsAutoStopTimeout),this.lsAutoStopTimeout=null),(r=this.lsStream)==null||r.getTracks().forEach(l=>l.stop()),this.lsStream=null,(s=this.lsVideo)==null||s.remove(),this.lsVideo=null,(i=this.lsCanvas)==null||i.remove(),this.lsCanvas=null,(o=this.lsPip)==null||o.remove(),this.lsPip=null,(a=this.lsPermissionBanner)==null||a.remove(),this.lsPermissionBanner=null,t&&e&&this.sendClientEvent(e,"client_live_screen_stopped",{data:{session_id:t}})}async uploadLiveStreamFrame(e,t,r,s){const i=`frame_${r}.jpg`;if(typeof e.uploadMediaFrame=="function")return e.uploadMediaFrame(t,s,i);const o=e.serverUrl||"";let a="";try{a=new URL(o).origin}catch{a=o.replace(/\/webrtc.*$/,"").replace(/\/$/,"")}const l=e.callId||"",c=`${a}/media/upload`,u=new FormData;u.append("file",t,i),u.append("call_id",l),u.append("reason",s);const d=await fetch(c,{method:"POST",body:u});if(!d.ok)throw new Error(`Upload HTTP ${d.status}`);const p=await d.json();if(!p.media_id||!p.url)throw new Error("Upload response missing media_id/url");return{media_id:p.media_id,url:p.url,content_type:p.content_type||"image/jpeg"}}async captureAndSendScreenFrame(e,t,r,s){if(!e||!this.lsVideo||!this.lsCanvas||!this.lsSessionId)return;const i=this.lsVideo;if(i.readyState<2)return;const o=this.lsCanvas,a=i.videoWidth||r,l=i.videoHeight||r,c=Math.min(1,r/a);o.width=Math.round(a*c),o.height=Math.round(l*c);const u=o.getContext("2d");if(!u)return;u.drawImage(i,0,0,o.width,o.height);let d;try{d=await new Promise((p,h)=>o.toBlob(f=>f?p(f):h(new Error("toBlob failed")),"image/jpeg",.75))}catch{return}try{const{media_id:p,url:h,content_type:f}=await this.uploadLiveStreamFrame(e,d,t,s);if(!this.lsSessionId||this.lsSessionId!==t||!p||!h)return;const y=++this.lsFrameSeq;await this.sendClientEvent(e,"client_media_frame",{data:{session_id:t,source:"screen",frame_seq:y,media_id:p,media_url:h,content_type:f,reason:s,viewport:{width:o.width,height:o.height}}})}catch{}}createLiveScreenPip(e){const t=document.createElement("div");if(t.id="vnr-live-screen-pip",t.style.cssText=["position:fixed","bottom:24px","right:24px","z-index:2147483647","width:220px","height:124px","border-radius:16px","overflow:hidden","background:#0f172a","border:1px solid rgba(96,165,250,0.25)","box-shadow:0 12px 32px rgba(0,0,0,0.35)","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif","transition:transform 0.2s ease"].join(";"),t.innerHTML=`
336
+ <video autoplay playsinline muted style="width:100%;height:100%;object-fit:contain;display:block;background:#020617"></video>
337
+ <div style="position:absolute;top:10px;left:10px;display:flex;align-items:center;gap:6px;padding:3px 8px;border-radius:6px;background:rgba(15,23,42,0.8);border:1px solid rgba(255,255,255,0.1);font-size:10px;font-weight:700;color:#f8fafc;text-transform:uppercase;letter-spacing:0.04em;pointer-events:none;">
338
+ <span style="width:6px;height:6px;border-radius:50%;background:#3b82f6;flex-shrink:0;animation:vnr-pip-pulse 1.5s ease-in-out infinite;"></span>
339
+ SCREEN
340
+ </div>
341
+ <button id="vnr-screen-pip-stop" style="position:absolute;top:10px;right:10px;width:22px;height:22px;border-radius:50%;background:rgba(15,23,42,0.8);border:1px solid rgba(255,255,255,0.1);color:#fff;font-size:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background 0.2s,transform 0.2s;">✕</button>
342
+ `,!document.getElementById("vnr-pip-style")){const r=document.createElement("style");r.id="vnr-pip-style",r.textContent=`
343
+ @keyframes vnr-pip-pulse{0%,100%{opacity:1;transform:scale(1);}50%{opacity:.5;transform:scale(1.2);}}
344
+ #vnr-live-screen-pip:hover { transform: scale(1.02); }
345
+ #vnr-screen-pip-stop:hover { background: rgba(239,68,68,0.9) !important; transform: scale(1.1); }
346
+ `,document.head.appendChild(r)}return t.querySelector("#vnr-screen-pip-stop").addEventListener("click",()=>e()),document.body.appendChild(t),t}async captureAndSendFrame(e,t,r,s){if(!e||!this.lvVideo||!this.lvCanvas||!this.lvSessionId)return;const i=this.lvVideo;if(i.readyState<2)return;const o=this.lvCanvas,a=i.videoWidth||r,l=i.videoHeight||r,c=Math.min(1,r/a);o.width=Math.round(a*c),o.height=Math.round(l*c);const u=o.getContext("2d");if(!u)return;u.drawImage(i,0,0,o.width,o.height);let d;try{d=await new Promise((p,h)=>o.toBlob(f=>f?p(f):h(new Error("toBlob failed")),"image/jpeg",.75))}catch{return}try{const{media_id:p,url:h,content_type:f}=await this.uploadLiveStreamFrame(e,d,t,s);if(!this.lvSessionId||this.lvSessionId!==t||!p||!h)return;const y=++this.lvFrameSeq;await this.sendClientEvent(e,"client_media_frame",{data:{session_id:t,frame_seq:y,media_id:p,media_url:h,content_type:f,reason:s}})}catch{}}createLivePip(e,t){const r=document.createElement("div");r.id="vnr-live-pip";const s=e==="user";if(r.style.cssText=["position:fixed","bottom:24px","right:24px","z-index:2147483647","width:180px","height:135px","border-radius:16px","overflow:hidden","background:#0f172a","border:1px solid rgba(255,255,255,0.15)","box-shadow:0 12px 32px rgba(0,0,0,0.35)","font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif","transition:transform 0.2s ease"].join(";"),r.innerHTML=`
347
+ <video autoplay playsinline muted style="width:100%;height:100%;object-fit:cover;display:block;${s?"transform:scaleX(-1);":""}"></video>
348
+ <div style="position:absolute;top:10px;left:10px;display:flex;align-items:center;gap:6px;padding:3px 8px;border-radius:6px;background:rgba(15,23,42,0.8);border:1px solid rgba(255,255,255,0.1);font-size:10px;font-weight:700;color:#f8fafc;text-transform:uppercase;letter-spacing:0.04em;pointer-events:none;">
349
+ <span style="width:6px;height:6px;border-radius:50%;background:#ef4444;flex-shrink:0;animation:vnr-pip-pulse 1.5s ease-in-out infinite;"></span>
350
+ REC
351
+ </div>
352
+ <button id="vnr-pip-stop" style="position:absolute;top:10px;right:10px;width:22px;height:22px;border-radius:50%;background:rgba(15,23,42,0.8);border:1px solid rgba(255,255,255,0.1);color:#fff;font-size:10px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background 0.2s,transform 0.2s;">✕</button>
353
+ `,!document.getElementById("vnr-pip-style")){const i=document.createElement("style");i.id="vnr-pip-style",i.textContent=`
354
+ @keyframes vnr-pip-pulse{0%,100%{opacity:1;transform:scale(1);}50%{opacity:.5;transform:scale(1.2);}}
355
+ #vnr-live-pip:hover { transform: scale(1.02); }
356
+ #vnr-pip-stop:hover { background: rgba(239,68,68,0.9) !important; transform: scale(1.1); }
357
+ `,document.head.appendChild(i)}return r.querySelector("#vnr-pip-stop").addEventListener("click",()=>t()),document.body.appendChild(r),r}injectStyles(){if(this.styleInjected||document.getElementById("vnr-preset-styles"))return;const e=document.createElement("style");e.id="vnr-preset-styles",e.textContent=vs,document.head.appendChild(e),this.styleInjected=!0}createOverlay(){const e=document.createElement("div");return e.className="vnr-overlay",document.body.appendChild(e),this.overlay=e,e}createModal(e,t,r){const s=document.createElement("div");return s.className="vnr-modal",s.style.position="relative",s.innerHTML=`
358
+ <button class="vnr-close-btn" aria-label="Close">
359
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
360
+ <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
361
+ </svg>
362
+ </button>
363
+ <h2 class="vnr-title">${t}</h2>
364
+ <div class="vnr-reason">
365
+ <svg width="14" height="14" style="flex-shrink:0;margin-top:1px" fill="none" stroke="#9ca3af" stroke-width="2" viewBox="0 0 24 24">
366
+ <path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>
367
+ </svg>
368
+ <span>${r}</span>
369
+ </div>
370
+ `,e.appendChild(s),s}renderCalendar(e,t,r){this.bindActiveModalPreset(e,m.Calendar,t,r);const s=v=>{this.clearActiveModalPreset(),t({status:"success",preset_id:m.Calendar,...v})},i=v=>{this.clearActiveModalPreset(),r(v,{status:"cancelled"})},o=new Date;o.setHours(0,0,0,0),this.calViewYear=o.getFullYear(),this.calViewMonth=o.getMonth(),this.calSelectedTs=null,this.calSelectedTime=null;const a=e.clientFields.title||"Select Date & Time",l=e.args.reason||"Please select a preferred time for your appointment.",c=this.createOverlay(),u=this.createModal(c,a,l);u.querySelector(".vnr-close-btn").addEventListener("click",()=>{this.dismiss(),i("User closed the preset")});const d=document.createElement("div");u.appendChild(d);const p=document.createElement("div");p.style.display="none",u.appendChild(p);const h=document.createElement("div");h.className="vnr-actions",h.innerHTML=`
371
+ <button class="vnr-cancel-btn">Cancel</button>
372
+ <button class="vnr-confirm-btn" disabled>
373
+ <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>
374
+ Confirm
375
+ </button>
376
+ `,u.appendChild(h);const f=h.querySelector(".vnr-confirm-btn");h.querySelector(".vnr-cancel-btn").addEventListener("click",()=>{this.dismiss(),i("User cancelled")}),f.addEventListener("click",()=>{if(!this.calSelectedTs||!this.calSelectedTime)return;const v=new Date(this.calSelectedTs),g=Ye(this.calSelectedTime),b=v.getFullYear(),S=String(v.getMonth()+1).padStart(2,"0"),w=String(v.getDate()).padStart(2,"0"),x=`${b}-${S}-${w}`,C=e.clientFields.timezone||"";let k=typeof this.calSelectedTime=="object"?{...this.calSelectedTime}:void 0;if(k){for(const E of["start","startTime","end","endTime"])if(k[E]&&typeof k[E]=="string"&&(k[E].includes("T")||!isNaN(Date.parse(k[E]))))try{k[E]=ms(new Date(k[E]),C)}catch{}}this.dismiss(),s({date:x,time:g,timestamp:this.calSelectedTs,formatted:`${v.toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric"})} at ${g}`,slot_data:k})});const y=()=>{const v=new Date;v.setHours(0,0,0,0);const g=new Date(this.calViewYear,this.calViewMonth,1).getDay(),b=new Date(this.calViewYear,this.calViewMonth+1,0).getDate(),S=new Date(this.calViewYear,this.calViewMonth,1).toLocaleDateString("en-US",{month:"long",year:"numeric"}),w=this.calViewYear===v.getFullYear()&&this.calViewMonth===v.getMonth();d.innerHTML=`
377
+ <div class="vnr-month-nav">
378
+ <button class="vnr-nav-btn" id="vnr-prev" ${w?"disabled":""}>
379
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="15 18 9 12 15 6"/></svg>
380
+ </button>
381
+ <span class="vnr-month-label">${S}</span>
382
+ <button class="vnr-nav-btn" id="vnr-next">
383
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="9 18 15 12 9 6"/></svg>
384
+ </button>
385
+ </div>
386
+ <div class="vnr-cal-grid" id="vnr-grid"></div>
387
+ `,d.querySelector("#vnr-prev").addEventListener("click",()=>{this.calViewMonth===0?(this.calViewMonth=11,this.calViewYear--):this.calViewMonth--,y()}),d.querySelector("#vnr-next").addEventListener("click",()=>{this.calViewMonth===11?(this.calViewMonth=0,this.calViewYear++):this.calViewMonth++,y()});const x=d.querySelector("#vnr-grid");["Su","Mo","Tu","We","Th","Fr","Sa"].forEach(C=>{const k=document.createElement("div");k.className="vnr-wd",k.textContent=C,x.appendChild(k)});for(let C=0;C<g;C++){const k=document.createElement("div");x.appendChild(k)}for(let C=1;C<=b;C++){const k=new Date(this.calViewYear,this.calViewMonth,C).getTime(),E=k<v.getTime(),I=k===v.getTime(),L=this.calSelectedTs===k,$=document.createElement("div");$.style.textAlign="center";const D=document.createElement("button");D.className="vnr-day-btn",E&&D.classList.add("vnr-day-past"),I&&!L&&D.classList.add("vnr-day-today"),L&&D.classList.add("vnr-day-sel"),D.disabled=E,D.textContent=String(C),D.addEventListener("click",()=>{this.calSelectedTs=k,this.calSelectedTime=null,f.disabled=!0,y(),this.loadSlots(e,p,f)}),$.appendChild(D),x.appendChild($)}};y()}loadSlots(e,t,r){const s=e.clientFields.slots_api_url;if(!this.calSelectedTs||!s){this.renderSlots(t,["09:00 AM","10:30 AM","01:00 PM","02:30 PM","04:00 PM"],r);return}const i=new Date(this.calSelectedTs),o=i.getFullYear(),a=String(i.getMonth()+1).padStart(2,"0"),l=String(i.getDate()).padStart(2,"0"),c=`${o}-${a}-${l}`,u=e.clientFields.timezone||"",d=fs(o,i.getMonth(),i.getDate(),u),p=d.start,h=d.end,f=w=>{if(typeof w!="string")return w;let x=w.replace(/\{\{date\}\}/g,c).replace(/\{\{timezone\}\}/g,u).replace(/\{\{start_of_day\}\}/g,p.toISOString()).replace(/\{\{end_of_day\}\}/g,h.toISOString());return Object.entries(e.clientFields).forEach(([C,k])=>{if(k!=null){const E=C.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&"),I=new RegExp(`\\{\\{${E}\\}\\}`,"g");x=x.replace(I,String(k))}}),x},y=(e.clientFields.slots_api_method||"GET").toUpperCase();let v={"Content-Type":"application/json"};try{Object.entries(JSON.parse(e.clientFields.slots_api_headers||"{}")).forEach(([w,x])=>{v[w]=f(String(x))})}catch{}let g={};try{Object.entries(JSON.parse(e.clientFields.slots_api_body||"{}")).forEach(([w,x])=>{g[w]=f(String(x))})}catch{}let b=f(s);const S={method:y,headers:v};if(y==="GET"){const w=new URLSearchParams(Object.entries(g).map(([x,C])=>[x,String(C)])).toString();w&&(b+=(b.includes("?")?"&":"?")+w)}else S.body=JSON.stringify(g);t.style.display="block",t.innerHTML='<div class="vnr-divider"></div><div class="vnr-center"><div class="vnr-spinner" style="margin:0 auto 8px"></div>Loading slots…</div>',fetch(b,S).then(w=>{if(!w.ok)throw new Error(`HTTP ${w.status}`);return w.json()}).then(w=>{let x=[];if(Array.isArray(w))x=w;else if(w&&typeof w=="object"){for(const C of["slots","free_slots","times","data","available_slots"])if(Array.isArray(w[C])){x=w[C];break}}this.renderSlots(t,x,r)}).catch(()=>{t.innerHTML='<div class="vnr-divider"></div><div class="vnr-center" style="color:#ef4444">Failed to load slots. Please try again.</div>'})}renderSlots(e,t,r){const s=this.calSelectedTs?new Date(this.calSelectedTs).toLocaleDateString("en-US",{weekday:"long",month:"short",day:"numeric"}):"Available Times",i=t.some(a=>Ye(a).length>8)?2:3;if(e.style.display="block",e.innerHTML=`
388
+ <div class="vnr-divider"></div>
389
+ <div class="vnr-section-label">${s}</div>
390
+ ${t.length===0?'<div class="vnr-center">No slots available for this date.</div>':`<div class="vnr-slots-grid" style="grid-template-columns:repeat(${i},1fr)"></div>`}
391
+ `,t.length===0)return;const o=e.querySelector(".vnr-slots-grid");t.forEach(a=>{const l=document.createElement("button");l.className="vnr-slot-btn",this.calSelectedTime!==null&&(typeof a=="object"&&typeof this.calSelectedTime=="object"?JSON.stringify(a)===JSON.stringify(this.calSelectedTime):a===this.calSelectedTime)&&l.classList.add("vnr-slot-sel"),l.textContent=Ye(a),l.addEventListener("click",()=>{this.calSelectedTime=a,r.disabled=!1,o.querySelectorAll(".vnr-slot-btn").forEach(u=>u.classList.remove("vnr-slot-sel")),l.classList.add("vnr-slot-sel")}),o.appendChild(l)})}collectFormFieldValues(e,t){const r={};for(const s of t){if(s.type==="checkbox"){const o=e.querySelector(`#vnr_${s.id}`);r[s.id]=!!(o!=null&&o.checked);continue}if(s.type==="radio"){const o=e.querySelector(`input[name="vnr_${s.id}"]:checked`);r[s.id]=(o==null?void 0:o.value)??"";continue}const i=e.querySelector(`#vnr_${s.id}`);r[s.id]=String((i==null?void 0:i.value)??"").trim()}return r}appendFormFieldElement(e,t,r){const s=document.createElement("div");s.className="vnr-field-wrap",s.dataset.fieldId=t.id;const i=t.placeholder||`Enter your ${t.label.toLowerCase()}`,o=c=>typeof c=="string"?c:c.value,a=c=>typeof c=="string"?c:c.label;if(t.type!=="checkbox"){const c=document.createElement("label");c.className="vnr-field-label",c.htmlFor=`vnr_${t.id}`,c.textContent=t.required?`${t.label} *`:t.label,s.appendChild(c)}switch(t.type){case"textarea":{const c=document.createElement("textarea");c.className="vnr-input vnr-textarea",c.id=`vnr_${t.id}`,c.rows=4,c.placeholder=i,typeof r=="string"&&(c.value=r),s.appendChild(c);break}case"select":{const c=document.createElement("select");c.className="vnr-input",c.id=`vnr_${t.id}`;const u=document.createElement("option");u.value="",u.textContent="Select…",c.appendChild(u);for(const d of t.options){const p=document.createElement("option");p.value=o(d),p.textContent=a(d),c.appendChild(p)}typeof r=="string"&&r&&(c.value=r),s.appendChild(c);break}case"radio":{const c=document.createElement("div");c.className="vnr-radio-group";const u=typeof r=="string"?r:"";t.options.forEach((d,p)=>{const h=document.createElement("label");h.className="vnr-radio-row";const f=document.createElement("input");f.type="radio",f.name=`vnr_${t.id}`,f.id=`vnr_${t.id}_${p}`;const y=o(d);f.value=y,u&&u===y&&(f.checked=!0);const v=document.createElement("span");v.textContent=a(d),h.appendChild(f),h.appendChild(v),c.appendChild(h)}),s.appendChild(c);break}case"checkbox":{const c=document.createElement("label");c.className="vnr-checkbox-row";const u=document.createElement("input");u.type="checkbox",u.id=`vnr_${t.id}`,u.checked=r===!0||r==="true";const d=document.createElement("span");d.textContent=t.required?`${t.label} *`:t.label,c.appendChild(u),c.appendChild(d),s.appendChild(c);break}default:{const c=document.createElement("input");c.className="vnr-input",c.id=`vnr_${t.id}`,c.placeholder=i,t.type==="phone"?c.type="tel":t.type==="email"||t.type==="number"||t.type==="date"?c.type=t.type:c.type="text",typeof r=="string"&&(c.value=r),s.appendChild(c);break}}const l=document.createElement("p");l.className="vnr-field-error",l.style.display="none",s.appendChild(l),e.appendChild(s)}showFormFieldErrors(e,t){e.querySelectorAll(".vnr-field-wrap").forEach(r=>{var a,l;const s=r.dataset.fieldId;if(!s)return;const i=r.querySelector(".vnr-field-error"),o=t[s];o&&i?(i.textContent=o,i.style.display="block",(a=r.querySelector(".vnr-input, .vnr-textarea"))==null||a.classList.add("vnr-input-error")):i&&(i.style.display="none",(l=r.querySelector(".vnr-input, .vnr-textarea"))==null||l.classList.remove("vnr-input-error"))})}renderForm(e,t,r){this.bindActiveModalPreset(e,m.Form,t,r);const s=v=>{this.clearActiveModalPreset(),t({status:"success",preset_id:m.Form,...v})},i=v=>{this.clearActiveModalPreset(),r(v,{status:"cancelled"})},o=e.args.title||e.clientFields.title||"Please fill out this form",a=e.args.reason||"Please provide the following information.",l=pe(e.args.fields??e.clientFields.fields),c=ps(l,us(e.args,e.clientFields)),u=this.createOverlay(),d=this.createModal(u,o,a);d.querySelector(".vnr-close-btn").addEventListener("click",()=>{this.dismiss(),i("User closed")});const p=document.createElement("div");if(p.className="vnr-fields",l.length===0){const v=document.createElement("p");v.className="vnr-form-error",v.style.color="#dc2626",v.style.fontSize="13px",v.textContent="No form fields configured.",p.appendChild(v)}else l.forEach(v=>this.appendFormFieldElement(p,v,c[v.id]));d.appendChild(p);const h=document.createElement("p");h.className="vnr-form-error",h.style.cssText="display:none;color:#dc2626;font-size:13px;margin:8px 0 0;",d.appendChild(h);const f=document.createElement("div");f.className="vnr-actions",f.style.marginTop="16px",f.innerHTML=`
392
+ <button class="vnr-cancel-btn">Cancel</button>
393
+ <button class="vnr-confirm-btn">
394
+ <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>
395
+ Submit
396
+ </button>
397
+ `,d.appendChild(f),f.querySelector(".vnr-cancel-btn").addEventListener("click",()=>{this.dismiss(),i("User cancelled")});const y=f.querySelector(".vnr-confirm-btn");l.length===0&&(y.disabled=!0),y.addEventListener("click",()=>{if(l.length===0){h.textContent="No form fields configured.",h.style.display="block";return}const v=this.collectFormFieldValues(d,l),g=ls(l,v);if(Object.keys(g).length>0){this.showFormFieldErrors(d,g),h.textContent="Please fix the highlighted fields.",h.style.display="block";const S=Object.keys(g)[0],w=d.querySelector(`[data-field-id="${S}"]`),x=w==null?void 0:w.querySelector("input, textarea, select");x==null||x.focus();return}h.style.display="none",this.showFormFieldErrors(d,{}),y.disabled=!0,y.innerHTML='<div class="vnr-spinner"></div>';const b=ds(l,v);setTimeout(()=>{this.dismiss(),s(b)},300)})}renderCamera(e,t,r,s){this.bindActiveModalPreset(e,m.Camera,t,r);const i=T=>{this.clearActiveModalPreset(),t({status:"success",preset_id:m.Camera,...T})},o=(T,M="cancelled")=>{this.clearActiveModalPreset(),r(T,{status:M})},a=this,l=e.clientFields.title||"Take a Photo",c=e.clientFields.description||"Point your camera at the subject, then tap capture.",u=e.clientFields.facing_mode||e.args.facing_mode||"environment",d=e.clientFields.reason||"camera_capture",p=e.clientFields.liveness_check===!0||e.clientFields.liveness_check==="true"||e.args.liveness_check===!0||e.args.liveness_check==="true";let h=null,f=null;this.stopCaptureCamera(),this.captureActive=!0;const y=this.createOverlay(),v=document.createElement("div");v.className="vnr-modal",v.style.cssText="position:relative;max-width:480px;width:100%",v.innerHTML=`
398
+ <button class="vnr-close-btn" aria-label="Close">
399
+ <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>
400
+ </button>
401
+ <h2 class="vnr-title" style="padding-right:32px">${l}</h2>
402
+ <p style="margin:0 0 14px;font-size:13px;color:#6b7280;line-height:1.5">${c}</p>
403
+
404
+ <div class="vnr-liveness-toggle-wrap" style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:10px;padding:8px 12px">
405
+ <span style="font-size:12px;font-weight:600;color:#374151">Liveness Verification</span>
406
+ <label class="vnr-switch" style="position:relative;display:inline-block;width:34px;height:20px">
407
+ <input type="checkbox" id="vnr-cam-liveness-toggle" style="opacity:0;width:0;height:0">
408
+ <span class="vnr-slider" style="position:absolute;cursor:pointer;inset:0;background-color:#ccc;transition:.3s;border-radius:20px"></span>
409
+ </label>
410
+ </div>
411
+
412
+ <div class="vnr-video-wrap" id="vnr-cam-wrap" style="position:relative">
413
+ <video id="vnr-cam-video" autoplay playsinline muted></video>
414
+ <div id="vnr-cam-guide" style="display:none;position:absolute;inset:0;pointer-events:none;border:3px dashed rgba(255,255,255,0.45);border-radius:50%;margin:auto;width:180px;height:240px;box-shadow:0 0 0 9999px rgba(15,23,42,0.6);transition:border-color 0.3s ease, box-shadow 0.3s ease">
415
+ <div id="vnr-cam-guide-text" style="position:absolute;bottom:-45px;left:-40px;right:-40px;text-align:center;color:#fff;font-size:11px;font-weight:600;background:rgba(15,23,42,0.85);padding:6px 10px;border-radius:6px;border:1px solid rgba(255,255,255,0.1)">
416
+ Align your face
417
+ </div>
418
+ </div>
419
+ <div id="vnr-cam-overlay" style="position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#0f172a">
420
+ <div class="vnr-spinner" style="width:32px;height:32px;border-width:3px;border-color:rgba(255,255,255,.15);border-top-color:#fff"></div>
421
+ <p style="margin:0;font-size:13px;color:#94a3b8">Opening camera…</p>
422
+ </div>
423
+ </div>
424
+
425
+ <div id="vnr-liveness-progress-container" style="display:none;margin-top:12px">
426
+ <div style="display:flex;justify-content:space-between;font-size:11px;font-weight:700;color:#6b7280;margin-bottom:6px;letter-spacing:0.04em">
427
+ <span>LIVENESS ANALYSIS</span>
428
+ <span id="vnr-liveness-pct" style="color:#6366f1">0%</span>
429
+ </div>
430
+ <div style="width:100%;height:6px;background:#f3f4f6;border-radius:3px;overflow:hidden">
431
+ <div id="vnr-liveness-bar" style="width:0%;height:100%;background:#6366f1;transition:width 0.1s linear"></div>
432
+ </div>
433
+ </div>
434
+
435
+ <canvas id="vnr-cam-canvas" style="display:none"></canvas>
436
+ <div id="vnr-cam-status" style="display:none"></div>
437
+ <div class="vnr-actions" style="margin-top:14px">
438
+ <button class="vnr-cancel-btn" id="vnr-cam-cancel">Cancel</button>
439
+ <button class="vnr-confirm-btn" id="vnr-cam-capture" disabled>
440
+ <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
441
+ Capture & Send
442
+ </button>
443
+ </div>
444
+ `,y.appendChild(v);const g=v.querySelector("#vnr-cam-video"),b=v.querySelector("#vnr-cam-canvas"),S=v.querySelector("#vnr-cam-overlay"),w=v.querySelector("#vnr-cam-status"),x=v.querySelector("#vnr-cam-capture"),C=v.querySelector("#vnr-cam-liveness-toggle"),k=v.querySelector("#vnr-liveness-progress-container"),E=v.querySelector("#vnr-liveness-bar"),I=v.querySelector("#vnr-liveness-pct"),L=v.querySelector("#vnr-cam-guide"),$=v.querySelector("#vnr-cam-guide-text"),D=()=>{f&&(clearInterval(f),f=null),this.captureLivenessInterval=null,h==null||h.getTracks().forEach(T=>T.stop()),h=null,a.captureStream=null,g.srcObject=null};v.querySelector(".vnr-close-btn").addEventListener("click",()=>{D(),this.captureActive=!1,this.dismiss(),o("User closed")}),v.querySelector("#vnr-cam-cancel").addEventListener("click",()=>{D(),this.captureActive=!1,this.dismiss(),o("User cancelled")});const O=()=>{this.captureActive&&(S.style.display="flex",S.innerHTML=`
445
+ <div class="vnr-spinner" style="width:32px;height:32px;border-width:3px;border-color:rgba(255,255,255,.15);border-top-color:#fff"></div>
446
+ <p style="margin:0;font-size:13px;color:#94a3b8">Opening camera…</p>
447
+ `,x.disabled=!0,navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:u}},audio:!1}).then(T=>{if(!this.captureActive){T.getTracks().forEach(M=>M.stop());return}return h=T,a.captureStream=T,g.srcObject=T,g.play().catch(()=>{})}).then(()=>{if(!(!this.captureActive||!h)){if(S.style.display="none",!v.querySelector(".vnr-live-badge")){const T=document.createElement("div");T.className="vnr-live-badge",T.innerHTML='<span class="vnr-live-dot"></span>LIVE',v.querySelector("#vnr-cam-wrap").appendChild(T)}C.checked=p,F()}}).catch(()=>{this.captureActive&&(this.notifyCameraPermissionDenied(s,e.toolCallId),this.fillCameraPermissionPrompt(S,{onRetry:O,onDismiss:()=>{D(),this.captureActive=!1,this.dismiss(),o("Camera permission denied","cancelled")}}))}))};O();function F(){f&&(clearInterval(f),f=null,a.captureLivenessInterval=null),C.checked?(k.style.display="block",L.style.display="block",x.disabled=!0,A()):(k.style.display="none",L.style.display="none",x.disabled=!1)}C.addEventListener("change",F);function A(){let T=null;const M=[];let R=1,U=0,J=0,ye=0,ut=!1;const $e=document.createElement("canvas"),ht=$e.getContext("2d");$e.width=80,$e.height=60,E.style.width="0%",E.style.backgroundColor="#6366f1",I.style.color="#6366f1",I.innerText="0%",L.style.borderColor="rgba(255,255,255,0.45)",L.style.boxShadow="0 0 0 9999px rgba(15,23,42,0.6)",$.innerText="Align your face in center",$.style.color="#fff",f=setInterval(()=>{if(!h||g.paused||g.ended)return;ht.drawImage(g,0,0,80,60);const ne=ht.getImageData(0,0,80,60).data;if(T){let ge=0;for(let z=0;z<ne.length;z+=4)ge+=Math.abs(ne[z]-T[z]),ge+=Math.abs(ne[z+1]-T[z+1]),ge+=Math.abs(ne[z+2]-T[z+2]);const be=ge/(ne.length/4*3);if(J===0){ye++,M.push(be);const z=Math.min(100,Math.round(ye/15*100));E.style.width=`${z*.3}%`,I.innerText=`${Math.round(z*.3)}%`,$.innerText="Hold still to calibrate…",$.style.color="#a5b4fc",ye>=15&&(R=M.reduce((gr,br)=>gr+br,0)/M.length,R<.2&&(R=.2),J=1,ye=0,E.style.width="30%",I.innerText="30%")}else if(J===1){$.innerText="Now blink or turn head slightly",$.style.color="#ffd2d2";const z=Math.max(3,R*3.5);if(be>z&&be<30){U+=15,U>70&&(U=70,ut=!0);const Re=30+U;E.style.width=`${Re}%`,I.innerText=`${Re}%`}else ut&&be<=z*1.5&&(J=2,E.style.width="100%",E.style.backgroundColor="#10b981",I.innerText="100%",I.style.color="#10b981",$.innerText="✓ Liveness Verified! Click Capture & Send.",$.style.color="#10b981",L.style.borderColor="#10b981",L.style.boxShadow="0 0 0 9999px rgba(16,185,129,0.2)",x.disabled=!1,f&&(clearInterval(f),f=null,a.captureLivenessInterval=null))}}T=ne},100),a.captureLivenessInterval=f}x.addEventListener("click",async()=>{if(!h||g.videoWidth===0)return;b.width=g.videoWidth,b.height=g.videoHeight,b.getContext("2d").drawImage(g,0,0),D(),v.querySelector("#vnr-cam-wrap").setAttribute("style","display:none"),v.querySelector(".vnr-liveness-toggle-wrap")&&(v.querySelector(".vnr-liveness-toggle-wrap").style.display="none"),k.style.display="none",x.disabled=!0,w.style.display="block",w.innerHTML='<div class="vnr-center"><div class="vnr-spinner" style="margin:0 auto 8px"></div>Sending photo…</div>';try{const M=await new Promise(U=>b.toBlob(J=>U(J),"image/jpeg",.85));if(!M)throw new Error("Capture failed");const R=new File([M],`capture-${Date.now()}.jpg`,{type:"image/jpeg"});if(s&&typeof s.uploadMedia=="function"){const{media_id:U,url:J}=await s.uploadMedia(R,d,"User captured a photo via camera");w.innerHTML='<div class="vnr-center" style="color:#22c55e">✓ Photo sent!</div>',setTimeout(()=>{this.dismiss(),i({file_name:R.name,file_type:R.type,file_size:R.size,media_id:U,url:J,message:"User captured and sent a photo."})},400)}else{const U=b.toDataURL("image/jpeg",.85);w.innerHTML='<div class="vnr-center" style="color:#22c55e">✓ Photo ready!</div>',setTimeout(()=>{this.dismiss(),i({file_name:R.name,data_url:U,message:"User captured a photo."})},400)}}catch(M){w.innerHTML=`<div class="vnr-center" style="color:#ef4444">${(M==null?void 0:M.message)||"Capture failed"}</div>`}})}renderClipRegion(e,t,r,s){const i=e.args??{},o=String(i.reason??e.clientFields.reason??"page_clip"),a=String(i.prompt??i.message??e.clientFields.default_prompt??"").trim(),l=String(e.clientFields.hint??(a?`Select the area to answer: "${a}"`:"Drag to select an area — release to clip.")),c=Number(e.clientFields.min_region_px??24),u=d=>{ze(),r(d,{status:"cancelled"})};if(typeof document>"u"){u("Page clip is only available in browser environments");return}Jr({hint:l,minSizePx:c}).then(async d=>{if(!d){u("User cancelled region selection");return}const p=new File([d.blob],`clip-${Date.now()}.jpg`,{type:"image/jpeg"}),h=a?`User clipped a page region and asked: ${a}`:"User clipped a region of the page and sent it for analysis.";try{await this.completeBlockingMediaTool(s,p,o,{preset_id:m.ClipRegion,region:d.region,viewport:d.viewport,pixel_size:d.pixelSize,prompt:a||void 0,message:h},t)}catch(f){const y=f instanceof Error?f.message:"Clip upload failed";r(y,{status:"cancelled"})}}).catch(d=>{u(d instanceof Error?d.message:"Region clip failed")})}async completeBlockingMediaTool(e,t,r,s,i){const o=e==null?void 0:e.uploadMediaForToolResult;let a,l;if(o&&typeof o=="function")try{const u=await o.call(e,t,r);a=u.media_id,l=u.url}catch{}if(a&&l){i({status:"success",media_id:a,url:l,...s});return}const c=await new Promise((u,d)=>{const p=new FileReader;p.onload=()=>u(String(p.result)),p.onerror=()=>d(new Error("Failed to read media blob")),p.readAsDataURL(t)});i({status:"success",data_url:c,...s})}renderTabScreenshot(e,t,r,s){const i=e.args??{},o=String(i.reason??e.clientFields.reason??"tab_screenshot"),a=String(i.prompt??i.message??e.clientFields.default_prompt??"").trim(),l=Number(i.max_width??e.clientFields.max_width??1280),c=Number(i.max_elements??e.clientFields.max_elements??80);if(typeof document>"u"){r("Tab screenshot is only available in browser environments");return}(async()=>{try{const u=rr({maxElements:Number.isFinite(c)?c:80}),d=Xr(u),h=`${a?`Tab snapshot captured. Context: ${a}`:"Tab snapshot of the visible page captured."}
448
+
449
+ COORDINATES ARE NORMALIZED VIEWPORT (0–1), NOT JPEG PIXELS. viewport=${u.viewport.width}x${u.viewport.height}
450
+
451
+ For screen_ink prefer css_selector (live DOM) OR copy stroke_points from below:
452
+ ${d}`,f={layout:u,elements:u.elements,element_count:u.elements.length,layout_summary:d,coordinate_system:u.coordinate_system,drawing_guide:"Use screen_ink with css_selector for exact placement, or strokes:[{ points: element.stroke_points, close:true }]. Coords are 0–1 viewport fractions."};t({status:"success",preset_id:m.TabScreenshot,viewport:u.viewport,prompt:a||void 0,message:h,...f}),(async()=>{try{let y=await Jt();Number.isFinite(l)&&l>0&&(y=Qt(y,l));const v=await lt(y),g=new File([v],`tab-${Date.now()}.jpg`,{type:"image/jpeg"}),b=s==null?void 0:s.uploadMediaForToolResult;b&&typeof b=="function"&&await b.call(s,g,o)}catch{}})()}catch(u){const d=u instanceof Error?u.message:"Tab screenshot failed";r(d,{status:"cancelled"})}})()}renderUpload(e,t,r,s){this.bindActiveModalPreset(e,m.Upload,t,r);const i=w=>{this.clearActiveModalPreset(),t({status:"success",preset_id:m.Upload,...w})},o=w=>{this.clearActiveModalPreset(),r(w,{status:"cancelled"})},a=e.clientFields.title||"Upload a File",l=e.clientFields.description||"Drop or select a file to send to your agent.",c=e.clientFields.reason||"upload",u=e.clientFields.accept||"image/*,application/pdf,text/plain,text/csv";let d=null;const p=this.createOverlay(),h=document.createElement("div");h.className="vnr-modal",h.style.cssText="position:relative;max-width:480px;width:100%",h.innerHTML=`
453
+ <button class="vnr-close-btn" aria-label="Close">
454
+ <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>
455
+ </button>
456
+ <h2 class="vnr-title" style="padding-right:32px">${a}</h2>
457
+ <p style="margin:0 0 14px;font-size:13px;color:#6b7280;line-height:1.5">${l}</p>
458
+ <div class="vnr-dropzone" id="vnr-drop-zone">
459
+ <div style="font-size:32px;margin-bottom:8px">📁</div>
460
+ <p style="margin:0 0 4px;font-weight:600;color:#374151;font-size:14px">Drag & drop here</p>
461
+ <p style="margin:0 0 14px;color:#9ca3af;font-size:12px">or click to browse</p>
462
+ <span style="display:inline-block;padding:7px 16px;background:#111;color:#fff;border-radius:9px;font-size:13px;font-weight:600">Choose File</span>
463
+ <p style="margin:12px 0 0;font-size:11px;color:#9ca3af">Images, PDF, CSV, Docs · Max 10 MB</p>
464
+ </div>
465
+ <input id="vnr-file-input" type="file" accept="${u}" style="display:none">
466
+ <div id="vnr-file-preview" style="display:none;border:1px solid #e5e7eb;border-radius:12px;padding:14px;background:#f9fafb"></div>
467
+ <div id="vnr-upload-status" style="display:none"></div>
468
+ <div class="vnr-actions" style="margin-top:14px">
469
+ <button class="vnr-cancel-btn" id="vnr-up-cancel">Cancel</button>
470
+ <button class="vnr-confirm-btn" id="vnr-up-submit" disabled>
471
+ <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>
472
+ Upload & Send
473
+ </button>
474
+ </div>
475
+ `,p.appendChild(h);const f=h.querySelector("#vnr-drop-zone"),y=h.querySelector("#vnr-file-input"),v=h.querySelector("#vnr-file-preview"),g=h.querySelector("#vnr-upload-status"),b=h.querySelector("#vnr-up-submit");h.querySelector(".vnr-close-btn").addEventListener("click",()=>{this.dismiss(),o("User closed")}),h.querySelector("#vnr-up-cancel").addEventListener("click",()=>{this.dismiss(),o("User cancelled")});const S=w=>{d=w,f.style.display="none";const x=w.type.startsWith("image/")?"🖼️":w.type.includes("pdf")?"📄":"📁",C=(w.size/1024).toFixed(1);v.style.display="block",v.innerHTML=`
476
+ <div style="display:flex;align-items:center;gap:10px">
477
+ <span style="font-size:28px">${x}</span>
478
+ <div style="flex:1;min-width:0">
479
+ <p style="margin:0;font-weight:600;font-size:13px;color:#111;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${w.name}</p>
480
+ <p style="margin:3px 0 0;font-size:11px;color:#6b7280">${w.type||"unknown"} · ${C} KB</p>
481
+ </div>
482
+ <button id="vnr-remove-file" style="width:30px;height:30px;display:flex;align-items:center;justify-content:center;background:#fff;border:1px solid #e5e7eb;border-radius:8px;cursor:pointer;color:#6b7280;flex-shrink:0">
483
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
484
+ </button>
485
+ </div>
486
+ `,v.querySelector("#vnr-remove-file").addEventListener("click",()=>{d=null,v.style.display="none",f.style.display="block",b.disabled=!0}),b.disabled=!1};f.addEventListener("click",()=>y.click()),f.addEventListener("dragover",w=>{w.preventDefault(),f.classList.add("drag")}),f.addEventListener("dragleave",()=>f.classList.remove("drag")),f.addEventListener("drop",w=>{var C;w.preventDefault(),f.classList.remove("drag");const x=(C=w.dataTransfer)==null?void 0:C.files[0];x&&S(x)}),y.addEventListener("change",()=>{var x;const w=(x=y.files)==null?void 0:x[0];w&&S(w)}),b.addEventListener("click",async()=>{if(!d)return;const w=d;f.style.display="none",v.style.display="none",g.style.display="block",g.innerHTML='<div class="vnr-center"><div class="vnr-spinner" style="margin:0 auto 8px"></div>Uploading…</div>',b.disabled=!0;try{if(s&&typeof s.uploadMedia=="function"){const{media_id:x,url:C}=await s.uploadMedia(w,c,`User uploaded: ${w.name}`);g.innerHTML='<div class="vnr-center" style="color:#22c55e">✓ File sent!</div>',setTimeout(()=>{this.dismiss(),i({file_name:w.name,file_type:w.type,file_size:w.size,media_id:x,url:C,message:`User uploaded: ${w.name}`})},400)}else{const x=new FileReader;x.onload=C=>{g.innerHTML='<div class="vnr-center" style="color:#22c55e">✓ File ready!</div>',setTimeout(()=>{this.dismiss(),i({file_name:w.name,file_type:w.type,file_size:w.size,data_url:C.target.result,message:`User uploaded: ${w.name}`})},400)},x.readAsDataURL(w)}}catch(x){g.innerHTML=`<div class="vnr-center" style="color:#ef4444">${(x==null?void 0:x.message)||"Upload failed. Please try again."}</div>`,b.disabled=!1,this.dismiss(),this.clearActiveModalPreset(),r((x==null?void 0:x.message)||"Upload failed",{status:"cancelled"})}})}extractElementRoute(e){const t=e.args||{},r=e.clientFields||{};return String(t.route||r.route||t.target_route||r.target_route||"").trim()}normalizeRouteForCompare(e){const t=(e.trim()||"/").split("#")[0],r=t.startsWith("/")?t:`/${t}`;try{const s=new URL(r,window.location.origin);return`${s.pathname}${s.search}`||"/"}catch{return r||"/"}}isCurrentRoute(e){const t=this.normalizeRouteForCompare(e);return(`${window.location.pathname}${window.location.search}`||"/")===t}parseDomTarget(e){const t=e.trim();return t?/^[.#\[]/.test(t)||t.includes(" ")||t.includes(">")?{selector:t}:{elementId:t.replace(/^#/,"")}:{}}findDomTarget(e){if(e.selector)try{const t=document.querySelector(e.selector);if(t)return t}catch{}return e.elementId?document.getElementById(e.elementId.replace(/^#/,"")):null}waitForRouteReady(e,t,r=6e3,s=100){return new Promise(i=>{const o=Date.now()+r,a=!!(t.elementId||t.selector),l=()=>{const c=this.isCurrentRoute(e),u=a?!!this.findDomTarget(t):!0;if(c&&u){i(!0);return}if(Date.now()>=o){i(c);return}window.setTimeout(l,s)};window.setTimeout(l,80)})}dispatchAgentNavigate(e,t){Wt(e,{presetId:t.presetId,toolName:t.toolName});const r={url:e,path:e,handled:!1,initiated_by:"agent",preset_id:t.presetId};return window.dispatchEvent(new CustomEvent("vanira:navigate",{detail:r,cancelable:!0})),r}async withElementRoute(e,t,r,s,i){if(!e){s({navigated:!1});return}if(this.isCurrentRoute(e)){s({navigated:!1,route:e});return}const o=this.resolveNavigateTarget(e);if("external"in o){r("Element route must be a same-origin path");return}const a=o.internal;if(!this.dispatchAgentNavigate(a,{presetId:i,toolName:"element_route"}).handled){window.location.assign(a);return}if(!await this.waitForRouteReady(a,t)){r(`Timed out navigating to ${a} for element action`);return}s({navigated:!0,route:a})}resolveNavigateTarget(e){const t=e.trim()||"/";if(t.startsWith("http://")||t.startsWith("https://"))try{const r=new URL(t);return r.origin===window.location.origin?{internal:`${r.pathname}${r.search}${r.hash}`||"/"}:{external:t}}catch{return{internal:t}}return{internal:t}}renderNavigate(e,t,r){var c,u;const s=String(((c=e.clientFields)==null?void 0:c.target_url)||((u=e.args)==null?void 0:u.target_url)||"/"),i=e.toolCallId;if(i&&this.settledNavigateToolCallIds.has(i))return;this.activeNavigate={ctx:e,onComplete:t,onCancel:r,targetUrl:s};const o=this.resolveNavigateTarget(s);if("external"in o){window.open(o.external,"_blank","noopener,noreferrer"),this.completeNavigate({navigation_type:"external"});return}const a=o.internal;if(!this.dispatchAgentNavigate(a,{presetId:m.Navigate,toolName:"vanira_navigate"}).handled){this.cancelNavigate("No SPA listener handled vanira:navigate","cancelled");return}this.completeNavigate({path:a,navigation_type:"internal"})}renderHighlight(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.css_selector||i.css_selector||s.selector||i.selector||""),a=String(s.highlight_color||i.highlight_color||s.color||i.color||"#a855f7"),l=Number(s.duration_ms||i.duration_ms||3e3);if(!o){r("No css_selector provided for highlight");return}const c=document.querySelector(o);if(!c){r(`Element not found for selector: "${o}"`);return}const u=c.style.outline,d=c.style.outlineOffset,p=c.style.boxShadow,h=c.style.transition,f=c.style.scrollMarginTop;c.style.transition="outline 0.2s ease, box-shadow 0.2s ease",c.style.outline=`3px solid ${a}`,c.style.outlineOffset="6px",c.style.boxShadow=`0 0 0 8px ${a}33, 0 0 32px ${a}88`,c.style.scrollMarginTop="100px",c.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(()=>{c.style.outline=u,c.style.outlineOffset=d,c.style.boxShadow=p,c.style.transition=h,c.style.scrollMarginTop=f},l),t({status:"success",preset_id:m.HighlightElement,message:`Element highlighted: ${o}`})}renderScreenInk(e,t,r){const s=e.args||{},i=e.clientFields||{},o=fe(),a=s.interactive===!0||s.user_draw===!0||i.interactive===!0||String(s.interactive??i.interactive??"").toLowerCase()==="true";(async()=>{const l=await o.applyInkFromArgs(s,i),c=l.strokes+l.labels;if(c===0&&!a){r("No valid strokes or labels (provide strokes[], labels[], or points)");return}const u=[];l.strokes>0&&u.push(`${l.strokes} stroke(s)`),l.labels>0&&u.push(`${l.labels} label(s)`),t({status:"success",preset_id:m.ScreenInk,message:a?`Drew ${u.join(" and ")}; user can freehand draw until cleared`:`Drew ${u.join(" and ")}`,stroke_count:l.strokes,label_count:l.labels,annotation_count:c,interactive:a||void 0})})()}renderScreenCursor(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.color||i.color||"#f97316"),a=String(s.label||i.label||""),l=Number(s.duration_ms??i.duration_ms??2500),u=fe().showCursor({x:s.x??i.x,y:s.y??i.y,css_selector:String(s.css_selector||i.css_selector||s.selector||i.selector||"")||void 0,label:a||void 0,color:o,duration_ms:l});if(!u){r("No valid position for screen cursor (provide x/y or css_selector)");return}t({status:"success",preset_id:m.ScreenCursor,message:"Screen cursor shown",x:u.px,y:u.py})}renderScreenClick(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.color||i.color||"#f97316"),a=s.show_ripple??i.show_ripple??!0,l=s.show_cursor??i.show_cursor??!0,c=s.perform_click??i.perform_click??!0,u=String(s.css_selector||i.css_selector||s.selector||i.selector||"").trim();let d,p;if(u){const v=document.querySelector(u);if(!v){r(`Element not found for selector: "${u}"`);return}const g=v.getBoundingClientRect();d=g.left+g.width/2,p=g.top+g.height/2}else{const v=s.x??i.x,g=s.y??i.y;if(v==null||g==null){r("No valid position for screen click (provide x/y or css_selector)");return}const b=window.innerWidth,S=window.innerHeight,w=Number(v),x=Number(g);d=w>=0&&w<=1?w*b:w,p=x>=0&&x<=1?x*S:x}const h=fe();l&&h.showCursor({x:d,y:p,color:o,duration_ms:800}),a&&h.showClickRipple(d,p,o);let f="",y="";if(c){const v=xn(d,p);v&&(Sn(v),f=v.tagName.toLowerCase(),y=v.id||"")}t({status:"success",preset_id:m.ScreenClick,message:c&&f?`Clicked ${f}${y?`#${y}`:""} at (${Math.round(d)}, ${Math.round(p)})`:`Click ripple at (${Math.round(d)}, ${Math.round(p)})`,x:d,y:p,clicked_tag:f||void 0,clicked_id:y||void 0})}renderClickElement(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.element_id||i.element_id||s.id||i.id||"").trim().replace(/^#/,""),a=s.scroll_before_click??i.scroll_before_click??!0,l=this.extractElementRoute(e);if(!o){r("No element_id provided for click");return}this.withElementRoute(l,{elementId:o},r,c=>{this.executeClickElement(o,a,c,t,r)},m.ClickElement)}executeClickElement(e,t,r,s,i){const o=document.getElementById(e);if(!o){i(`Element not found for id: "${e}"`);return}if(!this.isElementClickable(o)){i(`Element matched but is not clickable: "#${e}"`);return}t!==!1&&t!=="false"&&o.scrollIntoView({behavior:"smooth",block:"center"}),o.classList.add("vnr-click-pulse"),window.setTimeout(()=>o.classList.remove("vnr-click-pulse"),450),this.programmaticClick(o),s({status:"success",preset_id:m.ClickElement,element_id:e,...r.route?{route:r.route}:{},...r.navigated?{navigated_to_route:r.route}:{},message:`Clicked element: #${e}`,tag_name:o.tagName.toLowerCase(),element_text:(o.textContent||"").trim().slice(0,120)})}renderSelectOption(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.element_id||i.element_id||s.id||i.id||"").trim().replace(/^#/,""),a=this.extractElementRoute(e),l=String(s.option_value||i.option_value||"").trim(),c=String(s.option_label||i.option_label||s.option_text||i.option_text||"").trim();if(!o){r("No element_id provided for select");return}if(!l&&!c){r("Provide option_value or option_label");return}this.withElementRoute(a,{elementId:o},r,u=>{this.executeSelectOption(o,l,c,u,t,r)},m.SelectOption)}async executeSelectOption(e,t,r,s,i,o){var u,d,p,h;const a=document.getElementById(e);if(!a){o(`Element not found for id: "${e}"`);return}a.scrollIntoView({behavior:"smooth",block:"center"});let l="",c="";if(a instanceof HTMLSelectElement){if(!this.setNativeSelectValue(a,t,r)){o(`No matching option in #${e}`);return}l=a.value,c=((d=(u=a.options[a.selectedIndex])==null?void 0:u.text)==null?void 0:d.trim())||l}else{const f=a.querySelector("select");if(f instanceof HTMLSelectElement){if(!this.setNativeSelectValue(f,t,r)){o(`No matching option in #${e} select`);return}l=f.value,c=((h=(p=f.options[f.selectedIndex])==null?void 0:p.text)==null?void 0:h.trim())||l}else{if(!await this.selectCustomDropdownOption(a,t,r)){o(`Could not select option in #${e}`);return}l=t||r,c=r||t}}i({status:"success",preset_id:m.SelectOption,element_id:e,option_value:l||t,option_label:c||r,...s.route?{route:s.route}:{},...s.navigated?{navigated_to_route:s.route}:{},message:`Selected option in #${e}`})}setNativeSelectValue(e,t,r){const s=t.trim();if(s&&this.applyNativeSelectMatch(e,s,{matchValue:!0,matchLabel:!0}))return!0;const i=r.trim();return!!(i&&this.applyNativeSelectMatch(e,i,{matchValue:!0,matchLabel:!0}))}applyNativeSelectMatch(e,t,r){const s=t.trim();if(!s)return!1;const i=s.toLowerCase();for(const o of Array.from(e.options))if(r.matchValue&&o.value===s)return e.value=o.value,this.dispatchInputChange(e),!0;if(r.matchLabel)for(const o of Array.from(e.options)){const a=o.text.trim().toLowerCase();if(a===i||a.includes(i))return e.value=o.value,this.dispatchInputChange(e),!0}return!1}async selectCustomDropdownOption(e,t,r){this.programmaticClick(e),await new Promise(o=>window.setTimeout(o,200));const s=(r||t||"").trim().toLowerCase(),i=Array.from(document.querySelectorAll('[role="option"], [role="menuitem"], [role="menuitemradio"], li, button, a, div'));for(const o of i){if(!o.offsetParent&&o!==document.activeElement)continue;const a=(o.textContent||"").trim().toLowerCase(),l=o.getAttribute("data-value")||o.getAttribute("value")||"";if(t&&l===t)return this.programmaticClick(o),!0;if(s&&a&&(a===s||a.includes(s)))return this.programmaticClick(o),!0}return!1}renderSetDate(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.element_id||i.element_id||s.id||i.id||"").trim().replace(/^#/,""),a=this.extractElementRoute(e),l=String(s.date||i.date||"").trim(),c=String(s.input_kind||i.input_kind||"text").trim().toLowerCase(),u=String(s.text_format||i.text_format||"YYYY-MM-DD").trim();if(!o){r("No element_id provided for set date");return}if(!this.parseIsoDate(l)){r("date must be ISO YYYY-MM-DD");return}this.withElementRoute(a,{elementId:o},r,d=>{this.executeSetDate(o,l,c,u,d,t,r)},m.SetDate)}executeSetDate(e,t,r,s,i,o,a){const l=document.getElementById(e);if(!l){a(`Element not found for id: "${e}"`);return}if(!(l instanceof HTMLInputElement)&&!(l instanceof HTMLTextAreaElement)){a(`Element #${e} is not an input or textarea`);return}l.scrollIntoView({behavior:"smooth",block:"center"}),l.focus({preventScroll:!0});const c=r==="native_date"||l.type==="date",u=c?t:this.formatIsoDate(t,s);this.setNativeInputValue(l,u),o({status:"success",preset_id:m.SetDate,element_id:e,date:t,formatted_value:u,input_kind:c?"native_date":"text",text_format:c?"YYYY-MM-DD":s,...i.route?{route:i.route}:{},...i.navigated?{navigated_to_route:i.route}:{},message:`Set date on #${e}`})}parseIsoDate(e){const t=String(e).trim().match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const r=parseInt(t[1],10),s=parseInt(t[2],10),i=parseInt(t[3],10);return s<1||s>12||i<1||i>31?null:{y:t[1],mo:t[2],d:t[3],year:r,month:s,day:i}}formatIsoDate(e,t){const r=this.parseIsoDate(e);if(!r)return e;const{y:s,mo:i,d:o,month:a,day:l}=r,c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];switch(t){case"DD/MM/YYYY":return`${o}/${i}/${s}`;case"MM/DD/YYYY":return`${i}/${o}/${s}`;case"DD-MM-YYYY":return`${o}-${i}-${s}`;case"D MMM YYYY":return`${l} ${c[a-1]} ${s}`;case"YYYY-MM-DD":default:return e}}setNativeInputValue(e,t){var i;const r=e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,s=(i=Object.getOwnPropertyDescriptor(r,"value"))==null?void 0:i.set;s?s.call(e,t):e.value=t,this.dispatchInputChange(e)}dispatchInputChange(e){e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0}))}isElementClickable(e){if(e.hasAttribute("disabled")||"disabled"in e&&e.disabled)return!1;const t=window.getComputedStyle(e);return!(t.display==="none"||t.visibility==="hidden"||t.pointerEvents==="none")}programmaticClick(e){try{e.focus({preventScroll:!0})}catch{}const t=e.tagName.toLowerCase(),r=t==="input"?e.type.toLowerCase():"";if((t==="button"||t==="a"||["submit","button","checkbox","radio","reset"].includes(r))&&typeof e.click=="function"){e.click();return}const i={bubbles:!0,cancelable:!0,view:window,button:0,buttons:1};e.dispatchEvent(new MouseEvent("mousedown",i)),e.dispatchEvent(new MouseEvent("mouseup",i)),e.dispatchEvent(new MouseEvent("click",i))}applyBoardSizeToModal(e){const t=_s[this.boardSizePreset],r=this.boardViewMode==="reduced"?.5:1,s=Ut(t.maxWidth,r),i=Ut(t.height,r);e.style.setProperty("width",s,"important"),e.style.setProperty("max-width",s,"important"),e.style.setProperty("height",i,"important"),e.style.setProperty("max-height",i,"important"),e.classList.toggle("is-reduced",r<1),this.boardViewMode==="reduced"&&this.syncBoardDragLayout(e)}syncBoardResizeButton(e){if(!e)return;const t=this.boardViewMode==="reduced";e.innerHTML=t?gs:ys,e.setAttribute("aria-label",t?"Restore board size":"Shrink board to half size"),e.title=t?"Restore board size":"Shrink board to half size"}toggleBoardReduced(e){const t=this.boardViewMode==="reduced";this.boardViewMode=t?"expanded":"reduced",t||(this.boardDragPosition=null),this.applyBoardSizeToModal(e),this.applyBoardLayoutMode(this.getBoardOverlay(),e)}wireChalkboardChrome(e,t){let r=e.querySelector(".vnr-whiteboard-header");if(r){const s=r.querySelector(".vnr-whiteboard-resize-btn");s&&(s.onclick=()=>this.toggleBoardReduced(e));const i=r.querySelector(".vnr-whiteboard-close-btn");i&&(i.onclick=()=>{if(this.activePresetGeneration++,t)try{t()}catch{}this.closeBoardUi()})}else{r=document.createElement("div"),r.className="vnr-whiteboard-header";const s=document.createElement("button");s.type="button",s.className="vnr-whiteboard-action-btn vnr-whiteboard-resize-btn",s.onclick=()=>this.toggleBoardReduced(e);const i=document.createElement("button");i.type="button",i.className="vnr-whiteboard-action-btn is-close vnr-whiteboard-close-btn",i.innerHTML=bs,i.setAttribute("aria-label","Close board"),i.title="Close board",i.onclick=()=>{if(this.activePresetGeneration++,t)try{t()}catch{}this.closeBoardUi()},r.appendChild(s),r.appendChild(i);const o=e.querySelector(".vnr-whiteboard-canvas-wrap");o?e.insertBefore(r,o):e.prepend(r)}this.applyBoardSizeToModal(e),this.applyBoardLayoutMode(this.getBoardOverlay(),e),r&&this.wireBoardDrag(r,e)}wireChalkboardCloseButton(e,t){this.wireChalkboardChrome(e,t)}styleChalkboardTextarea(e){e.style.width="100%",e.style.height="100%",e.style.flex="1",e.style.position="relative",e.style.zIndex="1",e.style.background="transparent",e.style.border="none",e.style.padding="20px 28px 24px",e.style.fontSize="22px",e.style.lineHeight="1.55",e.style.fontFamily="'Architects Daughter', 'Caveat', 'Chalkboard SE', 'Chalkboard', cursive, sans-serif",e.style.color="#ffffff",e.style.textShadow="0 0 3px rgba(255, 255, 255, 0.45), 0 0 8px rgba(255, 255, 255, 0.15)",e.style.outline="none",e.style.resize="none",e.style.boxSizing="border-box"}applySplitBoardLayout(e,t){let r=e.querySelector(".vnr-whiteboard-draw-zone");if(r)return r;j("Board","Applying split layout — diagram top, notes below");const s=e.querySelector(".vnr-whiteboard-draw-layer");r=document.createElement("div"),r.className="vnr-whiteboard-draw-zone",r.style.flex="0 0 42%",r.style.minHeight="0",r.style.position="relative",r.style.width="100%",r.style.borderBottom="1px solid rgba(255,255,255,0.1)",r.style.background="#08080a";const i=document.createElement("div");for(i.className="vnr-whiteboard-text-zone",i.style.flex="1",i.style.minHeight="0",i.style.display="flex",i.style.flexDirection="column",i.style.position="relative",i.style.background="#0a0a0c",i.style.overflow="hidden";e.firstChild;)e.removeChild(e.firstChild);return e.appendChild(r),e.appendChild(i),i.appendChild(t),s?r.appendChild(s):X(r),this.styleChalkboardTextarea(t),this.syncBoardLayout(e),r}syncBoardLayout(e){const t=e.querySelector(".vnr-whiteboard-draw-zone");if(!t)return;const r=this.boardInk.strokes.length>0||this.boardInk.labels.length>0||this.boardDrawInProgress;t.style.display=r?"":"none",t.style.flex=r?"0 0 42%":"0 0 0",t.style.minHeight=r?"200px":"0",this.syncBoardChapterTitle(t),j("Board:Layout",r?"diagram top + notes below":"notes full board",{strokes:this.boardInk.strokes.length,labels:this.boardInk.labels.length})}syncBoardChapterTitle(e){const t=e??document.querySelector(".vnr-whiteboard-draw-zone");if(!t)return;let r=t.querySelector(".vnr-board-chapter-title");if(!this.boardChapterTitle){r==null||r.remove();return}r||(r=document.createElement("div"),r.className="vnr-board-chapter-title",r.style.cssText=["position:absolute","top:10px","left:12px","right:12px","z-index:3","pointer-events:none","text-align:center","color:#4A9EFF",'font-family:"Architects Daughter","Caveat",cursive,sans-serif',"font-size:22px","line-height:1.3","text-shadow:none"].join(";"),t.appendChild(r)),r.textContent=this.boardChapterTitle}getBoardDrawZone(e){const t=this.upgradeChalkboardCanvas(e),r=this.applySplitBoardLayout(t,e);return this.syncBoardLayout(t),r}upgradeChalkboardCanvas(e){let t=e.closest(".vnr-whiteboard-canvas-wrap");if(t)return t;j("Board","Upgrading legacy chalkboard — adding draw layer");const r=e.parentElement;if(!r)return e;t=document.createElement("div"),t.className="vnr-whiteboard-canvas-wrap",t.style.display="flex",t.style.flexDirection="column",t.style.flex="1",t.style.height="100%",t.style.position="relative",r.insertBefore(t,e),t.appendChild(e),e.style.position="relative",e.style.zIndex="1",e.style.background="transparent",this.applySplitBoardLayout(t,e);const s=t.querySelector(".vnr-whiteboard-draw-zone");return(this.boardInk.strokes.length>0||this.boardInk.labels.length>0)&&this.syncDiagramLayer(X(s)),t}ensureChalkboardTextarea(e){let t=document.querySelector(".vnr-whiteboard-textarea");if(t){this.syncChalkboardNotes();const o=this.upgradeChalkboardCanvas(t);this.applySplitBoardLayout(o,t);const a=o.querySelector(".vnr-whiteboard-draw-zone"),l=X(a);l.childElementCount<=1&&(this.boardInk.strokes.length>0||this.boardInk.labels.length>0)&&this.syncDiagramLayer(l);const c=t.closest(".vnr-whiteboard-modal");return c&&(this.wireChalkboardChrome(c,e),this.revealBoardUi(c)),this.syncBoardLayout(o),t}if(!document.getElementById("vnr-chalk-font")){const o=document.createElement("link");o.id="vnr-chalk-font",o.rel="stylesheet",o.href="https://fonts.googleapis.com/css2?family=Architects+Daughter&family=Caveat:wght@400;700&display=swap",document.head.appendChild(o)}const r=this.createOverlay();r.classList.add("vnr-whiteboard-overlay","vnr-whiteboard-overlay-expanded");const s=document.createElement("div");s.className="vnr-modal vnr-whiteboard-modal",s.style.position="relative",s.style.display="flex",s.style.flexDirection="column",s.style.background="#0d0e12",s.style.border="12px solid #5c4033",s.style.borderRadius="16px",s.style.boxShadow="0 25px 60px rgba(0,0,0,0.65), inset 0 0 30px rgba(0,0,0,0.95)",s.style.padding="0",s.style.overflow="hidden",this.applyBoardSizeToModal(s);const i=document.createElement("div");if(i.className="vnr-whiteboard-canvas-wrap",i.style.display="flex",i.style.flexDirection="column",i.style.flex="1",i.style.minHeight="0",i.style.height="auto",i.style.position="relative",t=document.createElement("textarea"),t.className="vnr-whiteboard-textarea",t.placeholder="Notes appear here…",t.value=this.chalkboardContent,t.addEventListener("input",()=>{this.chalkboardContent=t.value}),i.appendChild(t),this.applySplitBoardLayout(i,t),this.syncBoardLayout(i),this.boardInk.strokes.length>0||this.boardInk.labels.length>0){const o=i.querySelector(".vnr-whiteboard-draw-zone");this.syncDiagramLayer(X(o))}return s.appendChild(i),r.appendChild(s),this.wireChalkboardChrome(s,e),t}eraseChalkboardInMemory(e,t){return e==="words"?this.eraseLastWords(this.chalkboardContent,t):(this.boardChapterTitle="","")}renderEraseDrawingBoard(e,t,r){this.syncChalkboardNotes();const s=this.boardInk.strokes.length,i=this.boardInk.labels.length,o=s>0||i>0,a=document.querySelector(".vnr-whiteboard-textarea");if(a){const l=this.getBoardDrawZone(a),c=X(l);Se(c);const u=a.closest(".vnr-whiteboard-canvas-wrap");u&&this.syncBoardLayout(u)}else if(o){this.ensureChalkboardTextarea(()=>r("User dismissed chalkboard"));const l=document.querySelector(".vnr-whiteboard-textarea");if(l){const c=this.getBoardDrawZone(l);Se(X(c));const u=l.closest(".vnr-whiteboard-canvas-wrap");u&&this.syncBoardLayout(u)}}this.boardInk=we(),this.boardDrawInProgress=!1,this.boardChapterTitle="",j("Board:EraseDraw","Cleared diagram panel (notes kept)",{strokesCleared:s,labelsCleared:i}),t({status:"success",preset_id:m.EraseDraw,message:o?`Cleared ${s} stroke(s) and ${i} label(s) from the diagram panel. Written notes were kept.`:"Diagram panel was already empty. Written notes were not changed.",strokes_cleared:s,labels_cleared:i,shapes_cleared:s+i,diagram_cleared:!0,notes_preserved:!0,whiteboard_content:this.chalkboardContent,text_written:this.chalkboardContent,board_snapshot:this.getBoardSnapshot(),...this.buildBoardVerification()})}renderDrawShapes(e,t,r){const s={...e.clientFields||{},...e.args||{}};this.syncChalkboardNotes();const i=Yn(s,e.clientFields||{}),o=this.activePresetGeneration;if(j("Board:Draw","draw_on_board invoked",{toolCallId:e.toolCallId,strokes:i.strokes.length,labels:i.labels.length,clearBefore:i.clearBefore,animate:i.animate,shape_duration_ms:i.durationMs}),!i.clearBefore&&i.strokes.length===0&&i.labels.length===0){Un("Board:Draw","No strokes or labels",s),t({status:"error",preset_id:m.Draw,message:"Provide strokes[] or labels[] (same as vanira_screen_ink), or flat points/path_d/label_text+coords. Use clear_old_diagrams_on_board:true to wipe the diagram.",board_snapshot:this.getBoardSnapshot()});return}const a=this.ensureChalkboardTextarea(()=>r("User dismissed chalkboard"));if(!a){t({status:"error",message:"Could not open chalkboard"});return}this.syncChalkboardNotes();const l=this.getBoardDrawZone(a),c=X(l);if(i.clearBefore){Se(c),this.boardInk=we();const p=a.closest(".vnr-whiteboard-canvas-wrap");p&&this.syncBoardLayout(p),j("Board:Draw","Cleared old diagrams on board (notes kept)")}if(i.strokes.length===0&&i.labels.length===0){t({status:"success",preset_id:m.Draw,message:"Old diagrams cleared from board",strokes_drawn:0,labels_drawn:0,shapes_drawn:0,clear_old_diagrams_on_board:!0,clear_drawings:!0,board_snapshot:this.getBoardSnapshot(),...this.buildBoardVerification()});return}const u=(p,h,f={})=>{this.boardDrawInProgress=!1;const y=o!==this.activePresetGeneration,v=a.closest(".vnr-whiteboard-canvas-wrap");v&&this.syncBoardLayout(v);const g={status:y?"cancelled":"success",preset_id:m.Draw,message:y?`Draw interrupted (${p} stroke(s), ${h} label(s) on board)`:`Drew ${p} stroke(s) and ${h} label(s) on chalkboard`,strokes_drawn:p,labels_drawn:h,shapes_drawn:p+h,shape_duration_ms:i.durationMs,clear_old_diagrams_on_board:i.clearBefore,clear_drawings:i.clearBefore,whiteboard_content:this.chalkboardContent,text_written:this.chalkboardContent,board_snapshot:this.getBoardSnapshot(),...this.buildBoardVerification(),...f};j("Board:Draw","finished",g),t(g)};this.boardDrawInProgress=!0;const d=a.closest(".vnr-whiteboard-canvas-wrap");if(d&&this.syncBoardLayout(d),!i.animate||i.durationMs<=0){this.boardInk.strokes.push(...i.strokes),this.boardInk.labels.push(...i.labels),this.syncDiagramLayer(c),u(i.strokes.length,i.labels.length);return}(this.boardInk.strokes.length>0||this.boardInk.labels.length>0)&&Bt(c,this.boardInk,{strokeColor:i.strokeColor,labelColor:i.labelColor,strokeWidth:i.strokeWidth}),Zn(c,i.strokes,i.labels,{strokeColor:i.strokeColor,labelColor:i.labelColor,strokeWidth:i.strokeWidth,animate:!0,durationMs:i.durationMs,gapMs:i.gapMs,isAborted:()=>o!==this.activePresetGeneration}).then(({strokesDrawn:p,labelsDrawn:h})=>{this.boardInk.strokes.push(...i.strokes),this.boardInk.labels.push(...i.labels);const f={};(p<i.strokes.length||h<i.labels.length)&&(f.flushed_remaining=!0),u(p,h,f)})}renderTypeText(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.element_id||i.element_id||s.css_selector||i.css_selector||s.selector||i.selector||"").trim(),a=o?this.extractElementRoute(e):"",l=c=>{this.executeTypeText(e,t,r,o,c)};if(!a){l({navigated:!1});return}this.withElementRoute(a,this.parseDomTarget(o),r,l,m.TypeText)}executeTypeText(e,t,r,s,i){const o=e.args||{},a=e.clientFields||{};let l=String(o.text_to_type||a.text_to_type||o.text||a.text||o.value||a.value||o.search_query||a.search_query||o.query||a.query||"");const{chapterTitle:c,body:u}=this.splitChapterHeading(l),d=Number(o.delay_ms!==void 0?o.delay_ms:a.delay_ms!==void 0?a.delay_ms:50),p=this.resolveTypingMode(e),h=k=>{const E={...k,...i.route?{route:i.route}:{},...i.navigated?{navigated_to_route:i.route}:{}};if(document.querySelector(".vnr-whiteboard-modal")){E.board_snapshot=this.getBoardSnapshot();const I=document.querySelector(".vnr-whiteboard-canvas-wrap");I&&this.syncBoardLayout(I)}t(E)};let f=null;s&&!c&&(f=this.findDomTarget(this.parseDomTarget(s)));const y=()=>{j("Board:Type","Using chalkboard fallback",{toolCallId:e.toolCallId,textPreview:(u||l).slice(0,80),sessionChars:this.chalkboardContent.length});const k=this.ensureChalkboardTextarea(()=>r("User dismissed typing popup"));if(!k){h({status:"error",message:"Could not open chalkboard"});return}k.focus(),c&&(this.boardChapterTitle=c);const E=c&&!u?l.trim().split(`
487
+ `)[0].trim():u||l;let I=this.chalkboardContent||"";const L=I?`
488
+ ${E}`:E,$=this.activePresetGeneration,D=d<=0;if(this.activeBoardProgress={ctx:e,mode:"type",textAtStart:I,plannedUnits:L.length,unitsDone:0},D){this.chalkboardContent=I+L,k.value=this.chalkboardContent,k.scrollTop=k.scrollHeight;const O=k.closest(".vnr-whiteboard-canvas-wrap");if(O){const F=O.querySelector(".vnr-whiteboard-draw-zone");this.syncBoardChapterTitle(F),this.syncBoardLayout(O)}this.syncBoardProgressUnits(L.length),j("Board:Type","Chalkboard typed (instant)",{chars:this.chalkboardContent.length,preview:this.chalkboardContent.slice(0,120),chapter:c}),h({status:"success",preset_id:m.TypeText,typing_mode:"append",message:"Typed on chalkboard",whiteboard_content:this.chalkboardContent,text_written:this.chalkboardContent,...this.buildBoardVerification()})}else{let O=I,F=0;const A=()=>{if($!==this.activePresetGeneration){this.chalkboardContent=O,k.value=O;return}document.body.contains(k)&&(F<L.length?(O+=L[F],this.chalkboardContent=O,k.value=O,k.scrollTop=k.scrollHeight,F++,this.syncBoardProgressUnits(F),this.scheduleBoardAnim(A,d)):(this.syncBoardProgressUnits(L.length),h({status:"success",preset_id:m.TypeText,typing_mode:"append",message:"Typed on chalkboard",whiteboard_content:this.chalkboardContent,text_written:this.chalkboardContent,...this.buildBoardVerification()})))};A()}};if(!f){y();return}if(f.focus(),!(f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||"value"in f)){f.textContent=l,h({status:"success"});return}const g=f;let b=g.value||"";if(p==="replace"&&b&&(this.setNativeInputValue(g,""),b=""),d<=0){g.value=b+l,this.dispatchInputChange(g),h({status:"success",preset_id:m.TypeText,typing_mode:p,message:`Typed into ${s||"input"}`});return}let S=b,w=0;const x=this.activePresetGeneration,C=()=>{x===this.activePresetGeneration&&document.body.contains(g)&&(w<l.length?(S+=l[w],g.value=S,g.dispatchEvent(new Event("input",{bubbles:!0})),w++,this.scheduleBoardAnim(C,d)):(g.dispatchEvent(new Event("change",{bubbles:!0})),h({status:"success",preset_id:m.TypeText,typing_mode:p,message:`Typed into ${s||"input"}`})))};C()}resolveTypingMode(e){const t=e.args||{},r=e.clientFields||{},s=String(t.typing_mode||r.typing_mode||"append").trim().toLowerCase();return s==="replace"||s==="clear"||s==="clear_first"||s==="erase_and_type"?"replace":"append"}renderEraseText(e,t,r){const s=e.args||{},i=e.clientFields||{},o=String(s.element_id||i.element_id||s.css_selector||i.css_selector||s.selector||i.selector||"").trim(),a=o?this.extractElementRoute(e):"",l=c=>{this.executeEraseText(e,t,r,o,c)};if(!a){l({navigated:!1});return}this.withElementRoute(a,this.parseDomTarget(o),r,l,m.EraseText)}executeEraseText(e,t,r,s,i){const o=e.args||{},a=e.clientFields||{},l=String(o.mode||a.mode||"all").trim().toLowerCase(),c=Number(o.num_words!==void 0?o.num_words:o.words_count!==void 0?o.words_count:o.count!==void 0?o.count:1),u=Number(o.delay_ms!==void 0?o.delay_ms:a.delay_ms!==void 0?a.delay_ms:50),d=w=>{t({...w,...i.route?{route:i.route}:{},...i.navigated?{navigated_to_route:i.route}:{}})};let p=null;if(s&&(p=this.findDomTarget(this.parseDomTarget(s))),p||(p=document.querySelector(".vnr-whiteboard-textarea")),!p&&this.chalkboardContent&&(p=this.ensureChalkboardTextarea(()=>r("User dismissed chalkboard"))),!p){if(this.chalkboardContent){this.chalkboardContent=this.eraseChalkboardInMemory(l,c),d({status:"success",erased_from_memory:!0});return}d({status:"error",message:"Target element not found"});return}if(p.classList.contains("vnr-whiteboard-textarea")){const w=p.closest(".vnr-whiteboard-modal");w&&this.wireChalkboardCloseButton(w,()=>r("User dismissed chalkboard"))}if(!(p instanceof HTMLInputElement)&&!(p instanceof HTMLTextAreaElement)){if(l==="words"){const w=p.textContent||"";p.textContent=this.eraseLastWords(w,c)}else p.textContent="";d({status:"success"});return}const h=p,f=h.value||"";let y="";if(l==="words"?y=this.eraseLastWords(f,c):y="",u<=0){if(h.value=y,h.classList.contains("vnr-whiteboard-textarea")){this.chalkboardContent=y;const w=Math.max(0,f.length-y.length);this.activeBoardProgress={ctx:e,mode:"erase",textAtStart:f,plannedUnits:w,unitsDone:w}}h.dispatchEvent(new Event("input",{bubbles:!0})),h.dispatchEvent(new Event("change",{bubbles:!0})),d({status:"success"});return}const v=this.activePresetGeneration,g=h.classList.contains("vnr-whiteboard-textarea"),b=Math.max(0,f.length-y.length);g&&(this.activeBoardProgress={ctx:e,mode:"erase",textAtStart:f,plannedUnits:b,unitsDone:0});const S=()=>{v===this.activePresetGeneration&&document.body.contains(h)&&(h.value.length>y.length?(h.value=h.value.slice(0,-1),g&&(this.chalkboardContent=h.value,this.syncBoardProgressUnits(f.length-h.value.length)),h.dispatchEvent(new Event("input",{bubbles:!0})),h.classList.contains("vnr-whiteboard-textarea")&&(h.scrollTop=h.scrollHeight),this.scheduleBoardAnim(S,Math.max(10,u/2))):(h.dispatchEvent(new Event("change",{bubbles:!0})),d({status:"success"})))};S()}eraseLastWords(e,t){if(!e)return"";const r=e.trimEnd();if(!r)return"";let s=r;for(let i=0;i<t;i++){const o=s.lastIndexOf(" "),a=s.lastIndexOf(`
489
+ `),l=Math.max(o,a);if(l===-1){s="";break}else s=s.slice(0,l).trimEnd()}return s}}function Ot(n){const e=(n==null?void 0:n.data)||n;return String((e==null?void 0:e.tool_call_id)||(e==null?void 0:e.call_id)||"")}const Cs=V.forwardRef(function({client:e,toolCall:t=null,onCustomTool:r},s){const i=V.useRef(null),o=V.useRef(new Set),a=V.useRef(new Set),l=V.useRef([]),c=V.useRef(!1);V.useEffect(()=>(i.current=new Ss(null),()=>{var h;(h=i.current)==null||h.resetBoardSession()}),[]),V.useEffect(()=>{const h=f=>{var v;const y=f.detail||{};(v=i.current)==null||v.abortBoardTools(y.reason||"Server interrupted",y.toolCallId)};return window.addEventListener(Rt,h),()=>window.removeEventListener(Rt,h)},[]);const u=V.useCallback(()=>{if(c.current||!i.current||!e)return;const h=l.current.shift();if(!h)return;c.current=!0;const f=h.data||h,y=f.arguments||f.args,v=f.client_fields||{},g=ot(v,y,f.name||f.tool_name),b=Ot(h),S=()=>{c.current=!1,l.current.length>0&&u()};if(!g||!Y(g)){r&&r(h),S();return}!Ar(g)&&e.sendContextUpdate&&b&&(e.sendToolResult(b,{status:"popup_shown",message:`The UI preset ${g} is now visible. I am waiting for the user to complete it. STAY SILENT.`}),e.sendContextUpdate({ui_state:"waiting_for_preset_data",tool_status:"active_waiting",visible_preset:g})),i.current.handle(h,x=>{var k,E;if(!b){S();return}const C=typeof x=="string"?{response:x}:x;if(Ge(g)){S();return}if(mt(g)){(C==null?void 0:C.status)!=="cancelled"&&!o.current.has(b)&&(o.current.add(b),e.sendToolResult(b,C)),S();return}if(Je(g)){if((C==null?void 0:C.status)==="cancelled"){S();return}(k=e.triggerActionInterrupt)==null||k.call(e);const I=ft(g,f.name||f.tool_name||"",v);(E=e.sendActionTrigger)==null||E.call(e,I,C),S();return}e.triggerActionInterrupt&&e.triggerActionInterrupt(),e.sendActionTrigger?e.sendActionTrigger(ft(g,f.name||f.tool_name||"",v),C):e.sendToolResult(b,C),S()},(x,C)=>{var k,E;if(!b){S();return}if(mt(g)){const I=(C==null?void 0:C.status)??"cancelled",L=String(v.target_url||(typeof y=="object"&&y?y.target_url:"")||"");o.current.has(b)||(o.current.add(b),e.sendToolResult(b,g===m.Navigate?((k=i.current)==null?void 0:k.getNavigateTerminalResult(I,x,L||void 0))??{status:I,reason:x||"Navigation cancelled",preset_id:g,target_url:L||void 0}:((E=i.current)==null?void 0:E.getBoardTerminalResult(I,x,g))??{status:I,reason:x||"User dismissed",preset_id:g})),S();return}if(Ge(g))try{e.sendToolResult(b,{status:"cancelled",reason:x||"User dismissed",preset_id:g})}catch{}else if(Je(g))if(typeof e.sendToolError=="function")e.sendToolError(b,x||"User cancelled the action");else try{e.sendToolResult(b,{status:"cancelled",reason:x||"User dismissed",preset_id:g})}catch{}else typeof e.sendToolError=="function"&&e.sendToolError(b,x||"User cancelled the action");S()},e)||(r&&r(h),S())},[e,r]),d=V.useCallback(h=>{const f=Ot(h);if(f){if(a.current.has(f))return;a.current.add(f)}l.current.push(h),u()},[u]),p=V.useCallback(()=>{var h,f;l.current=[],c.current=!1,a.current.clear(),o.current.clear(),(h=i.current)!=null&&h.hasActiveBoardSession()||((f=i.current)==null||f.dismiss(),Me())},[]);return V.useImperativeHandle(s,()=>({enqueueToolCall:d,clearQueue:p}),[d,p]),V.useEffect(()=>{t&&d(t)},[t,d]),V.useEffect(()=>{e||p()},[e,p]),null});class ks{constructor(e){_(this,"el");this.el=new Audio,this.el.srcObject=e,this.el.play().catch(t=>{})}pause(){}cleanup(){this.el.pause(),this.el.srcObject=null}onEnded(e){this.el.onended=e}}class Es{createRemotePlayer(e){return new ks(e)}}class Ts{async getUserAudio(e){return navigator.mediaDevices.getUserMedia({audio:e})}stopStream(e){e.getTracks().forEach(t=>t.stop())}}class As{create(e){return new RTCPeerConnection({iceServers:e.iceServers,iceTransportPolicy:e.iceTransportPolicy??"all"})}}class Is{bind(e,t){return e.onopen=()=>t.onOpen(),e.onerror=r=>t.onError(r),e.onmessage=r=>{if(typeof r.data=="string"){t.onMessage({text:r.data});return}if(r.data instanceof ArrayBuffer){try{const s=new TextDecoder().decode(r.data),i=JSON.parse(s);jt(i)&&t.onMessage({text:s})}catch{}return}r.data instanceof Blob&&r.data.text().then(s=>{t.onMessage({text:s})}).catch(s=>{})},{send(r){e.readyState==="open"&&e.send(r)},isOpen(){return e.readyState==="open"},close(){e.close()}}}}var Ft;const vr={supportsAudioEndedEvent:!0,supportsScreenShare:typeof navigator<"u"&&typeof((Ft=navigator.mediaDevices)==null?void 0:Ft.getDisplayMedia)=="function",supportsDom:typeof document<"u",supportsHtmlAudio:typeof Audio<"u",supportsCustomElements:typeof customElements<"u",supportsLocalStorage:typeof localStorage<"u",supportsBroadcastChannel:typeof BroadcastChannel<"u"},yr={name:"browser",callType:"web",runtimeName:"browser",callIdPrefix:"web_",capabilities:vr,audio:new Es,media:new Ts,peer:new As,dataChannel:new Is};function Ls(n){return new Le({...n,runtime:yr})}exports.PresetRenderer=Cs;exports.RouteContextTracker=Yt;exports.VaniraClient=Le;exports.browserCapabilities=vr;exports.browserRuntime=yr;exports.createBrowserClient=Ls;exports.getCurrentPageRoute=he;exports.hasContinueSession=Br;exports.loadContinueSession=Ie;exports.markAgentNavigation=Wt;exports.normalizePageRoute=at;exports.saveCallSession=Ht;