@d-id/client-sdk 1.2.9 → 1.2.10-staging.374

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -115,13 +115,23 @@ The `agentManager` object created during initialization has several built-in met
115
115
  });
116
116
  ```
117
117
 
118
+ Text scripts also accept an optional `sentiment` (expressive avatars only). If the requested sentiment is not supported by the agent, the default sentiment is used.
119
+
120
+ ```javascript Text with sentiment - JavaScript
121
+ let speak = agentManager.speak({
122
+ type: 'text',
123
+ input: "Hi! I'm Alice!",
124
+ sentiment: 'friendly',
125
+ });
126
+ ```
127
+
118
128
  ```javascript Audio File - JavaScript
119
129
  let speak = agentManager.speak(
120
130
  {
121
131
  type: "audio",
122
- audio_url: "http://www.yourwebsite.com/audio.mp3";
132
+ audio_url: "http://www.yourwebsite.com/audio.mp3"
123
133
  }
124
- )
134
+ );
125
135
  ```
126
136
 
127
137
  - **`agentManager.chat(string)`**
@@ -395,7 +395,7 @@ function Be(e) {
395
395
  function ge(e) {
396
396
  return e instanceof G ? e.toJson() : { kind: "UnknownError", message: Bt(e) || "UnknownError" };
397
397
  }
398
- const Jt = "1.2.9", Ot = "https://api-js.mixpanel.com/track/?verbose=1&ip=1", Ze = 50, Z = [];
398
+ const Jt = "1.2.10-staging.374", Ot = "https://api-js.mixpanel.com/track/?verbose=1&ip=1", Ze = 50, Z = [];
399
399
  let pe = !1;
400
400
  async function et(e) {
401
401
  const t = await fetch(Ot, {
@@ -1190,7 +1190,7 @@ async function yn(e, t, n, i) {
1190
1190
  const { version: o, ...s } = t;
1191
1191
  switch (s.transport.provider) {
1192
1192
  case Se.Livekit:
1193
- const { createLiveKitStreamingManager: r } = await import("./livekit-manager-DuYnmxDa.js");
1193
+ const { createLiveKitStreamingManager: r } = await import("./livekit-manager-Dr9FMFme.js");
1194
1194
  return r(c, s, n);
1195
1195
  default:
1196
1196
  throw new Error(`Unsupported transport provider: ${s.transport.provider}`);
@@ -1408,7 +1408,7 @@ async function Ln(e, t) {
1408
1408
  }, a = Wt({
1409
1409
  token: i,
1410
1410
  agentId: e,
1411
- isEnabled: t.enableAnalitics,
1411
+ isEnabled: t.enableAnalytics ?? t.enableAnalitics,
1412
1412
  externalId: t.externalId,
1413
1413
  mixpanelAdditionalProperties: t.mixpanelAdditionalProperties
1414
1414
  }), d = Date.now();
@@ -1738,7 +1738,8 @@ async function Ln(e, t) {
1738
1738
  provider: f.presenter.voice,
1739
1739
  input: l.input,
1740
1740
  ssml: l.ssml,
1741
- should_queue_speaks: l.should_queue_speaks
1741
+ should_queue_speaks: l.should_queue_speaks,
1742
+ sentiment: l.sentiment
1742
1743
  };
1743
1744
  }
1744
1745
  return l;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as e, k as r, B as t, m as o, o as n, p as i, C as S, f as p, g as d, D as g, H as c, K as E, N as m, P as y, q as C, R as P, r as T, e as v, S as A, b as D, j as V, s as l, T as u, U as h, V as w, u as M, v as K, W as N, w as R, x as b, y as f, z as j } from "./index-Gnq_YadB.js";
1
+ import { A as e, k as r, B as t, m as o, o as n, p as i, C as S, f as p, g as d, D as g, H as c, K as E, N as m, P as y, q as C, R as P, r as T, e as v, S as A, b as D, j as V, s as l, T as u, U as h, V as w, u as M, v as K, W as N, w as R, x as b, y as f, z as j } from "./index-Mm1kFqJw.js";
2
2
  export {
3
3
  e as AgentActivityState,
4
4
  r as AgentStatus,
@@ -1,4 +1,4 @@
1
- (function(G,Ce){typeof exports=="object"&&typeof module<"u"?Ce(exports):typeof define=="function"&&define.amd?define(["exports"],Ce):(G=typeof globalThis<"u"?globalThis:G||self,Ce(G.index={}))})(this,(function(G){"use strict";var Cv=Object.defineProperty;var Ev=(G,Ce,dn)=>Ce in G?Cv(G,Ce,{enumerable:!0,configurable:!0,writable:!0,value:dn}):G[Ce]=dn;var Nt=(G,Ce,dn)=>Ev(G,typeof Ce!="symbol"?Ce+"":Ce,dn);class Ce extends Error{constructor(e,t="Error",i){super(e),this.kind=t,this.originalError=i,Object.setPrototypeOf(this,new.target.prototype)}toJson(){const e=this.originalError instanceof Error?this.originalError.message.slice(0,256):void 0;return{kind:this.kind,message:this.message,...e&&e!==this.message?{cause:e}:{}}}}function dn(n){return n instanceof Error&&typeof n.kind=="string"}class Zs extends Ce{constructor(e,t){super(`Failed to create ${t?"persistent":""} chat, mode: ${e}`,"ChatCreationFailed")}}class ea extends Ce{constructor(e){super(`Chat mode downgraded to ${e}`,"ChatModeDowngraded")}}function Kl(n){try{const e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.kind=="string")return e}catch{}}class ar extends Ce{constructor(t,i,r={}){const s=Kl(i);super(((s==null?void 0:s.description)??i).slice(0,256),(s==null?void 0:s.kind)??"HttpError");Nt(this,"status");Nt(this,"url");Nt(this,"method");this.status=t,this.url=r.url,this.method=r.method}toJson(){return{...super.toJson(),httpStatus:this.status,...this.url?{endpoint:this.url}:{},...this.method?{method:this.method}:{}}}}class ta extends Ce{constructor(t,i={}){super("Network request failed","NetworkError",t);Nt(this,"endpoint");Nt(this,"method");Nt(this,"durationMs");Nt(this,"online");Nt(this,"visibility");this.endpoint=i.url,this.method=i.method,this.durationMs=i.durationMs,this.online=i.online,this.visibility=i.visibility}toJson(){return{...super.toJson(),...this.endpoint?{endpoint:this.endpoint}:{},...this.method?{method:this.method}:{},...this.durationMs!==void 0?{durationMs:this.durationMs}:{},...this.online!==void 0?{online:this.online}:{},...this.visibility?{visibility:this.visibility}:{}}}}class oi extends Ce{constructor(e,t){super(e,"StreamError",t)}}class He extends Ce{constructor(e,t){super(e,"ValidationError"),this.key=t}}class na extends Ce{constructor(e){super(e,"WSError")}}var ia=(n=>(n.TRIAL="trial",n.BASIC="basic",n.ENTERPRISE="enterprise",n.LITE="lite",n.ADVANCED="advanced",n))(ia||{}),ra=(n=>(n.TRIAL="deid-trial",n.PRO="deid-pro",n.ENTERPRISE="deid-enterprise",n.LITE="deid-lite",n.ADVANCED="deid-advanced",n.BUILD="deid-api-build",n.LAUNCH="deid-api-launch",n.SCALE="deid-api-scale",n))(ra||{}),sa=(n=>(n.Created="created",n.Started="started",n.Done="done",n.Error="error",n.Rejected="rejected",n.Ready="ready",n))(sa||{}),aa=(n=>(n.Unrated="Unrated",n.Positive="Positive",n.Negative="Negative",n))(aa||{}),Pe=(n=>(n.Functional="Functional",n.TextOnly="TextOnly",n.Maintenance="Maintenance",n.Playground="Playground",n.DirectPlayback="DirectPlayback",n.Off="Off",n))(Pe||{}),xe=(n=>(n.Embed="embed",n.Query="query",n.Partial="partial",n.Answer="answer",n.Transcribe="transcribe",n.Complete="done",n))(xe||{}),oa=(n=>(n.KnowledgeProcessing="knowledge/processing",n.KnowledgeIndexing="knowledge/indexing",n.KnowledgeFailed="knowledge/error",n.KnowledgeDone="knowledge/done",n))(oa||{}),ca=(n=>(n.Knowledge="knowledge",n.Document="document",n.Record="record",n))(ca||{}),da=(n=>(n.Pdf="pdf",n.Text="text",n.Html="html",n.Word="word",n.Json="json",n.Markdown="markdown",n.Csv="csv",n.Excel="excel",n.Powerpoint="powerpoint",n.Archive="archive",n.Image="image",n.Audio="audio",n.Video="video",n))(da||{}),or=(n=>(n.Clip="clip",n.Talk="talk",n.Expressive="expressive",n))(or||{});const Wl=n=>{switch(n){case"clip":return"clip";case"talk":return"talk";case"expressive":return"expressive";default:throw new Error(`Unknown video type: ${n}`)}};var Z=(n=>(n.Start="START",n.Stop="STOP",n))(Z||{}),rt=(n=>(n.Strong="STRONG",n.Weak="WEAK",n.Unknown="UNKNOWN",n))(rt||{}),fe=(n=>(n.Idle="IDLE",n.Loading="LOADING",n.Talking="TALKING",n.ToolActive="TOOL_ACTIVE",n))(fe||{}),Q=(n=>(n.ChatAnswer="chat/answer",n.ChatPartial="chat/partial",n.ChatAudioTranscribed="chat/audio-transcribed",n.StreamDone="stream/done",n.StreamStarted="stream/started",n.StreamFailed="stream/error",n.StreamReady="stream/ready",n.StreamCreated="stream/created",n.StreamInterrupt="stream/interrupt",n.StreamVideoCreated="stream-video/started",n.StreamVideoDone="stream-video/done",n.StreamVideoError="stream-video/error",n.StreamVideoRejected="stream-video/rejected",n.ToolCallStarted="tool-call/started",n.ToolCallDone="tool-call/done",n.ToolCallError="tool-call/error",n))(Q||{}),le=(n=>(n.New="new",n.Fail="fail",n.Connected="connected",n.Connecting="connecting",n.Closed="closed",n.Completed="completed",n.Disconnecting="disconnecting",n.Disconnected="disconnected",n))(le||{}),st=(n=>(n.Legacy="legacy",n.Fluent="fluent",n))(st||{}),ci=(n=>(n.Livekit="livekit",n))(ci||{}),la=(n=>(n.Amazon="amazon",n.AzureOpenAi="azure-openai",n.Microsoft="microsoft",n.Afflorithmics="afflorithmics",n.Elevenlabs="elevenlabs",n))(la||{}),ua=(n=>(n.Public="public",n.Premium="premium",n.Private="private",n))(ua||{});const Hl=(...n)=>{},ha=n=>new Promise(e=>setTimeout(e,n)),Gt=(n=16)=>{const e=new Uint8Array(n);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,13)};function cr(n){if(n!==void 0)return window.localStorage.setItem("did_external_key_id",n),n;let e=window.localStorage.getItem("did_external_key_id");if(!e){let t=Gt();window.localStorage.setItem("did_external_key_id",t),e=t}return e}let di=Gt();function Jl(){di=Gt()}function ma(n,e){if(n.type==="bearer")return`Bearer ${n.token}~${di}`;if(n.type==="basic")return`Basic ${"token"in n?n.token:btoa(`${n.username}:${n.password}`)}~${di}`;if(n.type==="key")return`Client-Key ${n.clientKey}.${cr(e)}_${di}`;throw new Error(`Unknown auth type: ${n}`)}const Gl=45*1e3,zl="X-Playground-Chat",fa=2e3,Mn="https://api.d-id.com",$l="wss://notifications.d-id.com",Ql="79f81a83a67430be2bc0fd61042b8faa",pa=n=>n.type==="clip"&&n.presenter_id.startsWith("v2_")?"clip_v2":n.type,Yl=n=>{switch(n.type){case"expressive":return"v4";case"clip":return"v3-pro";case"talk":return"v2"}},Xl=n=>n.type==="talk"?n.source_url:n.presenter_id,dr=n=>n===or.Expressive,Zl=n=>[Pe.TextOnly,Pe.Playground,Pe.Maintenance].includes(n),ga=n=>n&&[Pe.DirectPlayback,Pe.Off].includes(n),va=/\[!\[([^\[\]]*)\]\(([^)\s]+)\)\]\(([^)\s]+)\)/g,ya=/!\[([^\[\]]*)\]\(([^)\s]+)\)/g,eu=[".mp4",".webm",".mkv",".mov",".m4v",".ogv"];function tu(n){const e=n.split("?")[0].split("#")[0].toLowerCase();return eu.some(t=>e.endsWith(t))}const ba=new RegExp("(?<!!)\\[([^\\[\\]]+)\\]\\(([^)\\s]+)\\)","g"),ka=/<a\s+href="([^"]*)"[^>]*?>([^<]*)<\/a>/gi;function Ta(n){if(n.length===0)return[];const e=[];let t;for(va.lastIndex=0;(t=va.exec(n))!==null;)e.push({index:t.index,length:t[0].length,part:{type:"video",src:t[3],alt:t[1],thumbnail:t[2]}});for(ya.lastIndex=0;(t=ya.exec(n))!==null;)if(!e.some(o=>t.index>=o.index&&t.index<o.index+o.length)){const o=t[2],a=t[1];let c;tu(o)?c={type:"video",src:o,alt:a}:(c={type:"image",src:o,alt:a},o.toLowerCase().endsWith(".gif")&&(c.mimeType="image/gif")),e.push({index:t.index,length:t[0].length,part:c})}for(ba.lastIndex=0;(t=ba.exec(n))!==null;)e.some(o=>t.index>=o.index&&t.index<o.index+o.length)||e.push({index:t.index,length:t[0].length,part:{type:"link",href:t[2],label:t[1]}});for(ka.lastIndex=0;(t=ka.exec(n))!==null;)e.some(o=>t.index>=o.index&&t.index<o.index+o.length)||e.push({index:t.index,length:t[0].length,part:{type:"link",href:t[1],label:t[2]}});if(e.length===0)return[{type:"text",text:n}];e.sort((s,o)=>s.index-o.index);const i=[];let r=0;for(const s of e)s.index>r&&i.push({type:"text",text:n.slice(r,s.index)}),i.push(s.part),r=s.index+s.length;return r<n.length&&i.push({type:"text",text:n.slice(r)}),i}let Sa="",lr=[];function On(n){return n===Sa||(Sa=n,lr=Ta(n)),lr}function nu(n,e){let t;return{promise:new Promise((r,s)=>{t=setTimeout(()=>s(new Error(e)),n)}),clear:()=>clearTimeout(t)}}async function ur(n,e){const t={limit:(e==null?void 0:e.limit)??3,delayMs:(e==null?void 0:e.delayMs)??0,timeout:(e==null?void 0:e.timeout)??3e4,timeoutErrorMessage:(e==null?void 0:e.timeoutErrorMessage)||"Timeout error",shouldRetryFn:(e==null?void 0:e.shouldRetryFn)??(()=>!0),onRetry:(e==null?void 0:e.onRetry)??(()=>{})};let i;for(let r=1;r<=t.limit;r++)try{if(!t.timeout)return await n();const{promise:s,clear:o}=nu(t.timeout,t.timeoutErrorMessage),a=n().finally(o);return await Promise.race([a,s])}catch(s){if(i=s,!t.shouldRetryFn(s)||r>=t.limit)throw s;await ha(t.delayMs),t.onRetry(s)}throw i}const iu=n=>ur(n,{limit:3,delayMs:1e3,timeout:0,shouldRetryFn:e=>e.status===429});function hr(n,e=Mn,t,i){const r=async(s,o)=>{const{skipErrorHandler:a,...c}=o||{},d=c.method??"GET",l=performance.now();let u;try{u=await iu(()=>fetch(e+(s!=null&&s.startsWith("/")?s:`/${s}`),{...c,headers:{...c.headers,Authorization:ma(n,i),"Content-Type":"application/json"}}))}catch(h){if((h==null?void 0:h.name)==="AbortError")throw h;const v=new ta(h,{url:s,method:d,durationMs:Math.round(performance.now()-l),online:typeof navigator<"u"?navigator.onLine:void 0,visibility:typeof document<"u"?document.visibilityState:void 0});throw a||t==null||t(v,{url:s,options:c}),v}if(!u.ok){const h=await u.text().catch(()=>`Failed to fetch with status ${u.status}`),m=new ar(u.status,h,{url:s,method:d});throw a||t==null||t(m,{url:s,options:c,headers:u.headers}),m}return u.json()};return{get(s,o){return r(s,{...o,method:"GET"})},post(s,o,a){return r(s,{...a,body:JSON.stringify(o),method:"POST"})},delete(s,o,a){return r(s,{...a,body:JSON.stringify(o),method:"DELETE"})},patch(s,o,a){return r(s,{...a,body:JSON.stringify(o),method:"PATCH"})}}}function ru(n,e=Mn,t,i){const r=hr(n,`${e}/agents`,t,i);return{create(s,o){return r.post("/",s,o)},getAgents(s,o){return r.get(`/${s?`?tag=${s}`:""}`,o).then(a=>a??[])},getById(s,o){return r.get(`/${s}`,o)},delete(s,o){return r.delete(`/${s}`,void 0,o)},update(s,o,a){return r.patch(`/${s}`,o,a)},newChat(s,o,a){return r.post(`/${s}/chat`,o,a)},chat(s,o,a,c){return r.post(`/${s}/chat/${o}`,a,c)},createRating(s,o,a,c){return r.post(`/${s}/chat/${o}/ratings`,a,c)},updateRating(s,o,a,c,d){return r.patch(`/${s}/chat/${o}/ratings/${a}`,c,d)},deleteRating(s,o,a,c){return r.delete(`/${s}/chat/${o}/ratings/${a}`,c)},submitFeedback(s,o,a,c){return r.post(`/${s}/chat/${o}/feedback`,a,c)},getSTTToken(s,o){return r.get(`/${s}/stt-token`,o)}}}function su(n){var r,s,o,a;const e=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",t=()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"},i=n.presenter;return{$os:`${t()}`,isMobile:`${e()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:pa(i),agentVoice:{voiceId:(s=(r=n.presenter)==null?void 0:r.voice)==null?void 0:s.voice_id,provider:(a=(o=n.presenter)==null?void 0:o.voice)==null?void 0:a.type}}}function au(n){var t,i,r,s,o,a;const e=(t=n.llm)==null?void 0:t.prompt_customization;return{agentType:pa(n.presenter),presenterType:Yl(n.presenter),presenter:Xl(n.presenter),owner_id:n.owner_id??"",promptVersion:(i=n.llm)==null?void 0:i.prompt_version,behavior:{role:e==null?void 0:e.role,personality:e==null?void 0:e.personality,instructions:(r=n.llm)==null?void 0:r.instructions},temperature:(s=n.llm)==null?void 0:s.temperature,knowledgeSource:e==null?void 0:e.knowledge_source,starterQuestionsCount:(a=(o=n.knowledge)==null?void 0:o.starter_message)==null?void 0:a.length,topicsToAvoid:e==null?void 0:e.topics_to_avoid,maxResponseLength:e==null?void 0:e.max_response_length,agentId:n.id,access:n.access,agentName:n.preview_name,...n.access==="public"?{from:"agent-template"}:{}}}const ou=n=>{try{return String((n==null?void 0:n.message)??n??"").slice(0,256)}catch{return"Unknown error"}},cu=n=>n.reduce((e,t)=>e+t,0),Ca=n=>cu(n)/n.length,Ea=n=>Math.min(...n),wa=n=>Math.max(...n),li=(n,e=0)=>{const t=10**e;return Math.round(n*t)/t},du=(n,e)=>{const t=[...n].sort((i,r)=>i-r);return t[Math.min(t.length-1,Math.floor(e*(t.length-1)))]},lu=n=>du(n,.5),uu=(n,e)=>{try{return n()}catch{return e}};function hu(n,e,t){var c,d,l;const{event:i,...r}=n,{template:s}=(e==null?void 0:e.llm)||{},{language:o}=((c=e==null?void 0:e.presenter)==null?void 0:c.voice)||{};return{...r,llm:{...r.llm,template:s},script:{...r.script,provider:{...(d=r==null?void 0:r.script)==null?void 0:d.provider,language:o}},stitch:(e==null?void 0:e.presenter.type)==="talk"?(l=e==null?void 0:e.presenter)==null?void 0:l.stitch:void 0,...t}}function _a(n){"requestIdleCallback"in window?requestIdleCallback(n,{timeout:2e3}):setTimeout(n,0)}function ui(n){return n instanceof Ce?n.toJson():{kind:"UnknownError",message:ou(n)||"UnknownError"}}const Ra="1.2.9",mu="https://api-js.mixpanel.com/track/?verbose=1&ip=1",Pa=50,zt=[];let mr=!1;async function Ia(n){const e=await fetch(mu,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify(n)})});if(!e.ok)throw new Error(`Mixpanel responded with ${e.status}`)}function fu(n){zt.push(n),zt.splice(Pa)}function fr(){if(mr||!zt.length)return;mr=!0;const n=zt.splice(0,zt.length);Ia(n).catch(()=>{zt.unshift(...n),zt.splice(Pa)}).finally(()=>{mr=!1})}typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("online",fr),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&fr()}));function pu(n){const e=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={};return{token:n.token||"testKey",distinct_id:cr(n.externalId),agentId:n.agentId,additionalProperties:{id:cr(n.externalId),...n.mixpanelAdditionalProperties||{}},isEnabled:n.isEnabled??!0,getRandom:Gt,enrich(i){this.additionalProperties={...this.additionalProperties,...i}},async track(i,r,s){if(!this.isEnabled)return Promise.resolve();const{audioPath:o,...a}=r||{},c=s||Date.now(),d={event:i,properties:{...this.additionalProperties,...a,agentId:this.agentId,source:e,emittedBy:"agents-sdk",sdkVersion:Ra,token:this.token,time:c,$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerHeight,"Screen Width":window.screen.width||window.innerWidth,"User Agent":navigator.userAgent}};return fr(),Ia([d]).catch(()=>fu(d)),Promise.resolve()},linkTrack(i,r,s,o){t[i]||(t[i]={events:{},resolvedDependencies:[]}),o.includes(s)||o.push(s);const a=t[i];if(a.events[s]={props:r},a.resolvedDependencies.push(s),o.every(d=>a.resolvedDependencies.includes(d))){const d=o.reduce((l,u)=>a.events[u]?{...l,...a.events[u].props}:l,{});this.track(i,d),a.resolvedDependencies=a.resolvedDependencies.filter(l=>!o.includes(l)),o.forEach(l=>{delete a.events[l]})}}}}function pr(){let n=0;return{reset:()=>n=0,update:()=>n=Date.now(),get:(e=!1)=>e?Date.now()-n:n}}const pt=pr(),gr=pr(),Ma=pr();function Oa(n){return n===Pe.Playground?{headers:{[zl]:"true"}}:{}}async function Da(n,e,t,i,r=!1,s){return!s&&!ga(i)&&(s=await e.newChat(n.id,{persist:r},Oa(i)),t.track("agent-chat",{event:"created",chatId:s.id,mode:i})),{chat:s,chatMode:(s==null?void 0:s.chat_mode)??i}}function gu(n){return n&&n.length>0?n:[]}function vu(n){return new Promise((e,t)=>{const{callbacks:i,host:r,auth:s,externalId:o}=n,{onMessage:a=null,onOpen:c=null,onClose:d=null,onError:l=null}=i||{},u=new WebSocket(`${r}?authorization=${encodeURIComponent(ma(s,o))}`);u.onmessage=a,u.onclose=d,u.onerror=h=>{console.error(h),l==null||l("Websocket failed to connect",h),t(h)},u.onopen=h=>{c==null||c(h),e(u)}})}async function yu(n){const{retries:e=1}=n;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await vu(n)}catch(r){if(i===e)throw r;await ha(i*500)}return t}async function bu(n,e,t,i){const r=t!=null&&t.onMessage?[t.onMessage]:[],s=await yu({auth:n,host:e,externalId:i,callbacks:{onError:o=>{var a;return(a=t.onError)==null?void 0:a.call(t,new na(o))},onMessage(o){const a=JSON.parse(o.data);r.forEach(c=>c(a.event,a))}}});return{socket:s,disconnect:()=>s.close(),subscribeToEvents:o=>r.push(o)}}function Aa(n){if(n.answer!==void 0)return n.answer;let e=0,t="";for(;e in n;)t+=n[e++];return t}function ku(n,e,t){if(!n.content)return;const i={id:n.id||`user-${Date.now()}`,role:n.role,content:n.content,parts:On(n.content),created_at:n.created_at||new Date().toISOString(),transcribed:!0};e.messages.push(i),t==null||t([...e.messages],"user")}function Tu(n,e,t,i,r,s,o){if(n===xe.Transcribe&&e.content){ku(e,i,r);return}if(!(n===xe.Partial||n===xe.Answer))return;const a=i.messages[i.messages.length-1];if(n===xe.Answer&&(a==null?void 0:a.role)==="user"&&o==="partial")return;const d=o==="answer";let l;if((a==null?void 0:a.role)==="assistant"&&!d)l=a;else if(!a||a.role==="user"||d)d&&s(),l={id:e.id||`assistant-${Date.now()}`,role:e.role||"assistant",content:e.content||"",parts:[],created_at:e.created_at||new Date().toISOString()},i.messages.push(l);else return;const{content:u,sequence:h}=e;if(n===xe.Partial)t[h]=u;else{const v=Aa(t);!!(u&&u.length<v.length)&&(l.interrupted=!0),t.answer=u}const m=Aa(t);(l.content!==m||n===xe.Answer)&&(l.content=m,l.parts=On(m),r==null||r([...i.messages],n))}function Su(n,e,t,i,r){const s={},o=()=>{for(const d of Object.keys(s))delete s[d]};let a=null;const c=(d,l)=>{var u,h;l==="user"&&o(),(h=(u=t.callbacks).onNewMessage)==null||h.call(u,d,l)};return{clearQueue:o,onMessage:(d,l)=>{var u,h;if("content"in l){const m=d===Q.ChatAnswer?xe.Answer:d===Q.ChatAudioTranscribed?xe.Transcribe:d;Tu(m,l,s,e,c,o,a),m===xe.Partial?a="partial":m===xe.Answer&&(a="answer",o()),m===xe.Answer&&n.track("agent-message-received",{content:l.content,messages:e.messages.length,mode:e.chatMode})}else{const m=Q,v=[m.StreamVideoDone,m.StreamVideoError,m.StreamVideoRejected],g=[m.StreamFailed,m.StreamVideoError,m.StreamVideoRejected],S=hu(l,i,{mode:e.chatMode});if(d=d,d===m.StreamVideoCreated&&(n.linkTrack("agent-video",S,m.StreamVideoCreated,["start"]),l.sentiment)){const k=e.messages[e.messages.length-1];if((k==null?void 0:k.role)==="assistant"){const _={...k,sentiment:l.sentiment};e.messages[e.messages.length-1]=_,c==null||c([...e.messages],a??"answer")}}if(v.includes(d)){const k=d.split("/")[1];g.includes(d)?n.track("agent-video",{...S,event:k}):n.linkTrack("agent-video",{...S,event:k},d,["done"])}g.includes(d)&&((h=(u=t.callbacks).onError)==null||h.call(u,new oi(`Stream failed with event ${d}`),{data:l})),l.event===m.StreamDone&&r()}}}}function Cu(n,e,t,i){const r=hr(n,`${e}/agents/${t}`,i);return{createStream(s,o){return r.post("/streams",s,{signal:o})},startConnection(s,o,a,c){return r.post(`/streams/${s}/sdp`,{session_id:a,answer:o},{signal:c})},addIceCandidate(s,o,a,c){return r.post(`/streams/${s}/ice`,{session_id:a,...o},{signal:c})},sendStreamRequest(s,o,a){return r.post(`/streams/${s}`,{session_id:o,...a})},close(s,o){return r.delete(`/streams/${s}`,{session_id:o})}}}const xa=(n,e)=>(t,i)=>n&&console.log(`[${e}] ${t}`,i??""),Eu=45;function wu(n){const e=n.map(c=>c.av).filter(c=>!!c&&c.audioPlayout>0&&c.videoPlayout>0);if(e.length<2)return null;const t=e[0].localTs,i=e[e.length-1].localTs-t,r=e.map(c=>c.audioPlayout-c.videoPlayout),s=r.filter(c=>c>Eu||c<-100),o=e.filter(c=>c.localTs-t>=Math.min(5e3,i/2)),a=(o.length?o:e).map(c=>c.audioPlayout-c.videoPlayout);return{sampleCount:e.length,durationMs:li(i),desyncDurationMs:li(i*(s.length/r.length)),maxOffsetMs:li(r.reduce((c,d)=>Math.abs(d)>Math.abs(c)?d:c)),residualOffsetMs:li(lu(a))}}function _u(n,e,t){const i=(e.timestamp-n.timestamp)/1e3;return{duration:i,bytesReceived:e.bytesReceived-n.bytesReceived,bitrate:Math.round((e.bytesReceived-n.bytesReceived)*8/i),packetsReceived:e.packetsReceived-n.packetsReceived,packetsLost:e.packetsLost-n.packetsLost,framesDropped:e.framesDropped-n.framesDropped,framesDecoded:e.framesDecoded-n.framesDecoded,jitter:e.jitter,avgJitterDelayInInterval:(e.jitterBufferDelay-n.jitterBufferDelay)/(e.jitterBufferEmittedCount-n.jitterBufferEmittedCount),jitterBufferEmittedCount:e.jitterBufferEmittedCount-n.jitterBufferEmittedCount,jitterBufferDelay:(e.jitterBufferDelay-n.jitterBufferDelay)/i,framesPerSecond:e.framesPerSecond,freezeCount:e.freezeCount-n.freezeCount,freezeDuration:e.freezeDuration-n.freezeDuration,lowFpsCount:t}}function Ru(n){return n.filter(e=>e.freezeCount>0||e.framesPerSecond<21||e.framesDropped>0||e.packetsLost>0).map(e=>{const{timestamp:t,...i}=e,r=[];return e.freezeCount>0&&r.push("freeze"),e.framesPerSecond<21&&r.push("low fps"),e.framesDropped>0&&r.push("frames dropped"),e.packetsLost>0&&r.push("packet loss"),{...i,causes:r}})}function Pu(n){var c;let e="",t=0,i=null,r=null;const s=new Map;for(const d of n.values())if(d)if(d.type==="codec"&&((c=d.mimeType)!=null&&c.startsWith("video")))s.set(d.id,d.mimeType.split("/")[1]);else if(d.type==="candidate-pair"){const l=d,u=l.currentRoundTripTime??0;u>0&&(l.nominated===!0||t===0)&&(t=u)}else d.type==="inbound-rtp"&&d.kind==="video"?i=d:d.type==="inbound-rtp"&&d.kind==="audio"&&(r=d);if(!i)return{};const o=i;o.codecId&&s.has(o.codecId)?e=s.get(o.codecId):s.size>0&&(e=s.values().next().value??"");const a={codec:e,rtt:t,timestamp:o.timestamp,bytesReceived:o.bytesReceived,packetsReceived:o.packetsReceived,packetsLost:o.packetsLost,framesDropped:o.framesDropped,framesDecoded:o.framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount,avgJitterDelayInInterval:o.jitterBufferDelay/o.jitterBufferEmittedCount,frameWidth:o.frameWidth,frameHeight:o.frameHeight,framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount,freezeDuration:o.totalFreezesDuration};return r&&(a.av={audioPlayout:r.estimatedPlayoutTimestamp??0,videoPlayout:o.estimatedPlayoutTimestamp??0,localTs:o.timestamp}),a}function La(n,e,t){const i=n.map((c,d)=>d===0?t?{timestamp:c.timestamp,duration:0,rtt:c.rtt,bytesReceived:c.bytesReceived-t.bytesReceived,bitrate:(c.bytesReceived-t.bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-t.packetsReceived,packetsLost:c.packetsLost-t.packetsLost,framesDropped:c.framesDropped-t.framesDropped,framesDecoded:c.framesDecoded-t.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-t.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-t.jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-t.jitterBufferDelay)/(c.jitterBufferEmittedCount-t.jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-t.freezeCount,freezeDuration:c.freezeDuration-t.freezeDuration}:{timestamp:c.timestamp,rtt:c.rtt,duration:0,bytesReceived:c.bytesReceived,bitrate:c.bytesReceived*8/(e/1e3),packetsReceived:c.packetsReceived,packetsLost:c.packetsLost,framesDropped:c.framesDropped,framesDecoded:c.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount,avgJitterDelayInInterval:c.jitterBufferDelay/c.jitterBufferEmittedCount,framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount,freezeDuration:c.freezeDuration}:{timestamp:c.timestamp,duration:e*d/1e3,rtt:c.rtt,bytesReceived:c.bytesReceived-n[d-1].bytesReceived,bitrate:(c.bytesReceived-n[d-1].bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-n[d-1].packetsReceived,packetsLost:c.packetsLost-n[d-1].packetsLost,framesDropped:c.framesDropped-n[d-1].framesDropped,framesDecoded:c.framesDecoded-n[d-1].framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-n[d-1].jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-n[d-1].jitterBufferDelay)/(c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-n[d-1].freezeCount,freezeDuration:c.freezeDuration-n[d-1].freezeDuration}),r=Ru(i),s=r.reduce((c,d)=>c+(d.causes.includes("low fps")?1:0),0),o=i.filter(c=>!!c.avgJitterDelayInInterval).map(c=>c.avgJitterDelayInInterval),a=i.filter(c=>!!c.rtt).map(c=>c.rtt);return{webRTCStats:{anomalies:r,avSync:uu(()=>wu(n),null),minRtt:Ea(a),avgRtt:Ca(a),maxRtt:wa(a),aggregateReport:_u(n[0],n[n.length-1],s),minJitterDelayInInterval:Ea(o),maxJitterDelayInInterval:wa(o),avgJitterDelayInInterval:Ca(o)},codec:n[0].codec,resolution:`${n[0].frameWidth}x${n[0].frameHeight}`}}function Na(n,e){for(const t of n.values())if((t==null?void 0:t.type)==="inbound-rtp"&&t.kind===e)return t;return null}const Dn=10;function Iu(n,e){let t=!1,i=!1,r=null,s=0,o=0,a={};async function c(){if(t){try{const d=await n();if(!d){r=setTimeout(c,Dn);return}const l=Na(d,"audio");if(!l){r=setTimeout(c,Dn);return}const u=l.totalAudioEnergy??0,h=l.totalSamplesReceived??0;if(!i){s=u,o=h,i=!0,r=setTimeout(c,Dn);return}const m=u-s,v=h-o;if(s=u,o=h,v>0&&m>0){t=!1,e(a);return}}catch{}t&&(r=setTimeout(c,Dn))}}return{arm(d={}){a=d,t=!0,i=!1,performance.now(),r!==null&&clearTimeout(r),r=setTimeout(c,Dn)},destroy(){t=!1,r!==null&&(clearTimeout(r),r=null)}}}const hi=100,Mu=Math.max(Math.ceil(400/hi),1),Ou=.25,Du=.28;function Au(){let n=0,e,t,i=0;return r=>{const s=Na(r,"video");if(!s)return{isReceiving:!1,avgJitterDelayInInterval:i};const o=s.jitterBufferDelay,a=s.jitterBufferEmittedCount;if(t&&a>t){const l=o-e,u=a-t;i=l/u}e=o,t=a;const c=s.framesDecoded,d=c-n>0;return n=c,{isReceiving:d,avgJitterDelayInInterval:i,freezeCount:s.freezeCount}}}function Ua(n,e,t,i,r){let s=null,o=[],a,c=0,d=!1,l=rt.Unknown,u=rt.Unknown,h=0,m=0;const v=Au();async function g(){const S=await n();if(!S)return;const{isReceiving:k,avgJitterDelayInInterval:_,freezeCount:P}=v(S),y=Pu(S);if(k)c=0,h=P-m,u=_<Ou?rt.Strong:_>Du&&h>1?rt.Weak:l,u!==l&&(r==null||r(u),l=u,m+=h,h=0),d||(i==null||i(Z.Start),a=o[o.length-1],o=[],d=!0),o.push(y);else if(d&&(c++,c>=Mu)){const b=La(o,hi,a);i==null||i(Z.Stop,b),e()||t(),m=P,d=!1}}return{start:()=>{s||(s=setInterval(g,hi))},stop:()=>{s&&(clearInterval(s),s=null)},getReport:()=>La(o,hi,a)}}const xu=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function Fa(n){switch(n){case"connected":return le.Connected;case"checking":return le.Connecting;case"failed":return le.Fail;case"new":return le.New;case"closed":return le.Closed;case"disconnected":return le.Disconnected;case"completed":return le.Completed;default:return le.New}}const Lu=n=>e=>{const[t,i=""]=e.split(/:(.+)/);try{const r=JSON.parse(i);return n("parsed data channel message",{subject:t,data:r}),{subject:t,data:r}}catch(r){return n("Failed to parse data channel message, returning data as string",{subject:t,rawData:i,error:r}),{subject:t,data:i}}};function Nu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:i,log:r}){n===Z.Start&&e===Z.Start?(r("CALLBACK: onVideoStateChange(Start)"),t==null||t(Z.Start)):n===Z.Stop&&e===Z.Stop&&(r("CALLBACK: onVideoStateChange(Stop)"),t==null||t(Z.Stop,i))}function Uu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:r,log:s}){n===Z.Start?(s("CALLBACK: onVideoStateChange(Start)"),t==null||t(Z.Start)):n===Z.Stop&&(s("CALLBACK: onVideoStateChange(Stop)"),t==null||t(Z.Stop,r)),e===Z.Start?i==null||i(fe.Talking):e===Z.Stop&&(i==null||i(fe.Idle))}function Ba({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,streamType:r,report:s,log:o}){r===st.Legacy?Nu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:s,log:o}):r===st.Fluent&&Uu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:s,log:o})}async function Fu(n,e,{debug:t=!1,callbacks:i,auth:r,baseURL:s=Mn,analytics:o},a){var Ue;const c=xa(t,"WebRTCStreamingManager"),d=Lu(c);let l=!1,u=!1,h=Z.Stop,m=Z.Stop;const{startConnection:v,sendStreamRequest:g,close:S,createStream:k,addIceCandidate:_}=Cu(r,s,n,i.onError),{id:P,offer:y,ice_servers:b,session_id:T,fluent:L,interrupt_enabled:B}=await k(e,a);(Ue=i.onStreamCreated)==null||Ue.call(i,{stream_id:P,session_id:T,agent_id:n});const I=new xu({iceServers:b}),U=I.createDataChannel("JanusDataChannel");if(!T)throw new Error("Could not create session_id");const N=L?st.Fluent:st.Legacy;o.enrich({"stream-type":N});const W=e.stream_warmup&&!L,ee=()=>l,Se=()=>{var j;l=!0,u&&(c("CALLBACK: onConnectionStateChange(Connected)"),(j=i.onConnectionStateChange)==null||j.call(i,le.Connected))},R=Ua(()=>I.getStats(),ee,Se,(j,V)=>Ba({statsSignal:m=j,dataChannelSignal:N===st.Legacy?h:void 0,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,report:V,streamType:N,log:c}),j=>{var V;return(V=i.onConnectivityStateChange)==null?void 0:V.call(i,j)});R.start(),I.onicecandidate=j=>{var V;c("peerConnection.onicecandidate",j);try{j.candidate&&j.candidate.sdpMid&&j.candidate.sdpMLineIndex!==null?_(P,{candidate:j.candidate.candidate,sdpMid:j.candidate.sdpMid,sdpMLineIndex:j.candidate.sdpMLineIndex},T,a):_(P,{candidate:null},T,a)}catch(oe){(V=i.onError)==null||V.call(i,oe,{streamId:P})}},U.onopen=()=>{u=!0,(!W||l)&&Se()};let F=null;const q=j=>{var V;F=j,(V=i.onVideoIdChange)==null||V.call(i,j)};function te(j,V){if(j===Q.StreamStarted&&typeof V=="object"&&"metadata"in V){const oe=V.metadata;q(oe.videoId)}j===Q.StreamDone&&q(null),h=j===Q.StreamStarted?Z.Start:Z.Stop,Ba({statsSignal:N===st.Legacy?m:void 0,dataChannelSignal:h,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,streamType:N,log:c})}function se(j,V){var We;const oe=typeof V=="string"?V:V==null?void 0:V.metadata;oe&&o.enrich({streamMetadata:oe}),(We=i.onStreamReady)==null||We.call(i)}const ae={[Q.StreamStarted]:te,[Q.StreamDone]:te,[Q.StreamReady]:se};U.onmessage=j=>{var We;const{subject:V,data:oe}=d(j.data);(We=ae[V])==null||We.call(ae,V,oe)},I.oniceconnectionstatechange=()=>{var V;c("peerConnection.oniceconnectionstatechange => "+I.iceConnectionState);const j=Fa(I.iceConnectionState);j!==le.Connected&&((V=i.onConnectionStateChange)==null||V.call(i,j,`webrtc:ice-${I.iceConnectionState}`))},I.ontrack=j=>{var V;c("peerConnection.ontrack",j),c("CALLBACK: onSrcObjectReady"),(V=i.onSrcObjectReady)==null||V.call(i,j.streams[0])},await I.setRemoteDescription(y),c("set remote description OK");const Re=await I.createAnswer();c("create answer OK"),await I.setLocalDescription(Re),c("set local description OK"),await v(P,Re,T,a),c("start connection OK");function Ae(j){var V,oe;if(!l||U.readyState!=="open"){c("Data channel is not ready for sending messages"),(V=i.onError)==null||V.call(i,new oi("Data channel is not ready for sending messages"),{streamId:P});return}try{U.send(j)}catch(We){c("Error sending data channel message",We),(oe=i.onError)==null||oe.call(i,We,{streamId:P})}}return{speak(j){return g(P,T,j)},async disconnect(){var j;if(P){const V=Fa(I.iceConnectionState);if(I){if(V===le.New){R.stop();return}I.close(),I.oniceconnectionstatechange=null,I.onnegotiationneeded=null,I.onicecandidate=null,I.ontrack=null}try{V===le.Connected&&await S(P,T).catch(oe=>{})}catch(oe){c("Error on close stream connection",oe)}(j=i.onAgentActivityStateChange)==null||j.call(i,fe.Idle),R.stop()}},sendDataChannelMessage:Ae,sessionId:T,streamId:P,streamType:N,interruptAvailable:B??!1,isInterruptible:!0,interrupt(j){if(!B)throw new Error("Interrupt is not enabled for this stream");if(N!==st.Fluent)throw new Error("Interrupt only available for Fluent streams");if(!F)throw new Error("No active video to interrupt");const V={type:Q.StreamInterrupt,videoId:F,timestamp:Date.now()};Ae(JSON.stringify(V))}}}var vr=(n=>(n.V1="v1",n.V2="v2",n))(vr||{});async function Bu(n,e,t,i){const r=n.id;switch(e.version){case"v1":{const{version:s,...o}=e;return Fu(r,o,t,i)}case"v2":{const{version:s,...o}=e;switch(o.transport.provider){case ci.Livekit:const{createLiveKitStreamingManager:a}=await Promise.resolve().then(()=>sh);return a(r,o,t);default:throw new Error(`Unsupported transport provider: ${o.transport.provider}`)}}default:throw new Error(`Invalid stream version: ${e.version}`)}}const ju="cht";function Vu(){return{transport:{provider:ci.Livekit}}}function qu(n){var r,s;const{streamOptions:e}=n??{},t=((r=n==null?void 0:n.mixpanelAdditionalProperties)==null?void 0:r.plan)!==void 0?{plan:(s=n.mixpanelAdditionalProperties)==null?void 0:s.plan}:void 0;return{...{output_resolution:e==null?void 0:e.outputResolution,session_timeout:e==null?void 0:e.sessionTimeout,stream_warmup:e==null?void 0:e.streamWarmup,compatibility_mode:e==null?void 0:e.compatibilityMode,fluent:e==null?void 0:e.fluent},...t&&{end_user_data:t}}}function Ku(n,e){return dr(n.presenter.type)?{version:vr.V2,...Vu()}:{version:vr.V1,...qu(e)}}function Wu(n,e,t){t.track("agent-connection-state-change",{state:n,...e&&{reason:e}})}function Hu(n,e,t,i,r){r===st.Fluent?Ju(n,e,t,i,r):Gu(n,e,t,i,r)}function Ju(n,e,t,i,r){n===Z.Start?i.track("stream-session",{event:"start","stream-type":r}):n===Z.Stop&&i.track("stream-session",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t})}function ja(n,e,t,i,r){n===Z.Start?t.linkTrack("agent-video",{event:"start",...r,"stream-type":i},"start",[Q.StreamVideoCreated]):n===Z.Stop&&t.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":i},"done",[Q.StreamVideoDone])}function Gu(n,e,t,i,r){n===Z.Start?i.linkTrack("agent-video",{event:"start",latency:pt.get(!0),"stream-type":r},"start",[Q.StreamVideoCreated]):n===Z.Stop&&i.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t},"done",[Q.StreamVideoDone])}function zu(n,e,t){const i={call_id:e.call_id,name:e.name};if(n===Q.ToolCallStarted){t.track("agent-tool-call",{...i,event:"started"});return}const r=e;t.track("agent-tool-call",{...i,event:n===Q.ToolCallDone?"done":"error",duration_ms:r.duration_ms,extra_keys:r.extra?Object.keys(r.extra).length:0})}function Va(n,e,t,i){return pt.reset(),Ma.update(),new Promise(async(r,s)=>{try{let o,a=!1;const c=Ku(n,e);t.enrich({"stream-version":c.version.toString()});let d=null;const l=n.presenter.type==="expressive";o=await Bu(n,c,{...e,analytics:t,callbacks:{...e.callbacks,onConnectionStateChange:(u,h)=>{var m,v;(v=(m=e.callbacks).onConnectionStateChange)==null||v.call(m,u),Wu(u,h,t),u===le.Connected&&(o?r(o):a=!0)},onVideoStateChange:(u,h)=>{var m,v;(v=(m=e.callbacks).onVideoStateChange)==null||v.call(m,u),Hu(u,n,h,t,o.streamType)},onAgentActivityStateChange:u=>{var h,m;(m=(h=e.callbacks).onAgentActivityStateChange)==null||m.call(h,u),u===fe.Talking?(gr.update(),d=v=>{ja(Z.Start,n,t,o.streamType,v),d=null},l||d({latency:pt.get(!0)})):(gr.reset(),d=null,ja(Z.Stop,n,t,o.streamType))},onFirstAudioDetected:u=>{d==null||d(u)},onStreamReady:()=>{const u=Ma.get(!0);t.track("agent-chat",{event:"ready",latency:u})},onToolEvent:((u,h)=>{var m,v;(v=(m=e.callbacks).onToolEvent)==null||v.call(m,u,h),zu(u,h,t)})}},i),a&&r(o)}catch(o){s(o)}})}async function $u(n,e,t,i,r){var l,u,h,m;const s=async()=>{if(dr(n.presenter.type)){const v=await Va(n,e,i),g=`${ju}_${v.sessionId}`,S=new Date().toISOString();return{chatResult:{chatMode:Pe.Functional,chat:{id:g,agent_id:n.id,owner_id:n.owner_id??"",created:S,modified:S,agent_id__created_at:S,agent_id__modified_at:S,chat_mode:Pe.Functional,messages:[]}},streamingManager:v}}else{const v=new AbortController,g=v.signal;let S;try{const k=Da(n,t,i,e.mode,e.persistentChat,r),_=Va(n,e,i,g).then(b=>(S=b,b)),[P,y]=await Promise.all([k,_]);return{chatResult:P,streamingManager:y}}catch(k){throw v.abort(),S&&await S.disconnect().catch(()=>{}),k}}},{chatResult:o,streamingManager:a}=await s(),{chat:c,chatMode:d}=o;return d&&e.mode!==void 0&&d!==e.mode&&(e.mode=d,(u=(l=e.callbacks).onModeChange)==null||u.call(l,d),d!==Pe.Functional)?((m=(h=e.callbacks).onError)==null||m.call(h,new ea(d)),a==null||a.disconnect(),{chat:c}):{chat:c,streamingManager:a}}async function Qu(n,e){var N,W,ee,Se;let t=!0;const i=e.mixpanelKey||Ql,r=e.wsURL||$l,s=e.baseURL||Mn,o=e.mode||Pe.Functional,a={messages:[],chatMode:o},c=pu({token:i,agentId:n,isEnabled:e.enableAnalitics,externalId:e.externalId,mixpanelAdditionalProperties:e.mixpanelAdditionalProperties}),d=Date.now();_a(()=>{c.track("agent-sdk",{event:"init"},d)});const l=e.callbacks.onError;e.callbacks.onError=(R,F)=>{c.track("agent-error",{error:ui(R)}),l==null||l(R,F)};const u=ru(e.auth,s,e.callbacks.onError,e.externalId),h=await u.getById(n);e.debug=e.debug||((N=h==null?void 0:h.advanced_settings)==null?void 0:N.ui_debug_mode);const m=dr(h.presenter.type);c.enrich(au(h));const{onMessage:v,clearQueue:g}=Su(c,a,e,h,()=>{var R,F,q;(R=a.socketManager)==null||R.disconnect(),(q=(F=e.callbacks).onConnectionStateChange)==null||q.call(F,le.Disconnected)});a.messages=gu(e.initialMessages),(ee=(W=e.callbacks).onNewMessage)==null||ee.call(W,[...a.messages],"answer");const S=R=>{c.enrich({videoId:R})},k=({type:R})=>{var q,te,se,ae;if(!((q=a.streamingManager)!=null&&q.interruptAvailable)||!((te=a.streamingManager)!=null&&te.isInterruptible))return;const F=a.messages[a.messages.length-1];c.track("agent-video-interrupt",{type:R||"click",video_duration_to_interrupt:gr.get(!0),message_duration_to_interrupt:pt.get(!0)}),F.interrupted=!0,(ae=(se=e.callbacks).onNewMessage)==null||ae.call(se,[...a.messages],"answer"),a.streamingManager.interrupt(R)},_=new Map;function P(R){return async F=>{const q=_.get(R);if(!q)throw new Error(`No handler registered for client tool: ${R}`);try{const te=JSON.parse(F.payload);return await q(te)}catch(te){throw new Error(`Client tool "${R}" failed: ${te.message}`)}}}function y(){var R,F,q,te;for(const[se]of _)(F=(R=a.streamingManager)==null?void 0:R.unregisterRpcMethod)==null||F.call(R,se),(te=(q=a.streamingManager)==null?void 0:q.registerRpcMethod)==null||te.call(q,se,P(se))}function b(R,F){var te,se;const q=!_.has(R);_.set(R,F),q&&((se=(te=a.streamingManager)==null?void 0:te.registerRpcMethod)==null||se.call(te,R,P(R)))}function T(R){var F,q;_.delete(R),(q=(F=a.streamingManager)==null?void 0:F.unregisterRpcMethod)==null||q.call(F,R)}const L=Date.now();_a(()=>{c.track("agent-sdk",{event:"loaded",...su(h)},L)});async function B(R){var Re,Ae,Ue,j,V,oe,We;Jl(),(Ae=(Re=e.callbacks).onConnectionStateChange)==null||Ae.call(Re,le.Connecting),pt.reset(),R&&!t&&(delete a.chat,(j=(Ue=e.callbacks).onNewMessage)==null||j.call(Ue,[...a.messages],"answer"));const F=o===Pe.DirectPlayback||m?Promise.resolve(void 0):bu(e.auth,r,{onMessage:v,onError:e.callbacks.onError},e.externalId),q=ur(()=>$u(h,{...e,mode:o,callbacks:{...e.callbacks,onVideoIdChange:S,onMessage:v}},u,c,a.chat),{limit:3,timeout:Gl,timeoutErrorMessage:"Timeout initializing the stream",shouldRetryFn:mt=>(mt==null?void 0:mt.message)!=="Could not connect"&&!(mt instanceof ar&&(mt.status===429||mt.kind==="InsufficientCreditsError")),delayMs:1e3}).catch(mt=>{var ye,it;throw U(Pe.Maintenance),(it=(ye=e.callbacks).onConnectionStateChange)==null||it.call(ye,le.Fail),mt}),[te,{streamingManager:se,chat:ae}]=await Promise.all([F,q]);ae&&ae.id!==((V=a.chat)==null?void 0:V.id)&&((We=(oe=e.callbacks).onNewChat)==null||We.call(oe,ae.id)),a.streamingManager=se,a.socketManager=te,a.chat=ae,y(),t=!1,c.enrich({chatId:ae==null?void 0:ae.id,streamId:se==null?void 0:se.streamId,mode:a.chatMode}),U((ae==null?void 0:ae.chat_mode)??o)}async function I(){var R,F,q,te;(R=a.socketManager)==null||R.disconnect(),await((F=a.streamingManager)==null?void 0:F.disconnect()),delete a.streamingManager,delete a.socketManager,(te=(q=e.callbacks).onConnectionStateChange)==null||te.call(q,le.Disconnected)}async function U(R){var F,q;R!==a.chatMode&&(c.track("agent-mode-change",{mode:R}),a.chatMode=R,a.chatMode!==Pe.Functional&&await I(),(q=(F=e.callbacks).onModeChange)==null||q.call(F,R))}return{agent:h,getStreamType:()=>{var R;return(R=a.streamingManager)==null?void 0:R.streamType},getIsInterruptAvailable:()=>{var R;return((R=a.streamingManager)==null?void 0:R.interruptAvailable)??!1},starterMessages:((Se=h.knowledge)==null?void 0:Se.starter_message)||[],getSTTToken:()=>u.getSTTToken(h.id),changeMode:U,enrichAnalytics:c.enrich,async connect(){await B(!0),c.track("agent-chat",{event:"connect",mode:a.chatMode})},async reconnect(){const R=a.streamingManager;let F;if(m&&(R!=null&&R.reconnect))try{await R.reconnect()}catch(q){F=ui(q).kind,await I(),await B(!1)}else await I(),await B(!1);c.track("agent-chat",{event:"reconnect",mode:a.chatMode,success:!0,...F&&{fallbackReason:F}})},async disconnect(){await I(),c.track("agent-chat",{event:"disconnect",mode:a.chatMode})},publishMicrophoneStream(R){var F;return(F=a.streamingManager)!=null&&F.publishMicrophoneStream?a.streamingManager.publishMicrophoneStream(R):Promise.reject(new Error("publishMicrophoneStream is not available for this streaming manager"))},unpublishMicrophoneStream(){var R;return(R=a.streamingManager)!=null&&R.unpublishMicrophoneStream?a.streamingManager.unpublishMicrophoneStream():Promise.resolve()},replaceMicrophoneTrack(R){var F;return(F=a.streamingManager)!=null&&F.replaceMicrophoneTrack?a.streamingManager.replaceMicrophoneTrack(R):Promise.reject(new Error("replaceMicrophoneTrack is not available for this streaming manager"))},publishCameraStream(R){var F;return(F=a.streamingManager)!=null&&F.publishCameraStream?a.streamingManager.publishCameraStream(R):Promise.reject(new Error("publishCameraStream is not available for this streaming manager"))},unpublishCameraStream(){var R;return(R=a.streamingManager)!=null&&R.unpublishCameraStream?a.streamingManager.unpublishCameraStream():Promise.resolve()},async chat(R){var se,ae,Re,Ae,Ue;const F=()=>{if(ga(o))throw new He(`${o} is enabled, chat is disabled`);if(R.length>=fa)throw new He(`Message cannot be more than ${fa} characters`);if(R.length===0)throw new He("Message cannot be empty");if(a.chatMode===Pe.Maintenance)throw new He("Chat is in maintenance mode");if(![Pe.TextOnly,Pe.Playground].includes(a.chatMode)){if(!a.streamingManager)throw new He("Streaming manager is not initialized");if(!a.chat)throw new He("Chat is not initialized")}},q=async()=>{var j,V;if(!a.chat){const oe=await Da(h,u,c,a.chatMode,e.persistentChat);if(!oe.chat)throw new Zs(a.chatMode,!!e.persistentChat);a.chat=oe.chat,(V=(j=e.callbacks).onNewChat)==null||V.call(j,a.chat.id)}return a.chat.id},te=async(j,V)=>{const oe=a.chatMode===Pe.Playground;return ur(m&&!oe?async()=>{var ye,it;return await((it=(ye=a.streamingManager)==null?void 0:ye.sendTextMessage)==null?void 0:it.call(ye,R)),Promise.resolve({})}:async()=>{var ye,it;return u.chat(h.id,V,{chatMode:a.chatMode,streamId:(ye=a.streamingManager)==null?void 0:ye.streamId,sessionId:(it=a.streamingManager)==null?void 0:it.sessionId,messages:j.map(({matches:zs,...Pn})=>Pn)},{...Oa(a.chatMode),skipErrorHandler:!0})},{limit:2,shouldRetryFn:ye=>{var Pn,ir,rr,sr;const it=(Pn=ye==null?void 0:ye.message)==null?void 0:Pn.includes("missing or invalid session_id");return!((ir=ye==null?void 0:ye.message)==null?void 0:ir.includes("Stream Error"))&&!it?((sr=(rr=e.callbacks).onError)==null||sr.call(rr,ye),!1):!0},onRetry:async()=>{await I(),await B(!1)}})};try{g(),F(),a.messages.push({id:Gt(),role:"user",content:R,parts:On(R),created_at:new Date(pt.update()).toISOString()}),(ae=(se=e.callbacks).onNewMessage)==null||ae.call(se,[...a.messages],"user");const j=await q(),V=await te([...a.messages],j);return V.result&&a.messages.push({id:Gt(),role:"assistant",content:V.result,parts:On(V.result),created_at:new Date().toISOString(),context:V.context,matches:V.matches}),c.track("agent-message-send",{event:"success",messages:a.messages.length+1}),V.result&&((Ae=(Re=e.callbacks).onNewMessage)==null||Ae.call(Re,[...a.messages],"answer"),c.track("agent-message-received",{latency:pt.get(!0),messages:a.messages.length})),V}catch(j){throw((Ue=a.messages[a.messages.length-1])==null?void 0:Ue.role)==="assistant"&&a.messages.pop(),c.track("agent-message-send",{event:"error",messages:a.messages.length,error:ui(j)}),j}},rate(R,F,q){var ae,Re,Ae,Ue;const te=a.messages.find(j=>j.id===R);if(a.chat){if(!te)throw new He("Message not found")}else throw new He("Chat is not initialized");const se=((ae=te.matches)==null?void 0:ae.map(j=>[j.document_id,j.id]))??[];return c.track("agent-rate",{event:q?"update":"create",thumb:F===1?"up":"down",knowledge_id:((Re=h.knowledge)==null?void 0:Re.id)??"",matches:se,score:F}),q?u.updateRating(h.id,a.chat.id,q,{knowledge_id:((Ae=h.knowledge)==null?void 0:Ae.id)??"",message_id:R,matches:se,score:F}):u.createRating(h.id,a.chat.id,{knowledge_id:((Ue=h.knowledge)==null?void 0:Ue.id)??"",message_id:R,matches:se,score:F})},deleteRate(R){if(!a.chat)throw new He("Chat is not initialized");return c.track("agent-rate-delete",{type:"text"}),u.deleteRating(h.id,a.chat.id,R)},submitFeedback(R,F){if(!a.chat)throw new He("Chat is not initialized");return c.track("agent-feedback",{rating:R,hasAnswer:!!F}),u.submitFeedback(h.id,a.chat.id,{rating:R,answer:F})},async speak(R){var se,ae,Re;function F(){if(typeof R=="string"){if(!h.presenter.voice)throw new He("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:R,ssml:!1}}if(R.type==="text"&&!R.provider){if(!h.presenter.voice)throw new He("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:R.input,ssml:R.ssml,should_queue_speaks:R.should_queue_speaks}}return R}const q=F();if(c.track("agent-speak",q),pt.update(),a.messages&&q.type==="text"&&(a.messages.push({id:Gt(),role:"assistant",content:q.input,parts:On(q.input),created_at:new Date().toISOString()}),(ae=(se=e.callbacks).onNewMessage)==null||ae.call(se,[...a.messages],"answer")),Zl(a.chatMode))return{duration:0,video_id:"",status:"success"};if(!a.streamingManager)throw new He("Please connect to the agent first");return a.streamingManager.speak({script:q,metadata:{chat_id:(Re=a.chat)==null?void 0:Re.id,agent_id:h.id}})},interrupt:k,registerClientTool:b,unregisterClientTool:T}}function Yu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone??""}catch{return""}}function Xu(){if(typeof navigator>"u")return"";const n=navigator.userAgent??"",e=(navigator.platform??"").toLowerCase();let t="Unknown";/android/i.test(n)?t="Android":/iphone|ipad|ipod/i.test(n)?t="iOS":e.includes("win")?t="Windows":e.includes("mac")?t="Mac OS X":e.includes("linux")&&(t="Linux");const i=t==="Android"||t==="iOS"||/Mobi/i.test(n);return`${t}, ${i?"Mobile":"Desktop"}`}function Zu(){const n={},e=Yu();e&&(n.timezone=e);const t=Xu();return t&&(n.device=t),n}function eh(n,e,t,i){const r=hr(n,`${e}/v2/agents/${t}`,i);return{async createStream(s){return r.post("/sessions",s)}}}const th={[Q.ChatAnswer]:xe.Answer,[Q.ChatPartial]:xe.Partial},qa=2e4;async function nh(){try{return await Promise.resolve().then(()=>gv)}catch{throw new Error("LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client")}}const ih={excellent:rt.Strong,good:rt.Strong,poor:rt.Weak,lost:rt.Unknown,unknown:rt.Unknown},ln=(n="Stream Error")=>new oi(n);function yr(n,e,t){var i,r;throw e("Failed to connect to LiveKit room:",n),(i=t.onConnectionStateChange)==null||i.call(t,le.Fail,"internal:init-error"),(r=t.onError)==null||r.call(t,n,{sessionId:""}),n}async function rh(n,e,t){var Fl;const i=xa(t.debug||!1,"LiveKitStreamingManager"),{Room:r,RoomEvent:s,ConnectionState:o,Track:a}=await nh(),{callbacks:c,auth:d,baseURL:l,analytics:u}=t;let h=null,m=!1;const v=st.Fluent;let g=null;const S={isPublishing:!1,publication:null},k={isPublishing:!1,publication:null};let _=null,P=null,y=null,b=!1;h=new r({adaptiveStream:!1,dynacast:!0});let T=null,L=fe.Idle,B=!0;const I=new Set,U=eh(d,l||Mn,n,c.onError);let N,W,ee,Se=!0;try{const C=await U.createStream({transport:e.transport,chat_persist:e.chat_persist??!0,verbose:t.verbose??!1}),{id:O,session_token:H,session_url:J,interrupt_enabled:de}=C;(Fl=c.onStreamCreated)==null||Fl.call(c,{session_id:O,stream_id:O,agent_id:n}),N=O,W=H,ee=J,Se=de??!0,await h.prepareConnection(ee,W)}catch(C){yr(C,i,c)}if(!ee||!W||!N)return Promise.reject(new Error("Failed to initialize LiveKit stream"));h.on(s.ConnectionStateChanged,q).on(s.ConnectionQualityChanged,te).on(s.ParticipantConnected,se).on(s.ParticipantDisconnected,ae).on(s.TrackSubscribed,Ue).on(s.TrackUnsubscribed,j).on(s.DataReceived,Pn).on(s.MediaDevicesError,ir).on(s.TranscriptionReceived,R).on(s.EncryptionError,rr).on(s.TrackSubscriptionFailed,sr);function R(C,O){O!=null&&O.isLocal&&(pt.update(),L===fe.Talking&&(L=fe.Idle))}async function F(){const C=Zu();if(!(!h||Object.keys(C).length===0))try{await h.localParticipant.setAttributes(C)}catch(O){i("Failed to set user context attributes",O)}}try{await h.connect(ee,W),i("LiveKit room joined successfully"),F(),T=setTimeout(()=>{var O;i(`Track subscription timeout - no track subscribed within ${qa/1e3} seconds after connect`),T=null;const C=ln("Track subscription timeout");u.track("connectivity-error",{error:ui(C),sessionId:N}),(O=c.onError)==null||O.call(c,C,{sessionId:N}),Xs("internal:track-subscription-timeout")},qa)}catch(C){yr(C,i,c)}u.enrich({"stream-type":v});function q(C){var O,H,J,de;switch(i("Connection state changed:",C),C){case o.Connecting:i("CALLBACK: onConnectionStateChange(Connecting)"),(O=c.onConnectionStateChange)==null||O.call(c,le.Connecting,"livekit:connecting");break;case o.Connected:i("LiveKit room connected successfully"),m=!0;break;case o.Disconnected:i("LiveKit room disconnected"),m=!1,b=!1,S.publication=null,k.publication=null,(H=c.onConnectionStateChange)==null||H.call(c,le.Disconnected,"livekit:disconnected");break;case o.Reconnecting:i("LiveKit room reconnecting..."),(J=c.onConnectionStateChange)==null||J.call(c,le.Connecting,"livekit:reconnecting");break;case o.SignalReconnecting:i("LiveKit room signal reconnecting..."),(de=c.onConnectionStateChange)==null||de.call(c,le.Connecting,"livekit:signal-reconnecting");break}}function te(C,O){var H;i("Connection quality:",C),O!=null&&O.isLocal&&((H=c.onConnectivityStateChange)==null||H.call(c,ih[C]))}function se(C){i("Participant connected:",C.identity)}function ae(C){i("Participant disconnected:",C.identity),Xs("livekit:participant-disconnected")}function Re(){var C;y!==Z.Start&&(i("CALLBACK: onVideoStateChange(Start)"),y=Z.Start,(C=c.onVideoStateChange)==null||C.call(c,Z.Start))}function Ae(C){var O;y!==Z.Stop&&(i("CALLBACK: onVideoStateChange(Stop)"),y=Z.Stop,(O=c.onVideoStateChange)==null||O.call(c,Z.Stop,C))}function Ue(C,O,H){var de,he,Ie;i(`Track subscribed: ${C.kind} from ${H.identity}`);const J=C.mediaStreamTrack;if(!J){i(`No mediaStreamTrack available for ${C.kind}`);return}g?(g.addTrack(J),i(`Added ${C.kind} track to shared MediaStream`)):(g=new MediaStream([J]),i(`Created shared MediaStream with ${C.kind} track`)),C.kind==="audio"&&(P=Iu(()=>C.getRTCStatsReport(),({sttLatency:ie,serviceLatency:ft})=>{var Bl,jl,Vl;const si=pt.get(!0);let ai=0;if(ie){const ql=((jl=(Bl=_==null?void 0:_.getReport())==null?void 0:Bl.webRTCStats)==null?void 0:jl.avgRtt)??0;ai=ql>0?Math.round(ql*1e3):0}const In=si>0?si+(ie??0)+ai:void 0,Lt=In!==void 0&&ft!==void 0?In-ft:void 0;(Vl=c.onFirstAudioDetected)==null||Vl.call(c,{latency:In,networkLatency:Lt})})),C.kind==="video"&&((de=c.onStreamReady)==null||de.call(c),i("CALLBACK: onSrcObjectReady"),(he=c.onSrcObjectReady)==null||he.call(c,g),b||(b=!0,i("CALLBACK: onConnectionStateChange(Connected)"),(Ie=c.onConnectionStateChange)==null||Ie.call(c,le.Connected,"livekit:track-subscribed")),_=Ua(()=>C.getRTCStatsReport(),()=>m,Hl,(ie,ft)=>{i(`Video state change: ${ie}`),ie===Z.Start?(T&&(clearTimeout(T),T=null,i("Track subscription timeout cleared")),Re()):ie===Z.Stop&&Ae(ft)}),_.start())}function j(C,O,H){i(`Track unsubscribed: ${C.kind} from ${H.identity}`),C.kind==="audio"&&(P==null||P.destroy(),P=null),C.kind==="video"&&(Ae(_==null?void 0:_.getReport()),_==null||_.stop(),_=null)}function V(C,O){var J;const H=th[C];H&&((J=c.onMessage)==null||J.call(c,H,{event:H,...O}))}function oe(C,O){var H,J,de,he,Ie;if(C===Q.ToolCallStarted){const ie=O;B=ie.interruptible!==!1,(H=c.onInterruptibleChange)==null||H.call(c,B),I.add(ie.call_id),L=fe.ToolActive,(J=c.onAgentActivityStateChange)==null||J.call(c,fe.ToolActive),(de=c.onToolEvent)==null||de.call(c,Q.ToolCallStarted,ie);return}if(C===Q.ToolCallDone){const ie=O;We(ie.call_id),(he=c.onToolEvent)==null||he.call(c,Q.ToolCallDone,ie);return}if(C===Q.ToolCallError){const ie=O;We(ie.call_id),(Ie=c.onToolEvent)==null||Ie.call(c,Q.ToolCallError,ie)}}function We(C){var O;I.delete(C),I.size===0&&L===fe.ToolActive&&(L=fe.Idle,(O=c.onAgentActivityStateChange)==null||O.call(c,fe.Idle))}function mt(C,O){var H,J,de,he,Ie,ie;if(B=((H=O.metadata)==null?void 0:H.interruptible)!==!1,(J=c.onInterruptibleChange)==null||J.call(c,B),C===Q.StreamVideoCreated){L=fe.Talking,(de=c.onAgentActivityStateChange)==null||de.call(c,fe.Talking),P==null||P.arm({sttLatency:(he=O==null?void 0:O.stt)==null?void 0:he.latency,serviceLatency:O==null?void 0:O.serviceLatency});return}if(I.size>0){L!==fe.ToolActive&&(L=fe.ToolActive,(Ie=c.onAgentActivityStateChange)==null||Ie.call(c,fe.ToolActive));return}B&&(L=fe.Idle,(ie=c.onAgentActivityStateChange)==null||ie.call(c,fe.Idle))}function ye(C,O){var he,Ie,ie,ft;const H=((Ie=(he=_==null?void 0:_.getReport())==null?void 0:he.webRTCStats)==null?void 0:Ie.avgRtt)??0,J=H>0?Math.round(H/2*1e3):0,de={...O,downstreamNetworkLatency:J};t.debug&&((ie=O==null?void 0:O.metadata)!=null&&ie.sentiment)&&(de.sentiment={id:O.metadata.sentiment.id,name:O.metadata.sentiment.sentiment}),(ft=c.onMessage)==null||ft.call(c,C,de),mt(C,O)}function it(C,O){var H;(H=c.onMessage)==null||H.call(c,xe.Transcribe,{event:xe.Transcribe,...O}),queueMicrotask(()=>{var J;(J=c.onAgentActivityStateChange)==null||J.call(c,fe.Loading)})}const zs={[Q.ChatAnswer]:V,[Q.ChatPartial]:V,[Q.ToolCallStarted]:oe,[Q.ToolCallDone]:oe,[Q.ToolCallError]:oe,[Q.StreamVideoCreated]:ye,[Q.StreamVideoDone]:ye,[Q.StreamVideoError]:ye,[Q.StreamVideoRejected]:ye,[Q.ChatAudioTranscribed]:it};function Pn(C,O,H,J){const de=new TextDecoder().decode(C);try{const he=JSON.parse(de),Ie=J||he.subject;if(i("Data received:",{subject:Ie,data:he}),!Ie)return;const ie=zs[Ie];ie==null||ie(Ie,he)}catch(he){i("Failed to parse data channel message:",he)}}function ir(C){var O;i("Media devices error:",C),(O=c.onError)==null||O.call(c,ln(),{sessionId:N})}function rr(C){var O;i("Encryption error:",C),(O=c.onError)==null||O.call(c,ln(),{sessionId:N})}function sr(C,O,H){i("Track subscription failed:",{trackSid:C,participant:O,reason:H})}function vv(C,O,H){for(const[J,de]of H)if(de.source===O&&de.track){const he=de.track.mediaStreamTrack;if(he===C||(he==null?void 0:he.id)===C.id)return de}return null}async function Ll(C,O,H,J,de,he){var si,ai,In;if(!m||!h)throw i(`Room is not connected, cannot publish ${J} stream`),new Error("Room is not connected");if(C.isPublishing){i(`${J} publish already in progress, skipping`);return}const Ie=H(O);if(Ie.length===0)throw new Error(`No ${J} track found in the provided MediaStream`);const ie=Ie[0],ft=vv(ie,J,de());if(ft){i(`${J} track is already published, skipping`,{trackId:ie.id,publishedTrackId:(ai=(si=ft.track)==null?void 0:si.mediaStreamTrack)==null?void 0:ai.id}),C.publication=ft;return}if((In=C.publication)!=null&&In.track){const Lt=C.publication.track.mediaStreamTrack;Lt!==ie&&(Lt==null?void 0:Lt.id)!==ie.id&&(i(`Unpublishing existing ${J} track before publishing new one`),await he())}i(`Publishing ${J} track from provided MediaStream`,{trackId:ie.id}),C.isPublishing=!0;try{C.publication=await h.localParticipant.publishTrack(ie,{source:J}),i(`${J} track published successfully`,{trackSid:C.publication.trackSid})}catch(Lt){throw i(`Failed to publish ${J} track:`,Lt),Lt}finally{C.isPublishing=!1}}async function Nl(C,O){if(!(!C.publication||!C.publication.track))try{h&&(await h.localParticipant.unpublishTrack(C.publication.track,!1),i(`${O} track unpublished`))}catch(H){i(`Error unpublishing ${O} track:`,H)}finally{C.publication=null}}async function yv(C){return Ll(S,C,O=>O.getAudioTracks(),a.Source.Microphone,()=>h.localParticipant.audioTrackPublications,$s)}async function $s(){return Nl(S,"Microphone")}async function bv(C){if(!m||!h)throw i("Cannot replace microphone track: room is not connected"),new Error("Room is not connected");if(C.kind!=="audio")throw i("Cannot replace microphone track: not an audio track",{kind:C.kind}),new Error("Microphone track must be an audio track");if(S.isPublishing)throw i("Cannot replace microphone track: publish in progress"),new Error("Microphone publish in progress");const O=S.publication;if(!O||!O.track)throw i("Cannot replace microphone track: no publication to replace"),new Error("No microphone publication to replace");try{S.isPublishing=!0,await O.track.replaceTrack(C),i("Microphone track replaced",{trackId:C.id,trackSid:O.trackSid})}finally{S.isPublishing=!1}}async function kv(C){return Ll(k,C,O=>O.getVideoTracks(),a.Source.Camera,()=>h.localParticipant.videoTrackPublications,Qs)}async function Qs(){return Nl(k,"Camera")}function Tv(){g&&(g.getTracks().forEach(C=>C.stop()),g=null)}async function Ys(C,O){var H,J;if(!m||!h){i("Room is not connected for sending messages"),(H=c.onError)==null||H.call(c,ln(),{sessionId:N});return}try{await h.localParticipant.sendText(C,{topic:O}),i("Message sent successfully:",C)}catch(de){i("Failed to send message:",de),(J=c.onError)==null||J.call(c,ln(),{sessionId:N})}}async function Ul(C){var O;try{const J=JSON.parse(C).topic;return Ys("",J)}catch(H){i("Failed to send data channel message:",H),(O=c.onError)==null||O.call(c,ln(),{sessionId:N})}}function Sv(C){return Ys(C,"lk.chat")}async function Xs(C){var O,H;T&&(clearTimeout(T),T=null),P==null||P.destroy(),P=null,h&&((O=c.onConnectionStateChange)==null||O.call(c,le.Disconnecting,C),await Promise.all([$s(),Qs()]),await h.disconnect()),Tv(),m=!1,b=!1,I.clear(),(H=c.onAgentActivityStateChange)==null||H.call(c,fe.Idle),L=fe.Idle}return{speak(C){const O=typeof C=="string"?C:JSON.stringify(C);return Ys(O,"did.speak")},disconnect:()=>Xs("user:disconnect"),async reconnect(){var C,O;if((h==null?void 0:h.state)===o.Connected){i("Room is already connected");return}if(!h||!ee||!W)throw i("Cannot reconnect: missing room, URL or token"),new Error("Cannot reconnect: session not available");i("Reconnecting to LiveKit room, state:",h.state),b=!1,(C=c.onConnectionStateChange)==null||C.call(c,le.Connecting,"user:reconnect");try{if(await h.connect(ee,W),i("Room reconnected"),m=!0,h.remoteParticipants.size===0){if(i("Waiting for agent to join..."),!await new Promise(J=>{const de=setTimeout(()=>{h==null||h.off(s.ParticipantConnected,he),J(!1)},5e3),he=()=>{clearTimeout(de),h==null||h.off(s.ParticipantConnected,he),J(!0)};h==null||h.on(s.ParticipantConnected,he)}))throw i("Agent did not join within timeout"),await h.disconnect(),new Error("Agent did not rejoin the room");i("Agent joined, reconnection successful")}}catch(H){throw i("Failed to reconnect:",H),(O=c.onConnectionStateChange)==null||O.call(c,le.Fail,"user:reconnect-failed"),H}},sendDataChannelMessage:Ul,sendTextMessage:Sv,publishMicrophoneStream:yv,unpublishMicrophoneStream:$s,replaceMicrophoneTrack:bv,publishCameraStream:kv,unpublishCameraStream:Qs,interrupt(C){C!=="text"&&Ul(JSON.stringify({topic:"did.interrupt"}))},registerRpcMethod(C,O){h==null||h.registerRpcMethod(C,O)},unregisterRpcMethod(C){h==null||h.unregisterRpcMethod(C)},sessionId:N,streamId:N,streamType:v,interruptAvailable:Se,isInterruptible:B}}const sh=Object.freeze(Object.defineProperty({__proto__:null,createLiveKitStreamingManager:rh,handleInitError:yr},Symbol.toStringTag,{value:"Module"}));function ah(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var oh=Object.defineProperty,ch=(n,e,t)=>e in n?oh(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ka=(n,e,t)=>ch(n,typeof e!="symbol"?e+"":e,t);class Le{constructor(){Ka(this,"_locking"),Ka(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function be(n,e){if(!n)throw new Error(e)}const dh=34028234663852886e22,lh=-34028234663852886e22,uh=4294967295,hh=2147483647,mh=-2147483648;function mi(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>hh||n<mh)throw new Error("invalid int 32: "+n)}function br(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>uh||n<0)throw new Error("invalid uint 32: "+n)}function Wa(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>dh||n<lh))throw new Error("invalid float 32: "+n)}const Ha=Symbol("@bufbuild/protobuf/enum-type");function fh(n){const e=n[Ha];return be(e,"missing enum type on enum object"),e}function Ja(n,e,t,i){n[Ha]=Ga(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function Ga(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const o of e){const a=za(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:n,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function ph(n,e,t){const i={};for(const r of e){const s=za(r);i[s.localName]=s.no,i[s.no]=s.localName}return Ja(i,n,e),i}function za(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class kr{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function gh(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),o={[s]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new kr),Object.assign(o,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return n.util.equals(o,a,c)}}),o}function vh(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Tr(n,e,t){for(let s=0;s<28;s=s+7){const o=n>>>s,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=e>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const fi=4294967296;function $a(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(o,a){const c=Number(n.slice(o,a));r*=t,i=i*t+c,i>=fi&&(r=r+(i/fi|0),i=i%fi)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Ya(i,r):Sr(i,r)}function yh(n,e){let t=Sr(n,e);const i=t.hi&2147483648;i&&(t=Ya(t.lo,t.hi));const r=Qa(t.lo,t.hi);return i?"-"+r:r}function Qa(n,e){if({lo:n,hi:e}=bh(n,e),e<=2097151)return String(fi*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const c=1e7;return s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Xa(o)+Xa(s)}function bh(n,e){return{lo:n>>>0,hi:e>>>0}}function Sr(n,e){return{lo:n|0,hi:e|0}}function Ya(n,e){return e=~e,n?n=~n+1:e+=1,Sr(n,e)}const Xa=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Za(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function kh(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Th(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>s||d<r)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>a||d<o)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=r=>be(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>be(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),$a(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),$a(r)},dec(r,s){return yh(r,s)},uDec(r,s){return Qa(r,s)}}}const pe=Th();var w;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(w||(w={}));var Ut;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Ut||(Ut={}));function Ft(n,e,t){if(e===t)return!0;if(n==w.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==t}return!1}function un(n,e){switch(n){case w.BOOL:return!1;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==0?pe.zero:"0";case w.DOUBLE:case w.FLOAT:return 0;case w.BYTES:return new Uint8Array(0);case w.STRING:return"";default:return 0}}function eo(n,e){switch(n){case w.BOOL:return e===!1;case w.STRING:return e==="";case w.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Ee;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(Ee||(Ee={}));class Sh{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(br(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return mi(e),Za(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Wa(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){br(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){mi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return mi(e),e=(e<<1^e>>31)>>>0,Za(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=pe.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=pe.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=pe.enc(e);return Tr(t.lo,t.hi,this.buf),this}sint64(e){let t=pe.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return Tr(r,s,this.buf),this}uint64(e){let t=pe.uEnc(e);return Tr(t.lo,t.hi,this.buf),this}}class Ch{constructor(e,t){this.varint64=vh,this.uint32=kh,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Ee.Varint:for(;this.buf[this.pos++]&128;);break;case Ee.Bit64:this.pos+=4;case Ee.Bit32:this.pos+=4;break;case Ee.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ee.StartGroup:for(;;){const[s,o]=this.tag();if(o===Ee.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return pe.dec(...this.varint64())}uint64(){return pe.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,pe.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return pe.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return pe.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Eh(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function to(n){const e=n.field.localName,t=Object.create(null);return t[e]=wh(n),[t,()=>t[e]]}function wh(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return un(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function _h(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),pi=[];for(let n=0;n<wt.length;n++)pi[wt[n].charCodeAt(0)]=n;pi[45]=wt.indexOf("+"),pi[95]=wt.indexOf("/");const no={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,o=0;for(let a=0;a<n.length;a++){if(s=pi[n.charCodeAt(a)],s===void 0)switch(n[a]){case"=":r=0;case`
1
+ (function(G,Ce){typeof exports=="object"&&typeof module<"u"?Ce(exports):typeof define=="function"&&define.amd?define(["exports"],Ce):(G=typeof globalThis<"u"?globalThis:G||self,Ce(G.index={}))})(this,(function(G){"use strict";var Cv=Object.defineProperty;var Ev=(G,Ce,dn)=>Ce in G?Cv(G,Ce,{enumerable:!0,configurable:!0,writable:!0,value:dn}):G[Ce]=dn;var Nt=(G,Ce,dn)=>Ev(G,typeof Ce!="symbol"?Ce+"":Ce,dn);class Ce extends Error{constructor(e,t="Error",i){super(e),this.kind=t,this.originalError=i,Object.setPrototypeOf(this,new.target.prototype)}toJson(){const e=this.originalError instanceof Error?this.originalError.message.slice(0,256):void 0;return{kind:this.kind,message:this.message,...e&&e!==this.message?{cause:e}:{}}}}function dn(n){return n instanceof Error&&typeof n.kind=="string"}class Zs extends Ce{constructor(e,t){super(`Failed to create ${t?"persistent":""} chat, mode: ${e}`,"ChatCreationFailed")}}class ea extends Ce{constructor(e){super(`Chat mode downgraded to ${e}`,"ChatModeDowngraded")}}function Kl(n){try{const e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.kind=="string")return e}catch{}}class ar extends Ce{constructor(t,i,r={}){const s=Kl(i);super(((s==null?void 0:s.description)??i).slice(0,256),(s==null?void 0:s.kind)??"HttpError");Nt(this,"status");Nt(this,"url");Nt(this,"method");this.status=t,this.url=r.url,this.method=r.method}toJson(){return{...super.toJson(),httpStatus:this.status,...this.url?{endpoint:this.url}:{},...this.method?{method:this.method}:{}}}}class ta extends Ce{constructor(t,i={}){super("Network request failed","NetworkError",t);Nt(this,"endpoint");Nt(this,"method");Nt(this,"durationMs");Nt(this,"online");Nt(this,"visibility");this.endpoint=i.url,this.method=i.method,this.durationMs=i.durationMs,this.online=i.online,this.visibility=i.visibility}toJson(){return{...super.toJson(),...this.endpoint?{endpoint:this.endpoint}:{},...this.method?{method:this.method}:{},...this.durationMs!==void 0?{durationMs:this.durationMs}:{},...this.online!==void 0?{online:this.online}:{},...this.visibility?{visibility:this.visibility}:{}}}}class oi extends Ce{constructor(e,t){super(e,"StreamError",t)}}class He extends Ce{constructor(e,t){super(e,"ValidationError"),this.key=t}}class na extends Ce{constructor(e){super(e,"WSError")}}var ia=(n=>(n.TRIAL="trial",n.BASIC="basic",n.ENTERPRISE="enterprise",n.LITE="lite",n.ADVANCED="advanced",n))(ia||{}),ra=(n=>(n.TRIAL="deid-trial",n.PRO="deid-pro",n.ENTERPRISE="deid-enterprise",n.LITE="deid-lite",n.ADVANCED="deid-advanced",n.BUILD="deid-api-build",n.LAUNCH="deid-api-launch",n.SCALE="deid-api-scale",n))(ra||{}),sa=(n=>(n.Created="created",n.Started="started",n.Done="done",n.Error="error",n.Rejected="rejected",n.Ready="ready",n))(sa||{}),aa=(n=>(n.Unrated="Unrated",n.Positive="Positive",n.Negative="Negative",n))(aa||{}),Pe=(n=>(n.Functional="Functional",n.TextOnly="TextOnly",n.Maintenance="Maintenance",n.Playground="Playground",n.DirectPlayback="DirectPlayback",n.Off="Off",n))(Pe||{}),xe=(n=>(n.Embed="embed",n.Query="query",n.Partial="partial",n.Answer="answer",n.Transcribe="transcribe",n.Complete="done",n))(xe||{}),oa=(n=>(n.KnowledgeProcessing="knowledge/processing",n.KnowledgeIndexing="knowledge/indexing",n.KnowledgeFailed="knowledge/error",n.KnowledgeDone="knowledge/done",n))(oa||{}),ca=(n=>(n.Knowledge="knowledge",n.Document="document",n.Record="record",n))(ca||{}),da=(n=>(n.Pdf="pdf",n.Text="text",n.Html="html",n.Word="word",n.Json="json",n.Markdown="markdown",n.Csv="csv",n.Excel="excel",n.Powerpoint="powerpoint",n.Archive="archive",n.Image="image",n.Audio="audio",n.Video="video",n))(da||{}),or=(n=>(n.Clip="clip",n.Talk="talk",n.Expressive="expressive",n))(or||{});const Wl=n=>{switch(n){case"clip":return"clip";case"talk":return"talk";case"expressive":return"expressive";default:throw new Error(`Unknown video type: ${n}`)}};var Z=(n=>(n.Start="START",n.Stop="STOP",n))(Z||{}),rt=(n=>(n.Strong="STRONG",n.Weak="WEAK",n.Unknown="UNKNOWN",n))(rt||{}),fe=(n=>(n.Idle="IDLE",n.Loading="LOADING",n.Talking="TALKING",n.ToolActive="TOOL_ACTIVE",n))(fe||{}),Q=(n=>(n.ChatAnswer="chat/answer",n.ChatPartial="chat/partial",n.ChatAudioTranscribed="chat/audio-transcribed",n.StreamDone="stream/done",n.StreamStarted="stream/started",n.StreamFailed="stream/error",n.StreamReady="stream/ready",n.StreamCreated="stream/created",n.StreamInterrupt="stream/interrupt",n.StreamVideoCreated="stream-video/started",n.StreamVideoDone="stream-video/done",n.StreamVideoError="stream-video/error",n.StreamVideoRejected="stream-video/rejected",n.ToolCallStarted="tool-call/started",n.ToolCallDone="tool-call/done",n.ToolCallError="tool-call/error",n))(Q||{}),le=(n=>(n.New="new",n.Fail="fail",n.Connected="connected",n.Connecting="connecting",n.Closed="closed",n.Completed="completed",n.Disconnecting="disconnecting",n.Disconnected="disconnected",n))(le||{}),st=(n=>(n.Legacy="legacy",n.Fluent="fluent",n))(st||{}),ci=(n=>(n.Livekit="livekit",n))(ci||{}),la=(n=>(n.Amazon="amazon",n.AzureOpenAi="azure-openai",n.Microsoft="microsoft",n.Afflorithmics="afflorithmics",n.Elevenlabs="elevenlabs",n))(la||{}),ua=(n=>(n.Public="public",n.Premium="premium",n.Private="private",n))(ua||{});const Hl=(...n)=>{},ha=n=>new Promise(e=>setTimeout(e,n)),Gt=(n=16)=>{const e=new Uint8Array(n);return window.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("").slice(0,13)};function cr(n){if(n!==void 0)return window.localStorage.setItem("did_external_key_id",n),n;let e=window.localStorage.getItem("did_external_key_id");if(!e){let t=Gt();window.localStorage.setItem("did_external_key_id",t),e=t}return e}let di=Gt();function Jl(){di=Gt()}function ma(n,e){if(n.type==="bearer")return`Bearer ${n.token}~${di}`;if(n.type==="basic")return`Basic ${"token"in n?n.token:btoa(`${n.username}:${n.password}`)}~${di}`;if(n.type==="key")return`Client-Key ${n.clientKey}.${cr(e)}_${di}`;throw new Error(`Unknown auth type: ${n}`)}const Gl=45*1e3,zl="X-Playground-Chat",fa=2e3,Mn="https://api.d-id.com",$l="wss://notifications.d-id.com",Ql="79f81a83a67430be2bc0fd61042b8faa",pa=n=>n.type==="clip"&&n.presenter_id.startsWith("v2_")?"clip_v2":n.type,Yl=n=>{switch(n.type){case"expressive":return"v4";case"clip":return"v3-pro";case"talk":return"v2"}},Xl=n=>n.type==="talk"?n.source_url:n.presenter_id,dr=n=>n===or.Expressive,Zl=n=>[Pe.TextOnly,Pe.Playground,Pe.Maintenance].includes(n),ga=n=>n&&[Pe.DirectPlayback,Pe.Off].includes(n),va=/\[!\[([^\[\]]*)\]\(([^)\s]+)\)\]\(([^)\s]+)\)/g,ya=/!\[([^\[\]]*)\]\(([^)\s]+)\)/g,eu=[".mp4",".webm",".mkv",".mov",".m4v",".ogv"];function tu(n){const e=n.split("?")[0].split("#")[0].toLowerCase();return eu.some(t=>e.endsWith(t))}const ba=new RegExp("(?<!!)\\[([^\\[\\]]+)\\]\\(([^)\\s]+)\\)","g"),ka=/<a\s+href="([^"]*)"[^>]*?>([^<]*)<\/a>/gi;function Ta(n){if(n.length===0)return[];const e=[];let t;for(va.lastIndex=0;(t=va.exec(n))!==null;)e.push({index:t.index,length:t[0].length,part:{type:"video",src:t[3],alt:t[1],thumbnail:t[2]}});for(ya.lastIndex=0;(t=ya.exec(n))!==null;)if(!e.some(o=>t.index>=o.index&&t.index<o.index+o.length)){const o=t[2],a=t[1];let c;tu(o)?c={type:"video",src:o,alt:a}:(c={type:"image",src:o,alt:a},o.toLowerCase().endsWith(".gif")&&(c.mimeType="image/gif")),e.push({index:t.index,length:t[0].length,part:c})}for(ba.lastIndex=0;(t=ba.exec(n))!==null;)e.some(o=>t.index>=o.index&&t.index<o.index+o.length)||e.push({index:t.index,length:t[0].length,part:{type:"link",href:t[2],label:t[1]}});for(ka.lastIndex=0;(t=ka.exec(n))!==null;)e.some(o=>t.index>=o.index&&t.index<o.index+o.length)||e.push({index:t.index,length:t[0].length,part:{type:"link",href:t[1],label:t[2]}});if(e.length===0)return[{type:"text",text:n}];e.sort((s,o)=>s.index-o.index);const i=[];let r=0;for(const s of e)s.index>r&&i.push({type:"text",text:n.slice(r,s.index)}),i.push(s.part),r=s.index+s.length;return r<n.length&&i.push({type:"text",text:n.slice(r)}),i}let Sa="",lr=[];function On(n){return n===Sa||(Sa=n,lr=Ta(n)),lr}function nu(n,e){let t;return{promise:new Promise((r,s)=>{t=setTimeout(()=>s(new Error(e)),n)}),clear:()=>clearTimeout(t)}}async function ur(n,e){const t={limit:(e==null?void 0:e.limit)??3,delayMs:(e==null?void 0:e.delayMs)??0,timeout:(e==null?void 0:e.timeout)??3e4,timeoutErrorMessage:(e==null?void 0:e.timeoutErrorMessage)||"Timeout error",shouldRetryFn:(e==null?void 0:e.shouldRetryFn)??(()=>!0),onRetry:(e==null?void 0:e.onRetry)??(()=>{})};let i;for(let r=1;r<=t.limit;r++)try{if(!t.timeout)return await n();const{promise:s,clear:o}=nu(t.timeout,t.timeoutErrorMessage),a=n().finally(o);return await Promise.race([a,s])}catch(s){if(i=s,!t.shouldRetryFn(s)||r>=t.limit)throw s;await ha(t.delayMs),t.onRetry(s)}throw i}const iu=n=>ur(n,{limit:3,delayMs:1e3,timeout:0,shouldRetryFn:e=>e.status===429});function hr(n,e=Mn,t,i){const r=async(s,o)=>{const{skipErrorHandler:a,...c}=o||{},d=c.method??"GET",l=performance.now();let u;try{u=await iu(()=>fetch(e+(s!=null&&s.startsWith("/")?s:`/${s}`),{...c,headers:{...c.headers,Authorization:ma(n,i),"Content-Type":"application/json"}}))}catch(h){if((h==null?void 0:h.name)==="AbortError")throw h;const v=new ta(h,{url:s,method:d,durationMs:Math.round(performance.now()-l),online:typeof navigator<"u"?navigator.onLine:void 0,visibility:typeof document<"u"?document.visibilityState:void 0});throw a||t==null||t(v,{url:s,options:c}),v}if(!u.ok){const h=await u.text().catch(()=>`Failed to fetch with status ${u.status}`),m=new ar(u.status,h,{url:s,method:d});throw a||t==null||t(m,{url:s,options:c,headers:u.headers}),m}return u.json()};return{get(s,o){return r(s,{...o,method:"GET"})},post(s,o,a){return r(s,{...a,body:JSON.stringify(o),method:"POST"})},delete(s,o,a){return r(s,{...a,body:JSON.stringify(o),method:"DELETE"})},patch(s,o,a){return r(s,{...a,body:JSON.stringify(o),method:"PATCH"})}}}function ru(n,e=Mn,t,i){const r=hr(n,`${e}/agents`,t,i);return{create(s,o){return r.post("/",s,o)},getAgents(s,o){return r.get(`/${s?`?tag=${s}`:""}`,o).then(a=>a??[])},getById(s,o){return r.get(`/${s}`,o)},delete(s,o){return r.delete(`/${s}`,void 0,o)},update(s,o,a){return r.patch(`/${s}`,o,a)},newChat(s,o,a){return r.post(`/${s}/chat`,o,a)},chat(s,o,a,c){return r.post(`/${s}/chat/${o}`,a,c)},createRating(s,o,a,c){return r.post(`/${s}/chat/${o}/ratings`,a,c)},updateRating(s,o,a,c,d){return r.patch(`/${s}/chat/${o}/ratings/${a}`,c,d)},deleteRating(s,o,a,c){return r.delete(`/${s}/chat/${o}/ratings/${a}`,c)},submitFeedback(s,o,a,c){return r.post(`/${s}/chat/${o}/feedback`,a,c)},getSTTToken(s,o){return r.get(`/${s}/stt-token`,o)}}}function su(n){var r,s,o,a;const e=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",t=()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"},i=n.presenter;return{$os:`${t()}`,isMobile:`${e()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:pa(i),agentVoice:{voiceId:(s=(r=n.presenter)==null?void 0:r.voice)==null?void 0:s.voice_id,provider:(a=(o=n.presenter)==null?void 0:o.voice)==null?void 0:a.type}}}function au(n){var t,i,r,s,o,a;const e=(t=n.llm)==null?void 0:t.prompt_customization;return{agentType:pa(n.presenter),presenterType:Yl(n.presenter),presenter:Xl(n.presenter),owner_id:n.owner_id??"",promptVersion:(i=n.llm)==null?void 0:i.prompt_version,behavior:{role:e==null?void 0:e.role,personality:e==null?void 0:e.personality,instructions:(r=n.llm)==null?void 0:r.instructions},temperature:(s=n.llm)==null?void 0:s.temperature,knowledgeSource:e==null?void 0:e.knowledge_source,starterQuestionsCount:(a=(o=n.knowledge)==null?void 0:o.starter_message)==null?void 0:a.length,topicsToAvoid:e==null?void 0:e.topics_to_avoid,maxResponseLength:e==null?void 0:e.max_response_length,agentId:n.id,access:n.access,agentName:n.preview_name,...n.access==="public"?{from:"agent-template"}:{}}}const ou=n=>{try{return String((n==null?void 0:n.message)??n??"").slice(0,256)}catch{return"Unknown error"}},cu=n=>n.reduce((e,t)=>e+t,0),Ca=n=>cu(n)/n.length,Ea=n=>Math.min(...n),wa=n=>Math.max(...n),li=(n,e=0)=>{const t=10**e;return Math.round(n*t)/t},du=(n,e)=>{const t=[...n].sort((i,r)=>i-r);return t[Math.min(t.length-1,Math.floor(e*(t.length-1)))]},lu=n=>du(n,.5),uu=(n,e)=>{try{return n()}catch{return e}};function hu(n,e,t){var c,d,l;const{event:i,...r}=n,{template:s}=(e==null?void 0:e.llm)||{},{language:o}=((c=e==null?void 0:e.presenter)==null?void 0:c.voice)||{};return{...r,llm:{...r.llm,template:s},script:{...r.script,provider:{...(d=r==null?void 0:r.script)==null?void 0:d.provider,language:o}},stitch:(e==null?void 0:e.presenter.type)==="talk"?(l=e==null?void 0:e.presenter)==null?void 0:l.stitch:void 0,...t}}function _a(n){"requestIdleCallback"in window?requestIdleCallback(n,{timeout:2e3}):setTimeout(n,0)}function ui(n){return n instanceof Ce?n.toJson():{kind:"UnknownError",message:ou(n)||"UnknownError"}}const Ra="1.2.10-staging.374",mu="https://api-js.mixpanel.com/track/?verbose=1&ip=1",Pa=50,zt=[];let mr=!1;async function Ia(n){const e=await fetch(mu,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify(n)})});if(!e.ok)throw new Error(`Mixpanel responded with ${e.status}`)}function fu(n){zt.push(n),zt.splice(Pa)}function fr(){if(mr||!zt.length)return;mr=!0;const n=zt.splice(0,zt.length);Ia(n).catch(()=>{zt.unshift(...n),zt.splice(Pa)}).finally(()=>{mr=!1})}typeof window<"u"&&typeof window.addEventListener=="function"&&(window.addEventListener("online",fr),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&fr()}));function pu(n){const e=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={};return{token:n.token||"testKey",distinct_id:cr(n.externalId),agentId:n.agentId,additionalProperties:{id:cr(n.externalId),...n.mixpanelAdditionalProperties||{}},isEnabled:n.isEnabled??!0,getRandom:Gt,enrich(i){this.additionalProperties={...this.additionalProperties,...i}},async track(i,r,s){if(!this.isEnabled)return Promise.resolve();const{audioPath:o,...a}=r||{},c=s||Date.now(),d={event:i,properties:{...this.additionalProperties,...a,agentId:this.agentId,source:e,emittedBy:"agents-sdk",sdkVersion:Ra,token:this.token,time:c,$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerHeight,"Screen Width":window.screen.width||window.innerWidth,"User Agent":navigator.userAgent}};return fr(),Ia([d]).catch(()=>fu(d)),Promise.resolve()},linkTrack(i,r,s,o){t[i]||(t[i]={events:{},resolvedDependencies:[]}),o.includes(s)||o.push(s);const a=t[i];if(a.events[s]={props:r},a.resolvedDependencies.push(s),o.every(d=>a.resolvedDependencies.includes(d))){const d=o.reduce((l,u)=>a.events[u]?{...l,...a.events[u].props}:l,{});this.track(i,d),a.resolvedDependencies=a.resolvedDependencies.filter(l=>!o.includes(l)),o.forEach(l=>{delete a.events[l]})}}}}function pr(){let n=0;return{reset:()=>n=0,update:()=>n=Date.now(),get:(e=!1)=>e?Date.now()-n:n}}const pt=pr(),gr=pr(),Ma=pr();function Oa(n){return n===Pe.Playground?{headers:{[zl]:"true"}}:{}}async function Da(n,e,t,i,r=!1,s){return!s&&!ga(i)&&(s=await e.newChat(n.id,{persist:r},Oa(i)),t.track("agent-chat",{event:"created",chatId:s.id,mode:i})),{chat:s,chatMode:(s==null?void 0:s.chat_mode)??i}}function gu(n){return n&&n.length>0?n:[]}function vu(n){return new Promise((e,t)=>{const{callbacks:i,host:r,auth:s,externalId:o}=n,{onMessage:a=null,onOpen:c=null,onClose:d=null,onError:l=null}=i||{},u=new WebSocket(`${r}?authorization=${encodeURIComponent(ma(s,o))}`);u.onmessage=a,u.onclose=d,u.onerror=h=>{console.error(h),l==null||l("Websocket failed to connect",h),t(h)},u.onopen=h=>{c==null||c(h),e(u)}})}async function yu(n){const{retries:e=1}=n;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await vu(n)}catch(r){if(i===e)throw r;await ha(i*500)}return t}async function bu(n,e,t,i){const r=t!=null&&t.onMessage?[t.onMessage]:[],s=await yu({auth:n,host:e,externalId:i,callbacks:{onError:o=>{var a;return(a=t.onError)==null?void 0:a.call(t,new na(o))},onMessage(o){const a=JSON.parse(o.data);r.forEach(c=>c(a.event,a))}}});return{socket:s,disconnect:()=>s.close(),subscribeToEvents:o=>r.push(o)}}function Aa(n){if(n.answer!==void 0)return n.answer;let e=0,t="";for(;e in n;)t+=n[e++];return t}function ku(n,e,t){if(!n.content)return;const i={id:n.id||`user-${Date.now()}`,role:n.role,content:n.content,parts:On(n.content),created_at:n.created_at||new Date().toISOString(),transcribed:!0};e.messages.push(i),t==null||t([...e.messages],"user")}function Tu(n,e,t,i,r,s,o){if(n===xe.Transcribe&&e.content){ku(e,i,r);return}if(!(n===xe.Partial||n===xe.Answer))return;const a=i.messages[i.messages.length-1];if(n===xe.Answer&&(a==null?void 0:a.role)==="user"&&o==="partial")return;const d=o==="answer";let l;if((a==null?void 0:a.role)==="assistant"&&!d)l=a;else if(!a||a.role==="user"||d)d&&s(),l={id:e.id||`assistant-${Date.now()}`,role:e.role||"assistant",content:e.content||"",parts:[],created_at:e.created_at||new Date().toISOString()},i.messages.push(l);else return;const{content:u,sequence:h}=e;if(n===xe.Partial)t[h]=u;else{const v=Aa(t);!!(u&&u.length<v.length)&&(l.interrupted=!0),t.answer=u}const m=Aa(t);(l.content!==m||n===xe.Answer)&&(l.content=m,l.parts=On(m),r==null||r([...i.messages],n))}function Su(n,e,t,i,r){const s={},o=()=>{for(const d of Object.keys(s))delete s[d]};let a=null;const c=(d,l)=>{var u,h;l==="user"&&o(),(h=(u=t.callbacks).onNewMessage)==null||h.call(u,d,l)};return{clearQueue:o,onMessage:(d,l)=>{var u,h;if("content"in l){const m=d===Q.ChatAnswer?xe.Answer:d===Q.ChatAudioTranscribed?xe.Transcribe:d;Tu(m,l,s,e,c,o,a),m===xe.Partial?a="partial":m===xe.Answer&&(a="answer",o()),m===xe.Answer&&n.track("agent-message-received",{content:l.content,messages:e.messages.length,mode:e.chatMode})}else{const m=Q,v=[m.StreamVideoDone,m.StreamVideoError,m.StreamVideoRejected],g=[m.StreamFailed,m.StreamVideoError,m.StreamVideoRejected],S=hu(l,i,{mode:e.chatMode});if(d=d,d===m.StreamVideoCreated&&(n.linkTrack("agent-video",S,m.StreamVideoCreated,["start"]),l.sentiment)){const k=e.messages[e.messages.length-1];if((k==null?void 0:k.role)==="assistant"){const _={...k,sentiment:l.sentiment};e.messages[e.messages.length-1]=_,c==null||c([...e.messages],a??"answer")}}if(v.includes(d)){const k=d.split("/")[1];g.includes(d)?n.track("agent-video",{...S,event:k}):n.linkTrack("agent-video",{...S,event:k},d,["done"])}g.includes(d)&&((h=(u=t.callbacks).onError)==null||h.call(u,new oi(`Stream failed with event ${d}`),{data:l})),l.event===m.StreamDone&&r()}}}}function Cu(n,e,t,i){const r=hr(n,`${e}/agents/${t}`,i);return{createStream(s,o){return r.post("/streams",s,{signal:o})},startConnection(s,o,a,c){return r.post(`/streams/${s}/sdp`,{session_id:a,answer:o},{signal:c})},addIceCandidate(s,o,a,c){return r.post(`/streams/${s}/ice`,{session_id:a,...o},{signal:c})},sendStreamRequest(s,o,a){return r.post(`/streams/${s}`,{session_id:o,...a})},close(s,o){return r.delete(`/streams/${s}`,{session_id:o})}}}const xa=(n,e)=>(t,i)=>n&&console.log(`[${e}] ${t}`,i??""),Eu=45;function wu(n){const e=n.map(c=>c.av).filter(c=>!!c&&c.audioPlayout>0&&c.videoPlayout>0);if(e.length<2)return null;const t=e[0].localTs,i=e[e.length-1].localTs-t,r=e.map(c=>c.audioPlayout-c.videoPlayout),s=r.filter(c=>c>Eu||c<-100),o=e.filter(c=>c.localTs-t>=Math.min(5e3,i/2)),a=(o.length?o:e).map(c=>c.audioPlayout-c.videoPlayout);return{sampleCount:e.length,durationMs:li(i),desyncDurationMs:li(i*(s.length/r.length)),maxOffsetMs:li(r.reduce((c,d)=>Math.abs(d)>Math.abs(c)?d:c)),residualOffsetMs:li(lu(a))}}function _u(n,e,t){const i=(e.timestamp-n.timestamp)/1e3;return{duration:i,bytesReceived:e.bytesReceived-n.bytesReceived,bitrate:Math.round((e.bytesReceived-n.bytesReceived)*8/i),packetsReceived:e.packetsReceived-n.packetsReceived,packetsLost:e.packetsLost-n.packetsLost,framesDropped:e.framesDropped-n.framesDropped,framesDecoded:e.framesDecoded-n.framesDecoded,jitter:e.jitter,avgJitterDelayInInterval:(e.jitterBufferDelay-n.jitterBufferDelay)/(e.jitterBufferEmittedCount-n.jitterBufferEmittedCount),jitterBufferEmittedCount:e.jitterBufferEmittedCount-n.jitterBufferEmittedCount,jitterBufferDelay:(e.jitterBufferDelay-n.jitterBufferDelay)/i,framesPerSecond:e.framesPerSecond,freezeCount:e.freezeCount-n.freezeCount,freezeDuration:e.freezeDuration-n.freezeDuration,lowFpsCount:t}}function Ru(n){return n.filter(e=>e.freezeCount>0||e.framesPerSecond<21||e.framesDropped>0||e.packetsLost>0).map(e=>{const{timestamp:t,...i}=e,r=[];return e.freezeCount>0&&r.push("freeze"),e.framesPerSecond<21&&r.push("low fps"),e.framesDropped>0&&r.push("frames dropped"),e.packetsLost>0&&r.push("packet loss"),{...i,causes:r}})}function Pu(n){var c;let e="",t=0,i=null,r=null;const s=new Map;for(const d of n.values())if(d)if(d.type==="codec"&&((c=d.mimeType)!=null&&c.startsWith("video")))s.set(d.id,d.mimeType.split("/")[1]);else if(d.type==="candidate-pair"){const l=d,u=l.currentRoundTripTime??0;u>0&&(l.nominated===!0||t===0)&&(t=u)}else d.type==="inbound-rtp"&&d.kind==="video"?i=d:d.type==="inbound-rtp"&&d.kind==="audio"&&(r=d);if(!i)return{};const o=i;o.codecId&&s.has(o.codecId)?e=s.get(o.codecId):s.size>0&&(e=s.values().next().value??"");const a={codec:e,rtt:t,timestamp:o.timestamp,bytesReceived:o.bytesReceived,packetsReceived:o.packetsReceived,packetsLost:o.packetsLost,framesDropped:o.framesDropped,framesDecoded:o.framesDecoded,jitter:o.jitter,jitterBufferDelay:o.jitterBufferDelay,jitterBufferEmittedCount:o.jitterBufferEmittedCount,avgJitterDelayInInterval:o.jitterBufferDelay/o.jitterBufferEmittedCount,frameWidth:o.frameWidth,frameHeight:o.frameHeight,framesPerSecond:o.framesPerSecond,freezeCount:o.freezeCount,freezeDuration:o.totalFreezesDuration};return r&&(a.av={audioPlayout:r.estimatedPlayoutTimestamp??0,videoPlayout:o.estimatedPlayoutTimestamp??0,localTs:o.timestamp}),a}function La(n,e,t){const i=n.map((c,d)=>d===0?t?{timestamp:c.timestamp,duration:0,rtt:c.rtt,bytesReceived:c.bytesReceived-t.bytesReceived,bitrate:(c.bytesReceived-t.bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-t.packetsReceived,packetsLost:c.packetsLost-t.packetsLost,framesDropped:c.framesDropped-t.framesDropped,framesDecoded:c.framesDecoded-t.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-t.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-t.jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-t.jitterBufferDelay)/(c.jitterBufferEmittedCount-t.jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-t.freezeCount,freezeDuration:c.freezeDuration-t.freezeDuration}:{timestamp:c.timestamp,rtt:c.rtt,duration:0,bytesReceived:c.bytesReceived,bitrate:c.bytesReceived*8/(e/1e3),packetsReceived:c.packetsReceived,packetsLost:c.packetsLost,framesDropped:c.framesDropped,framesDecoded:c.framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount,avgJitterDelayInInterval:c.jitterBufferDelay/c.jitterBufferEmittedCount,framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount,freezeDuration:c.freezeDuration}:{timestamp:c.timestamp,duration:e*d/1e3,rtt:c.rtt,bytesReceived:c.bytesReceived-n[d-1].bytesReceived,bitrate:(c.bytesReceived-n[d-1].bytesReceived)*8/(e/1e3),packetsReceived:c.packetsReceived-n[d-1].packetsReceived,packetsLost:c.packetsLost-n[d-1].packetsLost,framesDropped:c.framesDropped-n[d-1].framesDropped,framesDecoded:c.framesDecoded-n[d-1].framesDecoded,jitter:c.jitter,jitterBufferDelay:c.jitterBufferDelay-n[d-1].jitterBufferDelay,jitterBufferEmittedCount:c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount,avgJitterDelayInInterval:(c.jitterBufferDelay-n[d-1].jitterBufferDelay)/(c.jitterBufferEmittedCount-n[d-1].jitterBufferEmittedCount),framesPerSecond:c.framesPerSecond,freezeCount:c.freezeCount-n[d-1].freezeCount,freezeDuration:c.freezeDuration-n[d-1].freezeDuration}),r=Ru(i),s=r.reduce((c,d)=>c+(d.causes.includes("low fps")?1:0),0),o=i.filter(c=>!!c.avgJitterDelayInInterval).map(c=>c.avgJitterDelayInInterval),a=i.filter(c=>!!c.rtt).map(c=>c.rtt);return{webRTCStats:{anomalies:r,avSync:uu(()=>wu(n),null),minRtt:Ea(a),avgRtt:Ca(a),maxRtt:wa(a),aggregateReport:_u(n[0],n[n.length-1],s),minJitterDelayInInterval:Ea(o),maxJitterDelayInInterval:wa(o),avgJitterDelayInInterval:Ca(o)},codec:n[0].codec,resolution:`${n[0].frameWidth}x${n[0].frameHeight}`}}function Na(n,e){for(const t of n.values())if((t==null?void 0:t.type)==="inbound-rtp"&&t.kind===e)return t;return null}const Dn=10;function Iu(n,e){let t=!1,i=!1,r=null,s=0,o=0,a={};async function c(){if(t){try{const d=await n();if(!d){r=setTimeout(c,Dn);return}const l=Na(d,"audio");if(!l){r=setTimeout(c,Dn);return}const u=l.totalAudioEnergy??0,h=l.totalSamplesReceived??0;if(!i){s=u,o=h,i=!0,r=setTimeout(c,Dn);return}const m=u-s,v=h-o;if(s=u,o=h,v>0&&m>0){t=!1,e(a);return}}catch{}t&&(r=setTimeout(c,Dn))}}return{arm(d={}){a=d,t=!0,i=!1,performance.now(),r!==null&&clearTimeout(r),r=setTimeout(c,Dn)},destroy(){t=!1,r!==null&&(clearTimeout(r),r=null)}}}const hi=100,Mu=Math.max(Math.ceil(400/hi),1),Ou=.25,Du=.28;function Au(){let n=0,e,t,i=0;return r=>{const s=Na(r,"video");if(!s)return{isReceiving:!1,avgJitterDelayInInterval:i};const o=s.jitterBufferDelay,a=s.jitterBufferEmittedCount;if(t&&a>t){const l=o-e,u=a-t;i=l/u}e=o,t=a;const c=s.framesDecoded,d=c-n>0;return n=c,{isReceiving:d,avgJitterDelayInInterval:i,freezeCount:s.freezeCount}}}function Ua(n,e,t,i,r){let s=null,o=[],a,c=0,d=!1,l=rt.Unknown,u=rt.Unknown,h=0,m=0;const v=Au();async function g(){const S=await n();if(!S)return;const{isReceiving:k,avgJitterDelayInInterval:_,freezeCount:P}=v(S),y=Pu(S);if(k)c=0,h=P-m,u=_<Ou?rt.Strong:_>Du&&h>1?rt.Weak:l,u!==l&&(r==null||r(u),l=u,m+=h,h=0),d||(i==null||i(Z.Start),a=o[o.length-1],o=[],d=!0),o.push(y);else if(d&&(c++,c>=Mu)){const b=La(o,hi,a);i==null||i(Z.Stop,b),e()||t(),m=P,d=!1}}return{start:()=>{s||(s=setInterval(g,hi))},stop:()=>{s&&(clearInterval(s),s=null)},getReport:()=>La(o,hi,a)}}const xu=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function Fa(n){switch(n){case"connected":return le.Connected;case"checking":return le.Connecting;case"failed":return le.Fail;case"new":return le.New;case"closed":return le.Closed;case"disconnected":return le.Disconnected;case"completed":return le.Completed;default:return le.New}}const Lu=n=>e=>{const[t,i=""]=e.split(/:(.+)/);try{const r=JSON.parse(i);return n("parsed data channel message",{subject:t,data:r}),{subject:t,data:r}}catch(r){return n("Failed to parse data channel message, returning data as string",{subject:t,rawData:i,error:r}),{subject:t,data:i}}};function Nu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:i,log:r}){n===Z.Start&&e===Z.Start?(r("CALLBACK: onVideoStateChange(Start)"),t==null||t(Z.Start)):n===Z.Stop&&e===Z.Stop&&(r("CALLBACK: onVideoStateChange(Stop)"),t==null||t(Z.Stop,i))}function Uu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:r,log:s}){n===Z.Start?(s("CALLBACK: onVideoStateChange(Start)"),t==null||t(Z.Start)):n===Z.Stop&&(s("CALLBACK: onVideoStateChange(Stop)"),t==null||t(Z.Stop,r)),e===Z.Start?i==null||i(fe.Talking):e===Z.Stop&&(i==null||i(fe.Idle))}function Ba({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,streamType:r,report:s,log:o}){r===st.Legacy?Nu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,report:s,log:o}):r===st.Fluent&&Uu({statsSignal:n,dataChannelSignal:e,onVideoStateChange:t,onAgentActivityStateChange:i,report:s,log:o})}async function Fu(n,e,{debug:t=!1,callbacks:i,auth:r,baseURL:s=Mn,analytics:o},a){var Ue;const c=xa(t,"WebRTCStreamingManager"),d=Lu(c);let l=!1,u=!1,h=Z.Stop,m=Z.Stop;const{startConnection:v,sendStreamRequest:g,close:S,createStream:k,addIceCandidate:_}=Cu(r,s,n,i.onError),{id:P,offer:y,ice_servers:b,session_id:T,fluent:L,interrupt_enabled:B}=await k(e,a);(Ue=i.onStreamCreated)==null||Ue.call(i,{stream_id:P,session_id:T,agent_id:n});const I=new xu({iceServers:b}),U=I.createDataChannel("JanusDataChannel");if(!T)throw new Error("Could not create session_id");const N=L?st.Fluent:st.Legacy;o.enrich({"stream-type":N});const W=e.stream_warmup&&!L,ee=()=>l,Se=()=>{var j;l=!0,u&&(c("CALLBACK: onConnectionStateChange(Connected)"),(j=i.onConnectionStateChange)==null||j.call(i,le.Connected))},R=Ua(()=>I.getStats(),ee,Se,(j,V)=>Ba({statsSignal:m=j,dataChannelSignal:N===st.Legacy?h:void 0,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,report:V,streamType:N,log:c}),j=>{var V;return(V=i.onConnectivityStateChange)==null?void 0:V.call(i,j)});R.start(),I.onicecandidate=j=>{var V;c("peerConnection.onicecandidate",j);try{j.candidate&&j.candidate.sdpMid&&j.candidate.sdpMLineIndex!==null?_(P,{candidate:j.candidate.candidate,sdpMid:j.candidate.sdpMid,sdpMLineIndex:j.candidate.sdpMLineIndex},T,a):_(P,{candidate:null},T,a)}catch(oe){(V=i.onError)==null||V.call(i,oe,{streamId:P})}},U.onopen=()=>{u=!0,(!W||l)&&Se()};let F=null;const q=j=>{var V;F=j,(V=i.onVideoIdChange)==null||V.call(i,j)};function te(j,V){if(j===Q.StreamStarted&&typeof V=="object"&&"metadata"in V){const oe=V.metadata;q(oe.videoId)}j===Q.StreamDone&&q(null),h=j===Q.StreamStarted?Z.Start:Z.Stop,Ba({statsSignal:N===st.Legacy?m:void 0,dataChannelSignal:h,onVideoStateChange:i.onVideoStateChange,onAgentActivityStateChange:i.onAgentActivityStateChange,streamType:N,log:c})}function se(j,V){var We;const oe=typeof V=="string"?V:V==null?void 0:V.metadata;oe&&o.enrich({streamMetadata:oe}),(We=i.onStreamReady)==null||We.call(i)}const ae={[Q.StreamStarted]:te,[Q.StreamDone]:te,[Q.StreamReady]:se};U.onmessage=j=>{var We;const{subject:V,data:oe}=d(j.data);(We=ae[V])==null||We.call(ae,V,oe)},I.oniceconnectionstatechange=()=>{var V;c("peerConnection.oniceconnectionstatechange => "+I.iceConnectionState);const j=Fa(I.iceConnectionState);j!==le.Connected&&((V=i.onConnectionStateChange)==null||V.call(i,j,`webrtc:ice-${I.iceConnectionState}`))},I.ontrack=j=>{var V;c("peerConnection.ontrack",j),c("CALLBACK: onSrcObjectReady"),(V=i.onSrcObjectReady)==null||V.call(i,j.streams[0])},await I.setRemoteDescription(y),c("set remote description OK");const Re=await I.createAnswer();c("create answer OK"),await I.setLocalDescription(Re),c("set local description OK"),await v(P,Re,T,a),c("start connection OK");function Ae(j){var V,oe;if(!l||U.readyState!=="open"){c("Data channel is not ready for sending messages"),(V=i.onError)==null||V.call(i,new oi("Data channel is not ready for sending messages"),{streamId:P});return}try{U.send(j)}catch(We){c("Error sending data channel message",We),(oe=i.onError)==null||oe.call(i,We,{streamId:P})}}return{speak(j){return g(P,T,j)},async disconnect(){var j;if(P){const V=Fa(I.iceConnectionState);if(I){if(V===le.New){R.stop();return}I.close(),I.oniceconnectionstatechange=null,I.onnegotiationneeded=null,I.onicecandidate=null,I.ontrack=null}try{V===le.Connected&&await S(P,T).catch(oe=>{})}catch(oe){c("Error on close stream connection",oe)}(j=i.onAgentActivityStateChange)==null||j.call(i,fe.Idle),R.stop()}},sendDataChannelMessage:Ae,sessionId:T,streamId:P,streamType:N,interruptAvailable:B??!1,isInterruptible:!0,interrupt(j){if(!B)throw new Error("Interrupt is not enabled for this stream");if(N!==st.Fluent)throw new Error("Interrupt only available for Fluent streams");if(!F)throw new Error("No active video to interrupt");const V={type:Q.StreamInterrupt,videoId:F,timestamp:Date.now()};Ae(JSON.stringify(V))}}}var vr=(n=>(n.V1="v1",n.V2="v2",n))(vr||{});async function Bu(n,e,t,i){const r=n.id;switch(e.version){case"v1":{const{version:s,...o}=e;return Fu(r,o,t,i)}case"v2":{const{version:s,...o}=e;switch(o.transport.provider){case ci.Livekit:const{createLiveKitStreamingManager:a}=await Promise.resolve().then(()=>sh);return a(r,o,t);default:throw new Error(`Unsupported transport provider: ${o.transport.provider}`)}}default:throw new Error(`Invalid stream version: ${e.version}`)}}const ju="cht";function Vu(){return{transport:{provider:ci.Livekit}}}function qu(n){var r,s;const{streamOptions:e}=n??{},t=((r=n==null?void 0:n.mixpanelAdditionalProperties)==null?void 0:r.plan)!==void 0?{plan:(s=n.mixpanelAdditionalProperties)==null?void 0:s.plan}:void 0;return{...{output_resolution:e==null?void 0:e.outputResolution,session_timeout:e==null?void 0:e.sessionTimeout,stream_warmup:e==null?void 0:e.streamWarmup,compatibility_mode:e==null?void 0:e.compatibilityMode,fluent:e==null?void 0:e.fluent},...t&&{end_user_data:t}}}function Ku(n,e){return dr(n.presenter.type)?{version:vr.V2,...Vu()}:{version:vr.V1,...qu(e)}}function Wu(n,e,t){t.track("agent-connection-state-change",{state:n,...e&&{reason:e}})}function Hu(n,e,t,i,r){r===st.Fluent?Ju(n,e,t,i,r):Gu(n,e,t,i,r)}function Ju(n,e,t,i,r){n===Z.Start?i.track("stream-session",{event:"start","stream-type":r}):n===Z.Stop&&i.track("stream-session",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t})}function ja(n,e,t,i,r){n===Z.Start?t.linkTrack("agent-video",{event:"start",...r,"stream-type":i},"start",[Q.StreamVideoCreated]):n===Z.Stop&&t.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":i},"done",[Q.StreamVideoDone])}function Gu(n,e,t,i,r){n===Z.Start?i.linkTrack("agent-video",{event:"start",latency:pt.get(!0),"stream-type":r},"start",[Q.StreamVideoCreated]):n===Z.Stop&&i.linkTrack("agent-video",{event:"stop",is_greenscreen:e.presenter.type==="clip"&&e.presenter.is_greenscreen,background:e.presenter.type==="clip"&&e.presenter.background,"stream-type":r,...t},"done",[Q.StreamVideoDone])}function zu(n,e,t){const i={call_id:e.call_id,name:e.name};if(n===Q.ToolCallStarted){t.track("agent-tool-call",{...i,event:"started"});return}const r=e;t.track("agent-tool-call",{...i,event:n===Q.ToolCallDone?"done":"error",duration_ms:r.duration_ms,extra_keys:r.extra?Object.keys(r.extra).length:0})}function Va(n,e,t,i){return pt.reset(),Ma.update(),new Promise(async(r,s)=>{try{let o,a=!1;const c=Ku(n,e);t.enrich({"stream-version":c.version.toString()});let d=null;const l=n.presenter.type==="expressive";o=await Bu(n,c,{...e,analytics:t,callbacks:{...e.callbacks,onConnectionStateChange:(u,h)=>{var m,v;(v=(m=e.callbacks).onConnectionStateChange)==null||v.call(m,u),Wu(u,h,t),u===le.Connected&&(o?r(o):a=!0)},onVideoStateChange:(u,h)=>{var m,v;(v=(m=e.callbacks).onVideoStateChange)==null||v.call(m,u),Hu(u,n,h,t,o.streamType)},onAgentActivityStateChange:u=>{var h,m;(m=(h=e.callbacks).onAgentActivityStateChange)==null||m.call(h,u),u===fe.Talking?(gr.update(),d=v=>{ja(Z.Start,n,t,o.streamType,v),d=null},l||d({latency:pt.get(!0)})):(gr.reset(),d=null,ja(Z.Stop,n,t,o.streamType))},onFirstAudioDetected:u=>{d==null||d(u)},onStreamReady:()=>{const u=Ma.get(!0);t.track("agent-chat",{event:"ready",latency:u})},onToolEvent:((u,h)=>{var m,v;(v=(m=e.callbacks).onToolEvent)==null||v.call(m,u,h),zu(u,h,t)})}},i),a&&r(o)}catch(o){s(o)}})}async function $u(n,e,t,i,r){var l,u,h,m;const s=async()=>{if(dr(n.presenter.type)){const v=await Va(n,e,i),g=`${ju}_${v.sessionId}`,S=new Date().toISOString();return{chatResult:{chatMode:Pe.Functional,chat:{id:g,agent_id:n.id,owner_id:n.owner_id??"",created:S,modified:S,agent_id__created_at:S,agent_id__modified_at:S,chat_mode:Pe.Functional,messages:[]}},streamingManager:v}}else{const v=new AbortController,g=v.signal;let S;try{const k=Da(n,t,i,e.mode,e.persistentChat,r),_=Va(n,e,i,g).then(b=>(S=b,b)),[P,y]=await Promise.all([k,_]);return{chatResult:P,streamingManager:y}}catch(k){throw v.abort(),S&&await S.disconnect().catch(()=>{}),k}}},{chatResult:o,streamingManager:a}=await s(),{chat:c,chatMode:d}=o;return d&&e.mode!==void 0&&d!==e.mode&&(e.mode=d,(u=(l=e.callbacks).onModeChange)==null||u.call(l,d),d!==Pe.Functional)?((m=(h=e.callbacks).onError)==null||m.call(h,new ea(d)),a==null||a.disconnect(),{chat:c}):{chat:c,streamingManager:a}}async function Qu(n,e){var N,W,ee,Se;let t=!0;const i=e.mixpanelKey||Ql,r=e.wsURL||$l,s=e.baseURL||Mn,o=e.mode||Pe.Functional,a={messages:[],chatMode:o},c=pu({token:i,agentId:n,isEnabled:e.enableAnalytics??e.enableAnalitics,externalId:e.externalId,mixpanelAdditionalProperties:e.mixpanelAdditionalProperties}),d=Date.now();_a(()=>{c.track("agent-sdk",{event:"init"},d)});const l=e.callbacks.onError;e.callbacks.onError=(R,F)=>{c.track("agent-error",{error:ui(R)}),l==null||l(R,F)};const u=ru(e.auth,s,e.callbacks.onError,e.externalId),h=await u.getById(n);e.debug=e.debug||((N=h==null?void 0:h.advanced_settings)==null?void 0:N.ui_debug_mode);const m=dr(h.presenter.type);c.enrich(au(h));const{onMessage:v,clearQueue:g}=Su(c,a,e,h,()=>{var R,F,q;(R=a.socketManager)==null||R.disconnect(),(q=(F=e.callbacks).onConnectionStateChange)==null||q.call(F,le.Disconnected)});a.messages=gu(e.initialMessages),(ee=(W=e.callbacks).onNewMessage)==null||ee.call(W,[...a.messages],"answer");const S=R=>{c.enrich({videoId:R})},k=({type:R})=>{var q,te,se,ae;if(!((q=a.streamingManager)!=null&&q.interruptAvailable)||!((te=a.streamingManager)!=null&&te.isInterruptible))return;const F=a.messages[a.messages.length-1];c.track("agent-video-interrupt",{type:R||"click",video_duration_to_interrupt:gr.get(!0),message_duration_to_interrupt:pt.get(!0)}),F.interrupted=!0,(ae=(se=e.callbacks).onNewMessage)==null||ae.call(se,[...a.messages],"answer"),a.streamingManager.interrupt(R)},_=new Map;function P(R){return async F=>{const q=_.get(R);if(!q)throw new Error(`No handler registered for client tool: ${R}`);try{const te=JSON.parse(F.payload);return await q(te)}catch(te){throw new Error(`Client tool "${R}" failed: ${te.message}`)}}}function y(){var R,F,q,te;for(const[se]of _)(F=(R=a.streamingManager)==null?void 0:R.unregisterRpcMethod)==null||F.call(R,se),(te=(q=a.streamingManager)==null?void 0:q.registerRpcMethod)==null||te.call(q,se,P(se))}function b(R,F){var te,se;const q=!_.has(R);_.set(R,F),q&&((se=(te=a.streamingManager)==null?void 0:te.registerRpcMethod)==null||se.call(te,R,P(R)))}function T(R){var F,q;_.delete(R),(q=(F=a.streamingManager)==null?void 0:F.unregisterRpcMethod)==null||q.call(F,R)}const L=Date.now();_a(()=>{c.track("agent-sdk",{event:"loaded",...su(h)},L)});async function B(R){var Re,Ae,Ue,j,V,oe,We;Jl(),(Ae=(Re=e.callbacks).onConnectionStateChange)==null||Ae.call(Re,le.Connecting),pt.reset(),R&&!t&&(delete a.chat,(j=(Ue=e.callbacks).onNewMessage)==null||j.call(Ue,[...a.messages],"answer"));const F=o===Pe.DirectPlayback||m?Promise.resolve(void 0):bu(e.auth,r,{onMessage:v,onError:e.callbacks.onError},e.externalId),q=ur(()=>$u(h,{...e,mode:o,callbacks:{...e.callbacks,onVideoIdChange:S,onMessage:v}},u,c,a.chat),{limit:3,timeout:Gl,timeoutErrorMessage:"Timeout initializing the stream",shouldRetryFn:mt=>(mt==null?void 0:mt.message)!=="Could not connect"&&!(mt instanceof ar&&(mt.status===429||mt.kind==="InsufficientCreditsError")),delayMs:1e3}).catch(mt=>{var ye,it;throw U(Pe.Maintenance),(it=(ye=e.callbacks).onConnectionStateChange)==null||it.call(ye,le.Fail),mt}),[te,{streamingManager:se,chat:ae}]=await Promise.all([F,q]);ae&&ae.id!==((V=a.chat)==null?void 0:V.id)&&((We=(oe=e.callbacks).onNewChat)==null||We.call(oe,ae.id)),a.streamingManager=se,a.socketManager=te,a.chat=ae,y(),t=!1,c.enrich({chatId:ae==null?void 0:ae.id,streamId:se==null?void 0:se.streamId,mode:a.chatMode}),U((ae==null?void 0:ae.chat_mode)??o)}async function I(){var R,F,q,te;(R=a.socketManager)==null||R.disconnect(),await((F=a.streamingManager)==null?void 0:F.disconnect()),delete a.streamingManager,delete a.socketManager,(te=(q=e.callbacks).onConnectionStateChange)==null||te.call(q,le.Disconnected)}async function U(R){var F,q;R!==a.chatMode&&(c.track("agent-mode-change",{mode:R}),a.chatMode=R,a.chatMode!==Pe.Functional&&await I(),(q=(F=e.callbacks).onModeChange)==null||q.call(F,R))}return{agent:h,getStreamType:()=>{var R;return(R=a.streamingManager)==null?void 0:R.streamType},getIsInterruptAvailable:()=>{var R;return((R=a.streamingManager)==null?void 0:R.interruptAvailable)??!1},starterMessages:((Se=h.knowledge)==null?void 0:Se.starter_message)||[],getSTTToken:()=>u.getSTTToken(h.id),changeMode:U,enrichAnalytics:c.enrich,async connect(){await B(!0),c.track("agent-chat",{event:"connect",mode:a.chatMode})},async reconnect(){const R=a.streamingManager;let F;if(m&&(R!=null&&R.reconnect))try{await R.reconnect()}catch(q){F=ui(q).kind,await I(),await B(!1)}else await I(),await B(!1);c.track("agent-chat",{event:"reconnect",mode:a.chatMode,success:!0,...F&&{fallbackReason:F}})},async disconnect(){await I(),c.track("agent-chat",{event:"disconnect",mode:a.chatMode})},publishMicrophoneStream(R){var F;return(F=a.streamingManager)!=null&&F.publishMicrophoneStream?a.streamingManager.publishMicrophoneStream(R):Promise.reject(new Error("publishMicrophoneStream is not available for this streaming manager"))},unpublishMicrophoneStream(){var R;return(R=a.streamingManager)!=null&&R.unpublishMicrophoneStream?a.streamingManager.unpublishMicrophoneStream():Promise.resolve()},replaceMicrophoneTrack(R){var F;return(F=a.streamingManager)!=null&&F.replaceMicrophoneTrack?a.streamingManager.replaceMicrophoneTrack(R):Promise.reject(new Error("replaceMicrophoneTrack is not available for this streaming manager"))},publishCameraStream(R){var F;return(F=a.streamingManager)!=null&&F.publishCameraStream?a.streamingManager.publishCameraStream(R):Promise.reject(new Error("publishCameraStream is not available for this streaming manager"))},unpublishCameraStream(){var R;return(R=a.streamingManager)!=null&&R.unpublishCameraStream?a.streamingManager.unpublishCameraStream():Promise.resolve()},async chat(R){var se,ae,Re,Ae,Ue;const F=()=>{if(ga(o))throw new He(`${o} is enabled, chat is disabled`);if(R.length>=fa)throw new He(`Message cannot be more than ${fa} characters`);if(R.length===0)throw new He("Message cannot be empty");if(a.chatMode===Pe.Maintenance)throw new He("Chat is in maintenance mode");if(![Pe.TextOnly,Pe.Playground].includes(a.chatMode)){if(!a.streamingManager)throw new He("Streaming manager is not initialized");if(!a.chat)throw new He("Chat is not initialized")}},q=async()=>{var j,V;if(!a.chat){const oe=await Da(h,u,c,a.chatMode,e.persistentChat);if(!oe.chat)throw new Zs(a.chatMode,!!e.persistentChat);a.chat=oe.chat,(V=(j=e.callbacks).onNewChat)==null||V.call(j,a.chat.id)}return a.chat.id},te=async(j,V)=>{const oe=a.chatMode===Pe.Playground;return ur(m&&!oe?async()=>{var ye,it;return await((it=(ye=a.streamingManager)==null?void 0:ye.sendTextMessage)==null?void 0:it.call(ye,R)),Promise.resolve({})}:async()=>{var ye,it;return u.chat(h.id,V,{chatMode:a.chatMode,streamId:(ye=a.streamingManager)==null?void 0:ye.streamId,sessionId:(it=a.streamingManager)==null?void 0:it.sessionId,messages:j.map(({matches:zs,...Pn})=>Pn)},{...Oa(a.chatMode),skipErrorHandler:!0})},{limit:2,shouldRetryFn:ye=>{var Pn,ir,rr,sr;const it=(Pn=ye==null?void 0:ye.message)==null?void 0:Pn.includes("missing or invalid session_id");return!((ir=ye==null?void 0:ye.message)==null?void 0:ir.includes("Stream Error"))&&!it?((sr=(rr=e.callbacks).onError)==null||sr.call(rr,ye),!1):!0},onRetry:async()=>{await I(),await B(!1)}})};try{g(),F(),a.messages.push({id:Gt(),role:"user",content:R,parts:On(R),created_at:new Date(pt.update()).toISOString()}),(ae=(se=e.callbacks).onNewMessage)==null||ae.call(se,[...a.messages],"user");const j=await q(),V=await te([...a.messages],j);return V.result&&a.messages.push({id:Gt(),role:"assistant",content:V.result,parts:On(V.result),created_at:new Date().toISOString(),context:V.context,matches:V.matches}),c.track("agent-message-send",{event:"success",messages:a.messages.length+1}),V.result&&((Ae=(Re=e.callbacks).onNewMessage)==null||Ae.call(Re,[...a.messages],"answer"),c.track("agent-message-received",{latency:pt.get(!0),messages:a.messages.length})),V}catch(j){throw((Ue=a.messages[a.messages.length-1])==null?void 0:Ue.role)==="assistant"&&a.messages.pop(),c.track("agent-message-send",{event:"error",messages:a.messages.length,error:ui(j)}),j}},rate(R,F,q){var ae,Re,Ae,Ue;const te=a.messages.find(j=>j.id===R);if(a.chat){if(!te)throw new He("Message not found")}else throw new He("Chat is not initialized");const se=((ae=te.matches)==null?void 0:ae.map(j=>[j.document_id,j.id]))??[];return c.track("agent-rate",{event:q?"update":"create",thumb:F===1?"up":"down",knowledge_id:((Re=h.knowledge)==null?void 0:Re.id)??"",matches:se,score:F}),q?u.updateRating(h.id,a.chat.id,q,{knowledge_id:((Ae=h.knowledge)==null?void 0:Ae.id)??"",message_id:R,matches:se,score:F}):u.createRating(h.id,a.chat.id,{knowledge_id:((Ue=h.knowledge)==null?void 0:Ue.id)??"",message_id:R,matches:se,score:F})},deleteRate(R){if(!a.chat)throw new He("Chat is not initialized");return c.track("agent-rate-delete",{type:"text"}),u.deleteRating(h.id,a.chat.id,R)},submitFeedback(R,F){if(!a.chat)throw new He("Chat is not initialized");return c.track("agent-feedback",{rating:R,hasAnswer:!!F}),u.submitFeedback(h.id,a.chat.id,{rating:R,answer:F})},async speak(R){var se,ae,Re;function F(){if(typeof R=="string"){if(!h.presenter.voice)throw new He("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:R,ssml:!1}}if(R.type==="text"&&!R.provider){if(!h.presenter.voice)throw new He("Presenter voice is not initialized");return{type:"text",provider:h.presenter.voice,input:R.input,ssml:R.ssml,should_queue_speaks:R.should_queue_speaks,sentiment:R.sentiment}}return R}const q=F();if(c.track("agent-speak",q),pt.update(),a.messages&&q.type==="text"&&(a.messages.push({id:Gt(),role:"assistant",content:q.input,parts:On(q.input),created_at:new Date().toISOString()}),(ae=(se=e.callbacks).onNewMessage)==null||ae.call(se,[...a.messages],"answer")),Zl(a.chatMode))return{duration:0,video_id:"",status:"success"};if(!a.streamingManager)throw new He("Please connect to the agent first");return a.streamingManager.speak({script:q,metadata:{chat_id:(Re=a.chat)==null?void 0:Re.id,agent_id:h.id}})},interrupt:k,registerClientTool:b,unregisterClientTool:T}}function Yu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone??""}catch{return""}}function Xu(){if(typeof navigator>"u")return"";const n=navigator.userAgent??"",e=(navigator.platform??"").toLowerCase();let t="Unknown";/android/i.test(n)?t="Android":/iphone|ipad|ipod/i.test(n)?t="iOS":e.includes("win")?t="Windows":e.includes("mac")?t="Mac OS X":e.includes("linux")&&(t="Linux");const i=t==="Android"||t==="iOS"||/Mobi/i.test(n);return`${t}, ${i?"Mobile":"Desktop"}`}function Zu(){const n={},e=Yu();e&&(n.timezone=e);const t=Xu();return t&&(n.device=t),n}function eh(n,e,t,i){const r=hr(n,`${e}/v2/agents/${t}`,i);return{async createStream(s){return r.post("/sessions",s)}}}const th={[Q.ChatAnswer]:xe.Answer,[Q.ChatPartial]:xe.Partial},qa=2e4;async function nh(){try{return await Promise.resolve().then(()=>gv)}catch{throw new Error("LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client")}}const ih={excellent:rt.Strong,good:rt.Strong,poor:rt.Weak,lost:rt.Unknown,unknown:rt.Unknown},ln=(n="Stream Error")=>new oi(n);function yr(n,e,t){var i,r;throw e("Failed to connect to LiveKit room:",n),(i=t.onConnectionStateChange)==null||i.call(t,le.Fail,"internal:init-error"),(r=t.onError)==null||r.call(t,n,{sessionId:""}),n}async function rh(n,e,t){var Fl;const i=xa(t.debug||!1,"LiveKitStreamingManager"),{Room:r,RoomEvent:s,ConnectionState:o,Track:a}=await nh(),{callbacks:c,auth:d,baseURL:l,analytics:u}=t;let h=null,m=!1;const v=st.Fluent;let g=null;const S={isPublishing:!1,publication:null},k={isPublishing:!1,publication:null};let _=null,P=null,y=null,b=!1;h=new r({adaptiveStream:!1,dynacast:!0});let T=null,L=fe.Idle,B=!0;const I=new Set,U=eh(d,l||Mn,n,c.onError);let N,W,ee,Se=!0;try{const C=await U.createStream({transport:e.transport,chat_persist:e.chat_persist??!0,verbose:t.verbose??!1}),{id:O,session_token:H,session_url:J,interrupt_enabled:de}=C;(Fl=c.onStreamCreated)==null||Fl.call(c,{session_id:O,stream_id:O,agent_id:n}),N=O,W=H,ee=J,Se=de??!0,await h.prepareConnection(ee,W)}catch(C){yr(C,i,c)}if(!ee||!W||!N)return Promise.reject(new Error("Failed to initialize LiveKit stream"));h.on(s.ConnectionStateChanged,q).on(s.ConnectionQualityChanged,te).on(s.ParticipantConnected,se).on(s.ParticipantDisconnected,ae).on(s.TrackSubscribed,Ue).on(s.TrackUnsubscribed,j).on(s.DataReceived,Pn).on(s.MediaDevicesError,ir).on(s.TranscriptionReceived,R).on(s.EncryptionError,rr).on(s.TrackSubscriptionFailed,sr);function R(C,O){O!=null&&O.isLocal&&(pt.update(),L===fe.Talking&&(L=fe.Idle))}async function F(){const C=Zu();if(!(!h||Object.keys(C).length===0))try{await h.localParticipant.setAttributes(C)}catch(O){i("Failed to set user context attributes",O)}}try{await h.connect(ee,W),i("LiveKit room joined successfully"),F(),T=setTimeout(()=>{var O;i(`Track subscription timeout - no track subscribed within ${qa/1e3} seconds after connect`),T=null;const C=ln("Track subscription timeout");u.track("connectivity-error",{error:ui(C),sessionId:N}),(O=c.onError)==null||O.call(c,C,{sessionId:N}),Xs("internal:track-subscription-timeout")},qa)}catch(C){yr(C,i,c)}u.enrich({"stream-type":v});function q(C){var O,H,J,de;switch(i("Connection state changed:",C),C){case o.Connecting:i("CALLBACK: onConnectionStateChange(Connecting)"),(O=c.onConnectionStateChange)==null||O.call(c,le.Connecting,"livekit:connecting");break;case o.Connected:i("LiveKit room connected successfully"),m=!0;break;case o.Disconnected:i("LiveKit room disconnected"),m=!1,b=!1,S.publication=null,k.publication=null,(H=c.onConnectionStateChange)==null||H.call(c,le.Disconnected,"livekit:disconnected");break;case o.Reconnecting:i("LiveKit room reconnecting..."),(J=c.onConnectionStateChange)==null||J.call(c,le.Connecting,"livekit:reconnecting");break;case o.SignalReconnecting:i("LiveKit room signal reconnecting..."),(de=c.onConnectionStateChange)==null||de.call(c,le.Connecting,"livekit:signal-reconnecting");break}}function te(C,O){var H;i("Connection quality:",C),O!=null&&O.isLocal&&((H=c.onConnectivityStateChange)==null||H.call(c,ih[C]))}function se(C){i("Participant connected:",C.identity)}function ae(C){i("Participant disconnected:",C.identity),Xs("livekit:participant-disconnected")}function Re(){var C;y!==Z.Start&&(i("CALLBACK: onVideoStateChange(Start)"),y=Z.Start,(C=c.onVideoStateChange)==null||C.call(c,Z.Start))}function Ae(C){var O;y!==Z.Stop&&(i("CALLBACK: onVideoStateChange(Stop)"),y=Z.Stop,(O=c.onVideoStateChange)==null||O.call(c,Z.Stop,C))}function Ue(C,O,H){var de,he,Ie;i(`Track subscribed: ${C.kind} from ${H.identity}`);const J=C.mediaStreamTrack;if(!J){i(`No mediaStreamTrack available for ${C.kind}`);return}g?(g.addTrack(J),i(`Added ${C.kind} track to shared MediaStream`)):(g=new MediaStream([J]),i(`Created shared MediaStream with ${C.kind} track`)),C.kind==="audio"&&(P=Iu(()=>C.getRTCStatsReport(),({sttLatency:ie,serviceLatency:ft})=>{var Bl,jl,Vl;const si=pt.get(!0);let ai=0;if(ie){const ql=((jl=(Bl=_==null?void 0:_.getReport())==null?void 0:Bl.webRTCStats)==null?void 0:jl.avgRtt)??0;ai=ql>0?Math.round(ql*1e3):0}const In=si>0?si+(ie??0)+ai:void 0,Lt=In!==void 0&&ft!==void 0?In-ft:void 0;(Vl=c.onFirstAudioDetected)==null||Vl.call(c,{latency:In,networkLatency:Lt})})),C.kind==="video"&&((de=c.onStreamReady)==null||de.call(c),i("CALLBACK: onSrcObjectReady"),(he=c.onSrcObjectReady)==null||he.call(c,g),b||(b=!0,i("CALLBACK: onConnectionStateChange(Connected)"),(Ie=c.onConnectionStateChange)==null||Ie.call(c,le.Connected,"livekit:track-subscribed")),_=Ua(()=>C.getRTCStatsReport(),()=>m,Hl,(ie,ft)=>{i(`Video state change: ${ie}`),ie===Z.Start?(T&&(clearTimeout(T),T=null,i("Track subscription timeout cleared")),Re()):ie===Z.Stop&&Ae(ft)}),_.start())}function j(C,O,H){i(`Track unsubscribed: ${C.kind} from ${H.identity}`),C.kind==="audio"&&(P==null||P.destroy(),P=null),C.kind==="video"&&(Ae(_==null?void 0:_.getReport()),_==null||_.stop(),_=null)}function V(C,O){var J;const H=th[C];H&&((J=c.onMessage)==null||J.call(c,H,{event:H,...O}))}function oe(C,O){var H,J,de,he,Ie;if(C===Q.ToolCallStarted){const ie=O;B=ie.interruptible!==!1,(H=c.onInterruptibleChange)==null||H.call(c,B),I.add(ie.call_id),L=fe.ToolActive,(J=c.onAgentActivityStateChange)==null||J.call(c,fe.ToolActive),(de=c.onToolEvent)==null||de.call(c,Q.ToolCallStarted,ie);return}if(C===Q.ToolCallDone){const ie=O;We(ie.call_id),(he=c.onToolEvent)==null||he.call(c,Q.ToolCallDone,ie);return}if(C===Q.ToolCallError){const ie=O;We(ie.call_id),(Ie=c.onToolEvent)==null||Ie.call(c,Q.ToolCallError,ie)}}function We(C){var O;I.delete(C),I.size===0&&L===fe.ToolActive&&(L=fe.Idle,(O=c.onAgentActivityStateChange)==null||O.call(c,fe.Idle))}function mt(C,O){var H,J,de,he,Ie,ie;if(B=((H=O.metadata)==null?void 0:H.interruptible)!==!1,(J=c.onInterruptibleChange)==null||J.call(c,B),C===Q.StreamVideoCreated){L=fe.Talking,(de=c.onAgentActivityStateChange)==null||de.call(c,fe.Talking),P==null||P.arm({sttLatency:(he=O==null?void 0:O.stt)==null?void 0:he.latency,serviceLatency:O==null?void 0:O.serviceLatency});return}if(I.size>0){L!==fe.ToolActive&&(L=fe.ToolActive,(Ie=c.onAgentActivityStateChange)==null||Ie.call(c,fe.ToolActive));return}B&&(L=fe.Idle,(ie=c.onAgentActivityStateChange)==null||ie.call(c,fe.Idle))}function ye(C,O){var he,Ie,ie,ft;const H=((Ie=(he=_==null?void 0:_.getReport())==null?void 0:he.webRTCStats)==null?void 0:Ie.avgRtt)??0,J=H>0?Math.round(H/2*1e3):0,de={...O,downstreamNetworkLatency:J};t.debug&&((ie=O==null?void 0:O.metadata)!=null&&ie.sentiment)&&(de.sentiment={id:O.metadata.sentiment.id,name:O.metadata.sentiment.sentiment}),(ft=c.onMessage)==null||ft.call(c,C,de),mt(C,O)}function it(C,O){var H;(H=c.onMessage)==null||H.call(c,xe.Transcribe,{event:xe.Transcribe,...O}),queueMicrotask(()=>{var J;(J=c.onAgentActivityStateChange)==null||J.call(c,fe.Loading)})}const zs={[Q.ChatAnswer]:V,[Q.ChatPartial]:V,[Q.ToolCallStarted]:oe,[Q.ToolCallDone]:oe,[Q.ToolCallError]:oe,[Q.StreamVideoCreated]:ye,[Q.StreamVideoDone]:ye,[Q.StreamVideoError]:ye,[Q.StreamVideoRejected]:ye,[Q.ChatAudioTranscribed]:it};function Pn(C,O,H,J){const de=new TextDecoder().decode(C);try{const he=JSON.parse(de),Ie=J||he.subject;if(i("Data received:",{subject:Ie,data:he}),!Ie)return;const ie=zs[Ie];ie==null||ie(Ie,he)}catch(he){i("Failed to parse data channel message:",he)}}function ir(C){var O;i("Media devices error:",C),(O=c.onError)==null||O.call(c,ln(),{sessionId:N})}function rr(C){var O;i("Encryption error:",C),(O=c.onError)==null||O.call(c,ln(),{sessionId:N})}function sr(C,O,H){i("Track subscription failed:",{trackSid:C,participant:O,reason:H})}function vv(C,O,H){for(const[J,de]of H)if(de.source===O&&de.track){const he=de.track.mediaStreamTrack;if(he===C||(he==null?void 0:he.id)===C.id)return de}return null}async function Ll(C,O,H,J,de,he){var si,ai,In;if(!m||!h)throw i(`Room is not connected, cannot publish ${J} stream`),new Error("Room is not connected");if(C.isPublishing){i(`${J} publish already in progress, skipping`);return}const Ie=H(O);if(Ie.length===0)throw new Error(`No ${J} track found in the provided MediaStream`);const ie=Ie[0],ft=vv(ie,J,de());if(ft){i(`${J} track is already published, skipping`,{trackId:ie.id,publishedTrackId:(ai=(si=ft.track)==null?void 0:si.mediaStreamTrack)==null?void 0:ai.id}),C.publication=ft;return}if((In=C.publication)!=null&&In.track){const Lt=C.publication.track.mediaStreamTrack;Lt!==ie&&(Lt==null?void 0:Lt.id)!==ie.id&&(i(`Unpublishing existing ${J} track before publishing new one`),await he())}i(`Publishing ${J} track from provided MediaStream`,{trackId:ie.id}),C.isPublishing=!0;try{C.publication=await h.localParticipant.publishTrack(ie,{source:J}),i(`${J} track published successfully`,{trackSid:C.publication.trackSid})}catch(Lt){throw i(`Failed to publish ${J} track:`,Lt),Lt}finally{C.isPublishing=!1}}async function Nl(C,O){if(!(!C.publication||!C.publication.track))try{h&&(await h.localParticipant.unpublishTrack(C.publication.track,!1),i(`${O} track unpublished`))}catch(H){i(`Error unpublishing ${O} track:`,H)}finally{C.publication=null}}async function yv(C){return Ll(S,C,O=>O.getAudioTracks(),a.Source.Microphone,()=>h.localParticipant.audioTrackPublications,$s)}async function $s(){return Nl(S,"Microphone")}async function bv(C){if(!m||!h)throw i("Cannot replace microphone track: room is not connected"),new Error("Room is not connected");if(C.kind!=="audio")throw i("Cannot replace microphone track: not an audio track",{kind:C.kind}),new Error("Microphone track must be an audio track");if(S.isPublishing)throw i("Cannot replace microphone track: publish in progress"),new Error("Microphone publish in progress");const O=S.publication;if(!O||!O.track)throw i("Cannot replace microphone track: no publication to replace"),new Error("No microphone publication to replace");try{S.isPublishing=!0,await O.track.replaceTrack(C),i("Microphone track replaced",{trackId:C.id,trackSid:O.trackSid})}finally{S.isPublishing=!1}}async function kv(C){return Ll(k,C,O=>O.getVideoTracks(),a.Source.Camera,()=>h.localParticipant.videoTrackPublications,Qs)}async function Qs(){return Nl(k,"Camera")}function Tv(){g&&(g.getTracks().forEach(C=>C.stop()),g=null)}async function Ys(C,O){var H,J;if(!m||!h){i("Room is not connected for sending messages"),(H=c.onError)==null||H.call(c,ln(),{sessionId:N});return}try{await h.localParticipant.sendText(C,{topic:O}),i("Message sent successfully:",C)}catch(de){i("Failed to send message:",de),(J=c.onError)==null||J.call(c,ln(),{sessionId:N})}}async function Ul(C){var O;try{const J=JSON.parse(C).topic;return Ys("",J)}catch(H){i("Failed to send data channel message:",H),(O=c.onError)==null||O.call(c,ln(),{sessionId:N})}}function Sv(C){return Ys(C,"lk.chat")}async function Xs(C){var O,H;T&&(clearTimeout(T),T=null),P==null||P.destroy(),P=null,h&&((O=c.onConnectionStateChange)==null||O.call(c,le.Disconnecting,C),await Promise.all([$s(),Qs()]),await h.disconnect()),Tv(),m=!1,b=!1,I.clear(),(H=c.onAgentActivityStateChange)==null||H.call(c,fe.Idle),L=fe.Idle}return{speak(C){const O=typeof C=="string"?C:JSON.stringify(C);return Ys(O,"did.speak")},disconnect:()=>Xs("user:disconnect"),async reconnect(){var C,O;if((h==null?void 0:h.state)===o.Connected){i("Room is already connected");return}if(!h||!ee||!W)throw i("Cannot reconnect: missing room, URL or token"),new Error("Cannot reconnect: session not available");i("Reconnecting to LiveKit room, state:",h.state),b=!1,(C=c.onConnectionStateChange)==null||C.call(c,le.Connecting,"user:reconnect");try{if(await h.connect(ee,W),i("Room reconnected"),m=!0,h.remoteParticipants.size===0){if(i("Waiting for agent to join..."),!await new Promise(J=>{const de=setTimeout(()=>{h==null||h.off(s.ParticipantConnected,he),J(!1)},5e3),he=()=>{clearTimeout(de),h==null||h.off(s.ParticipantConnected,he),J(!0)};h==null||h.on(s.ParticipantConnected,he)}))throw i("Agent did not join within timeout"),await h.disconnect(),new Error("Agent did not rejoin the room");i("Agent joined, reconnection successful")}}catch(H){throw i("Failed to reconnect:",H),(O=c.onConnectionStateChange)==null||O.call(c,le.Fail,"user:reconnect-failed"),H}},sendDataChannelMessage:Ul,sendTextMessage:Sv,publishMicrophoneStream:yv,unpublishMicrophoneStream:$s,replaceMicrophoneTrack:bv,publishCameraStream:kv,unpublishCameraStream:Qs,interrupt(C){C!=="text"&&Ul(JSON.stringify({topic:"did.interrupt"}))},registerRpcMethod(C,O){h==null||h.registerRpcMethod(C,O)},unregisterRpcMethod(C){h==null||h.unregisterRpcMethod(C)},sessionId:N,streamId:N,streamType:v,interruptAvailable:Se,isInterruptible:B}}const sh=Object.freeze(Object.defineProperty({__proto__:null,createLiveKitStreamingManager:rh,handleInitError:yr},Symbol.toStringTag,{value:"Module"}));function ah(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var r=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,r.get?r:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var oh=Object.defineProperty,ch=(n,e,t)=>e in n?oh(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Ka=(n,e,t)=>ch(n,typeof e!="symbol"?e+"":e,t);class Le{constructor(){Ka(this,"_locking"),Ka(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(r=>e=()=>{this._locks-=1,r()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function be(n,e){if(!n)throw new Error(e)}const dh=34028234663852886e22,lh=-34028234663852886e22,uh=4294967295,hh=2147483647,mh=-2147483648;function mi(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>hh||n<mh)throw new Error("invalid int 32: "+n)}function br(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>uh||n<0)throw new Error("invalid uint 32: "+n)}function Wa(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>dh||n<lh))throw new Error("invalid float 32: "+n)}const Ha=Symbol("@bufbuild/protobuf/enum-type");function fh(n){const e=n[Ha];return be(e,"missing enum type on enum object"),e}function Ja(n,e,t,i){n[Ha]=Ga(e,t.map(r=>({no:r.no,name:r.name,localName:n[r.no]})))}function Ga(n,e,t){const i=Object.create(null),r=Object.create(null),s=[];for(const o of e){const a=za(o);s.push(a),i[o.name]=a,r[o.no]=a}return{typeName:n,values:s,findName(o){return i[o]},findNumber(o){return r[o]}}}function ph(n,e,t){const i={};for(const r of e){const s=za(r);i[s.localName]=s.no,i[s.no]=s.localName}return Ja(i,n,e),i}function za(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class kr{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),r=i.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){const i=this.getType(),r=i.runtime.json,s=r.makeReadOptions(t);return r.readMessage(i,e,s,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,r=i.makeWriteOptions(e),s=r.writerFactory();return i.writeMessage(this,s,r),s.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,r=i.makeWriteOptions(e);return i.writeMessage(this,r)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function gh(n,e,t,i){var r;const s=(r=i==null?void 0:i.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),o={[s]:function(a){n.util.initFields(this),n.util.initPartial(a,this)}}[s];return Object.setPrototypeOf(o.prototype,new kr),Object.assign(o,{runtime:n,typeName:e,fields:n.util.newFieldList(t),fromBinary(a,c){return new o().fromBinary(a,c)},fromJson(a,c){return new o().fromJson(a,c)},fromJsonString(a,c){return new o().fromJsonString(a,c)},equals(a,c){return n.util.equals(o,a,c)}}),o}function vh(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Tr(n,e,t){for(let s=0;s<28;s=s+7){const o=n>>>s,a=!(!(o>>>7)&&e==0),c=(a?o|128:o)&255;if(t.push(c),!a)return}const i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){const o=e>>>s,a=!!(o>>>7),c=(a?o|128:o)&255;if(t.push(c),!a)return}t.push(e>>>31&1)}}const fi=4294967296;function $a(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,r=0;function s(o,a){const c=Number(n.slice(o,a));r*=t,i=i*t+c,i>=fi&&(r=r+(i/fi|0),i=i%fi)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Ya(i,r):Sr(i,r)}function yh(n,e){let t=Sr(n,e);const i=t.hi&2147483648;i&&(t=Ya(t.lo,t.hi));const r=Qa(t.lo,t.hi);return i?"-"+r:r}function Qa(n,e){if({lo:n,hi:e}=bh(n,e),e<=2097151)return String(fi*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535;let s=t+i*6777216+r*6710656,o=i+r*8147497,a=r*2;const c=1e7;return s>=c&&(o+=Math.floor(s/c),s%=c),o>=c&&(a+=Math.floor(o/c),o%=c),a.toString()+Xa(o)+Xa(s)}function bh(n,e){return{lo:n>>>0,hi:e>>>0}}function Sr(n,e){return{lo:n|0,hi:e|0}}function Ya(n,e){return e=~e,n?n=~n+1:e+=1,Sr(n,e)}const Xa=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Za(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function kh(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Th(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),o=BigInt("0"),a=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>s||d<r)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>a||d<o)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=r=>be(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),i=r=>be(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),i(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),$a(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),i(r),$a(r)},dec(r,s){return yh(r,s)},uDec(r,s){return Qa(r,s)}}}const pe=Th();var w;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(w||(w={}));var Ut;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(Ut||(Ut={}));function Ft(n,e,t){if(e===t)return!0;if(n==w.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==t}return!1}function un(n,e){switch(n){case w.BOOL:return!1;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==0?pe.zero:"0";case w.DOUBLE:case w.FLOAT:return 0;case w.BYTES:return new Uint8Array(0);case w.STRING:return"";default:return 0}}function eo(n,e){switch(n){case w.BOOL:return e===!1;case w.STRING:return e==="";case w.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Ee;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(Ee||(Ee={}));class Sh{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(br(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return mi(e),Za(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Wa(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){br(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){mi(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return mi(e),e=(e<<1^e>>31)>>>0,Za(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=pe.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=pe.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=pe.enc(e);return Tr(t.lo,t.hi,this.buf),this}sint64(e){let t=pe.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return Tr(r,s,this.buf),this}uint64(e){let t=pe.uEnc(e);return Tr(t.lo,t.hi,this.buf),this}}class Ch{constructor(e,t){this.varint64=vh,this.uint32=kh,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case Ee.Varint:for(;this.buf[this.pos++]&128;);break;case Ee.Bit64:this.pos+=4;case Ee.Bit32:this.pos+=4;break;case Ee.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ee.StartGroup:for(;;){const[s,o]=this.tag();if(o===Ee.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return pe.dec(...this.varint64())}uint64(){return pe.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,pe.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return pe.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return pe.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function Eh(n,e,t,i){let r;return{typeName:e,extendee:t,get field(){if(!r){const s=typeof i=="function"?i():i;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=n.util.newFieldList([s]).list()[0]}return r},runtime:n}}function to(n){const e=n.field.localName,t=Object.create(null);return t[e]=wh(n),[t,()=>t[e]]}function wh(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return un(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function _h(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),pi=[];for(let n=0;n<wt.length;n++)pi[wt[n].charCodeAt(0)]=n;pi[45]=wt.indexOf("+"),pi[95]=wt.indexOf("/");const no={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,r=0,s,o=0;for(let a=0;a<n.length;a++){if(s=pi[n.charCodeAt(a)],s===void 0)switch(n[a]){case"=":r=0;case`
2
2
  `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:t[i++]=o<<2|(s&48)>>4,o=s,r=2;break;case 2:t[i++]=(o&15)<<4|(s&60)>>2,o=s,r=3;break;case 3:t[i++]=(o&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,r=0;for(let s=0;s<n.length;s++)switch(i=n[s],t){case 0:e+=wt[i>>2],r=(i&3)<<4,t=1;break;case 1:e+=wt[r|i>>4],r=(i&15)<<2,t=2;break;case 2:e+=wt[r|i>>6],e+=wt[i&63],t=0;break}return t&&(e+=wt[r],e+="=",t==1&&(e+="=")),e}};function Rh(n,e,t){ro(e,n);const i=e.runtime.bin.makeReadOptions(t),r=_h(n.getType().runtime.bin.listUnknownFields(n),e.field),[s,o]=to(e);for(const a of r)e.runtime.bin.readField(s,i.readerFactory(a.data),e.field,a.wireType,i);return o()}function Ph(n,e,t,i){ro(e,n);const r=e.runtime.bin.makeReadOptions(i),s=e.runtime.bin.makeWriteOptions(i);if(io(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const o=s.writerFactory();let a=e.field;!a.opt&&!a.repeated&&(a.kind=="enum"||a.kind=="scalar")&&(a=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(a,t,o,s);const c=r.readerFactory(o.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function io(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function ro(n,e){be(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function so(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!eo(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function ao(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?un(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function _t(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(kr.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function oo(n,e){return _t(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}w.DOUBLE,w.FLOAT,w.INT64,w.UINT64,w.INT32,w.UINT32,w.BOOL,w.STRING,w.BYTES;const co={ignoreUnknownFields:!1},lo={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ih(n){return n?Object.assign(Object.assign({},co),n):co}function Mh(n){return n?Object.assign(Object.assign({},lo),n):lo}const gi=Symbol(),vi=Symbol();function Oh(){return{makeReadOptions:Ih,makeWriteOptions:Mh,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(gt(e)));i=i??new n;const r=new Map,s=t.typeRegistry;for(const[o,a]of Object.entries(e)){const c=n.fields.findJsonName(o);if(c){if(c.oneof){if(a===null&&c.kind=="scalar")continue;const d=r.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(o,'"'));r.set(c.oneof,o)}uo(i,a,c,t,n)}else{let d=!1;if(s!=null&&s.findExtension&&o.startsWith("[")&&o.endsWith("]")){const l=s.findExtension(o.substring(1,o.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=to(l);uo(u,a,l.field,t,l),Ph(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let r;try{for(r of t.fields.byNumber()){if(!so(r,n)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!Ah(r))continue}const o=r.oneof?n[r.oneof.localName].value:n[r.localName],a=ho(r,o,e);a!==void 0&&(i[e.useProtoFieldName?r.name:r.jsonName]=a)}const s=e.typeRegistry;if(s!=null&&s.findExtensionFor)for(const o of t.runtime.bin.listUnknownFields(n)){const a=s.findExtensionFor(t.typeName,o.no);if(a&&io(n,a)){const c=Rh(n,a,e),d=ho(a.field,c,e);d!==void 0&&(i[a.field.jsonName]=d)}}}catch(s){const o=r?"cannot encode field ".concat(t.typeName,".").concat(r.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),a=s instanceof Error?s.message:String(s);throw new Error(o+(a.length>0?": ".concat(a):""))}return i},readScalar(n,e,t){return An(n,e,t??Ut.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||eo(n,e)))return yi(n,e)},debug:gt}}function gt(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function uo(n,e,t,i,r){let s=t.localName;if(t.repeated){if(be(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(e)));const o=n[s];for(const a of e){if(a===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(a)));switch(t.kind){case"message":o.push(t.T.fromJson(a,i));break;case"enum":const c=Cr(t.T,a,i.ignoreUnknownFields,!0);c!==vi&&o.push(c);break;case"scalar":try{o.push(An(t.T,a,t.L,!0))}catch(d){let l="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(a));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}}else if(t.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(e)));const o=n[s];for(const[a,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: map value null"));let d;try{d=Dh(t.K,a)}catch(l){let u="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":o[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Cr(t.V.T,c,i.ignoreUnknownFields,!0);l!==vi&&(o[d]=l);break;case"scalar":try{o[d]=An(t.V.T,c,Ut.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[t.oneof.localName]={case:s},s="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let a=n[s];_t(a)?a.fromJson(e,i):(n[s]=a=o.fromJson(e,i),o.fieldWrapper&&!t.oneof&&(n[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":const c=Cr(t.T,e,i.ignoreUnknownFields,!1);switch(c){case gi:ao(t,n);break;case vi:break;default:n[s]=c;break}break;case"scalar":try{const d=An(t.T,e,t.L,!1);switch(d){case gi:ao(t,n);break;default:n[s]=d;break}}catch(d){let l="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(gt(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function Dh(n,e){if(n===w.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return An(n,e,Ut.BIGINT,!0).toString()}function An(n,e,t,i){if(e===null)return i?un(n,t):gi;switch(n){case w.DOUBLE:case w.FLOAT:if(e==="NaN")return Number.NaN;if(e==="Infinity")return Number.POSITIVE_INFINITY;if(e==="-Infinity")return Number.NEGATIVE_INFINITY;if(e===""||typeof e=="string"&&e.trim().length!==e.length||typeof e!="string"&&typeof e!="number")break;const r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return n==w.FLOAT&&Wa(r),r;case w.INT32:case w.FIXED32:case w.SFIXED32:case w.SINT32:case w.UINT32:let s;if(typeof e=="number"?s=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(s=Number(e)),s===void 0)break;return n==w.UINT32||n==w.FIXED32?br(s):mi(s),s;case w.INT64:case w.SFIXED64:case w.SINT64:if(typeof e!="number"&&typeof e!="string")break;const o=pe.parse(e);return t?o.toString():o;case w.FIXED64:case w.UINT64:if(typeof e!="number"&&typeof e!="string")break;const a=pe.uParse(e);return t?a.toString():a;case w.BOOL:if(typeof e!="boolean")break;return e;case w.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case w.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return no.dec(e)}throw new Error}function Cr(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:gi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const r=n.findName(e);if(r!==void 0)return r.no;if(t)return vi;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(gt(e)))}function Ah(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function ho(n,e,t){if(n.kind=="map"){be(typeof e=="object"&&e!=null);const i={},r=Object.entries(e);switch(n.V.kind){case"scalar":for(const[o,a]of r)i[o.toString()]=yi(n.V.T,a);break;case"message":for(const[o,a]of r)i[o.toString()]=a.toJson(t);break;case"enum":const s=n.V.T;for(const[o,a]of r)i[o.toString()]=Er(s,a,t.enumAsInteger);break}return t.emitDefaultValues||r.length>0?i:void 0}if(n.repeated){be(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let r=0;r<e.length;r++)i.push(yi(n.T,e[r]));break;case"enum":for(let r=0;r<e.length;r++)i.push(Er(n.T,e[r],t.enumAsInteger));break;case"message":for(let r=0;r<e.length;r++)i.push(e[r].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return yi(n.T,e);case"enum":return Er(n.T,e,t.enumAsInteger);case"message":return oo(n.T,e).toJson(t)}}function Er(n,e,t){var i;if(be(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const r=n.findNumber(e);return(i=r==null?void 0:r.name)!==null&&i!==void 0?i:e}function yi(n,e){switch(n){case w.INT32:case w.SFIXED32:case w.SINT32:case w.FIXED32:case w.UINT32:return be(typeof e=="number"),e;case w.FLOAT:case w.DOUBLE:return be(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case w.STRING:return be(typeof e=="string"),e;case w.BOOL:return be(typeof e=="boolean"),e;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return be(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case w.BYTES:return be(e instanceof Uint8Array),no.enc(e)}}const hn=Symbol("@bufbuild/protobuf/unknown-fields"),mo={readUnknownFields:!0,readerFactory:n=>new Ch(n)},fo={writeUnknownFields:!0,writerFactory:()=>new Sh};function xh(n){return n?Object.assign(Object.assign({},mo),n):mo}function Lh(n){return n?Object.assign(Object.assign({},fo),n):fo}function Nh(){return{makeReadOptions:xh,makeWriteOptions:Lh,listUnknownFields(n){var e;return(e=n[hn])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[hn]},writeUnknownFields(n,e){const i=n[hn];if(i)for(const r of i)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(n,e,t,i){const r=n;Array.isArray(r[hn])||(r[hn]=[]),r[hn].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,r){const s=n.getType(),o=r?e.len:e.pos+t;let a,c;for(;e.pos<o&&([a,c]=e.tag(),!(r===!0&&c==Ee.EndGroup));){const d=s.fields.find(a);if(!d){const l=e.skip(c,a);i.readUnknownFields&&this.onUnknownField(n,a,c,l);continue}po(n,e,d,c,i)}if(r&&(c!=Ee.EndGroup||a!==t))throw new Error("invalid end group tag")},readField:po,writeMessage(n,e,t){const i=n.getType();for(const r of i.fields.byNumber()){if(!so(r,n)){if(r.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(r.name," to binary: required field not set"));continue}const s=r.oneof?n[r.oneof.localName].value:n[r.localName];go(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&go(n,e,t,i)}}}function po(n,e,t,i,r){let{repeated:s,localName:o}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=o&&delete n.value,n.case=o,o="value"),t.kind){case"scalar":case"enum":const a=t.kind=="enum"?w.INT32:t.T;let c=ki;if(t.kind=="scalar"&&t.L>0&&(c=Fh),s){let h=n[o];if(i==Ee.LengthDelimited&&a!=w.STRING&&a!=w.BYTES){let v=e.uint32()+e.pos;for(;e.pos<v;)h.push(c(e,a))}else h.push(c(e,a))}else n[o]=c(e,a);break;case"message":const d=t.T;s?n[o].push(bi(e,new d,r,t)):_t(n[o])?bi(e,n[o],r,t):(n[o]=bi(e,new d,r,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[o]=d.fieldWrapper.unwrapField(n[o])));break;case"map":let[l,u]=Uh(t,e,r);n[o][l]=u;break}}function bi(n,e,t,i){const r=e.getType().runtime.bin,s=i==null?void 0:i.delimited;return r.readMessage(e,n,s?i.no:n.uint32(),t,s),e}function Uh(n,e,t){const i=e.uint32(),r=e.pos+i;let s,o;for(;e.pos<r;){const[a]=e.tag();switch(a){case 1:s=ki(e,n.K);break;case 2:switch(n.V.kind){case"scalar":o=ki(e,n.V.T);break;case"enum":o=e.int32();break;case"message":o=bi(e,new n.V.T,t,void 0);break}break}}if(s===void 0&&(s=un(n.K,Ut.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),o===void 0)switch(n.V.kind){case"scalar":o=un(n.V.T,Ut.BIGINT);break;case"enum":o=n.V.T.values[0].no;break;case"message":o=new n.V.T;break}return[s,o]}function Fh(n,e){const t=ki(n,e);return typeof t=="bigint"?t.toString():t}function ki(n,e){switch(e){case w.STRING:return n.string();case w.BOOL:return n.bool();case w.DOUBLE:return n.double();case w.FLOAT:return n.float();case w.INT32:return n.int32();case w.INT64:return n.int64();case w.UINT64:return n.uint64();case w.FIXED64:return n.fixed64();case w.BYTES:return n.bytes();case w.FIXED32:return n.fixed32();case w.SFIXED32:return n.sfixed32();case w.SFIXED64:return n.sfixed64();case w.SINT64:return n.sint64();case w.UINT32:return n.uint32();case w.SINT32:return n.sint32()}}function go(n,e,t,i){be(e!==void 0);const r=n.repeated;switch(n.kind){case"scalar":case"enum":let s=n.kind=="enum"?w.INT32:n.T;if(r)if(be(Array.isArray(e)),n.packed)jh(t,s,n.no,e);else for(const o of e)xn(t,s,n.no,o);else xn(t,s,n.no,e);break;case"message":if(r){be(Array.isArray(e));for(const o of e)vo(t,i,n,o)}else vo(t,i,n,e);break;case"map":be(typeof e=="object"&&e!=null);for(const[o,a]of Object.entries(e))Bh(t,i,n,o,a);break}}function Bh(n,e,t,i,r){n.tag(t.no,Ee.LengthDelimited),n.fork();let s=i;switch(t.K){case w.INT32:case w.FIXED32:case w.UINT32:case w.SFIXED32:case w.SINT32:s=Number.parseInt(i);break;case w.BOOL:be(i=="true"||i=="false"),s=i=="true";break}switch(xn(n,t.K,1,s),t.V.kind){case"scalar":xn(n,t.V.T,2,r);break;case"enum":xn(n,w.INT32,2,r);break;case"message":be(r!==void 0),n.tag(2,Ee.LengthDelimited).bytes(r.toBinary(e));break}n.join()}function vo(n,e,t,i){const r=oo(t.T,i);t.delimited?n.tag(t.no,Ee.StartGroup).raw(r.toBinary(e)).tag(t.no,Ee.EndGroup):n.tag(t.no,Ee.LengthDelimited).bytes(r.toBinary(e))}function xn(n,e,t,i){be(i!==void 0);let[r,s]=yo(e);n.tag(t,r)[s](i)}function jh(n,e,t,i){if(!i.length)return;n.tag(t,Ee.LengthDelimited).fork();let[,r]=yo(e);for(let s=0;s<i.length;s++)n[r](i[s]);n.join()}function yo(n){let e=Ee.Varint;switch(n){case w.BYTES:case w.STRING:e=Ee.LengthDelimited;break;case w.DOUBLE:case w.FIXED64:case w.SFIXED64:e=Ee.Bit64;break;case w.FIXED32:case w.SFIXED32:case w.FLOAT:e=Ee.Bit32;break}const t=w[n].toLowerCase();return[e,t]}function Vh(){return{setEnumType:Ja,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const r=i.localName,s=e,o=n;if(o[r]!=null)switch(i.kind){case"oneof":const a=o[r].case;if(a===void 0)continue;const c=i.findField(a);let d=o[r].value;c&&c.kind=="message"&&!_t(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===w.BYTES&&(d=Ln(d)),s[r]={case:a,value:d};break;case"scalar":case"enum":let l=o[r];i.T===w.BYTES&&(l=i.repeated?l.map(Ln):Ln(l)),s[r]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===w.BYTES)for(const[m,v]of Object.entries(o[r]))s[r][m]=Ln(v);else Object.assign(s[r],o[r]);break;case"message":const h=i.V.T;for(const m of Object.keys(o[r])){let v=o[r][m];h.fieldWrapper||(v=new h(v)),s[r][m]=v}break}break;case"message":const u=i.T;if(i.repeated)s[r]=o[r].map(h=>_t(h,u)?h:new u(h));else{const h=o[r];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?s[r]=Ln(h):s[r]=h:s[r]=_t(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const r=e[i.localName],s=t[i.localName];if(i.repeated){if(r.length!==s.length)return!1;switch(i.kind){case"message":return r.every((o,a)=>i.T.equals(o,s[a]));case"scalar":return r.every((o,a)=>Ft(i.T,o,s[a]));case"enum":return r.every((o,a)=>Ft(w.INT32,o,s[a]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":let o=r,a=s;return i.T.fieldWrapper&&(o!==void 0&&!_t(o)&&(o=i.T.fieldWrapper.wrapField(o)),a!==void 0&&!_t(a)&&(a=i.T.fieldWrapper.wrapField(a))),i.T.equals(o,a);case"enum":return Ft(w.INT32,r,s);case"scalar":return Ft(i.T,r,s);case"oneof":if(r.case!==s.case)return!1;const c=i.findField(r.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(r.value,s.value);case"enum":return Ft(w.INT32,r.value,s.value);case"scalar":return Ft(c.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const d=Object.keys(r).concat(Object.keys(s));switch(i.V.kind){case"message":const l=i.V.T;return d.every(h=>l.equals(r[h],s[h]));case"enum":return d.every(h=>Ft(w.INT32,r[h],s[h]));case"scalar":const u=i.V.T;return d.every(h=>Ft(u,r[h],s[h]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const r of e.fields.byMember()){const s=n[r.localName];let o;if(r.repeated)o=s.map(Ti);else if(r.kind=="map"){o=i[r.localName];for(const[a,c]of Object.entries(s))o[a]=Ti(c)}else r.kind=="oneof"?o=r.findField(s.case)?{case:s.case,value:Ti(s.value)}:{case:void 0}:o=Ti(s);i[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,r.no,r.wireType,r.data);return t}}}function Ti(n){if(n===void 0)return n;if(_t(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function Ln(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function qh(n,e,t){return{syntax:n,json:Oh(),bin:Nh(),util:Object.assign(Object.assign({},Vh()),{newFieldList:e,initFields:t}),makeMessageType(i,r,s){return gh(this,i,r,s)},makeEnum:ph,makeEnumType:Ga,getEnumType:fh,makeExtension(i,r,s){return Eh(this,i,r,s)}}}class Kh{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function bo(n,e){const t=ko(n);return e?t:$h(zh(t))}function Wh(n){return bo(n,!1)}const Hh=ko;function ko(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let r=n.charAt(i);switch(r){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":t.push(r),e=!1;break;default:e&&(e=!1,r=r.toUpperCase()),t.push(r);break}}return t.join("")}const Jh=new Set(["constructor","toString","toJSON","valueOf"]),Gh=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),To=n=>"".concat(n,"$"),zh=n=>Gh.has(n)?To(n):n,$h=n=>Jh.has(n)?To(n):n;class Qh{constructor(e){this.kind="oneof",this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Wh(e)}addField(e){be(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let t=0;t<this.fields.length;t++)this._lookup[this.fields[t].localName]=this.fields[t]}return this._lookup[e]}}function Yh(n,e){var t,i,r,s,o,a;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=bo(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Hh(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(r=l.L)!==null&&r!==void 0?r:Ut.BIGINT),u.delimited=(s=l.delimited)!==null&&s!==void 0?s:!1,u.req=(o=l.req)!==null&&o!==void 0?o:!1,u.opt=(a=l.opt)!==null&&a!==void 0?a:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=w.BYTES&&l.T!=w.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new Qh(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const p=qh("proto3",n=>new Kh(n,e=>Yh(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=un(e.T,e.L);break}}});class Je extends kr{constructor(e){super(),this.seconds=pe.zero,this.nanos=0,p.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(p.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const r=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(r))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(r<Date.parse("0001-01-01T00:00:00Z")||r>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");return this.seconds=pe.parse(r/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?i="."+r.substring(0,3)+"Z":r.substring(6)==="000"?i="."+r.substring(0,6)+"Z":i="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Je.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Je({seconds:pe.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Je().fromBinary(e,t)}static fromJson(e,t){return new Je().fromJson(e,t)}static fromJsonString(e,t){return new Je().fromJsonString(e,t)}static equals(e,t){return p.util.equals(Je,e,t)}}Je.runtime=p,Je.typeName="google.protobuf.Timestamp",Je.fields=p.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Xh=p.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Je},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Zh,repeated:!0},{no:5,name:"events",kind:"message",T:tm,repeated:!0}]),Zh=p.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:em,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),em=p.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Je},{no:3,name:"value",kind:"scalar",T:2}]),tm=p.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Je},{no:7,name:"normalized_end_timestamp",kind:"message",T:Je,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),nm=p.makeEnum("livekit.AudioCodec",[{no:0,name:"DEFAULT_AC"},{no:1,name:"OPUS"},{no:2,name:"AAC"},{no:3,name:"AC_MP3"}]),im=p.makeEnum("livekit.VideoCodec",[{no:0,name:"DEFAULT_VC"},{no:1,name:"H264_BASELINE"},{no:2,name:"H264_MAIN"},{no:3,name:"H264_HIGH"},{no:4,name:"VP8"}]),rm=p.makeEnum("livekit.ImageCodec",[{no:0,name:"IC_DEFAULT"},{no:1,name:"IC_JPEG"}]),So=p.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ye=p.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),_e=p.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),wr=p.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Nn=p.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Un=p.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Xe=p.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),$t=p.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Co=p.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Me=p.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),Si=p.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:Ci,repeated:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"num_participants",kind:"scalar",T:13},{no:11,name:"num_publishers",kind:"scalar",T:13},{no:10,name:"active_recording",kind:"scalar",T:8},{no:13,name:"version",kind:"message",T:Uo}]),Ci=p.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),sm=p.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:p.getEnumType(_e),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),Qt=p.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:p.getEnumType(mn)},{no:4,name:"tracks",kind:"message",T:pn,repeated:!0},{no:5,name:"metadata",kind:"scalar",T:9},{no:6,name:"joined_at",kind:"scalar",T:3},{no:17,name:"joined_at_ms",kind:"scalar",T:3},{no:9,name:"name",kind:"scalar",T:9},{no:10,name:"version",kind:"scalar",T:13},{no:11,name:"permission",kind:"message",T:sm},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:p.getEnumType(fn)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:p.getEnumType(Xe)},{no:18,name:"kind_details",kind:"enum",T:p.getEnumType(am),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:_r,repeated:!0}]),mn=p.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),fn=p.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"},{no:7,name:"CONNECTOR"},{no:8,name:"BRIDGE"}]),am=p.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"}]),ke=p.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),om=p.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Bt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:p.getEnumType(Eo)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),pn=p.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:p.getEnumType(Ye)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:p.getEnumType(_e)},{no:10,name:"layers",kind:"message",T:Bt,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:om,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:p.getEnumType(ke)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Uo},{no:19,name:"audio_features",kind:"enum",T:p.getEnumType(Me),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:p.getEnumType(So)}]),_r=p.makeMessageType("livekit.DataTrackInfo",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"sid",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"encryption",kind:"enum",T:p.getEnumType(ke)}]),cm=p.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),Bt=p.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:p.getEnumType(wr)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9},{no:8,name:"repair_ssrc",kind:"scalar",T:13}]),Eo=p.makeEnum("livekit.VideoLayer.Mode",[{no:0,name:"MODE_UNUSED"},{no:1,name:"ONE_SPATIAL_LAYER_PER_STREAM"},{no:2,name:"MULTIPLE_SPATIAL_LAYERS_PER_STREAM"},{no:3,name:"ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR"}]),je=p.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:p.getEnumType($)},{no:4,name:"participant_identity",kind:"scalar",T:9},{no:5,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:2,name:"user",kind:"message",T:Rr,oneof:"value"},{no:3,name:"speaker",kind:"message",T:dm,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Po,oneof:"value"},{no:7,name:"transcription",kind:"message",T:lm,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Xh,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Ei,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Pr,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Ir,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Mr,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:wi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:_i,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ri,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:wo,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),$=p.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),wo=p.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:p.getEnumType(ke)},{no:2,name:"iv",kind:"scalar",T:12},{no:3,name:"key_index",kind:"scalar",T:13},{no:4,name:"encrypted_value",kind:"scalar",T:12}]),_o=p.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:Rr,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:Ei,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:Pr,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Ir,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:Mr,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:wi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:_i,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Ri,oneof:"value"}]),dm=p.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Ro,repeated:!0}]),Ro=p.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Rr=p.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),Po=p.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),lm=p.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:um,repeated:!0}]),um=p.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),Ei=p.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Pr=p.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),Ir=p.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Mr=p.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:Io,oneof:"value"}]),Io=p.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),Mo=p.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Oo=p.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:p.getEnumType(Do)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"region",kind:"scalar",T:9},{no:5,name:"node_id",kind:"scalar",T:9},{no:6,name:"debug_info",kind:"scalar",T:9},{no:7,name:"agent_protocol",kind:"scalar",T:5}]),Do=p.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Ao=p.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:p.getEnumType(xo)},{no:2,name:"version",kind:"scalar",T:9},{no:3,name:"protocol",kind:"scalar",T:5},{no:4,name:"os",kind:"scalar",T:9},{no:5,name:"os_version",kind:"scalar",T:9},{no:6,name:"device_model",kind:"scalar",T:9},{no:7,name:"browser",kind:"scalar",T:9},{no:8,name:"browser_version",kind:"scalar",T:9},{no:9,name:"address",kind:"scalar",T:9},{no:10,name:"network",kind:"scalar",T:9},{no:11,name:"other_sdks",kind:"scalar",T:9}]),xo=p.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),Lo=p.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:No},{no:2,name:"screen",kind:"message",T:No},{no:3,name:"resume_connection",kind:"enum",T:p.getEnumType(Un)},{no:4,name:"disabled_codecs",kind:"message",T:hm},{no:5,name:"force_relay",kind:"enum",T:p.getEnumType(Un)}]),No=p.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:p.getEnumType(Un)}]),hm=p.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Ci,repeated:!0},{no:2,name:"publish",kind:"message",T:Ci,repeated:!0}]),Uo=p.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Or=p.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Fo=p.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:p.getEnumType(Or)},{no:2,name:"version",kind:"scalar",T:5},{no:3,name:"reply_to_stream_id",kind:"scalar",T:9},{no:4,name:"attached_stream_ids",kind:"scalar",T:9,repeated:!0},{no:5,name:"generated",kind:"scalar",T:8}],{localName:"DataStream_TextHeader"}),Bo=p.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),wi=p.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:p.getEnumType(ke)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Fo,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Bo,oneof:"content_header"}],{localName:"DataStream_Header"}),_i=p.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),Ri=p.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),mm=p.makeMessageType("livekit.FilterParams",()=>[{no:1,name:"include_events",kind:"scalar",T:9,repeated:!0},{no:2,name:"exclude_events",kind:"scalar",T:9,repeated:!0}]),fm=p.makeMessageType("livekit.WebhookConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"signing_key",kind:"scalar",T:9},{no:3,name:"filter_params",kind:"message",T:mm}]),pm=p.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),Dr=p.makeMessageType("livekit.RoomAgentDispatch",()=>[{no:1,name:"agent_name",kind:"scalar",T:9},{no:2,name:"metadata",kind:"scalar",T:9}]),at=p.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ar=p.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),gm=p.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),vm=p.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:jt,oneof:"message"},{no:2,name:"answer",kind:"message",T:jt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Pi,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Fn,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ii,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Mi,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Wo,oneof:"message"},{no:8,name:"leave",kind:"message",T:Oi,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Jo,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:$o,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Br,oneof:"message"},{no:13,name:"simulate",kind:"message",T:vt,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:Ur,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Xo,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Nr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Ho,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:Vo,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Ko,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:wm,oneof:"message"}]),jo=p.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Tm,oneof:"message"},{no:2,name:"answer",kind:"message",T:jt,oneof:"message"},{no:3,name:"offer",kind:"message",T:jt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Pi,oneof:"message"},{no:5,name:"update",kind:"message",T:Em,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Lr,oneof:"message"},{no:8,name:"leave",kind:"message",T:Oi,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ii,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Rm,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Pm,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Mm,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Dm,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:xm,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Nm,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Cm,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Sm,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Fm,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Vm,oneof:"message"},{no:22,name:"request_response",kind:"message",T:qm,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Km,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Um,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Gm,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:Lm,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:qo,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:ym,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:bm,oneof:"message"}]),xr=p.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:Bt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:p.getEnumType(Eo)}]),Fn=p.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:p.getEnumType(Ye)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:p.getEnumType(_e)},{no:9,name:"layers",kind:"message",T:Bt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:xr,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:p.getEnumType(ke)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:p.getEnumType(So)},{no:17,name:"audio_features",kind:"enum",T:p.getEnumType(Me),repeated:!0}]),Vo=p.makeMessageType("livekit.PublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"encryption",kind:"enum",T:p.getEnumType(ke)}]),qo=p.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:_r}]),Ko=p.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),ym=p.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:_r}]),bm=p.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:km}}]),km=p.makeMessageType("livekit.DataTrackSubscriberHandles.PublishedDataTrack",()=>[{no:1,name:"publisher_identity",kind:"scalar",T:9},{no:2,name:"publisher_sid",kind:"scalar",T:9},{no:3,name:"track_sid",kind:"scalar",T:9}],{localName:"DataTrackSubscriberHandles_PublishedDataTrack"}),Pi=p.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:p.getEnumType(at)},{no:3,name:"final",kind:"scalar",T:8}]),Ii=p.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Tm=p.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Si},{no:2,name:"participant",kind:"message",T:Qt},{no:3,name:"other_participants",kind:"message",T:Qt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Go,repeated:!0},{no:6,name:"subscriber_primary",kind:"scalar",T:8},{no:7,name:"alternative_url",kind:"scalar",T:9},{no:8,name:"client_configuration",kind:"message",T:Lo},{no:9,name:"server_region",kind:"scalar",T:9},{no:10,name:"ping_timeout",kind:"scalar",T:5},{no:11,name:"ping_interval",kind:"scalar",T:5},{no:12,name:"server_info",kind:"message",T:Oo},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Ci,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Sm=p.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Go,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Lo},{no:3,name:"server_info",kind:"message",T:Oo},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Lr=p.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:pn}]),Cm=p.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),jt=p.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13},{no:4,name:"mid_to_track_id",kind:"map",K:9,V:{kind:"scalar",T:9}}]),Em=p.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Qt,repeated:!0}]),Mi=p.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:Mo,repeated:!0}]),wm=p.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:_m,repeated:!0}]),_m=p.makeMessageType("livekit.UpdateDataSubscription.Update",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"options",kind:"message",T:cm}],{localName:"UpdateDataSubscription_Update"}),Wo=p.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:p.getEnumType(wr)},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"fps",kind:"scalar",T:13},{no:8,name:"priority",kind:"scalar",T:13}]),Nr=p.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:p.getEnumType(Me),repeated:!0}]),Ho=p.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),Oi=p.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:p.getEnumType(Xe)},{no:3,name:"action",kind:"enum",T:p.getEnumType(gn)},{no:4,name:"regions",kind:"message",T:Bm}]),gn=p.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Jo=p.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Bt,repeated:!0}]),Ur=p.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Go=p.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Rm=p.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Ro,repeated:!0}]),Pm=p.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Si}]),Im=p.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:p.getEnumType(Nn)},{no:3,name:"score",kind:"scalar",T:2}]),Mm=p.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Im,repeated:!0}]),Om=p.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:p.getEnumType(Ar)}]),Dm=p.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Om,repeated:!0}]),Fr=p.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:p.getEnumType(wr)},{no:2,name:"enabled",kind:"scalar",T:8}]),Am=p.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Fr,repeated:!0}]),xm=p.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Fr,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Am,repeated:!0}]),Lm=p.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:pm,repeated:!0}]),zo=p.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),$o=p.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:zo,repeated:!0}]),Nm=p.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),Um=p.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Si},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Qt},{no:4,name:"other_participants",kind:"message",T:Qt,repeated:!0}]),Br=p.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:jt},{no:2,name:"subscription",kind:"message",T:Mi},{no:3,name:"publish_tracks",kind:"message",T:Lr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Yo,repeated:!0},{no:5,name:"offer",kind:"message",T:jt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:Qo,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:qo,repeated:!0}]),Qo=p.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Yo=p.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:p.getEnumType(at)}]),vt=p.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:p.getEnumType(gm),oneof:"scenario"},{no:6,name:"subscriber_bandwidth",kind:"scalar",T:3,oneof:"scenario"},{no:7,name:"disconnect_signal_on_resume",kind:"scalar",T:8,oneof:"scenario"},{no:8,name:"disconnect_signal_on_resume_no_messages",kind:"scalar",T:8,oneof:"scenario"},{no:9,name:"leave_request_full_reconnect",kind:"scalar",T:8,oneof:"scenario"}]),Xo=p.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Fm=p.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Bm=p.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:jm,repeated:!0}]),jm=p.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),Vm=p.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:p.getEnumType(Co)}]),qm=p.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:p.getEnumType(jr)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Pi,oneof:"request"},{no:5,name:"add_track",kind:"message",T:Fn,oneof:"request"},{no:6,name:"mute",kind:"message",T:Ii,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:Ur,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Nr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Ho,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:Vo,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Ko,oneof:"request"}]),jr=p.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),Km=p.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Zo=p.makeMessageType("livekit.ConnectionSettings",()=>[{no:1,name:"auto_subscribe",kind:"scalar",T:8},{no:2,name:"adaptive_stream",kind:"scalar",T:8},{no:3,name:"subscriber_allow_pause",kind:"scalar",T:8,opt:!0},{no:4,name:"disable_ice_lite",kind:"scalar",T:8},{no:5,name:"auto_subscribe_data_track",kind:"scalar",T:8,opt:!0}]),Wm=p.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Ao},{no:2,name:"connection_settings",kind:"message",T:Zo},{no:3,name:"metadata",kind:"scalar",T:9},{no:4,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:5,name:"add_track_requests",kind:"message",T:Fn,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:jt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:p.getEnumType($t)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Br}]),Hm=p.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:p.getEnumType(Jm)},{no:2,name:"join_request",kind:"scalar",T:12}]),Jm=p.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Gm=p.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]),zm=p.makeEnum("livekit.EncodedFileType",[{no:0,name:"DEFAULT_FILETYPE"},{no:1,name:"MP4"},{no:2,name:"OGG"},{no:3,name:"MP3"}]),$m=p.makeEnum("livekit.SegmentedFileProtocol",[{no:0,name:"DEFAULT_SEGMENTED_FILE_PROTOCOL"},{no:1,name:"HLS_PROTOCOL"}]),Qm=p.makeEnum("livekit.SegmentedFileSuffix",[{no:0,name:"INDEX"},{no:1,name:"TIMESTAMP"}]),Ym=p.makeEnum("livekit.ImageFileSuffix",[{no:0,name:"IMAGE_SUFFIX_INDEX"},{no:1,name:"IMAGE_SUFFIX_TIMESTAMP"},{no:2,name:"IMAGE_SUFFIX_NONE_OVERWRITE"}]),Xm=p.makeEnum("livekit.StreamProtocol",[{no:0,name:"DEFAULT_PROTOCOL"},{no:1,name:"RTMP"},{no:2,name:"SRT"}]),Zm=p.makeEnum("livekit.AudioMixing",[{no:0,name:"DEFAULT_MIXING"},{no:1,name:"DUAL_CHANNEL_AGENT"},{no:2,name:"DUAL_CHANNEL_ALTERNATE"}]),ec=p.makeEnum("livekit.EncodingOptionsPreset",[{no:0,name:"H264_720P_30"},{no:1,name:"H264_720P_60"},{no:2,name:"H264_1080P_30"},{no:3,name:"H264_1080P_60"},{no:4,name:"PORTRAIT_H264_720P_30"},{no:5,name:"PORTRAIT_H264_720P_60"},{no:6,name:"PORTRAIT_H264_1080P_30"},{no:7,name:"PORTRAIT_H264_1080P_60"}]),ef=p.makeMessageType("livekit.RoomCompositeEgressRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9},{no:2,name:"layout",kind:"scalar",T:9},{no:3,name:"audio_only",kind:"scalar",T:8},{no:15,name:"audio_mixing",kind:"enum",T:p.getEnumType(Zm)},{no:4,name:"video_only",kind:"scalar",T:8},{no:5,name:"custom_base_url",kind:"scalar",T:9},{no:6,name:"file",kind:"message",T:Vr,oneof:"output"},{no:7,name:"stream",kind:"message",T:nc,oneof:"output"},{no:10,name:"segments",kind:"message",T:qr,oneof:"output"},{no:8,name:"preset",kind:"enum",T:p.getEnumType(ec),oneof:"options"},{no:9,name:"advanced",kind:"message",T:ic,oneof:"options"},{no:11,name:"file_outputs",kind:"message",T:Vr,repeated:!0},{no:12,name:"stream_outputs",kind:"message",T:nc,repeated:!0},{no:13,name:"segment_outputs",kind:"message",T:qr,repeated:!0},{no:14,name:"image_outputs",kind:"message",T:tf,repeated:!0},{no:16,name:"webhooks",kind:"message",T:fm,repeated:!0}]),Vr=p.makeMessageType("livekit.EncodedFileOutput",()=>[{no:1,name:"file_type",kind:"enum",T:p.getEnumType(zm)},{no:2,name:"filepath",kind:"scalar",T:9},{no:6,name:"disable_manifest",kind:"scalar",T:8},{no:3,name:"s3",kind:"message",T:Di,oneof:"output"},{no:4,name:"gcp",kind:"message",T:Ai,oneof:"output"},{no:5,name:"azure",kind:"message",T:xi,oneof:"output"},{no:7,name:"aliOSS",kind:"message",T:Li,oneof:"output"}]),qr=p.makeMessageType("livekit.SegmentedFileOutput",()=>[{no:1,name:"protocol",kind:"enum",T:p.getEnumType($m)},{no:2,name:"filename_prefix",kind:"scalar",T:9},{no:3,name:"playlist_name",kind:"scalar",T:9},{no:11,name:"live_playlist_name",kind:"scalar",T:9},{no:4,name:"segment_duration",kind:"scalar",T:13},{no:10,name:"filename_suffix",kind:"enum",T:p.getEnumType(Qm)},{no:8,name:"disable_manifest",kind:"scalar",T:8},{no:5,name:"s3",kind:"message",T:Di,oneof:"output"},{no:6,name:"gcp",kind:"message",T:Ai,oneof:"output"},{no:7,name:"azure",kind:"message",T:xi,oneof:"output"},{no:9,name:"aliOSS",kind:"message",T:Li,oneof:"output"}]),tf=p.makeMessageType("livekit.ImageOutput",()=>[{no:1,name:"capture_interval",kind:"scalar",T:13},{no:2,name:"width",kind:"scalar",T:5},{no:3,name:"height",kind:"scalar",T:5},{no:4,name:"filename_prefix",kind:"scalar",T:9},{no:5,name:"filename_suffix",kind:"enum",T:p.getEnumType(Ym)},{no:6,name:"image_codec",kind:"enum",T:p.getEnumType(rm)},{no:7,name:"disable_manifest",kind:"scalar",T:8},{no:8,name:"s3",kind:"message",T:Di,oneof:"output"},{no:9,name:"gcp",kind:"message",T:Ai,oneof:"output"},{no:10,name:"azure",kind:"message",T:xi,oneof:"output"},{no:11,name:"aliOSS",kind:"message",T:Li,oneof:"output"}]),Di=p.makeMessageType("livekit.S3Upload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:11,name:"session_token",kind:"scalar",T:9},{no:12,name:"assume_role_arn",kind:"scalar",T:9},{no:13,name:"assume_role_external_id",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9},{no:6,name:"force_path_style",kind:"scalar",T:8},{no:7,name:"metadata",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:8,name:"tagging",kind:"scalar",T:9},{no:9,name:"content_disposition",kind:"scalar",T:9},{no:10,name:"proxy",kind:"message",T:tc}]),Ai=p.makeMessageType("livekit.GCPUpload",()=>[{no:1,name:"credentials",kind:"scalar",T:9},{no:2,name:"bucket",kind:"scalar",T:9},{no:3,name:"proxy",kind:"message",T:tc}]),xi=p.makeMessageType("livekit.AzureBlobUpload",()=>[{no:1,name:"account_name",kind:"scalar",T:9},{no:2,name:"account_key",kind:"scalar",T:9},{no:3,name:"container_name",kind:"scalar",T:9}]),Li=p.makeMessageType("livekit.AliOSSUpload",()=>[{no:1,name:"access_key",kind:"scalar",T:9},{no:2,name:"secret",kind:"scalar",T:9},{no:3,name:"region",kind:"scalar",T:9},{no:4,name:"endpoint",kind:"scalar",T:9},{no:5,name:"bucket",kind:"scalar",T:9}]),tc=p.makeMessageType("livekit.ProxyConfig",()=>[{no:1,name:"url",kind:"scalar",T:9},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"password",kind:"scalar",T:9}]),nc=p.makeMessageType("livekit.StreamOutput",()=>[{no:1,name:"protocol",kind:"enum",T:p.getEnumType(Xm)},{no:2,name:"urls",kind:"scalar",T:9,repeated:!0}]),ic=p.makeMessageType("livekit.EncodingOptions",()=>[{no:1,name:"width",kind:"scalar",T:5},{no:2,name:"height",kind:"scalar",T:5},{no:3,name:"depth",kind:"scalar",T:5},{no:4,name:"framerate",kind:"scalar",T:5},{no:5,name:"audio_codec",kind:"enum",T:p.getEnumType(nm)},{no:6,name:"audio_bitrate",kind:"scalar",T:5},{no:11,name:"audio_quality",kind:"scalar",T:5},{no:7,name:"audio_frequency",kind:"scalar",T:5},{no:8,name:"video_codec",kind:"enum",T:p.getEnumType(im)},{no:9,name:"video_bitrate",kind:"scalar",T:5},{no:12,name:"video_quality",kind:"scalar",T:5},{no:10,name:"key_frame_interval",kind:"scalar",T:1}]),nf=p.makeMessageType("livekit.AutoParticipantEgress",()=>[{no:1,name:"preset",kind:"enum",T:p.getEnumType(ec),oneof:"options"},{no:2,name:"advanced",kind:"message",T:ic,oneof:"options"},{no:3,name:"file_outputs",kind:"message",T:Vr,repeated:!0},{no:4,name:"segment_outputs",kind:"message",T:qr,repeated:!0}]),rf=p.makeMessageType("livekit.AutoTrackEgress",()=>[{no:1,name:"filepath",kind:"scalar",T:9},{no:5,name:"disable_manifest",kind:"scalar",T:8},{no:2,name:"s3",kind:"message",T:Di,oneof:"output"},{no:3,name:"gcp",kind:"message",T:Ai,oneof:"output"},{no:4,name:"azure",kind:"message",T:xi,oneof:"output"},{no:6,name:"aliOSS",kind:"message",T:Li,oneof:"output"}]),sf=p.makeMessageType("livekit.RoomEgress",()=>[{no:1,name:"room",kind:"message",T:ef},{no:3,name:"participant",kind:"message",T:nf},{no:2,name:"tracks",kind:"message",T:rf}]),Ni=p.makeMessageType("livekit.RoomConfiguration",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"empty_timeout",kind:"scalar",T:13},{no:3,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:11,name:"metadata",kind:"scalar",T:9},{no:5,name:"egress",kind:"message",T:sf},{no:7,name:"min_playout_delay",kind:"scalar",T:13},{no:8,name:"max_playout_delay",kind:"scalar",T:13},{no:9,name:"sync_streams",kind:"scalar",T:8},{no:10,name:"agents",kind:"message",T:Dr,repeated:!0}]),af=p.makeMessageType("livekit.TokenSourceRequest",()=>[{no:1,name:"room_name",kind:"scalar",T:9,opt:!0},{no:2,name:"participant_name",kind:"scalar",T:9,opt:!0},{no:3,name:"participant_identity",kind:"scalar",T:9,opt:!0},{no:4,name:"participant_metadata",kind:"scalar",T:9,opt:!0},{no:5,name:"participant_attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:6,name:"room_config",kind:"message",T:Ni,opt:!0}]),rc=p.makeMessageType("livekit.TokenSourceResponse",()=>[{no:1,name:"server_url",kind:"scalar",T:9},{no:2,name:"participant_token",kind:"scalar",T:9}]);function of(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Ui={exports:{}},cf=Ui.exports,sc;function df(){return sc||(sc=1,(function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(cf,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},o=null;function a(g,S){var k=g[S];if(typeof k.bind=="function")return k.bind(g);try{return Function.prototype.bind.call(k,g)}catch{return function(){return Function.prototype.apply.apply(k,[g,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function d(g){return g==="debug"&&(g="log"),typeof console===t?!1:g==="trace"&&i?c:console[g]!==void 0?a(console,g):console.log!==void 0?a(console,"log"):e}function l(){for(var g=this.getLevel(),S=0;S<r.length;S++){var k=r[S];this[k]=S<g?e:this.methodFactory(k,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,S,k){return d(g)||u.apply(this,arguments)}function m(g,S){var k=this,_,P,y,b="loglevel";typeof g=="string"?b+=":"+g:typeof g=="symbol"&&(b=void 0);function T(N){var W=(r[N]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=W;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+W+";"}catch{}}}function L(){var N;if(!(typeof window===t||!b)){try{N=window.localStorage[b]}catch{}if(typeof N===t)try{var W=window.document.cookie,ee=encodeURIComponent(b),Se=W.indexOf(ee+"=");Se!==-1&&(N=/^([^;]+)/.exec(W.slice(Se+ee.length+1))[1])}catch{}return k.levels[N]===void 0&&(N=void 0),N}}function B(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b)}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function I(N){var W=N;if(typeof W=="string"&&k.levels[W.toUpperCase()]!==void 0&&(W=k.levels[W.toUpperCase()]),typeof W=="number"&&W>=0&&W<=k.levels.SILENT)return W;throw new TypeError("log.setLevel() called with invalid level: "+N)}k.name=g,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=S||h,k.getLevel=function(){return y??P??_},k.setLevel=function(N,W){return y=I(N),W!==!1&&T(y),l.call(k)},k.setDefaultLevel=function(N){P=I(N),L()||k.setLevel(N,!1)},k.resetLevel=function(){y=null,B(),l.call(k)},k.enableAll=function(N){k.setLevel(k.levels.TRACE,N)},k.disableAll=function(N){k.setLevel(k.levels.SILENT,N)},k.rebuild=function(){if(o!==k&&(_=I(o.getLevel())),l.call(k),o===k)for(var N in s)s[N].rebuild()},_=I(o?o.getLevel():"WARN");var U=L();U!=null&&(y=I(U)),l.call(k)}o=new m,o.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var k=s[S];return k||(k=s[S]=new m(S,o.methodFactory)),k};var v=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return s},o.default=o,o})})(Ui)),Ui.exports}var Bn=df(),vn;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(vn||(vn={}));var $e;(function(n){n.Default="livekit",n.Room="livekit-room",n.TokenSource="livekit-token-source",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee",n.DataTracks="livekit-data-tracks"})($e||($e={}));let z=Bn.getLogger("livekit");const ac=Object.values($e).map(n=>Bn.getLogger(n));z.setDefaultLevel(vn.info);function ot(n){const e=Bn.getLogger(n);return e.setDefaultLevel(z.getLevel()),e}function lf(n,e){if(e)Bn.getLogger(e).setLevel(n);else for(const t of ac)t.setLevel(n)}function uf(n,e){(e?[e]:ac).forEach(i=>{const r=i.methodFactory;i.methodFactory=(s,o,a)=>{const c=r(s,o,a),d=vn[s],l=d>=o&&d<vn.silent;return(u,h)=>{h?c(u,h):c(u),l&&n(d,u,h)}},i.setLevel(i.getLevel())})}const hf=Bn.getLogger("lk-e2ee"),jn=7e3,mf=[0,300,4*300,9*300,16*300,jn,jn,jn,jn,jn];class oc{constructor(e){this._retryDelays=e!==void 0?[...e]:mf}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Kr(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,i=Object.getOwnPropertySymbols(n);r<i.length;r++)e.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(n,i[r])&&(t[i[r]]=n[i[r]]);return t}function f(n,e,t,i){function r(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(l){try{d(i.next(l))}catch(u){o(u)}}function c(l){try{d(i.throw(l))}catch(u){o(u)}}function d(l){l.done?s(l.value):r(l.value).then(a,c)}d((i=i.apply(n,e||[])).next())})}function cc(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Rt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof cc=="function"?cc(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(s){t[s]=n[s]&&function(o){return new Promise(function(a,c){o=n[s](o),r(a,c,o.done,o.value)})}}function r(s,o,a,c){Promise.resolve(c).then(function(d){s({value:d,done:a})},o)}}typeof SuppressedError=="function"&&SuppressedError;var Fi={exports:{}},dc;function ff(){if(dc)return Fi.exports;dc=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(b,T,L){return Function.prototype.apply.call(b,T,L)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(b){return Object.getOwnPropertyNames(b).concat(Object.getOwnPropertySymbols(b))}:t=function(b){return Object.getOwnPropertyNames(b)};function i(y){console&&console.warn&&console.warn(y)}var r=Number.isNaN||function(b){return b!==b};function s(){s.init.call(this)}Fi.exports=s,Fi.exports.once=k,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(y){if(typeof y!="number"||y<0||r(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");o=y}}),s.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+b+".");return this._maxListeners=b,this};function c(y){return y._maxListeners===void 0?s.defaultMaxListeners:y._maxListeners}s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(b){for(var T=[],L=1;L<arguments.length;L++)T.push(arguments[L]);var B=b==="error",I=this._events;if(I!==void 0)B=B&&I.error===void 0;else if(!B)return!1;if(B){var U;if(T.length>0&&(U=T[0]),U instanceof Error)throw U;var N=new Error("Unhandled error."+(U?" ("+U.message+")":""));throw N.context=U,N}var W=I[b];if(W===void 0)return!1;if(typeof W=="function")e(W,this,T);else for(var ee=W.length,Se=v(W,ee),L=0;L<ee;++L)e(Se[L],this,T);return!0};function d(y,b,T,L){var B,I,U;if(a(T),I=y._events,I===void 0?(I=y._events=Object.create(null),y._eventsCount=0):(I.newListener!==void 0&&(y.emit("newListener",b,T.listener?T.listener:T),I=y._events),U=I[b]),U===void 0)U=I[b]=T,++y._eventsCount;else if(typeof U=="function"?U=I[b]=L?[T,U]:[U,T]:L?U.unshift(T):U.push(T),B=c(y),B>0&&U.length>B&&!U.warned){U.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+U.length+" "+String(b)+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=y,N.type=b,N.count=U.length,i(N)}return y}s.prototype.addListener=function(b,T){return d(this,b,T,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(b,T){return d(this,b,T,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,b,T){var L={fired:!1,wrapFn:void 0,target:y,type:b,listener:T},B=l.bind(L);return B.listener=T,L.wrapFn=B,B}s.prototype.once=function(b,T){return a(T),this.on(b,u(this,b,T)),this},s.prototype.prependOnceListener=function(b,T){return a(T),this.prependListener(b,u(this,b,T)),this},s.prototype.removeListener=function(b,T){var L,B,I,U,N;if(a(T),B=this._events,B===void 0)return this;if(L=B[b],L===void 0)return this;if(L===T||L.listener===T)--this._eventsCount===0?this._events=Object.create(null):(delete B[b],B.removeListener&&this.emit("removeListener",b,L.listener||T));else if(typeof L!="function"){for(I=-1,U=L.length-1;U>=0;U--)if(L[U]===T||L[U].listener===T){N=L[U].listener,I=U;break}if(I<0)return this;I===0?L.shift():g(L,I),L.length===1&&(B[b]=L[0]),B.removeListener!==void 0&&this.emit("removeListener",b,N||T)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(b){var T,L,B;if(L=this._events,L===void 0)return this;if(L.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):L[b]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete L[b]),this;if(arguments.length===0){var I=Object.keys(L),U;for(B=0;B<I.length;++B)U=I[B],U!=="removeListener"&&this.removeAllListeners(U);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(T=L[b],typeof T=="function")this.removeListener(b,T);else if(T!==void 0)for(B=T.length-1;B>=0;B--)this.removeListener(b,T[B]);return this};function h(y,b,T){var L=y._events;if(L===void 0)return[];var B=L[b];return B===void 0?[]:typeof B=="function"?T?[B.listener||B]:[B]:T?S(B):v(B,B.length)}s.prototype.listeners=function(b){return h(this,b,!0)},s.prototype.rawListeners=function(b){return h(this,b,!1)},s.listenerCount=function(y,b){return typeof y.listenerCount=="function"?y.listenerCount(b):m.call(y,b)},s.prototype.listenerCount=m;function m(y){var b=this._events;if(b!==void 0){var T=b[y];if(typeof T=="function")return 1;if(T!==void 0)return T.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function v(y,b){for(var T=new Array(b),L=0;L<b;++L)T[L]=y[L];return T}function g(y,b){for(;b+1<y.length;b++)y[b]=y[b+1];y.pop()}function S(y){for(var b=new Array(y.length),T=0;T<b.length;++T)b[T]=y[T].listener||y[T];return b}function k(y,b){return new Promise(function(T,L){function B(U){y.removeListener(b,I),L(U)}function I(){typeof y.removeListener=="function"&&y.removeListener("error",B),T([].slice.call(arguments))}P(y,b,I,{once:!0}),b!=="error"&&_(y,B,{once:!0})})}function _(y,b,T){typeof y.on=="function"&&P(y,"error",b,T)}function P(y,b,T,L){if(typeof y.on=="function")L.once?y.once(b,T):y.on(b,T);else if(typeof y.addEventListener=="function")y.addEventListener(b,function B(I){L.once&&y.removeEventListener(b,B),T(I)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return Fi.exports}var yt=ff();let lc=!0,uc=!0;function Vn(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseFloat(i[t],10)}function Yt(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(o,a){if(o!==e)return r.apply(this,arguments);const c=d=>{const l=t(d);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),r.apply(this,[o,c])};const s=i.removeEventListener;i.removeEventListener=function(o,a){if(o!==e||!this._eventMap||!this._eventMap[e])return s.apply(this,arguments);if(!this._eventMap[e].has(a))return s.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,s.apply(this,[o,c])},Object.defineProperty(i,"on"+e,{get(){return this["_on"+e]},set(o){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),o&&this.addEventListener(e,this["_on"+e]=o)},enumerable:!0,configurable:!0})}function pf(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(lc=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function gf(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(uc=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function hc(){if(typeof window=="object"){if(lc)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Wr(n,e){uc&&console.warn(n+" is deprecated, please use "+e+" instead.")}function vf(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Vn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Vn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Vn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype,e._safariVersion=Vn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function mc(n){return Object.prototype.toString.call(n)==="[object Object]"}function fc(n){return mc(n)?Object.keys(n).reduce(function(e,t){const i=mc(n[t]),r=i?fc(n[t]):n[t],s=i&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):n}function Hr(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Hr(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(r=>{Hr(n,n.get(r),t)})}))}function pc(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const s=[];return n.forEach(o=>{o.type==="track"&&o.trackIdentifier===e.id&&s.push(o)}),s.forEach(o=>{n.forEach(a=>{a.type===i&&a.trackId===o.id&&Hr(n,a,r)})}),r}const gc=hc;function vc(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(a){if(typeof a!="object"||a.mandatory||a.optional)return a;const c={};return Object.keys(a).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof a[d]=="object"?a[d]:{ideal:a[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,m){return h?h+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[h])})}),a.advanced&&(c.optional=(c.optional||[]).concat(a.advanced)),c},r=function(a,c){if(e.version>=61)return c(a);if(a=JSON.parse(JSON.stringify(a)),a&&typeof a.audio=="object"){const d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};a=JSON.parse(JSON.stringify(a)),d(a.audio,"autoGainControl","googAutoGainControl"),d(a.audio,"noiseSuppression","googNoiseSuppression"),a.audio=i(a.audio)}if(a&&typeof a.video=="object"){let d=a.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete a.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(v=>v.kind==="videoinput");let m=h.find(v=>u.some(g=>v.label.toLowerCase().includes(g)));return!m&&h.length&&u.includes("back")&&(m=h[h.length-1]),m&&(a.video.deviceId=d.exact?{exact:m.deviceId}:{ideal:m.deviceId}),a.video=i(a.video),gc("chrome: "+JSON.stringify(a)),c(a)})}a.video=i(a.video)}return gc("chrome: "+JSON.stringify(a)),c(a)},s=function(a){return e.version>=64?a:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[a.name]||a.name,message:a.message,constraint:a.constraint||a.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}},o=function(a,c,d){r(a,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(s(u))})})};if(t.getUserMedia=o.bind(t),t.mediaDevices.getUserMedia){const a=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return r(c,d=>a(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(s(l))))}}}function yc(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function bc(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",r=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.track.id):s={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(r=>{let s;n.RTCPeerConnection.prototype.getReceivers?s=this.getReceivers().find(a=>a.track&&a.track.id===r.id):s={track:r};const o=new Event("track");o.track=r,o.receiver=s,o.transceiver={receiver:s},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Yt(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function kc(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,c){let d=r.apply(this,arguments);return d||(d=e(this,a),this._senders.push(d)),d};const s=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(a){s.apply(this,arguments);const c=this._senders.indexOf(a);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],i.apply(this,[s]),s.getTracks().forEach(o=>{const a=this._senders.find(c=>c.track===o);a&&this._senders.splice(this._senders.indexOf(a),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Tc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=t.apply(this,[]);return s.forEach(o=>o._pc=this),s});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=i.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){const s=this;return this._pc.getStats().then(o=>pc(o,s.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const r=t.apply(this,[]);return r.forEach(s=>s._pc=this),r}),Yt(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>pc(s,r.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let r,s,o;return this.getSenders().forEach(a=>{a.track===i&&(r?o=!0:r=a)}),this.getReceivers().forEach(a=>(a.track===i&&(s?o=!0:s=a),a.track===i)),o||r&&s?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():s?s.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Sc(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,a){if(!a)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const c=e.apply(this,arguments);return this._shimmedLocalStreams[a.id]?this._shimmedLocalStreams[a.id].indexOf(c)===-1&&this._shimmedLocalStreams[a.id].push(c):this._shimmedLocalStreams[a.id]=[a,c],c};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const a=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>a.indexOf(d)===-1);this._shimmedLocalStreams[o.id]=[o].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],i.apply(this,arguments)};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(a=>{const c=this._shimmedLocalStreams[a].indexOf(o);c!==-1&&this._shimmedLocalStreams[a].splice(c,1),this._shimmedLocalStreams[a].length===1&&delete this._shimmedLocalStreams[a]}),r.apply(this,arguments)}}function Cc(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Sc(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(m=>m.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const r=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const v=this._streams[u.id];if(v)v.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new n.MediaStream([l]);this._streams[u.id]=g,this._reverseStreams[g.id]=u,this.addStream(g)}return this.getSenders().find(g=>g.track===l)};function s(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const m=d._reverseStreams[h],v=d._streams[m.id];u=u.replace(new RegExp(v.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function o(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const m=d._reverseStreams[h],v=d._streams[m.id];u=u.replace(new RegExp(m.id,"g"),v.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[v=>{const g=s(this,v);h[0].apply(null,[g])},v=>{h[1]&&h[1].apply(null,v)},arguments[2]]):l.apply(this,arguments).then(v=>s(this,v))}};n.RTCPeerConnection.prototype[d]=u[d]});const a=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?a.apply(this,arguments):(arguments[0]=o(this,arguments[0]),a.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:s(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(m=>{this._streams[m].getTracks().find(g=>l.track===g)&&(h=this._streams[m])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Jr(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=r[t]})}function Ec(n,e){Yt(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var wc=Object.freeze({__proto__:null,fixNegotiationNeeded:Ec,shimAddTrackRemoveTrack:Cc,shimAddTrackRemoveTrackWithNative:Sc,shimGetSendersWithDtmf:kc,shimGetUserMedia:vc,shimMediaStream:yc,shimOnTrack:bc,shimPeerConnection:Jr,shimSenderReceiverGetStats:Tc});function _c(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(r,s,o){Wr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,o)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const r=function(o,a,c){a in o&&!(c in o)&&(o[c]=o[a],delete o[a])},s=t.mediaDevices.getUserMedia.bind(t.mediaDevices);if(t.mediaDevices.getUserMedia=function(o){return typeof o=="object"&&typeof o.audio=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o.audio,"autoGainControl","mozAutoGainControl"),r(o.audio,"noiseSuppression","mozNoiseSuppression")),s(o)},i&&i.prototype.getSettings){const o=i.prototype.getSettings;i.prototype.getSettings=function(){const a=o.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(i&&i.prototype.applyConstraints){const o=i.prototype.applyConstraints;i.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),o.apply(this,[a])}}}}function yf(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Rc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Gr(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const s=n.RTCPeerConnection.prototype[r],o={[r](){return arguments[0]=new(r==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),s.apply(this,arguments)}};n.RTCPeerConnection.prototype[r]=o[r]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[s,o,a]=arguments;return i.apply(this,[s||null]).then(c=>{if(e.version<53&&!o)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(o,a)}}function Pc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ic(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i}),Yt(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Mc(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){Wr("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Oc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Dc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const r=i.length>0;r&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const s=e.apply(this,arguments);if(r){const{sender:o}=s,a=o.getParameters();(!("encodings"in a)||a.encodings.length===1&&Object.keys(a.encodings[0]).length===0)&&(a.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(a).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return s})}function Ac(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function xc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Lc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Nc=Object.freeze({__proto__:null,shimAddTransceiver:Dc,shimCreateAnswer:Lc,shimCreateOffer:xc,shimGetDisplayMedia:yf,shimGetParameters:Ac,shimGetUserMedia:_c,shimOnTrack:Rc,shimPeerConnection:Gr,shimRTCDataChannel:Oc,shimReceiverGetStats:Ic,shimRemoveStream:Mc,shimSenderGetStats:Pc});function Uc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},n.RTCPeerConnection.prototype.addTrack=function(i){for(var r=arguments.length,s=new Array(r>1?r-1:0),o=1;o<r;o++)s[o-1]=arguments[o];return s&&s.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function Fc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(s)>=0)return;i._remoteStreams.push(s);const o=new Event("addstream");o.stream=s,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function Bc(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,o=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let a=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=a,a=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=a,a=function(c,d,l){const u=o.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=a}function jc(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>i(Vc(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,r,s){e.mediaDevices.getUserMedia(i).then(r,s)}).bind(e))}function Vc(n){return n&&n.video!==void 0?Object.assign({},n,{video:fc(n.video)}):n}function qc(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,r){if(i&&i.iceServers){const s=[];for(let o=0;o<i.iceServers.length;o++){let a=i.iceServers[o];a.urls===void 0&&a.url?(Wr("RTCIceServer.url","RTCIceServer.urls"),a=JSON.parse(JSON.stringify(a)),a.urls=a.url,delete a.url,s.push(a)):s.push(i.iceServers[o])}i.iceServers=s}return new e(i,r)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Kc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Wc(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const s=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):i.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Hc(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Jc=Object.freeze({__proto__:null,shimAudioContext:Hc,shimCallbacksAPI:Bc,shimConstraints:Vc,shimCreateOfferLegacy:Wc,shimGetUserMedia:jc,shimLocalStreamsAPI:Uc,shimRTCIceServerUrls:qc,shimRemoteStreamsAPI:Fc,shimTrackEventTransceiver:Kc}),zr={exports:{}},Gc;function bf(){return Gc||(Gc=1,(function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
3
3
  `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
4
4
  m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
@@ -1,4 +1,4 @@
1
- import { c as Ue, C as z, S as f, a as Oe, b as je, A as g, d as Ne, l as le, e as ze, t as Be, f as A, g as O, h as Je, i as Qe, j as R, n as We } from "./index-Gnq_YadB.js";
1
+ import { c as Ue, C as z, S as f, a as Oe, b as je, A as g, d as Ne, l as le, e as ze, t as Be, f as A, g as O, h as Je, i as Qe, j as R, n as We } from "./index-Mm1kFqJw.js";
2
2
  function qe() {
3
3
  try {
4
4
  return Intl.DateTimeFormat().resolvedOptions().timeZone ?? "";
@@ -147,7 +147,18 @@ export interface AgentManagerOptions {
147
147
  wsURL?: string;
148
148
  debug?: boolean;
149
149
  verbose?: boolean;
150
+ /**
151
+ * Whether to enable analytics (Mixpanel) tracking.
152
+ * @default true
153
+ * @deprecated Use `enableAnalytics` instead. This misspelled prop is kept for backwards compatibility.
154
+ */
150
155
  enableAnalitics?: boolean;
156
+ /**
157
+ * Whether to enable analytics (Mixpanel) tracking.
158
+ * Takes precedence over the deprecated `enableAnalitics` prop when both are set.
159
+ * @default true
160
+ */
161
+ enableAnalytics?: boolean;
151
162
  mixpanelKey?: string;
152
163
  mixpanelAdditionalProperties?: Record<string, any>;
153
164
  externalId?: string;
@@ -28,10 +28,16 @@ export interface Stream_Text_Script extends BaseStreamScript {
28
28
  */
29
29
  ssml?: boolean;
30
30
  /**
31
- * Queue this speak behind the current speech instead of interrupting it.
31
+ * Queue this speak behind the current speech instead of interrupting it (expressive avatars only).
32
32
  * @default false
33
33
  */
34
34
  should_queue_speaks?: boolean;
35
+ /**
36
+ * Sentiment name to speak with (expressive avatars only).
37
+ * If the sentiment is not supported by the agent, the default sentiment is used.
38
+ * @example "friendly"
39
+ */
40
+ sentiment?: string;
35
41
  }
36
42
  export interface Stream_Audio_Script extends BaseStreamScript {
37
43
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@d-id/client-sdk",
3
3
  "private": false,
4
- "version": "1.2.9",
4
+ "version": "1.2.10-staging.374",
5
5
  "type": "module",
6
6
  "description": "d-id client sdk",
7
7
  "repository": {