pinecall 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +17 -9
  2. package/dist/agent/agent.d.ts +9 -38
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/agent.js +17 -18
  5. package/dist/agent/agent.js.map +1 -1
  6. package/dist/agent/knowledge.d.ts +9 -0
  7. package/dist/agent/knowledge.d.ts.map +1 -0
  8. package/dist/agent/knowledge.js +3 -0
  9. package/dist/agent/knowledge.js.map +1 -0
  10. package/dist/agent/searching.d.ts +8 -0
  11. package/dist/agent/searching.d.ts.map +1 -0
  12. package/dist/agent/searching.js +38 -0
  13. package/dist/agent/searching.js.map +1 -0
  14. package/dist/call/call.d.ts +20 -1
  15. package/dist/call/call.d.ts.map +1 -1
  16. package/dist/call/call.js +15 -1
  17. package/dist/call/call.js.map +1 -1
  18. package/dist/cli/agent-knowledge.d.ts +19 -0
  19. package/dist/cli/agent-knowledge.d.ts.map +1 -0
  20. package/dist/cli/agent-knowledge.js +84 -0
  21. package/dist/cli/agent-knowledge.js.map +1 -0
  22. package/dist/cli/agent-lines.d.ts +1 -1
  23. package/dist/cli/agent-lines.d.ts.map +1 -1
  24. package/dist/cli/agent-lines.js +8 -3
  25. package/dist/cli/agent-lines.js.map +1 -1
  26. package/dist/cli/agent-processes.js +1 -1
  27. package/dist/cli/agent-processes.js.map +1 -1
  28. package/dist/cli/agent.d.ts +3 -0
  29. package/dist/cli/agent.d.ts.map +1 -1
  30. package/dist/cli/agent.js +12 -3
  31. package/dist/cli/agent.js.map +1 -1
  32. package/dist/cli/docs-attach.d.ts +23 -0
  33. package/dist/cli/docs-attach.d.ts.map +1 -0
  34. package/dist/cli/docs-attach.js +87 -0
  35. package/dist/cli/docs-attach.js.map +1 -0
  36. package/dist/cli/{knowledge.d.ts → docs.d.ts} +2 -4
  37. package/dist/cli/docs.d.ts.map +1 -0
  38. package/dist/cli/{knowledge.js → docs.js} +69 -36
  39. package/dist/cli/docs.js.map +1 -0
  40. package/dist/cli/groups.js +1 -1
  41. package/dist/cli/groups.js.map +1 -1
  42. package/dist/cli/home.d.ts +23 -18
  43. package/dist/cli/home.d.ts.map +1 -1
  44. package/dist/cli/home.js +21 -30
  45. package/dist/cli/home.js.map +1 -1
  46. package/dist/cli/index.d.ts.map +1 -1
  47. package/dist/cli/index.js +9 -8
  48. package/dist/cli/index.js.map +1 -1
  49. package/dist/cli/lexicon.js +1 -1
  50. package/dist/cli/lexicon.js.map +1 -1
  51. package/dist/cli/load.d.ts +5 -5
  52. package/dist/cli/load.d.ts.map +1 -1
  53. package/dist/cli/load.js +19 -26
  54. package/dist/cli/load.js.map +1 -1
  55. package/dist/cli/memory-policy.js +1 -1
  56. package/dist/cli/memory-policy.js.map +1 -1
  57. package/dist/cli/memory.d.ts +0 -1
  58. package/dist/cli/memory.d.ts.map +1 -1
  59. package/dist/cli/memory.js +1 -4
  60. package/dist/cli/memory.js.map +1 -1
  61. package/dist/cli/pipeline.d.ts +3 -13
  62. package/dist/cli/pipeline.d.ts.map +1 -1
  63. package/dist/cli/pipeline.js +10 -16
  64. package/dist/cli/pipeline.js.map +1 -1
  65. package/dist/cli/remember.d.ts +2 -2
  66. package/dist/cli/remember.d.ts.map +1 -1
  67. package/dist/cli/remember.js +1 -1
  68. package/dist/cli/remember.js.map +1 -1
  69. package/dist/cli/start.d.ts.map +1 -1
  70. package/dist/cli/start.js +3 -6
  71. package/dist/cli/start.js.map +1 -1
  72. package/dist/cli/test.js +1 -1
  73. package/dist/cli/test.js.map +1 -1
  74. package/dist/cli/testing/goldens.d.ts.map +1 -1
  75. package/dist/cli/testing/goldens.js +7 -1
  76. package/dist/cli/testing/goldens.js.map +1 -1
  77. package/dist/cli/testing/models.d.ts +5 -0
  78. package/dist/cli/testing/models.d.ts.map +1 -0
  79. package/dist/cli/testing/models.js +18 -0
  80. package/dist/cli/testing/models.js.map +1 -0
  81. package/dist/cli/ui/console/assets/{index-aGyMCQUH.js → index-CZCFF8Yh.js} +13 -13
  82. package/dist/cli/ui/console/assets/{index-DmN15Axn.css → index-gPwW4dvS.css} +1 -1
  83. package/dist/cli/ui/console/index.html +2 -2
  84. package/dist/cli/ui/knowing.d.ts +3 -3
  85. package/dist/cli/ui/knowing.d.ts.map +1 -1
  86. package/dist/cli/ui/knowing.js +8 -12
  87. package/dist/cli/ui/knowing.js.map +1 -1
  88. package/dist/cli/ui/remembering.d.ts +1 -1
  89. package/dist/cli/ui/remembering.d.ts.map +1 -1
  90. package/dist/cli/ui/remembering.js +5 -5
  91. package/dist/cli/ui/remembering.js.map +1 -1
  92. package/dist/cli/ui/testing.d.ts +1 -1
  93. package/dist/cli/ui/testing.d.ts.map +1 -1
  94. package/dist/cli/ui/testing.js +1 -1
  95. package/dist/cli/ui/testing.js.map +1 -1
  96. package/dist/cli/world.d.ts +12 -6
  97. package/dist/cli/world.d.ts.map +1 -1
  98. package/dist/cli/world.js +14 -12
  99. package/dist/cli/world.js.map +1 -1
  100. package/dist/client/client.d.ts +13 -1
  101. package/dist/client/client.d.ts.map +1 -1
  102. package/dist/client/client.js +29 -0
  103. package/dist/client/client.js.map +1 -1
  104. package/dist/client/endpoints.d.ts +2 -0
  105. package/dist/client/endpoints.d.ts.map +1 -1
  106. package/dist/client/endpoints.js +5 -1
  107. package/dist/client/endpoints.js.map +1 -1
  108. package/dist/client/index.d.ts +2 -2
  109. package/dist/client/index.d.ts.map +1 -1
  110. package/dist/client/index.js +1 -1
  111. package/dist/client/index.js.map +1 -1
  112. package/dist/client/testing/gateway.d.ts +16 -0
  113. package/dist/client/testing/gateway.d.ts.map +1 -1
  114. package/dist/client/testing/gateway.js +43 -9
  115. package/dist/client/testing/gateway.js.map +1 -1
  116. package/dist/client/testing/index.d.ts +1 -1
  117. package/dist/client/testing/index.d.ts.map +1 -1
  118. package/dist/index.d.ts +1 -0
  119. package/dist/index.d.ts.map +1 -1
  120. package/dist/index.js +1 -0
  121. package/dist/index.js.map +1 -1
  122. package/dist/runtime/connect.d.ts +8 -9
  123. package/dist/runtime/connect.d.ts.map +1 -1
  124. package/dist/runtime/connect.js +19 -122
  125. package/dist/runtime/connect.js.map +1 -1
  126. package/dist/runtime/environment.d.ts +7 -0
  127. package/dist/runtime/environment.d.ts.map +1 -0
  128. package/dist/runtime/environment.js +30 -0
  129. package/dist/runtime/environment.js.map +1 -0
  130. package/dist/views/layout.d.ts.map +1 -1
  131. package/dist/views/layout.js +4 -5
  132. package/dist/views/layout.js.map +1 -1
  133. package/package.json +2 -2
  134. package/dist/cli/knowledge.d.ts.map +0 -1
  135. package/dist/cli/knowledge.js.map +0 -1
  136. package/dist/cli/tuned.d.ts +0 -8
  137. package/dist/cli/tuned.d.ts.map +0 -1
  138. package/dist/cli/tuned.js +0 -66
  139. package/dist/cli/tuned.js.map +0 -1
  140. package/dist/runtime/grounding.d.ts +0 -15
  141. package/dist/runtime/grounding.d.ts.map +0 -1
  142. package/dist/runtime/grounding.js +0 -72
  143. package/dist/runtime/grounding.js.map +0 -1
@@ -56,12 +56,12 @@ Error generating stack: `+e.message+`
56
56
  `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Aa,c=!Co.jitless,l=c&&ja.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Kc([],p,i,f,d,e):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Xc(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!qa(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Qa(e,r,wo())))}),t)}var Zc=N(`$ZodUnion`,(e,t)=>{Zs.init(e,t),po(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),po(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),po(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),po(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Ca(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Xc(t,r,e,i)):Xc(o,r,e,i)}}),Qc=N(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Zc.init(e,t);let n=e._zod.parse;po(e,`propValues`,e=>{let t={};for(let n of e.def.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(n)}"`);for(let[e,n]of Object.entries(r)){Object.prototype.hasOwnProperty.call(t,e)||Ta(t,e,new Set);for(let r of n)t[e].add(r)}}return t}),t.options.forEach((e,n)=>{let r=qc.get(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=xa(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Aa(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),$c=N(`$ZodIntersection`,(e,t)=>{Zs.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>tl(e,t,n)):tl(e,i,a)}});function el(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ma(e)&&Ma(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=el(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=el(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function tl(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=el(t.value,n.value);if(!c.valid){if(qa(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var nl=N(`$ZodTuple`,(e,t)=>{Zs.init(e,t);let n=t.items,r=Co.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=rl(n,`optin`),l=rl(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):u[e]=t}if(t.rest){let e=n.length-1,r=o.slice(n.length);for(let n of r){e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>il(t,i,e))):il(r,i,e)}}return s.length?Promise.all(s).then(()=>al(u,i,n,o,l)):al(u,i,n,o,l)}});function rl(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function il(e,t,n){e.issues.length&&t.issues.push(...Ya(n,e.issues)),t.value[n]=e.value}function al(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...Ya(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var ol=N(`$ZodRecord`,(e,t)=>{Zs.init(e,t);let n=Co.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Ma(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Qa(e,i,wo())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Ya(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Ya(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Ds.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>Qa(e,i,wo())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Ya(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Ya(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),sl=N(`$ZodEnum`,(e,t)=>{Zs.init(e,t);let n=va(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>Pa.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>Fa(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),cl=N(`$ZodLiteral`,(e,t)=>{Zs.init(e,t);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(t.values.length?`^(${t.values.map(e=>typeof e==`string`?Fa(e):e?Fa(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ll=N(`$ZodTransform`,(e,t)=>{Zs.init(e,t),e._zod.optin=`optional`,Co.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new So(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new xo;return n.value=i,n}});function ul(e,t){return e.value=t.issues.length?void 0:t.value,e}var dl=N(`$ZodOptional`,(e,t)=>{Zs.init(e,t),po(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,po(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),po(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ca(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ul(e,t)):ul(e,r)}return t.innerType._zod.run(e,n)}}),fl=N(`$ZodExactOptional`,(e,t)=>{dl.init(e,t),po(e,`values`,e=>e.def.innerType._zod.values),po(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),pl=N(`$ZodNullable`,(e,t)=>{Zs.init(e,t),po(e,`optin`,e=>e.def.innerType._zod.optin),po(e,`optout`,e=>e.def.innerType._zod.optout),po(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ca(t.source)}|null)$`):void 0}),po(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),ml=N(`$ZodDefault`,(e,t)=>{Zs.init(e,t),e._zod.optin=`defaulted`,po(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>hl(e,t)):hl(r,t)}});function hl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var gl=N(`$ZodPrefault`,(e,t)=>{Zs.init(e,t),e._zod.optin=`defaulted`,po(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),_l=N(`$ZodNonOptional`,(e,t)=>{Zs.init(e,t),po(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>vl(t,e)):vl(i,e)}});function vl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function yl(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Qa(e,r,wo()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var bl=N(`$ZodCatch`,(e,t)=>{Zs.init(e,t),po(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),po(e,`optout`,e=>e.def.innerType._zod.optout),po(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>yl(e,r,t,n)):yl(e,r,t,n)}}),xl=N(`$ZodPipe`,(e,t)=>{Zs.init(e,t),po(e,`values`,e=>e.def.in._zod.values),po(e,`optin`,e=>e.def.in._zod.optin),po(e,`optout`,e=>e.def.out._zod.optout),po(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Sl(e,t.in,n)):Sl(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Sl(e,t.out,n)):Sl(r,t.out,n)}});function Sl(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Cl=N(`$ZodReadonly`,(e,t)=>{Zs.init(e,t),po(e,`propValues`,e=>e.def.innerType._zod.propValues),po(e,`values`,e=>e.def.innerType._zod.values),po(e,`optin`,e=>e.def.innerType?._zod?.optin),po(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(wl):wl(r)}});function wl(e){return e.memo||(e.value=Object.freeze(e.value)),e}var Tl=N(`$ZodCustom`,(e,t)=>{js.init(e,t),Zs.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>El(t,n,r,e));El(i,n,r,e)}});function El(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ro(e))}}var Dl=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Ol=`~memo`,kl=[];function Al(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var jl=new WeakMap;function Ml(e,t){let n=jl.get(e);if(n!==void 0)return n;if(t.has(e))return!0;t.add(e);let r=!1,i=e=>{!r&&e?._zod&&Ml(e,t)&&(r=!0)},a=e._zod.def;switch(a.type){case`object`:for(let e of Reflect.ownKeys(a.shape))i(a.shape[e]);i(a.catchall);break;case`array`:i(a.element);break;case`tuple`:for(let e of a.items)i(e);i(a.rest);break;case`record`:case`map`:i(a.keyType),i(a.valueType);break;case`set`:i(a.valueType);break;case`union`:for(let e of a.options)i(e);break;case`intersection`:i(a.left),i(a.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:i(a.innerType);break;case`pipe`:i(a.in),i(a.out);break;case`function`:i(a.input),i(a.output);break;case`lazy`:i(e._zod.innerType);break;case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in a){let t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)i(n);else if(Array.isArray(n))for(let e of n)i(e)}}}return t.delete(e),jl.set(e,r),r}function Nl(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}var Pl,Fl=[],Il={alloc(e,t,n){let r=Pl;if(!r)return n;Pl=void 0;let i={value:n,issues:null};return r.set(t.value,i),Fl.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Rl(n,e.value))throw new Dl;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(o,s)=>{if(n===void 0&&(n=Ml(e,new Set),!n))return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(o,s);let c=o.value;if(typeof c!=`object`||!c)return t(o,s);let l=s[Ol];l||(l={buckets:new Map,backEdges:void 0},s[Ol]=l);let u;r===s?u=i:(u=Nl(l,e),r=s,i=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...Al(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=new Set),l.backEdges.add(d.value)),o;Pl=u;let f=Fl.length,p=t(o,s);Pl=void 0;let m=Fl.length>f?Fl.pop():void 0;return p instanceof Promise?p.then(e=>(m&&(m.issues=e.issues.length?Al(e.issues):kl),e)):(m&&(m.issues=p.issues.length?Al(p.issues):kl),p)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};function Ll(){return Il}function Rl(e,t){let n=e[Ol]?.backEdges;return n!==void 0&&typeof t==`object`&&!!t&&n.has(t)}var zl=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,credit_card:`credit card number`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(no(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${La(e.values[0])}`:`Invalid option: expected one of ${ya(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${ya(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Bl(){return{localeError:zl()}}var Vl,Hl=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Ul(){return new Hl}(Vl=globalThis).__zod_globalRegistry??(Vl.__zod_globalRegistry=Ul());var Wl=globalThis.__zod_globalRegistry;function Gl(e,t){return new e({type:`string`,...M(t)})}function Kl(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...M(t)})}function ql(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...M(t)})}function Jl(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...M(t)})}function Yl(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...M(t)})}function Xl(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...M(t)})}function Zl(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...M(t)})}function Ql(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...M(t)})}function $l(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...M(t)})}function eu(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...M(t)})}function tu(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...M(t)})}function nu(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...M(t)})}function ru(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...M(t)})}function iu(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...M(t)})}function au(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...M(t)})}function ou(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...M(t)})}function su(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...M(t)})}function cu(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...M(t)})}function lu(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...M(t)})}function uu(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...M(t)})}function du(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...M(t)})}function fu(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...M(t)})}function pu(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...M(t)})}function mu(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...M(t)})}function hu(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...M(t)})}function gu(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...M(t)})}function _u(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...M(t)})}function vu(e,t){return new e({type:`number`,checks:[],...M(t)})}function yu(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...M(t)})}function bu(e,t){return new e({type:`boolean`,...M(t)})}function xu(e){return new e({type:`unknown`})}function Su(e,t){return new e({type:`never`,...M(t)})}function Cu(e,t){return new Ps({check:`less_than`,...M(t),value:e,inclusive:!1})}function wu(e,t){return new Ps({check:`less_than`,...M(t),value:e,inclusive:!0})}function Tu(e,t){return new Fs({check:`greater_than`,...M(t),value:e,inclusive:!1})}function Eu(e,t){return new Fs({check:`greater_than`,...M(t),value:e,inclusive:!0})}function Du(e,t){return new Is({check:`multiple_of`,...M(t),value:e})}function Ou(e,t){return new Rs({check:`max_length`,...M(t),maximum:e})}function ku(e,t){return new zs({check:`min_length`,...M(t),minimum:e})}function Au(e,t){return new Bs({check:`length_equals`,...M(t),length:e})}function ju(e,t){return new Hs({check:`string_format`,format:`regex`,...M(t),pattern:e})}function Mu(e){return new Us({check:`string_format`,format:`lowercase`,...M(e)})}function Nu(e){return new Ws({check:`string_format`,format:`uppercase`,...M(e)})}function Pu(e,t){return new Gs({check:`string_format`,format:`includes`,...M(t),includes:e})}function Fu(e,t){return new Ks({check:`string_format`,format:`starts_with`,...M(t),prefix:e})}function Iu(e,t){return new qs({check:`string_format`,format:`ends_with`,...M(t),suffix:e})}function Lu(e){return new Js({check:`overwrite`,tx:e})}function Ru(e){return Lu(t=>t.normalize(e))}function zu(){return Lu(e=>e.trim())}function Bu(){return Lu(e=>e.toLowerCase())}function Vu(){return Lu(e=>e.toUpperCase())}function Hu(){return Lu(e=>Oa(e))}function Uu(e,t,n){return new e({type:`array`,element:t,...M(n)})}function Wu(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...M(n)})}function Gu(e,t){let n=Ku(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(ro(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(ro(r))}},e(t.value,t)),t);return n}function Ku(e,t){let n=new js({check:`custom`,...M(t)});return n._zod.check=e,n}function qu(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ta(e,t,n[t]);return e}function Ju(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Wl,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function Yu(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function Xu(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Xu(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&qu(o.schema,c),t.io===`input`&&od(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Zu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Qu(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${Zu(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+Zu(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
57
57
 
58
58
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function $u(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;$u(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ed=new Set([`type`,`properties`,`required`,`additionalProperties`]),td=[`oneOf`,`anyOf`];function nd(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function rd(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ed.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??nd(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ta(n,r,e.length===1?e[0]:rd(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=nd(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function id(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ed)if(t in e)return;let n=t.filter(e=>td.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=rd(t);else{let e=n[0],i=td.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>rd([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,qu(e,r))}function ad(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):qu(i,s),qu(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())$u(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])id(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}qu(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ta(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:cd(t,`input`,e.processors),output:cd(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function od(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return od(r.element,n);if(r.type===`set`)return od(r.valueType,n);if(r.type===`lazy`)return od(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return od(r.innerType,n);if(r.type===`intersection`)return od(r.left,n)||od(r.right,n);if(r.type===`record`||r.type===`map`)return od(r.keyType,n)||od(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:od(r.in,n)||od(r.out,n);if(r.type===`object`){for(let e in r.shape)if(od(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(od(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(od(e,n))return!0;return!!(r.rest&&od(r.rest,n))}return!1}var sd=(e,t={})=>n=>{let r=Ju({...n,processors:t});return Xu(e,r),Qu(r,e),ad(r,e)},cd=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ju({...i??{},target:a,io:t,processors:n});return Xu(e,o),Qu(o,e),ad(o,e)},ld={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ud=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ld[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},dd=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):Yu(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},fd=(e,t,n,r)=>{n.type=`boolean`},pd=(e,t,n,r)=>{Yu(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},md=(e,t,n,r)=>{Yu(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},hd=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},gd=(e,t,n,r)=>{Yu(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},_d=(e,t,n,r)=>{Yu(e,t,n,r,`Void cannot be represented in JSON Schema`)},vd=(e,t,n,r)=>{n.not={}},yd=(e,t,n,r)=>{},bd=(e,t,n,r)=>{},xd=(e,t,n,r)=>{Yu(e,t,n,r,`Date cannot be represented in JSON Schema`)},Sd=(e,t,n,r)=>{let i=e._zod.def,a=va(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Cd=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(Yu(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Yu(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},wd=(e,t,n,r)=>{Yu(e,t,n,r,`NaN cannot be represented in JSON Schema`)},Td=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ed=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Dd=(e,t,n,r)=>{n.type=`boolean`},Od=(e,t,n,r)=>{Yu(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},kd=(e,t,n,r)=>{Yu(e,t,n,r,`Function types cannot be represented in JSON Schema`)},Ad=(e,t,n,r)=>{Yu(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},jd=(e,t,n,r)=>{Yu(e,t,n,r,`Map cannot be represented in JSON Schema`)},Md=(e,t,n,r)=>{Yu(e,t,n,r,`Set cannot be represented in JSON Schema`)},Nd=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Xu(a.element,t,{...r,path:[...r.path,`items`]})};function Pd(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Pd(t.out):t.type===`catch`?Pd(t.innerType):e._zod.optin}var Fd=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Yu(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ta(i.properties,e,Xu(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?Pd(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Xu(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Id=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Xu(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ld=(e,t,n,r)=>{let i=e._zod.def,a=Xu(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Xu(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Rd=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Xu(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Xu(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Pd(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=e._zod.bag;typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function zd(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=zd(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>zd(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Ds:Es).source),p):p}var Bd=new WeakMap;function Vd(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of Bd.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=zd(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Hd=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Xu(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ta(i.patternProperties,t.source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=Xu(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Bd.get(t);n||(n=[],Bd.set(t,n),t.deferred.push(()=>Vd(t))),n.push(e)}i.additionalProperties=Xu(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Pd(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Ud=(e,t,n,r)=>{let i=e._zod.def,a=Xu(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Wd=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Gd=Symbol();function Kd(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Yu(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Gd):JSON.parse(o)}var qd=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Kd(i.defaultValue,e,t,n,r);o!==Gd&&(n.default=o)},Jd=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Kd(i.defaultValue,e,t,n,r);o!==Gd&&(n._prefault=o)},Yd=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Yu(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Xd=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Xu(o,t,r);let s=t.seen.get(e);s.ref=o},Zd=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Qd=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},$d=(e,t,n,r)=>{let i=e._zod.def;Xu(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ef={string:ud,number:dd,boolean:fd,bigint:pd,symbol:md,null:hd,undefined:gd,void:_d,never:vd,any:yd,unknown:bd,date:xd,enum:Sd,literal:Cd,nan:wd,template_literal:Td,file:Ed,success:Dd,custom:Od,function:kd,transform:Ad,map:jd,set:Md,array:Nd,object:Fd,union:Id,intersection:Ld,tuple:Rd,record:Hd,nullable:Ud,nonoptional:Wd,default:qd,prefault:Jd,catch:Yd,pipe:Xd,readonly:Zd,promise:Qd,optional:$d,lazy:(e,t,n,r)=>{let i=e._zod.innerType;Xu(i,t,r);let a=t.seen.get(e);a.ref=i}};function tf(e,t){if(`_idmap`in e){let n=e,r=Ju({...t,processors:ef}),i={};for(let e of n._idmap.entries()){let[t,n]=e;Xu(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Qu(r,n),Ta(a,t,ad(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Ju({...t,processors:ef});return Xu(e,n),Qu(n,e),ad(n,e)}var nf=new WeakSet([Object.prototype,Error.prototype]);function rf(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var af=N(`ZodError`,(e,t)=>{Mo.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);nf.has(n)||(nf.add(n),rf(n,`format`,e=>t=>Io(e,t)),rf(n,`flatten`,e=>t=>Fo(e,t)),rf(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ba,2)}),rf(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ba,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),of=Ro(af),sf=zo(af),cf=Bo(af),lf=Ho(af),uf=Wo(af),df=Go(af),ff=Ko(af),pf=qo(af),mf=Jo(af),hf=Yo(af),gf=Xo(af),_f=Zo(af);function vf(){Co.localeError||wo(Bl())}function yf(){Co.memoizer||wo({memoizer:Ll()})}var bf=N(`ZodType`,(e,t)=>(vf(),Zs.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Ea(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ia(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Rp(e,t))},superRefine(e,t){return this.check(zp(e,t))},overwrite(e){return this.check(Lu(e))},optional(){return bp(this)},exactOptional(){return Sp(this)},nullable(){return wp(this)},nullish(){return bp(wp(this))},nonoptional(e){return Ap(this,e)},array(){return R(this)},or(e){return ip([this,e])},and(e){return cp(this,e)},transform(e){return Pp(this,vp(e))},default(e){return Ep(this,e)},prefault(e){return Op(this,e)},catch(e){return Mp(this,e)},pipe(e){return Pp(this,e)},readonly(){return Ip(this)},describe(e){let t=this.clone();return Wl.add(t,{description:e}),t},meta(...e){if(e.length===0)return Wl.get(this);let t=this.clone();return Wl.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return oo(this,`~standard`,{...$s(this),jsonSchema:{input:cd(this,`input`),output:cd(this,`output`)}})},set"~standard"(e){ao(this,`~standard`,e)},parse:function e(t,n){return of(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await sf(this,t,n,{callee:e})},safeParse(e,t){return cf(this,e,t)},async safeParseAsync(e,t){return lf(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ao(this,`spa`,e)},encode:function e(t,n){return uf(this,t,n,{callee:e})},decode:function e(t,n){return df(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await ff(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await pf(this,t,n,{callee:e})},safeEncode(e,t){return mf(this,e,t)},safeDecode(e,t){return hf(this,e,t)},async safeEncodeAsync(e,t){return gf(this,e,t)},async safeDecodeAsync(e,t){return _f(this,e,t)},toJSONSchema(e){return sd(this,{})(e)},get description(){return Wl.get(this)?.description},get _def(){return this._zod.def}}),xf=N(`_ZodString`,(e,t)=>{ec.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ud(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(ju(...e))},includes(...e){return this.check(Pu(...e))},startsWith(...e){return this.check(Fu(...e))},endsWith(...e){return this.check(Iu(...e))},min(...e){return this.check(ku(...e))},max(...e){return this.check(Ou(...e))},length(...e){return this.check(Au(...e))},nonempty(...e){return this.check(ku(1,...e))},lowercase(e){return this.check(Mu(e))},uppercase(e){return this.check(Nu(e))},trim(){return this.check(zu())},normalize(...e){return this.check(Ru(...e))},toLowerCase(){return this.check(Bu())},toUpperCase(){return this.check(Vu())},slugify(){return this.check(Hu())}}),Sf=N(`ZodString`,(e,t)=>{ec.init(e,t),xf.init(e,t)},{email(e){return this.check(Kl(Of,e))},url(e){return this.check(Ql(jf,e))},jwt(e){return this.check(pu(Kf,e))},emoji(e){return this.check($l(Mf,e))},guid(e){return this.check(ql(kf,e))},uuid(e){return this.check(Jl(Af,e))},uuidv4(e){return this.check(Yl(Af,e))},uuidv6(e){return this.check(Xl(Af,e))},uuidv7(e){return this.check(Zl(Af,e))},nanoid(e){return this.check(eu(Nf,e))},cuid(e){return this.check(tu(Pf,e))},cuid2(e){return this.check(nu(Ff,e))},ulid(e){return this.check(ru(If,e))},base64(e){return this.check(uu(Uf,e))},base64url(e){return this.check(du(Wf,e))},xid(e){return this.check(iu(Lf,e))},ksuid(e){return this.check(au(Rf,e))},ipv4(e){return this.check(ou(zf,e))},ipv6(e){return this.check(su(Bf,e))},cidrv4(e){return this.check(cu(Vf,e))},cidrv6(e){return this.check(lu(Hf,e))},e164(e){return this.check(fu(Gf,e))},datetime(e){return this.check(mu(wf,e))},date(e){return this.check(hu(Tf,e))},time(e){return this.check(gu(Ef,e))},duration(e){return this.check(_u(Df,e))}});function P(e){return Gl(Sf,e)}var Cf=N(`ZodStringFormat`,(e,t)=>{tc.init(e,t),xf.init(e,t)}),wf=N(`ZodISODateTime`,(e,t)=>{vc.init(e,t),Cf.init(e,t)}),Tf=N(`ZodISODate`,(e,t)=>{yc.init(e,t),Cf.init(e,t)}),Ef=N(`ZodISOTime`,(e,t)=>{bc.init(e,t),Cf.init(e,t)}),Df=N(`ZodISODuration`,(e,t)=>{xc.init(e,t),Cf.init(e,t)}),Of=N(`ZodEmail`,(e,t)=>{ic.init(e,t),Cf.init(e,t)}),kf=N(`ZodGUID`,(e,t)=>{nc.init(e,t),Cf.init(e,t)}),Af=N(`ZodUUID`,(e,t)=>{rc.init(e,t),Cf.init(e,t)}),jf=N(`ZodURL`,(e,t)=>{uc.init(e,t),Cf.init(e,t)}),Mf=N(`ZodEmoji`,(e,t)=>{dc.init(e,t),Cf.init(e,t)}),Nf=N(`ZodNanoID`,(e,t)=>{fc.init(e,t),Cf.init(e,t)}),Pf=N(`ZodCUID`,(e,t)=>{pc.init(e,t),Cf.init(e,t)}),Ff=N(`ZodCUID2`,(e,t)=>{mc.init(e,t),Cf.init(e,t)}),If=N(`ZodULID`,(e,t)=>{hc.init(e,t),Cf.init(e,t)}),Lf=N(`ZodXID`,(e,t)=>{gc.init(e,t),Cf.init(e,t)}),Rf=N(`ZodKSUID`,(e,t)=>{_c.init(e,t),Cf.init(e,t)}),zf=N(`ZodIPv4`,(e,t)=>{Sc.init(e,t),Cf.init(e,t)}),Bf=N(`ZodIPv6`,(e,t)=>{Tc.init(e,t),Cf.init(e,t)}),Vf=N(`ZodCIDRv4`,(e,t)=>{Ec.init(e,t),Cf.init(e,t)}),Hf=N(`ZodCIDRv6`,(e,t)=>{Oc.init(e,t),Cf.init(e,t)}),Uf=N(`ZodBase64`,(e,t)=>{Ac.init(e,t),Cf.init(e,t)}),Wf=N(`ZodBase64URL`,(e,t)=>{Mc.init(e,t),Cf.init(e,t)}),Gf=N(`ZodE164`,(e,t)=>{Nc.init(e,t),Cf.init(e,t)}),Kf=N(`ZodJWT`,(e,t)=>{Fc.init(e,t),Cf.init(e,t)}),qf=N(`ZodNumber`,(e,t)=>{Ic.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dd(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(Tu(e,t))},gte(e,t){return this.check(Eu(e,t))},min(e,t){return this.check(Eu(e,t))},lt(e,t){return this.check(Cu(e,t))},lte(e,t){return this.check(wu(e,t))},max(e,t){return this.check(wu(e,t))},int(e){return this.check(I(e))},safe(e){return this.check(I(e))},positive(e){return this.check(Tu(0,e))},nonnegative(e){return this.check(Eu(0,e))},negative(e){return this.check(Cu(0,e))},nonpositive(e){return this.check(wu(0,e))},multipleOf(e,t){return this.check(Du(e,t))},step(e,t){return this.check(Du(e,t))},finite(){return this}});function F(e){return vu(qf,e)}var Jf=N(`ZodNumberFormat`,(e,t)=>{Lc.init(e,t),qf.init(e,t)});function I(e){return yu(Jf,e)}var Yf=N(`ZodBoolean`,(e,t)=>{Rc.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fd(e,t,n,r)});function L(e){return bu(Yf,e)}var Xf=N(`ZodUnknown`,(e,t)=>{zc.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Zf(){return xu(Xf)}var Qf=N(`ZodNever`,(e,t)=>{Bc.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vd(e,t,n,r)});function $f(e){return Su(Qf,e)}var ep=N(`ZodArray`,(e,t)=>{yf(),Hc.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nd(e,t,n,r),e.element=t.element},{min(e,t){return this.check(ku(e,t))},nonempty(e){return this.check(ku(1,e))},max(e,t){return this.check(Ou(e,t))},length(e,t){return this.check(Au(e,t))},unwrap(){return this.element}});function R(e,t){return Uu(ep,e,t)}var tp=N(`ZodObject`,(e,t)=>{yf(),Yc.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fd(e,t,n,r),mo(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return mp(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:Zf()})},loose(){return this.clone({...this._zod.def,catchall:Zf()})},strict(){return this.clone({...this._zod.def,catchall:$f()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Ha(this,e)},safeExtend(e){return Ua(this,e)},merge(e){return Wa(this,e)},pick(e){return Ba(this,e)},omit(e){return Va(this,e)},partial(...e){return Ga(yp,this,e[0])},exactPartial(...e){return Ga(xp,this,e[0],`exactPartial`)},required(...e){return Ka(kp,this,e[0])}});function z(e,t){return new tp({type:`object`,shape:e??{},...M(t)})}function B(e,t){return new tp({type:`object`,shape:e,catchall:$f(),...M(t)})}function np(e,t){return new tp({type:`object`,shape:e,catchall:Zf(),...M(t)})}var rp=N(`ZodUnion`,(e,t)=>{Zc.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Id(e,t,n,r),e.options=t.options});function ip(e,t){return new rp({type:`union`,options:e,...M(t)})}var ap=N(`ZodDiscriminatedUnion`,(e,t)=>{rp.init(e,t),Qc.init(e,t)});function op(e,t,n){return new ap({type:`union`,options:t,discriminator:e,...M(n)})}var sp=N(`ZodIntersection`,(e,t)=>{$c.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ld(e,t,n,r)});function cp(e,t){return new sp({type:`intersection`,left:e,right:t})}var lp=N(`ZodTuple`,(e,t)=>{yf(),nl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rd(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new yp({type:`optional`,innerType:e}))})}});function up(e,t,n){let r=t instanceof Zs;return new lp({type:`tuple`,items:e,rest:r?t:null,...M(r?n:t)})}var dp=N(`ZodRecord`,(e,t)=>{yf(),ol.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hd(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function fp(e,t,n){return!t||!t._zod?new dp({type:`record`,keyType:P(),valueType:e,...M(t)}):new dp({type:`record`,keyType:e,valueType:t,...M(n)})}var pp=N(`ZodEnum`,(e,t)=>{sl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sd(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new pp({...t,checks:[],...M(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new pp({...t,checks:[],...M(r),entries:i})}});function mp(e,t){return new pp({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...M(t)})}var hp=N(`ZodLiteral`,(e,t)=>{cl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cd(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function gp(e,t){return new hp({type:`literal`,values:Array.isArray(e)?e:[e],...M(t)})}var _p=N(`ZodTransform`,(e,t)=>{yf(),ll.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ad(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new So(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ro(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(ro(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function vp(e){return new _p({type:`transform`,transform:e})}var yp=N(`ZodOptional`,(e,t)=>{dl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$d(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function bp(e){return new yp({type:`optional`,innerType:e})}var xp=N(`ZodExactOptional`,(e,t)=>{fl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$d(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sp(e){return new xp({type:`optional`,innerType:e})}var Cp=N(`ZodNullable`,(e,t)=>{pl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ud(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wp(e){return new Cp({type:`nullable`,innerType:e})}var Tp=N(`ZodDefault`,(e,t)=>{ml.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ep(e,t){return new Tp({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Na(t)}})}var Dp=N(`ZodPrefault`,(e,t)=>{gl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Op(e,t){return new Dp({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Na(t)}})}var kp=N(`ZodNonOptional`,(e,t)=>{_l.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ap(e,t){return new kp({type:`nonoptional`,innerType:e,...M(t)})}var jp=N(`ZodCatch`,(e,t)=>{bl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Mp(e,t){return new jp({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:go(t)})}var Np=N(`ZodPipe`,(e,t)=>{xl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xd(e,t,n,r),e.in=t.in,e.out=t.out});function Pp(e,t){return new Np({type:`pipe`,in:e,out:t})}var Fp=N(`ZodReadonly`,(e,t)=>{Cl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zd(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ip(e){return new Fp({type:`readonly`,innerType:e})}var Lp=N(`ZodCustom`,(e,t)=>{Tl.init(e,t),bf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Od(e,t,n,r)});function Rp(e,t={}){return Wu(Lp,e,t)}function zp(e,t){return Gu(e,t)}var Bp=z({key:P(),key_id:P(),org:P(),label:P().nullish(),env:mp([`production`,`sandbox`]),scopes:R(P()),subject:P().nullish(),name:P().nullish()}),Vp=`console`;async function Hp(e,t){return rm(e,{code:t,device:Vp})}async function Up(e,t){return rm(e,{...t,org:t.org===void 0||t.org===``?null:t.org,device:Vp})}var Wp=z({orgs:R(z({org:P(),slug:P().nullish(),name:P().nullish(),role:P(),status:P(),here:L(),member:L().optional()}))});async function Gp(e){return Wp.parse(await k(e,`/v1/login/orgs`)).orgs}async function Kp(e,t){return Bp.parse(await sa(e,`/v1/login/org`,{org:t}))}async function qp(e,t,n){return im(e,`/v1/invitations/${encodeURIComponent(t)}`,{password:n,device:Vp})}var Jp=z({orgs:R(z({org:P(),slug:P().nullish(),name:P().nullish(),role:P()}))});async function Yp(e,t,n){let r=await fetch(new URL(`${e.replace(/\/$/,``)}/v1/login/orgs`,window.location.origin),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})});return r.status===404||r.status===405?null:Jp.parse(await fa(r)).orgs}var Xp=z({orgs:R(z({org:P(),slug:P().nullish(),name:P().nullish()}))});async function Zp(e,t){return fetch(new URL(`${e.replace(/\/$/,``)}/v1/login/sso/discover`,window.location.origin),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t})})}async function Qp(e){try{let t=await Zp(e,``);return t.status!==404&&t.status!==405}catch{return!1}}async function $p(e,t){return Xp.parse(await fa(await Zp(e,t))).orgs}function em(e,t){return new URL(`${e.replace(/\/$/,``)}/v1/login/sso?org=${encodeURIComponent(t)}`,window.location.origin).toString()}function tm(e){return new URL(`${e.replace(/\/$/,``)}/v1/login/google`,window.location.origin).toString()}function nm(e){return`${e.replace(/\/$/,``)}/v1/login/google/callback`}async function rm(e,t){return im(e,`/v1/login`,t)}async function im(e,t,n){let r=await fetch(new URL(`${e.replace(/\/$/,``)}${t}`,window.location.origin),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)});return Bp.parse(await fa(r))}function am({children:e,foot:t}){return(0,A.jsxs)(`div`,{className:`login`,children:[(0,A.jsxs)(`div`,{className:`login-side`,children:[(0,A.jsx)(`img`,{className:`login-logo`,src:`/pinecall-logo.png`,alt:`Pinecall`}),(0,A.jsx)(`div`,{className:`login-form`,children:e}),(0,A.jsx)(`p`,{className:`login-foot`,children:t??(0,A.jsxs)(A.Fragment,{children:[`Working from a terminal? Run `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall link`}),` in your project's folder.`]})})]}),(0,A.jsx)(sm,{})]})}var om=[{initials:`DK`,tint:`violet`,name:`Dana Keller`,line:`Booked · Friday 2 PM, work order #SO-2026-PL-0060`,channel:`phone`},{initials:`TS`,tint:`pink`,name:`Tim Stacy`,line:`Quoted the fifteen dollar dispatch fee`,channel:`web`},{initials:`AR`,tint:`green`,name:`Ana Ruiz`,line:`Callback promised within the hour`,channel:`whatsapp`}];function sm(){return(0,A.jsxs)(`div`,{className:`login-show`,"aria-hidden":!0,children:[(0,A.jsxs)(`div`,{className:`login-show-words`,children:[(0,A.jsx)(`h2`,{className:`login-show-title`,children:`Every conversation your company has, in one place.`}),(0,A.jsx)(`p`,{className:`login-show-lede`,children:`Web, WhatsApp and phone land in the same inbox — with the transcript, the outcome and the cost on every row.`})]}),(0,A.jsxs)(`div`,{className:`login-show-card`,children:[(0,A.jsxs)(`div`,{className:`login-show-head`,children:[(0,A.jsx)(`span`,{className:`ui-dot ui-dot-green`}),(0,A.jsx)(`span`,{className:`login-show-today`,children:`Today`}),(0,A.jsx)(`span`,{className:`login-show-count`,children:`137 conversations`})]}),om.map(e=>(0,A.jsxs)(`div`,{className:`login-show-row`,children:[(0,A.jsx)(`span`,{className:`ui-avatar ui-avatar-26 ui-tint-${e.tint}`,children:e.initials}),(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`login-show-name`,children:e.name}),(0,A.jsx)(`div`,{className:`login-show-line`,children:e.line})]}),(0,A.jsx)(`span`,{className:`login-show-channel`,children:e.channel})]},e.name))]})]})}function cm(){return(0,A.jsxs)(am,{foot:(0,A.jsx)(A.Fragment,{children:`This is your sandbox, on this machine. Production is watched on the gateway's console.`}),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`This project is not linked`}),(0,A.jsxs)(`p`,{className:`login-lede`,children:[`The gateway refused the key `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall serve`}),` is using. Link the project again, in its folder, then start it once more:`]}),(0,A.jsxs)(`pre`,{className:`login-commands`,children:[`pinecall link`,`
59
- `,`pinecall serve`]})]})}var lm=(0,D.createContext)(null);function um({value:e,children:t}){return(0,A.jsx)(lm,{value:e,children:t})}function dm(){let e=(0,D.useContext)(lm);if(e===null)throw Error(`the console was mounted without a way out`);return e}var fm=typeof document<`u`&&document.querySelector(`meta[name="pinecall-console"]`)?.getAttribute(`content`)===`local`?`local`:`hosted`;function pm(){return(document.querySelector(`meta[name="pinecall-gateway"]`)?.getAttribute(`content`)??window.location.origin).replace(/\/$/,``)}var mm={hosted:`production`,local:`sandbox`},hm=[`hosted`,`local`],gm=[`hosted`],_m=[`local`],vm=[{key:`home`,path:``,name:`Home`,in:hm,group:`gateway`,icon:`home`},{key:`agents`,path:`overview`,name:`Overview`,in:hm,group:`gateway`,icon:`grid`},{key:`live`,path:`live`,name:`Live`,in:hm,group:`gateway`,icon:`activity`},{key:`sessions`,path:`sessions`,name:`Sessions`,in:hm,group:`gateway`,icon:`list`},{key:`org-evals`,path:`evals`,name:`Evals`,in:hm,group:`gateway`,icon:`check`},{key:`org-memory`,path:`memory`,name:`Memory`,in:hm,group:`gateway`,icon:`memory`},{key:`usage`,path:`usage`,name:`Usage`,in:gm,group:`gateway`,icon:`chart`},{key:`numbers`,path:`numbers`,name:`Numbers`,in:gm,group:`settings`,icon:`phone`},{key:`phone`,path:`phone`,name:`Phone testing`,in:_m,group:`settings`,icon:`phone`},{key:`tokens`,path:`tokens`,name:`Tokens`,in:gm,group:`settings`,icon:`key`},{key:`providers`,path:`providers`,name:`Providers`,in:gm,group:`settings`,icon:`plug`},{key:`team`,path:`team`,name:`Team`,in:gm,group:`settings`,icon:`users`},{key:`lexicon`,path:`lexicon`,name:`Lexicon`,in:hm,group:`settings`,icon:`words`}],ym=[{key:`box-orgs`,path:`box/orgs`,name:`Organizations`,in:gm,group:`box`,icon:`building`,operator:!0},{key:`box-fleet`,path:`box/fleet`,name:`Fleet`,in:gm,group:`box`,icon:`server`,operator:!0},{key:`box-routes`,path:`box/routes`,name:`Routes`,in:gm,group:`box`,icon:`route`,operator:!0},{key:`box-usage`,path:`box/usage`,name:`Box usage`,in:gm,group:`box`,icon:`chart`,operator:!0},{key:`box-settings`,path:`box/settings`,name:`Box settings`,in:gm,group:`box`,icon:`sliders`,operator:!0}],bm=[{key:`talk`,path:`talk`,name:`Talk`,in:hm},{key:`chat`,path:`chat`,name:`Chat`,in:hm},{key:`devchat`,path:`dev-chat`,name:`Dev chat`,in:_m},{key:`calls`,path:`calls`,name:`Calls`,in:hm},{key:`sessions`,path:`sessions`,name:`Sessions`,in:hm},{key:`settings`,path:`settings`,name:`Settings`,in:hm},{key:`pipeline`,path:`pipeline`,name:`Pipeline`,in:hm},{key:`knowledge`,path:`knowledge`,name:`Knowledge`,in:hm},{key:`memory`,path:`memory`,name:`Memory`,in:hm},{key:`evals`,path:`evals`,name:`Evals`,in:hm},{key:`widget`,path:`widget`,name:`Widget`,in:hm}];function xm(e,t=fm,n=!1){return e.filter(e=>e.in.includes(t)&&(n||e.operator!==!0))}function Sm(e,t,n=fm){return e.some(e=>e.key===t&&e.in.includes(n))}var Cm=`pinecall.key`;function wm(){return window.localStorage.getItem(Cm)}function Tm(e){window.localStorage.setItem(Cm,e)}function Em(){window.localStorage.removeItem(Cm)}var Dm=`pinecall.corner`;function Om(){return window.sessionStorage.getItem(Dm)}function km(e){e===null?window.sessionStorage.removeItem(Dm):window.sessionStorage.setItem(Dm,e)}function V({children:e,pad:t=!1,style:n}){return(0,A.jsx)(`div`,{className:t?`ui-card ui-card-pad`:`ui-card`,style:n,children:e})}function H({title:e,meta:t,action:n,children:r}){return(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[typeof e==`string`?(0,A.jsx)(`span`,{className:`ui-card-title`,children:e}):e,t!==void 0&&(0,A.jsx)(`span`,{className:`ui-card-meta`,children:t}),r,n]})}function Am({to:e,onClick:t,children:n}){return e===void 0?(0,A.jsx)(`button`,{type:`button`,className:`ui-card-action`,onClick:t,children:n}):(0,A.jsx)(Wi,{to:e,className:`ui-card-action`,children:n})}function jm({children:e}){return(0,A.jsx)(`div`,{className:`ui-card-foot`,children:e})}function Mm({children:e}){return(0,A.jsx)(`div`,{className:`ui-empty`,children:e})}function Nm({children:e}){return e==null||e===``?null:(0,A.jsx)(`div`,{className:`ui-refused`,children:e})}function Pm({lead:e,name:t,tag:n,sub:r,end:i,to:a,onClick:o}){let s=(0,A.jsxs)(A.Fragment,{children:[e,(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsxs)(`div`,{className:`ui-row-line`,children:[(0,A.jsx)(`span`,{className:`ui-row-name`,children:t}),n]}),r!==void 0&&(0,A.jsx)(`div`,{className:`ui-row-sub`,children:r})]}),i!==void 0&&(0,A.jsx)(`div`,{className:`ui-row-end`,children:i})]});return a===void 0?(0,A.jsx)(`div`,{className:o===void 0?`ui-row`:`ui-row ui-row-link`,onClick:o,children:s}):(0,A.jsx)(Wi,{to:a,className:`ui-row ui-row-link`,children:s})}function Fm({name:e,sub:t,end:n,to:r}){let i=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`ui-item-name`,children:e}),t!==void 0&&(0,A.jsx)(`div`,{className:`ui-item-sub`,children:t})]}),n]});return r===void 0?(0,A.jsx)(`div`,{className:`ui-item`,children:i}):(0,A.jsx)(Wi,{to:r,className:`ui-item`,children:i})}function Im({children:e,ruled:t=!1}){return(0,A.jsx)(`div`,{className:t?`ui-section-label ui-section-label-ruled`:`ui-section-label`,children:e})}function Lm({label:e,children:t,keyWidth:n}){return(0,A.jsxs)(`div`,{className:`ui-kv`,children:[(0,A.jsx)(`span`,{className:`ui-kv-key`,style:n===void 0?void 0:{width:n},children:e}),(0,A.jsx)(`span`,{className:`ui-kv-value`,children:t})]})}function Rm(e,t,n,r){let i=[`ui-button`];return e!==`secondary`&&i.push(`ui-button-${e}`),t!==`base`&&i.push(`ui-button-${t}`),n&&i.push(`ui-button-pill`),r!==void 0&&i.push(r),i.join(` `)}function U({kind:e=`secondary`,size:t=`base`,pill:n=!1,className:r,type:i=`button`,...a}){return(0,A.jsx)(`button`,{type:i,className:Rm(e,t,n,r),...a})}function zm({to:e,kind:t=`secondary`,size:n=`base`,children:r}){return(0,A.jsx)(Wi,{to:e,className:Rm(t,n,!1),children:r})}function Bm({danger:e=!1,...t}){return(0,A.jsx)(`button`,{type:`button`,className:e?`ui-text-action ui-text-action-danger`:`ui-text-action`,...t})}function Vm({children:e,htmlFor:t}){return(0,A.jsx)(`label`,{className:`ui-label`,htmlFor:t,children:e})}function W({size:e=`form`,className:t,...n}){let r=[`ui-input`];return e===`sm`&&r.push(`ui-input-sm`),e===`lg`&&r.push(`ui-input-lg`),t!==void 0&&r.push(t),(0,A.jsx)(`input`,{className:r.join(` `),...n})}function Hm({size:e=`form`,className:t,...n}){let r=[`ui-select`];return e===`sm`&&r.push(`ui-select-sm`),t!==void 0&&r.push(t),(0,A.jsx)(`select`,{className:r.join(` `),...n})}function Um(e){return(0,A.jsx)(`textarea`,{className:`ui-textarea`,...e})}function Wm({label:e,grow:t=!1,minWidth:n,children:r}){return(0,A.jsxs)(`div`,{className:t?`ui-form-grow`:void 0,style:n===void 0?void 0:{minWidth:n},children:[(0,A.jsx)(`label`,{className:`ui-label`,children:e}),r]})}function Gm({options:e,value:t,onChange:n}){return(0,A.jsx)(`div`,{className:`ui-segmented`,role:`group`,children:e.map(e=>(0,A.jsx)(`button`,{type:`button`,className:e.value===t?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":e.value===t,onClick:()=>n(e.value),children:e.label},e.value))})}function Km({options:e,value:t,onChange:n}){return(0,A.jsx)(`div`,{className:`ui-chips`,role:`group`,children:e.map(e=>(0,A.jsx)(`button`,{type:`button`,className:e.value===t?`ui-chip ui-chip-on`:`ui-chip`,"aria-pressed":e.value===t,onClick:()=>n(e.value),children:e.label},e.value))})}function qm({on:e,children:t,...n}){return(0,A.jsx)(`button`,{type:`button`,className:e?`ui-choice ui-choice-on`:`ui-choice`,"aria-pressed":e,...n,children:t})}function Jm({on:e,onChange:t,label:n}){return(0,A.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,"aria-label":n,className:e?`ui-switch ui-switch-on`:`ui-switch`,onClick:()=>t(!e),children:(0,A.jsx)(`span`,{className:`ui-switch-knob`})})}function Ym({checked:e,onChange:t,children:n}){return(0,A.jsxs)(`label`,{className:`ui-check`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),n]})}var Xm={home:[`M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z`],grid:[{rect:[3,3,7,7,1.5]},{rect:[14,3,7,7,1.5]},{rect:[3,14,7,7,1.5]},{rect:[14,14,7,7,1.5]}],activity:[`M22 12h-4l-3 9L9 3l-3 9H2`],list:[`M8 6h13`,`M8 12h13`,`M8 18h13`,`M3 6h.01`,`M3 12h.01`,`M3 18h.01`],check:[{circle:[12,12,9]},`m8.5 12.5 2.5 2.5 4.5-5`],chart:[`M3 3v18h18`,`M7 15v3`,`M12 9v9`,`M17 5v13`],phone:[`M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2z`],key:[`m21 2-9.6 9.6`,`m15.5 7.5 3 3L22 7l-3-3`,{circle:[7.5,15.5,5.5]}],plug:[`M12 22v-5`,`M9 8V2`,`M15 8V2`,`M18 8v3a6 6 0 0 1-12 0V8z`],users:[`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,{circle:[9,7,4]},`M22 21v-2a4 4 0 0 0-3-3.9`],bot:[`M12 8V4`,{rect:[4,8,16,12,2]},`M2 14h2`,`M20 14h2`,`M9 13v2`,`M15 13v2`],search:[{circle:[11,11,7]},`m21 21-4.3-4.3`],panel:[{rect:[3,3,18,18,2]},`M9 3v18`],building:[{rect:[4,2,16,20,2]},`M9 22v-4h6v4`,`M8 6h.01`,`M16 6h.01`,`M12 6h.01`,`M12 10h.01`,`M12 14h.01`,`M16 10h.01`,`M16 14h.01`,`M8 10h.01`,`M8 14h.01`],server:[{rect:[2,2,20,8,2]},{rect:[2,14,20,8,2]},`M6 6h.01`,`M6 18h.01`],route:[{circle:[6,19,3]},`M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15`,{circle:[18,5,3]}],sliders:[`M21 4h-7`,`M10 4H3`,`M21 12h-9`,`M8 12H3`,`M21 20h-5`,`M12 20H3`,`M14 2v4`,`M8 10v4`,`M16 18v4`],words:[`M4 5h16v10H9l-5 4z`,`M8 9h8`,`M8 12h5`],memory:[`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,`M12 5v13`]};function Zm({name:e,size:t=16}){return(0,A.jsx)(`svg`,{className:`ui-icon`,width:t,height:t,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0,children:Xm[e].map((e,t)=>{if(typeof e==`string`)return(0,A.jsx)(`path`,{d:e},t);if(`circle`in e){let[n,r,i]=e.circle;return(0,A.jsx)(`circle`,{cx:n,cy:r,r:i},t)}let[n,r,i,a,o]=e.rect;return(0,A.jsx)(`rect`,{x:n,y:r,width:i,height:a,rx:o},t)})})}function Qm({tone:e,small:t=!1,children:n}){return(0,A.jsx)(`span`,{className:`ui-pill ui-pill-${e}${t?` ui-pill-small`:``}`,children:n})}function $m({children:e}){return(0,A.jsx)(`span`,{className:`ui-tag`,children:e})}function eh({tone:e,small:t=!1}){let n=[`ui-dot`];return t&&n.push(`ui-dot-small`),e!==void 0&&n.push(`ui-dot-${e}`),(0,A.jsx)(`span`,{className:n.join(` `),"aria-hidden":!0})}var th=[`violet`,`green`,`pink`,`amber`,`indigo`];function nh(e){return[`violet`,`pink`,`green`,`amber`,`indigo`][e%5]??`violet`}function rh(e){let t=0;for(let n of e)t=(t+(n.codePointAt(0)??0))%9973;return th[t%th.length]??`violet`}function ih(e){let t=e.split(/[\s@._-]+/).filter(e=>/[A-Za-z0-9]/.test(e));if(t.length===0)return`?`;if(t.length===1){let e=t[0]??``;return(/^[A-Za-z]/.test(e)?e.slice(0,2):e.slice(0,1)).toUpperCase()}return`${t[0]?.[0]??``}${t[1]?.[0]??``}`.toUpperCase()}function ah({name:e,letters:t,tint:n,size:r=28,round:i=!1}){let a=[`ui-avatar`,`ui-tint-${n??rh(e)}`];r===26&&a.push(`ui-avatar-26`),(r===36||r===38)&&a.push(`ui-avatar-36`),i&&a.push(`ui-avatar-round`),r===38&&a.push(`ui-avatar-38`);let o=r===20?{width:20,height:20,borderRadius:6,fontSize:9.5}:void 0;return(0,A.jsx)(`span`,{className:a.join(` `),style:o,"aria-hidden":!0,children:t??ih(e)})}function oh({share:e,color:t,height:n}){let r=`${Math.max(0,Math.min(1,e))*100}%`;return(0,A.jsx)(`span`,{className:`ui-bar`,style:n===void 0?void 0:{height:n},children:(0,A.jsx)(`span`,{className:`ui-bar-fill`,style:{width:r,background:t}})})}function sh({width:e=1180,tight:t=!1,children:n}){let r=[`ui-page`];return t&&r.push(`ui-page-tight`),e!==1180&&r.push(`ui-page-${e}`),(0,A.jsx)(`div`,{className:r.join(` `),"data-page":!0,children:n})}function ch({title:e,lede:t,ledeWidth:n,back:r,actions:i}){return(0,A.jsxs)(`div`,{className:`ui-head`,children:[(0,A.jsxs)(`div`,{className:`ui-head-words`,style:n===void 0?void 0:{maxWidth:n},children:[r,(0,A.jsx)(`h1`,{className:`ui-title`,children:e}),t!==void 0&&(0,A.jsx)(`p`,{className:n===void 0?`ui-lede`:`ui-lede ui-lede-long`,children:t})]}),i!==void 0&&(0,A.jsx)(`div`,{className:`ui-head-actions`,children:i})]})}function lh({min:e,children:t}){return(0,A.jsx)(`div`,{className:`ui-stats`,style:{gridTemplateColumns:`repeat(auto-fit,minmax(${e}px,1fr))`},children:t})}function uh({label:e,value:t,of:n,delta:r,tone:i,size:a=`medium`,accent:o=!1}){let s=[`ui-stat`];a!==`medium`&&s.push(`ui-stat-${a}`),o&&s.push(`ui-stat-accent`);let c=i===`green`?{color:`var(--green)`}:i===`red`?{color:`var(--red)`}:void 0;return(0,A.jsxs)(`div`,{className:s.join(` `),children:[(0,A.jsx)(`div`,{className:`ui-stat-label`,children:e}),a===`big`?(0,A.jsxs)(`div`,{className:`ui-stat-line`,children:[(0,A.jsx)(`span`,{className:`ui-stat-value`,children:t}),r!==void 0&&(0,A.jsx)(`span`,{className:i===`up`?`ui-stat-delta ui-stat-delta-up`:i===`down`?`ui-stat-delta ui-stat-delta-down`:`ui-stat-delta`,children:r})]}):(0,A.jsxs)(`div`,{className:`ui-stat-value`,style:c,children:[t,n!==void 0&&(0,A.jsxs)(`span`,{className:`ui-stat-of`,children:[` `,n]})]})]})}function dh({columns:e,labels:t,padding:n}){return(0,A.jsx)(`div`,{className:`ui-table-head`,style:{gridTemplateColumns:e,padding:n},children:t.map((e,t)=>e.endsWith(`>`)?(0,A.jsx)(`span`,{style:{textAlign:`right`},children:e.slice(0,-1)},t):(0,A.jsx)(`span`,{children:e},t))})}function fh({columns:e,to:t,onClick:n,padding:r,children:i}){let a={gridTemplateColumns:e,padding:r};return t===void 0?(0,A.jsx)(`div`,{className:n===void 0?`ui-table-row`:`ui-table-row ui-table-row-link`,style:a,onClick:n,children:i}):(0,A.jsx)(Wi,{to:t,className:`ui-table-row ui-table-row-link`,style:a,children:i})}var ph=`pinecall.pane.`;function mh(e){try{let t=Number(window.localStorage.getItem(ph+e));return Number.isFinite(t)&&t>0?t:null}catch{return null}}function hh(e,t){try{window.localStorage.setItem(ph+e,String(Math.round(t)))}catch{}}function gh(e){try{window.localStorage.removeItem(ph+e)}catch{}}var _h=(e,t,n)=>Math.min(n,Math.max(t,e));function vh({name:e,initial:t,min:n,max:r,side:i}){let[a,o]=(0,D.useState)(()=>_h(mh(e)??t,n,r)),s=(0,D.useRef)(null),c=(0,D.useCallback)(e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={x:e.clientX,width:a}},[a]),l=(0,D.useCallback)(e=>{if(s.current===null)return;let t=e.clientX-s.current.x;o(_h(s.current.width+(i===`right`?-t:t),n,r))},[i,n,r]),u=(0,D.useCallback)(()=>{s.current!==null&&(s.current=null,hh(e,a))},[e,a]),d=(0,D.useCallback)(()=>{gh(e),o(t)},[e,t]);return{width:a,style:{"--pane":`${String(a)}px`},handle:(0,A.jsx)(`div`,{className:i===`right`?`ui-resize ui-resize-right`:`ui-resize ui-resize-left`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Drag to resize. Double-click to reset.`,title:`Drag to resize · double-click to reset`,onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,onDoubleClick:d})}}function yh({label:e,tabs:t,on:n,onPick:r}){return(0,A.jsx)(`nav`,{className:`ui-tabs`,"aria-label":e,children:t.map(e=>(0,A.jsxs)(`button`,{type:`button`,className:n===e.tab?`ui-tab ui-tab-on`:`ui-tab`,"aria-current":n===e.tab?`page`:void 0,onClick:()=>r(e.tab),children:[e.name,e.mark]},e.tab))})}function bh({said:e}){return(0,A.jsxs)(am,{foot:(0,A.jsxs)(A.Fragment,{children:[`Your sandbox is on your machine: `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall serve`}),` in your project's folder.`]}),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`No production access`}),(0,A.jsx)(`p`,{className:`login-lede`,children:e}),(0,A.jsx)(Bm,{onClick:()=>{Em(),window.location.assign(`/`)},children:`Sign in as somebody else`})]})}var xh=z({org:P(),slug:P().nullish(),key_id:P(),label:P().nullish(),env:mp([`production`,`sandbox`]),scopes:R(P()),subject:P().nullish(),name:P().nullish(),operator:L().optional(),visiting:L().optional(),production:L()}),Sh=(0,D.createContext)(null);function Ch({children:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let e=!1;return r(null),a(null),k(t,`/v1/whoami`).then(t=>{e||r(xh.parse(t))},t=>{!e&&t instanceof na&&t.status===403&&a(t.message)}),()=>{e=!0}},[t]),i===null?(0,A.jsx)(Sh,{value:n,children:e}):(0,A.jsx)(bh,{said:i})}function wh(){return(0,D.useContext)(Sh)}function Th(e){return e.slug??e.org}function Eh(){return wh()?.scopes??null}var Dh=(0,D.createContext)(null);function Oh({value:e,children:t}){return(0,A.jsx)(Dh,{value:e,children:t})}function kh(){let e=(0,D.useContext)(Dh);if(e===null)throw Error(`the console was mounted without a world`);return e}var Ah=`ready`,jh=`no plugin`,Mh=`no key`,Nh=`its own`,Ph=z({name:P(),does:R(mp([`llm`,`stt`,`tts`])),aliases:R(P()),note:P(),standing:mp([Ah,jh,Mh,Nh]),ready:L(),env:P().nullable(),extra:P()}),Fh=[`llm`,`stt`,`tts`],Ih=z({providers:R(Ph),defaults:fp(P(),P()),voices:R(P())});async function Lh(e){return Ih.parse(await k(e,`/v1/providers`))}function Rh(e,t){return e.filter(e=>e.does.includes(t)).sort((e,t)=>Number(t.ready)-Number(e.ready)||e.name.localeCompare(t.name))}function zh(e){return e.standing===`no plugin`?`the box needs livekit-agents[${e.extra}]`:e.standing===`no key`?`the box needs ${e.env??`a credential`}`:e.standing===`its own`?`its credentials are its own: a profile, a pair, not one key`:e.note||`ready on this box`}var Bh=[`everything`,`mine`,`the team's`];function Vh(e,t){let n=e.holder?.holder;return n!=null&&n!==t}function Hh(e,t,n){if(t===`everything`)return e;let r=t===`the team's`;return e.filter(e=>Vh(e,n)===r)}function Uh(e,t){let n=new Map;for(let r of e){let e=n.get(r.slug);(e===void 0||Vh(e,t)&&!Vh(r,t))&&n.set(r.slug,r)}return[...n.values()]}function Wh(e){let t=e.holder;return t==null?`the org's`:t.name??t.holder??`the org's`}function Gh(e){return e?.subject??null}var Kh=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function qh(e){if(e.started_at===null||e.ended_at===null)return`—`;let t=Math.max(0,Math.round(e.ended_at-e.started_at));return`${Math.floor(t/60)}m ${String(t%60).padStart(2,`0`)}s`}function Jh(e,t=Date.now()/1e3){if(e===null)return`—`;let n=Math.max(0,Math.round(t-e)),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=String(n%60).padStart(2,`0`);return r>0?`${r}:${String(i).padStart(2,`0`)}:${a}`:`${i}:${a}`}function Yh(e){return e==null?`—`:`${e.toFixed(4)} €`}function Xh(e){return`€${e.toFixed(2)}`}function Zh(e){return e===null?`—`:new Date(e*1e3).toISOString().slice(11,19)}function Qh(e){if(e===null)return`—`;let t=new Date(e*1e3);return`${t.getUTCDate()} ${Kh[t.getUTCMonth()]}, ${t.toISOString().slice(11,16)}`}function $h(e){if(e===null)return`—`;let t=new Date(e*1e3);return`${t.getUTCDate()} ${Kh[t.getUTCMonth()]}`}function eg(e,t=Date.now()/1e3){if(e===null)return`—`;let n=Math.max(0,t-e);return n<60?`just now`:n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<172800?`Yesterday`:$h(e)}function tg(e){return new Date(e*1e3).toISOString().slice(0,10)}function ng(e=Date.now()/1e3){return{today:tg(e),yesterday:tg(e-86400)}}function rg(e,t){return e.filter(e=>e.started_at!==null&&tg(e.started_at)===t)}function ig(e,t){if(t===0)return null;let n=Math.round((e-t)/t*100);return n===0?{text:`steady`,tone:`flat`}:n>0?{text:`+${n}%`,tone:`up`}:{text:`−${Math.abs(n)}%`,tone:`down`}}function ag(e){return`${Math.round(e*100)}%`}function og(e){if(e==null)return`—`;let t=e.replace(/[^\d]/g,``);return e.startsWith(`+1`)&&t.length===11?`+1 (${t.slice(1,4)}) ${t.slice(4,7)}-${t.slice(7)}`:e.startsWith(`+34`)&&t.length===11?`+34 ${t.slice(2,5)} ${t.slice(5,8)} ${t.slice(8)}`:e.startsWith(`+598`)&&t.length===11?`+598 ${t.slice(3,5)} ${t.slice(5,8)} ${t.slice(8)}`:e}function sg(e){let t=e.caller?.name;if(t!=null&&t!==``)return t;let n=e.direction===`outbound`?e.to:e.from;return n==null?`—`:n.startsWith(`+`)?og(n):n}var cg=np({day:P(),conversations:z({today:F(),yesterday:F()}),resolved_rate:F().nullable(),median_e2e_s:F().nullable(),spend_eur:F(),channels:z({phone:F(),web:F(),whatsapp:F()}),sessions_total:F(),live:F(),agents:R(z({slug:P(),today:F(),score:F().nullable()})),budget:z({limit_eur:F().nullable(),spent_eur_month:F()})}),lg=15e3;function ug(e){let t=j(),[n,r]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i,a=async()=>{try{let i=cg.parse(await k(t,`/v1/insights`,e===void 0?{}:{day:e}));n||r(i)}catch(e){e instanceof na&&[403,404].includes(e.status)&&(window.clearInterval(i),n||r(null))}};return a(),i=window.setInterval(()=>void a(),lg),()=>{n=!0,window.clearInterval(i)}},[t,e]),n}function dg(){let e=j(),[t,n]=(0,D.useState)(fm===`hosted`&&null);return(0,D.useEffect)(()=>{if(fm!==`hosted`)return;let t=!1;return fetch(la(e,`/v1/ops/whoami`),{headers:ra(e)}).then(e=>{t||n(e.ok)},()=>{t||n(!1)}),()=>{t=!0}},[e]),t}var fg=B({seq:I(),ts:F(),call:P().nullable(),agent:P(),type:P(),ephemeral:L(),data:fp(P(),Zf())});B({type:P(),agent:P(),call:P().nullable(),id:P().nullish(),data:fp(P(),Zf())});var pg=mp([`phone`,`web`,`whatsapp`]),mg=mp([`inbound`,`outbound`]),hg=mp([`production`,`sandbox`]),gg=mp([`chat.roster`,`chat.start`,`chat.say`,`chat.end`,`simulate.roster`,`simulate.start`,`goldens.roster`,`goldens.run`,`knowledge.roster`,`knowledge.push`,`knowledge.eval`,`memory.roster`,`memory.eval`,`memory.extraction`,`promote.roster`,`promote.write`,`drift.read`,`reproductions.roster`,`reproductions.read`]),_g=mp([`caller_hung_up`,`agent_hung_up`,`supervisor_ended`,`transferred`,`no_answer`,`busy`,`dial_failed`,`timeout`,`drained`,`app_detached`,`error`]),vg=mp([`caller`,`agent`,`supervisor`,`platform`]),yg=mp([`held`,`broken`,`deferred`,`skipped`]),bg=mp([`cold`,`warm`]),xg=mp([`static`,`dynamic`]),Sg=mp([`retrieved`,`tool`]),Cg=mp([`recall`,`search`]),wg=B({name:P().regex(/^[a-z][a-z0-9_]*$/),region:xg}),Tg=mp([`listening`,`speaking`,`away`]),Eg=mp([`initializing`,`idle`,`listening`,`thinking`,`speaking`]),Dg=mp([`caller`,`agent`,`supervisor`,`listener`,`sip`]),Og=mp([`audio`,`video`,`screen`]),kg=mp([`microphone`,`camera`,`screen_share`,`screen_share_audio`,`unknown`]),Ag=mp([`app`,`participant`]),jg=mp([`public`,`tenant`,`pii`]);mp([`public`,`tenant`]);var Mg=B({id:P().nullish(),phone:P().nullish(),name:P().nullish(),email:P().nullish(),external_id:P().nullish()}),Ng=B({channel:pg,number:P().nullable(),label:P().nullish()}),Pg=B({id:P(),name:P().nullish()}),Fg=B({name:P(),description:P(),parameters:fp(P(),Zf()),side_effect:mp([`read`,`write`,`irreversible`]).nullish(),confirm:P().nullish(),pii:R(P()).nullish(),timeout_s:F().nullish()}),Ig=B({call_id:P(),name:P(),output:Zf().nullish(),error:P().nullish(),summary:P().nullish(),duration_s:F().nullish()}),Lg=B({id:P().nullish(),text:P(),category:P().nullish(),score:F().nullish(),source:P().nullish()}),Rg=B({op:mp([`recall`,`remember`,`forget`]),contact:P().nullish(),query:P().nullish(),facts:R(Lg),took_ms:F()}),zg=B({id:P(),path:P(),heading:P().nullish(),score:F(),excerpt:P().nullish()}),Bg=B({currency:gp(`EUR`),usd_to_eur:F(),as_of:P()}),Vg=B({provider:P(),model:P(),unit:mp([`input_tokens`,`cached_input_tokens`,`cache_creation_tokens`,`output_tokens`,`characters`,`audio_seconds`,`requests`,`session_seconds`]),quantity:F(),unit_price_usd:F(),eur:F()}),Hg=B({provider:P(),model:P()}),Ug=B({eur:F(),rate:Bg,rows:R(Vg),unpriced:R(Hg)}),Wg=B({name:P().nullish(),provider:P().nullish(),model:P().nullish(),voice_id:P().nullish()}),Gg=B({provider:P(),model:P(),temperature:F().nullish()}),Kg=B({min_interruption_words:I().nullish(),endpointing_ms:I().nullish()}),qg=B({word:P(),spoken:P()}),Jg=B({name:P(),visibility:jg}),Yg=B({name:P(),from:R(Ag)}),Xg=B({path:P(),text:P(),mode:mp([`retrieved`,`whole`]).nullish()}),Zg=B({base:P(),mode:Sg.nullish(),k:I().nullish(),min_score:F().nullish()}),Qg=B({say:P().nullish(),reply:P().nullish(),allow_interruptions:L().nullish()}),$g=B({when:P().nullish()}),e_=B({remember:R(P()).nullish(),forget:R(P()).nullish()}),t_=B({prompt:R(wg).nullish(),language:P().nullish(),greeting:Qg.nullish(),voice:Wg.nullish(),llm:Gg.nullish(),stt:Gg.nullish(),turn:Kg.nullish(),says:R(qg).nullish(),hears:R(P()).nullish(),knowledge:Xg.nullish(),docs:Zg.nullish(),memory:e_.nullish(),hangup:$g.nullish(),tools:R(Fg).nullish(),uses_knowledge:L().nullish(),state_fields:R(Jg).nullish(),events:R(Yg).nullish()}),n_=op(`verb`,[B({verb:gp(`say`),text:P()}),B({verb:gp(`whisper`),text:P()}),B({verb:gp(`takeover`)}),B({verb:gp(`release`)}),B({verb:gp(`transfer`),to:P(),mode:bg}),B({verb:gp(`end`),reason:P().nullish()})]);B({config:t_}),B({routes:R(Ng),sdk:P().nullish(),host:P().nullish(),takes_unclaimed:L().nullish()}),B({instructions:P(),allow_interruptions:L().nullish()}),B({text:P(),allow_interruptions:L().nullish()}),B({to:P(),from:P().nullish(),caller:Mg.nullish(),metadata:fp(P(),Zf()).nullish()}),B({digits:P()}),B({name:P(),data:fp(P(),Zf())}),B({reason:P().nullish()}),B({}),B({name:P(),data:fp(P(),Zf())}),B({}),B({to:P(),mode:bg}),B({}),B({});var r_=B({status:I(),detail:P()});B({id:P(),result:fp(P(),Zf()).nullish(),refused:r_.nullish()}),B({identity:P()}),B({identity:P()}),B({}),B({name:P(),text:P()}),B({to:P(),kind:mp([`sip`,`participant`])}),B({topic:P(),data:fp(P(),Zf()),to:P().nullish()}),B({state:fp(P(),Zf()).nullish(),config:t_.nullish()}),B({state:fp(P(),Zf()),changed:R(P()).nullish()}),B({by:Pg,verb:n_}),B({tools:R(Fg)});var i_=B({model_name:P().nullable().nullish(),model_provider:P().nullable().nullish()}),a_=B({type:gp(`llm_metrics`),label:P(),request_id:P(),timestamp:F(),duration:F(),ttft:F(),cancelled:L(),completion_tokens:I(),prompt_tokens:I(),prompt_cached_tokens:I(),cache_creation_tokens:I().nullish(),reasoning_tokens:I().nullish(),total_tokens:I(),tokens_per_second:F(),speech_id:P().nullable().nullish(),metadata:i_.nullable().nullish()}),o_=B({type:gp(`stt_metrics`),label:P(),request_id:P(),timestamp:F(),duration:F(),audio_duration:F(),input_tokens:I().nullish(),output_tokens:I().nullish(),streamed:L(),acquire_time:F().nullish(),connection_reused:L().nullish(),metadata:i_.nullable().nullish()}),s_=B({type:gp(`tts_metrics`),label:P(),request_id:P(),timestamp:F(),ttfb:F(),duration:F(),audio_duration:F(),cancelled:L(),characters_count:I(),input_tokens:I().nullish(),output_tokens:I().nullish(),streamed:L(),acquire_time:F().nullish(),connection_reused:L().nullish(),segment_id:P().nullable().nullish(),speech_id:P().nullable().nullish(),metadata:i_.nullable().nullish()}),c_=B({type:gp(`vad_metrics`),label:P(),timestamp:F(),idle_time:F(),inference_duration_total:F(),inference_count:I(),metadata:i_.nullable().nullish()}),l_=B({type:gp(`eou_metrics`),timestamp:F(),end_of_utterance_delay:F(),transcription_delay:F(),on_user_turn_completed_delay:F(),speech_id:P().nullable().nullish(),metadata:i_.nullable().nullish()}),u_=B({type:gp(`eot_inference_metrics`),timestamp:F(),total_duration:F(),detection_delay:F(),prediction_duration:F(),num_requests:I().nullish(),metadata:i_.nullable().nullish()}),d_=B({type:gp(`interruption_metrics`),timestamp:F(),total_duration:F(),prediction_duration:F(),detection_delay:F(),num_interruptions:I(),num_backchannels:I(),num_requests:I(),metadata:i_.nullable().nullish()}),f_=B({audio_tokens:I().nullish(),text_tokens:I().nullish(),image_tokens:I().nullish()}),p_=B({audio_tokens:I().nullish(),text_tokens:I().nullish(),image_tokens:I().nullish(),cached_tokens:I().nullish(),cached_tokens_details:f_.nullable().nullish()}),m_=B({text_tokens:I().nullish(),audio_tokens:I().nullish(),image_tokens:I().nullish()}),h_=B({type:gp(`realtime_model_metrics`),label:P().nullish(),request_id:P(),timestamp:F(),duration:F().nullish(),session_duration:F().nullish(),ttft:F().nullish(),cancelled:L().nullish(),input_tokens:I().nullish(),output_tokens:I().nullish(),total_tokens:I().nullish(),tokens_per_second:F().nullish(),input_token_details:p_,output_token_details:m_,acquire_time:F().nullish(),connection_reused:L().nullish(),metadata:i_.nullable().nullish()}),g_=B({type:gp(`avatar_metrics`),timestamp:F(),playback_latency:F().nullish(),session_started_time:F().nullable().nullish(),avatar_joined_time:F().nullable().nullish(),metadata:i_.nullable().nullish()}),__=B({model_name:P().nullish(),model_provider:P().nullish()}),v_=B({started_speaking_at:F().nullish(),stopped_speaking_at:F().nullish(),transcription_delay:F().nullish(),end_of_turn_delay:F().nullish(),on_user_turn_completed_delay:F().nullish(),stt_metadata:__.nullish()}),y_=B({started_speaking_at:F().nullish(),stopped_speaking_at:F().nullish(),llm_node_ttft:F().nullish(),llm_node_tps:F().nullish(),llm_node_ttfs:F().nullish(),tts_node_ttfb:F().nullish(),playback_latency:F().nullish(),e2e_latency:F().nullish(),provider_request_ids:R(P()).nullish(),llm_metadata:__.nullish(),tts_metadata:__.nullish()}),b_=op(`type`,[B({type:gp(`llm_usage`),provider:P(),model:P(),input_tokens:I().nullish(),input_cached_tokens:I().nullish(),input_cache_creation_tokens:I().nullish(),input_audio_tokens:I().nullish(),input_cached_audio_tokens:I().nullish(),input_text_tokens:I().nullish(),input_cached_text_tokens:I().nullish(),input_image_tokens:I().nullish(),input_cached_image_tokens:I().nullish(),output_tokens:I().nullish(),output_audio_tokens:I().nullish(),output_text_tokens:I().nullish(),output_reasoning_tokens:I().nullish(),session_duration:F().nullish()}),B({type:gp(`tts_usage`),provider:P(),model:P(),input_tokens:I().nullish(),output_tokens:I().nullish(),characters_count:I().nullish(),audio_duration:F().nullish()}),B({type:gp(`stt_usage`),provider:P(),model:P(),input_tokens:I().nullish(),output_tokens:I().nullish(),audio_duration:F().nullish()}),B({type:gp(`interruption_usage`),provider:P(),model:P(),total_requests:I().nullish()}),B({type:gp(`eot_usage`),provider:P(),model:P(),total_requests:I().nullish()})]),x_=mp([`idle`,`ringing`,`dialing`,`active`,`ended`]),S_=op(`role`,[B({role:gp(`user`),speech_id:P(),item_id:P().nullish(),text:P(),language:P().nullish(),transcript_confidence:F().nullish(),metrics:v_}),B({role:gp(`agent`),speech_id:P(),item_id:P().nullish(),text:P(),interrupted:L(),metrics:y_})]),C_=B({llm:R(a_),stt:R(o_),tts:R(s_),vad:R(c_),eou:R(l_),eot:R(u_),interruption:R(d_),realtime:R(h_),avatar:R(g_)}),w_=B({call_id:P(),name:P(),arguments:fp(P(),Zf()),speech_id:P().nullish(),status:mp([`running`,`done`,`failed`]),output:Zf().nullish(),error:P().nullish(),summary:P().nullish(),duration_s:F().nullish(),seq:I()}),T_=B({hash:P(),chars:I(),seq:I()}),E_=fp(P(),T_),D_=B({tool:P(),call_id:P(),audience:P(),phrase:P(),status:mp([`pending`,`granted`,`declined`]),said:P().nullish(),reason:P().nullish()}),O_=B({active:L(),by:Pg.nullable()}),k_=B({to:P(),mode:bg,status:mp([`requested`,`done`,`failed`]),by:mp([`agent`,`supervisor`])}),A_=B({user:P().nullable(),agent:P().nullable()}),j_=B({from_seq:I(),to_seq:I()}),M_=B({seq:I(),code:P(),message:P()}),N_=B({identity:P(),kind:Dg,name:P().nullish(),joined_at:F(),speaking:L(),attributes:fp(P(),Zf())}),P_=B({name:P(),sid:P(),participants:R(N_),caller:P().nullable()}),F_=B({seq:I(),name:P(),source:Ag,identity:P().nullish()}),I_=B({seq:I(),name:P(),data:fp(P(),Zf())}),L_=B({seq:I(),agent:P(),call:P().nullable(),status:x_,channel:pg.nullable(),direction:mg.nullable(),from:P().nullable(),to:P().nullable(),caller:Mg.nullable(),room:P_.nullable(),started_at:F().nullable(),ended_at:F().nullable(),end_reason:_g.nullable(),outcome:P().nullable(),user_state:Tg.nullable(),agent_state:Eg.nullable(),live:A_,turns:R(S_),metrics:C_,tools:R(w_),app_state:fp(P(),Zf()),events:R(F_),prompt:E_,tools_visible:R(P()),confirms:R(D_),memory:R(Rg),sources:R(zg),handoff:O_,held:L(),muted:L(),transfer:k_.nullable(),usage:R(b_),cost:Ug.nullable(),routes:R(Ng),gaps:R(j_),errors:R(M_),custom:R(I_)}),R_=B({changed:R(P())}),z_=B({app:P(),env:hg,left:L()}),B_=B({routes:R(Ng),app:P(),sdk:P().nullish(),env:hg.nullish()}),V_=B({state:Eg}),H_=B({speech_id:P(),text:P(),final:L(),start:F().nullish(),end:F().nullish()}),U_=B({channel:pg,from:P(),to:P(),run:P().nullable().nullish(),caller:Mg.nullable(),external_id:P().nullish(),asked_by:P().nullish()}),W_=B({reason:_g,ended_by:vg,ended_at:F(),duration_s:F()}),G_=B({held:L(),muted:L()}),K_=B({channel:pg,from:P(),to:P(),route:Ng,run:P().nullable().nullish(),caller:Mg.nullable(),external_id:P().nullish()}),q_=B({seqs:R(I()),said:P().nullish()}),J_=B({name:P(),verdict:yg,criteria:P(),reason:P(),evidence:q_}),Y_=B({passed:L().nullish(),not_judged:P().nullish(),judges:R(J_),panel:R(P()).nullish(),judge_calls:I(),judge_cost_eur:F().nullish()}),X_=B({channel:pg,direction:mg,from:P(),to:P(),run:P().nullable().nullish(),caller:Mg.nullable(),started_at:F(),env:hg.nullish()}),Z_=B({reason:_g,outcome:P(),duration_s:F(),turns:I(),usage:R(b_),cost:Ug,recording:P().nullish()}),Q_=B({to:P(),mode:bg,ok:L(),error:P().nullish()}),$_=B({channel:pg,number:P(),via:mp([`overflow`,`widget`]),call:P().nullable(),contact:Mg.nullable()}),ev=B({tool:P(),call_id:P(),audience:P(),said:P().nullish(),reason:mp([`no`,`timeout`,`changed`,`cancelled`])}),tv=B({tool:P(),call_id:P(),audience:P(),said:P(),ttl_s:I()}),nv=B({tool:P(),call_id:P(),arguments:fp(P(),Zf()),audience:P(),phrase:P(),ttl_s:I()}),rv=B({org:P(),quota:mp([`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`]),used:F(),limit:I()}),iv=B({name:P(),data:fp(P(),Zf())}),av=B({id:P(),verb:gg,data:fp(P(),Zf())}),ov=B({query:P(),sources:R(zg),took_ms:F(),speech_id:P().nullish()}),sv=B({code:P(),message:P(),command:P().nullish(),id:P().nullish(),recoverable:L()}),cv=B({channel:pg,workers:I(),active:I()}),lv=B({seq:I()}),uv=B({from_seq:I(),to_seq:I(),snapshot:L_.nullable()}),dv=B({ops:R(Rg),speech_id:P().nullish()}),fv=B({ts:F()}),pv=B({name:P(),hash:P(),chars:I()}),mv=op(`kind`,[B({kind:gp(`tool`),tool:P(),call_id:P()}),B({kind:gp(`event`),name:P(),seq:I()})]),hv=B({state:fp(P(),Zf()),changed:R(P()),cause:mv.nullish()}),gv=B({by:Pg,reason:P().nullish()}),_v=B({by:Pg}),vv=B({by:Pg,text:P()}),yv=B({by:Pg}),bv=B({by:Pg,to:P(),mode:bg}),xv=B({by:Pg,text:P()}),Sv=B({call_id:P(),name:P(),arguments:fp(P(),Zf()),speech_id:P().nullish()}),Cv=B({visible:R(P())}),wv=B({speech_id:P(),item_id:P().nullish(),text:P(),interrupted:L(),metrics:y_}),Tv=B({speech_id:P(),item_id:P().nullish(),text:P(),language:P().nullish(),transcript_confidence:F().nullish(),metrics:v_}),Ev=B({state:Tg}),Dv=B({text:P(),final:L(),language:P().nullish(),confidence:F().nullish()}),Ov=B({name:P(),sid:P(),channel:pg}),kv=B({identity:P(),kind:Dg,name:P().nullish(),attributes:fp(P(),Zf())}),Av=B({identity:P(),reason:P()}),jv=B({identity:P(),speaking:L()}),Mv=B({identity:P(),kind:Og,source:kg}),Nv=B({identity:P(),kind:Og,source:kg}),Pv={"agent.configured":R_,"agent.detached":z_,"agent.registered":B_,"agent.state":V_,"agent.transcript":H_,"call.dialing":U_,"call.ended":W_,"call.line":G_,"call.ringing":K_,"call.score":Y_,"call.started":X_,"call.summary":Z_,"call.transferred":Q_,"callback.requested":$_,"confirm.declined":ev,"confirm.granted":tv,"confirm.request":nv,"credits.exhausted":rv,custom:iv,"dev.request":av,"docs.sources":ov,error:sv,"event.received":B({name:P(),data:fp(P(),Zf()),source:Ag,identity:P().nullish()}),"fleet.full":cv,"log.caught_up":lv,"log.gap":uv,"memory.ops":dv,"metrics.avatar":g_,"metrics.eot":u_,"metrics.eou":l_,"metrics.interruption":d_,"metrics.llm":a_,"metrics.realtime":h_,"metrics.stt":o_,"metrics.tts":s_,"metrics.vad":c_,"participant.joined":kv,"participant.left":Av,"participant.speaking":jv,pong:fv,"prompt.changed":pv,"room.opened":Ov,"room.sent":B({topic:P(),to:P().nullish(),bytes:I()}),"state.changed":hv,"supervisor.ended":gv,"supervisor.released":_v,"supervisor.said":vv,"supervisor.took_over":yv,"supervisor.transferred":bv,"supervisor.whispered":xv,"tool.call":Sv,"tool.result":Ig,"tools.changed":Cv,"track.published":Mv,"track.unpublished":Nv,"turn.agent":wv,"turn.user":Tv,"user.state":Ev,"user.transcript":Dv},Fv=`call.score`,Iv=class extends Error{name=`ProtocolError`};function Lv(e){return fg.parse(e)}function Rv(e){if(!zv(e.type))throw new Iv(`unknown event type: ${e.type}`);let t=Pv[e.type].parse(e.data);return{type:e.type,data:t}}function zv(e){return Object.hasOwn(Pv,e)}B({state:L_,last_seq:I(),live:L()});var Bv=B({entries:R(fg),live:L(),next:I().nullable()}),Vv=B({held:I(),judged:I(),passed:L(),reason:P().nullable()}),Hv=mp([`escalated`,`low_score`,`promise`]),Uv=B({call:P(),agent:P(),live:L(),last_seq:I(),status:x_,channel:pg.nullable(),direction:mg.nullable(),from:P().nullable(),to:P().nullable(),caller:Mg.nullable(),started_at:F().nullable(),ended_at:F().nullable(),end_reason:_g.nullable(),outcome:P().nullable(),cost:Ug.nullable(),score:Vv.nullable().nullish(),flags:R(Hv).nullish()}),Wv=B({calls:R(Uv),total:I().nullable().nullish(),next:P().nullable().nullish()}),Gv=B({today:I(),yesterday:I()}),Kv=B({phone:I(),web:I(),whatsapp:I()}),qv=B({slug:P(),today:I(),score:F().nullable()}),Jv=B({limit_eur:F().nullable(),spent_eur_month:F()});B({day:P(),timezone:P(),conversations:Gv,resolved_rate:F().nullable(),median_e2e_s:F().nullable(),spend_eur:F(),channels:Kv,sessions_total:I(),live:I(),agents:R(qv),budget:Jv}),B({on:L(),ceiling_eur:F().nullable()}),B({on:L()});var Yv=mp([`in`,`out`,`call`]),Xv=B({text:P().nullable(),at:F(),kind:Yv});B({threads:R(B({contact:P(),name:P().nullable(),channel_last:pg,last:Xv,unread:I(),calls:I()})),next:P().nullable()});var Zv=B({kind:Yv,text:P().nullable(),at:F(),call:P(),channel:pg,duration_s:F().nullable().nullish(),answered:L().nullish()});B({contact:P(),name:P().nullable(),messages:R(Zv)}),B({text:P()}),B({contact:P(),call:P()}),B({facts:R(B({id:P(),contact:P(),text:P(),category:P().nullable(),written_at:F()})),next:P().nullable()}),B({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()}),B({configured:L(),issuer:P().nullable(),client_id:P().nullable(),domains:R(P()),role:P().nullable(),required:L(),redirect_uri:P()}),B({issuer:P(),client_id:P(),client_secret:P(),domains:R(P()),role:P().nullable().nullish(),required:L().nullish()}),B({configured:L(),host:P().nullable(),port:I().nullable(),security:P().nullable(),username:P().nullable(),from:P().nullable(),verified_at:P().nullable(),last_error:P().nullable()}),B({host:P(),port:I(),security:mp([`starttls`,`tls`,`none`]).nullish(),username:P().nullish(),password:P().nullish(),from:P()}),B({configured:L(),source:P().nullable(),host:P().nullable(),port:I().nullable(),security:P().nullable(),username:P().nullable(),from:P().nullable(),verified_at:P().nullable(),last_error:P().nullable()}),B({name:P(),logo_url:P().nullable(),accent:P()}),B({name:P().nullable().nullish(),logo_url:P().nullable().nullish(),accent:P().nullable().nullish()}),B({google:B({configured:L(),client_id:P().nullable(),redirect_uri:P()})}),B({client_id:P(),client_secret:P()}),B({sent:L(),error:P().nullable()}),B({orgs:R(B({org:P(),slug:P(),name:P()}))});var Qv=B({holder:P().nullable(),name:P().nullable()}),$v=B({agents:R(B({slug:P(),channels:R(pg),holder:Qv.nullish()}))}),ey=B({apps:R(B({app:P(),agents:R(P()),env:hg,host:P().nullable(),address:P().nullable(),sdk:P().nullable(),holder:Qv.nullable(),connected_at:F()}))}),ty=B({app:P(),stopped:L()});B({agent:P(),env:hg,held:L(),holding:Qv.nullish(),yours:L(),waiting:R(Qv),calling:R(P())}),B({files:R(Xg)}),B({questions:R(B({asks:P(),expects:P()})),k:I().nullish()});var ny=B({asks:P(),expects:P(),found:R(P())}),ry=B({base:P(),model:P(),questions:I(),k:I(),recall_at_k:F(),ndcg_at_10:F(),took_ms:F(),misses:R(ny)}),iy=B({base:P(),chunks:I(),took_ms:F(),whole_tokens:I().nullish(),notice:P().nullable().nullish()}),ay=B({bases:R(B({base:P(),chunks:I(),model:P(),pushed_at:F()}))}),oy=B({facts:R(B({id:P().nullish(),text:P(),category:P().nullish(),source:P().nullish(),valid_from:F(),invalidated_at:F().nullable()}))}),sy=B({forgotten:I()});B({questions:R(B({holds:R(P()),asks:P(),expects:R(P())})),k:I().nullish()});var cy=B({asks:P(),missing:R(P()),found:R(P())}),ly=B({model:P(),questions:I(),k:I(),recall_at_k:F(),ndcg_at_10:F(),took_ms:F(),misses:R(cy)}),uy=B({writes:R(P()).nullish(),never:R(P()).nullish(),never_says:R(P()).nullish(),invalidates:R(P()).nullish()});B({cases:R(B({name:P(),said:R(up([P(),P()])),holds:R(P()).nullish(),plants:R(P()).nullish(),channel:pg.nullish(),expect:uy.nullish()}))});var dy=B({check:P(),detail:P()}),fy=B({name:P(),held:L(),wrote:R(P()).nullish(),refused:R(P()).nullish(),broke:R(dy).nullish()}),py=B({agent:P(),model:P(),cases:I(),held:I(),took_ms:F(),results:R(fy)});B({tool:Cg,input:fp(P(),Zf()),speech_id:P().nullish()}),B({output:fp(P(),Zf()),took_ms:F()}),B({chunks:R(B({path:P(),heading:P().nullable(),text:P()}))}),B({ops:I(),took_ms:F()}),B({call:P(),agent:P(),to:P(),from:P(),env:hg});var my=B({dial_anywhere:L(),per_minute:I(),per_day:I(),max_duration_s:I()});B({ready:L(),kind:P().nullable(),from_numbers:R(P()),steps_missing:R(P()),guards:my}),B({steps:R(P()),dry_run:L(),ready:L(),trunk:P().nullish(),address:P().nullish()});var hy=B({voice:P().nullish(),tts:P().nullish(),tts_model:P().nullish(),stt:P().nullish(),llm:P().nullish(),greeting:Qg.nullish(),hangup:$g.nullish(),turn:Kg.nullish(),memory:e_.nullish(),knowledge:R(Zg).nullish()}),gy=B({holder:P(),version:I(),author:P(),note:P().nullable(),set_at:F(),config:hy}),_y=B({world:hg,yours:gy.nullable(),team:gy.nullable(),production:gy.nullable()});B({config:hy,if_version:I().nullable().nullish(),note:P().nullable().nullish(),team:L().nullish()});var vy=B({world:hg,holder:P(),rows:R(gy)});B({ours:gy.nullable(),theirs:gy.nullable(),changed:R(P())}),B({version:I(),team:L().nullish()});var yy=B({said:R(qg),heard:R(P())}),by=B({holder:P(),version:I(),author:P(),note:P().nullable(),set_at:F(),lexicon:yy}),xy=B({world:hg,yours:by.nullable(),team:by.nullable(),production:by.nullable()});B({lexicon:yy,if_version:I().nullable().nullish(),note:P().nullable().nullish(),team:L().nullish()}),B({world:hg,holder:P(),rows:R(by)}),B({config_version:I().nullable(),lexicon_version:I().nullable(),config:gy.nullable(),lexicon:by.nullable()}),B({bases:R(B({base:P(),agents:R(P())}))});var Sy={acquire_time:`s`,audio_duration:`s`,audio_tokens:`tokens`,avatar_joined_time:`unix s`,cache_creation_tokens:`tokens`,cached_tokens:`tokens`,cached_tokens_details:`object`,cancelled:`flag`,characters_count:`chars`,completion_tokens:`tokens`,connection_reused:`flag`,detection_delay:`s`,duration:`s`,e2e_latency:`s`,end_of_turn_delay:`s`,end_of_utterance_delay:`s`,idle_time:`s`,image_tokens:`tokens`,inference_count:`count`,inference_duration_total:`s`,input_audio_tokens:`tokens`,input_cache_creation_tokens:`tokens`,input_cached_audio_tokens:`tokens`,input_cached_image_tokens:`tokens`,input_cached_text_tokens:`tokens`,input_cached_tokens:`tokens`,input_image_tokens:`tokens`,input_text_tokens:`tokens`,input_token_details:`object`,input_tokens:`tokens`,label:`name`,llm_metadata:`object`,llm_node_tps:`tokens/s`,llm_node_ttfs:`s`,llm_node_ttft:`s`,metadata:`object`,model:`name`,model_name:`name`,model_provider:`name`,num_backchannels:`count`,num_interruptions:`count`,num_requests:`count`,on_user_turn_completed_delay:`s`,output_audio_tokens:`tokens`,output_reasoning_tokens:`tokens`,output_text_tokens:`tokens`,output_token_details:`object`,output_tokens:`tokens`,playback_latency:`s`,prediction_duration:`s`,prompt_cached_tokens:`tokens`,prompt_tokens:`tokens`,provider:`name`,provider_request_ids:`ids`,reasoning_tokens:`tokens`,request_id:`id`,segment_id:`id`,session_duration:`s`,session_started_time:`unix s`,speech_id:`id`,started_speaking_at:`unix s`,stopped_speaking_at:`unix s`,streamed:`flag`,stt_metadata:`object`,text_tokens:`tokens`,timestamp:`unix s`,tokens_per_second:`tokens/s`,total_duration:`s`,total_requests:`count`,total_tokens:`tokens`,transcription_delay:`s`,ttfb:`s`,ttft:`s`,tts_metadata:`object`,tts_node_ttfb:`s`,type:`tag`};function Cy(e){let t=wy();for(let n of e)t=Dy(t,n);return t}function wy(){return{seq:0,agent:``,call:null,status:`idle`,channel:null,direction:null,from:null,to:null,caller:null,room:null,started_at:null,ended_at:null,end_reason:null,outcome:null,user_state:null,agent_state:null,live:{user:null,agent:null},turns:[],metrics:{llm:[],stt:[],tts:[],vad:[],eou:[],eot:[],interruption:[],realtime:[],avatar:[]},tools:[],app_state:{},events:[],prompt:{},tools_visible:[],confirms:[],memory:[],sources:[],handoff:{active:!1,by:null},held:!1,muted:!1,transfer:null,usage:[],cost:null,routes:[],gaps:[],errors:[],custom:[]}}var Ty=`unreadable`;function Ey(e,t,n){let r=n instanceof Error?n.message:String(n);return e.errors.push({seq:t.seq,code:Ty,message:`${t.type} at seq ${t.seq} is not the shape this reader knows: ${r.split(`
60
- `)[0]?.trim()??r}`}),e}function Dy(e,t){let n;try{n=Rv(t)}catch(n){let r=Ey(e,t,n);return r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}let r=e;return n.type===`log.gap`?r=Fy(e,n):Oy(e,t,n),r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}function Oy(e,t,n){switch(n.type){case`call.ringing`:e.status=`ringing`,e.direction=`inbound`,ky(e,n.data);return;case`call.dialing`:e.status=`dialing`,e.direction=`outbound`,ky(e,n.data);return;case`call.started`:e.status=`active`,e.direction=n.data.direction,e.started_at=n.data.started_at,ky(e,n.data);return;case`call.ended`:e.status=`ended`,e.ended_at=n.data.ended_at,e.end_reason=n.data.reason,e.live={user:null,agent:null};return;case`call.transferred`:e.transfer={to:n.data.to,mode:n.data.mode,status:n.data.ok?`done`:`failed`,by:e.transfer?.by??`agent`};return;case`call.line`:e.held=n.data.held,e.muted=n.data.muted;return;case`call.summary`:e.usage=[...n.data.usage],e.cost=n.data.cost,e.outcome=n.data.outcome,e.end_reason??=n.data.reason;return;case`user.state`:e.user_state=n.data.state;return;case`agent.state`:e.agent_state=n.data.state;return;case`user.transcript`:e.live.user=n.data.final?null:n.data.text;return;case`agent.transcript`:e.live.agent=n.data.final?null:Ly(e.live.agent,n.data);return;case`turn.user`:e.turns.push({role:`user`,...n.data}),e.live.user=null;return;case`turn.agent`:e.turns.push({role:`agent`,...n.data}),e.live.agent=null;return;case`memory.ops`:e.memory.push(...n.data.ops);return;case`docs.sources`:e.sources=[...n.data.sources];return;case`metrics.llm`:e.metrics.llm.push(n.data);return;case`metrics.stt`:e.metrics.stt.push(n.data);return;case`metrics.tts`:e.metrics.tts.push(n.data);return;case`metrics.vad`:e.metrics.vad.push(n.data);return;case`metrics.eou`:e.metrics.eou.push(n.data);return;case`metrics.eot`:e.metrics.eot.push(n.data);return;case`metrics.interruption`:e.metrics.interruption.push(n.data);return;case`metrics.realtime`:e.metrics.realtime.push(n.data);return;case`metrics.avatar`:e.metrics.avatar.push(n.data);return;case`tool.call`:e.tools.push({...n.data,status:`running`,seq:t.seq});return;case`tool.result`:Ay(e,n.data);return;case`state.changed`:e.app_state={...n.data.state};return;case`prompt.changed`:e.prompt[n.data.name]={hash:n.data.hash,chars:n.data.chars,seq:t.seq};return;case`tools.changed`:e.tools_visible=[...n.data.visible];return;case`confirm.request`:e.confirms.push({tool:n.data.tool,call_id:n.data.call_id,audience:n.data.audience,phrase:n.data.phrase,status:`pending`});return;case`confirm.granted`:jy(e,n.data.call_id,{status:`granted`,said:n.data.said});return;case`confirm.declined`:jy(e,n.data.call_id,{status:`declined`,reason:n.data.reason,...n.data.said===void 0?{}:{said:n.data.said}});return;case`supervisor.took_over`:e.handoff={active:!0,by:n.data.by};return;case`supervisor.released`:e.handoff={active:!1,by:null};return;case`supervisor.transferred`:e.transfer={to:n.data.to,mode:n.data.mode,status:`requested`,by:`supervisor`};return;case`agent.registered`:e.routes=[...n.data.routes];return;case`error`:e.errors.push({seq:t.seq,code:n.data.code,message:n.data.message});return;case`custom`:e.custom.push({seq:t.seq,name:n.data.name,data:{...n.data.data}});return;case`room.opened`:e.room={name:n.data.name,sid:n.data.sid,participants:[],caller:null};return;case`participant.joined`:My(e,t,n.data);return;case`participant.left`:Ny(e,n.data.identity);return;case`participant.speaking`:{let t=Py(e,n.data.identity);t!==void 0&&(t.speaking=n.data.speaking);return}case`event.received`:{let{data:r,...i}=n.data;e.events.push({...i,seq:t.seq});return}case`track.published`:case`track.unpublished`:case`room.sent`:case`supervisor.said`:case`supervisor.whispered`:case`supervisor.ended`:case`agent.configured`:case`pong`:case`log.caught_up`:case`log.gap`:return}}function ky(e,t){e.channel=t.channel,e.from=t.from,e.to=t.to,e.caller=t.caller}function Ay(e,t){let n=Iy(e.tools,e=>e.call_id===t.call_id);if(n===-1)return;let{call_id:r,name:i,...a}=t,o=e.tools[n];e.tools[n]={...o,...a,status:a.error===void 0?`done`:`failed`}}function jy(e,t,n){let r=Iy(e.confirms,e=>e.call_id===t);if(r===-1)return;let i=e.confirms[r];e.confirms[r]={...i,...n}}function My(e,t,n){e.room!==null&&(e.room.participants.push({...n,joined_at:t.ts,speaking:!1}),n.kind===`caller`&&(e.room.caller=n.identity))}function Ny(e,t){if(e.room===null)return;let n=e.room.participants.findIndex(e=>e.identity===t);n!==-1&&e.room.participants.splice(n,1),e.room.caller===t&&(e.room.caller=null)}function Py(e,t){return e.room?.participants.find(e=>e.identity===t)}function Fy(e,t){let n=t.data.snapshot===null?e:structuredClone(t.data.snapshot);return n.gaps.push({from_seq:t.data.from_seq,to_seq:t.data.to_seq}),n}function Iy(e,t){for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1}function Ly(e,t){if(e===null||e===``)return t.text;let n=/\s$/.test(e)||/^\s/.test(t.text);return t.start!=null&&!n?`${e} ${t.text}`:`${e}${t.text}`}var Ry=500,zy=8e3,By=204,Vy=class{#e=``;#t=null;#n=null;#r=[];feed(e){this.#e+=e;let t=[],n;for(;(n=this.#e.search(/\r\n|\n|\r/))!==-1;){let e=this.#e.slice(0,n);this.#e=this.#e.slice(n+(this.#e.startsWith(`\r
59
+ `,`pinecall serve`]})]})}var lm=(0,D.createContext)(null);function um({value:e,children:t}){return(0,A.jsx)(lm,{value:e,children:t})}function dm(){let e=(0,D.useContext)(lm);if(e===null)throw Error(`the console was mounted without a way out`);return e}var fm=typeof document<`u`&&document.querySelector(`meta[name="pinecall-console"]`)?.getAttribute(`content`)===`local`?`local`:`hosted`;function pm(){return(document.querySelector(`meta[name="pinecall-gateway"]`)?.getAttribute(`content`)??window.location.origin).replace(/\/$/,``)}var mm={hosted:`production`,local:`sandbox`},hm=[`hosted`,`local`],gm=[`hosted`],_m=[`local`],vm=[{key:`home`,path:``,name:`Home`,in:hm,group:`gateway`,icon:`home`},{key:`agents`,path:`overview`,name:`Overview`,in:hm,group:`gateway`,icon:`grid`},{key:`live`,path:`live`,name:`Live`,in:hm,group:`gateway`,icon:`activity`},{key:`sessions`,path:`sessions`,name:`Sessions`,in:hm,group:`gateway`,icon:`list`},{key:`org-evals`,path:`evals`,name:`Evals`,in:hm,group:`gateway`,icon:`check`},{key:`org-memory`,path:`memory`,name:`Memory`,in:hm,group:`gateway`,icon:`memory`},{key:`org-docs`,path:`docs`,name:`Docs`,in:hm,group:`gateway`,icon:`book`},{key:`usage`,path:`usage`,name:`Usage`,in:gm,group:`gateway`,icon:`chart`},{key:`numbers`,path:`numbers`,name:`Numbers`,in:gm,group:`settings`,icon:`phone`},{key:`phone`,path:`phone`,name:`Phone testing`,in:_m,group:`settings`,icon:`phone`},{key:`tokens`,path:`tokens`,name:`Tokens`,in:gm,group:`settings`,icon:`key`},{key:`providers`,path:`providers`,name:`Providers`,in:gm,group:`settings`,icon:`plug`},{key:`team`,path:`team`,name:`Team`,in:gm,group:`settings`,icon:`users`},{key:`lexicon`,path:`lexicon`,name:`Lexicon`,in:hm,group:`settings`,icon:`words`}],ym=[{key:`box-orgs`,path:`box/orgs`,name:`Organizations`,in:gm,group:`box`,icon:`building`,operator:!0},{key:`box-fleet`,path:`box/fleet`,name:`Fleet`,in:gm,group:`box`,icon:`server`,operator:!0},{key:`box-routes`,path:`box/routes`,name:`Routes`,in:gm,group:`box`,icon:`route`,operator:!0},{key:`box-usage`,path:`box/usage`,name:`Box usage`,in:gm,group:`box`,icon:`chart`,operator:!0},{key:`box-settings`,path:`box/settings`,name:`Box settings`,in:gm,group:`box`,icon:`sliders`,operator:!0}],bm=[{key:`talk`,path:`talk`,name:`Talk`,in:hm},{key:`chat`,path:`chat`,name:`Chat`,in:hm},{key:`devchat`,path:`dev-chat`,name:`Dev chat`,in:_m},{key:`calls`,path:`calls`,name:`Calls`,in:hm},{key:`sessions`,path:`sessions`,name:`Sessions`,in:hm},{key:`settings`,path:`settings`,name:`Settings`,in:hm},{key:`pipeline`,path:`pipeline`,name:`Pipeline`,in:hm},{key:`docs`,path:`docs`,name:`Docs`,in:hm},{key:`memory`,path:`memory`,name:`Memory`,in:hm},{key:`evals`,path:`evals`,name:`Evals`,in:hm},{key:`widget`,path:`widget`,name:`Widget`,in:hm}];function xm(e,t=fm,n=!1){return e.filter(e=>e.in.includes(t)&&(n||e.operator!==!0))}function Sm(e,t,n=fm){return e.some(e=>e.key===t&&e.in.includes(n))}var Cm=`pinecall.key`;function wm(){return window.localStorage.getItem(Cm)}function Tm(e){window.localStorage.setItem(Cm,e)}function Em(){window.localStorage.removeItem(Cm)}var Dm=`pinecall.corner`;function Om(){return window.sessionStorage.getItem(Dm)}function km(e){e===null?window.sessionStorage.removeItem(Dm):window.sessionStorage.setItem(Dm,e)}function V({children:e,pad:t=!1,style:n}){return(0,A.jsx)(`div`,{className:t?`ui-card ui-card-pad`:`ui-card`,style:n,children:e})}function H({title:e,meta:t,action:n,children:r}){return(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[typeof e==`string`?(0,A.jsx)(`span`,{className:`ui-card-title`,children:e}):e,t!==void 0&&(0,A.jsx)(`span`,{className:`ui-card-meta`,children:t}),r,n]})}function Am({to:e,onClick:t,children:n}){return e===void 0?(0,A.jsx)(`button`,{type:`button`,className:`ui-card-action`,onClick:t,children:n}):(0,A.jsx)(Wi,{to:e,className:`ui-card-action`,children:n})}function jm({children:e}){return(0,A.jsx)(`div`,{className:`ui-card-foot`,children:e})}function Mm({children:e}){return(0,A.jsx)(`div`,{className:`ui-empty`,children:e})}function Nm({children:e}){return e==null||e===``?null:(0,A.jsx)(`div`,{className:`ui-refused`,children:e})}function Pm({lead:e,name:t,tag:n,sub:r,end:i,to:a,onClick:o}){let s=(0,A.jsxs)(A.Fragment,{children:[e,(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsxs)(`div`,{className:`ui-row-line`,children:[(0,A.jsx)(`span`,{className:`ui-row-name`,children:t}),n]}),r!==void 0&&(0,A.jsx)(`div`,{className:`ui-row-sub`,children:r})]}),i!==void 0&&(0,A.jsx)(`div`,{className:`ui-row-end`,children:i})]});return a===void 0?(0,A.jsx)(`div`,{className:o===void 0?`ui-row`:`ui-row ui-row-link`,onClick:o,children:s}):(0,A.jsx)(Wi,{to:a,className:`ui-row ui-row-link`,children:s})}function Fm({name:e,sub:t,end:n,to:r}){let i=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`ui-item-name`,children:e}),t!==void 0&&(0,A.jsx)(`div`,{className:`ui-item-sub`,children:t})]}),n]});return r===void 0?(0,A.jsx)(`div`,{className:`ui-item`,children:i}):(0,A.jsx)(Wi,{to:r,className:`ui-item`,children:i})}function Im({children:e,ruled:t=!1}){return(0,A.jsx)(`div`,{className:t?`ui-section-label ui-section-label-ruled`:`ui-section-label`,children:e})}function Lm({label:e,children:t,keyWidth:n}){return(0,A.jsxs)(`div`,{className:`ui-kv`,children:[(0,A.jsx)(`span`,{className:`ui-kv-key`,style:n===void 0?void 0:{width:n},children:e}),(0,A.jsx)(`span`,{className:`ui-kv-value`,children:t})]})}function Rm(e,t,n,r){let i=[`ui-button`];return e!==`secondary`&&i.push(`ui-button-${e}`),t!==`base`&&i.push(`ui-button-${t}`),n&&i.push(`ui-button-pill`),r!==void 0&&i.push(r),i.join(` `)}function U({kind:e=`secondary`,size:t=`base`,pill:n=!1,className:r,type:i=`button`,...a}){return(0,A.jsx)(`button`,{type:i,className:Rm(e,t,n,r),...a})}function zm({to:e,kind:t=`secondary`,size:n=`base`,children:r}){return(0,A.jsx)(Wi,{to:e,className:Rm(t,n,!1),children:r})}function Bm({danger:e=!1,...t}){return(0,A.jsx)(`button`,{type:`button`,className:e?`ui-text-action ui-text-action-danger`:`ui-text-action`,...t})}function Vm({children:e,htmlFor:t}){return(0,A.jsx)(`label`,{className:`ui-label`,htmlFor:t,children:e})}function W({size:e=`form`,className:t,...n}){let r=[`ui-input`];return e===`sm`&&r.push(`ui-input-sm`),e===`lg`&&r.push(`ui-input-lg`),t!==void 0&&r.push(t),(0,A.jsx)(`input`,{className:r.join(` `),...n})}function Hm({size:e=`form`,className:t,...n}){let r=[`ui-select`];return e===`sm`&&r.push(`ui-select-sm`),t!==void 0&&r.push(t),(0,A.jsx)(`select`,{className:r.join(` `),...n})}function Um(e){return(0,A.jsx)(`textarea`,{className:`ui-textarea`,...e})}function Wm({label:e,grow:t=!1,minWidth:n,children:r}){return(0,A.jsxs)(`div`,{className:t?`ui-form-grow`:void 0,style:n===void 0?void 0:{minWidth:n},children:[(0,A.jsx)(`label`,{className:`ui-label`,children:e}),r]})}function Gm({options:e,value:t,onChange:n}){return(0,A.jsx)(`div`,{className:`ui-segmented`,role:`group`,children:e.map(e=>(0,A.jsx)(`button`,{type:`button`,className:e.value===t?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":e.value===t,onClick:()=>n(e.value),children:e.label},e.value))})}function Km({options:e,value:t,onChange:n}){return(0,A.jsx)(`div`,{className:`ui-chips`,role:`group`,children:e.map(e=>(0,A.jsx)(`button`,{type:`button`,className:e.value===t?`ui-chip ui-chip-on`:`ui-chip`,"aria-pressed":e.value===t,onClick:()=>n(e.value),children:e.label},e.value))})}function qm({on:e,children:t,...n}){return(0,A.jsx)(`button`,{type:`button`,className:e?`ui-choice ui-choice-on`:`ui-choice`,"aria-pressed":e,...n,children:t})}function Jm({on:e,onChange:t,label:n}){return(0,A.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,"aria-label":n,className:e?`ui-switch ui-switch-on`:`ui-switch`,onClick:()=>t(!e),children:(0,A.jsx)(`span`,{className:`ui-switch-knob`})})}function Ym({checked:e,onChange:t,children:n}){return(0,A.jsxs)(`label`,{className:`ui-check`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),n]})}var Xm={home:[`M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z`],grid:[{rect:[3,3,7,7,1.5]},{rect:[14,3,7,7,1.5]},{rect:[3,14,7,7,1.5]},{rect:[14,14,7,7,1.5]}],activity:[`M22 12h-4l-3 9L9 3l-3 9H2`],list:[`M8 6h13`,`M8 12h13`,`M8 18h13`,`M3 6h.01`,`M3 12h.01`,`M3 18h.01`],check:[{circle:[12,12,9]},`m8.5 12.5 2.5 2.5 4.5-5`],chart:[`M3 3v18h18`,`M7 15v3`,`M12 9v9`,`M17 5v13`],phone:[`M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2z`],key:[`m21 2-9.6 9.6`,`m15.5 7.5 3 3L22 7l-3-3`,{circle:[7.5,15.5,5.5]}],plug:[`M12 22v-5`,`M9 8V2`,`M15 8V2`,`M18 8v3a6 6 0 0 1-12 0V8z`],users:[`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,{circle:[9,7,4]},`M22 21v-2a4 4 0 0 0-3-3.9`],bot:[`M12 8V4`,{rect:[4,8,16,12,2]},`M2 14h2`,`M20 14h2`,`M9 13v2`,`M15 13v2`],search:[{circle:[11,11,7]},`m21 21-4.3-4.3`],panel:[{rect:[3,3,18,18,2]},`M9 3v18`],building:[{rect:[4,2,16,20,2]},`M9 22v-4h6v4`,`M8 6h.01`,`M16 6h.01`,`M12 6h.01`,`M12 10h.01`,`M12 14h.01`,`M16 10h.01`,`M16 14h.01`,`M8 10h.01`,`M8 14h.01`],server:[{rect:[2,2,20,8,2]},{rect:[2,14,20,8,2]},`M6 6h.01`,`M6 18h.01`],route:[{circle:[6,19,3]},`M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15`,{circle:[18,5,3]}],sliders:[`M21 4h-7`,`M10 4H3`,`M21 12h-9`,`M8 12H3`,`M21 20h-5`,`M12 20H3`,`M14 2v4`,`M8 10v4`,`M16 18v4`],words:[`M4 5h16v10H9l-5 4z`,`M8 9h8`,`M8 12h5`],book:[`M4 4a2 2 0 0 1 2-2h14v18H6a2 2 0 0 0-2 2z`,`M4 20a2 2 0 0 1 2-2h14`,`M8 6h8`,`M8 10h6`],memory:[`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,`M12 5v13`]};function Zm({name:e,size:t=16}){return(0,A.jsx)(`svg`,{className:`ui-icon`,width:t,height:t,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0,children:Xm[e].map((e,t)=>{if(typeof e==`string`)return(0,A.jsx)(`path`,{d:e},t);if(`circle`in e){let[n,r,i]=e.circle;return(0,A.jsx)(`circle`,{cx:n,cy:r,r:i},t)}let[n,r,i,a,o]=e.rect;return(0,A.jsx)(`rect`,{x:n,y:r,width:i,height:a,rx:o},t)})})}function Qm({tone:e,small:t=!1,children:n}){return(0,A.jsx)(`span`,{className:`ui-pill ui-pill-${e}${t?` ui-pill-small`:``}`,children:n})}function $m({children:e}){return(0,A.jsx)(`span`,{className:`ui-tag`,children:e})}function eh({tone:e,small:t=!1}){let n=[`ui-dot`];return t&&n.push(`ui-dot-small`),e!==void 0&&n.push(`ui-dot-${e}`),(0,A.jsx)(`span`,{className:n.join(` `),"aria-hidden":!0})}var th=[`violet`,`green`,`pink`,`amber`,`indigo`];function nh(e){return[`violet`,`pink`,`green`,`amber`,`indigo`][e%5]??`violet`}function rh(e){let t=0;for(let n of e)t=(t+(n.codePointAt(0)??0))%9973;return th[t%th.length]??`violet`}function ih(e){let t=e.split(/[\s@._-]+/).filter(e=>/[A-Za-z0-9]/.test(e));if(t.length===0)return`?`;if(t.length===1){let e=t[0]??``;return(/^[A-Za-z]/.test(e)?e.slice(0,2):e.slice(0,1)).toUpperCase()}return`${t[0]?.[0]??``}${t[1]?.[0]??``}`.toUpperCase()}function ah({name:e,letters:t,tint:n,size:r=28,round:i=!1}){let a=[`ui-avatar`,`ui-tint-${n??rh(e)}`];r===26&&a.push(`ui-avatar-26`),(r===36||r===38)&&a.push(`ui-avatar-36`),i&&a.push(`ui-avatar-round`),r===38&&a.push(`ui-avatar-38`);let o=r===20?{width:20,height:20,borderRadius:6,fontSize:9.5}:void 0;return(0,A.jsx)(`span`,{className:a.join(` `),style:o,"aria-hidden":!0,children:t??ih(e)})}function oh({share:e,color:t,height:n}){let r=`${Math.max(0,Math.min(1,e))*100}%`;return(0,A.jsx)(`span`,{className:`ui-bar`,style:n===void 0?void 0:{height:n},children:(0,A.jsx)(`span`,{className:`ui-bar-fill`,style:{width:r,background:t}})})}function sh({width:e=1180,tight:t=!1,children:n}){let r=[`ui-page`];return t&&r.push(`ui-page-tight`),e!==1180&&r.push(`ui-page-${e}`),(0,A.jsx)(`div`,{className:r.join(` `),"data-page":!0,children:n})}function ch({title:e,lede:t,ledeWidth:n,back:r,actions:i}){return(0,A.jsxs)(`div`,{className:`ui-head`,children:[(0,A.jsxs)(`div`,{className:`ui-head-words`,style:n===void 0?void 0:{maxWidth:n},children:[r,(0,A.jsx)(`h1`,{className:`ui-title`,children:e}),t!==void 0&&(0,A.jsx)(`p`,{className:n===void 0?`ui-lede`:`ui-lede ui-lede-long`,children:t})]}),i!==void 0&&(0,A.jsx)(`div`,{className:`ui-head-actions`,children:i})]})}function lh({min:e,children:t}){return(0,A.jsx)(`div`,{className:`ui-stats`,style:{gridTemplateColumns:`repeat(auto-fit,minmax(${e}px,1fr))`},children:t})}function uh({label:e,value:t,of:n,delta:r,tone:i,size:a=`medium`,accent:o=!1}){let s=[`ui-stat`];a!==`medium`&&s.push(`ui-stat-${a}`),o&&s.push(`ui-stat-accent`);let c=i===`green`?{color:`var(--green)`}:i===`red`?{color:`var(--red)`}:void 0;return(0,A.jsxs)(`div`,{className:s.join(` `),children:[(0,A.jsx)(`div`,{className:`ui-stat-label`,children:e}),a===`big`?(0,A.jsxs)(`div`,{className:`ui-stat-line`,children:[(0,A.jsx)(`span`,{className:`ui-stat-value`,children:t}),r!==void 0&&(0,A.jsx)(`span`,{className:i===`up`?`ui-stat-delta ui-stat-delta-up`:i===`down`?`ui-stat-delta ui-stat-delta-down`:`ui-stat-delta`,children:r})]}):(0,A.jsxs)(`div`,{className:`ui-stat-value`,style:c,children:[t,n!==void 0&&(0,A.jsxs)(`span`,{className:`ui-stat-of`,children:[` `,n]})]})]})}function dh({columns:e,labels:t,padding:n}){return(0,A.jsx)(`div`,{className:`ui-table-head`,style:{gridTemplateColumns:e,padding:n},children:t.map((e,t)=>e.endsWith(`>`)?(0,A.jsx)(`span`,{style:{textAlign:`right`},children:e.slice(0,-1)},t):(0,A.jsx)(`span`,{children:e},t))})}function fh({columns:e,to:t,onClick:n,padding:r,children:i}){let a={gridTemplateColumns:e,padding:r};return t===void 0?(0,A.jsx)(`div`,{className:n===void 0?`ui-table-row`:`ui-table-row ui-table-row-link`,style:a,onClick:n,children:i}):(0,A.jsx)(Wi,{to:t,className:`ui-table-row ui-table-row-link`,style:a,children:i})}var ph=`pinecall.pane.`;function mh(e){try{let t=Number(window.localStorage.getItem(ph+e));return Number.isFinite(t)&&t>0?t:null}catch{return null}}function hh(e,t){try{window.localStorage.setItem(ph+e,String(Math.round(t)))}catch{}}function gh(e){try{window.localStorage.removeItem(ph+e)}catch{}}var _h=(e,t,n)=>Math.min(n,Math.max(t,e));function vh({name:e,initial:t,min:n,max:r,side:i}){let[a,o]=(0,D.useState)(()=>_h(mh(e)??t,n,r)),s=(0,D.useRef)(null),c=(0,D.useCallback)(e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={x:e.clientX,width:a}},[a]),l=(0,D.useCallback)(e=>{if(s.current===null)return;let t=e.clientX-s.current.x;o(_h(s.current.width+(i===`right`?-t:t),n,r))},[i,n,r]),u=(0,D.useCallback)(()=>{s.current!==null&&(s.current=null,hh(e,a))},[e,a]),d=(0,D.useCallback)(()=>{gh(e),o(t)},[e,t]);return{width:a,style:{"--pane":`${String(a)}px`},handle:(0,A.jsx)(`div`,{className:i===`right`?`ui-resize ui-resize-right`:`ui-resize ui-resize-left`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Drag to resize. Double-click to reset.`,title:`Drag to resize · double-click to reset`,onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,onDoubleClick:d})}}function yh({label:e,tabs:t,on:n,onPick:r}){return(0,A.jsx)(`nav`,{className:`ui-tabs`,"aria-label":e,children:t.map(e=>(0,A.jsxs)(`button`,{type:`button`,className:n===e.tab?`ui-tab ui-tab-on`:`ui-tab`,"aria-current":n===e.tab?`page`:void 0,onClick:()=>r(e.tab),children:[e.name,e.mark]},e.tab))})}function bh({said:e}){return(0,A.jsxs)(am,{foot:(0,A.jsxs)(A.Fragment,{children:[`Your sandbox is on your machine: `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall serve`}),` in your project's folder.`]}),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`No production access`}),(0,A.jsx)(`p`,{className:`login-lede`,children:e}),(0,A.jsx)(Bm,{onClick:()=>{Em(),window.location.assign(`/`)},children:`Sign in as somebody else`})]})}var xh=z({org:P(),slug:P().nullish(),key_id:P(),label:P().nullish(),env:mp([`production`,`sandbox`]),scopes:R(P()),subject:P().nullish(),name:P().nullish(),operator:L().optional(),visiting:L().optional(),production:L()}),Sh=(0,D.createContext)(null);function Ch({children:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let e=!1;return r(null),a(null),k(t,`/v1/whoami`).then(t=>{e||r(xh.parse(t))},t=>{!e&&t instanceof na&&t.status===403&&a(t.message)}),()=>{e=!0}},[t]),i===null?(0,A.jsx)(Sh,{value:n,children:e}):(0,A.jsx)(bh,{said:i})}function wh(){return(0,D.useContext)(Sh)}function Th(e){return e.slug??e.org}function Eh(){return wh()?.scopes??null}var Dh=(0,D.createContext)(null);function Oh({value:e,children:t}){return(0,A.jsx)(Dh,{value:e,children:t})}function kh(){let e=(0,D.useContext)(Dh);if(e===null)throw Error(`the console was mounted without a world`);return e}var Ah=`ready`,jh=`no plugin`,Mh=`no key`,Nh=`its own`,Ph=z({name:P(),does:R(mp([`llm`,`stt`,`tts`])),aliases:R(P()),note:P(),standing:mp([Ah,jh,Mh,Nh]),ready:L(),env:P().nullable(),extra:P()}),Fh=[`llm`,`stt`,`tts`],Ih=z({providers:R(Ph),defaults:fp(P(),P()),voices:R(P())});async function Lh(e){return Ih.parse(await k(e,`/v1/providers`))}function Rh(e,t){return e.filter(e=>e.does.includes(t)).sort((e,t)=>Number(t.ready)-Number(e.ready)||e.name.localeCompare(t.name))}function zh(e){return e.standing===`no plugin`?`the box needs livekit-agents[${e.extra}]`:e.standing===`no key`?`the box needs ${e.env??`a credential`}`:e.standing===`its own`?`its credentials are its own: a profile, a pair, not one key`:e.note||`ready on this box`}var Bh=[`everything`,`mine`,`the team's`];function Vh(e,t){let n=e.holder?.holder;return n!=null&&n!==t}function Hh(e,t,n){if(t===`everything`)return e;let r=t===`the team's`;return e.filter(e=>Vh(e,n)===r)}function Uh(e,t){let n=new Map;for(let r of e){let e=n.get(r.slug);(e===void 0||Vh(e,t)&&!Vh(r,t))&&n.set(r.slug,r)}return[...n.values()]}function Wh(e){let t=e.holder;return t==null?`the org's`:t.name??t.holder??`the org's`}function Gh(e){return e?.subject??null}var Kh=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function qh(e){if(e.started_at===null||e.ended_at===null)return`—`;let t=Math.max(0,Math.round(e.ended_at-e.started_at));return`${Math.floor(t/60)}m ${String(t%60).padStart(2,`0`)}s`}function Jh(e,t=Date.now()/1e3){if(e===null)return`—`;let n=Math.max(0,Math.round(t-e)),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=String(n%60).padStart(2,`0`);return r>0?`${r}:${String(i).padStart(2,`0`)}:${a}`:`${i}:${a}`}function Yh(e){return e==null?`—`:`${e.toFixed(4)} €`}function Xh(e){return`€${e.toFixed(2)}`}function Zh(e){return e===null?`—`:new Date(e*1e3).toISOString().slice(11,19)}function Qh(e){if(e===null)return`—`;let t=new Date(e*1e3);return`${t.getUTCDate()} ${Kh[t.getUTCMonth()]}, ${t.toISOString().slice(11,16)}`}function $h(e){if(e===null)return`—`;let t=new Date(e*1e3);return`${t.getUTCDate()} ${Kh[t.getUTCMonth()]}`}function eg(e,t=Date.now()/1e3){if(e===null)return`—`;let n=Math.max(0,t-e);return n<60?`just now`:n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<172800?`Yesterday`:$h(e)}function tg(e){return new Date(e*1e3).toISOString().slice(0,10)}function ng(e=Date.now()/1e3){return{today:tg(e),yesterday:tg(e-86400)}}function rg(e,t){return e.filter(e=>e.started_at!==null&&tg(e.started_at)===t)}function ig(e,t){if(t===0)return null;let n=Math.round((e-t)/t*100);return n===0?{text:`steady`,tone:`flat`}:n>0?{text:`+${n}%`,tone:`up`}:{text:`−${Math.abs(n)}%`,tone:`down`}}function ag(e){return`${Math.round(e*100)}%`}function og(e){if(e==null)return`—`;let t=e.replace(/[^\d]/g,``);return e.startsWith(`+1`)&&t.length===11?`+1 (${t.slice(1,4)}) ${t.slice(4,7)}-${t.slice(7)}`:e.startsWith(`+34`)&&t.length===11?`+34 ${t.slice(2,5)} ${t.slice(5,8)} ${t.slice(8)}`:e.startsWith(`+598`)&&t.length===11?`+598 ${t.slice(3,5)} ${t.slice(5,8)} ${t.slice(8)}`:e}function sg(e){let t=e.caller?.name;if(t!=null&&t!==``)return t;let n=e.direction===`outbound`?e.to:e.from;return n==null?`—`:n.startsWith(`+`)?og(n):n}var cg=np({day:P(),conversations:z({today:F(),yesterday:F()}),resolved_rate:F().nullable(),median_e2e_s:F().nullable(),spend_eur:F(),channels:z({phone:F(),web:F(),whatsapp:F()}),sessions_total:F(),live:F(),agents:R(z({slug:P(),today:F(),score:F().nullable()})),budget:z({limit_eur:F().nullable(),spent_eur_month:F()})}),lg=15e3;function ug(e){let t=j(),[n,r]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i,a=async()=>{try{let i=cg.parse(await k(t,`/v1/insights`,e===void 0?{}:{day:e}));n||r(i)}catch(e){e instanceof na&&[403,404].includes(e.status)&&(window.clearInterval(i),n||r(null))}};return a(),i=window.setInterval(()=>void a(),lg),()=>{n=!0,window.clearInterval(i)}},[t,e]),n}function dg(){let e=j(),[t,n]=(0,D.useState)(fm===`hosted`&&null);return(0,D.useEffect)(()=>{if(fm!==`hosted`)return;let t=!1;return fetch(la(e,`/v1/ops/whoami`),{headers:ra(e)}).then(e=>{t||n(e.ok)},()=>{t||n(!1)}),()=>{t=!0}},[e]),t}var fg=B({seq:I(),ts:F(),call:P().nullable(),agent:P(),type:P(),ephemeral:L(),data:fp(P(),Zf())});B({type:P(),agent:P(),call:P().nullable(),id:P().nullish(),data:fp(P(),Zf())});var pg=mp([`phone`,`web`,`whatsapp`]),mg=mp([`inbound`,`outbound`]),hg=mp([`production`,`sandbox`]),gg=mp([`chat.roster`,`chat.start`,`chat.say`,`chat.end`,`simulate.roster`,`simulate.start`,`goldens.roster`,`goldens.run`,`knowledge.roster`,`knowledge.push`,`knowledge.eval`,`memory.roster`,`memory.eval`,`memory.extraction`,`promote.roster`,`promote.write`,`drift.read`,`reproductions.roster`,`reproductions.read`]),_g=mp([`caller_hung_up`,`agent_hung_up`,`supervisor_ended`,`transferred`,`no_answer`,`busy`,`dial_failed`,`timeout`,`drained`,`app_detached`,`error`]),vg=mp([`caller`,`agent`,`supervisor`,`platform`]),yg=mp([`held`,`broken`,`deferred`,`skipped`]),bg=mp([`cold`,`warm`]),xg=mp([`static`,`dynamic`]),Sg=mp([`retrieved`,`tool`]),Cg=mp([`recall`,`search`]),wg=B({name:P().regex(/^[a-z][a-z0-9_]*$/),region:xg}),Tg=mp([`listening`,`speaking`,`away`]),Eg=mp([`initializing`,`idle`,`listening`,`thinking`,`speaking`]),Dg=mp([`caller`,`agent`,`supervisor`,`listener`,`sip`]),Og=mp([`audio`,`video`,`screen`]),kg=mp([`microphone`,`camera`,`screen_share`,`screen_share_audio`,`unknown`]),Ag=mp([`app`,`participant`]),jg=mp([`public`,`tenant`,`pii`]);mp([`public`,`tenant`]);var Mg=B({id:P().nullish(),phone:P().nullish(),name:P().nullish(),email:P().nullish(),external_id:P().nullish()}),Ng=B({channel:pg,number:P().nullable(),label:P().nullish()}),Pg=B({id:P(),name:P().nullish()}),Fg=B({name:P(),description:P(),parameters:fp(P(),Zf()),side_effect:mp([`read`,`write`,`irreversible`]).nullish(),confirm:P().nullish(),pii:R(P()).nullish(),timeout_s:F().nullish()}),Ig=B({call_id:P(),name:P(),output:Zf().nullish(),error:P().nullish(),summary:P().nullish(),duration_s:F().nullish()}),Lg=B({id:P().nullish(),text:P(),category:P().nullish(),score:F().nullish(),source:P().nullish()}),Rg=B({op:mp([`recall`,`remember`,`forget`]),contact:P().nullish(),query:P().nullish(),facts:R(Lg),took_ms:F()}),zg=B({id:P(),path:P(),heading:P().nullish(),score:F(),excerpt:P().nullish()}),Bg=B({currency:gp(`EUR`),usd_to_eur:F(),as_of:P()}),Vg=B({provider:P(),model:P(),unit:mp([`input_tokens`,`cached_input_tokens`,`cache_creation_tokens`,`output_tokens`,`characters`,`audio_seconds`,`requests`,`session_seconds`]),quantity:F(),unit_price_usd:F(),eur:F()}),Hg=B({provider:P(),model:P()}),Ug=B({eur:F(),rate:Bg,rows:R(Vg),unpriced:R(Hg)}),Wg=B({name:P().nullish(),provider:P().nullish(),model:P().nullish(),voice_id:P().nullish()}),Gg=B({provider:P(),model:P(),temperature:F().nullish()}),Kg=B({min_interruption_words:I().nullish(),endpointing_ms:I().nullish()}),qg=B({word:P(),spoken:P()}),Jg=B({name:P(),visibility:jg}),Yg=B({name:P(),from:R(Ag)}),Xg=B({path:P(),text:P()}),Zg=B({base:P(),mode:Sg.nullish(),k:I().nullish(),min_score:F().nullish()}),Qg=B({say:P().nullish(),reply:P().nullish(),allow_interruptions:L().nullish()}),$g=B({when:P().nullish()}),e_=B({remember:R(P()).nullish(),forget:R(P()).nullish()}),t_=B({prompt:R(wg).nullish(),language:P().nullish(),greeting:Qg.nullish(),voice:Wg.nullish(),llm:Gg.nullish(),stt:Gg.nullish(),turn:Kg.nullish(),says:R(qg).nullish(),hears:R(P()).nullish(),knowledge:Xg.nullish(),docs:Zg.nullish(),memory:e_.nullish(),hangup:$g.nullish(),tools:R(Fg).nullish(),uses_knowledge:L().nullish(),state_fields:R(Jg).nullish(),events:R(Yg).nullish()}),n_=op(`verb`,[B({verb:gp(`say`),text:P()}),B({verb:gp(`whisper`),text:P()}),B({verb:gp(`takeover`)}),B({verb:gp(`release`)}),B({verb:gp(`transfer`),to:P(),mode:bg}),B({verb:gp(`end`),reason:P().nullish()})]);B({config:t_}),B({routes:R(Ng),sdk:P().nullish(),host:P().nullish(),takes_unclaimed:L().nullish()}),B({instructions:P(),allow_interruptions:L().nullish()}),B({text:P(),allow_interruptions:L().nullish()}),B({to:P(),from:P().nullish(),caller:Mg.nullish(),metadata:fp(P(),Zf()).nullish()}),B({digits:P()}),B({name:P(),data:fp(P(),Zf())}),B({reason:P().nullish()}),B({}),B({name:P(),data:fp(P(),Zf())}),B({}),B({to:P(),mode:bg}),B({}),B({});var r_=B({status:I(),detail:P()});B({id:P(),result:fp(P(),Zf()).nullish(),refused:r_.nullish()}),B({identity:P()}),B({identity:P()}),B({}),B({name:P(),text:P()}),B({to:P(),kind:mp([`sip`,`participant`])}),B({topic:P(),data:fp(P(),Zf()),to:P().nullish()}),B({state:fp(P(),Zf()).nullish(),config:t_.nullish()}),B({state:fp(P(),Zf()),changed:R(P()).nullish()}),B({by:Pg,verb:n_}),B({tools:R(Fg)});var i_=B({model_name:P().nullable().nullish(),model_provider:P().nullable().nullish()}),a_=B({type:gp(`llm_metrics`),label:P(),request_id:P(),timestamp:F(),duration:F(),ttft:F(),cancelled:L(),completion_tokens:I(),prompt_tokens:I(),prompt_cached_tokens:I(),cache_creation_tokens:I().nullish(),reasoning_tokens:I().nullish(),total_tokens:I(),tokens_per_second:F(),speech_id:P().nullable().nullish(),metadata:i_.nullable().nullish()}),o_=B({type:gp(`stt_metrics`),label:P(),request_id:P(),timestamp:F(),duration:F(),audio_duration:F(),input_tokens:I().nullish(),output_tokens:I().nullish(),streamed:L(),acquire_time:F().nullish(),connection_reused:L().nullish(),metadata:i_.nullable().nullish()}),s_=B({type:gp(`tts_metrics`),label:P(),request_id:P(),timestamp:F(),ttfb:F(),duration:F(),audio_duration:F(),cancelled:L(),characters_count:I(),input_tokens:I().nullish(),output_tokens:I().nullish(),streamed:L(),acquire_time:F().nullish(),connection_reused:L().nullish(),segment_id:P().nullable().nullish(),speech_id:P().nullable().nullish(),metadata:i_.nullable().nullish()}),c_=B({type:gp(`vad_metrics`),label:P(),timestamp:F(),idle_time:F(),inference_duration_total:F(),inference_count:I(),metadata:i_.nullable().nullish()}),l_=B({type:gp(`eou_metrics`),timestamp:F(),end_of_utterance_delay:F(),transcription_delay:F(),on_user_turn_completed_delay:F(),speech_id:P().nullable().nullish(),metadata:i_.nullable().nullish()}),u_=B({type:gp(`eot_inference_metrics`),timestamp:F(),total_duration:F(),detection_delay:F(),prediction_duration:F(),num_requests:I().nullish(),metadata:i_.nullable().nullish()}),d_=B({type:gp(`interruption_metrics`),timestamp:F(),total_duration:F(),prediction_duration:F(),detection_delay:F(),num_interruptions:I(),num_backchannels:I(),num_requests:I(),metadata:i_.nullable().nullish()}),f_=B({audio_tokens:I().nullish(),text_tokens:I().nullish(),image_tokens:I().nullish()}),p_=B({audio_tokens:I().nullish(),text_tokens:I().nullish(),image_tokens:I().nullish(),cached_tokens:I().nullish(),cached_tokens_details:f_.nullable().nullish()}),m_=B({text_tokens:I().nullish(),audio_tokens:I().nullish(),image_tokens:I().nullish()}),h_=B({type:gp(`realtime_model_metrics`),label:P().nullish(),request_id:P(),timestamp:F(),duration:F().nullish(),session_duration:F().nullish(),ttft:F().nullish(),cancelled:L().nullish(),input_tokens:I().nullish(),output_tokens:I().nullish(),total_tokens:I().nullish(),tokens_per_second:F().nullish(),input_token_details:p_,output_token_details:m_,acquire_time:F().nullish(),connection_reused:L().nullish(),metadata:i_.nullable().nullish()}),g_=B({type:gp(`avatar_metrics`),timestamp:F(),playback_latency:F().nullish(),session_started_time:F().nullable().nullish(),avatar_joined_time:F().nullable().nullish(),metadata:i_.nullable().nullish()}),__=B({model_name:P().nullish(),model_provider:P().nullish()}),v_=B({started_speaking_at:F().nullish(),stopped_speaking_at:F().nullish(),transcription_delay:F().nullish(),end_of_turn_delay:F().nullish(),on_user_turn_completed_delay:F().nullish(),stt_metadata:__.nullish()}),y_=B({started_speaking_at:F().nullish(),stopped_speaking_at:F().nullish(),llm_node_ttft:F().nullish(),llm_node_tps:F().nullish(),llm_node_ttfs:F().nullish(),tts_node_ttfb:F().nullish(),playback_latency:F().nullish(),e2e_latency:F().nullish(),provider_request_ids:R(P()).nullish(),llm_metadata:__.nullish(),tts_metadata:__.nullish()}),b_=op(`type`,[B({type:gp(`llm_usage`),provider:P(),model:P(),input_tokens:I().nullish(),input_cached_tokens:I().nullish(),input_cache_creation_tokens:I().nullish(),input_audio_tokens:I().nullish(),input_cached_audio_tokens:I().nullish(),input_text_tokens:I().nullish(),input_cached_text_tokens:I().nullish(),input_image_tokens:I().nullish(),input_cached_image_tokens:I().nullish(),output_tokens:I().nullish(),output_audio_tokens:I().nullish(),output_text_tokens:I().nullish(),output_reasoning_tokens:I().nullish(),session_duration:F().nullish()}),B({type:gp(`tts_usage`),provider:P(),model:P(),input_tokens:I().nullish(),output_tokens:I().nullish(),characters_count:I().nullish(),audio_duration:F().nullish()}),B({type:gp(`stt_usage`),provider:P(),model:P(),input_tokens:I().nullish(),output_tokens:I().nullish(),audio_duration:F().nullish()}),B({type:gp(`interruption_usage`),provider:P(),model:P(),total_requests:I().nullish()}),B({type:gp(`eot_usage`),provider:P(),model:P(),total_requests:I().nullish()})]),x_=mp([`idle`,`ringing`,`dialing`,`active`,`ended`]),S_=op(`role`,[B({role:gp(`user`),speech_id:P(),item_id:P().nullish(),text:P(),language:P().nullish(),transcript_confidence:F().nullish(),metrics:v_}),B({role:gp(`agent`),speech_id:P(),item_id:P().nullish(),text:P(),interrupted:L(),metrics:y_})]),C_=B({llm:R(a_),stt:R(o_),tts:R(s_),vad:R(c_),eou:R(l_),eot:R(u_),interruption:R(d_),realtime:R(h_),avatar:R(g_)}),w_=B({call_id:P(),name:P(),arguments:fp(P(),Zf()),speech_id:P().nullish(),status:mp([`running`,`done`,`failed`]),output:Zf().nullish(),error:P().nullish(),summary:P().nullish(),duration_s:F().nullish(),seq:I()}),T_=B({hash:P(),chars:I(),seq:I()}),E_=fp(P(),T_),D_=B({tool:P(),call_id:P(),audience:P(),phrase:P(),status:mp([`pending`,`granted`,`declined`]),said:P().nullish(),reason:P().nullish()}),O_=B({active:L(),by:Pg.nullable()}),k_=B({to:P(),mode:bg,status:mp([`requested`,`done`,`failed`]),by:mp([`agent`,`supervisor`])}),A_=B({user:P().nullable(),agent:P().nullable()}),j_=B({from_seq:I(),to_seq:I()}),M_=B({seq:I(),code:P(),message:P()}),N_=B({identity:P(),kind:Dg,name:P().nullish(),joined_at:F(),speaking:L(),attributes:fp(P(),Zf())}),P_=B({name:P(),sid:P(),participants:R(N_),caller:P().nullable()}),F_=B({seq:I(),name:P(),source:Ag,identity:P().nullish()}),I_=B({seq:I(),name:P(),data:fp(P(),Zf())}),L_=B({seq:I(),agent:P(),call:P().nullable(),status:x_,channel:pg.nullable(),direction:mg.nullable(),from:P().nullable(),to:P().nullable(),caller:Mg.nullable(),room:P_.nullable(),started_at:F().nullable(),ended_at:F().nullable(),end_reason:_g.nullable(),outcome:P().nullable(),user_state:Tg.nullable(),agent_state:Eg.nullable(),live:A_,turns:R(S_),metrics:C_,tools:R(w_),app_state:fp(P(),Zf()),events:R(F_),prompt:E_,tools_visible:R(P()),confirms:R(D_),memory:R(Rg),sources:R(zg),handoff:O_,held:L(),muted:L(),transfer:k_.nullable(),usage:R(b_),cost:Ug.nullable(),routes:R(Ng),gaps:R(j_),errors:R(M_),custom:R(I_)}),R_=B({changed:R(P())}),z_=B({app:P(),env:hg,left:L()}),B_=B({routes:R(Ng),app:P(),sdk:P().nullish(),env:hg.nullish()}),V_=B({state:Eg}),H_=B({speech_id:P(),text:P(),final:L(),start:F().nullish(),end:F().nullish()}),U_=B({channel:pg,from:P(),to:P(),run:P().nullable().nullish(),caller:Mg.nullable(),external_id:P().nullish(),asked_by:P().nullish()}),W_=B({reason:_g,ended_by:vg,ended_at:F(),duration_s:F()}),G_=B({held:L(),muted:L()}),K_=B({channel:pg,from:P(),to:P(),route:Ng,run:P().nullable().nullish(),caller:Mg.nullable(),external_id:P().nullish()}),q_=B({seqs:R(I()),said:P().nullish()}),J_=B({name:P(),verdict:yg,criteria:P(),reason:P(),evidence:q_}),Y_=B({passed:L().nullish(),not_judged:P().nullish(),judges:R(J_),panel:R(P()).nullish(),judge_calls:I(),judge_cost_eur:F().nullish()}),X_=B({channel:pg,direction:mg,from:P(),to:P(),run:P().nullable().nullish(),caller:Mg.nullable(),started_at:F(),env:hg.nullish()}),Z_=B({reason:_g,outcome:P(),duration_s:F(),turns:I(),usage:R(b_),cost:Ug,recording:P().nullish()}),Q_=B({to:P(),mode:bg,ok:L(),error:P().nullish()}),$_=B({channel:pg,number:P(),via:mp([`overflow`,`widget`]),call:P().nullable(),contact:Mg.nullable()}),ev=B({tool:P(),call_id:P(),audience:P(),said:P().nullish(),reason:mp([`no`,`timeout`,`changed`,`cancelled`])}),tv=B({tool:P(),call_id:P(),audience:P(),said:P(),ttl_s:I()}),nv=B({tool:P(),call_id:P(),arguments:fp(P(),Zf()),audience:P(),phrase:P(),ttl_s:I()}),rv=B({org:P(),quota:mp([`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`]),used:F(),limit:I()}),iv=B({name:P(),data:fp(P(),Zf())}),av=B({id:P(),verb:gg,data:fp(P(),Zf())}),ov=B({query:P(),sources:R(zg),took_ms:F(),speech_id:P().nullish()}),sv=B({code:P(),message:P(),command:P().nullish(),id:P().nullish(),recoverable:L()}),cv=B({channel:pg,workers:I(),active:I()}),lv=B({seq:I()}),uv=B({from_seq:I(),to_seq:I(),snapshot:L_.nullable()}),dv=B({ops:R(Rg),speech_id:P().nullish()}),fv=B({ts:F()}),pv=B({name:P(),hash:P(),chars:I()}),mv=op(`kind`,[B({kind:gp(`tool`),tool:P(),call_id:P()}),B({kind:gp(`event`),name:P(),seq:I()})]),hv=B({state:fp(P(),Zf()),changed:R(P()),cause:mv.nullish()}),gv=B({by:Pg,reason:P().nullish()}),_v=B({by:Pg}),vv=B({by:Pg,text:P()}),yv=B({by:Pg}),bv=B({by:Pg,to:P(),mode:bg}),xv=B({by:Pg,text:P()}),Sv=B({call_id:P(),name:P(),arguments:fp(P(),Zf()),speech_id:P().nullish()}),Cv=B({visible:R(P())}),wv=B({speech_id:P(),item_id:P().nullish(),text:P(),interrupted:L(),metrics:y_}),Tv=B({speech_id:P(),item_id:P().nullish(),text:P(),language:P().nullish(),transcript_confidence:F().nullish(),metrics:v_}),Ev=B({state:Tg}),Dv=B({text:P(),final:L(),language:P().nullish(),confidence:F().nullish()}),Ov=B({name:P(),sid:P(),channel:pg}),kv=B({identity:P(),kind:Dg,name:P().nullish(),attributes:fp(P(),Zf())}),Av=B({identity:P(),reason:P()}),jv=B({identity:P(),speaking:L()}),Mv=B({identity:P(),kind:Og,source:kg}),Nv=B({identity:P(),kind:Og,source:kg}),Pv={"agent.configured":R_,"agent.detached":z_,"agent.registered":B_,"agent.state":V_,"agent.transcript":H_,"call.dialing":U_,"call.ended":W_,"call.line":G_,"call.ringing":K_,"call.score":Y_,"call.started":X_,"call.summary":Z_,"call.transferred":Q_,"callback.requested":$_,"confirm.declined":ev,"confirm.granted":tv,"confirm.request":nv,"credits.exhausted":rv,custom:iv,"dev.request":av,"docs.sources":ov,error:sv,"event.received":B({name:P(),data:fp(P(),Zf()),source:Ag,identity:P().nullish()}),"fleet.full":cv,"log.caught_up":lv,"log.gap":uv,"memory.ops":dv,"metrics.avatar":g_,"metrics.eot":u_,"metrics.eou":l_,"metrics.interruption":d_,"metrics.llm":a_,"metrics.realtime":h_,"metrics.stt":o_,"metrics.tts":s_,"metrics.vad":c_,"participant.joined":kv,"participant.left":Av,"participant.speaking":jv,pong:fv,"prompt.changed":pv,"room.opened":Ov,"room.sent":B({topic:P(),to:P().nullish(),bytes:I()}),"state.changed":hv,"supervisor.ended":gv,"supervisor.released":_v,"supervisor.said":vv,"supervisor.took_over":yv,"supervisor.transferred":bv,"supervisor.whispered":xv,"tool.call":Sv,"tool.result":Ig,"tools.changed":Cv,"track.published":Mv,"track.unpublished":Nv,"turn.agent":wv,"turn.user":Tv,"user.state":Ev,"user.transcript":Dv},Fv=`call.score`,Iv=class extends Error{name=`ProtocolError`};function Lv(e){return fg.parse(e)}function Rv(e){if(!zv(e.type))throw new Iv(`unknown event type: ${e.type}`);let t=Pv[e.type].parse(e.data);return{type:e.type,data:t}}function zv(e){return Object.hasOwn(Pv,e)}B({state:L_,last_seq:I(),live:L()});var Bv=B({entries:R(fg),live:L(),next:I().nullable()}),Vv=B({held:I(),judged:I(),passed:L(),reason:P().nullable()}),Hv=mp([`escalated`,`low_score`,`promise`]),Uv=B({call:P(),agent:P(),live:L(),last_seq:I(),status:x_,channel:pg.nullable(),direction:mg.nullable(),from:P().nullable(),to:P().nullable(),caller:Mg.nullable(),started_at:F().nullable(),ended_at:F().nullable(),end_reason:_g.nullable(),outcome:P().nullable(),cost:Ug.nullable(),score:Vv.nullable().nullish(),flags:R(Hv).nullish()}),Wv=B({calls:R(Uv),total:I().nullable().nullish(),next:P().nullable().nullish()}),Gv=B({today:I(),yesterday:I()}),Kv=B({phone:I(),web:I(),whatsapp:I()}),qv=B({slug:P(),today:I(),score:F().nullable()}),Jv=B({limit_eur:F().nullable(),spent_eur_month:F()});B({day:P(),timezone:P(),conversations:Gv,resolved_rate:F().nullable(),median_e2e_s:F().nullable(),spend_eur:F(),channels:Kv,sessions_total:I(),live:I(),agents:R(qv),budget:Jv}),B({on:L(),ceiling_eur:F().nullable()}),B({on:L()});var Yv=mp([`in`,`out`,`call`]),Xv=B({text:P().nullable(),at:F(),kind:Yv});B({threads:R(B({contact:P(),name:P().nullable(),channel_last:pg,last:Xv,unread:I(),calls:I()})),next:P().nullable()});var Zv=B({kind:Yv,text:P().nullable(),at:F(),call:P(),channel:pg,duration_s:F().nullable().nullish(),answered:L().nullish()});B({contact:P(),name:P().nullable(),messages:R(Zv)}),B({text:P()}),B({contact:P(),call:P()}),B({facts:R(B({id:P(),contact:P(),text:P(),category:P().nullable(),written_at:F()})),next:P().nullable()}),B({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()}),B({configured:L(),issuer:P().nullable(),client_id:P().nullable(),domains:R(P()),role:P().nullable(),required:L(),redirect_uri:P()}),B({issuer:P(),client_id:P(),client_secret:P(),domains:R(P()),role:P().nullable().nullish(),required:L().nullish()}),B({configured:L(),host:P().nullable(),port:I().nullable(),security:P().nullable(),username:P().nullable(),from:P().nullable(),verified_at:P().nullable(),last_error:P().nullable()}),B({host:P(),port:I(),security:mp([`starttls`,`tls`,`none`]).nullish(),username:P().nullish(),password:P().nullish(),from:P()}),B({configured:L(),source:P().nullable(),host:P().nullable(),port:I().nullable(),security:P().nullable(),username:P().nullable(),from:P().nullable(),verified_at:P().nullable(),last_error:P().nullable()}),B({name:P(),logo_url:P().nullable(),accent:P()}),B({name:P().nullable().nullish(),logo_url:P().nullable().nullish(),accent:P().nullable().nullish()}),B({google:B({configured:L(),client_id:P().nullable(),redirect_uri:P()})}),B({client_id:P(),client_secret:P()}),B({sent:L(),error:P().nullable()}),B({orgs:R(B({org:P(),slug:P(),name:P()}))});var Qv=B({holder:P().nullable(),name:P().nullable()}),$v=B({agents:R(B({slug:P(),channels:R(pg),holder:Qv.nullish()}))}),ey=B({apps:R(B({app:P(),agents:R(P()),env:hg,host:P().nullable(),address:P().nullable(),sdk:P().nullable(),holder:Qv.nullable(),connected_at:F()}))}),ty=B({app:P(),stopped:L()});B({agent:P(),env:hg,held:L(),holding:Qv.nullish(),yours:L(),waiting:R(Qv),calling:R(P())}),B({files:R(Xg)}),B({questions:R(B({asks:P(),expects:P()})),k:I().nullish()});var ny=B({asks:P(),expects:P(),found:R(P())}),ry=B({base:P(),model:P(),questions:I(),k:I(),recall_at_k:F(),ndcg_at_10:F(),took_ms:F(),misses:R(ny)}),iy=B({base:P(),chunks:I(),took_ms:F()}),ay=B({bases:R(B({base:P(),chunks:I(),model:P(),pushed_at:F()}))}),oy=B({facts:R(B({id:P().nullish(),text:P(),category:P().nullish(),source:P().nullish(),valid_from:F(),invalidated_at:F().nullable()}))}),sy=B({forgotten:I()});B({questions:R(B({holds:R(P()),asks:P(),expects:R(P())})),k:I().nullish()});var cy=B({asks:P(),missing:R(P()),found:R(P())}),ly=B({model:P(),questions:I(),k:I(),recall_at_k:F(),ndcg_at_10:F(),took_ms:F(),misses:R(cy)}),uy=B({writes:R(P()).nullish(),never:R(P()).nullish(),never_says:R(P()).nullish(),invalidates:R(P()).nullish()});B({cases:R(B({name:P(),said:R(up([P(),P()])),holds:R(P()).nullish(),plants:R(P()).nullish(),channel:pg.nullish(),expect:uy.nullish()}))});var dy=B({check:P(),detail:P()}),fy=B({name:P(),held:L(),wrote:R(P()).nullish(),refused:R(P()).nullish(),broke:R(dy).nullish()}),py=B({agent:P(),model:P(),cases:I(),held:I(),took_ms:F(),results:R(fy)});B({tool:Cg,input:fp(P(),Zf()),speech_id:P().nullish()}),B({output:fp(P(),Zf()),took_ms:F()}),B({chunks:R(B({path:P(),heading:P().nullable(),text:P()}))}),B({ops:I(),took_ms:F()}),B({call:P(),agent:P(),to:P(),from:P(),env:hg});var my=B({dial_anywhere:L(),per_minute:I(),per_day:I(),max_duration_s:I()});B({ready:L(),kind:P().nullable(),from_numbers:R(P()),steps_missing:R(P()),guards:my}),B({steps:R(P()),dry_run:L(),ready:L(),trunk:P().nullish(),address:P().nullish()});var hy=B({voice:P().nullish(),tts:P().nullish(),tts_model:P().nullish(),stt:P().nullish(),llm:P().nullish(),greeting:Qg.nullish(),hangup:$g.nullish(),turn:Kg.nullish(),memory:e_.nullish(),knowledge:P().nullish(),bases:R(Zg).nullish()}),gy=B({holder:P(),version:I(),author:P(),note:P().nullable(),set_at:F(),config:hy}),_y=B({world:hg,yours:gy.nullable(),team:gy.nullable(),production:gy.nullable()});B({config:hy,if_version:I().nullable().nullish(),note:P().nullable().nullish(),team:L().nullish()});var vy=B({world:hg,holder:P(),rows:R(gy)});B({ours:gy.nullable(),theirs:gy.nullable(),changed:R(P())}),B({version:I(),team:L().nullish()});var yy=B({said:R(qg),heard:R(P())}),by=B({holder:P(),version:I(),author:P(),note:P().nullable(),set_at:F(),lexicon:yy}),xy=B({world:hg,yours:by.nullable(),team:by.nullable(),production:by.nullable()});B({lexicon:yy,if_version:I().nullable().nullish(),note:P().nullable().nullish(),team:L().nullish()}),B({world:hg,holder:P(),rows:R(by)}),B({config_version:I().nullable(),lexicon_version:I().nullable(),config:gy.nullable(),lexicon:by.nullable()});var Sy=B({bases:R(B({base:P(),agents:R(P())}))}),Cy={acquire_time:`s`,audio_duration:`s`,audio_tokens:`tokens`,avatar_joined_time:`unix s`,cache_creation_tokens:`tokens`,cached_tokens:`tokens`,cached_tokens_details:`object`,cancelled:`flag`,characters_count:`chars`,completion_tokens:`tokens`,connection_reused:`flag`,detection_delay:`s`,duration:`s`,e2e_latency:`s`,end_of_turn_delay:`s`,end_of_utterance_delay:`s`,idle_time:`s`,image_tokens:`tokens`,inference_count:`count`,inference_duration_total:`s`,input_audio_tokens:`tokens`,input_cache_creation_tokens:`tokens`,input_cached_audio_tokens:`tokens`,input_cached_image_tokens:`tokens`,input_cached_text_tokens:`tokens`,input_cached_tokens:`tokens`,input_image_tokens:`tokens`,input_text_tokens:`tokens`,input_token_details:`object`,input_tokens:`tokens`,label:`name`,llm_metadata:`object`,llm_node_tps:`tokens/s`,llm_node_ttfs:`s`,llm_node_ttft:`s`,metadata:`object`,model:`name`,model_name:`name`,model_provider:`name`,num_backchannels:`count`,num_interruptions:`count`,num_requests:`count`,on_user_turn_completed_delay:`s`,output_audio_tokens:`tokens`,output_reasoning_tokens:`tokens`,output_text_tokens:`tokens`,output_token_details:`object`,output_tokens:`tokens`,playback_latency:`s`,prediction_duration:`s`,prompt_cached_tokens:`tokens`,prompt_tokens:`tokens`,provider:`name`,provider_request_ids:`ids`,reasoning_tokens:`tokens`,request_id:`id`,segment_id:`id`,session_duration:`s`,session_started_time:`unix s`,speech_id:`id`,started_speaking_at:`unix s`,stopped_speaking_at:`unix s`,streamed:`flag`,stt_metadata:`object`,text_tokens:`tokens`,timestamp:`unix s`,tokens_per_second:`tokens/s`,total_duration:`s`,total_requests:`count`,total_tokens:`tokens`,transcription_delay:`s`,ttfb:`s`,ttft:`s`,tts_metadata:`object`,tts_node_ttfb:`s`,type:`tag`};function wy(e){let t=Ty();for(let n of e)t=Oy(t,n);return t}function Ty(){return{seq:0,agent:``,call:null,status:`idle`,channel:null,direction:null,from:null,to:null,caller:null,room:null,started_at:null,ended_at:null,end_reason:null,outcome:null,user_state:null,agent_state:null,live:{user:null,agent:null},turns:[],metrics:{llm:[],stt:[],tts:[],vad:[],eou:[],eot:[],interruption:[],realtime:[],avatar:[]},tools:[],app_state:{},events:[],prompt:{},tools_visible:[],confirms:[],memory:[],sources:[],handoff:{active:!1,by:null},held:!1,muted:!1,transfer:null,usage:[],cost:null,routes:[],gaps:[],errors:[],custom:[]}}var Ey=`unreadable`;function Dy(e,t,n){let r=n instanceof Error?n.message:String(n);return e.errors.push({seq:t.seq,code:Ey,message:`${t.type} at seq ${t.seq} is not the shape this reader knows: ${r.split(`
60
+ `)[0]?.trim()??r}`}),e}function Oy(e,t){let n;try{n=Rv(t)}catch(n){let r=Dy(e,t,n);return r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}let r=e;return n.type===`log.gap`?r=Iy(e,n):ky(e,t,n),r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}function ky(e,t,n){switch(n.type){case`call.ringing`:e.status=`ringing`,e.direction=`inbound`,Ay(e,n.data);return;case`call.dialing`:e.status=`dialing`,e.direction=`outbound`,Ay(e,n.data);return;case`call.started`:e.status=`active`,e.direction=n.data.direction,e.started_at=n.data.started_at,Ay(e,n.data);return;case`call.ended`:e.status=`ended`,e.ended_at=n.data.ended_at,e.end_reason=n.data.reason,e.live={user:null,agent:null};return;case`call.transferred`:e.transfer={to:n.data.to,mode:n.data.mode,status:n.data.ok?`done`:`failed`,by:e.transfer?.by??`agent`};return;case`call.line`:e.held=n.data.held,e.muted=n.data.muted;return;case`call.summary`:e.usage=[...n.data.usage],e.cost=n.data.cost,e.outcome=n.data.outcome,e.end_reason??=n.data.reason;return;case`user.state`:e.user_state=n.data.state;return;case`agent.state`:e.agent_state=n.data.state;return;case`user.transcript`:e.live.user=n.data.final?null:n.data.text;return;case`agent.transcript`:e.live.agent=n.data.final?null:Ry(e.live.agent,n.data);return;case`turn.user`:e.turns.push({role:`user`,...n.data}),e.live.user=null;return;case`turn.agent`:e.turns.push({role:`agent`,...n.data}),e.live.agent=null;return;case`memory.ops`:e.memory.push(...n.data.ops);return;case`docs.sources`:e.sources=[...n.data.sources];return;case`metrics.llm`:e.metrics.llm.push(n.data);return;case`metrics.stt`:e.metrics.stt.push(n.data);return;case`metrics.tts`:e.metrics.tts.push(n.data);return;case`metrics.vad`:e.metrics.vad.push(n.data);return;case`metrics.eou`:e.metrics.eou.push(n.data);return;case`metrics.eot`:e.metrics.eot.push(n.data);return;case`metrics.interruption`:e.metrics.interruption.push(n.data);return;case`metrics.realtime`:e.metrics.realtime.push(n.data);return;case`metrics.avatar`:e.metrics.avatar.push(n.data);return;case`tool.call`:e.tools.push({...n.data,status:`running`,seq:t.seq});return;case`tool.result`:jy(e,n.data);return;case`state.changed`:e.app_state={...n.data.state};return;case`prompt.changed`:e.prompt[n.data.name]={hash:n.data.hash,chars:n.data.chars,seq:t.seq};return;case`tools.changed`:e.tools_visible=[...n.data.visible];return;case`confirm.request`:e.confirms.push({tool:n.data.tool,call_id:n.data.call_id,audience:n.data.audience,phrase:n.data.phrase,status:`pending`});return;case`confirm.granted`:My(e,n.data.call_id,{status:`granted`,said:n.data.said});return;case`confirm.declined`:My(e,n.data.call_id,{status:`declined`,reason:n.data.reason,...n.data.said===void 0?{}:{said:n.data.said}});return;case`supervisor.took_over`:e.handoff={active:!0,by:n.data.by};return;case`supervisor.released`:e.handoff={active:!1,by:null};return;case`supervisor.transferred`:e.transfer={to:n.data.to,mode:n.data.mode,status:`requested`,by:`supervisor`};return;case`agent.registered`:e.routes=[...n.data.routes];return;case`error`:e.errors.push({seq:t.seq,code:n.data.code,message:n.data.message});return;case`custom`:e.custom.push({seq:t.seq,name:n.data.name,data:{...n.data.data}});return;case`room.opened`:e.room={name:n.data.name,sid:n.data.sid,participants:[],caller:null};return;case`participant.joined`:Ny(e,t,n.data);return;case`participant.left`:Py(e,n.data.identity);return;case`participant.speaking`:{let t=Fy(e,n.data.identity);t!==void 0&&(t.speaking=n.data.speaking);return}case`event.received`:{let{data:r,...i}=n.data;e.events.push({...i,seq:t.seq});return}case`track.published`:case`track.unpublished`:case`room.sent`:case`supervisor.said`:case`supervisor.whispered`:case`supervisor.ended`:case`agent.configured`:case`pong`:case`log.caught_up`:case`log.gap`:return}}function Ay(e,t){e.channel=t.channel,e.from=t.from,e.to=t.to,e.caller=t.caller}function jy(e,t){let n=Ly(e.tools,e=>e.call_id===t.call_id);if(n===-1)return;let{call_id:r,name:i,...a}=t,o=e.tools[n];e.tools[n]={...o,...a,status:a.error===void 0?`done`:`failed`}}function My(e,t,n){let r=Ly(e.confirms,e=>e.call_id===t);if(r===-1)return;let i=e.confirms[r];e.confirms[r]={...i,...n}}function Ny(e,t,n){e.room!==null&&(e.room.participants.push({...n,joined_at:t.ts,speaking:!1}),n.kind===`caller`&&(e.room.caller=n.identity))}function Py(e,t){if(e.room===null)return;let n=e.room.participants.findIndex(e=>e.identity===t);n!==-1&&e.room.participants.splice(n,1),e.room.caller===t&&(e.room.caller=null)}function Fy(e,t){return e.room?.participants.find(e=>e.identity===t)}function Iy(e,t){let n=t.data.snapshot===null?e:structuredClone(t.data.snapshot);return n.gaps.push({from_seq:t.data.from_seq,to_seq:t.data.to_seq}),n}function Ly(e,t){for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1}function Ry(e,t){if(e===null||e===``)return t.text;let n=/\s$/.test(e)||/^\s/.test(t.text);return t.start!=null&&!n?`${e} ${t.text}`:`${e}${t.text}`}var zy=500,By=8e3,Vy=204,Hy=class{#e=``;#t=null;#n=null;#r=[];feed(e){this.#e+=e;let t=[],n;for(;(n=this.#e.search(/\r\n|\n|\r/))!==-1;){let e=this.#e.slice(0,n);this.#e=this.#e.slice(n+(this.#e.startsWith(`\r
61
61
  `,n)?2:1));let r=this.#i(e);r!==null&&t.push(r)}return t}#i(e){if(e===``){if(this.#r.length===0&&this.#n===null&&this.#t===null)return null;let e={id:this.#t,event:this.#n,data:this.#r.join(`
62
- `)};return this.#n=null,this.#r=[],e}if(e.startsWith(`:`))return null;let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1).replace(/^ /,``);return n===`id`?this.#t=r:n===`event`?this.#n=r:n===`data`&&this.#r.push(r),null}};function Hy(e,t,n){let r=new AbortController,i=null,a=null,o=Ry,s=!0,c=()=>{i===null&&(i=window.setTimeout(()=>{i=null,n.onPaint()},100))},l=e=>{if(e.id!==null&&(a=e.id),e.data!==``){try{n.onEntry(Lv(JSON.parse(e.data)))}catch(e){n.onRefused(String(e));return}c()}};return n.onConnection(`connecting`),(async()=>{for(;s;){let i;try{i=await fetch(e,{headers:{...ra(t),accept:`text/event-stream`,...a===null?{}:{"last-event-id":a}},signal:r.signal})}catch{if(!s)return;n.onConnection(`reconnecting`),await Uy(o,r.signal),o=Math.min(o*2,zy);continue}if(i.status===By){n.onConnection(`ended`);return}if(!i.ok||i.body===null){n.onRefused(`the stream answered ${i.status}`),n.onConnection(`ended`);return}n.onConnection(`live`),o=Ry;let c=new Vy,u=new TextDecoder,d=i.body.getReader();try{for(;;){let{value:e,done:t}=await d.read();if(t)break;for(let t of c.feed(u.decode(e,{stream:!0})))l(t)}}catch{if(!s)return}if(!s)return;n.onConnection(`reconnecting`),await Uy(o,r.signal),o=Math.min(o*2,zy)}})(),()=>{s=!1,i!==null&&window.clearTimeout(i),r.abort()}}function Uy(e,t){return new Promise(n=>{let r=window.setTimeout(n,e);t.addEventListener(`abort`,()=>{window.clearTimeout(r),n()},{once:!0})})}var Wy=3e3;function Gy(e=50){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(`connecting`),[o,s]=(0,D.useState)(0),[c,l]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=Wv.parse(await k(t,`/v1/sessions`,{limit:e}));n||(r(i.calls),l(null))}catch(e){n||l(String(e))}};i();let o=window.setInterval(()=>void i(),Wy),c=Hy(la(t,`/v1/events`),t,{onEntry(e){(e.type===`agent.registered`||e.type===`agent.detached`)&&s(e=>e+1),i()},onPaint:()=>void 0,onConnection:a,onRefused:l});return()=>{n=!0,window.clearInterval(o),c()}},[t,e]),{lines:n,connection:i,agentsChanged:o,error:c}}function Ky(e=0){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{let e=!1;return(async()=>{try{let n=$v.parse(await k(t,`/v1/agents`));e||(r(n.agents),a(null))}catch(t){e||a(String(t))}finally{e||s(!0)}})(),()=>{e=!0}},[t,e]),{agents:n,error:i,loaded:o}}var qy=200,Jy=(0,D.createContext)(null);function Yy({children:e}){let t=j(),n=wh(),r=Gy(qy),i=ug(),a=dg(),o=Ky(r.agentsChanged),[s,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=!1;return Gp(t).then(t=>{e||c(t)},()=>{e||c(null)}),()=>{e=!0}},[t]);let l=Gh(n),u=(0,D.useMemo)(()=>({lines:r.lines,live:r.lines.filter(e=>e.live),connection:r.connection,floorError:r.error,held:o.agents,agents:Uh(o.agents,l),agentsLoaded:o.loaded,agentsError:o.error,orgs:s,here:s?.find(e=>e.here)??null,insights:i,operator:a}),[r.lines,r.connection,r.error,o.agents,o.loaded,o.error,s,l,i,a]);return(0,A.jsx)(Jy,{value:u,children:e})}function Xy(){let e=(0,D.useContext)(Jy);if(e===null)throw Error(`a screen was mounted outside the shell's org`);return e}var Zy={talk:`talk`,chat:`talk`,devchat:`talk`,calls:`calls`,sessions:`calls`,pipeline:`pipeline`,settings:`words`,lexicon:`words`,knowledge:`knowledge`,memory:`memory`,evals:`evals`,widget:`talk`,agents:`calls`,live:`calls`,"org-evals":`evals`,"org-memory":`memory`,numbers:`numbers`,providers:`providers`,team:`team`,usage:`usage`};function Qy(e,t){let n=Zy[t];return n===void 0||e.includes(n)}var $y=[`app`,`calls`,`evals`,`keys`,`knowledge`,`memory`,`numbers`,`pipeline`,`providers`,`supervise`,`talk`,`team`,`usage`,`words`];function eb(e){let t=$y.filter(t=>!e.includes(t));return t.length===0||t.length===1&&t[0]===`app`?`everything`:e.join(`, `)}var tb=z({fingerprint:P(),label:P().nullable(),kind:mp([`person`,`server`]),env:mp([`production`,`sandbox`]).nullable(),name:P().nullable(),created_by:P().nullable(),created_at:P(),last_used_at:P().nullable(),revoked_at:P().nullable(),scopes:R(P())}),nb=z({key:P(),key_id:P(),label:P().nullable(),env:P(),scopes:R(P())});async function rb(e){return R(tb).parse(await k(e,`/v1/keys`))}async function ib(e,t){return nb.parse(await sa(e,`/v1/keys`,t))}async function ab(e,t){await sa(e,`/v1/keys/${encodeURIComponent(t)}/revoke`,{})}async function ob(e){return ey.parse(await k(e,`/v1/apps`)).apps}async function sb(e,t){ty.parse(await sa(e,`/v1/apps/${encodeURIComponent(t)}/stop`,{}))}function cb({held:e,stops:t}){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=!1;return ob(n).then(t=>{e||i(t)},t=>{e||o(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[n,e]);let s=async e=>{o(null);try{await sb(n,e),i(await ob(n))}catch(e){o(e instanceof na?e.message:String(e))}};return r===null&&a===null?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Processes`,meta:`the machines holding these agents — a stop closes one, and it exits instead of dialling back`}),(0,A.jsx)(Nm,{children:a}),(0,A.jsxs)(`div`,{className:`ui-card-list`,children:[r?.length===0&&(0,A.jsx)(`div`,{className:`agents-none`,children:`No process is connected.`}),r?.map(e=>(0,A.jsx)(lb,{app:e,stop:t?s:void 0},e.app))]})]})}function lb({app:e,stop:t}){let[n,r]=(0,D.useState)(!1),i=e.holder===null?`the org's`:e.holder.name??e.holder.holder??``,a=`${e.host??`an unnamed host`}${e.address===null?``:` (${e.address})`}`;return(0,A.jsx)(`div`,{onMouseLeave:()=>r(!1),children:(0,A.jsx)(Fm,{name:e.agents.join(`, `)||e.app,sub:`${a} · ${e.sdk??`an unknown sdk`} · ${i} · connected ${eg(e.connected_at)}`,end:t!==void 0&&(0,A.jsx)(Bm,{danger:!0,onClick:()=>n?void t(e.app):r(!0),children:n?`Stop it`:`Stop`})})})}var ub=z({route:z({org:P(),agent:P(),channel:mp([`phone`,`web`,`whatsapp`]),number:P().nullable(),label:P().nullable(),env:mp([`production`,`sandbox`]),managed:L().default(!1)}),source:mp([`operator`,`app`])}),db=z({kind:mp([`twilio`,`sip`]),account:P()}),fb=z({kind:mp([`twilio`,`sip`]),numbers:R(z({number:P(),name:P(),imported:L()}))}),pb=z({route:ub.shape.route,steps:R(P()),dry_run:L()});async function mb(e){return R(ub).parse(await k(e,`/v1/numbers`))}async function hb(e){try{return db.parse(await k(e,`/v1/carrier`))}catch(e){if(Ob(e,404))return null;throw e}}async function gb(e,t){await oa(e,`/v1/carrier`,t)}async function _b(e){await ca(e,`/v1/carrier`)}async function vb(e){return fb.parse(await k(e,`/v1/numbers/available`))}async function yb(e,t,n){return pb.parse(await sa(e,`/v1/numbers${n?`?dry_run=true`:``}`,t))}async function bb(e,t,n){return pb.parse(await sa(e,`/v1/numbers/buy${n?`?dry_run=true`:``}`,t))}async function xb(e,t){await ca(e,`/v1/numbers/${encodeURIComponent(t)}`)}var Sb=np({ready:L(),kind:P().nullish(),from_numbers:R(P()),steps_missing:R(P()),guards:np({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()})}),Cb=np({steps:R(P()),dry_run:L(),ready:L()});async function wb(e){try{return Sb.parse(await k(e,`/v1/carrier/outbound`))}catch(e){if(Ob(e,404)||Ob(e,405)||Ob(e,403))return null;throw e}}async function Tb(e,t){return Cb.parse(await sa(e,`/v1/carrier/outbound${t?`?dry_run=true`:``}`,{}))}var Eb=np({call:P()});async function Db(e,t,n,r){let i=r===void 0||r===``?{to:n}:{to:n,from:r};return Eb.parse(await sa(e,`/v1/agents/${encodeURIComponent(t)}/dial`,i)).call}function Ob(e,t){return typeof e==`object`&&!!e&&e.status===t}var kb=z({vendors:R(P())});async function Ab(e){return kb.parse(await k(e,`/v1/provider-keys`)).vendors}async function jb(e,t,n){await oa(e,`/v1/provider-keys/${encodeURIComponent(t)}`,{key:n})}async function Mb(e,t){await ca(e,`/v1/provider-keys/${encodeURIComponent(t)}`)}var Nb=`minmax(0,1.5fr) minmax(0,1.3fr) minmax(0,1.1fr) 90px 90px`;function Pb(){let e=j(),t=Eh(),[n,r]=(0,D.useState)({numbers:null,free:null,keys:null,catalogue:null,brought:[]}),i=e=>Sm(vm,e)&&t!==null&&Qy(t,e),a=i(`numbers`),o=Sm(vm,`tokens`),s=i(`providers`);return(0,D.useEffect)(()=>{let t=!1;return(async()=>{let[n,i,c,l,u]=await Promise.all([a?mb(e).catch(()=>null):Promise.resolve(null),a?vb(e).catch(()=>null):Promise.resolve(null),o?rb(e).catch(()=>null):Promise.resolve(null),s?Lh(e).catch(()=>null):Promise.resolve(null),s?Ab(e).catch(()=>[]):Promise.resolve([])]);t||r({numbers:n,free:i===null?null:i.numbers.filter(e=>!e.imported).length,keys:c,catalogue:l,brought:u})})(),()=>{t=!0}},[e,a,o,s]),n}function Fb(){let{held:e,agents:t,live:n,lines:r,connection:i,agentsError:a,agentsLoaded:o,insights:s}=Xy(),c=Gh(wh()),l=Eh(),u=Pb(),[d,f]=(0,D.useState)(`everything`),p=rg(r,ng().today),m=e.some(e=>Vh(e,c)),h=m?Hh(e,d,c):t,g=new Set((u.numbers??[]).map(e=>e.route.agent)),_=new Set([...t.map(e=>e.slug),...g]),v=e=>(u.numbers??[]).filter(t=>t.route.agent===e&&t.route.number!==null).map(e=>og(e.route.number)),y=u.keys?.filter(e=>e.revoked_at===null)??[],b=u.catalogue?.providers.filter(e=>e.standing===`ready`)??[],x=fm===`hosted`&&l!==null&&l.includes(`app`);return(0,A.jsxs)(sh,{children:[(0,A.jsx)(ch,{title:`Overview`,lede:`Which agents this gateway is holding right now — the list changes the moment a socket connects.`,actions:x?(0,A.jsx)(zm,{to:`/tokens`,size:`base`,children:`New server token`}):void 0}),(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{label:`Agents up`,value:t.length,of:`of ${_.size}`}),u.numbers===null?(0,A.jsx)(uh,{label:`Calls live`,value:n.length}):(0,A.jsx)(uh,{label:`Numbers ringing`,value:u.numbers.filter(e=>e.route.number!==null).length,of:u.free===null?void 0:`· ${u.free} free`}),u.keys===null?(0,A.jsx)(uh,{label:`Calls today`,value:p.length}):(0,A.jsx)(uh,{label:`Active tokens`,value:y.length,of:`· ${u.keys.length-y.length} revoked`}),u.catalogue!==null&&(0,A.jsx)(uh,{label:`Providers ready`,value:b.length,of:`of ${u.catalogue.providers.length}`})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Agents`,meta:`the list changes the moment a socket connects`,action:(0,A.jsxs)(`span`,{className:`agents-watching`,children:[(0,A.jsx)(eh,{tone:i===`live`?`green`:void 0,small:!0}),i===`live`?`watching`:i]}),children:m&&(0,A.jsx)(`div`,{className:`agents-corners`,children:(0,A.jsx)(Km,{options:Bh.map(e=>({value:e,label:e})),value:d,onChange:f})})}),(0,A.jsx)(Nm,{children:a}),o&&h.length===0&&(0,A.jsx)(Mm,{children:d===`everything`?fm===`local`?(0,A.jsxs)(A.Fragment,{children:[`Nothing of yours is running. `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in a project puts its agents here.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing is running in production: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start --prod`}),` on your server holds it, on a server token.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing here is `,d,`.`]})}),h.length>0&&(0,A.jsx)(dh,{columns:Nb,padding:`9px 16px`,labels:[`Agent`,`Doors`,`Numbers`,`Today>`,`Score>`]}),h.map((e,t)=>{let i=n.filter(t=>t.agent===e.slug).length,a=r.find(t=>t.agent===e.slug),o=v(e.slug);return(0,A.jsxs)(fh,{columns:Nb,padding:`13px 16px`,to:`/a/${e.slug}/talk`,children:[(0,A.jsxs)(`div`,{className:`agents-name`,children:[(0,A.jsx)(ah,{name:e.slug,letters:e.slug.slice(0,1).toUpperCase(),tint:nh(t)}),(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`ui-cell-strong ui-clip`,children:e.slug}),i>0?(0,A.jsxs)(`div`,{className:`agents-live`,children:[(0,A.jsx)(eh,{tone:`green`,small:!0}),i===1?`1 call live`:`${i} calls live`]}):(0,A.jsxs)(`div`,{className:`agents-idle`,children:[m?`${Wh(e)} · `:``,`idle`,a===void 0?``:` · last call ${eg(a.started_at)}`]})]})]}),(0,A.jsx)(`div`,{className:`ui-tags`,children:e.channels.map(e=>(0,A.jsx)($m,{children:e},e))}),(0,A.jsx)(`span`,{className:`agents-numbers ui-clip`,children:o.length===0?`—`:o.join(`, `)}),(0,A.jsx)(`span`,{className:`agents-figure`,children:s?.agents.find(t=>t.slug===e.slug)?.today??p.filter(t=>t.agent===e.slug).length}),(0,A.jsx)(Rb,{share:s?.agents.find(t=>t.slug===e.slug)?.score??null})]},`${e.slug}/${e.holder?.holder??``}`)}),h.length>0&&(0,A.jsx)(jm,{children:(0,A.jsx)(`span`,{children:h.length>1?`Every agent writes the same log — open one to read its turns.`:`Open the agent to read its turns.`})})]}),(0,A.jsx)(cb,{held:e,stops:l!==null&&l.includes(`app`)}),(u.keys!==null||u.catalogue!==null)&&(0,A.jsxs)(`div`,{className:`agents-split`,children:[u.keys!==null&&(0,A.jsx)(Ib,{tokens:u.keys}),u.catalogue!==null&&(0,A.jsx)(Lb,{catalogue:u.catalogue,brought:u.brought})]})]})}function Ib({tokens:e}){let t=[...e].sort((e,t)=>Number(e.revoked_at!==null)-Number(t.revoked_at!==null)).slice(0,4);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Tokens in use`,action:(0,A.jsx)(Am,{to:`/tokens`,children:`Manage`})}),(0,A.jsxs)(`div`,{className:`ui-card-list`,children:[t.length===0&&(0,A.jsx)(`div`,{className:`agents-none`,children:`No token has been made yet.`}),t.map(e=>(0,A.jsx)(Fm,{name:e.label??e.fingerprint,sub:e.kind===`person`?`${e.name??`a person`} · their own`:`the org's · ${e.env??``}${e.created_by===null?``:` · made by ${e.created_by}`}`,end:e.revoked_at===null?(0,A.jsx)(Qm,{tone:`green`,children:`active`}):(0,A.jsx)(Qm,{tone:`muted`,children:`revoked`})},e.fingerprint))]})]})}function Lb({catalogue:e,brought:t}){let n=e.providers.filter(e=>e.standing===Ah),r=new Set(Object.values(e.defaults).map(e=>e.split(`/`)[0]??e)),i=[...n].sort((e,n)=>Number(t.includes(n.name))-Number(t.includes(e.name))||Number(r.has(n.name))-Number(r.has(e.name))||e.name.localeCompare(n.name));return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Providers`,meta:`${n.length} ready · ${e.providers.length-n.length} need a key`,action:(0,A.jsx)(Am,{to:`/providers`,children:`Bring one`})}),(0,A.jsx)(`div`,{className:`ui-card-list`,children:i.slice(0,4).map(n=>(0,A.jsx)(Fm,{name:n.name.charAt(0).toUpperCase()+n.name.slice(1),sub:Bb(n,e),end:t.includes(n.name)?(0,A.jsx)(Qm,{tone:`green`,children:`ready`}):(0,A.jsx)(Qm,{tone:`amber`,children:`box key`})},n.name))})]})}function Rb({share:e}){return e===null?(0,A.jsx)(`span`,{className:`agents-figure agents-score`,children:`—`}):(0,A.jsxs)(`span`,{className:`agents-figure ${e>=.9?`agents-score-good`:e>=.7?`agents-score-fair`:`agents-score-poor`}`,children:[Math.round(e*100),`%`]})}var zb={llm:`decides`,stt:`hears`,tts:`speaks`};function Bb(e,t){let n=e.does.filter(n=>(t.defaults[n]??``).split(`/`)[0]===e.name);return n.length>0?`${n.map(e=>zb[e]).join(`, `)} · the default`:`${e.does.map(e=>zb[e]).join(`, `)} · ${e.note}`}var Vb=`/v1/ops`,Hb=np({worker:P(),active:F(),max_jobs:F().nullish(),load:F(),draining:L(),cordoned:L(),seen_at:F()}),Ub=np({now:F(),stale_after_s:F(),workers:R(Hb)}),Wb=np({route:np({agent:P(),channel:P(),number:P().nullish(),env:P(),managed:L().nullish()}),source:P()}),Gb=np({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),cost_eur:F()}),Kb=np({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F()}),qb=np({rows:R(Gb),totals:fp(P(),Kb),next:F().nullish()});async function Jb(e){return Ub.parse(await k(e,`${Vb}/fleet`))}async function Yb(e,t,n){let r=`${Vb}/fleet/${encodeURIComponent(t)}/cordon`;await(n?sa(e,r,{}):ca(e,r))}async function Xb(e,t,n){return R(Wb).parse(await k(e,`${Vb}/routes`,{org:t,env:n}))}async function Zb(e,t){return np({overrides:P().nullish()}).parse(await sa(e,`${Vb}/routes`,t)).overrides??null}async function Qb(e,t,n){await ca(e,`${Vb}/routes/${encodeURIComponent(n)}?org=${encodeURIComponent(t)}`)}async function $b(e,t,n){return qb.parse(await k(e,`${Vb}/usage`,{after:t,limit:n}))}function ex(e){let[t,n]=(0,D.useState)(void 0),[r,i]=(0,D.useState)(null),a=(0,D.useCallback)(async()=>{try{n(await e()),i(null)}catch(e){i(tx(e))}},[e]);return(0,D.useEffect)(()=>{let t=!1;return e().then(e=>{t||n(e)},e=>{t||i(tx(e))}),()=>{t=!0}},[e]),{value:t,refused:r,reread:a}}function tx(e){return e instanceof na||e instanceof Error?e.message:String(e)}function nx(){let[e,t]=(0,D.useState)(!1),[n,r]=(0,D.useState)(null);return{busy:e,refused:n,move:(0,D.useCallback)(async e=>{t(!0),r(null);try{return await e(),!0}catch(e){return r(tx(e)),!1}finally{t(!1)}},[])}}var rx=5e3,ix=`minmax(0,1.4fr) 150px 130px 120px 90px`;function ax(){let e=j(),t=ex((0,D.useCallback)(()=>Jb(e),[e])),n=nx(),{reread:r}=t;(0,D.useEffect)(()=>{let e=window.setInterval(()=>void r(),rx);return()=>window.clearInterval(e)},[r]);let i=t.value,a=e=>i!==void 0&&i.now-e.seen_at>i.stale_after_s,o=(i?.workers??[]).filter(e=>!a(e)&&!e.cordoned&&!e.draining),s=(i?.workers??[]).reduce((e,t)=>e+t.active,0),c=(i?.workers??[]).reduce((e,t)=>e+(a(t)?0:t.max_jobs??0),0);return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Fleet`,lede:`Every worker the hub has heard from. A cordoned worker finishes its calls and is handed no new one — the move before a deploy, and it ends nothing.`}),(0,A.jsx)(Nm,{children:t.refused??n.refused}),i!==void 0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{size:`small`,label:`Workers taking calls`,value:o.length,of:`of ${i.workers.length}`}),(0,A.jsx)(uh,{size:`small`,label:`Calls right now`,value:s,of:c>0?`of ${c} seats`:void 0}),(0,A.jsx)(uh,{size:`small`,label:`Cordoned`,value:i.workers.filter(e=>e.cordoned).length})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Workers`,meta:`re-read every ${rx/1e3} s`}),i.workers.length===0?(0,A.jsx)(Mm,{children:`No worker has reported. A hub with none answers every call on itself.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:ix,labels:[`Worker`,`Calls`,`Load`,`Standing`,``]}),i.workers.map(t=>{let[i,o]=ox(t,a(t));return(0,A.jsxs)(fh,{columns:ix,children:[(0,A.jsx)(`span`,{className:a(t)?`ui-cell-faint box-fixed ui-clip`:`ui-cell-strong box-fixed ui-clip`,children:t.worker}),(0,A.jsxs)(`span`,{className:`ui-cell-ink`,children:[t.active,t.max_jobs===null||t.max_jobs===void 0?``:` / ${t.max_jobs}`]}),(0,A.jsxs)(`span`,{className:`box-load`,children:[(0,A.jsx)(oh,{share:Math.min(1,t.load)}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:t.load.toFixed(2)})]}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:o,children:i})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{disabled:n.busy,onClick:()=>void n.move(async()=>{await Yb(e,t.worker,!t.cordoned),await r()}),children:t.cordoned?`Uncordon`:`Cordon`})})]},t.worker)})]})]})]})]})}function ox(e,t){return t?[`not heard from`,`gray`]:e.draining?[`draining`,`amber`]:e.cordoned?[`cordoned`,`amber`]:[`taking calls`,`green`]}var sx=`/v1/ops`,cx=e=>`${sx}/orgs/${encodeURIComponent(e)}`,lx=[`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`,`budget_eur`],ux=F().nullish(),dx=np({id:P(),slug:P(),name:P()}),fx=np({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()}),px=dx.extend({quotas:np({minutes:ux,messages:ux,agents:ux,concurrent_calls:ux,memory_facts:ux,knowledge_chunks:ux,numbers:ux,seats:ux,budget_eur:ux}),dialling:fx.nullish(),holding:np({memory_facts:F(),knowledge_chunks:F(),numbers:F(),seats:F()})}),mx=np({fingerprint:P(),label:P().nullish(),created_at:P(),revoked_at:P().nullish(),env:P(),scopes:R(P()),subject:P().nullish(),name:P().nullish()}),hx=np({key:P(),key_id:P(),label:P().nullish(),env:P(),scopes:R(P())}),gx=np({id:P(),email:P(),name:P(),role:P(),agents:R(P()),status:P(),operator:L().nullish()}),_x=np({member:gx,token:P().nullish(),expires_at:P().nullish(),mailed:L().nullish()}),vx=np({configured:L(),issuer:P().nullish(),domains:R(P()).nullish(),required:L()});async function yx(e){return R(dx).parse(await k(e,`${sx}/orgs`))}async function bx(e,t){return px.parse(await k(e,cx(t)))}async function xx(e,t,n){return dx.parse(await sa(e,`${sx}/orgs`,{slug:t,name:n||null}))}async function Sx(e,t){await ca(e,cx(t))}async function Cx(e,t,n){await oa(e,`${cx(t)}/quotas`,n)}async function wx(e,t,n){await oa(e,`${cx(t)}/dialling`,n)}async function Tx(e,t,n){return np({logs:F(),numbers:R(P())}).parse(await oa(e,`${cx(t)}/agents`,{agent:n}))}async function Ex(e,t){return R(mx).parse(await k(e,`${cx(t)}/keys`))}async function Dx(e,t,n){return hx.parse(await sa(e,`${cx(t)}/keys`,n))}async function Ox(e,t){await sa(e,`${sx}/keys/${encodeURIComponent(t)}/revoke`,{})}async function kx(e,t){return np({members:R(gx),seated:F()}).parse(await k(e,`${cx(t)}/members`))}async function Ax(e,t,n){return _x.parse(await sa(e,`${cx(t)}/members`,n))}async function jx(e,t,n,r){await oa(e,`${cx(t)}/members/${encodeURIComponent(n)}/operator`,{operator:r})}async function Mx(e,t,n){await ca(e,`${cx(t)}/members/${encodeURIComponent(n)}`)}async function Nx(e,t){return np({vendors:R(P())}).parse(await k(e,`${cx(t)}/provider-keys`)).vendors}async function Px(e,t,n,r){await oa(e,`${cx(t)}/provider-keys/${encodeURIComponent(n)}`,{key:r})}async function Fx(e,t,n){await ca(e,`${cx(t)}/provider-keys/${encodeURIComponent(n)}`)}async function Ix(e,t){try{return vx.parse(await k(e,`${cx(t)}/sso`))}catch{return null}}async function Lx(e,t,n){await oa(e,`${cx(t)}/sso/required`,{required:n})}var Rx=`minmax(0,1fr) 96px 140px minmax(0,1.3fr) 92px`,zx=[{name:`app — what a deployed agent runs on`,scopes:[`app`]},{name:`everything — the org's own machine key`,scopes:null}];function Bx({named:e}){let t=j(),n=ex((0,D.useCallback)(()=>Ex(t,e),[t,e])),r=nx(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(`production`),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(null),[m,h]=(0,D.useState)(!1),g=async i=>{i.preventDefault(),await r.move(async()=>{p(await Dx(t,e,{label:o.trim(),env:c,scopes:zx[u]?.scopes??null})),h(!1),await n.reread()})&&(s(``),a(!1))},_=(n.value??[]).filter(e=>e.revoked_at===null||e.revoked_at===void 0).length;return(0,A.jsxs)(A.Fragment,{children:[f!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The key for ${f.label??`this machine`}`,meta:`copy it now: the table keeps its sha256, and it is never shown again`,children:(0,A.jsxs)(`span`,{className:`box-head-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(f.key).then(()=>h(!0)),children:m?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>p(null),children:`Done`})]})}),(0,A.jsx)(`pre`,{className:`ui-code`,children:f.key})]}),(0,A.jsx)(Nm,{children:n.refused??r.refused}),n.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Keys`,meta:`${_} live`,action:i?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>a(!0),children:`Issue a key`})}),i&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void g(e),children:[(0,A.jsx)(Wm,{label:`What it is for`,grow:!0,minWidth:200,children:(0,A.jsx)(W,{value:o,placeholder:`prod server`,onChange:e=>s(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`World`,minWidth:130,children:(0,A.jsxs)(Hm,{value:c,onChange:e=>l(e.target.value),children:[(0,A.jsx)(`option`,{value:`production`,children:`production`}),(0,A.jsx)(`option`,{value:`sandbox`,children:`sandbox`})]})}),(0,A.jsx)(Wm,{label:`Opens`,minWidth:260,children:(0,A.jsx)(Hm,{value:String(u),onChange:e=>d(Number(e.target.value)),children:zx.map((e,t)=>(0,A.jsx)(`option`,{value:t,children:e.name},e.name))})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:r.busy||o.trim()===``,children:r.busy?`Issuing…`:`Issue`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`A machine's key names nobody: people get theirs by signing in.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>a(!1),children:`Close`})})]})]}),n.value.length===0?(0,A.jsx)(Mm,{children:`No key issued to this org yet.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:Rx,labels:[`Key`,`World`,`Whose`,`Opens`,``]}),n.value.map(e=>{let i=e.revoked_at!==null&&e.revoked_at!==void 0;return(0,A.jsxs)(fh,{columns:Rx,children:[(0,A.jsx)(`span`,{className:i?`ui-cell-faint ui-clip`:`ui-cell-strong ui-clip`,title:e.fingerprint,children:e.label??e.fingerprint.slice(0,12)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:e.env===`production`?`green`:`indigo`,children:e.env})}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.name??`a machine`}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip`,title:e.scopes.join(`, `),children:eb(e.scopes)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:i?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`revoked`}):(0,A.jsx)(Bm,{danger:!0,disabled:r.busy,onClick:()=>void r.move(async()=>{await Ox(t,e.fingerprint),await n.reread()}),children:`Revoke`})})]},e.fingerprint)})]})]})]})}var Vx={minutes:{name:`Minutes`,about:`of call, ever`},messages:{name:`Messages`,about:`written turns, ever`},agents:{name:`Agents`,about:`slugs held at once`},concurrent_calls:{name:`Concurrent calls`,about:`calls at once`},memory_facts:{name:`Memory facts`,about:`facts kept`},knowledge_chunks:{name:`Knowledge chunks`,about:`chunks kept`},numbers:{name:`Numbers`,about:`numbers this box bought`},seats:{name:`Seats`,about:`people invited or active`},budget_eur:{name:`Budget, €`,about:`a month's spend`}},Hx={memory_facts:`memory_facts`,knowledge_chunks:`knowledge_chunks`,numbers:`numbers`,seats:`seats`},Ux=e=>e.replace(/[^0-9]/g,``);function Wx({org:e,onSaved:t}){let n=j(),r=nx(),i=nx(),[a,o]=(0,D.useState)(()=>Object.fromEntries(lx.map(t=>[t,e.quotas[t]===null||e.quotas[t]===void 0?``:String(e.quotas[t])]))),[s,c]=(0,D.useState)(null),l=e.dialling??null,[u,d]=(0,D.useState)(l?.dial_anywhere??!1),[f,p]=(0,D.useState)(String(l?.per_minute??``)),[m,h]=(0,D.useState)(String(l?.per_day??``)),[g,_]=(0,D.useState)(String(l?.max_duration_s??``)),v=async()=>{c(null),await r.move(async()=>{await Cx(n,e.slug,Object.fromEntries(lx.map(e=>[e,a[e]===``?null:Number(a[e])]))),await t()})&&c(`quotas`)},y=async()=>{c(null),await i.move(async()=>{await wx(n,e.slug,{dial_anywhere:u,per_minute:Number(f),per_day:Number(m),max_duration_s:Number(g)}),await t()})&&c(`dialling`)};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Quotas`,meta:`empty is no limit · 0 refuses everything`}),(0,A.jsx)(`div`,{className:`box-limits`,children:lx.map(t=>(0,A.jsxs)(Wm,{label:Vx[t].name,children:[(0,A.jsx)(W,{inputMode:`numeric`,value:a[t]??``,placeholder:`no limit`,onChange:e=>o({...a,[t]:Ux(e.target.value)})}),(0,A.jsxs)(`div`,{className:`box-limit-about`,children:[Vx[t].about,Hx[t]!==void 0&&` · holding ${e.holding[Hx[t]]}`]})]},t))}),(0,A.jsxs)(`div`,{className:`box-save`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:r.busy,onClick:()=>void v(),children:r.busy?`Saving…`:`Save the quotas`}),s===`quotas`&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. They bite the next call and the next register.`})]}),(0,A.jsx)(Nm,{children:r.refused})]}),l!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Outbound calls`,meta:`the fence around the calls this org's agents place`}),(0,A.jsxs)(`div`,{className:`box-anywhere`,children:[(0,A.jsxs)(`span`,{className:`box-anywhere-words`,children:[(0,A.jsx)(`strong`,{children:`Call anybody`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Off, an agent only calls numbers that already called or wrote to this org — "call back" means back.`})]}),(0,A.jsx)(Jm,{on:u,onChange:d,label:`Call anybody`})]}),(0,A.jsxs)(`div`,{className:`box-limits`,children:[(0,A.jsx)(Wm,{label:`Calls a minute`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:f,onChange:e=>p(Ux(e.target.value))})}),(0,A.jsx)(Wm,{label:`Calls a day`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:m,onChange:e=>h(Ux(e.target.value))})}),(0,A.jsx)(Wm,{label:`Longest call, seconds`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:g,onChange:e=>_(Ux(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`box-save`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:i.busy,onClick:()=>void y(),children:i.busy?`Saving…`:`Save the guards`}),s===`dialling`&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. They bite the next dial.`})]}),(0,A.jsx)(Nm,{children:i.refused})]})]})}var Gx=[`admin`,`manager`,`developer`,`supervisor`,`qa`],Kx=`minmax(0,1fr) minmax(0,1.3fr) 100px 90px 220px`,qx={active:`green`,invited:`amber`,disabled:`gray`};function Jx({named:e,seats:t}){let n=j(),r=ex((0,D.useCallback)(()=>kx(n,e),[n,e])),i=nx(),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(`admin`),[h,g]=(0,D.useState)(null),_=async t=>{t.preventDefault(),await i.move(async()=>{c(await Ax(n,e,{email:l.trim(),name:d.trim(),role:p,agents:[]})),await r.reread()})&&(u(``),f(``),o(!1))},v=e=>void i.move(async()=>{await e(),await r.reread()});return(0,A.jsxs)(A.Fragment,{children:[s!==null&&(0,A.jsx)(Yx,{invited:s,onClose:()=>c(null)}),(0,A.jsx)(Nm,{children:r.refused??i.refused}),r.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Members`,meta:`${r.value.seated} seated${t===null?``:` of ${t}`}`,action:a?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>o(!0),children:`Invite someone`})}),a&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void _(e),children:[(0,A.jsx)(Wm,{label:`Email`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{type:`email`,value:l,placeholder:`name@company.com`,onChange:e=>u(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Name`,grow:!0,minWidth:150,children:(0,A.jsx)(W,{value:d,placeholder:`Full name`,onChange:e=>f(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Role`,minWidth:130,children:(0,A.jsx)(Hm,{value:p,onChange:e=>m(e.target.value),children:Gx.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:i.busy,children:i.busy?`Inviting…`:`Invite`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`The box's invitation takes no seat: it is how an org gets its first admin.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>o(!1),children:`Close`})})]})]}),r.value.members.length===0?(0,A.jsx)(Mm,{children:`Nobody has been invited to this org.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:Kx,labels:[`Name`,`Email`,`Role`,`Status`,``]}),r.value.members.map(t=>(0,A.jsxs)(fh,{columns:Kx,children:[(0,A.jsxs)(`span`,{className:`ui-cell-strong box-line`,children:[t.name,t.operator===!0&&(0,A.jsx)(Qm,{tone:`violet`,small:!0,children:`operator`})]}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:t.email}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:t.role}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:qx[t.status]??`gray`,children:t.status})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:h===t.id?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Bm,{danger:!0,disabled:i.busy,onClick:()=>v(()=>Mx(n,e,t.id).finally(()=>g(null))),children:`Remove for good`}),(0,A.jsx)(Bm,{onClick:()=>g(null),children:`Cancel`})]}):(0,A.jsxs)(A.Fragment,{children:[t.status===`active`&&(0,A.jsx)(Bm,{disabled:i.busy,onClick:()=>v(()=>jx(n,e,t.id,t.operator!==!0)),children:t.operator===!0?`Stop running the box`:`Make operator`}),(0,A.jsx)(Bm,{danger:!0,onClick:()=>g(t.id),children:`Remove`})]})})]},t.id))]}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`Roles and agents are the org's own to change, from its Team screen. An operator's own key opens this box's doors as well as their org's.`})]})]})}function Yx({invited:e,onClose:t}){let[n,r]=(0,D.useState)(!1),i=e.token??null,a=i===null?null:`${window.location.origin}/invitations/${encodeURIComponent(i)}`;return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`${e.member.name} is invited`,meta:e.mailed===!0?`the link was mailed to them too`:a===null?`they already have a password here: nothing to send`:`copy it now: it is never shown again`,children:(0,A.jsxs)(`span`,{className:`box-head-moves`,children:[a!==null&&(0,A.jsx)(U,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(a).then(()=>r(!0)),children:n?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:t,children:`Done`})]})}),a!==null&&(0,A.jsx)(`pre`,{className:`ui-code`,children:a})]})}function Xx({org:e}){let t=j(),n=vr(),r=ex((0,D.useCallback)(()=>Ix(t,e.slug),[t,e.slug])),i=nx(),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),d=async n=>{n.preventDefault(),c(null),await i.move(async()=>{let n=await Tx(t,e.slug,a.trim());c(`${a.trim()} is ${e.slug}'s now: ${n.logs} ${n.logs===1?`log`:`logs`}${n.numbers.length>0?`, and ${n.numbers.join(`, `)}`:``}.`),o(``)})},f=e=>e==null?void 0:`of ${e}`;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{size:`small`,label:`Seats`,value:e.holding.seats,of:f(e.quotas.seats)}),(0,A.jsx)(uh,{size:`small`,label:`Numbers bought`,value:e.holding.numbers,of:f(e.quotas.numbers)}),(0,A.jsx)(uh,{size:`small`,label:`Memory facts`,value:e.holding.memory_facts,of:f(e.quotas.memory_facts)}),(0,A.jsx)(uh,{size:`small`,label:`Knowledge chunks`,value:e.holding.knowledge_chunks,of:f(e.quotas.knowledge_chunks)})]}),(0,A.jsx)(Nm,{children:i.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Sign-in`,meta:`how this org's people prove who they are`}),(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsx)(Lm,{label:`Provider`,keyWidth:120,children:r.value?.configured?r.value.issuer??`its own identity provider`:`passwords — no identity provider wired`}),r.value?.configured&&(0,A.jsx)(Lm,{label:`Passwords`,keyWidth:120,children:r.value.required?(0,A.jsxs)(`span`,{className:`box-line`,children:[(0,A.jsx)(Qm,{tone:`amber`,children:`stopped`}),(0,A.jsx)(Bm,{disabled:i.busy,onClick:()=>void i.move(async()=>{await Lx(t,e.slug,!1),await r.reread()}),children:`Let passwords work again`})]}):`still work`})]}),r.value?.configured&&r.value.required&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`The break-glass: the day their provider stops answering, the admin who would turn this off is the one locked out.`})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Bring an agent here`,meta:`one that registered in the wrong org, with every call it took and its numbers`}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void d(e),children:[(0,A.jsx)(Wm,{label:`Agent slug`,grow:!0,minWidth:220,children:(0,A.jsx)(W,{value:a,placeholder:`clinica-norte`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(U,{size:`form`,type:`submit`,disabled:i.busy||a.trim()===``,children:`Move it here`})]}),s!==null&&(0,A.jsx)(`div`,{className:`box-done box-done-under`,children:s}),(0,A.jsx)(`div`,{className:`ui-note box-note`,children:`The agent must be stopped first: a slug somebody is holding is refused.`})]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Remove this organization`,meta:`refused while a live key or a route still names it`}),(0,A.jsx)(`div`,{className:`ui-card-body box-line`,children:l?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`span`,{className:`ui-note`,children:[`Forget `,e.slug,` for good?`]}),(0,A.jsx)(U,{kind:`danger`,size:`sm`,disabled:i.busy,onClick:()=>void i.move(async()=>{await Sx(t,e.slug),n(`/box/orgs`)}),children:`Yes, remove it`}),(0,A.jsx)(Bm,{onClick:()=>u(!1),children:`Cancel`})]}):(0,A.jsxs)(U,{kind:`danger`,size:`sm`,onClick:()=>u(!0),children:[`Remove `,e.slug]})})]})]})}function Zx({named:e}){let t=j(),n=ex((0,D.useCallback)(()=>Nx(t,e),[t,e])),r=nx(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(``),u=async i=>{i.preventDefault(),await r.move(async()=>{await Px(t,e,o.trim(),c.trim()),await n.reread()})&&(s(``),l(``),a(!1))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused??r.refused}),n.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Vendors it brought`,meta:`every other vendor runs on the box's own key`,action:i?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>a(!0),children:`Bring a key`})}),i&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void u(e),children:[(0,A.jsx)(Wm,{label:`Vendor`,minWidth:170,children:(0,A.jsx)(W,{value:o,placeholder:`elevenlabs`,onChange:e=>s(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Its key, sent once`,grow:!0,minWidth:240,children:(0,A.jsx)(W,{type:`password`,autoComplete:`off`,value:c,placeholder:`never shown again`,onChange:e=>l(e.target.value),required:!0})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:r.busy,children:r.busy?`Keeping…`:`Keep it`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`No door a person reads ever answers with a provider key: a lost one is set again.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>a(!1),children:`Close`})})]})]}),n.value.length===0?(0,A.jsx)(Mm,{children:`None: every call of this org runs on the keys of the box.`}):n.value.map(i=>(0,A.jsx)(Pm,{name:i,sub:`this org's own account with them`,end:(0,A.jsx)(Bm,{disabled:r.busy,onClick:()=>void r.move(async()=>{await Fx(t,e,i),await n.reread()}),children:`Give it back to the box`})},i))]})]})}var Qx=[{tab:`overview`,name:`Overview`},{tab:`members`,name:`Members`},{tab:`keys`,name:`Keys`},{tab:`limits`,name:`Limits`},{tab:`providers`,name:`Providers`}];function $x(){let e=j(),t=Sr().org??``,[n,r]=Xi(),i=Qx.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`overview`,a=ex((0,D.useCallback)(()=>bx(e,t),[e,t])),{moveTo:o}=kh(),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(null),d=async e=>{c(!0),u(null);try{await o(e)}catch(e){u(tx(e)),c(!1)}};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{back:(0,A.jsx)(Wi,{to:`/box/orgs`,className:`box-back`,children:`← Organizations`}),title:a.value?.name??t,lede:a.value===void 0?void 0:(0,A.jsx)(`span`,{className:`box-fixed`,children:`${a.value.slug} · ${a.value.id}`}),actions:a.value!==void 0&&(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:s,onClick:()=>void d(a.value?.id??t),children:s?`Opening…`:`Open as operator`})}),(0,A.jsx)(yh,{label:`Organization`,tabs:Qx,on:i,onPick:e=>r(e===`overview`?{}:{tab:e})}),(0,A.jsx)(Nm,{children:l??a.refused}),a.value!==void 0&&i===`overview`&&(0,A.jsx)(Xx,{org:a.value}),i===`members`&&(0,A.jsx)(Jx,{named:t,seats:a.value?.quotas.seats??null}),i===`keys`&&(0,A.jsx)(Bx,{named:t}),a.value!==void 0&&i===`limits`&&(0,A.jsx)(Wx,{org:a.value,onSaved:a.reread}),i===`providers`&&(0,A.jsx)(Zx,{named:t})]})}var eS=`minmax(0,1.2fr) minmax(0,1fr) minmax(0,1fr) 60px`;function tS(){let e=j(),t=ex((0,D.useCallback)(()=>yx(e),[e])),n=nx(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),l=async r=>{r.preventDefault(),await n.move(async()=>{await xx(e,a.trim(),s.trim()),await t.reread()})&&(o(``),c(``),i(!1))};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Organizations`,lede:`Every tenant this box serves. Open one to see its people, its keys, its limits and the vendors it brought.`}),(0,A.jsx)(Nm,{children:t.refused??n.refused}),t.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`On this box`,meta:`${t.value.length} ${t.value.length===1?`organization`:`organizations`}`,action:r?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>i(!0),children:`Add an organization`})}),r&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void l(e),children:[(0,A.jsx)(Wm,{label:`Slug`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{value:a,placeholder:`tienda-sur`,onChange:e=>o(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Name`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{value:s,placeholder:`Tienda Sur (optional)`,onChange:e=>c(e.target.value)})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:n.busy||a.trim()===``,children:n.busy?`Adding…`:`Add`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`The slug is what people type and the gateway is its judge. Its first admin is invited from the org's Members tab.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>i(!1),children:`Close`})})]})]}),t.value.length===0?(0,A.jsx)(Mm,{children:`No organization on this box yet. The first one is what a key is issued against.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:eS,labels:[`Organization`,`Slug`,`Id`,``]}),t.value.map(e=>(0,A.jsxs)(fh,{columns:eS,to:`/box/orgs/${encodeURIComponent(e.slug)}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.slug}),(0,A.jsx)(`span`,{className:`ui-cell-faint box-fixed`,children:e.id}),(0,A.jsx)(`span`,{className:`ui-cell-link ui-cell-end`,children:`Open`})]},e.id))]})]})]})}var nS=[`production`,`sandbox`],rS=[`phone`,`whatsapp`],iS=`minmax(0,1.1fr) 110px minmax(0,1fr) 150px 80px`;function aS(){let e=j(),t=ex((0,D.useCallback)(()=>yx(e),[e])),[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(nS[0]),o=ex((0,D.useCallback)(()=>n===``?Promise.resolve(void 0):Xb(e,n,i),[e,n,i])),s=nx(),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(rS[0]),[g,_]=(0,D.useState)(null);(0,D.useEffect)(()=>{n===``&&t.value!==void 0&&r(t.value.find(e=>e.slug!=="default")?.slug??t.value[0]?.slug??``)},[n,t.value]);let v=async t=>{t.preventDefault(),_(null),await s.move(async()=>{let t=await Zb(e,{org:n,number:u.trim(),agent:f.trim(),channel:m,env:i});_(t===null?`${u.trim()} now rings ${f.trim()}.`:`${u.trim()} now rings ${f.trim()}, taken from ${t}.`),await o.reread()})&&(d(``),p(``),l(!1))};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Routes`,lede:`Every door one org answers at, in one world. A row typed here outranks whatever an app declared.`}),(0,A.jsxs)(`div`,{className:`box-pick`,children:[(0,A.jsx)(Hm,{size:`sm`,value:n,onChange:e=>r(e.target.value),"aria-label":`Organization`,children:(t.value??[]).map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.id))}),(0,A.jsx)(Hm,{size:`sm`,value:i,onChange:e=>a(e.target.value),"aria-label":`World`,children:nS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})]}),(0,A.jsx)(Nm,{children:t.refused??o.refused??s.refused}),o.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`${n} · ${i}`,meta:`${o.value.length} ${o.value.length===1?`door`:`doors`}`,action:c?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>l(!0),children:`Type a number`})}),c&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void v(e),children:[(0,A.jsx)(Wm,{label:`Number`,minWidth:170,children:(0,A.jsx)(W,{value:u,placeholder:`+34910000000`,onChange:e=>d(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Agent`,grow:!0,minWidth:170,children:(0,A.jsx)(W,{value:f,placeholder:`clinica-norte`,onChange:e=>p(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Channel`,minWidth:120,children:(0,A.jsx)(Hm,{value:m,onChange:e=>h(e.target.value),children:rS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:s.busy,children:s.busy?`Typing…`:`Add`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`A row and nothing else: the carrier and the SFU trunk are the org's Numbers screen.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>l(!1),children:`Close`})})]})]}),g!==null&&(0,A.jsx)(`div`,{className:`box-done box-done-row`,children:g}),o.value.length===0?(0,A.jsx)(Mm,{children:`No door in this world: nothing typed, and no app holding an agent here.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:iS,labels:[`Number`,`Channel`,`Agent`,`Said by`,``]}),o.value.map(t=>(0,A.jsxs)(fh,{columns:iS,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:t.route.number?og(t.route.number):`—`}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:t.route.channel}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:t.route.agent}),(0,A.jsxs)(`span`,{className:`box-line`,children:[(0,A.jsx)(Qm,{tone:t.source===`operator`?`indigo`:`gray`,children:t.source===`operator`?`typed`:t.source}),t.route.managed===!0&&(0,A.jsx)(Qm,{tone:`violet`,children:`bought`})]}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:t.source===`operator`&&typeof t.route.number==`string`&&(0,A.jsx)(Bm,{danger:!0,disabled:s.busy,onClick:()=>void s.move(async()=>{await Qb(e,n,t.route.number??``),await o.reread()}),children:`Forget`})})]},`${t.route.channel}-${t.route.number??t.route.agent}`))]})]})]})}var oS=`/v1/ops`;async function sS(e){try{return await e}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}var cS=np({google:np({configured:L(),client_id:P().nullish(),redirect_uri:P().nullish()})});async function lS(e){return sS(k(e,`${oS}/signin`).then(e=>cS.parse(e)))}async function uS(e,t){await oa(e,`${oS}/signin/google`,t)}async function dS(e){await ca(e,`${oS}/signin/google`)}var fS=[`starttls`,`tls`,`none`],pS=np({configured:L(),source:P().nullish(),host:P().nullish(),port:F().nullish(),security:P().nullish(),username:P().nullish(),from:P().nullish(),verified_at:P().nullish(),last_error:P().nullish()});async function mS(e){return sS(k(e,`${oS}/mail`).then(e=>pS.parse(e)))}async function hS(e,t){await oa(e,`${oS}/mail`,t)}async function gS(e){await ca(e,`${oS}/mail`)}async function _S(e,t){let n=np({sent:L(),error:P().nullish()}).parse(await sa(e,`${oS}/mail/test`,{to:t}));return{sent:n.sent,error:n.error??null}}var vS=np({name:P().nullish(),logo_url:P().nullish(),accent:P().nullish()});async function yS(e){return sS(k(e,`${oS}/brand`).then(e=>vS.parse(e)))}async function bS(e,t){await oa(e,`${oS}/brand`,t)}var xS=`Pinecall`,SS=`#5b3df5`,CS=/^#[0-9a-fA-F]{6}$/;function wS(){let e=j(),t=ex((0,D.useCallback)(()=>yS(e),[e])),n=nx(),[r,i]=(0,D.useState)(xS),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(SS),[l,u]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{t.value!==void 0&&t.value!==null&&(i(t.value.name??xS),o(t.value.logo_url??``),c(t.value.accent??SS))},[t.value]),t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(AS,{});let d=async i=>{i.preventDefault(),u(!1),u(await n.move(async()=>{await bS(e,{name:r.trim(),logo_url:a.trim(),accent:s}),await t.reread()}))},f=CS.test(s)?s:SS;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`What the letters carry`,meta:`invitations and password resets, for every org on this box`}),(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>void d(e),children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(Wm,{label:`Name`,children:(0,A.jsx)(W,{value:r,onChange:e=>i(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Accent`,children:(0,A.jsxs)(`span`,{className:`box-accent`,children:[(0,A.jsx)(`input`,{type:`color`,className:`box-accent-well`,value:f,onChange:e=>c(e.target.value),"aria-label":`Accent`}),(0,A.jsx)(W,{value:s,onChange:e=>c(e.target.value)})]})}),(0,A.jsx)(Wm,{label:`Logo URL`,children:(0,A.jsx)(W,{type:`url`,value:a,placeholder:`https://… (https only; empty shows the name)`,onChange:e=>o(e.target.value)})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:n.busy,children:n.busy?`Saving…`:`Save`}),l&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. The next letter carries it.`})]})]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Preview`,meta:`the head of a letter`}),(0,A.jsx)(`div`,{className:`box-letter-ground`,children:(0,A.jsxs)(`div`,{className:`box-letter`,children:[a.trim().startsWith(`https://`)?(0,A.jsx)(`img`,{className:`box-letter-logo`,src:a.trim(),alt:r}):(0,A.jsx)(`span`,{className:`box-letter-name`,children:r}),(0,A.jsxs)(`div`,{className:`box-letter-title`,children:[`You're invited to Acme on `,r]}),(0,A.jsx)(`div`,{className:`box-letter-words`,children:`Ana invited you as a supervisor. Choose a password to take your first key.`}),(0,A.jsx)(`span`,{className:`box-letter-button`,style:{background:f},children:`Accept the invitation`})]})})]})]})}function TS(){let e=j(),t=ex((0,D.useCallback)(()=>mS(e),[e])),n=nx(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null);if(t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(AS,{});let l=t.value,u=async r=>{r.preventDefault(),c(null),await n.move(async()=>{c(await _S(e,a.trim())),await t.reread()})};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The box's mail`,meta:`invitations, password resets and a forgotten password`,children:(0,A.jsx)(`span`,{className:`box-head-moves`,children:(0,A.jsx)(Qm,{tone:l.configured?`green`:`gray`,children:l.configured?l.source===`environment`?`on · from the environment`:`on`:`off`})})}),r||!l.configured?(0,A.jsx)(ES,{kept:l,busy:n.busy,onCancel:l.configured?()=>i(!1):void 0,onSave:async r=>{await n.move(async()=>{await hS(e,r),await t.reread()})&&i(!1)}}):(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsxs)(Lm,{label:`Server`,keyWidth:120,children:[(0,A.jsx)(`span`,{className:`box-fixed`,children:`${l.host??`—`}:${l.port??``}`}),` · `,l.security??`starttls`]}),(0,A.jsx)(Lm,{label:`Username`,keyWidth:120,children:(0,A.jsx)(`span`,{className:`box-fixed`,children:l.username??`none`})}),(0,A.jsx)(Lm,{label:`From`,keyWidth:120,children:l.from??`—`}),(0,A.jsx)(Lm,{label:`Last letter`,keyWidth:120,children:l.last_error?(0,A.jsx)(`span`,{className:`box-bad`,children:l.last_error}):l.verified_at?`went through · ${l.verified_at.slice(0,16).replace(`T`,` `)}`:`none sent yet`}),(0,A.jsxs)(`div`,{className:`box-line box-kvs-moves`,children:[(0,A.jsx)(U,{size:`sm`,onClick:()=>i(!0),children:l.source===`environment`?`Replace it here`:`Change`}),l.source!==`environment`&&(0,A.jsx)(Bm,{danger:!0,disabled:n.busy,onClick:()=>void n.move(async()=>{await gS(e),await t.reread()}),children:`Forget it`})]})]})]}),l.configured&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Send a test letter`,meta:`the one door that waits for the mail server's answer`}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void u(e),children:[(0,A.jsx)(Wm,{label:`To`,grow:!0,minWidth:240,children:(0,A.jsx)(W,{type:`email`,value:a,placeholder:`you@company.com`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(U,{size:`form`,type:`submit`,disabled:n.busy,children:n.busy?`Sending…`:`Send`})]}),s!==null&&(s.sent?(0,A.jsx)(`div`,{className:`box-done box-done-under`,children:`Taken by the mail server.`}):(0,A.jsx)(`div`,{className:`box-bad box-note`,children:s.error??`It was refused.`}))]})]})]})}function ES({kept:e,busy:t,onSave:n,onCancel:r}){let[i,a]=(0,D.useState)(e.host??``),[o,s]=(0,D.useState)(String(e.port??587)),[c,l]=(0,D.useState)(fS.find(t=>t===e.security)??`starttls`),[u,d]=(0,D.useState)(e.username??``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(e.from??``);return(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>{e.preventDefault(),n({host:i.trim(),port:Number(o),security:c,username:u.trim()===``?null:u.trim(),...f===``?{}:{password:f},from:m.trim()})},children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(Wm,{label:`Host`,children:(0,A.jsx)(W,{value:i,placeholder:`email-smtp.us-east-1.amazonaws.com`,onChange:e=>a(e.target.value),required:!0})}),(0,A.jsxs)(`div`,{className:`box-form-pair`,children:[(0,A.jsx)(Wm,{label:`Port`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:o,onChange:e=>s(e.target.value.replace(/[^0-9]/g,``)),required:!0})}),(0,A.jsx)(Wm,{label:`Security`,children:(0,A.jsx)(Hm,{value:c,onChange:e=>l(e.target.value),children:fS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})})]}),(0,A.jsx)(Wm,{label:`Username`,children:(0,A.jsx)(W,{autoComplete:`off`,value:u,onChange:e=>d(e.target.value)})}),(0,A.jsx)(Wm,{label:`Password, sent once`,children:(0,A.jsx)(W,{type:`password`,autoComplete:`new-password`,value:f,placeholder:e.configured?`unchanged`:`never shown again`,onChange:e=>p(e.target.value)})}),(0,A.jsx)(Wm,{label:`From`,children:(0,A.jsx)(W,{value:m,placeholder:`Pinecall <noreply@pinecall.io>`,onChange:e=>h(e.target.value),required:!0})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:t,children:t?`Saving…`:`Save`}),r!==void 0&&(0,A.jsx)(Bm,{onClick:r,children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Saving sends nothing: the test letter below is what proves it.`})]})]})}function DS(){let e=j(),t=ex((0,D.useCallback)(()=>lS(e),[e])),n=nx(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1);if(t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(AS,{});let d=t.value.google,f=d.redirect_uri??nm(pm()),p=r||!d.configured,m=async r=>{r.preventDefault(),await n.move(async()=>{await uS(e,{client_id:a.trim(),client_secret:s.trim()}),await t.reread()})&&(c(``),i(!1))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Continue with Google`,meta:`one client for the whole box — no org configures anything`,children:(0,A.jsx)(`span`,{className:`box-head-moves`,children:(0,A.jsx)(Qm,{tone:d.configured?`green`:`gray`,children:d.configured?`on`:`off`})})}),p?(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>void m(e),children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(Wm,{label:`Client ID`,children:(0,A.jsx)(W,{value:a,placeholder:`…apps.googleusercontent.com`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Client secret, sent once`,children:(0,A.jsx)(W,{type:`password`,autoComplete:`off`,value:s,placeholder:`never shown again`,onChange:e=>c(e.target.value),required:!0})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:n.busy,children:n.busy?`Saving…`:`Save`}),r&&(0,A.jsx)(Bm,{onClick:()=>i(!1),children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Made at Google Cloud Console → APIs & Services → Credentials → OAuth client ID → Web application.`})]})]}):(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsx)(Lm,{label:`Client ID`,keyWidth:120,children:(0,A.jsx)(`span`,{className:`box-fixed`,children:d.client_id??`—`})}),(0,A.jsx)(Lm,{label:`Secret`,keyWidth:120,children:`kept, and read back by no door`}),(0,A.jsxs)(`div`,{className:`box-line box-kvs-moves`,children:[(0,A.jsx)(U,{size:`sm`,onClick:()=>{o(d.client_id??``),i(!0)},children:`Change`}),(0,A.jsx)(Bm,{danger:!0,disabled:n.busy,onClick:()=>void n.move(async()=>{await dS(e),await t.reread()}),children:`Turn it off`})]})]}),(0,A.jsxs)(`div`,{className:`box-redirect`,children:[(0,A.jsxs)(`div`,{className:`box-redirect-head`,children:[(0,A.jsx)(`span`,{className:`ui-note`,children:`Register this at Google as the authorized redirect URI`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(f).then(()=>u(!0)),children:l?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:f})]})]})]})}var OS=[{tab:`signin`,name:`Sign-in`},{tab:`email`,name:`Email`},{tab:`brand`,name:`Brand`}];function kS(){let[e,t]=Xi(),n=OS.some(t=>t.tab===e.get(`tab`))?e.get(`tab`):`signin`;return(0,A.jsxs)(sh,{width:900,children:[(0,A.jsx)(ch,{title:`Box settings`,lede:`What this gateway is set to, for every organization on it.`}),(0,A.jsx)(yh,{label:`Box settings`,tabs:OS,on:n,onPick:e=>t(e===`signin`?{}:{tab:e})}),n===`signin`&&(0,A.jsx)(DS,{}),n===`email`&&(0,A.jsx)(TS,{}),n===`brand`&&(0,A.jsx)(wS,{})]})}function AS(){return(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`This gateway does not have this door yet.`})})}var jS=100,MS=`minmax(0,1.2fr) 110px 110px 140px 140px`,NS=`130px minmax(0,1fr) minmax(0,1.4fr) 110px 80px 80px 90px`;function PS(){let e=j(),[t,n]=(0,D.useState)([]),[r,i]=(0,D.useState)({}),[a,o]=(0,D.useState)(0),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),p=async(t,r)=>{u(!0);try{let a=await $b(e,t,jS);n(e=>r?a.rows:[...e,...a.rows]),i(e=>r?a.totals:IS(e,a.totals)),o(a.next??null),c(!0)}catch(e){f(tx(e))}finally{u(!1)}};(0,D.useEffect)(()=>{p(0,!0)},[e]);let m=e=>t.filter(t=>t.org===e).reduce((e,t)=>e+t.cost_eur,0);return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Box usage`,lede:`What every organization consumed, folded off the log by a cursor — there is no counter table to drift from it.`}),(0,A.jsx)(Nm,{children:d}),s&&t.length===0&&a===null&&(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`Nothing metered yet: no call of any org has been summarised.`})}),Object.keys(r).length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`By organization`,meta:a===null?`the whole log`:`the pages read so far`}),(0,A.jsx)(dh,{columns:MS,labels:[`Organization`,`Minutes>`,`Messages>`,`Tokens>`,`Cost>`]}),Object.entries(r).map(([e,t])=>(0,A.jsxs)(fh,{columns:MS,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:t.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:t.messages}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:(t.input_tokens+t.output_tokens).toLocaleString(`en`)}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-cell-right`,children:[`€`,m(e).toFixed(2)]})]},e))]}),t.length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Metered rows`,meta:`${t.length} read, oldest first`}),(0,A.jsx)(dh,{columns:NS,labels:[`When`,`Organization`,`Agent · call`,`What`,`Min>`,`Msgs>`,`Cost>`]}),t.map(e=>(0,A.jsxs)(fh,{columns:NS,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:FS(e.at)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.org}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-clip`,title:e.call,children:[e.agent,` `,(0,A.jsxs)(`span`,{className:`ui-cell-faint box-fixed`,children:[e.call.slice(0,13),`…`]})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint box-fixed`,children:e.type}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:e.minutes.toFixed(2)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:e.messages}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-cell-right`,children:[`€`,e.cost_eur.toFixed(4)]})]},`${e.cursor}-${e.call}-${e.type}`)),a!==null&&(0,A.jsx)(jm,{children:(0,A.jsx)(U,{size:`sm`,disabled:l,onClick:()=>void p(a,!1),children:l?`Reading…`:`Read on`})})]})]})}function FS(e){return new Date(e*1e3).toISOString().slice(0,16).replace(`T`,` `)}function IS(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t===void 0?r:{...r,minutes:t.minutes+r.minutes,messages:t.messages+r.messages,input_tokens:t.input_tokens+r.input_tokens,output_tokens:t.output_tokens+r.output_tokens,characters:t.characters+r.characters}}return n}function LS({children:e}){let{operator:t}=Xy();return t===null?null:t?e:(0,A.jsx)(Xr,{to:`/`,replace:!0})}var RS=3e3;function zS(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=Wv.parse(await k(t,`/v1/agents/${e}/sessions`));n||(r(i.calls),a(null))}catch(e){n||a(String(e))}};i();let o=window.setInterval(()=>void i(),RS);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{lines:n,error:i}}function BS(e){return e.status!==`ended`}var VS=/^\+[1-9]\d{4,14}$/;function HS(){let e=j(),[t,n]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return wb(e).then(e=>{t||n(e!==null&&e.ready?e:null)},()=>void 0),()=>{t=!0}},[e]),t}function US({outbound:e,value:t,onChange:n}){return e.from_numbers.length<2?null:(0,A.jsx)(Wm,{label:`From`,children:(0,A.jsxs)(Hm,{size:`sm`,value:t,onChange:e=>n(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the agent's own number`}),e.from_numbers.map(e=>(0,A.jsx)(`option`,{value:e,children:og(e)},e))]})})}function WS({agent:e,to:t,outbound:n,onClose:r,onRefused:i}){let a=j(),o=vr(),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),d=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()},t=e=>{let t=d.current?.parentElement;t!=null&&!t.contains(e.target)&&r()};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,t)}},[r]);let f=async()=>{u(!0);try{let n=await Db(a,e,t,s);o(`/live/${n}`)}catch(e){i(e instanceof na?e.message:String(e)),r()}finally{u(!1)}};return(0,A.jsxs)(`div`,{className:`dial-pop`,role:`dialog`,"aria-label":`call back`,ref:d,children:[(0,A.jsxs)(`div`,{className:`dial-ask`,children:[`Call `,og(t),` as `,e,`?`]}),(0,A.jsx)(US,{outbound:n,value:s,onChange:c}),(0,A.jsxs)(`div`,{className:`dial-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:l,onClick:()=>void f(),children:l?`Calling…`:`Call`}),(0,A.jsx)(U,{size:`md`,disabled:l,onClick:r,children:`Cancel`})]})]})}function GS({agent:e,outbound:t,onClose:n}){let r=j(),i=vr(),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),p=a.replace(/[\s()-]/g,``),m=async t=>{if(t.preventDefault(),!VS.test(p)){f(`A number is written whole, with its country: +14176743169.`);return}u(!0),f(null);try{let t=await Db(r,e,p,s);n(),i(`/live/${t}`)}catch(e){f(e instanceof na?e.message:String(e))}finally{u(!1)}};return(0,A.jsxs)(`form`,{className:`dial-form`,onSubmit:e=>void m(e),children:[(0,A.jsx)(Wm,{label:`Number`,children:(0,A.jsx)(W,{size:`sm`,value:a,placeholder:`+1 417 674 3169`,autoFocus:!0,autoComplete:`off`,onChange:e=>o(e.target.value)})}),(0,A.jsx)(US,{outbound:t,value:s,onChange:c}),(0,A.jsx)(`p`,{className:`dial-note`,children:t.guards.dial_anywhere?`${e} places the call and speaks first.`:`${e} places the call and speaks first. Only a number that has already called or written to you is dialled.`}),d!==null&&(0,A.jsx)(`p`,{className:`dial-refused`,children:d}),(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:l||p===``,children:l?`Calling…`:`Call`})]})}var KS=np({threads:R(np({contact:P(),name:P().nullish(),unread:F().nullish()}))});async function qS(e,t){try{let n=KS.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/threads`));return new Map(n.threads.map(e=>[e.contact,e]))}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}async function JS(e,t,n){await sa(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/read`,{})}async function YS(e,t,n,r){await sa(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/messages`,{text:r})}async function XS(e,t,n){await sa(e,`/v1/calls/${encodeURIComponent(t)}/verbs`,n_.parse({verb:`say`,text:n}))}var ZS={"chat.roster":`chat`,"chat.start":`chat`,"chat.say":`chat`,"chat.end":`chat`,"knowledge.roster":`knowledge`,"knowledge.push":`knowledge`,"knowledge.eval":`knowledge`,"memory.roster":`memory`,"memory.eval":`memory`,"memory.extraction":`memory`,"simulate.roster":`evals`,"simulate.start":`evals`,"goldens.roster":`evals`,"goldens.run":`evals`,"promote.roster":`evals`,"promote.write":`evals`,"drift.read":`evals`,"reproductions.roster":`evals`,"reproductions.read":`evals`};function QS(e,t){return`/v1/agents/${encodeURIComponent(e)}/dev/${ZS[t]}/${t}`}async function $S(e,t,n,r={}){return sa(e,QS(t,n),r)}var eC=z({name:P(),goal:P(),style:P()}),tC=z({agent:P().nullable(),personas:R(eC)}),nC=z({call:P()});async function rC(e,t){return tC.parse(await $S(e,t,`simulate.roster`))}async function iC(e,t){return nC.parse(await $S(e,t.agent,`simulate.start`,t)).call}var aC=6,oC=15,sC=0;function cC({agent:e,agents:t,onClose:n}){let r=j(),i=vr(),[a,o]=(0,D.useState)(e??t?.[0]??``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(aC),[_,v]=(0,D.useState)(oC),[y,b]=(0,D.useState)(sC),[x,S]=(0,D.useState)(!1),[C,w]=(0,D.useState)(!1),[T,ee]=(0,D.useState)(null);(0,D.useEffect)(()=>{if(a===``)return;let e=!1;return c(null),ee(null),rC(r,a).then(t=>{e||(c(t),u(t.personas[0]?.name??``))},t=>{e||ee(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[r,a]);let te=s?.personas.find(e=>e.name===l),ne=lC(s,a),re=async e=>{e.preventDefault(),w(!0),ee(null);try{let e=await iC(r,{agent:a,persona:l,voice:d,judge:p,turns:h,...d&&x?{background_noise:_,packet_loss:y}:{}});n(),i(`/live/${e}`)}catch(e){ee(e instanceof na?e.message:String(e))}finally{w(!1)}};return(0,A.jsxs)(`form`,{className:`sim`,onSubmit:e=>void re(e),children:[(0,A.jsxs)(`div`,{className:`sim-head`,children:[(0,A.jsx)(`span`,{className:`sim-title`,children:`Simulate a caller`}),(0,A.jsx)(`button`,{type:`button`,className:`sim-close`,onClick:n,"aria-label":`close`,children:`×`})]}),t!==void 0&&(0,A.jsx)(Wm,{label:`Agent`,children:(0,A.jsx)(Hm,{size:`sm`,value:a,onChange:e=>o(e.target.value),children:t.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),s===null&&T===null&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Asking the process that holds `,a||`the agent`,` for its personas…`]}),ne!==null&&(0,A.jsx)(`p`,{className:`sim-note`,children:ne}),s!==null&&ne===null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Wm,{label:`Persona`,children:(0,A.jsx)(Hm,{size:`sm`,value:l,onChange:e=>u(e.target.value),children:s.personas.map(e=>(0,A.jsx)(`option`,{value:e.name,children:e.name},e.name))})}),te!==void 0&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Goal: `,te.goal]}),(0,A.jsxs)(`div`,{className:`sim-pair`,children:[(0,A.jsx)(Wm,{label:`Turns`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:30,value:h,onChange:e=>g(Number(e.target.value))})}),d&&x&&(0,A.jsx)(Wm,{label:`Noise, dB under`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:60,value:_,onChange:e=>v(Number(e.target.value))})}),d&&x&&(0,A.jsx)(Wm,{label:`Packets lost, %`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:100,value:y,onChange:e=>b(Number(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`sim-checks`,children:[(0,A.jsxs)(Ym,{checked:d,onChange:f,children:[`Voice `,(0,A.jsx)(`span`,{className:`sim-aside`,children:`a real line, and you can listen`})]}),(0,A.jsx)(Ym,{checked:p,onChange:m,children:`Judge at hang-up`}),d&&(0,A.jsxs)(Ym,{checked:x,onChange:S,children:[`Noisy line `,(0,A.jsx)(`span`,{className:`sim-aside`,children:`a TV behind the caller, packets lost`})]})]}),(0,A.jsx)(U,{type:`submit`,kind:`primary`,size:`md`,disabled:C||l===``,children:C?`Calling…`:`Call the agent`})]}),T!==null&&(0,A.jsx)(`p`,{className:`sim-refused`,children:T})]})}function lC(e,t){return e===null?null:e.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so nothing to simulate against.":e.agent===t?e.personas.length===0?`No personas in test/personas: one file per caller, default-exporting one.`:null:`The process holding the agent runs in ${e.agent}'s directory; a simulated caller is for that agent.`}function uC(e){return e.direction===`outbound`?e.to:e.from}function dC(e){let t=new Map;for(let n of e){let e=n.caller?.id??n.caller?.phone??uC(n)??n.call,r=t.get(e);if(r===void 0){t.set(e,{contact:e,name:n.caller?.name??null,handle:fC(n),lines:[n],latest:n});continue}r.lines.push(n),r.name??=n.caller?.name??null,(n.started_at??0)>(r.latest.started_at??0)&&(r.latest=n)}let n=[...t.values()];for(let e of n)e.lines.sort((e,t)=>(t.started_at??0)-(e.started_at??0));return n.sort((e,t)=>(t.latest.started_at??0)-(e.latest.started_at??0))}function fC(e){let t=uC(e);return t===null?e.channel===`web`?`web visitor`:`—`:t.startsWith(`+`)?og(t):e.channel===`web`?`web visitor`:t}function pC(e){return e.name!==null&&e.name!==``?e.name:e.contact.startsWith(`+`)?og(e.contact):e.contact}function mC(e){if(e.name===null||e.name===``)return e.handle===`web visitor`?`W`:e.contact.startsWith(`+`)?e.contact.slice(-2):void 0}function hC(e,t){if(e.channel===`phone`)return!0;let n=wy();for(let e of t)n=Dy(n,e);return n.room!==null}function gC(e,t,n){let r=[],i=t[0]?.ts??e.started_at??0;n&&r.push({kind:`call`,text:_C(e),at:i,call:e.call});for(let n of t){let t=n.data.text;typeof t==`string`&&t!==``&&(n.type===`turn.user`&&r.push({kind:`in`,text:t,at:n.ts,call:e.call}),(n.type===`turn.agent`||n.type===`supervisor.said`)&&r.push({kind:`out`,text:t,at:n.ts,call:e.call}))}return r}function _C(e){let t=e.direction===`outbound`?`outbound`:`inbound`;return e.status===`ended`?e.end_reason===`no_answer`||e.end_reason===`busy`||e.end_reason===`dial_failed`?`Voice call · ${e.end_reason.replace(`_`,` `)}`:`Voice call · answered · ${qh(e)}`:`Voice call · ${t} · on the line now`}function vC(e){let t=e.latest;return t.status===`ended`?t.outcome!==null&&t.outcome!==``?t.outcome:`${t.channel??`a`} call · ${qh(t)}`:`On a call now`}var yC=500;async function bC(e,t){let n=[],r=0;for(;;){let i=Bv.parse(await k(e,`/v1/calls/${t}/events`,{after:r,limit:yC}));if(n.push(...i.entries),i.next===null||i.entries.length<yC)return n;r=i.next}}var xC=12;function SC(e){let t=j(),n=(0,D.useRef)(new Map),[,r]=(0,D.useState)(0),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null),c=e?.lines.slice(0,xC)??[],l=c.map(e=>`${e.call}@${e.last_seq}`).join(` `);return(0,D.useEffect)(()=>{let e=!1,i=c.filter(e=>n.current.get(e.call)?.seq!==e.last_seq);if(i.length!==0)return a(!0),(async()=>{try{await Promise.all(i.map(async e=>{let r=await bC(t,e.call),i=hC(e,r);n.current.set(e.call,{seq:e.last_seq,voice:i,messages:gC(e,r,i)})})),e||s(null)}catch(t){e||s(String(t))}finally{e||(a(!1),r(e=>e+1))}})(),()=>{e=!0}},[l,t]),{messages:c.flatMap(e=>n.current.get(e.call)?.messages??[]).sort((e,t)=>e.at-t.at),voice:(e===void 0?void 0:n.current.get(e.latest.call))?.voice??null,loading:i,error:o}}function CC(){let e=Sr(),t=e.agent??``,n=e.call,r=vr(),i=j(),a=zS(t),o=(0,D.useMemo)(()=>dC(a.lines),[a.lines]),[s,c]=(0,D.useState)(``),l=vh({name:`agent.conversations`,initial:292,min:200,max:520,side:`left`}),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(`simulate`),m=HS(),h=EC(t,a.lines.length),g=o.find(e=>n!==void 0&&e.lines.some(e=>e.call===n))??o[0],_=s.trim().toLowerCase(),v=o.filter(e=>_===``||`${TC(e,h)} ${e.handle} ${vC(e)}`.toLowerCase().includes(_));return(0,D.useEffect)(()=>{g!==void 0&&h!==null&&(h.get(g.contact)?.unread??0)!==0&&JS(i,t,g.contact).catch(()=>void 0)},[g?.contact,h,i,t]),(0,A.jsxs)(`div`,{className:`ib`,style:l.style,children:[l.handle,(0,A.jsxs)(`div`,{className:`ib-list`,children:[(0,A.jsxs)(`div`,{className:`ib-list-head`,children:[(0,A.jsx)(`input`,{className:`ib-search`,placeholder:`Search a caller or number`,value:s,onChange:e=>c(e.target.value)}),(0,A.jsx)(`button`,{type:`button`,className:`ib-new`,title:m===null?`Simulate a caller`:`Simulate a caller, or call a number`,"aria-expanded":u,onClick:()=>d(!u),children:`+`}),u&&m===null&&(0,A.jsx)(`div`,{className:`ib-sim`,children:(0,A.jsx)(cC,{agent:t,onClose:()=>d(!1)})}),u&&m!==null&&(0,A.jsx)(`div`,{className:`ib-sim`,children:f===`simulate`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`ib-sim-ways`,children:(0,A.jsx)(Gm,{options:wC,value:f,onChange:p})}),(0,A.jsx)(cC,{agent:t,onClose:()=>d(!1)})]}):(0,A.jsxs)(`div`,{className:`dial-panel`,children:[(0,A.jsxs)(`div`,{className:`dial-panel-head`,children:[(0,A.jsx)(Gm,{options:wC,value:f,onChange:p}),(0,A.jsx)(`button`,{type:`button`,className:`dial-panel-close`,onClick:()=>d(!1),"aria-label":`close`,children:`×`})]}),(0,A.jsx)(GS,{agent:t,outbound:m,onClose:()=>d(!1)})]})})]}),(0,A.jsxs)(`div`,{className:`ib-threads`,children:[a.error!==null&&(0,A.jsx)(`p`,{className:`ib-empty ib-refused`,children:a.error}),a.error===null&&o.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`No conversations yet. The first call to reach `,t,` opens a thread here as it rings.`]}),o.length>0&&v.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`Nobody here matches “`,s,`”.`]}),v.map(e=>(0,A.jsx)(DC,{thread:e,name:TC(e,h),unread:h?.get(e.contact)?.unread??0,on:e===g,onOpen:()=>void r(`/a/${t}/calls/${e.latest.call}`)},e.contact))]})]}),g===void 0?(0,A.jsx)(`div`,{className:`ib-thread`,children:(0,A.jsx)(`p`,{className:`ib-nothing`,children:a.error===null?`Pick a conversation on the left.`:``})}):(0,A.jsx)(kC,{agent:t,thread:g,name:TC(g,h),door:h!==null,outbound:m},g.contact)]})}var wC=[{value:`simulate`,label:`Simulate a caller`},{value:`dial`,label:`Call a number`}];function TC(e,t){return t?.get(e.contact)?.name??pC(e)}function EC(e,t){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(a)return;let t=!1;return qS(n,e).then(e=>{t||(e===null&&o(!0),i(e))},()=>void 0),()=>{t=!0}},[n,e,t,a]),r}function DC({thread:e,name:t,unread:n,on:r,onOpen:i}){return(0,A.jsxs)(`button`,{type:`button`,className:r?`ib-row ib-row-on`:`ib-row`,onClick:i,children:[(0,A.jsx)(ah,{name:t,letters:mC(e),size:36,round:!0}),(0,A.jsxs)(`span`,{className:`ib-row-main`,children:[(0,A.jsxs)(`span`,{className:`ib-row-top`,children:[(0,A.jsx)(`span`,{className:`ib-row-name`,children:t}),(0,A.jsx)(`span`,{className:`ib-row-time`,children:OC(e.latest.started_at)})]}),(0,A.jsxs)(`span`,{className:`ib-row-bottom`,children:[(0,A.jsx)(`span`,{className:e.latest.status===`ended`?`ib-row-last`:`ib-row-last ib-row-last-live`,children:vC(e)}),n>0&&(0,A.jsx)(`span`,{className:`ib-unread`,children:n})]})]})]})}function OC(e){if(e===null)return``;let t=ng(),n=tg(e);return n===t.today?Zh(e).slice(0,5):n===t.yesterday?`Yesterday`:$h(e)}function kC({agent:e,thread:t,name:n,door:r,outbound:i}){let a=vr(),o=j(),{messages:s,voice:c,loading:l,error:u}=SC(t),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(!1),y=(0,D.useCallback)(()=>v(!1),[]),b=i!==null&&t.contact.startsWith(`+`),x=t.latest,S=x.status!==`ended`,C=S&&c===!1?`call`:!S&&r&&x.channel===`whatsapp`?`thread`:null,w=C===null?S&&c===!0?`A live voice call — Listen in on Live to speak into it`:S?`Reading the call…`:`The conversation is closed — nothing can be written into it from here`:`Write as ${e} — the agent keeps the thread from here`,T=async()=>{if(C!==null&&d.trim()!==``){m(!0),g(null);try{C===`call`?await XS(o,x.call,d.trim()):await YS(o,e,t.contact,d.trim()),f(``)}catch(e){g(e instanceof na?e.message:String(e))}finally{m(!1)}}};return(0,A.jsxs)(`div`,{className:`ib-thread`,children:[(0,A.jsxs)(`div`,{className:`ib-head`,children:[(0,A.jsx)(ah,{name:n,letters:mC(t),size:38,round:!0}),(0,A.jsxs)(`div`,{className:`ib-head-words`,children:[(0,A.jsx)(`div`,{className:`ib-head-name`,children:n}),(0,A.jsxs)(`div`,{className:`ib-head-sub`,children:[t.handle!==n&&`${t.handle} · `,x.channel??`—`,` · handled by `,e]})]}),(0,A.jsxs)(`div`,{className:`ib-head-actions`,children:[S&&(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-md`,onClick:()=>void a(`/live/${x.call}`),children:`Watch live`}),(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-md`,onClick:()=>void a(`/a/${e}/sessions/${x.call}`),children:`Session`}),b&&i!==null&&(0,A.jsxs)(`span`,{className:`dial-anchor`,children:[(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-primary ui-button-md`,"aria-expanded":_,onClick:()=>v(!_),children:`Call back`}),_&&(0,A.jsx)(WS,{agent:e,to:t.contact,outbound:i,onClose:y,onRefused:g})]})]})]}),(0,A.jsxs)(`div`,{className:`ib-messages`,children:[u!==null&&(0,A.jsx)(`p`,{className:`ib-refused-line`,children:u}),s.length===0&&u===null&&(0,A.jsx)(`p`,{className:`ib-quiet`,children:l?`Reading the conversation…`:`Nothing was said in this conversation.`}),(0,A.jsx)(AC,{messages:s})]}),h!==null&&(0,A.jsx)(`p`,{className:`ib-refused-line ib-refused-foot`,children:h}),(0,A.jsxs)(`form`,{className:`ib-composer`,onSubmit:e=>{e.preventDefault(),T()},children:[(0,A.jsx)(`input`,{className:`ib-write`,value:d,placeholder:w,disabled:C===null||p,onChange:e=>f(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`ib-send`,disabled:C===null||p||d.trim()===``,children:`Send`})]})]})}function AC({messages:e}){let t=ng(),n=``;return(0,A.jsx)(A.Fragment,{children:e.map((e,r)=>{let i=tg(e.at),a=i===n?null:i===t.today?`Today`:i===t.yesterday?`Yesterday`:$h(e.at);return n=i,(0,A.jsxs)(`div`,{className:`ib-bubble-wrap`,children:[a!==null&&(0,A.jsx)(`div`,{className:`ib-day`,children:a}),e.kind===`call`?(0,A.jsx)(`div`,{className:`ib-line ib-line-call`,children:(0,A.jsx)(`span`,{className:`ib-call`,children:e.text})}):(0,A.jsx)(`div`,{className:e.kind===`out`?`ib-line ib-line-out`:`ib-line`,children:(0,A.jsxs)(`span`,{className:e.kind===`out`?`ib-bubble ib-bubble-out`:`ib-bubble`,children:[e.text,(0,A.jsx)(`span`,{className:`ib-time`,children:Zh(e.at).slice(0,5)})]})})]},`${e.call}-${String(r)}`)})})}function jC(e){let t=new Map;for(let n of e)!t.has(n)&&zv(n)&&t.set(n,tf(Pv[n],{io:`input`}));return t}function MC(e,t){return e==null?`null`:typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?JSON.stringify(e):typeof e==`number`?IC(e,t):Array.isArray(e)?`[${e.map(e=>MC(e,t?.items)).join(`,`)}]`:PC(e,t)}function NC(e,t){return typeof e==`string`?e:MC(e,t)}function PC(e,t){let n=FC(e,t)?.properties;return`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${MC(t,n?.[e])}`).join(`,`)}}`}function FC(e,t){return t?.oneOf===void 0?t:t.oneOf.find(t=>Object.entries(t.properties??{}).every(([t,n])=>n.const===void 0||n.const===e[t]))}function IC(e,t){if(t?.type!==`number`||!Number.isFinite(e))return String(e);let n=Math.abs(e);return e!==0&&(n<1e-4||n>=0x2386f26fc10000)?LC(e):Number.isInteger(e)?`${e}.0`:String(e)}function LC(e){let[t=``,n=``]=e.toExponential().split(`e`);return`${t}e${n.startsWith(`-`)?`-`:`+`}${n.replace(/^[+-]/,``).padStart(2,`0`)}`}var RC=[`transcription_delay`,`end_of_turn_delay`],zC=[`llm_node_ttft`,`tts_node_ttfb`,`e2e_latency`],BC=[...RC,...zC];function VC(e){return ZC(e).map(([e,t])=>({field:e,value:WC(t),unit:null}))}function HC(e,t){return GC(e,``,t)}function UC(){let e=tf(C_,{io:`input`}),t=new Map;for(let[n,r]of Object.entries(e.properties??{}))r.items!==void 0&&t.set(n,r.items);return t}function WC(e){return e<0?`—`:e<1?`${Math.round(e*1e3)} ms`:`${e.toFixed(2)} s`}function GC(e,t,n){let r=[];for(let[i,a]of Object.entries(e)){let e=t+i,o=n?.properties?.[i];a!=null&&(typeof a==`object`&&!Array.isArray(a)?r.push(...GC(a,`${e}.`,o)):r.push({field:e,value:NC(a,o),unit:KC(i)}))}return r}function KC(e){return Sy[e]??null}function qC(e,t){let n=UC(),r=[];for(let[i,a]of Object.entries(e))for(let e of a)XC(e,t)&&r.push({kind:i,readings:HC(e,n.get(i))});return r}var JC=[`turn.user`,`turn.agent`];function YC(e){let t=QC(e);return BC.filter(e=>(t.get(e)??[]).length>0).map(e=>{let n=t.get(e)??[];return{name:e,seconds:$C(n),max:Math.max(...n),turns:n.length}})}function XC(e,t){return`speech_id`in e&&e.speech_id===t}function ZC(e){let t=e.role===`user`?RC:zC,n=e.metrics,r=[];for(let e of t){let t=n[e];typeof t==`number`&&r.push([e,t])}return r}function QC(e){let t=new Map(BC.map(e=>[e,[]]));for(let n of e){if(!JC.includes(n.type))continue;let e=n.data.metrics;for(let n of BC){let r=e?.[n];typeof r==`number`&&t.get(n)?.push(r)}}return t}function $C(e){let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2),r=t[n]??0;return t.length%2==1?r:((t[n-1]??0)+r)/2}function ew(e,t={}){let n=j(),[r,i]=(0,D.useState)(wy),[a,o]=(0,D.useState)(`connecting`),[s,c]=(0,D.useState)(null),l=(0,D.useRef)(t);return(0,D.useEffect)(()=>{l.current=t}),(0,D.useEffect)(()=>{let t={current:wy()},r=!1,a=null,s=()=>i({...t.current}),u=()=>{r=!0,a?.()};return(async()=>{let i=0;try{i=await tw(n,e,t,l)}catch(e){c(String(e)),o(`ended`);return}if(!r){if(s(),t.current.status===`ended`){o(`ended`);return}a=Hy(la(n,`/v1/calls/${e}/events`,{after:i}),n,{onEntry(e){t.current=Dy(t.current,e),l.current.onEntry?.(e),nw(e,t.current,l.current),e.type===`call.score`&&(s(),o(`ended`),u())},onPaint:s,onConnection:o,onRefused:c}),r&&a()}})(),u},[e,n]),{state:r,connection:a,error:s}}async function tw(e,t,n,r){let i;try{i=await bC(e,t)}catch(e){if(e instanceof na&&e.status===404)return 0;throw e}for(let e of i)n.current=Dy(n.current,e),r.current.onEntry?.(e),nw(e,n.current,r.current);return i.at(-1)?.seq??0}function nw(e,t,n){if(e.type!==`custom`)return;let r=t.custom.at(-1);r!==void 0&&n.onCustom?.(r)}function rw(e){let t=(0,D.useRef)([]),n=ew(e,{onEntry(e){let n=t.current.at(-1);n!==void 0&&e.seq<=n.seq||t.current.push(e)}}),r=(0,D.useMemo)(()=>[...t.current],[n.state.seq]);return{state:n.state,entries:r,connection:n.connection,error:n.error}}function iw({agent:e,call:t}){let{lines:n}=Xy(),r=n.find(t=>t.agent===e)?.call??null,i=t??r;return(0,A.jsx)(`aside`,{className:`inspector`,"aria-label":`Inspector`,children:i===null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(aw,{connection:null}),(0,A.jsx)(`p`,{className:`inspector-quiet`,children:`Nothing to read yet: the first call this agent takes is read here as it happens.`})]}):(0,A.jsx)(sw,{call:i,yours:t!==null},i)})}function aw({connection:e}){return(0,A.jsxs)(`div`,{className:`inspector-head`,children:[(0,A.jsx)(`span`,{className:`inspector-title`,children:`Inspector`}),(0,A.jsx)(`span`,{className:`inspector-standing`,children:ow(e)})]})}function ow(e){switch(e){case`live`:return(0,A.jsx)(Qm,{tone:`green`,children:`reading the log`});case`connecting`:return(0,A.jsx)(Qm,{tone:`muted`,children:`opening the log`});case`reconnecting`:return(0,A.jsx)(Qm,{tone:`amber`,children:`reconnecting`});case`ended`:return(0,A.jsx)(Qm,{tone:`muted`,children:`call ended`});default:return(0,A.jsx)(Qm,{tone:`muted`,children:`no call yet`})}}function sw({call:e,yours:t}){let[n,r]=(0,D.useState)(`call`),i=rw(e),{state:a}=i,o=new Set,s=YC(i.entries.filter(e=>!o.has(e.seq)&&(o.add(e.seq),!0))),c=e=>{let t=s.find(t=>t.name===e);return t===void 0?`—`:WC(t.seconds)},l=lw(a),u=[[`Turns`,String(a.turns.length)],[`ttft`,c(`llm_node_ttft`)],[`e2e`,c(`e2e_latency`)],[`Cost`,Yh(a.cost?.eur)],[`Tokens in`,uw(l.in)],[`Tokens out`,uw(l.out)]],d=Object.keys(a.app_state).sort(),f=[{tab:`call`,name:`Call`},{tab:`turns`,name:`Turns`,mark:(0,A.jsx)(`span`,{className:`inspector-count`,children:a.turns.length})},{tab:`tools`,name:`Tools`,mark:(0,A.jsx)(`span`,{className:`inspector-count`,children:a.tools.length})},{tab:`state`,name:`State`}];return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(aw,{connection:i.connection}),(0,A.jsx)(`div`,{className:`inspector-tabs`,children:(0,A.jsx)(yh,{label:`Inspector`,tabs:f,on:n,onPick:r})}),n===`call`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{children:t?`This session`:`Last session`}),(0,A.jsx)(`div`,{className:`inspector-figures`,children:u.map(([e,t])=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`inspector-figure-label`,children:e}),(0,A.jsx)(`div`,{className:`inspector-figure`,children:t})]},e))}),!t&&(0,A.jsx)(`p`,{className:`inspector-call`,children:e})]}),n===`turns`&&(0,A.jsxs)(`div`,{className:`inspector-turns`,children:[a.turns.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`No turn yet.`}),a.turns.map((e,t)=>(0,A.jsxs)(`div`,{className:`inspector-turn`,children:[(0,A.jsx)(`span`,{className:e.role===`agent`?`inspector-who inspector-who-agent`:`inspector-who`,children:e.role===`agent`?`agent`:`caller`}),(0,A.jsxs)(`span`,{className:`inspector-turn-body`,children:[(0,A.jsx)(`span`,{className:`inspector-turn-text`,children:e.text}),(0,A.jsx)(`span`,{className:`inspector-turn-meta`,children:cw(e)})]})]},`${e.speech_id}-${t}`))]}),n===`tools`&&(0,A.jsxs)(`div`,{className:`inspector-tools`,children:[a.tools.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`No tool has run.`}),a.tools.map(e=>(0,A.jsxs)(`div`,{className:`inspector-tool`,children:[(0,A.jsx)(`div`,{className:`inspector-tool-name`,children:e.name}),(0,A.jsx)(`div`,{className:`inspector-tool-args`,children:dw(e.arguments)}),(0,A.jsx)(`div`,{className:e.status===`failed`?`inspector-tool-result inspector-tool-failed`:e.status===`running`?`inspector-tool-result inspector-tool-running`:`inspector-tool-result`,children:e.status===`failed`?e.error??`failed`:e.status===`running`?`running…`:`ok${e.summary?` · ${e.summary}`:``}`})]},e.call_id))]}),n===`state`&&(0,A.jsxs)(`div`,{className:`inspector-state`,children:[d.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`The app has declared no state yet.`}),d.map(e=>(0,A.jsxs)(`div`,{className:`inspector-field`,children:[(0,A.jsx)(`span`,{className:`inspector-field-key`,children:e}),(0,A.jsx)(`span`,{className:`inspector-field-value`,children:fw(a.app_state[e])})]},e))]}),i.error!==null&&(0,A.jsx)(`p`,{className:`inspector-refused`,children:i.error})]})}function cw(e){if(e.role===`agent`){let t=[];return typeof e.metrics.llm_node_ttft==`number`&&t.push(`ttft ${WC(e.metrics.llm_node_ttft)}`),typeof e.metrics.e2e_latency==`number`&&t.push(`e2e ${WC(e.metrics.e2e_latency)}`),e.interrupted&&t.push(`interrupted`),t.join(` · `)}let t=[];return typeof e.metrics.transcription_delay==`number`&&t.push(`stt ${WC(e.metrics.transcription_delay)}`),t.push(e.speech_id),t.join(` · `)}function lw(e){let t=0,n=0;for(let r of e.usage)r.type===`llm_usage`&&(t+=(r.input_tokens??0)+(r.input_cached_tokens??0),n+=r.output_tokens??0);return{in:t,out:n}}function uw(e){return e.toLocaleString(`en-US`).replace(/,/g,` `)}function dw(e){let t=Object.entries(e).map(([e,t])=>`${e}=${fw(t)}`);return t.length===0?`no arguments`:t.join(` · `)}function fw(e){return typeof e==`string`?e:JSON.stringify(e)}var pw=`supervisor.`;function mw(e){if(!e.type.startsWith(pw))return null;let t=Rv(e);switch(t.type){case`supervisor.whispered`:return{said:`supervisor whispered: ${t.data.text}`,by:hw(t.data.by)};case`supervisor.said`:return{said:`supervisor made the agent say: ${t.data.text}`,by:hw(t.data.by)};case`supervisor.took_over`:return{said:`supervisor took the line`,by:hw(t.data.by)};case`supervisor.released`:return{said:`supervisor handed the line back`,by:hw(t.data.by)};case`supervisor.transferred`:return{said:`supervisor transferred the call to ${t.data.to}`,by:hw(t.data.by)};case`supervisor.ended`:return{said:`supervisor ended the call${gw(t.data.reason)}`,by:hw(t.data.by)};default:return null}}function hw(e){return e.name??e.id}function gw(e){return e==null?``:`: ${e}`}function _w(e,t){let n=[],r=[],i=()=>{r.length>0&&(n.push({kind:`quiet`,seq:r[0]?.seq??0,entries:r}),r=[])};for(let a of e){let e=vw(a,t);if(e===null){r.push(a);continue}i(),n.push(e)}return i(),n}function vw(e,t){let n=e.seq,r=mw(e);if(r!==null)return{kind:`supervisor`,seq:n,mark:r};let i=Rv(e);switch(i.type){case`turn.user`:case`turn.agent`:{let e=yw(t,i.type===`turn.user`?`user`:`agent`,i.data.speech_id);return e===void 0?null:{kind:`turn`,seq:n,turn:e}}case`tool.call`:{let e=bw(t.tools,e=>e.call_id===i.data.call_id);return e===void 0?null:{kind:`tool`,seq:n,run:e}}case`state.changed`:return{kind:`state`,seq:n,changed:i.data.changed,cause:i.data.cause??null};case`confirm.request`:{let e=bw(t.confirms,e=>e.call_id===i.data.call_id);return e===void 0?null:{kind:`confirm`,seq:n,confirm:e}}case`event.received`:return{kind:`event`,seq:n,name:i.data.name,source:i.data.source,data:i.data.data};case`memory.ops`:return{kind:`memory`,seq:n,ops:i.data};case`docs.sources`:return{kind:`sources`,seq:n,sources:i.data};default:return null}}function yw(e,t,n){return bw(e.turns,e=>e.role===t&&e.speech_id===n)}function bw(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(t(r))return r}}function xw(e){let t=new Map,n=new Set;for(let r of e)if(r.type===`agent.transcript`){let e=r.data;if(e.final)continue;t.set(e.speech_id,(t.get(e.speech_id)??``)+e.text)}else r.type===`turn.agent`&&n.add(r.data.speech_id);return{streaming:t,settled:n}}var Sw=new Map,Cw=1,ww=.18;function Tw(e,t,n){let[r,i]=(0,D.useState)(()=>n?t.length:Sw.get(e)??0),a=(0,D.useRef)(t.length);return a.current=t.length,(0,D.useEffect)(()=>{if(n){Sw.set(e,t.length),i(t.length);return}let r=0,o=()=>{i(t=>{let n=a.current-t;if(n<=0)return t;let r=Math.min(a.current,t+Math.max(Cw,Math.ceil(n*ww)));return Sw.set(e,r),r}),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>cancelAnimationFrame(r)},[e,n,t.length]),t.slice(0,Math.min(r,t.length))}var Ew=80;function Dw({watched:e,pending:t,onConfirmed:n}){let r=kw(e.entries),i=_w(r,e.state),{streaming:a,settled:o}=xw(r),s=(0,D.useRef)(null),c=(0,D.useRef)(!0),[l]=(0,D.useState)(()=>performance.now()),[u,d]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let e=window.setTimeout(()=>d(!0),600);return()=>window.clearTimeout(e)},[l]);let f=i.filter(e=>e.kind===`turn`&&e.turn.role===`user`).length;(0,D.useEffect)(()=>{let e=[...i].reverse().find(e=>e.kind===`turn`&&e.turn.role===`user`);e?.kind===`turn`&&n(e.turn.text)},[f]);let p=[...a.entries()].filter(([e])=>!o.has(e)),m=e.state.agent_state===`thinking`&&p.length===0;return(0,D.useLayoutEffect)(()=>{let e=s.current;e!==null&&c.current&&(e.scrollTop=e.scrollHeight)}),(0,A.jsxs)(`div`,{className:`chat-lines`,ref:s,onScroll:e=>{let t=e.currentTarget;c.current=t.scrollHeight-t.scrollTop-t.clientHeight<Ew},children:[i.map(e=>{if(e.kind===`turn`){let t=e.turn.speech_id??`seq-${String(e.seq)}`;return e.turn.role===`agent`?(0,A.jsx)(Ow,{speech:t,text:e.turn.text,instant:!u,done:!0},`turn-${String(e.seq)}`):(0,A.jsx)(`div`,{className:`chat-line chat-line-user`,children:(0,A.jsx)(`span`,{className:`chat-bubble chat-bubble-you`,children:e.turn.text})},`turn-${String(e.seq)}`)}return e.kind===`tool`?(0,A.jsx)(`div`,{className:`chat-line chat-line-tool`,children:(0,A.jsxs)(`span`,{className:`chat-tool chat-tool-${e.run.status}`,children:[e.run.name,` · `,e.run.error??e.run.summary??(e.run.status===`running`?`running…`:`done`)]})},`tool-${String(e.seq)}`):null}),p.map(([e,t])=>(0,A.jsx)(Ow,{speech:e,text:t,instant:!1,done:!1},`writing-${e}`)),t.map(e=>(0,A.jsx)(`div`,{className:`chat-line chat-line-user chat-line-pending`,children:(0,A.jsx)(`span`,{className:`chat-bubble chat-bubble-you`,children:e.text})},`pending-${String(e.id)}`)),m&&(0,A.jsx)(`div`,{className:`chat-line chat-line-agent`,children:(0,A.jsxs)(`span`,{className:`chat-bubble chat-typing`,"aria-label":`the agent is writing`,children:[(0,A.jsx)(`i`,{}),(0,A.jsx)(`i`,{}),(0,A.jsx)(`i`,{})]})}),e.error!==null&&(0,A.jsx)(`p`,{className:`chat-error`,children:e.error})]})}function Ow({speech:e,text:t,instant:n,done:r}){let i=Tw(e,t,n),a=i.length>=t.length;return(0,A.jsx)(`div`,{className:`chat-line chat-line-agent`,children:(0,A.jsxs)(`span`,{className:`chat-bubble`,children:[i,!(r&&a)&&(0,A.jsx)(`span`,{className:`chat-caret`,"aria-hidden":!0})]})})}function kw(e){let t=new Set;return e.filter(e=>!t.has(e.seq)&&(t.add(e.seq),!0))}var Aw=z({agent:P().nullable(),states:R(P())}),jw=z({call:P()});async function Mw(e,t){return Aw.parse(await $S(e,t,`chat.roster`))}async function Nw(e,t,n,r){let i={agent:t,...n===``?{}:{as:n},...r===``?{}:{golden:r}};return jw.parse(await $S(e,t,`chat.start`,i)).call}async function Pw(e,t,n,r){jw.parse(await $S(e,t,`chat.say`,{call:n,text:r}))}async function Fw(e,t,n){jw.parse(await $S(e,t,`chat.end`,{call:n}))}function Iw(){let e=Sr(),t=e.agent??``,n=e.call;return(0,A.jsxs)(`div`,{className:`chat-grid`,children:[(0,A.jsx)(`div`,{className:`chat-column`,children:n===void 0?(0,A.jsx)(Rw,{agent:t}):(0,A.jsx)(zw,{agent:t,call:n})}),(0,A.jsx)(iw,{agent:t,call:n??null})]})}function Lw({agent:e,children:t}){return(0,A.jsxs)(`div`,{className:`chat-head`,children:[(0,A.jsxs)(`div`,{className:`chat-head-words`,children:[(0,A.jsxs)(`div`,{className:`chat-title`,children:[`Chat with `,e]}),(0,A.jsx)(`div`,{className:`chat-sub`,children:`The same agent, typed instead of spoken — every turn still lands in the log.`})]}),t]})}function Rw({agent:e}){let t=j(),n=vr(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let n=!1;return Mw(t,e).then(e=>{n||i(e)},e=>{n||u(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[t,e]);let p=async r=>{r.preventDefault(),f(!0),u(null);try{n(`/a/${e}/dev-chat/${await Nw(t,e,a.trim(),s)}`)}catch(e){u(e instanceof na?e.message:String(e))}finally{f(!1)}};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Lw,{agent:e}),(0,A.jsx)(`div`,{className:`chat-lines`,children:(0,A.jsxs)(`div`,{className:`chat-start ui-card`,children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Start a conversation`})}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[r===null&&l===null&&(0,A.jsxs)(`p`,{className:`chat-note`,children:[`Asking the terminal that holds `,e,`…`]}),r!==null&&r.agent!==e&&(0,A.jsx)(`p`,{className:`chat-note`,children:r.agent===null?"No agent class in the directory this agent's `pinecall start` runs in, so there is nothing to chat with. Run `pinecall start` where its agent.tsx is.":`The process holding the agent runs in ${r.agent}'s directory: to chat with ${e}, run \`pinecall start\` there.`}),r!==null&&r.agent===e&&(0,A.jsxs)(`form`,{className:`chat-start-form`,onSubmit:e=>void p(e),children:[(0,A.jsx)(`p`,{className:`chat-note`,children:`The class of this directory, in writing. Its tools run in the terminal that serves this page, and a conversation can open part-way through, in the state one of the goldens declares.`}),(0,A.jsx)(Wm,{label:`As`,children:(0,A.jsx)(W,{value:a,placeholder:`a phone number, a customer id — or nobody`,onChange:e=>o(e.target.value)})}),r.states.length>0&&(0,A.jsx)(Wm,{label:`From`,children:(0,A.jsxs)(Hm,{value:s,onChange:e=>c(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the call's own opening`}),r.states.map(e=>(0,A.jsxs)(`option`,{value:e,children:[`the state of `,e]},e))]})}),(0,A.jsx)(`div`,{children:(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:d,children:d?`Opening…`:`Start the chat`})})]}),(0,A.jsx)(Nm,{children:l})]})]})})]})}function zw({agent:e,call:t}){let n=j(),r=vr(),[i,a]=(0,D.useState)([]),[o,s]=(0,D.useState)(null),c=(0,D.useRef)(0),l=rw(t),u=l.state.status===`ended`||l.connection===`ended`,d=async()=>{try{await Fw(n,e,t)}catch(e){s(e instanceof na?e.message:String(e));return}r(`/a/${e}/sessions/${t}`)};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Lw,{agent:e,children:(0,A.jsxs)(`div`,{className:`chat-head-actions`,children:[(0,A.jsx)(Wi,{className:`chat-whole`,to:`/a/${e}/sessions/${t}`,children:`Session`}),!u&&(0,A.jsx)(U,{size:`md`,onClick:()=>void d(),title:`hanging up seals the log and runs the judges`,children:`Hang up`})]})}),(0,A.jsx)(Dw,{watched:l,pending:i,onConfirmed:e=>a(t=>{let n=t.findIndex(t=>t.text===e);return n===-1?t:[...t.slice(0,n),...t.slice(n+1)]})}),o!==null&&(0,A.jsx)(`div`,{className:`chat-refused`,children:(0,A.jsx)(Nm,{children:o})}),u?(0,A.jsx)(`div`,{className:`chat-over`,children:`This chat has ended — it is on the session, whole.`}):(0,A.jsx)(Bw,{agent:e,call:t,onRefused:s,onSent:e=>{c.current+=1;let t={id:c.current,text:e};return a(e=>[...e,t]),()=>a(e=>e.filter(e=>e.id!==t.id))}})]})}function Bw({agent:e,call:t,onSent:n,onRefused:r}){let i=j(),[a,o]=(0,D.useState)(``),s=async s=>{s.preventDefault();let c=a.trim();if(c===``)return;o(``),r(null);let l=n(c);try{await Pw(i,e,t,c)}catch(e){l(),o(c),r(e instanceof na?e.message:String(e))}};return(0,A.jsxs)(`form`,{className:`chat-composer`,onSubmit:e=>void s(e),children:[(0,A.jsx)(`input`,{className:`chat-say`,value:a,autoFocus:!0,placeholder:`Ask the agent something`,onChange:e=>o(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`chat-send`,disabled:a.trim()===``,children:`Send`})]})}var Vw=z({golden:P(),model:P(),call:P()}),Hw=z({metric:P(),score:F(),passed:L(),reason:P(),criteria:P(),judge_calls:I()}),Uw=z({model:P(),golden:P(),scores:R(Hw),summary:fp(P(),Zf()).nullable()}),Ww=z({models:R(P()),goldens:R(P()),metrics:R(P()),judge_calls:I(),runs:R(Uw),failures:R(z({model:P(),golden:P(),metric:P()}))}),Gw=z({runs:R(z({id:P(),agent:P(),started_at:F(),finished_at:F().nullable(),status:mp([`running`,`done`,`failed`]),calls:R(Vw),matrix:Ww.nullable(),error:P().nullable()}))}),Kw=200;async function qw(e){return Gw.parse(await k(e,`/v1/evals/runs`,{limit:Kw})).runs}async function Jw(e,t){return Gw.parse(await k(e,`/v1/evals/runs`,{agent:t,limit:Kw})).runs}var Yw=z({held:I(),settled:I(),percent:F()}),Xw=z({judge:P(),before:Yw.nullable(),now:Yw.nullable(),delta:F().nullable()}),Zw=z({call:P(),judge:P(),seqs:R(I()),reason:P()}),Qw=z({agent:P(),window:F(),baseline:F(),threshold:F(),drift:z({judges:R(Xw),notJudged:z({now:I(),before:I()}),broke:R(Zw),worst:F().nullable()})});async function $w(e,t,n,r){return Qw.parse(await $S(e,t,`drift.read`,{agent:t,window:n,baseline:r}))}var eT=z({check:P(),status:P(),detail:P()}),tT=z({call:P(),agent:P(),passed:L(),verdicts:R(eT)});async function nT(e,t){return tT.parse(await sa(e,`/v1/evals/replay/${encodeURIComponent(t)}`,{}))}var rT=z({path:P(),candidate:z({name:P(),input:R(P())}),notes:R(P())});async function iT(e,t,n){return rT.parse(await $S(e,t,`promote.write`,{call:n}))}var aT=z({run:P(),folder:P(),goldens:R(P())}),oT=z({run:P(),agent:P(),golden:P(),model:P(),call:P(),declared:Zf(),verdicts:R(z({metric:P(),passed:L(),criteria:P(),reason:P()})),asked:Zf()});async function sT(e,t,n){return aT.parse(await $S(e,t,`reproductions.roster`,{run:n}))}async function cT(e,t,n,r){return oT.parse(await $S(e,t,`reproductions.read`,{run:n,golden:r}))}var lT=`minmax(0,1.2fr) minmax(0,1.3fr) 90px minmax(0,1fr) 80px`,uT=`minmax(0,1fr) 150px 70px minmax(0,2fr) 90px`;function dT(){let e=j(),{agents:t,lines:n}=Xy(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return qw(e).then(e=>{t||i(e)},e=>{t||(i([]),o(e instanceof na?e.message:String(e)))}),()=>{t=!0}},[e]);let s=n.filter(e=>e.score!=null),c=s.filter(e=>e.score?.passed===!1),l=[...new Set([...t.map(e=>e.slug),...(r??[]).map(e=>e.agent),...s.map(e=>e.agent)])].sort().map(e=>fT(e,r??[],s)),u=s.length-c.length,d=l.filter(e=>e.suite!==null),f=d.filter(e=>e.suite!==null&&e.suite.held===e.suite.cells).length;return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Evals`,lede:`How every agent is doing: the suites run on purpose, and the real calls judged at hang-up.`}),(0,A.jsx)(Nm,{children:a}),(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{size:`small`,label:`Calls judged`,value:s.length,of:`of the last ${n.length}`}),(0,A.jsx)(uh,{size:`small`,label:`Held`,value:s.length===0?`—`:ag(u/s.length),accent:!0}),(0,A.jsx)(uh,{size:`small`,label:`Did not hold`,value:c.length}),(0,A.jsx)(uh,{size:`small`,label:`Suites green`,value:d.length===0?`—`:`${f} of ${d.length}`})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`By agent`,meta:`a row opens that agent's Evals: its goldens, its runs, its drift`}),l.length===0?(0,A.jsx)(Mm,{children:`No agent is held here yet.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:lT,labels:[`Agent`,`Last suite`,`Judged`,`Held on real calls`,``]}),l.map(e=>(0,A.jsxs)(fh,{columns:lT,to:`/a/${e.slug}/evals`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.slug}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.suite===null?(0,A.jsx)(`span`,{className:`oev-none`,children:`no suite run in this world`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(Qm,{tone:e.suite.held===e.suite.cells?`green`:`red`,children:[e.suite.held,`/`,e.suite.cells]}),` `,(0,A.jsx)(`span`,{className:`oev-when`,children:eg(e.suite.at)})]})}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.judged}),(0,A.jsx)(`span`,{className:`oev-held`,children:e.judged===0?(0,A.jsx)(`span`,{className:`oev-none`,children:`nothing judged yet`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(oh,{share:e.held/e.judged}),(0,A.jsx)(`span`,{className:`oev-share`,children:ag(e.held/e.judged)})]})}),(0,A.jsx)(`span`,{className:`ui-cell-end oev-open`,children:`Open →`})]},e.slug))]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Calls that did not hold`,meta:`a judge answered broken — the reason is the judge's own`}),c.length===0?(0,A.jsx)(Mm,{children:s.length===0?`No call has been judged yet. Judging is turned on from Home.`:`Every judged call held.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:uT,labels:[`Caller`,`Agent`,`Score`,`Why`,`When>`]}),c.slice(0,40).map(e=>(0,A.jsxs)(fh,{columns:uT,to:`/sessions/${e.call}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:sg(e)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(`span`,{className:`ui-cell`,children:(0,A.jsxs)(Qm,{tone:`red`,children:[e.score?.held,`/`,e.score?.judged]})}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.score?.reason??`—`}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-cell-end`,children:eg(e.started_at)})]},e.call))]})]})]})}function fT(e,t,n){let r=t.find(t=>t.agent===e&&t.status===`done`&&t.matrix!==null),i=r?.matrix??null,a=n.filter(t=>t.agent===e);return{slug:e,suite:r===void 0||i===null?null:{at:r.started_at,cells:i.runs.length,held:i.runs.filter(e=>e.scores.every(e=>e.passed)).length,failing:[...new Set(i.failures.map(e=>e.golden))]},judged:a.length,held:a.filter(e=>e.score?.passed===!0).length}}var pT=z({agent:P().nullable(),golden:P().nullable(),questions:I(),cases:R(P())});async function mT(e,t){return oy.parse(await k(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function hT(e,t){return sy.parse(await ca(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function gT(e,t){return pT.parse(await $S(e,t,`memory.roster`,{agent:t}))}async function _T(e,t){return ly.parse(await $S(e,t,`memory.eval`,{agent:t}))}async function vT(e,t){return py.parse(await $S(e,t,`memory.extraction`,{agent:t}))}var yT=z({facts:R(z({id:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:ip([P(),F()]).nullish()});async function bT(e,t){try{return yT.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/memory`)).facts}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}async function xT(e,t){await ca(e,`/v1/memory/facts/${encodeURIComponent(t)}`)}var ST=z({facts:R(z({id:P(),agent:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:P().nullish()});async function CT(e,t,n){let r={};t!==``&&(r.q=t),n!==null&&(r.after=n);try{return ST.parse(await k(e,`/v1/memory`,r))}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}var wT=`150px 140px minmax(0,1fr) 100px 64px`;function TT(e){return e.startsWith(`+`)?og(e):e}function ET(e){return e instanceof Error?e.message:String(e)}function DT(){let e=j(),[t,n]=(0,D.useState)(``),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(void 0),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=window.setTimeout(()=>i(t.trim()),300);return()=>window.clearTimeout(e)},[t]),(0,D.useEffect)(()=>{let t=!1;return u(null),CT(e,r,null).then(e=>{t||(o(e===null?null:e.facts),c(e?.next??null))},e=>{t||u(ET(e))}),()=>{t=!0}},[e,r]);let d=async()=>{if(s!==null)try{let t=await CT(e,r,s);if(t===null)return;o(e=>[...e??[],...t.facts]),c(t.next??null)}catch(e){u(ET(e))}},f=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${TT(t.contact)} stays.`)){u(null);try{await xT(e,t.id),o(e=>(e??[]).filter(e=>e.id!==t.id))}catch(e){u(ET(e))}}};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Memory`,ledeWidth:640,lede:`What every agent carries between calls with the same caller — newest first, each fact with the agent whose call taught it, droppable one row at a time.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Remembered`,meta:a?`${a.length}${s===null?``:`+`} facts`:void 0,children:(0,A.jsx)(`div`,{className:`mem-look`,children:(0,A.jsx)(W,{size:`sm`,value:t,placeholder:`Search a caller, a word, a category`,onChange:e=>n(e.target.value)})})}),a===void 0?(0,A.jsx)(Mm,{children:`Asking the gateway what the agents remember…`}):a===null?(0,A.jsx)(Mm,{children:`This gateway keeps no memory: it runs without the database memory lives in.`}):a.length===0?(0,A.jsx)(Mm,{children:r===``?"No agent remembers anything about any caller yet. An agent that declares `memory` writes what it learns when a call hangs up.":`Nothing remembered matches.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:wT,labels:[`Caller`,`Agent`,`Remembered`,`Written`,`Action>`]}),a.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:wT},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:TT(e.contact)}),(0,A.jsx)(`span`,{className:`ui-clip`,children:(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e.agent)}/memory`,children:e.agent})}),(0,A.jsxs)(`span`,{className:`mem-fact`,children:[e.text,e.category?(0,A.jsxs)(`span`,{className:`mem-superseded`,children:[` · `,e.category]}):null]}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:$h(e.written_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void f(e),children:`Drop`})})]},e.id)),s!==null&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:(0,A.jsx)(U,{size:`sm`,onClick:()=>void d(),children:`Load more`})})]})]}),(0,A.jsx)(Nm,{children:l})]})}var OT=`lk.transcription`,kT=`lk.transcription_final`,AT=`lk.chat`,jT=1500,MT=`→`,NT=`←`,PT=`✗`;function FT(e,t){let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[...e,t];let r=e.slice();return r[n]=t,r}function IT(e){return e.split(/(\s+)/).filter(e=>e.length>0)}function LT(e){let t=mw(e);if(t!==null)return{kind:`mark`,id:`mark-${e.seq}`,tone:`supervisor`,text:t.said};let n=e.data;switch(e.type){case`tool.call`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${MT} ${String(n.name)}(${zT(n.arguments)})`};case`tool.result`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${NT} ${String(n.name)} ${RT(n)}`};case`error`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`error`,text:`${PT} ${String(n.message)}`};default:return null}}function RT(e){return e.error!==void 0&&e.error!==null?`error: ${zT(e.error)}`:typeof e.summary==`string`?e.summary:e.output===void 0?`nothing`:zT(e.output)}function zT(e,t=80){let n=typeof e==`string`?e:JSON.stringify(e)??String(e);return n.length>t?`${n.slice(0,t-1)}…`:n}function BT({lines:e,mode:t,children:n}){let r=(0,D.useRef)(null);return(0,D.useEffect)(()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight)},[e]),(0,A.jsxs)(`div`,{className:t===`chat`?`talk-whole`:`ui-card`,children:[t===`talk`&&(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`This call`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`spoken or written, as the room says it`})]}),(0,A.jsxs)(`div`,{className:`talk-lines`,ref:r,children:[e.length===0&&(0,A.jsxs)(`p`,{className:`talk-quiet`,children:[`Nothing said yet. `,t===`talk`?`What you say and what you write both land here.`:`What you write and the agent's replies land here.`]}),e.map(e=>e.kind===`said`?(0,A.jsx)(VT,{line:e},e.id):(0,A.jsx)(HT,{mark:e},e.id))]}),n]})}function VT({line:e}){return(0,A.jsx)(`div`,{className:e.speaker===`user`?`talk-said talk-said-you`:`talk-said`,children:(0,A.jsxs)(`p`,{className:`talk-bubble${e.speaker===`user`?` talk-bubble-you`:``}${!e.final||e.pending===!0?` talk-bubble-unsettled`:``}`,children:[IT(e.text).map((e,t)=>(0,A.jsx)(`span`,{className:`talk-word`,children:e},t)),!e.final&&(0,A.jsx)(`span`,{className:`talk-cursor`,"aria-hidden":!0})]})})}function HT({mark:e}){return(0,A.jsx)(`p`,{className:`talk-mark talk-mark-${e.tone}`,children:e.text})}function UT({open:e,mode:t,onWrite:n}){let[r,i]=(0,D.useState)(``);return(0,A.jsxs)(`form`,{className:`talk-composer`,onSubmit:t=>{t.preventDefault();let a=r.trim();a!==``&&e&&(i(``),n(a))},children:[(0,A.jsx)(`input`,{className:`talk-write`,value:r,disabled:!e,placeholder:e?t===`talk`?`Write to the agent — or just speak`:`Write to the agent`:t===`talk`?`Press Call first — then speak or write`:`Press Chat first — then write`,onChange:e=>i(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`talk-send`,disabled:!e||r.trim()===``,children:`Send`})]})}function WT(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var GT=Object.defineProperty,KT=(e,t,n)=>t in e?GT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,qT=(e,t,n)=>KT(e,typeof t==`symbol`?t:t+``,n),JT=class{constructor(){qT(this,`_locking`),qT(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function YT(e,t){if(!e)throw Error(t)}var XT=34028234663852886e22,ZT=-34028234663852886e22,QT=4294967295,$T=2147483647,eE=-2147483648;function tE(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>$T||e<eE)throw Error(`invalid int 32: `+e)}function nE(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>QT||e<0)throw Error(`invalid uint 32: `+e)}function rE(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>XT||e<ZT))throw Error(`invalid float 32: `+e)}var iE=Symbol(`@bufbuild/protobuf/enum-type`);function aE(e){let t=e[iE];return YT(t,`missing enum type on enum object`),t}function oE(e,t,n,r){e[iE]=sE(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function sE(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=lE(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function cE(e,t,n){let r={};for(let e of t){let t=lE(e);r[t.localName]=t.no,r[t.no]=t.localName}return oE(r,e,t),r}function lE(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var uE=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function dE(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new uE),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function fE(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function pE(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var mE=4294967296;function hE(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=mE&&(i+=r/mE|0,r%=mE)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?bE(r,i):yE(r,i)}function gE(e,t){let n=yE(e,t),r=n.hi&2147483648;r&&(n=bE(n.lo,n.hi));let i=_E(n.lo,n.hi);return r?`-`+i:i}function _E(e,t){var n=vE(e,t);if(e=n.lo,t=n.hi,t<=2097151)return String(mE*t+e);let r=e&16777215,i=(e>>>24|t<<8)&16777215,a=t>>16&65535,o=r+i*6777216+a*6710656,s=i+a*8147497,c=a*2,l=1e7;return o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(c+=Math.floor(s/l),s%=l),c.toString()+xE(s)+xE(o)}function vE(e,t){return{lo:e>>>0,hi:t>>>0}}function yE(e,t){return{lo:e|0,hi:t|0}}function bE(e,t){return t=~t,e?e=~e+1:t+=1,yE(e,t)}var xE=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function SE(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function CE(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function wE(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||{}.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>YT(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>YT(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),hE(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),hE(e)},dec(e,t){return gE(e,t)},uDec(e,t){return _E(e,t)}}}var TE=wE(),G;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(G||={});var EE;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(EE||={});function DE(e,t,n){if(t===n)return!0;if(e==G.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return t==n}return!1}function OE(e,t){switch(e){case G.BOOL:return!1;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return t==0?TE.zero:`0`;case G.DOUBLE:case G.FLOAT:return 0;case G.BYTES:return new Uint8Array;case G.STRING:return``;default:return 0}}function kE(e,t){switch(e){case G.BOOL:return t===!1;case G.STRING:return t===``;case G.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}function AE(e,t){this.v=e,this.k=t}function jE(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ME(e){if(Array.isArray(e))return e}function NE(e,t,n){return(t=UE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PE(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function FE(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function IE(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
63
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function LE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function RE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?LE(Object(n),!0).forEach(function(t){NE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):LE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function zE(e,t){if(e==null)return{};var n,r,i=BE(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function BE(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function K(e,t){return ME(e)||FE(e,t)||WE(e,t)||IE()}function VE(e){return ME(e)||PE(e)||WE(e)||IE()}function HE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function UE(e){var t=HE(e,`string`);return typeof t==`symbol`?t:t+``}function WE(e,t){if(e){if(typeof e==`string`)return jE(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?jE(e,t):void 0}}function GE(e){return function(){return new KE(e.apply(this,arguments))}}function KE(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof AE;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}KE.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},KE.prototype.next=function(e){return this._invoke(`next`,e)},KE.prototype.throw=function(e){return this._invoke(`throw`,e)},KE.prototype.return=function(e){return this._invoke(`return`,e)};var qE;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(qE||={});var JE=class{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 t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].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 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(nE(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return tE(e),SE(e,this.buf),this}bool(e){return this.buf.push(+!!e),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){rE(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){nE(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){tE(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return tE(e),e=(e<<1^e>>31)>>>0,SE(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=TE.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=TE.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=TE.enc(e);return pE(t.lo,t.hi,this.buf),this}sint64(e){let t=TE.enc(e),n=t.hi>>31;return pE(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=TE.uEnc(e);return pE(t.lo,t.hi,this.buf),this}},YE=class{constructor(e,t){this.varint64=fE,this.uint32=CE,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,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case qE.Varint:for(;this.buf[this.pos++]&128;);break;case qE.Bit64:this.pos+=4;case qE.Bit32:this.pos+=4;break;case qE.LengthDelimited:let n=this.uint32();this.pos+=n;break;case qE.StartGroup:for(;;){let e=K(this.tag(),2),n=e[0],r=e[1];if(r===qE.EndGroup){if(t!==void 0&&n!==t)throw Error(`invalid end group tag`);break}this.skip(r,n)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return TE.dec(...this.varint64())}uint64(){return TE.uDec(...this.varint64())}sint64(){let e=K(this.varint64(),2),t=e[0],n=e[1],r=-(t&1);return t=(t>>>1|(n&1)<<31)^r,n=n>>>1^r,TE.dec(t,n)}bool(){let e=K(this.varint64(),2),t=e[0],n=e[1];return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return TE.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return TE.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 XE(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function ZE(e){let t=e.field.localName,n=Object.create(null);return n[t]=QE(e),[n,()=>n[t]]}function QE(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return OE(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function $E(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var eD=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),tD=[];for(let e=0;e<eD.length;e++)tD[eD[e].charCodeAt(0)]=e;tD[45]=eD.indexOf(`+`),tD[95]=eD.indexOf(`/`);var nD={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=tD[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
64
- `:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=eD[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=eD[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=eD[i|r>>6],t+=eD[r&63],n=0}return n&&(t+=eD[i],t+=`=`,n==1&&(t+=`=`)),t}};function rD(e,t,n){oD(t,e);let r=t.runtime.bin.makeReadOptions(n),i=$E(e.getType().runtime.bin.listUnknownFields(e),t.field),a=K(ZE(t),2),o=a[0],s=a[1];for(let e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function iD(e,t,n,r){oD(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(aD(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let t=K(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function aD(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function oD(e,t){YT(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function sD(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!kE(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function cD(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?OE(e.T,e.L):void 0;break;case`message`:t[n]=void 0}}function lD(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(uE.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0||n.typeName==t.typeName}function uD(e,t){return lD(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}G.DOUBLE,G.FLOAT,G.INT64,G.UINT64,G.INT32,G.UINT32,G.BOOL,G.STRING,G.BYTES;var dD={ignoreUnknownFields:!1},fD={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function pD(e){return e?Object.assign(Object.assign({},dD),e):dD}function mD(e){return e?Object.assign(Object.assign({},fD),e):fD}var hD=Symbol(),gD=Symbol();function _D(){return{makeReadOptions:pD,makeWriteOptions:mD,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${vD(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let s of Object.entries(t)){var o=K(s,2);let t=o[0],c=o[1],l=e.fields.findJsonName(t);if(l){if(l.oneof){if(c===null&&l.kind==`scalar`)continue;let n=i.get(l.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${l.oneof.name}" present: "${n}", "${t}"`);i.set(l.oneof,t)}yD(r,c,l,n,e)}else{let i=!1;if(a?.findExtension&&t.startsWith(`[`)&&t.endsWith(`]`)){let o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;let e=K(ZE(o),2),t=e[0],a=e[1];yD(t,c,o.field,n,o),iD(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${t}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!sD(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!CD(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=wD(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&aD(e,o)){let n=rD(e,o,t),i=wD(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return xD(e,t,n??EE.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||kE(e,t)))return ED(e,t)},debug:vD}}function vD(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function yD(e,t,n,r,i){let a=n.localName;if(n.repeated){if(YT(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${vD(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${vD(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=SD(n.T,e,r.ignoreUnknownFields,!0);t!==gD&&o.push(t);break;case`scalar`:try{o.push(xD(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${vD(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${vD(t)}`);let s=e[a];for(let e of Object.entries(t)){var o=K(e,2);let a=o[0],c=o[1];if(c===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let l;try{l=bD(n.K,a)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${vD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:s[l]=n.V.T.fromJson(c,r);break;case`enum`:let e=SD(n.V.T,c,r.ignoreUnknownFields,!0);e!==gD&&(s[l]=e);break;case`scalar`:try{s[l]=xD(n.V.T,c,EE.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${vD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];lD(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=SD(n.T,t,r.ignoreUnknownFields,!1);switch(c){case hD:cD(n,e);break;case gD:break;default:e[a]=c}break;case`scalar`:try{let r=xD(n.T,t,n.L,!1);switch(r){case hD:cD(n,e);break;default:e[a]=r}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${vD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}function bD(e,t){if(e===G.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1}return xD(e,t,EE.BIGINT,!0).toString()}function xD(e,t,n,r){if(t===null)return r?OE(e,n):hD;switch(e){case G.DOUBLE:case G.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==G.FLOAT&&rE(r),r;case G.INT32:case G.FIXED32:case G.SFIXED32:case G.SINT32:case G.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==G.UINT32||e==G.FIXED32?nE(i):tE(i),i;case G.INT64:case G.SFIXED64:case G.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=TE.parse(t);return n?a.toString():a;case G.FIXED64:case G.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=TE.uParse(t);return n?o.toString():o;case G.BOOL:if(typeof t!=`boolean`)break;return t;case G.STRING:if(typeof t!=`string`)break;return t;case G.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return nD.dec(t)}throw Error()}function SD(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:hD;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return gD}throw Error(`cannot decode enum ${e.typeName} from JSON: ${vD(t)}`)}function CD(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function wD(e,t,n){if(e.kind==`map`){YT(typeof t==`object`&&!!t);let o={},s=Object.entries(t);switch(e.V.kind){case`scalar`:for(let t of s){var r=K(t,2);let n=r[0],i=r[1];o[n.toString()]=ED(e.V.T,i)}break;case`message`:for(let e of s){var i=K(e,2);let t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case`enum`:let t=e.V.T;for(let e of s){var a=K(e,2);let r=a[0],i=a[1];o[r.toString()]=TD(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){YT(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(ED(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(TD(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return ED(e.T,t);case`enum`:return TD(e.T,t,n.enumAsInteger);case`message`:return uD(e.T,t).toJson(n)}}function TD(e,t,n){return YT(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function ED(e,t){switch(e){case G.INT32:case G.SFIXED32:case G.SINT32:case G.FIXED32:case G.UINT32:return YT(typeof t==`number`),t;case G.FLOAT:case G.DOUBLE:return YT(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case G.STRING:return YT(typeof t==`string`),t;case G.BOOL:return YT(typeof t==`boolean`),t;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return YT(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case G.BYTES:return YT(t instanceof Uint8Array),nD.enc(t)}}var DD=Symbol(`@bufbuild/protobuf/unknown-fields`),OD={readUnknownFields:!0,readerFactory:e=>new YE(e)},kD={writeUnknownFields:!0,writerFactory:()=>new JE};function AD(e){return e?Object.assign(Object.assign({},OD),e):OD}function jD(e){return e?Object.assign(Object.assign({},kD),e):kD}function MD(){return{makeReadOptions:AD,makeWriteOptions:jD,listUnknownFields(e){return e[DD]??[]},discardUnknownFields(e){delete e[DD]},writeUnknownFields(e,t){let n=e[DD];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[DD])||(i[DD]=[]),i[DD].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o;){var l=K(t.tag(),2);if(s=l[0],c=l[1],i===!0&&c==qE.EndGroup)break;let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}ND(e,t,n,c,r)}if(i&&(c!=qE.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:ND,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!sD(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}RD(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&RD(e,t,n,r)}}}function ND(e,t,n,r,i){let a=n.repeated,o=n.localName;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?G.INT32:n.T,c=LD;if(n.kind==`scalar`&&n.L>0&&(c=ID),a){let n=e[o];if(r==qE.LengthDelimited&&s!=G.STRING&&s!=G.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(PD(t,new l,i,n)):lD(e[o])?PD(t,e[o],i,n):(e[o]=PD(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let u=K(FD(n,t,i),2),d=u[0],f=u[1];e[o][d]=f}}function PD(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function FD(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;)switch(K(t.tag(),1)[0]){case 1:a=LD(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=LD(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=PD(t,new e.V.T,n,void 0)}}if(a===void 0&&(a=OE(e.K,EE.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=OE(e.V.T,EE.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T}return[a,o]}function ID(e,t){let n=LD(e,t);return typeof n==`bigint`?n.toString():n}function LD(e,t){switch(t){case G.STRING:return e.string();case G.BOOL:return e.bool();case G.DOUBLE:return e.double();case G.FLOAT:return e.float();case G.INT32:return e.int32();case G.INT64:return e.int64();case G.UINT64:return e.uint64();case G.FIXED64:return e.fixed64();case G.BYTES:return e.bytes();case G.FIXED32:return e.fixed32();case G.SFIXED32:return e.sfixed32();case G.SFIXED64:return e.sfixed64();case G.SINT64:return e.sint64();case G.UINT32:return e.uint32();case G.SINT32:return e.sint32()}}function RD(e,t,n,r){YT(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let o=e.kind==`enum`?G.INT32:e.T;if(i){if(YT(Array.isArray(t)),e.packed)HD(n,o,e.no,t);else for(let r of t)VD(n,o,e.no,r)}else VD(n,o,e.no,t);break;case`message`:if(i){YT(Array.isArray(t));for(let i of t)BD(n,r,e,i)}else BD(n,r,e,t);break;case`map`:YT(typeof t==`object`&&!!t);for(let i of Object.entries(t)){var a=K(i,2);let t=a[0],o=a[1];zD(n,r,e,t,o)}}}function zD(e,t,n,r,i){e.tag(n.no,qE.LengthDelimited),e.fork();let a=r;switch(n.K){case G.INT32:case G.FIXED32:case G.UINT32:case G.SFIXED32:case G.SINT32:a=Number.parseInt(r);break;case G.BOOL:YT(r==`true`||r==`false`),a=r==`true`}switch(VD(e,n.K,1,a),n.V.kind){case`scalar`:VD(e,n.V.T,2,i);break;case`enum`:VD(e,G.INT32,2,i);break;case`message`:YT(i!==void 0),e.tag(2,qE.LengthDelimited).bytes(i.toBinary(t))}e.join()}function BD(e,t,n,r){let i=uD(n.T,r);n.delimited?e.tag(n.no,qE.StartGroup).raw(i.toBinary(t)).tag(n.no,qE.EndGroup):e.tag(n.no,qE.LengthDelimited).bytes(i.toBinary(t))}function VD(e,t,n,r){YT(r!==void 0);let i=K(UD(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function HD(e,t,n,r){if(!r.length)return;e.tag(n,qE.LengthDelimited).fork();let i=K(UD(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function UD(e){let t=qE.Varint;switch(e){case G.BYTES:case G.STRING:t=qE.LengthDelimited;break;case G.DOUBLE:case G.FIXED64:case G.SFIXED64:t=qE.Bit64;break;case G.FIXED32:case G.SFIXED32:case G.FLOAT:t=qE.Bit32}let n=G[e].toLowerCase();return[t,n]}function WD(){return{setEnumType:oE,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let i of n.fields.byMember()){let n=i.localName,a=t,o=e;if(o[n]!=null)switch(i.kind){case`oneof`:let e=o[n].case;if(e===void 0)continue;let t=i.findField(e),s=o[n].value;t&&t.kind==`message`&&!lD(s,t.T)?s=new t.T(s):t&&t.kind===`scalar`&&t.T===G.BYTES&&(s=KD(s)),a[n]={case:e,value:s};break;case`scalar`:case`enum`:let c=o[n];i.T===G.BYTES&&(c=i.repeated?c.map(KD):KD(c)),a[n]=c;break;case`map`:switch(i.V.kind){case`scalar`:case`enum`:if(i.V.T===G.BYTES)for(let e of Object.entries(o[n])){var r=K(e,2);let t=r[0],i=r[1];a[n][t]=KD(i)}else Object.assign(a[n],o[n]);break;case`message`:let e=i.V.T;for(let t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case`message`:let l=i.T;if(i.repeated)a[n]=o[n].map(e=>lD(e,l)?e:new l(e));else{let e=o[n];a[n]=l.fieldWrapper?l.typeName===`google.protobuf.BytesValue`?KD(e):e:lD(e,l)?e:new l(e)}}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>DE(e.T,t,i[n]));case`enum`:return r.every((e,t)=>DE(G.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!lD(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!lD(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return DE(G.INT32,r,i);case`scalar`:return DE(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return DE(G.INT32,r.value,i.value);case`scalar`:return DE(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>DE(G.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>DE(n,r[e],i[e]))}}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],a;if(n.repeated)a=t.map(GD);else if(n.kind==`map`){a=r[n.localName];for(let e of Object.entries(t)){var i=K(e,2);let t=i[0],n=i[1];a[t]=GD(n)}}else a=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:GD(t.value)}:{case:void 0}:GD(t);r[n.localName]=a}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function GD(e){if(e===void 0)return e;if(lD(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function KD(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function qD(e,t,n){return{syntax:e,json:_D(),bin:MD(),util:Object.assign(Object.assign({},WD()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return dE(this,e,t,n)},makeEnum:cE,makeEnumType:sE,getEnumType:aE,makeExtension(e,t,n){return XE(this,e,t,n)}}}var JD=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function YD(e,t){let n=QD(e);return t?n:rO(nO(n))}function XD(e){return YD(e,!1)}var ZD=QD;function QD(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join(``)}var $D=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),eO=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),tO=e=>`${e}\$`,nO=e=>eO.has(e)?tO(e):e,rO=e=>$D.has(e)?tO(e):e,iO=class{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=XD(e)}addField(e){YT(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function aO(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=YD(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??ZD(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??EE.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=G.BYTES&&t.T!=G.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new iO(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var q=qD(`proto3`,e=>new JD(e,e=>aO(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=OE(t.T,t.L)}}}),oO=class e extends uE{constructor(e){super(),this.seconds=TE.zero,this.nanos=0,q.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${q.json.debug(e)}`);let n=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(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw 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 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=TE.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw 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 Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:TE.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return q.util.equals(e,t,n)}};oO.runtime=q,oO.typeName=`google.protobuf.Timestamp`,oO.fields=q.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var sO=q.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:oO},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:cO,repeated:!0},{no:5,name:`events`,kind:`message`,T:uO,repeated:!0}]),cO=q.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:lO,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),lO=q.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:oO},{no:3,name:`value`,kind:`scalar`,T:2}]),uO=q.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:oO},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:oO,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),dO=q.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),fO=q.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),pO=q.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`}]),mO=q.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),hO=q.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),gO=q.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),_O=q.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`},{no:16,name:`AGENT_ERROR`}]),vO=q.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`}]),yO=q.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),bO=q.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`}]),xO=q.makeEnum(`livekit.PacketTrailerFeature`,[{no:0,name:`PTF_USER_TIMESTAMP`},{no:1,name:`PTF_FRAME_ID`},{no:2,name:`PTF_USER_DATA`}]),SO=q.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:CO,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:pk}]),CO=q.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),wO=q.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:q.getEnumType(pO),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},{no:13,name:`can_manage_agent_session`,kind:`scalar`,T:8}]),TO=q.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:q.getEnumType(EO)},{no:4,name:`tracks`,kind:`message`,T:jO,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:wO},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:q.getEnumType(DO)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:q.getEnumType(_O)},{no:18,name:`kind_details`,kind:`enum`,T:q.getEnumType(OO),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:MO,repeated:!0},{no:20,name:`client_protocol`,kind:`scalar`,T:5},{no:21,name:`capabilities`,kind:`enum`,T:q.getEnumType(lk),repeated:!0}]),EO=q.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),DO=q.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`}]),OO=q.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`},{no:5,name:`SIMULATION`}]),kO=q.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),AO=q.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:VO,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(HO)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),jO=q.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:q.getEnumType(fO)},{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:q.getEnumType(pO)},{no:10,name:`layers`,kind:`message`,T:VO,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:AO,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:q.getEnumType(kO)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:pk},{no:19,name:`audio_features`,kind:`enum`,T:q.getEnumType(bO),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(dO)},{no:21,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(xO),repeated:!0}]),MO=q.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:q.getEnumType(kO)},{no:5,name:`frame_encoding`,kind:`message`,T:NO,opt:!0},{no:6,name:`schema`,kind:`message`,T:LO,opt:!0}]),NO=q.makeMessageType(`livekit.DataTrackFrameEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(PO),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),PO=q.makeEnum(`livekit.DataTrackFrameEncoding.WellKnownFrameEncoding`,[{no:0,name:`WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED`,localName:`UNSPECIFIED`},{no:1,name:`WELL_KNOWN_FRAME_ENCODING_ROS1`,localName:`ROS1`},{no:2,name:`WELL_KNOWN_FRAME_ENCODING_CDR`,localName:`CDR`},{no:3,name:`WELL_KNOWN_FRAME_ENCODING_PROTOBUF`,localName:`PROTOBUF`},{no:4,name:`WELL_KNOWN_FRAME_ENCODING_FLATBUFFER`,localName:`FLATBUFFER`},{no:5,name:`WELL_KNOWN_FRAME_ENCODING_CBOR`,localName:`CBOR`},{no:6,name:`WELL_KNOWN_FRAME_ENCODING_MSGPACK`,localName:`MSGPACK`},{no:7,name:`WELL_KNOWN_FRAME_ENCODING_JSON`,localName:`JSON`}]),FO=q.makeMessageType(`livekit.DataTrackSchemaEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(IO),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),IO=q.makeEnum(`livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding`,[{no:0,name:`WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED`,localName:`UNSPECIFIED`},{no:1,name:`WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF`,localName:`PROTOBUF`},{no:2,name:`WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER`,localName:`FLATBUFFER`},{no:3,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG`,localName:`ROS1_MSG`},{no:4,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG`,localName:`ROS2_MSG`},{no:5,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL`,localName:`ROS2_IDL`},{no:6,name:`WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL`,localName:`OMG_IDL`},{no:7,name:`WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA`,localName:`JSON_SCHEMA`}]),LO=q.makeMessageType(`livekit.DataTrackSchemaId`,()=>[{no:1,name:`name`,kind:`scalar`,T:9},{no:2,name:`encoding`,kind:`message`,T:FO}]),RO=q.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),zO=q.makeMessageType(`livekit.DataBlobKey`,()=>[{no:1,name:`generic`,kind:`scalar`,T:9,oneof:`key`},{no:2,name:`schema_id`,kind:`message`,T:LO,oneof:`key`}]),BO=q.makeMessageType(`livekit.DataBlob`,()=>[{no:1,name:`key`,kind:`message`,T:zO},{no:2,name:`contents`,kind:`scalar`,T:12}]),VO=q.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(mO)},{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}]),HO=q.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`}]),UO=q.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:q.getEnumType(WO)},{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:YO,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:qO,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:XO,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:ZO,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:sO,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:$O,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:ek,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:tk,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:nk,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:vk,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:yk,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:bk,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:GO,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),WO=q.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),GO=q.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:q.getEnumType(kO)},{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}]),KO=q.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:YO,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:$O,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:ek,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:tk,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:nk,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:vk,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:yk,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:bk,oneof:`value`}]),qO=q.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:JO,repeated:!0}]),JO=q.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}]),YO=q.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}]),XO=q.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),ZO=q.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:QO,repeated:!0}]),QO=q.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}]),$O=q.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}]),ek=q.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},{no:6,name:`compressed_payload`,kind:`scalar`,T:12}]),tk=q.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),nk=q.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:rk,oneof:`value`},{no:4,name:`compressed_payload`,kind:`scalar`,T:12,oneof:`value`}]),rk=q.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}]),ik=q.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),ak=q.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:q.getEnumType(ok)},{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}]),ok=q.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),sk=q.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:q.getEnumType(ck)},{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},{no:12,name:`client_protocol`,kind:`scalar`,T:5},{no:13,name:`capabilities`,kind:`enum`,T:q.getEnumType(lk),repeated:!0}]),ck=q.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`}]),lk=q.makeEnum(`livekit.ClientInfo.Capability`,[{no:0,name:`CAP_UNUSED`},{no:1,name:`CAP_PACKET_TRAILER`},{no:2,name:`CAP_COMPRESSION_DEFLATE_RAW`}]),uk=q.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:dk},{no:2,name:`screen`,kind:`message`,T:dk},{no:3,name:`resume_connection`,kind:`enum`,T:q.getEnumType(gO)},{no:4,name:`disabled_codecs`,kind:`message`,T:fk},{no:5,name:`force_relay`,kind:`enum`,T:q.getEnumType(gO)}]),dk=q.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:q.getEnumType(gO)}]),fk=q.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:CO,repeated:!0},{no:2,name:`publish`,kind:`message`,T:CO,repeated:!0}]),pk=q.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),mk=q.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),hk=q.makeEnum(`livekit.DataStream.CompressionType`,[{no:0,name:`NONE`},{no:1,name:`DEFLATE_RAW`}]),gk=q.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:q.getEnumType(mk)},{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`}),_k=q.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),vk=q.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:q.getEnumType(kO)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:gk,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:_k,oneof:`content_header`},{no:11,name:`inline_content`,kind:`scalar`,T:12,opt:!0},{no:12,name:`compression`,kind:`enum`,T:q.getEnumType(hk)}],{localName:`DataStream_Header`}),yk=q.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`}),bk=q.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`}),xk=q.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Sk=q.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),Ck=q.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),wk=q.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),Tk=q.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Vk,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Vk,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:Fk,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:Ok,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:Ik,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Uk,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:Xk,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:$k,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:tA,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:hA,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:vA,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:xA,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:nA,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:SA,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Zk,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Qk,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:kk,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:jk,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Wk,oneof:`message`},{no:22,name:`store_data_blob_request`,kind:`message`,T:Kk,oneof:`message`},{no:23,name:`get_data_blob_request`,kind:`message`,T:Jk,oneof:`message`}]),Ek=q.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Lk,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Vk,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Vk,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:Fk,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Hk,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:zk,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:$k,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:Ik,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:iA,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:aA,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:sA,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:lA,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:fA,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:gA,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:Bk,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:Rk,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:CA,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:EA,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:DA,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:kA,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:_A,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:PA,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:pA,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:Ak,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:Mk,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Nk,oneof:`message`},{no:30,name:`store_data_blob_response`,kind:`message`,T:qk,oneof:`message`},{no:31,name:`get_data_blob_response`,kind:`message`,T:Yk,oneof:`message`}]),Dk=q.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:VO,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(HO)}]),Ok=q.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:q.getEnumType(fO)},{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:q.getEnumType(pO)},{no:9,name:`layers`,kind:`message`,T:VO,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:Dk,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:q.getEnumType(kO)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(dO)},{no:17,name:`audio_features`,kind:`enum`,T:q.getEnumType(bO),repeated:!0},{no:18,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(xO),repeated:!0}]),kk=q.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:q.getEnumType(kO)},{no:4,name:`frame_encoding`,kind:`message`,T:NO,opt:!0},{no:5,name:`schema`,kind:`message`,T:LO,opt:!0}]),Ak=q.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:MO}]),jk=q.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),Mk=q.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:MO}]),Nk=q.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:Pk}}]),Pk=q.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`}),Fk=q.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:q.getEnumType(Sk)},{no:3,name:`final`,kind:`scalar`,T:8}]),Ik=q.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Lk=q.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:SO},{no:2,name:`participant`,kind:`message`,T:TO},{no:3,name:`other_participants`,kind:`message`,T:TO,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:rA,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:uk},{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:ak},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:CO,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),Rk=q.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:rA,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:uk},{no:3,name:`server_info`,kind:`message`,T:ak},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),zk=q.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:jO}]),Bk=q.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Vk=q.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}}]),Hk=q.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:TO,repeated:!0}]),Uk=q.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:ik,repeated:!0}]),Wk=q.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Gk,repeated:!0}]),Gk=q.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:RO}],{localName:`UpdateDataSubscription_Update`}),Kk=q.makeMessageType(`livekit.StoreDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:BO}]),qk=q.makeMessageType(`livekit.StoreDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`key`,kind:`message`,T:zO}]),Jk=q.makeMessageType(`livekit.GetDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:9},{no:3,name:`key`,kind:`message`,T:zO}]),Yk=q.makeMessageType(`livekit.GetDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:BO}]),Xk=q.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:q.getEnumType(mO)},{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}]),Zk=q.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:q.getEnumType(bO),repeated:!0}]),Qk=q.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}]),$k=q.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(_O)},{no:3,name:`action`,kind:`enum`,T:q.getEnumType(eA)},{no:4,name:`regions`,kind:`message`,T:wA}]),eA=q.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),tA=q.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:VO,repeated:!0}]),nA=q.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}]),rA=q.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}]),iA=q.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:JO,repeated:!0}]),aA=q.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:SO}]),oA=q.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:q.getEnumType(hO)},{no:3,name:`score`,kind:`scalar`,T:2}]),sA=q.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:oA,repeated:!0}]),cA=q.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:q.getEnumType(Ck)}]),lA=q.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:cA,repeated:!0}]),uA=q.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(mO)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),dA=q.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:uA,repeated:!0}]),fA=q.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:uA,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:dA,repeated:!0}]),pA=q.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:xk,repeated:!0}]),mA=q.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}]),hA=q.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:mA,repeated:!0}]),gA=q.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}]),_A=q.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:SO},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:TO},{no:4,name:`other_participants`,kind:`message`,T:TO,repeated:!0}]),vA=q.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Vk},{no:2,name:`subscription`,kind:`message`,T:Uk},{no:3,name:`publish_tracks`,kind:`message`,T:zk,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:bA,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Vk},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:yA,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:Ak,repeated:!0}]),yA=q.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),bA=q.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:q.getEnumType(Sk)}]),xA=q.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:q.getEnumType(wk),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`}]),SA=q.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),CA=q.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),wA=q.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:TA,repeated:!0}]),TA=q.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}]),EA=q.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:q.getEnumType(yO)}]),DA=q.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(OA)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:Fk,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:Ok,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:Ik,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:nA,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Zk,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Qk,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:kk,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:jk,oneof:`request`}]),OA=q.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`},{no:11,name:`INVALID_REQUEST`}]),kA=q.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),AA=q.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}]),jA=q.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:sk},{no:2,name:`connection_settings`,kind:`message`,T:AA},{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:Ok,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Vk},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:q.getEnumType(vO)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:vA}]),MA=q.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:q.getEnumType(NA)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),NA=q.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),PA=q.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function FA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var IA={exports:{}},LA=IA.exports,RA;function zA(){return RA?IA.exports:(RA=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(LA,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(typeof window!==t&&f){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(typeof window!==t&&f){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(typeof window!==t&&f){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(IA),IA.exports)}var BA=zA(),VA;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(VA||={});var HA;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`,e.Region=`livekit-region`,e.ICE=`livekit-ice`,e.Stats=`livekit-stats`})(HA||={});var UA=BA.getLogger(HA.Default);Object.values(HA).map(e=>BA.getLogger(e)),UA.setDefaultLevel(VA.info);function WA(e,t){let n=BA.getLogger(e);return n.setDefaultLevel(UA.getLevel()),t?GA(n,t):n}function GA(e,t){let n=n=>(r,i)=>{let a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n(`trace`),r.debug=n(`debug`),r.info=n(`info`),r.warn=n(`warn`),r.error=n(`error`),r}var KA=BA.getLogger(HA.E2EE),qA=new Set,JA=KA.setLevel.bind(KA);KA.setLevel=(e,t)=>{JA(e,t);let n=KA.getLevel();qA.forEach(e=>e(n))};function YA(e){return qA.add(e),()=>{qA.delete(e)}}var XA=7e3,ZA=[0,300,1200,2700,4800,XA,XA,XA,XA,XA],QA=class{constructor(e){this._retryDelays=e===void 0?ZA:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function $A(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function J(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function ej(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function tj(e){return this instanceof tj?(this.v=e,this):new tj(e)}function nj(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof tj?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function rj(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:tj(e[r](t)),done:!1}:i?i(t):t}:i}}function ij(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ej==`function`?ej(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var aj={exports:{}},oj;function sj(){if(oj)return aj.exports;oj=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}aj.exports=a,aj.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.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},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){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 d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return aj.exports}var cj=sj(),lj=!0,uj=!0;function dj(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function fj(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,`addEventListener`).writable){hj(`Unable to polyfill events`);return}let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function pj(e){return typeof e==`boolean`?(lj=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function mj(e){return typeof e==`boolean`?(uj=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function hj(){if(typeof window==`object`){if(lj)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function gj(e,t){uj&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function _j(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e){let t=parseInt(e.version,10);if(t>=90)return{browser:`chrome`,version:t}}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(dj(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(dj(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(dj(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=dj(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function vj(e){return Object.prototype.toString.call(e)===`[object Object]`}function yj(e){return vj(e)?Object.keys(e).reduce(function(t,n){let r=vj(e[n]),i=r?yj(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function bj(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?bj(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{bj(e,e.get(t),n)})}))}function xj(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&bj(e,n,i)})}),i}var Sj=hj;function Cj(e,t){if(t.version>=64)return;let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),Sj(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return Sj(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function wj(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Tj(e,t){if(!(t.version>102)){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else fj(e,`track`,e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}}function Ej(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(this._dtmf=t.kind===`audio`?e.createDTMFSender(t):null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this._dtmf=this.track.kind===`audio`?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function Dj(e,t){if(t.version>=67||!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>xj(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),fj(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>xj(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return n.apply(this,arguments)}}function Oj(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function kj(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Oj(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))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(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function Aj(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function jj(e,t){t.version>102||fj(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var Mj=Object.freeze({__proto__:null,fixNegotiationNeeded:jj,shimAddTrackRemoveTrack:kj,shimAddTrackRemoveTrackWithNative:Oj,shimGetSendersWithDtmf:Ej,shimGetUserMedia:Cj,shimMediaStream:wj,shimOnTrack:Tj,shimPeerConnection:Aj,shimSenderReceiverGetStats:Dj});function Nj(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){gj(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function Pj(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)}))}function Fj(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ij(e,t){typeof e==`object`&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function Lj(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection)||t.version>=151)return;let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let e=Array.prototype.slice.call(arguments),i=e[0],a=e[1],o=e[2];return this.signalingState===`closed`?Promise.resolve(new Map):r.apply(this,[i||null]).then(e=>{if(t.version<53&&!a)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(a,o)}}function Rj(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function zj(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),fj(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Bj(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){gj(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Vj(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Hj(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let t=e.length>0;t&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=n.apply(this,arguments);if(t){let t=r.sender,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function Uj(e,t){if(!(typeof e==`object`&&e.RTCRtpSender)||t.version>=110)return;let n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){let e=n.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Wj(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function Gj(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}var Kj=Object.freeze({__proto__:null,shimAddTransceiver:Hj,shimCreateAnswer:Gj,shimCreateOffer:Wj,shimGetDisplayMedia:Pj,shimGetParameters:Uj,shimGetStats:Lj,shimGetUserMedia:Nj,shimOnTrack:Fj,shimPeerConnection:Ij,shimRTCDataChannel:Vj,shimReceiverGetStats:zj,shimRemoveStream:Bj,shimSenderGetStats:Rj});function qj(e){if(typeof e==`object`&&e.RTCPeerConnection){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){var n=[...arguments].slice(1);return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function Jj(e){if(typeof e==`object`&&e.RTCPeerConnection&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function Yj(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function Xj(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(Zj(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function Zj(e){return e&&e.video!==void 0?Object.assign({},e,{video:yj(e.video)}):e}function Qj(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(gj(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function $j(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function eM(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function tM(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var nM=Object.freeze({__proto__:null,shimAudioContext:tM,shimCallbacksAPI:Yj,shimConstraints:Zj,shimCreateOfferLegacy:eM,shimGetUserMedia:Xj,shimLocalStreamsAPI:qj,shimRTCIceServerUrls:Qj,shimRemoteStreamsAPI:Jj,shimTrackEventTransceiver:$j}),rM={exports:{}},iM;function aM(){return iM?rM.exports:(iM=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
62
+ `)};return this.#n=null,this.#r=[],e}if(e.startsWith(`:`))return null;let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1).replace(/^ /,``);return n===`id`?this.#t=r:n===`event`?this.#n=r:n===`data`&&this.#r.push(r),null}};function Uy(e,t,n){let r=new AbortController,i=null,a=null,o=zy,s=!0,c=()=>{i===null&&(i=window.setTimeout(()=>{i=null,n.onPaint()},100))},l=e=>{if(e.id!==null&&(a=e.id),e.data!==``){try{n.onEntry(Lv(JSON.parse(e.data)))}catch(e){n.onRefused(String(e));return}c()}};return n.onConnection(`connecting`),(async()=>{for(;s;){let i;try{i=await fetch(e,{headers:{...ra(t),accept:`text/event-stream`,...a===null?{}:{"last-event-id":a}},signal:r.signal})}catch{if(!s)return;n.onConnection(`reconnecting`),await Wy(o,r.signal),o=Math.min(o*2,By);continue}if(i.status===Vy){n.onConnection(`ended`);return}if(!i.ok||i.body===null){n.onRefused(`the stream answered ${i.status}`),n.onConnection(`ended`);return}n.onConnection(`live`),o=zy;let c=new Hy,u=new TextDecoder,d=i.body.getReader();try{for(;;){let{value:e,done:t}=await d.read();if(t)break;for(let t of c.feed(u.decode(e,{stream:!0})))l(t)}}catch{if(!s)return}if(!s)return;n.onConnection(`reconnecting`),await Wy(o,r.signal),o=Math.min(o*2,By)}})(),()=>{s=!1,i!==null&&window.clearTimeout(i),r.abort()}}function Wy(e,t){return new Promise(n=>{let r=window.setTimeout(n,e);t.addEventListener(`abort`,()=>{window.clearTimeout(r),n()},{once:!0})})}var Gy=3e3;function Ky(e=50){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(`connecting`),[o,s]=(0,D.useState)(0),[c,l]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=Wv.parse(await k(t,`/v1/sessions`,{limit:e}));n||(r(i.calls),l(null))}catch(e){n||l(String(e))}};i();let o=window.setInterval(()=>void i(),Gy),c=Uy(la(t,`/v1/events`),t,{onEntry(e){(e.type===`agent.registered`||e.type===`agent.detached`)&&s(e=>e+1),i()},onPaint:()=>void 0,onConnection:a,onRefused:l});return()=>{n=!0,window.clearInterval(o),c()}},[t,e]),{lines:n,connection:i,agentsChanged:o,error:c}}function qy(e=0){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{let e=!1;return(async()=>{try{let n=$v.parse(await k(t,`/v1/agents`));e||(r(n.agents),a(null))}catch(t){e||a(String(t))}finally{e||s(!0)}})(),()=>{e=!0}},[t,e]),{agents:n,error:i,loaded:o}}var Jy=200,Yy=(0,D.createContext)(null);function Xy({children:e}){let t=j(),n=wh(),r=Ky(Jy),i=ug(),a=dg(),o=qy(r.agentsChanged),[s,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=!1;return Gp(t).then(t=>{e||c(t)},()=>{e||c(null)}),()=>{e=!0}},[t]);let l=Gh(n),u=(0,D.useMemo)(()=>({lines:r.lines,live:r.lines.filter(e=>e.live),connection:r.connection,floorError:r.error,held:o.agents,agents:Uh(o.agents,l),agentsLoaded:o.loaded,agentsError:o.error,orgs:s,here:s?.find(e=>e.here)??null,insights:i,operator:a}),[r.lines,r.connection,r.error,o.agents,o.loaded,o.error,s,l,i,a]);return(0,A.jsx)(Yy,{value:u,children:e})}function Zy(){let e=(0,D.useContext)(Yy);if(e===null)throw Error(`a screen was mounted outside the shell's org`);return e}var Qy={talk:`talk`,chat:`talk`,devchat:`talk`,calls:`calls`,sessions:`calls`,pipeline:`pipeline`,settings:`words`,lexicon:`words`,docs:`knowledge`,memory:`memory`,evals:`evals`,widget:`talk`,agents:`calls`,live:`calls`,"org-evals":`evals`,"org-memory":`memory`,"org-docs":`knowledge`,numbers:`numbers`,providers:`providers`,team:`team`,usage:`usage`};function $y(e,t){let n=Qy[t];return n===void 0||e.includes(n)}var eb=[`app`,`calls`,`evals`,`keys`,`knowledge`,`memory`,`numbers`,`pipeline`,`providers`,`supervise`,`talk`,`team`,`usage`,`words`];function tb(e){let t=eb.filter(t=>!e.includes(t));return t.length===0||t.length===1&&t[0]===`app`?`everything`:e.join(`, `)}var nb=z({fingerprint:P(),label:P().nullable(),kind:mp([`person`,`server`]),env:mp([`production`,`sandbox`]).nullable(),name:P().nullable(),created_by:P().nullable(),created_at:P(),last_used_at:P().nullable(),revoked_at:P().nullable(),scopes:R(P())}),rb=z({key:P(),key_id:P(),label:P().nullable(),env:P(),scopes:R(P())});async function ib(e){return R(nb).parse(await k(e,`/v1/keys`))}async function ab(e,t){return rb.parse(await sa(e,`/v1/keys`,t))}async function ob(e,t){await sa(e,`/v1/keys/${encodeURIComponent(t)}/revoke`,{})}async function sb(e){return ey.parse(await k(e,`/v1/apps`)).apps}async function cb(e,t){ty.parse(await sa(e,`/v1/apps/${encodeURIComponent(t)}/stop`,{}))}function lb({held:e,stops:t}){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=!1;return sb(n).then(t=>{e||i(t)},t=>{e||o(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[n,e]);let s=async e=>{o(null);try{await cb(n,e),i(await sb(n))}catch(e){o(e instanceof na?e.message:String(e))}};return r===null&&a===null?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Processes`,meta:`the machines holding these agents — a stop closes one, and it exits instead of dialling back`}),(0,A.jsx)(Nm,{children:a}),(0,A.jsxs)(`div`,{className:`ui-card-list`,children:[r?.length===0&&(0,A.jsx)(`div`,{className:`agents-none`,children:`No process is connected.`}),r?.map(e=>(0,A.jsx)(ub,{app:e,stop:t?s:void 0},e.app))]})]})}function ub({app:e,stop:t}){let[n,r]=(0,D.useState)(!1),i=e.holder===null?`the org's`:e.holder.name??e.holder.holder??``,a=`${e.host??`an unnamed host`}${e.address===null?``:` (${e.address})`}`;return(0,A.jsx)(`div`,{onMouseLeave:()=>r(!1),children:(0,A.jsx)(Fm,{name:e.agents.join(`, `)||e.app,sub:`${a} · ${e.sdk??`an unknown sdk`} · ${i} · connected ${eg(e.connected_at)}`,end:t!==void 0&&(0,A.jsx)(Bm,{danger:!0,onClick:()=>n?void t(e.app):r(!0),children:n?`Stop it`:`Stop`})})})}var db=z({route:z({org:P(),agent:P(),channel:mp([`phone`,`web`,`whatsapp`]),number:P().nullable(),label:P().nullable(),env:mp([`production`,`sandbox`]),managed:L().default(!1)}),source:mp([`operator`,`app`])}),fb=z({kind:mp([`twilio`,`sip`]),account:P()}),pb=z({kind:mp([`twilio`,`sip`]),numbers:R(z({number:P(),name:P(),imported:L()}))}),mb=z({route:db.shape.route,steps:R(P()),dry_run:L()});async function hb(e){return R(db).parse(await k(e,`/v1/numbers`))}async function gb(e){try{return fb.parse(await k(e,`/v1/carrier`))}catch(e){if(kb(e,404))return null;throw e}}async function _b(e,t){await oa(e,`/v1/carrier`,t)}async function vb(e){await ca(e,`/v1/carrier`)}async function yb(e){return pb.parse(await k(e,`/v1/numbers/available`))}async function bb(e,t,n){return mb.parse(await sa(e,`/v1/numbers${n?`?dry_run=true`:``}`,t))}async function xb(e,t,n){return mb.parse(await sa(e,`/v1/numbers/buy${n?`?dry_run=true`:``}`,t))}async function Sb(e,t){await ca(e,`/v1/numbers/${encodeURIComponent(t)}`)}var Cb=np({ready:L(),kind:P().nullish(),from_numbers:R(P()),steps_missing:R(P()),guards:np({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()})}),wb=np({steps:R(P()),dry_run:L(),ready:L()});async function Tb(e){try{return Cb.parse(await k(e,`/v1/carrier/outbound`))}catch(e){if(kb(e,404)||kb(e,405)||kb(e,403))return null;throw e}}async function Eb(e,t){return wb.parse(await sa(e,`/v1/carrier/outbound${t?`?dry_run=true`:``}`,{}))}var Db=np({call:P()});async function Ob(e,t,n,r){let i=r===void 0||r===``?{to:n}:{to:n,from:r};return Db.parse(await sa(e,`/v1/agents/${encodeURIComponent(t)}/dial`,i)).call}function kb(e,t){return typeof e==`object`&&!!e&&e.status===t}var Ab=z({vendors:R(P())});async function jb(e){return Ab.parse(await k(e,`/v1/provider-keys`)).vendors}async function Mb(e,t,n){await oa(e,`/v1/provider-keys/${encodeURIComponent(t)}`,{key:n})}async function Nb(e,t){await ca(e,`/v1/provider-keys/${encodeURIComponent(t)}`)}var Pb=`minmax(0,1.5fr) minmax(0,1.3fr) minmax(0,1.1fr) 90px 90px`;function Fb(){let e=j(),t=Eh(),[n,r]=(0,D.useState)({numbers:null,free:null,keys:null,catalogue:null,brought:[]}),i=e=>Sm(vm,e)&&t!==null&&$y(t,e),a=i(`numbers`),o=Sm(vm,`tokens`),s=i(`providers`);return(0,D.useEffect)(()=>{let t=!1;return(async()=>{let[n,i,c,l,u]=await Promise.all([a?hb(e).catch(()=>null):Promise.resolve(null),a?yb(e).catch(()=>null):Promise.resolve(null),o?ib(e).catch(()=>null):Promise.resolve(null),s?Lh(e).catch(()=>null):Promise.resolve(null),s?jb(e).catch(()=>[]):Promise.resolve([])]);t||r({numbers:n,free:i===null?null:i.numbers.filter(e=>!e.imported).length,keys:c,catalogue:l,brought:u})})(),()=>{t=!0}},[e,a,o,s]),n}function Ib(){let{held:e,agents:t,live:n,lines:r,connection:i,agentsError:a,agentsLoaded:o,insights:s}=Zy(),c=Gh(wh()),l=Eh(),u=Fb(),[d,f]=(0,D.useState)(`everything`),p=rg(r,ng().today),m=e.some(e=>Vh(e,c)),h=m?Hh(e,d,c):t,g=new Set((u.numbers??[]).map(e=>e.route.agent)),_=new Set([...t.map(e=>e.slug),...g]),v=e=>(u.numbers??[]).filter(t=>t.route.agent===e&&t.route.number!==null).map(e=>og(e.route.number)),y=u.keys?.filter(e=>e.revoked_at===null)??[],b=u.catalogue?.providers.filter(e=>e.standing===`ready`)??[],x=fm===`hosted`&&l!==null&&l.includes(`app`);return(0,A.jsxs)(sh,{children:[(0,A.jsx)(ch,{title:`Overview`,lede:`Which agents this gateway is holding right now — the list changes the moment a socket connects.`,actions:x?(0,A.jsx)(zm,{to:`/tokens`,size:`base`,children:`New server token`}):void 0}),(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{label:`Agents up`,value:t.length,of:`of ${_.size}`}),u.numbers===null?(0,A.jsx)(uh,{label:`Calls live`,value:n.length}):(0,A.jsx)(uh,{label:`Numbers ringing`,value:u.numbers.filter(e=>e.route.number!==null).length,of:u.free===null?void 0:`· ${u.free} free`}),u.keys===null?(0,A.jsx)(uh,{label:`Calls today`,value:p.length}):(0,A.jsx)(uh,{label:`Active tokens`,value:y.length,of:`· ${u.keys.length-y.length} revoked`}),u.catalogue!==null&&(0,A.jsx)(uh,{label:`Providers ready`,value:b.length,of:`of ${u.catalogue.providers.length}`})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Agents`,meta:`the list changes the moment a socket connects`,action:(0,A.jsxs)(`span`,{className:`agents-watching`,children:[(0,A.jsx)(eh,{tone:i===`live`?`green`:void 0,small:!0}),i===`live`?`watching`:i]}),children:m&&(0,A.jsx)(`div`,{className:`agents-corners`,children:(0,A.jsx)(Km,{options:Bh.map(e=>({value:e,label:e})),value:d,onChange:f})})}),(0,A.jsx)(Nm,{children:a}),o&&h.length===0&&(0,A.jsx)(Mm,{children:d===`everything`?fm===`local`?(0,A.jsxs)(A.Fragment,{children:[`Nothing of yours is running. `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in a project puts its agents here.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing is running in production: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start --prod`}),` on your server holds it, on a server token.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing here is `,d,`.`]})}),h.length>0&&(0,A.jsx)(dh,{columns:Pb,padding:`9px 16px`,labels:[`Agent`,`Doors`,`Numbers`,`Today>`,`Score>`]}),h.map((e,t)=>{let i=n.filter(t=>t.agent===e.slug).length,a=r.find(t=>t.agent===e.slug),o=v(e.slug);return(0,A.jsxs)(fh,{columns:Pb,padding:`13px 16px`,to:`/a/${e.slug}/talk`,children:[(0,A.jsxs)(`div`,{className:`agents-name`,children:[(0,A.jsx)(ah,{name:e.slug,letters:e.slug.slice(0,1).toUpperCase(),tint:nh(t)}),(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`ui-cell-strong ui-clip`,children:e.slug}),i>0?(0,A.jsxs)(`div`,{className:`agents-live`,children:[(0,A.jsx)(eh,{tone:`green`,small:!0}),i===1?`1 call live`:`${i} calls live`]}):(0,A.jsxs)(`div`,{className:`agents-idle`,children:[m?`${Wh(e)} · `:``,`idle`,a===void 0?``:` · last call ${eg(a.started_at)}`]})]})]}),(0,A.jsx)(`div`,{className:`ui-tags`,children:e.channels.map(e=>(0,A.jsx)($m,{children:e},e))}),(0,A.jsx)(`span`,{className:`agents-numbers ui-clip`,children:o.length===0?`—`:o.join(`, `)}),(0,A.jsx)(`span`,{className:`agents-figure`,children:s?.agents.find(t=>t.slug===e.slug)?.today??p.filter(t=>t.agent===e.slug).length}),(0,A.jsx)(zb,{share:s?.agents.find(t=>t.slug===e.slug)?.score??null})]},`${e.slug}/${e.holder?.holder??``}`)}),h.length>0&&(0,A.jsx)(jm,{children:(0,A.jsx)(`span`,{children:h.length>1?`Every agent writes the same log — open one to read its turns.`:`Open the agent to read its turns.`})})]}),(0,A.jsx)(lb,{held:e,stops:l!==null&&l.includes(`app`)}),(u.keys!==null||u.catalogue!==null)&&(0,A.jsxs)(`div`,{className:`agents-split`,children:[u.keys!==null&&(0,A.jsx)(Lb,{tokens:u.keys}),u.catalogue!==null&&(0,A.jsx)(Rb,{catalogue:u.catalogue,brought:u.brought})]})]})}function Lb({tokens:e}){let t=[...e].sort((e,t)=>Number(e.revoked_at!==null)-Number(t.revoked_at!==null)).slice(0,4);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Tokens in use`,action:(0,A.jsx)(Am,{to:`/tokens`,children:`Manage`})}),(0,A.jsxs)(`div`,{className:`ui-card-list`,children:[t.length===0&&(0,A.jsx)(`div`,{className:`agents-none`,children:`No token has been made yet.`}),t.map(e=>(0,A.jsx)(Fm,{name:e.label??e.fingerprint,sub:e.kind===`person`?`${e.name??`a person`} · their own`:`the org's · ${e.env??``}${e.created_by===null?``:` · made by ${e.created_by}`}`,end:e.revoked_at===null?(0,A.jsx)(Qm,{tone:`green`,children:`active`}):(0,A.jsx)(Qm,{tone:`muted`,children:`revoked`})},e.fingerprint))]})]})}function Rb({catalogue:e,brought:t}){let n=e.providers.filter(e=>e.standing===Ah),r=new Set(Object.values(e.defaults).map(e=>e.split(`/`)[0]??e)),i=[...n].sort((e,n)=>Number(t.includes(n.name))-Number(t.includes(e.name))||Number(r.has(n.name))-Number(r.has(e.name))||e.name.localeCompare(n.name));return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Providers`,meta:`${n.length} ready · ${e.providers.length-n.length} need a key`,action:(0,A.jsx)(Am,{to:`/providers`,children:`Bring one`})}),(0,A.jsx)(`div`,{className:`ui-card-list`,children:i.slice(0,4).map(n=>(0,A.jsx)(Fm,{name:n.name.charAt(0).toUpperCase()+n.name.slice(1),sub:Vb(n,e),end:t.includes(n.name)?(0,A.jsx)(Qm,{tone:`green`,children:`ready`}):(0,A.jsx)(Qm,{tone:`amber`,children:`box key`})},n.name))})]})}function zb({share:e}){return e===null?(0,A.jsx)(`span`,{className:`agents-figure agents-score`,children:`—`}):(0,A.jsxs)(`span`,{className:`agents-figure ${e>=.9?`agents-score-good`:e>=.7?`agents-score-fair`:`agents-score-poor`}`,children:[Math.round(e*100),`%`]})}var Bb={llm:`decides`,stt:`hears`,tts:`speaks`};function Vb(e,t){let n=e.does.filter(n=>(t.defaults[n]??``).split(`/`)[0]===e.name);return n.length>0?`${n.map(e=>Bb[e]).join(`, `)} · the default`:`${e.does.map(e=>Bb[e]).join(`, `)} · ${e.note}`}var Hb=`/v1/ops`,Ub=np({worker:P(),active:F(),max_jobs:F().nullish(),load:F(),draining:L(),cordoned:L(),seen_at:F()}),Wb=np({now:F(),stale_after_s:F(),workers:R(Ub)}),Gb=np({route:np({agent:P(),channel:P(),number:P().nullish(),env:P(),managed:L().nullish()}),source:P()}),Kb=np({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),cost_eur:F()}),qb=np({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F()}),Jb=np({rows:R(Kb),totals:fp(P(),qb),next:F().nullish()});async function Yb(e){return Wb.parse(await k(e,`${Hb}/fleet`))}async function Xb(e,t,n){let r=`${Hb}/fleet/${encodeURIComponent(t)}/cordon`;await(n?sa(e,r,{}):ca(e,r))}async function Zb(e,t,n){return R(Gb).parse(await k(e,`${Hb}/routes`,{org:t,env:n}))}async function Qb(e,t){return np({overrides:P().nullish()}).parse(await sa(e,`${Hb}/routes`,t)).overrides??null}async function $b(e,t,n){await ca(e,`${Hb}/routes/${encodeURIComponent(n)}?org=${encodeURIComponent(t)}`)}async function ex(e,t,n){return Jb.parse(await k(e,`${Hb}/usage`,{after:t,limit:n}))}function tx(e){let[t,n]=(0,D.useState)(void 0),[r,i]=(0,D.useState)(null),a=(0,D.useCallback)(async()=>{try{n(await e()),i(null)}catch(e){i(nx(e))}},[e]);return(0,D.useEffect)(()=>{let t=!1;return e().then(e=>{t||n(e)},e=>{t||i(nx(e))}),()=>{t=!0}},[e]),{value:t,refused:r,reread:a}}function nx(e){return e instanceof na||e instanceof Error?e.message:String(e)}function rx(){let[e,t]=(0,D.useState)(!1),[n,r]=(0,D.useState)(null);return{busy:e,refused:n,move:(0,D.useCallback)(async e=>{t(!0),r(null);try{return await e(),!0}catch(e){return r(nx(e)),!1}finally{t(!1)}},[])}}var ix=5e3,ax=`minmax(0,1.4fr) 150px 130px 120px 90px`;function ox(){let e=j(),t=tx((0,D.useCallback)(()=>Yb(e),[e])),n=rx(),{reread:r}=t;(0,D.useEffect)(()=>{let e=window.setInterval(()=>void r(),ix);return()=>window.clearInterval(e)},[r]);let i=t.value,a=e=>i!==void 0&&i.now-e.seen_at>i.stale_after_s,o=(i?.workers??[]).filter(e=>!a(e)&&!e.cordoned&&!e.draining),s=(i?.workers??[]).reduce((e,t)=>e+t.active,0),c=(i?.workers??[]).reduce((e,t)=>e+(a(t)?0:t.max_jobs??0),0);return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Fleet`,lede:`Every worker the hub has heard from. A cordoned worker finishes its calls and is handed no new one — the move before a deploy, and it ends nothing.`}),(0,A.jsx)(Nm,{children:t.refused??n.refused}),i!==void 0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{size:`small`,label:`Workers taking calls`,value:o.length,of:`of ${i.workers.length}`}),(0,A.jsx)(uh,{size:`small`,label:`Calls right now`,value:s,of:c>0?`of ${c} seats`:void 0}),(0,A.jsx)(uh,{size:`small`,label:`Cordoned`,value:i.workers.filter(e=>e.cordoned).length})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Workers`,meta:`re-read every ${ix/1e3} s`}),i.workers.length===0?(0,A.jsx)(Mm,{children:`No worker has reported. A hub with none answers every call on itself.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:ax,labels:[`Worker`,`Calls`,`Load`,`Standing`,``]}),i.workers.map(t=>{let[i,o]=sx(t,a(t));return(0,A.jsxs)(fh,{columns:ax,children:[(0,A.jsx)(`span`,{className:a(t)?`ui-cell-faint box-fixed ui-clip`:`ui-cell-strong box-fixed ui-clip`,children:t.worker}),(0,A.jsxs)(`span`,{className:`ui-cell-ink`,children:[t.active,t.max_jobs===null||t.max_jobs===void 0?``:` / ${t.max_jobs}`]}),(0,A.jsxs)(`span`,{className:`box-load`,children:[(0,A.jsx)(oh,{share:Math.min(1,t.load)}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:t.load.toFixed(2)})]}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:o,children:i})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{disabled:n.busy,onClick:()=>void n.move(async()=>{await Xb(e,t.worker,!t.cordoned),await r()}),children:t.cordoned?`Uncordon`:`Cordon`})})]},t.worker)})]})]})]})]})}function sx(e,t){return t?[`not heard from`,`gray`]:e.draining?[`draining`,`amber`]:e.cordoned?[`cordoned`,`amber`]:[`taking calls`,`green`]}var cx=`/v1/ops`,lx=e=>`${cx}/orgs/${encodeURIComponent(e)}`,ux=[`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`,`budget_eur`],dx=F().nullish(),fx=np({id:P(),slug:P(),name:P()}),px=np({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()}),mx=fx.extend({quotas:np({minutes:dx,messages:dx,agents:dx,concurrent_calls:dx,memory_facts:dx,knowledge_chunks:dx,numbers:dx,seats:dx,budget_eur:dx}),dialling:px.nullish(),holding:np({memory_facts:F(),knowledge_chunks:F(),numbers:F(),seats:F()})}),hx=np({fingerprint:P(),label:P().nullish(),created_at:P(),revoked_at:P().nullish(),env:P(),scopes:R(P()),subject:P().nullish(),name:P().nullish()}),gx=np({key:P(),key_id:P(),label:P().nullish(),env:P(),scopes:R(P())}),_x=np({id:P(),email:P(),name:P(),role:P(),agents:R(P()),status:P(),operator:L().nullish()}),vx=np({member:_x,token:P().nullish(),expires_at:P().nullish(),mailed:L().nullish()}),yx=np({configured:L(),issuer:P().nullish(),domains:R(P()).nullish(),required:L()});async function bx(e){return R(fx).parse(await k(e,`${cx}/orgs`))}async function xx(e,t){return mx.parse(await k(e,lx(t)))}async function Sx(e,t,n){return fx.parse(await sa(e,`${cx}/orgs`,{slug:t,name:n||null}))}async function Cx(e,t){await ca(e,lx(t))}async function wx(e,t,n){await oa(e,`${lx(t)}/quotas`,n)}async function Tx(e,t,n){await oa(e,`${lx(t)}/dialling`,n)}async function Ex(e,t,n){return np({logs:F(),numbers:R(P())}).parse(await oa(e,`${lx(t)}/agents`,{agent:n}))}async function Dx(e,t){return R(hx).parse(await k(e,`${lx(t)}/keys`))}async function Ox(e,t,n){return gx.parse(await sa(e,`${lx(t)}/keys`,n))}async function kx(e,t){await sa(e,`${cx}/keys/${encodeURIComponent(t)}/revoke`,{})}async function Ax(e,t){return np({members:R(_x),seated:F()}).parse(await k(e,`${lx(t)}/members`))}async function jx(e,t,n){return vx.parse(await sa(e,`${lx(t)}/members`,n))}async function Mx(e,t,n,r){await oa(e,`${lx(t)}/members/${encodeURIComponent(n)}/operator`,{operator:r})}async function Nx(e,t,n){await ca(e,`${lx(t)}/members/${encodeURIComponent(n)}`)}async function Px(e,t){return np({vendors:R(P())}).parse(await k(e,`${lx(t)}/provider-keys`)).vendors}async function Fx(e,t,n,r){await oa(e,`${lx(t)}/provider-keys/${encodeURIComponent(n)}`,{key:r})}async function Ix(e,t,n){await ca(e,`${lx(t)}/provider-keys/${encodeURIComponent(n)}`)}async function Lx(e,t){try{return yx.parse(await k(e,`${lx(t)}/sso`))}catch{return null}}async function Rx(e,t,n){await oa(e,`${lx(t)}/sso/required`,{required:n})}var zx=`minmax(0,1fr) 96px 140px minmax(0,1.3fr) 92px`,Bx=[{name:`app — what a deployed agent runs on`,scopes:[`app`]},{name:`everything — the org's own machine key`,scopes:null}];function Vx({named:e}){let t=j(),n=tx((0,D.useCallback)(()=>Dx(t,e),[t,e])),r=rx(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(`production`),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(null),[m,h]=(0,D.useState)(!1),g=async i=>{i.preventDefault(),await r.move(async()=>{p(await Ox(t,e,{label:o.trim(),env:c,scopes:Bx[u]?.scopes??null})),h(!1),await n.reread()})&&(s(``),a(!1))},_=(n.value??[]).filter(e=>e.revoked_at===null||e.revoked_at===void 0).length;return(0,A.jsxs)(A.Fragment,{children:[f!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The key for ${f.label??`this machine`}`,meta:`copy it now: the table keeps its sha256, and it is never shown again`,children:(0,A.jsxs)(`span`,{className:`box-head-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(f.key).then(()=>h(!0)),children:m?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>p(null),children:`Done`})]})}),(0,A.jsx)(`pre`,{className:`ui-code`,children:f.key})]}),(0,A.jsx)(Nm,{children:n.refused??r.refused}),n.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Keys`,meta:`${_} live`,action:i?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>a(!0),children:`Issue a key`})}),i&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void g(e),children:[(0,A.jsx)(Wm,{label:`What it is for`,grow:!0,minWidth:200,children:(0,A.jsx)(W,{value:o,placeholder:`prod server`,onChange:e=>s(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`World`,minWidth:130,children:(0,A.jsxs)(Hm,{value:c,onChange:e=>l(e.target.value),children:[(0,A.jsx)(`option`,{value:`production`,children:`production`}),(0,A.jsx)(`option`,{value:`sandbox`,children:`sandbox`})]})}),(0,A.jsx)(Wm,{label:`Opens`,minWidth:260,children:(0,A.jsx)(Hm,{value:String(u),onChange:e=>d(Number(e.target.value)),children:Bx.map((e,t)=>(0,A.jsx)(`option`,{value:t,children:e.name},e.name))})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:r.busy||o.trim()===``,children:r.busy?`Issuing…`:`Issue`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`A machine's key names nobody: people get theirs by signing in.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>a(!1),children:`Close`})})]})]}),n.value.length===0?(0,A.jsx)(Mm,{children:`No key issued to this org yet.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:zx,labels:[`Key`,`World`,`Whose`,`Opens`,``]}),n.value.map(e=>{let i=e.revoked_at!==null&&e.revoked_at!==void 0;return(0,A.jsxs)(fh,{columns:zx,children:[(0,A.jsx)(`span`,{className:i?`ui-cell-faint ui-clip`:`ui-cell-strong ui-clip`,title:e.fingerprint,children:e.label??e.fingerprint.slice(0,12)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:e.env===`production`?`green`:`indigo`,children:e.env})}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.name??`a machine`}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip`,title:e.scopes.join(`, `),children:tb(e.scopes)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:i?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`revoked`}):(0,A.jsx)(Bm,{danger:!0,disabled:r.busy,onClick:()=>void r.move(async()=>{await kx(t,e.fingerprint),await n.reread()}),children:`Revoke`})})]},e.fingerprint)})]})]})]})}var Hx={minutes:{name:`Minutes`,about:`of call, ever`},messages:{name:`Messages`,about:`written turns, ever`},agents:{name:`Agents`,about:`slugs held at once`},concurrent_calls:{name:`Concurrent calls`,about:`calls at once`},memory_facts:{name:`Memory facts`,about:`facts kept`},knowledge_chunks:{name:`Knowledge chunks`,about:`chunks kept`},numbers:{name:`Numbers`,about:`numbers this box bought`},seats:{name:`Seats`,about:`people invited or active`},budget_eur:{name:`Budget, €`,about:`a month's spend`}},Ux={memory_facts:`memory_facts`,knowledge_chunks:`knowledge_chunks`,numbers:`numbers`,seats:`seats`},Wx=e=>e.replace(/[^0-9]/g,``);function Gx({org:e,onSaved:t}){let n=j(),r=rx(),i=rx(),[a,o]=(0,D.useState)(()=>Object.fromEntries(ux.map(t=>[t,e.quotas[t]===null||e.quotas[t]===void 0?``:String(e.quotas[t])]))),[s,c]=(0,D.useState)(null),l=e.dialling??null,[u,d]=(0,D.useState)(l?.dial_anywhere??!1),[f,p]=(0,D.useState)(String(l?.per_minute??``)),[m,h]=(0,D.useState)(String(l?.per_day??``)),[g,_]=(0,D.useState)(String(l?.max_duration_s??``)),v=async()=>{c(null),await r.move(async()=>{await wx(n,e.slug,Object.fromEntries(ux.map(e=>[e,a[e]===``?null:Number(a[e])]))),await t()})&&c(`quotas`)},y=async()=>{c(null),await i.move(async()=>{await Tx(n,e.slug,{dial_anywhere:u,per_minute:Number(f),per_day:Number(m),max_duration_s:Number(g)}),await t()})&&c(`dialling`)};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Quotas`,meta:`empty is no limit · 0 refuses everything`}),(0,A.jsx)(`div`,{className:`box-limits`,children:ux.map(t=>(0,A.jsxs)(Wm,{label:Hx[t].name,children:[(0,A.jsx)(W,{inputMode:`numeric`,value:a[t]??``,placeholder:`no limit`,onChange:e=>o({...a,[t]:Wx(e.target.value)})}),(0,A.jsxs)(`div`,{className:`box-limit-about`,children:[Hx[t].about,Ux[t]!==void 0&&` · holding ${e.holding[Ux[t]]}`]})]},t))}),(0,A.jsxs)(`div`,{className:`box-save`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:r.busy,onClick:()=>void v(),children:r.busy?`Saving…`:`Save the quotas`}),s===`quotas`&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. They bite the next call and the next register.`})]}),(0,A.jsx)(Nm,{children:r.refused})]}),l!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Outbound calls`,meta:`the fence around the calls this org's agents place`}),(0,A.jsxs)(`div`,{className:`box-anywhere`,children:[(0,A.jsxs)(`span`,{className:`box-anywhere-words`,children:[(0,A.jsx)(`strong`,{children:`Call anybody`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Off, an agent only calls numbers that already called or wrote to this org — "call back" means back.`})]}),(0,A.jsx)(Jm,{on:u,onChange:d,label:`Call anybody`})]}),(0,A.jsxs)(`div`,{className:`box-limits`,children:[(0,A.jsx)(Wm,{label:`Calls a minute`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:f,onChange:e=>p(Wx(e.target.value))})}),(0,A.jsx)(Wm,{label:`Calls a day`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:m,onChange:e=>h(Wx(e.target.value))})}),(0,A.jsx)(Wm,{label:`Longest call, seconds`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:g,onChange:e=>_(Wx(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`box-save`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:i.busy,onClick:()=>void y(),children:i.busy?`Saving…`:`Save the guards`}),s===`dialling`&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. They bite the next dial.`})]}),(0,A.jsx)(Nm,{children:i.refused})]})]})}var Kx=[`admin`,`manager`,`developer`,`supervisor`,`qa`],qx=`minmax(0,1fr) minmax(0,1.3fr) 100px 90px 220px`,Jx={active:`green`,invited:`amber`,disabled:`gray`};function Yx({named:e,seats:t}){let n=j(),r=tx((0,D.useCallback)(()=>Ax(n,e),[n,e])),i=rx(),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(`admin`),[h,g]=(0,D.useState)(null),_=async t=>{t.preventDefault(),await i.move(async()=>{c(await jx(n,e,{email:l.trim(),name:d.trim(),role:p,agents:[]})),await r.reread()})&&(u(``),f(``),o(!1))},v=e=>void i.move(async()=>{await e(),await r.reread()});return(0,A.jsxs)(A.Fragment,{children:[s!==null&&(0,A.jsx)(Xx,{invited:s,onClose:()=>c(null)}),(0,A.jsx)(Nm,{children:r.refused??i.refused}),r.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Members`,meta:`${r.value.seated} seated${t===null?``:` of ${t}`}`,action:a?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>o(!0),children:`Invite someone`})}),a&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void _(e),children:[(0,A.jsx)(Wm,{label:`Email`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{type:`email`,value:l,placeholder:`name@company.com`,onChange:e=>u(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Name`,grow:!0,minWidth:150,children:(0,A.jsx)(W,{value:d,placeholder:`Full name`,onChange:e=>f(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Role`,minWidth:130,children:(0,A.jsx)(Hm,{value:p,onChange:e=>m(e.target.value),children:Kx.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:i.busy,children:i.busy?`Inviting…`:`Invite`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`The box's invitation takes no seat: it is how an org gets its first admin.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>o(!1),children:`Close`})})]})]}),r.value.members.length===0?(0,A.jsx)(Mm,{children:`Nobody has been invited to this org.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:qx,labels:[`Name`,`Email`,`Role`,`Status`,``]}),r.value.members.map(t=>(0,A.jsxs)(fh,{columns:qx,children:[(0,A.jsxs)(`span`,{className:`ui-cell-strong box-line`,children:[t.name,t.operator===!0&&(0,A.jsx)(Qm,{tone:`violet`,small:!0,children:`operator`})]}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:t.email}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:t.role}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:Jx[t.status]??`gray`,children:t.status})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:h===t.id?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Bm,{danger:!0,disabled:i.busy,onClick:()=>v(()=>Nx(n,e,t.id).finally(()=>g(null))),children:`Remove for good`}),(0,A.jsx)(Bm,{onClick:()=>g(null),children:`Cancel`})]}):(0,A.jsxs)(A.Fragment,{children:[t.status===`active`&&(0,A.jsx)(Bm,{disabled:i.busy,onClick:()=>v(()=>Mx(n,e,t.id,t.operator!==!0)),children:t.operator===!0?`Stop running the box`:`Make operator`}),(0,A.jsx)(Bm,{danger:!0,onClick:()=>g(t.id),children:`Remove`})]})})]},t.id))]}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`Roles and agents are the org's own to change, from its Team screen. An operator's own key opens this box's doors as well as their org's.`})]})]})}function Xx({invited:e,onClose:t}){let[n,r]=(0,D.useState)(!1),i=e.token??null,a=i===null?null:`${window.location.origin}/invitations/${encodeURIComponent(i)}`;return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`${e.member.name} is invited`,meta:e.mailed===!0?`the link was mailed to them too`:a===null?`they already have a password here: nothing to send`:`copy it now: it is never shown again`,children:(0,A.jsxs)(`span`,{className:`box-head-moves`,children:[a!==null&&(0,A.jsx)(U,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(a).then(()=>r(!0)),children:n?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:t,children:`Done`})]})}),a!==null&&(0,A.jsx)(`pre`,{className:`ui-code`,children:a})]})}function Zx({org:e}){let t=j(),n=vr(),r=tx((0,D.useCallback)(()=>Lx(t,e.slug),[t,e.slug])),i=rx(),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),d=async n=>{n.preventDefault(),c(null),await i.move(async()=>{let n=await Ex(t,e.slug,a.trim());c(`${a.trim()} is ${e.slug}'s now: ${n.logs} ${n.logs===1?`log`:`logs`}${n.numbers.length>0?`, and ${n.numbers.join(`, `)}`:``}.`),o(``)})},f=e=>e==null?void 0:`of ${e}`;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{size:`small`,label:`Seats`,value:e.holding.seats,of:f(e.quotas.seats)}),(0,A.jsx)(uh,{size:`small`,label:`Numbers bought`,value:e.holding.numbers,of:f(e.quotas.numbers)}),(0,A.jsx)(uh,{size:`small`,label:`Memory facts`,value:e.holding.memory_facts,of:f(e.quotas.memory_facts)}),(0,A.jsx)(uh,{size:`small`,label:`Knowledge chunks`,value:e.holding.knowledge_chunks,of:f(e.quotas.knowledge_chunks)})]}),(0,A.jsx)(Nm,{children:i.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Sign-in`,meta:`how this org's people prove who they are`}),(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsx)(Lm,{label:`Provider`,keyWidth:120,children:r.value?.configured?r.value.issuer??`its own identity provider`:`passwords — no identity provider wired`}),r.value?.configured&&(0,A.jsx)(Lm,{label:`Passwords`,keyWidth:120,children:r.value.required?(0,A.jsxs)(`span`,{className:`box-line`,children:[(0,A.jsx)(Qm,{tone:`amber`,children:`stopped`}),(0,A.jsx)(Bm,{disabled:i.busy,onClick:()=>void i.move(async()=>{await Rx(t,e.slug,!1),await r.reread()}),children:`Let passwords work again`})]}):`still work`})]}),r.value?.configured&&r.value.required&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`The break-glass: the day their provider stops answering, the admin who would turn this off is the one locked out.`})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Bring an agent here`,meta:`one that registered in the wrong org, with every call it took and its numbers`}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void d(e),children:[(0,A.jsx)(Wm,{label:`Agent slug`,grow:!0,minWidth:220,children:(0,A.jsx)(W,{value:a,placeholder:`clinica-norte`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(U,{size:`form`,type:`submit`,disabled:i.busy||a.trim()===``,children:`Move it here`})]}),s!==null&&(0,A.jsx)(`div`,{className:`box-done box-done-under`,children:s}),(0,A.jsx)(`div`,{className:`ui-note box-note`,children:`The agent must be stopped first: a slug somebody is holding is refused.`})]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Remove this organization`,meta:`refused while a live key or a route still names it`}),(0,A.jsx)(`div`,{className:`ui-card-body box-line`,children:l?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`span`,{className:`ui-note`,children:[`Forget `,e.slug,` for good?`]}),(0,A.jsx)(U,{kind:`danger`,size:`sm`,disabled:i.busy,onClick:()=>void i.move(async()=>{await Cx(t,e.slug),n(`/box/orgs`)}),children:`Yes, remove it`}),(0,A.jsx)(Bm,{onClick:()=>u(!1),children:`Cancel`})]}):(0,A.jsxs)(U,{kind:`danger`,size:`sm`,onClick:()=>u(!0),children:[`Remove `,e.slug]})})]})]})}function Qx({named:e}){let t=j(),n=tx((0,D.useCallback)(()=>Px(t,e),[t,e])),r=rx(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(``),u=async i=>{i.preventDefault(),await r.move(async()=>{await Fx(t,e,o.trim(),c.trim()),await n.reread()})&&(s(``),l(``),a(!1))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused??r.refused}),n.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Vendors it brought`,meta:`every other vendor runs on the box's own key`,action:i?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>a(!0),children:`Bring a key`})}),i&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void u(e),children:[(0,A.jsx)(Wm,{label:`Vendor`,minWidth:170,children:(0,A.jsx)(W,{value:o,placeholder:`elevenlabs`,onChange:e=>s(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Its key, sent once`,grow:!0,minWidth:240,children:(0,A.jsx)(W,{type:`password`,autoComplete:`off`,value:c,placeholder:`never shown again`,onChange:e=>l(e.target.value),required:!0})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:r.busy,children:r.busy?`Keeping…`:`Keep it`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`No door a person reads ever answers with a provider key: a lost one is set again.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>a(!1),children:`Close`})})]})]}),n.value.length===0?(0,A.jsx)(Mm,{children:`None: every call of this org runs on the keys of the box.`}):n.value.map(i=>(0,A.jsx)(Pm,{name:i,sub:`this org's own account with them`,end:(0,A.jsx)(Bm,{disabled:r.busy,onClick:()=>void r.move(async()=>{await Ix(t,e,i),await n.reread()}),children:`Give it back to the box`})},i))]})]})}var $x=[{tab:`overview`,name:`Overview`},{tab:`members`,name:`Members`},{tab:`keys`,name:`Keys`},{tab:`limits`,name:`Limits`},{tab:`providers`,name:`Providers`}];function eS(){let e=j(),t=Sr().org??``,[n,r]=Xi(),i=$x.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`overview`,a=tx((0,D.useCallback)(()=>xx(e,t),[e,t])),{moveTo:o}=kh(),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(null),d=async e=>{c(!0),u(null);try{await o(e)}catch(e){u(nx(e)),c(!1)}};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{back:(0,A.jsx)(Wi,{to:`/box/orgs`,className:`box-back`,children:`← Organizations`}),title:a.value?.name??t,lede:a.value===void 0?void 0:(0,A.jsx)(`span`,{className:`box-fixed`,children:`${a.value.slug} · ${a.value.id}`}),actions:a.value!==void 0&&(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:s,onClick:()=>void d(a.value?.id??t),children:s?`Opening…`:`Open as operator`})}),(0,A.jsx)(yh,{label:`Organization`,tabs:$x,on:i,onPick:e=>r(e===`overview`?{}:{tab:e})}),(0,A.jsx)(Nm,{children:l??a.refused}),a.value!==void 0&&i===`overview`&&(0,A.jsx)(Zx,{org:a.value}),i===`members`&&(0,A.jsx)(Yx,{named:t,seats:a.value?.quotas.seats??null}),i===`keys`&&(0,A.jsx)(Vx,{named:t}),a.value!==void 0&&i===`limits`&&(0,A.jsx)(Gx,{org:a.value,onSaved:a.reread}),i===`providers`&&(0,A.jsx)(Qx,{named:t})]})}var tS=`minmax(0,1.2fr) minmax(0,1fr) minmax(0,1fr) 60px`;function nS(){let e=j(),t=tx((0,D.useCallback)(()=>bx(e),[e])),n=rx(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),l=async r=>{r.preventDefault(),await n.move(async()=>{await Sx(e,a.trim(),s.trim()),await t.reread()})&&(o(``),c(``),i(!1))};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Organizations`,lede:`Every tenant this box serves. Open one to see its people, its keys, its limits and the vendors it brought.`}),(0,A.jsx)(Nm,{children:t.refused??n.refused}),t.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`On this box`,meta:`${t.value.length} ${t.value.length===1?`organization`:`organizations`}`,action:r?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>i(!0),children:`Add an organization`})}),r&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void l(e),children:[(0,A.jsx)(Wm,{label:`Slug`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{value:a,placeholder:`tienda-sur`,onChange:e=>o(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Name`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{value:s,placeholder:`Tienda Sur (optional)`,onChange:e=>c(e.target.value)})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:n.busy||a.trim()===``,children:n.busy?`Adding…`:`Add`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`The slug is what people type and the gateway is its judge. Its first admin is invited from the org's Members tab.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>i(!1),children:`Close`})})]})]}),t.value.length===0?(0,A.jsx)(Mm,{children:`No organization on this box yet. The first one is what a key is issued against.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:tS,labels:[`Organization`,`Slug`,`Id`,``]}),t.value.map(e=>(0,A.jsxs)(fh,{columns:tS,to:`/box/orgs/${encodeURIComponent(e.slug)}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.slug}),(0,A.jsx)(`span`,{className:`ui-cell-faint box-fixed`,children:e.id}),(0,A.jsx)(`span`,{className:`ui-cell-link ui-cell-end`,children:`Open`})]},e.id))]})]})]})}var rS=[`production`,`sandbox`],iS=[`phone`,`whatsapp`],aS=`minmax(0,1.1fr) 110px minmax(0,1fr) 150px 80px`;function oS(){let e=j(),t=tx((0,D.useCallback)(()=>bx(e),[e])),[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(rS[0]),o=tx((0,D.useCallback)(()=>n===``?Promise.resolve(void 0):Zb(e,n,i),[e,n,i])),s=rx(),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(iS[0]),[g,_]=(0,D.useState)(null);(0,D.useEffect)(()=>{n===``&&t.value!==void 0&&r(t.value.find(e=>e.slug!=="default")?.slug??t.value[0]?.slug??``)},[n,t.value]);let v=async t=>{t.preventDefault(),_(null),await s.move(async()=>{let t=await Qb(e,{org:n,number:u.trim(),agent:f.trim(),channel:m,env:i});_(t===null?`${u.trim()} now rings ${f.trim()}.`:`${u.trim()} now rings ${f.trim()}, taken from ${t}.`),await o.reread()})&&(d(``),p(``),l(!1))};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Routes`,lede:`Every door one org answers at, in one world. A row typed here outranks whatever an app declared.`}),(0,A.jsxs)(`div`,{className:`box-pick`,children:[(0,A.jsx)(Hm,{size:`sm`,value:n,onChange:e=>r(e.target.value),"aria-label":`Organization`,children:(t.value??[]).map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.id))}),(0,A.jsx)(Hm,{size:`sm`,value:i,onChange:e=>a(e.target.value),"aria-label":`World`,children:rS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})]}),(0,A.jsx)(Nm,{children:t.refused??o.refused??s.refused}),o.value!==void 0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`${n} · ${i}`,meta:`${o.value.length} ${o.value.length===1?`door`:`doors`}`,action:c?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>l(!0),children:`Type a number`})}),c&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void v(e),children:[(0,A.jsx)(Wm,{label:`Number`,minWidth:170,children:(0,A.jsx)(W,{value:u,placeholder:`+34910000000`,onChange:e=>d(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Agent`,grow:!0,minWidth:170,children:(0,A.jsx)(W,{value:f,placeholder:`clinica-norte`,onChange:e=>p(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Channel`,minWidth:120,children:(0,A.jsx)(Hm,{value:m,onChange:e=>h(e.target.value),children:iS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:s.busy,children:s.busy?`Typing…`:`Add`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`A row and nothing else: the carrier and the SFU trunk are the org's Numbers screen.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(Bm,{onClick:()=>l(!1),children:`Close`})})]})]}),g!==null&&(0,A.jsx)(`div`,{className:`box-done box-done-row`,children:g}),o.value.length===0?(0,A.jsx)(Mm,{children:`No door in this world: nothing typed, and no app holding an agent here.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:aS,labels:[`Number`,`Channel`,`Agent`,`Said by`,``]}),o.value.map(t=>(0,A.jsxs)(fh,{columns:aS,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:t.route.number?og(t.route.number):`—`}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:t.route.channel}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:t.route.agent}),(0,A.jsxs)(`span`,{className:`box-line`,children:[(0,A.jsx)(Qm,{tone:t.source===`operator`?`indigo`:`gray`,children:t.source===`operator`?`typed`:t.source}),t.route.managed===!0&&(0,A.jsx)(Qm,{tone:`violet`,children:`bought`})]}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:t.source===`operator`&&typeof t.route.number==`string`&&(0,A.jsx)(Bm,{danger:!0,disabled:s.busy,onClick:()=>void s.move(async()=>{await $b(e,n,t.route.number??``),await o.reread()}),children:`Forget`})})]},`${t.route.channel}-${t.route.number??t.route.agent}`))]})]})]})}var sS=`/v1/ops`;async function cS(e){try{return await e}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}var lS=np({google:np({configured:L(),client_id:P().nullish(),redirect_uri:P().nullish()})});async function uS(e){return cS(k(e,`${sS}/signin`).then(e=>lS.parse(e)))}async function dS(e,t){await oa(e,`${sS}/signin/google`,t)}async function fS(e){await ca(e,`${sS}/signin/google`)}var pS=[`starttls`,`tls`,`none`],mS=np({configured:L(),source:P().nullish(),host:P().nullish(),port:F().nullish(),security:P().nullish(),username:P().nullish(),from:P().nullish(),verified_at:P().nullish(),last_error:P().nullish()});async function hS(e){return cS(k(e,`${sS}/mail`).then(e=>mS.parse(e)))}async function gS(e,t){await oa(e,`${sS}/mail`,t)}async function _S(e){await ca(e,`${sS}/mail`)}async function vS(e,t){let n=np({sent:L(),error:P().nullish()}).parse(await sa(e,`${sS}/mail/test`,{to:t}));return{sent:n.sent,error:n.error??null}}var yS=np({name:P().nullish(),logo_url:P().nullish(),accent:P().nullish()});async function bS(e){return cS(k(e,`${sS}/brand`).then(e=>yS.parse(e)))}async function xS(e,t){await oa(e,`${sS}/brand`,t)}var SS=`Pinecall`,CS=`#5b3df5`,wS=/^#[0-9a-fA-F]{6}$/;function TS(){let e=j(),t=tx((0,D.useCallback)(()=>bS(e),[e])),n=rx(),[r,i]=(0,D.useState)(SS),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(CS),[l,u]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{t.value!==void 0&&t.value!==null&&(i(t.value.name??SS),o(t.value.logo_url??``),c(t.value.accent??CS))},[t.value]),t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(jS,{});let d=async i=>{i.preventDefault(),u(!1),u(await n.move(async()=>{await xS(e,{name:r.trim(),logo_url:a.trim(),accent:s}),await t.reread()}))},f=wS.test(s)?s:CS;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`What the letters carry`,meta:`invitations and password resets, for every org on this box`}),(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>void d(e),children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(Wm,{label:`Name`,children:(0,A.jsx)(W,{value:r,onChange:e=>i(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Accent`,children:(0,A.jsxs)(`span`,{className:`box-accent`,children:[(0,A.jsx)(`input`,{type:`color`,className:`box-accent-well`,value:f,onChange:e=>c(e.target.value),"aria-label":`Accent`}),(0,A.jsx)(W,{value:s,onChange:e=>c(e.target.value)})]})}),(0,A.jsx)(Wm,{label:`Logo URL`,children:(0,A.jsx)(W,{type:`url`,value:a,placeholder:`https://… (https only; empty shows the name)`,onChange:e=>o(e.target.value)})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:n.busy,children:n.busy?`Saving…`:`Save`}),l&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. The next letter carries it.`})]})]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Preview`,meta:`the head of a letter`}),(0,A.jsx)(`div`,{className:`box-letter-ground`,children:(0,A.jsxs)(`div`,{className:`box-letter`,children:[a.trim().startsWith(`https://`)?(0,A.jsx)(`img`,{className:`box-letter-logo`,src:a.trim(),alt:r}):(0,A.jsx)(`span`,{className:`box-letter-name`,children:r}),(0,A.jsxs)(`div`,{className:`box-letter-title`,children:[`You're invited to Acme on `,r]}),(0,A.jsx)(`div`,{className:`box-letter-words`,children:`Ana invited you as a supervisor. Choose a password to take your first key.`}),(0,A.jsx)(`span`,{className:`box-letter-button`,style:{background:f},children:`Accept the invitation`})]})})]})]})}function ES(){let e=j(),t=tx((0,D.useCallback)(()=>hS(e),[e])),n=rx(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null);if(t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(jS,{});let l=t.value,u=async r=>{r.preventDefault(),c(null),await n.move(async()=>{c(await vS(e,a.trim())),await t.reread()})};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The box's mail`,meta:`invitations, password resets and a forgotten password`,children:(0,A.jsx)(`span`,{className:`box-head-moves`,children:(0,A.jsx)(Qm,{tone:l.configured?`green`:`gray`,children:l.configured?l.source===`environment`?`on · from the environment`:`on`:`off`})})}),r||!l.configured?(0,A.jsx)(DS,{kept:l,busy:n.busy,onCancel:l.configured?()=>i(!1):void 0,onSave:async r=>{await n.move(async()=>{await gS(e,r),await t.reread()})&&i(!1)}}):(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsxs)(Lm,{label:`Server`,keyWidth:120,children:[(0,A.jsx)(`span`,{className:`box-fixed`,children:`${l.host??`—`}:${l.port??``}`}),` · `,l.security??`starttls`]}),(0,A.jsx)(Lm,{label:`Username`,keyWidth:120,children:(0,A.jsx)(`span`,{className:`box-fixed`,children:l.username??`none`})}),(0,A.jsx)(Lm,{label:`From`,keyWidth:120,children:l.from??`—`}),(0,A.jsx)(Lm,{label:`Last letter`,keyWidth:120,children:l.last_error?(0,A.jsx)(`span`,{className:`box-bad`,children:l.last_error}):l.verified_at?`went through · ${l.verified_at.slice(0,16).replace(`T`,` `)}`:`none sent yet`}),(0,A.jsxs)(`div`,{className:`box-line box-kvs-moves`,children:[(0,A.jsx)(U,{size:`sm`,onClick:()=>i(!0),children:l.source===`environment`?`Replace it here`:`Change`}),l.source!==`environment`&&(0,A.jsx)(Bm,{danger:!0,disabled:n.busy,onClick:()=>void n.move(async()=>{await _S(e),await t.reread()}),children:`Forget it`})]})]})]}),l.configured&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Send a test letter`,meta:`the one door that waits for the mail server's answer`}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void u(e),children:[(0,A.jsx)(Wm,{label:`To`,grow:!0,minWidth:240,children:(0,A.jsx)(W,{type:`email`,value:a,placeholder:`you@company.com`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(U,{size:`form`,type:`submit`,disabled:n.busy,children:n.busy?`Sending…`:`Send`})]}),s!==null&&(s.sent?(0,A.jsx)(`div`,{className:`box-done box-done-under`,children:`Taken by the mail server.`}):(0,A.jsx)(`div`,{className:`box-bad box-note`,children:s.error??`It was refused.`}))]})]})]})}function DS({kept:e,busy:t,onSave:n,onCancel:r}){let[i,a]=(0,D.useState)(e.host??``),[o,s]=(0,D.useState)(String(e.port??587)),[c,l]=(0,D.useState)(pS.find(t=>t===e.security)??`starttls`),[u,d]=(0,D.useState)(e.username??``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(e.from??``);return(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>{e.preventDefault(),n({host:i.trim(),port:Number(o),security:c,username:u.trim()===``?null:u.trim(),...f===``?{}:{password:f},from:m.trim()})},children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(Wm,{label:`Host`,children:(0,A.jsx)(W,{value:i,placeholder:`email-smtp.us-east-1.amazonaws.com`,onChange:e=>a(e.target.value),required:!0})}),(0,A.jsxs)(`div`,{className:`box-form-pair`,children:[(0,A.jsx)(Wm,{label:`Port`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:o,onChange:e=>s(e.target.value.replace(/[^0-9]/g,``)),required:!0})}),(0,A.jsx)(Wm,{label:`Security`,children:(0,A.jsx)(Hm,{value:c,onChange:e=>l(e.target.value),children:pS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})})]}),(0,A.jsx)(Wm,{label:`Username`,children:(0,A.jsx)(W,{autoComplete:`off`,value:u,onChange:e=>d(e.target.value)})}),(0,A.jsx)(Wm,{label:`Password, sent once`,children:(0,A.jsx)(W,{type:`password`,autoComplete:`new-password`,value:f,placeholder:e.configured?`unchanged`:`never shown again`,onChange:e=>p(e.target.value)})}),(0,A.jsx)(Wm,{label:`From`,children:(0,A.jsx)(W,{value:m,placeholder:`Pinecall <noreply@pinecall.io>`,onChange:e=>h(e.target.value),required:!0})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:t,children:t?`Saving…`:`Save`}),r!==void 0&&(0,A.jsx)(Bm,{onClick:r,children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Saving sends nothing: the test letter below is what proves it.`})]})]})}function OS(){let e=j(),t=tx((0,D.useCallback)(()=>uS(e),[e])),n=rx(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1);if(t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(jS,{});let d=t.value.google,f=d.redirect_uri??nm(pm()),p=r||!d.configured,m=async r=>{r.preventDefault(),await n.move(async()=>{await dS(e,{client_id:a.trim(),client_secret:s.trim()}),await t.reread()})&&(c(``),i(!1))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Nm,{children:n.refused}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Continue with Google`,meta:`one client for the whole box — no org configures anything`,children:(0,A.jsx)(`span`,{className:`box-head-moves`,children:(0,A.jsx)(Qm,{tone:d.configured?`green`:`gray`,children:d.configured?`on`:`off`})})}),p?(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>void m(e),children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(Wm,{label:`Client ID`,children:(0,A.jsx)(W,{value:a,placeholder:`…apps.googleusercontent.com`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Client secret, sent once`,children:(0,A.jsx)(W,{type:`password`,autoComplete:`off`,value:s,placeholder:`never shown again`,onChange:e=>c(e.target.value),required:!0})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:n.busy,children:n.busy?`Saving…`:`Save`}),r&&(0,A.jsx)(Bm,{onClick:()=>i(!1),children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Made at Google Cloud Console → APIs & Services → Credentials → OAuth client ID → Web application.`})]})]}):(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsx)(Lm,{label:`Client ID`,keyWidth:120,children:(0,A.jsx)(`span`,{className:`box-fixed`,children:d.client_id??`—`})}),(0,A.jsx)(Lm,{label:`Secret`,keyWidth:120,children:`kept, and read back by no door`}),(0,A.jsxs)(`div`,{className:`box-line box-kvs-moves`,children:[(0,A.jsx)(U,{size:`sm`,onClick:()=>{o(d.client_id??``),i(!0)},children:`Change`}),(0,A.jsx)(Bm,{danger:!0,disabled:n.busy,onClick:()=>void n.move(async()=>{await fS(e),await t.reread()}),children:`Turn it off`})]})]}),(0,A.jsxs)(`div`,{className:`box-redirect`,children:[(0,A.jsxs)(`div`,{className:`box-redirect-head`,children:[(0,A.jsx)(`span`,{className:`ui-note`,children:`Register this at Google as the authorized redirect URI`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(f).then(()=>u(!0)),children:l?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:f})]})]})]})}var kS=[{tab:`signin`,name:`Sign-in`},{tab:`email`,name:`Email`},{tab:`brand`,name:`Brand`}];function AS(){let[e,t]=Xi(),n=kS.some(t=>t.tab===e.get(`tab`))?e.get(`tab`):`signin`;return(0,A.jsxs)(sh,{width:900,children:[(0,A.jsx)(ch,{title:`Box settings`,lede:`What this gateway is set to, for every organization on it.`}),(0,A.jsx)(yh,{label:`Box settings`,tabs:kS,on:n,onPick:e=>t(e===`signin`?{}:{tab:e})}),n===`signin`&&(0,A.jsx)(OS,{}),n===`email`&&(0,A.jsx)(ES,{}),n===`brand`&&(0,A.jsx)(TS,{})]})}function jS(){return(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`This gateway does not have this door yet.`})})}var MS=100,NS=`minmax(0,1.2fr) 110px 110px 140px 140px`,PS=`130px minmax(0,1fr) minmax(0,1.4fr) 110px 80px 80px 90px`;function FS(){let e=j(),[t,n]=(0,D.useState)([]),[r,i]=(0,D.useState)({}),[a,o]=(0,D.useState)(0),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),p=async(t,r)=>{u(!0);try{let a=await ex(e,t,MS);n(e=>r?a.rows:[...e,...a.rows]),i(e=>r?a.totals:LS(e,a.totals)),o(a.next??null),c(!0)}catch(e){f(nx(e))}finally{u(!1)}};(0,D.useEffect)(()=>{p(0,!0)},[e]);let m=e=>t.filter(t=>t.org===e).reduce((e,t)=>e+t.cost_eur,0);return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Box usage`,lede:`What every organization consumed, folded off the log by a cursor — there is no counter table to drift from it.`}),(0,A.jsx)(Nm,{children:d}),s&&t.length===0&&a===null&&(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`Nothing metered yet: no call of any org has been summarised.`})}),Object.keys(r).length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`By organization`,meta:a===null?`the whole log`:`the pages read so far`}),(0,A.jsx)(dh,{columns:NS,labels:[`Organization`,`Minutes>`,`Messages>`,`Tokens>`,`Cost>`]}),Object.entries(r).map(([e,t])=>(0,A.jsxs)(fh,{columns:NS,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:t.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:t.messages}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:(t.input_tokens+t.output_tokens).toLocaleString(`en`)}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-cell-right`,children:[`€`,m(e).toFixed(2)]})]},e))]}),t.length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Metered rows`,meta:`${t.length} read, oldest first`}),(0,A.jsx)(dh,{columns:PS,labels:[`When`,`Organization`,`Agent · call`,`What`,`Min>`,`Msgs>`,`Cost>`]}),t.map(e=>(0,A.jsxs)(fh,{columns:PS,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:IS(e.at)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.org}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-clip`,title:e.call,children:[e.agent,` `,(0,A.jsxs)(`span`,{className:`ui-cell-faint box-fixed`,children:[e.call.slice(0,13),`…`]})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint box-fixed`,children:e.type}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:e.minutes.toFixed(2)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:e.messages}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-cell-right`,children:[`€`,e.cost_eur.toFixed(4)]})]},`${e.cursor}-${e.call}-${e.type}`)),a!==null&&(0,A.jsx)(jm,{children:(0,A.jsx)(U,{size:`sm`,disabled:l,onClick:()=>void p(a,!1),children:l?`Reading…`:`Read on`})})]})]})}function IS(e){return new Date(e*1e3).toISOString().slice(0,16).replace(`T`,` `)}function LS(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t===void 0?r:{...r,minutes:t.minutes+r.minutes,messages:t.messages+r.messages,input_tokens:t.input_tokens+r.input_tokens,output_tokens:t.output_tokens+r.output_tokens,characters:t.characters+r.characters}}return n}function RS({children:e}){let{operator:t}=Zy();return t===null?null:t?e:(0,A.jsx)(Xr,{to:`/`,replace:!0})}var zS=3e3;function BS(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=Wv.parse(await k(t,`/v1/agents/${e}/sessions`));n||(r(i.calls),a(null))}catch(e){n||a(String(e))}};i();let o=window.setInterval(()=>void i(),zS);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{lines:n,error:i}}function VS(e){return e.status!==`ended`}var HS=/^\+[1-9]\d{4,14}$/;function US(){let e=j(),[t,n]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return Tb(e).then(e=>{t||n(e!==null&&e.ready?e:null)},()=>void 0),()=>{t=!0}},[e]),t}function WS({outbound:e,value:t,onChange:n}){return e.from_numbers.length<2?null:(0,A.jsx)(Wm,{label:`From`,children:(0,A.jsxs)(Hm,{size:`sm`,value:t,onChange:e=>n(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the agent's own number`}),e.from_numbers.map(e=>(0,A.jsx)(`option`,{value:e,children:og(e)},e))]})})}function GS({agent:e,to:t,outbound:n,onClose:r,onRefused:i}){let a=j(),o=vr(),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),d=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()},t=e=>{let t=d.current?.parentElement;t!=null&&!t.contains(e.target)&&r()};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,t)}},[r]);let f=async()=>{u(!0);try{let n=await Ob(a,e,t,s);o(`/live/${n}`)}catch(e){i(e instanceof na?e.message:String(e)),r()}finally{u(!1)}};return(0,A.jsxs)(`div`,{className:`dial-pop`,role:`dialog`,"aria-label":`call back`,ref:d,children:[(0,A.jsxs)(`div`,{className:`dial-ask`,children:[`Call `,og(t),` as `,e,`?`]}),(0,A.jsx)(WS,{outbound:n,value:s,onChange:c}),(0,A.jsxs)(`div`,{className:`dial-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,disabled:l,onClick:()=>void f(),children:l?`Calling…`:`Call`}),(0,A.jsx)(U,{size:`md`,disabled:l,onClick:r,children:`Cancel`})]})]})}function KS({agent:e,outbound:t,onClose:n}){let r=j(),i=vr(),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),p=a.replace(/[\s()-]/g,``),m=async t=>{if(t.preventDefault(),!HS.test(p)){f(`A number is written whole, with its country: +14176743169.`);return}u(!0),f(null);try{let t=await Ob(r,e,p,s);n(),i(`/live/${t}`)}catch(e){f(e instanceof na?e.message:String(e))}finally{u(!1)}};return(0,A.jsxs)(`form`,{className:`dial-form`,onSubmit:e=>void m(e),children:[(0,A.jsx)(Wm,{label:`Number`,children:(0,A.jsx)(W,{size:`sm`,value:a,placeholder:`+1 417 674 3169`,autoFocus:!0,autoComplete:`off`,onChange:e=>o(e.target.value)})}),(0,A.jsx)(WS,{outbound:t,value:s,onChange:c}),(0,A.jsx)(`p`,{className:`dial-note`,children:t.guards.dial_anywhere?`${e} places the call and speaks first.`:`${e} places the call and speaks first. Only a number that has already called or written to you is dialled.`}),d!==null&&(0,A.jsx)(`p`,{className:`dial-refused`,children:d}),(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,disabled:l||p===``,children:l?`Calling…`:`Call`})]})}var qS=np({threads:R(np({contact:P(),name:P().nullish(),unread:F().nullish()}))});async function JS(e,t){try{let n=qS.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/threads`));return new Map(n.threads.map(e=>[e.contact,e]))}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}async function YS(e,t,n){await sa(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/read`,{})}async function XS(e,t,n,r){await sa(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/messages`,{text:r})}async function ZS(e,t,n){await sa(e,`/v1/calls/${encodeURIComponent(t)}/verbs`,n_.parse({verb:`say`,text:n}))}var QS={"chat.roster":`chat`,"chat.start":`chat`,"chat.say":`chat`,"chat.end":`chat`,"knowledge.roster":`knowledge`,"knowledge.push":`knowledge`,"knowledge.eval":`knowledge`,"memory.roster":`memory`,"memory.eval":`memory`,"memory.extraction":`memory`,"simulate.roster":`evals`,"simulate.start":`evals`,"goldens.roster":`evals`,"goldens.run":`evals`,"promote.roster":`evals`,"promote.write":`evals`,"drift.read":`evals`,"reproductions.roster":`evals`,"reproductions.read":`evals`};function $S(e,t){return`/v1/agents/${encodeURIComponent(e)}/dev/${QS[t]}/${t}`}async function eC(e,t,n,r={}){return sa(e,$S(t,n),r)}var tC=z({name:P(),goal:P(),style:P()}),nC=z({agent:P().nullable(),personas:R(tC)}),rC=z({call:P()});async function iC(e,t){return nC.parse(await eC(e,t,`simulate.roster`))}async function aC(e,t){return rC.parse(await eC(e,t.agent,`simulate.start`,t)).call}var oC=6,sC=15,cC=0;function lC({agent:e,agents:t,onClose:n}){let r=j(),i=vr(),[a,o]=(0,D.useState)(e??t?.[0]??``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(oC),[_,v]=(0,D.useState)(sC),[y,b]=(0,D.useState)(cC),[x,S]=(0,D.useState)(!1),[C,w]=(0,D.useState)(!1),[T,ee]=(0,D.useState)(null);(0,D.useEffect)(()=>{if(a===``)return;let e=!1;return c(null),ee(null),iC(r,a).then(t=>{e||(c(t),u(t.personas[0]?.name??``))},t=>{e||ee(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[r,a]);let te=s?.personas.find(e=>e.name===l),ne=uC(s,a),re=async e=>{e.preventDefault(),w(!0),ee(null);try{let e=await aC(r,{agent:a,persona:l,voice:d,judge:p,turns:h,...d&&x?{background_noise:_,packet_loss:y}:{}});n(),i(`/live/${e}`)}catch(e){ee(e instanceof na?e.message:String(e))}finally{w(!1)}};return(0,A.jsxs)(`form`,{className:`sim`,onSubmit:e=>void re(e),children:[(0,A.jsxs)(`div`,{className:`sim-head`,children:[(0,A.jsx)(`span`,{className:`sim-title`,children:`Simulate a caller`}),(0,A.jsx)(`button`,{type:`button`,className:`sim-close`,onClick:n,"aria-label":`close`,children:`×`})]}),t!==void 0&&(0,A.jsx)(Wm,{label:`Agent`,children:(0,A.jsx)(Hm,{size:`sm`,value:a,onChange:e=>o(e.target.value),children:t.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),s===null&&T===null&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Asking the process that holds `,a||`the agent`,` for its personas…`]}),ne!==null&&(0,A.jsx)(`p`,{className:`sim-note`,children:ne}),s!==null&&ne===null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Wm,{label:`Persona`,children:(0,A.jsx)(Hm,{size:`sm`,value:l,onChange:e=>u(e.target.value),children:s.personas.map(e=>(0,A.jsx)(`option`,{value:e.name,children:e.name},e.name))})}),te!==void 0&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Goal: `,te.goal]}),(0,A.jsxs)(`div`,{className:`sim-pair`,children:[(0,A.jsx)(Wm,{label:`Turns`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:30,value:h,onChange:e=>g(Number(e.target.value))})}),d&&x&&(0,A.jsx)(Wm,{label:`Noise, dB under`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:60,value:_,onChange:e=>v(Number(e.target.value))})}),d&&x&&(0,A.jsx)(Wm,{label:`Packets lost, %`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:100,value:y,onChange:e=>b(Number(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`sim-checks`,children:[(0,A.jsxs)(Ym,{checked:d,onChange:f,children:[`Voice `,(0,A.jsx)(`span`,{className:`sim-aside`,children:`a real line, and you can listen`})]}),(0,A.jsx)(Ym,{checked:p,onChange:m,children:`Judge at hang-up`}),d&&(0,A.jsxs)(Ym,{checked:x,onChange:S,children:[`Noisy line `,(0,A.jsx)(`span`,{className:`sim-aside`,children:`a TV behind the caller, packets lost`})]})]}),(0,A.jsx)(U,{type:`submit`,kind:`primary`,size:`md`,disabled:C||l===``,children:C?`Calling…`:`Call the agent`})]}),T!==null&&(0,A.jsx)(`p`,{className:`sim-refused`,children:T})]})}function uC(e,t){return e===null?null:e.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so nothing to simulate against.":e.agent===t?e.personas.length===0?`No personas in test/personas: one file per caller, default-exporting one.`:null:`The process holding the agent runs in ${e.agent}'s directory; a simulated caller is for that agent.`}function dC(e){return e.direction===`outbound`?e.to:e.from}function fC(e){let t=new Map;for(let n of e){let e=n.caller?.id??n.caller?.phone??dC(n)??n.call,r=t.get(e);if(r===void 0){t.set(e,{contact:e,name:n.caller?.name??null,handle:pC(n),lines:[n],latest:n});continue}r.lines.push(n),r.name??=n.caller?.name??null,(n.started_at??0)>(r.latest.started_at??0)&&(r.latest=n)}let n=[...t.values()];for(let e of n)e.lines.sort((e,t)=>(t.started_at??0)-(e.started_at??0));return n.sort((e,t)=>(t.latest.started_at??0)-(e.latest.started_at??0))}function pC(e){let t=dC(e);return t===null?e.channel===`web`?`web visitor`:`—`:t.startsWith(`+`)?og(t):e.channel===`web`?`web visitor`:t}function mC(e){return e.name!==null&&e.name!==``?e.name:e.contact.startsWith(`+`)?og(e.contact):e.contact}function hC(e){if(e.name===null||e.name===``)return e.handle===`web visitor`?`W`:e.contact.startsWith(`+`)?e.contact.slice(-2):void 0}function gC(e,t){if(e.channel===`phone`)return!0;let n=Ty();for(let e of t)n=Oy(n,e);return n.room!==null}function _C(e,t,n){let r=[],i=t[0]?.ts??e.started_at??0;n&&r.push({kind:`call`,text:vC(e),at:i,call:e.call});for(let n of t){let t=n.data.text;typeof t==`string`&&t!==``&&(n.type===`turn.user`&&r.push({kind:`in`,text:t,at:n.ts,call:e.call}),(n.type===`turn.agent`||n.type===`supervisor.said`)&&r.push({kind:`out`,text:t,at:n.ts,call:e.call}))}return r}function vC(e){let t=e.direction===`outbound`?`outbound`:`inbound`;return e.status===`ended`?e.end_reason===`no_answer`||e.end_reason===`busy`||e.end_reason===`dial_failed`?`Voice call · ${e.end_reason.replace(`_`,` `)}`:`Voice call · answered · ${qh(e)}`:`Voice call · ${t} · on the line now`}function yC(e){let t=e.latest;return t.status===`ended`?t.outcome!==null&&t.outcome!==``?t.outcome:`${t.channel??`a`} call · ${qh(t)}`:`On a call now`}var bC=500;async function xC(e,t){let n=[],r=0;for(;;){let i=Bv.parse(await k(e,`/v1/calls/${t}/events`,{after:r,limit:bC}));if(n.push(...i.entries),i.next===null||i.entries.length<bC)return n;r=i.next}}var SC=12;function CC(e){let t=j(),n=(0,D.useRef)(new Map),[,r]=(0,D.useState)(0),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null),c=e?.lines.slice(0,SC)??[],l=c.map(e=>`${e.call}@${e.last_seq}`).join(` `);return(0,D.useEffect)(()=>{let e=!1,i=c.filter(e=>n.current.get(e.call)?.seq!==e.last_seq);if(i.length!==0)return a(!0),(async()=>{try{await Promise.all(i.map(async e=>{let r=await xC(t,e.call),i=gC(e,r);n.current.set(e.call,{seq:e.last_seq,voice:i,messages:_C(e,r,i)})})),e||s(null)}catch(t){e||s(String(t))}finally{e||(a(!1),r(e=>e+1))}})(),()=>{e=!0}},[l,t]),{messages:c.flatMap(e=>n.current.get(e.call)?.messages??[]).sort((e,t)=>e.at-t.at),voice:(e===void 0?void 0:n.current.get(e.latest.call))?.voice??null,loading:i,error:o}}function wC(){let e=Sr(),t=e.agent??``,n=e.call,r=vr(),i=j(),a=BS(t),o=(0,D.useMemo)(()=>fC(a.lines),[a.lines]),[s,c]=(0,D.useState)(``),l=vh({name:`agent.conversations`,initial:292,min:200,max:520,side:`left`}),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(`simulate`),m=US(),h=DC(t,a.lines.length),g=o.find(e=>n!==void 0&&e.lines.some(e=>e.call===n))??o[0],_=s.trim().toLowerCase(),v=o.filter(e=>_===``||`${EC(e,h)} ${e.handle} ${yC(e)}`.toLowerCase().includes(_));return(0,D.useEffect)(()=>{g!==void 0&&h!==null&&(h.get(g.contact)?.unread??0)!==0&&YS(i,t,g.contact).catch(()=>void 0)},[g?.contact,h,i,t]),(0,A.jsxs)(`div`,{className:`ib`,style:l.style,children:[l.handle,(0,A.jsxs)(`div`,{className:`ib-list`,children:[(0,A.jsxs)(`div`,{className:`ib-list-head`,children:[(0,A.jsx)(`input`,{className:`ib-search`,placeholder:`Search a caller or number`,value:s,onChange:e=>c(e.target.value)}),(0,A.jsx)(`button`,{type:`button`,className:`ib-new`,title:m===null?`Simulate a caller`:`Simulate a caller, or call a number`,"aria-expanded":u,onClick:()=>d(!u),children:`+`}),u&&m===null&&(0,A.jsx)(`div`,{className:`ib-sim`,children:(0,A.jsx)(lC,{agent:t,onClose:()=>d(!1)})}),u&&m!==null&&(0,A.jsx)(`div`,{className:`ib-sim`,children:f===`simulate`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`ib-sim-ways`,children:(0,A.jsx)(Gm,{options:TC,value:f,onChange:p})}),(0,A.jsx)(lC,{agent:t,onClose:()=>d(!1)})]}):(0,A.jsxs)(`div`,{className:`dial-panel`,children:[(0,A.jsxs)(`div`,{className:`dial-panel-head`,children:[(0,A.jsx)(Gm,{options:TC,value:f,onChange:p}),(0,A.jsx)(`button`,{type:`button`,className:`dial-panel-close`,onClick:()=>d(!1),"aria-label":`close`,children:`×`})]}),(0,A.jsx)(KS,{agent:t,outbound:m,onClose:()=>d(!1)})]})})]}),(0,A.jsxs)(`div`,{className:`ib-threads`,children:[a.error!==null&&(0,A.jsx)(`p`,{className:`ib-empty ib-refused`,children:a.error}),a.error===null&&o.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`No conversations yet. The first call to reach `,t,` opens a thread here as it rings.`]}),o.length>0&&v.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`Nobody here matches “`,s,`”.`]}),v.map(e=>(0,A.jsx)(OC,{thread:e,name:EC(e,h),unread:h?.get(e.contact)?.unread??0,on:e===g,onOpen:()=>void r(`/a/${t}/calls/${e.latest.call}`)},e.contact))]})]}),g===void 0?(0,A.jsx)(`div`,{className:`ib-thread`,children:(0,A.jsx)(`p`,{className:`ib-nothing`,children:a.error===null?`Pick a conversation on the left.`:``})}):(0,A.jsx)(AC,{agent:t,thread:g,name:EC(g,h),door:h!==null,outbound:m},g.contact)]})}var TC=[{value:`simulate`,label:`Simulate a caller`},{value:`dial`,label:`Call a number`}];function EC(e,t){return t?.get(e.contact)?.name??mC(e)}function DC(e,t){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(a)return;let t=!1;return JS(n,e).then(e=>{t||(e===null&&o(!0),i(e))},()=>void 0),()=>{t=!0}},[n,e,t,a]),r}function OC({thread:e,name:t,unread:n,on:r,onOpen:i}){return(0,A.jsxs)(`button`,{type:`button`,className:r?`ib-row ib-row-on`:`ib-row`,onClick:i,children:[(0,A.jsx)(ah,{name:t,letters:hC(e),size:36,round:!0}),(0,A.jsxs)(`span`,{className:`ib-row-main`,children:[(0,A.jsxs)(`span`,{className:`ib-row-top`,children:[(0,A.jsx)(`span`,{className:`ib-row-name`,children:t}),(0,A.jsx)(`span`,{className:`ib-row-time`,children:kC(e.latest.started_at)})]}),(0,A.jsxs)(`span`,{className:`ib-row-bottom`,children:[(0,A.jsx)(`span`,{className:e.latest.status===`ended`?`ib-row-last`:`ib-row-last ib-row-last-live`,children:yC(e)}),n>0&&(0,A.jsx)(`span`,{className:`ib-unread`,children:n})]})]})]})}function kC(e){if(e===null)return``;let t=ng(),n=tg(e);return n===t.today?Zh(e).slice(0,5):n===t.yesterday?`Yesterday`:$h(e)}function AC({agent:e,thread:t,name:n,door:r,outbound:i}){let a=vr(),o=j(),{messages:s,voice:c,loading:l,error:u}=CC(t),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(!1),y=(0,D.useCallback)(()=>v(!1),[]),b=i!==null&&t.contact.startsWith(`+`),x=t.latest,S=x.status!==`ended`,C=S&&c===!1?`call`:!S&&r&&x.channel===`whatsapp`?`thread`:null,w=C===null?S&&c===!0?`A live voice call — Listen in on Live to speak into it`:S?`Reading the call…`:`The conversation is closed — nothing can be written into it from here`:`Write as ${e} — the agent keeps the thread from here`,T=async()=>{if(C!==null&&d.trim()!==``){m(!0),g(null);try{C===`call`?await ZS(o,x.call,d.trim()):await XS(o,e,t.contact,d.trim()),f(``)}catch(e){g(e instanceof na?e.message:String(e))}finally{m(!1)}}};return(0,A.jsxs)(`div`,{className:`ib-thread`,children:[(0,A.jsxs)(`div`,{className:`ib-head`,children:[(0,A.jsx)(ah,{name:n,letters:hC(t),size:38,round:!0}),(0,A.jsxs)(`div`,{className:`ib-head-words`,children:[(0,A.jsx)(`div`,{className:`ib-head-name`,children:n}),(0,A.jsxs)(`div`,{className:`ib-head-sub`,children:[t.handle!==n&&`${t.handle} · `,x.channel??`—`,` · handled by `,e]})]}),(0,A.jsxs)(`div`,{className:`ib-head-actions`,children:[S&&(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-md`,onClick:()=>void a(`/live/${x.call}`),children:`Watch live`}),(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-md`,onClick:()=>void a(`/a/${e}/sessions/${x.call}`),children:`Session`}),b&&i!==null&&(0,A.jsxs)(`span`,{className:`dial-anchor`,children:[(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-primary ui-button-md`,"aria-expanded":_,onClick:()=>v(!_),children:`Call back`}),_&&(0,A.jsx)(GS,{agent:e,to:t.contact,outbound:i,onClose:y,onRefused:g})]})]})]}),(0,A.jsxs)(`div`,{className:`ib-messages`,children:[u!==null&&(0,A.jsx)(`p`,{className:`ib-refused-line`,children:u}),s.length===0&&u===null&&(0,A.jsx)(`p`,{className:`ib-quiet`,children:l?`Reading the conversation…`:`Nothing was said in this conversation.`}),(0,A.jsx)(jC,{messages:s})]}),h!==null&&(0,A.jsx)(`p`,{className:`ib-refused-line ib-refused-foot`,children:h}),(0,A.jsxs)(`form`,{className:`ib-composer`,onSubmit:e=>{e.preventDefault(),T()},children:[(0,A.jsx)(`input`,{className:`ib-write`,value:d,placeholder:w,disabled:C===null||p,onChange:e=>f(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`ib-send`,disabled:C===null||p||d.trim()===``,children:`Send`})]})]})}function jC({messages:e}){let t=ng(),n=``;return(0,A.jsx)(A.Fragment,{children:e.map((e,r)=>{let i=tg(e.at),a=i===n?null:i===t.today?`Today`:i===t.yesterday?`Yesterday`:$h(e.at);return n=i,(0,A.jsxs)(`div`,{className:`ib-bubble-wrap`,children:[a!==null&&(0,A.jsx)(`div`,{className:`ib-day`,children:a}),e.kind===`call`?(0,A.jsx)(`div`,{className:`ib-line ib-line-call`,children:(0,A.jsx)(`span`,{className:`ib-call`,children:e.text})}):(0,A.jsx)(`div`,{className:e.kind===`out`?`ib-line ib-line-out`:`ib-line`,children:(0,A.jsxs)(`span`,{className:e.kind===`out`?`ib-bubble ib-bubble-out`:`ib-bubble`,children:[e.text,(0,A.jsx)(`span`,{className:`ib-time`,children:Zh(e.at).slice(0,5)})]})})]},`${e.call}-${String(r)}`)})})}function MC(e){let t=new Map;for(let n of e)!t.has(n)&&zv(n)&&t.set(n,tf(Pv[n],{io:`input`}));return t}function NC(e,t){return e==null?`null`:typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?JSON.stringify(e):typeof e==`number`?LC(e,t):Array.isArray(e)?`[${e.map(e=>NC(e,t?.items)).join(`,`)}]`:FC(e,t)}function PC(e,t){return typeof e==`string`?e:NC(e,t)}function FC(e,t){let n=IC(e,t)?.properties;return`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${NC(t,n?.[e])}`).join(`,`)}}`}function IC(e,t){return t?.oneOf===void 0?t:t.oneOf.find(t=>Object.entries(t.properties??{}).every(([t,n])=>n.const===void 0||n.const===e[t]))}function LC(e,t){if(t?.type!==`number`||!Number.isFinite(e))return String(e);let n=Math.abs(e);return e!==0&&(n<1e-4||n>=0x2386f26fc10000)?RC(e):Number.isInteger(e)?`${e}.0`:String(e)}function RC(e){let[t=``,n=``]=e.toExponential().split(`e`);return`${t}e${n.startsWith(`-`)?`-`:`+`}${n.replace(/^[+-]/,``).padStart(2,`0`)}`}var zC=[`transcription_delay`,`end_of_turn_delay`],BC=[`llm_node_ttft`,`tts_node_ttfb`,`e2e_latency`],VC=[...zC,...BC];function HC(e){return QC(e).map(([e,t])=>({field:e,value:GC(t),unit:null}))}function UC(e,t){return KC(e,``,t)}function WC(){let e=tf(C_,{io:`input`}),t=new Map;for(let[n,r]of Object.entries(e.properties??{}))r.items!==void 0&&t.set(n,r.items);return t}function GC(e){return e<0?`—`:e<1?`${Math.round(e*1e3)} ms`:`${e.toFixed(2)} s`}function KC(e,t,n){let r=[];for(let[i,a]of Object.entries(e)){let e=t+i,o=n?.properties?.[i];a!=null&&(typeof a==`object`&&!Array.isArray(a)?r.push(...KC(a,`${e}.`,o)):r.push({field:e,value:PC(a,o),unit:qC(i)}))}return r}function qC(e){return Cy[e]??null}function JC(e,t){let n=WC(),r=[];for(let[i,a]of Object.entries(e))for(let e of a)ZC(e,t)&&r.push({kind:i,readings:UC(e,n.get(i))});return r}var YC=[`turn.user`,`turn.agent`];function XC(e){let t=$C(e);return VC.filter(e=>(t.get(e)??[]).length>0).map(e=>{let n=t.get(e)??[];return{name:e,seconds:ew(n),max:Math.max(...n),turns:n.length}})}function ZC(e,t){return`speech_id`in e&&e.speech_id===t}function QC(e){let t=e.role===`user`?zC:BC,n=e.metrics,r=[];for(let e of t){let t=n[e];typeof t==`number`&&r.push([e,t])}return r}function $C(e){let t=new Map(VC.map(e=>[e,[]]));for(let n of e){if(!YC.includes(n.type))continue;let e=n.data.metrics;for(let n of VC){let r=e?.[n];typeof r==`number`&&t.get(n)?.push(r)}}return t}function ew(e){let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2),r=t[n]??0;return t.length%2==1?r:((t[n-1]??0)+r)/2}function tw(e,t={}){let n=j(),[r,i]=(0,D.useState)(Ty),[a,o]=(0,D.useState)(`connecting`),[s,c]=(0,D.useState)(null),l=(0,D.useRef)(t);return(0,D.useEffect)(()=>{l.current=t}),(0,D.useEffect)(()=>{let t={current:Ty()},r=!1,a=null,s=()=>i({...t.current}),u=()=>{r=!0,a?.()};return(async()=>{let i=0;try{i=await nw(n,e,t,l)}catch(e){c(String(e)),o(`ended`);return}if(!r){if(s(),t.current.status===`ended`){o(`ended`);return}a=Uy(la(n,`/v1/calls/${e}/events`,{after:i}),n,{onEntry(e){t.current=Oy(t.current,e),l.current.onEntry?.(e),rw(e,t.current,l.current),e.type===`call.score`&&(s(),o(`ended`),u())},onPaint:s,onConnection:o,onRefused:c}),r&&a()}})(),u},[e,n]),{state:r,connection:a,error:s}}async function nw(e,t,n,r){let i;try{i=await xC(e,t)}catch(e){if(e instanceof na&&e.status===404)return 0;throw e}for(let e of i)n.current=Oy(n.current,e),r.current.onEntry?.(e),rw(e,n.current,r.current);return i.at(-1)?.seq??0}function rw(e,t,n){if(e.type!==`custom`)return;let r=t.custom.at(-1);r!==void 0&&n.onCustom?.(r)}function iw(e){let t=(0,D.useRef)([]),n=tw(e,{onEntry(e){let n=t.current.at(-1);n!==void 0&&e.seq<=n.seq||t.current.push(e)}}),r=(0,D.useMemo)(()=>[...t.current],[n.state.seq]);return{state:n.state,entries:r,connection:n.connection,error:n.error}}function aw({agent:e,call:t}){let{lines:n}=Zy(),r=n.find(t=>t.agent===e)?.call??null,i=t??r;return(0,A.jsx)(`aside`,{className:`inspector`,"aria-label":`Inspector`,children:i===null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(ow,{connection:null}),(0,A.jsx)(`p`,{className:`inspector-quiet`,children:`Nothing to read yet: the first call this agent takes is read here as it happens.`})]}):(0,A.jsx)(cw,{call:i,yours:t!==null},i)})}function ow({connection:e}){return(0,A.jsxs)(`div`,{className:`inspector-head`,children:[(0,A.jsx)(`span`,{className:`inspector-title`,children:`Inspector`}),(0,A.jsx)(`span`,{className:`inspector-standing`,children:sw(e)})]})}function sw(e){switch(e){case`live`:return(0,A.jsx)(Qm,{tone:`green`,children:`reading the log`});case`connecting`:return(0,A.jsx)(Qm,{tone:`muted`,children:`opening the log`});case`reconnecting`:return(0,A.jsx)(Qm,{tone:`amber`,children:`reconnecting`});case`ended`:return(0,A.jsx)(Qm,{tone:`muted`,children:`call ended`});default:return(0,A.jsx)(Qm,{tone:`muted`,children:`no call yet`})}}function cw({call:e,yours:t}){let[n,r]=(0,D.useState)(`call`),i=iw(e),{state:a}=i,o=new Set,s=XC(i.entries.filter(e=>!o.has(e.seq)&&(o.add(e.seq),!0))),c=e=>{let t=s.find(t=>t.name===e);return t===void 0?`—`:GC(t.seconds)},l=uw(a),u=[[`Turns`,String(a.turns.length)],[`ttft`,c(`llm_node_ttft`)],[`e2e`,c(`e2e_latency`)],[`Cost`,Yh(a.cost?.eur)],[`Tokens in`,dw(l.in)],[`Tokens out`,dw(l.out)]],d=Object.keys(a.app_state).sort(),f=[{tab:`call`,name:`Call`},{tab:`turns`,name:`Turns`,mark:(0,A.jsx)(`span`,{className:`inspector-count`,children:a.turns.length})},{tab:`tools`,name:`Tools`,mark:(0,A.jsx)(`span`,{className:`inspector-count`,children:a.tools.length})},{tab:`state`,name:`State`}];return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(ow,{connection:i.connection}),(0,A.jsx)(`div`,{className:`inspector-tabs`,children:(0,A.jsx)(yh,{label:`Inspector`,tabs:f,on:n,onPick:r})}),n===`call`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{children:t?`This session`:`Last session`}),(0,A.jsx)(`div`,{className:`inspector-figures`,children:u.map(([e,t])=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`inspector-figure-label`,children:e}),(0,A.jsx)(`div`,{className:`inspector-figure`,children:t})]},e))}),!t&&(0,A.jsx)(`p`,{className:`inspector-call`,children:e})]}),n===`turns`&&(0,A.jsxs)(`div`,{className:`inspector-turns`,children:[a.turns.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`No turn yet.`}),a.turns.map((e,t)=>(0,A.jsxs)(`div`,{className:`inspector-turn`,children:[(0,A.jsx)(`span`,{className:e.role===`agent`?`inspector-who inspector-who-agent`:`inspector-who`,children:e.role===`agent`?`agent`:`caller`}),(0,A.jsxs)(`span`,{className:`inspector-turn-body`,children:[(0,A.jsx)(`span`,{className:`inspector-turn-text`,children:e.text}),(0,A.jsx)(`span`,{className:`inspector-turn-meta`,children:lw(e)})]})]},`${e.speech_id}-${t}`))]}),n===`tools`&&(0,A.jsxs)(`div`,{className:`inspector-tools`,children:[a.tools.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`No tool has run.`}),a.tools.map(e=>(0,A.jsxs)(`div`,{className:`inspector-tool`,children:[(0,A.jsx)(`div`,{className:`inspector-tool-name`,children:e.name}),(0,A.jsx)(`div`,{className:`inspector-tool-args`,children:fw(e.arguments)}),(0,A.jsx)(`div`,{className:e.status===`failed`?`inspector-tool-result inspector-tool-failed`:e.status===`running`?`inspector-tool-result inspector-tool-running`:`inspector-tool-result`,children:e.status===`failed`?e.error??`failed`:e.status===`running`?`running…`:`ok${e.summary?` · ${e.summary}`:``}`})]},e.call_id))]}),n===`state`&&(0,A.jsxs)(`div`,{className:`inspector-state`,children:[d.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`The app has declared no state yet.`}),d.map(e=>(0,A.jsxs)(`div`,{className:`inspector-field`,children:[(0,A.jsx)(`span`,{className:`inspector-field-key`,children:e}),(0,A.jsx)(`span`,{className:`inspector-field-value`,children:pw(a.app_state[e])})]},e))]}),i.error!==null&&(0,A.jsx)(`p`,{className:`inspector-refused`,children:i.error})]})}function lw(e){if(e.role===`agent`){let t=[];return typeof e.metrics.llm_node_ttft==`number`&&t.push(`ttft ${GC(e.metrics.llm_node_ttft)}`),typeof e.metrics.e2e_latency==`number`&&t.push(`e2e ${GC(e.metrics.e2e_latency)}`),e.interrupted&&t.push(`interrupted`),t.join(` · `)}let t=[];return typeof e.metrics.transcription_delay==`number`&&t.push(`stt ${GC(e.metrics.transcription_delay)}`),t.push(e.speech_id),t.join(` · `)}function uw(e){let t=0,n=0;for(let r of e.usage)r.type===`llm_usage`&&(t+=(r.input_tokens??0)+(r.input_cached_tokens??0),n+=r.output_tokens??0);return{in:t,out:n}}function dw(e){return e.toLocaleString(`en-US`).replace(/,/g,` `)}function fw(e){let t=Object.entries(e).map(([e,t])=>`${e}=${pw(t)}`);return t.length===0?`no arguments`:t.join(` · `)}function pw(e){return typeof e==`string`?e:JSON.stringify(e)}var mw=`supervisor.`;function hw(e){if(!e.type.startsWith(mw))return null;let t=Rv(e);switch(t.type){case`supervisor.whispered`:return{said:`supervisor whispered: ${t.data.text}`,by:gw(t.data.by)};case`supervisor.said`:return{said:`supervisor made the agent say: ${t.data.text}`,by:gw(t.data.by)};case`supervisor.took_over`:return{said:`supervisor took the line`,by:gw(t.data.by)};case`supervisor.released`:return{said:`supervisor handed the line back`,by:gw(t.data.by)};case`supervisor.transferred`:return{said:`supervisor transferred the call to ${t.data.to}`,by:gw(t.data.by)};case`supervisor.ended`:return{said:`supervisor ended the call${_w(t.data.reason)}`,by:gw(t.data.by)};default:return null}}function gw(e){return e.name??e.id}function _w(e){return e==null?``:`: ${e}`}function vw(e,t){let n=[],r=[],i=()=>{r.length>0&&(n.push({kind:`quiet`,seq:r[0]?.seq??0,entries:r}),r=[])};for(let a of e){let e=yw(a,t);if(e===null){r.push(a);continue}i(),n.push(e)}return i(),n}function yw(e,t){let n=e.seq,r=hw(e);if(r!==null)return{kind:`supervisor`,seq:n,mark:r};let i=Rv(e);switch(i.type){case`turn.user`:case`turn.agent`:{let e=bw(t,i.type===`turn.user`?`user`:`agent`,i.data.speech_id);return e===void 0?null:{kind:`turn`,seq:n,turn:e}}case`tool.call`:{let e=xw(t.tools,e=>e.call_id===i.data.call_id);return e===void 0?null:{kind:`tool`,seq:n,run:e}}case`state.changed`:return{kind:`state`,seq:n,changed:i.data.changed,cause:i.data.cause??null};case`confirm.request`:{let e=xw(t.confirms,e=>e.call_id===i.data.call_id);return e===void 0?null:{kind:`confirm`,seq:n,confirm:e}}case`event.received`:return{kind:`event`,seq:n,name:i.data.name,source:i.data.source,data:i.data.data};case`memory.ops`:return{kind:`memory`,seq:n,ops:i.data};case`docs.sources`:return{kind:`sources`,seq:n,sources:i.data};default:return null}}function bw(e,t,n){return xw(e.turns,e=>e.role===t&&e.speech_id===n)}function xw(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(t(r))return r}}function Sw(e){let t=new Map,n=new Set;for(let r of e)if(r.type===`agent.transcript`){let e=r.data;if(e.final)continue;t.set(e.speech_id,(t.get(e.speech_id)??``)+e.text)}else r.type===`turn.agent`&&n.add(r.data.speech_id);return{streaming:t,settled:n}}var Cw=new Map,ww=1,Tw=.18;function Ew(e,t,n){let[r,i]=(0,D.useState)(()=>n?t.length:Cw.get(e)??0),a=(0,D.useRef)(t.length);return a.current=t.length,(0,D.useEffect)(()=>{if(n){Cw.set(e,t.length),i(t.length);return}let r=0,o=()=>{i(t=>{let n=a.current-t;if(n<=0)return t;let r=Math.min(a.current,t+Math.max(ww,Math.ceil(n*Tw)));return Cw.set(e,r),r}),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>cancelAnimationFrame(r)},[e,n,t.length]),t.slice(0,Math.min(r,t.length))}var Dw=80;function Ow({watched:e,pending:t,onConfirmed:n}){let r=Aw(e.entries),i=vw(r,e.state),{streaming:a,settled:o}=Sw(r),s=(0,D.useRef)(null),c=(0,D.useRef)(!0),[l]=(0,D.useState)(()=>performance.now()),[u,d]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let e=window.setTimeout(()=>d(!0),600);return()=>window.clearTimeout(e)},[l]);let f=i.filter(e=>e.kind===`turn`&&e.turn.role===`user`).length;(0,D.useEffect)(()=>{let e=[...i].reverse().find(e=>e.kind===`turn`&&e.turn.role===`user`);e?.kind===`turn`&&n(e.turn.text)},[f]);let p=[...a.entries()].filter(([e])=>!o.has(e)),m=e.state.agent_state===`thinking`&&p.length===0;return(0,D.useLayoutEffect)(()=>{let e=s.current;e!==null&&c.current&&(e.scrollTop=e.scrollHeight)}),(0,A.jsxs)(`div`,{className:`chat-lines`,ref:s,onScroll:e=>{let t=e.currentTarget;c.current=t.scrollHeight-t.scrollTop-t.clientHeight<Dw},children:[i.map(e=>{if(e.kind===`turn`){let t=e.turn.speech_id??`seq-${String(e.seq)}`;return e.turn.role===`agent`?(0,A.jsx)(kw,{speech:t,text:e.turn.text,instant:!u,done:!0},`turn-${String(e.seq)}`):(0,A.jsx)(`div`,{className:`chat-line chat-line-user`,children:(0,A.jsx)(`span`,{className:`chat-bubble chat-bubble-you`,children:e.turn.text})},`turn-${String(e.seq)}`)}return e.kind===`tool`?(0,A.jsx)(`div`,{className:`chat-line chat-line-tool`,children:(0,A.jsxs)(`span`,{className:`chat-tool chat-tool-${e.run.status}`,children:[e.run.name,` · `,e.run.error??e.run.summary??(e.run.status===`running`?`running…`:`done`)]})},`tool-${String(e.seq)}`):null}),p.map(([e,t])=>(0,A.jsx)(kw,{speech:e,text:t,instant:!1,done:!1},`writing-${e}`)),t.map(e=>(0,A.jsx)(`div`,{className:`chat-line chat-line-user chat-line-pending`,children:(0,A.jsx)(`span`,{className:`chat-bubble chat-bubble-you`,children:e.text})},`pending-${String(e.id)}`)),m&&(0,A.jsx)(`div`,{className:`chat-line chat-line-agent`,children:(0,A.jsxs)(`span`,{className:`chat-bubble chat-typing`,"aria-label":`the agent is writing`,children:[(0,A.jsx)(`i`,{}),(0,A.jsx)(`i`,{}),(0,A.jsx)(`i`,{})]})}),e.error!==null&&(0,A.jsx)(`p`,{className:`chat-error`,children:e.error})]})}function kw({speech:e,text:t,instant:n,done:r}){let i=Ew(e,t,n),a=i.length>=t.length;return(0,A.jsx)(`div`,{className:`chat-line chat-line-agent`,children:(0,A.jsxs)(`span`,{className:`chat-bubble`,children:[i,!(r&&a)&&(0,A.jsx)(`span`,{className:`chat-caret`,"aria-hidden":!0})]})})}function Aw(e){let t=new Set;return e.filter(e=>!t.has(e.seq)&&(t.add(e.seq),!0))}var jw=z({agent:P().nullable(),states:R(P())}),Mw=z({call:P()});async function Nw(e,t){return jw.parse(await eC(e,t,`chat.roster`))}async function Pw(e,t,n,r){let i={agent:t,...n===``?{}:{as:n},...r===``?{}:{golden:r}};return Mw.parse(await eC(e,t,`chat.start`,i)).call}async function Fw(e,t,n,r){Mw.parse(await eC(e,t,`chat.say`,{call:n,text:r}))}async function Iw(e,t,n){Mw.parse(await eC(e,t,`chat.end`,{call:n}))}function Lw(){let e=Sr(),t=e.agent??``,n=e.call;return(0,A.jsxs)(`div`,{className:`chat-grid`,children:[(0,A.jsx)(`div`,{className:`chat-column`,children:n===void 0?(0,A.jsx)(zw,{agent:t}):(0,A.jsx)(Bw,{agent:t,call:n})}),(0,A.jsx)(aw,{agent:t,call:n??null})]})}function Rw({agent:e,children:t}){return(0,A.jsxs)(`div`,{className:`chat-head`,children:[(0,A.jsxs)(`div`,{className:`chat-head-words`,children:[(0,A.jsxs)(`div`,{className:`chat-title`,children:[`Chat with `,e]}),(0,A.jsx)(`div`,{className:`chat-sub`,children:`The same agent, typed instead of spoken — every turn still lands in the log.`})]}),t]})}function zw({agent:e}){let t=j(),n=vr(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let n=!1;return Nw(t,e).then(e=>{n||i(e)},e=>{n||u(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[t,e]);let p=async r=>{r.preventDefault(),f(!0),u(null);try{n(`/a/${e}/dev-chat/${await Pw(t,e,a.trim(),s)}`)}catch(e){u(e instanceof na?e.message:String(e))}finally{f(!1)}};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Rw,{agent:e}),(0,A.jsx)(`div`,{className:`chat-lines`,children:(0,A.jsxs)(`div`,{className:`chat-start ui-card`,children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Start a conversation`})}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[r===null&&l===null&&(0,A.jsxs)(`p`,{className:`chat-note`,children:[`Asking the terminal that holds `,e,`…`]}),r!==null&&r.agent!==e&&(0,A.jsx)(`p`,{className:`chat-note`,children:r.agent===null?"No agent class in the directory this agent's `pinecall start` runs in, so there is nothing to chat with. Run `pinecall start` where its agent.tsx is.":`The process holding the agent runs in ${r.agent}'s directory: to chat with ${e}, run \`pinecall start\` there.`}),r!==null&&r.agent===e&&(0,A.jsxs)(`form`,{className:`chat-start-form`,onSubmit:e=>void p(e),children:[(0,A.jsx)(`p`,{className:`chat-note`,children:`The class of this directory, in writing. Its tools run in the terminal that serves this page, and a conversation can open part-way through, in the state one of the goldens declares.`}),(0,A.jsx)(Wm,{label:`As`,children:(0,A.jsx)(W,{value:a,placeholder:`a phone number, a customer id — or nobody`,onChange:e=>o(e.target.value)})}),r.states.length>0&&(0,A.jsx)(Wm,{label:`From`,children:(0,A.jsxs)(Hm,{value:s,onChange:e=>c(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the call's own opening`}),r.states.map(e=>(0,A.jsxs)(`option`,{value:e,children:[`the state of `,e]},e))]})}),(0,A.jsx)(`div`,{children:(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:d,children:d?`Opening…`:`Start the chat`})})]}),(0,A.jsx)(Nm,{children:l})]})]})})]})}function Bw({agent:e,call:t}){let n=j(),r=vr(),[i,a]=(0,D.useState)([]),[o,s]=(0,D.useState)(null),c=(0,D.useRef)(0),l=iw(t),u=l.state.status===`ended`||l.connection===`ended`,d=async()=>{try{await Iw(n,e,t)}catch(e){s(e instanceof na?e.message:String(e));return}r(`/a/${e}/sessions/${t}`)};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Rw,{agent:e,children:(0,A.jsxs)(`div`,{className:`chat-head-actions`,children:[(0,A.jsx)(Wi,{className:`chat-whole`,to:`/a/${e}/sessions/${t}`,children:`Session`}),!u&&(0,A.jsx)(U,{size:`md`,onClick:()=>void d(),title:`hanging up seals the log and runs the judges`,children:`Hang up`})]})}),(0,A.jsx)(Ow,{watched:l,pending:i,onConfirmed:e=>a(t=>{let n=t.findIndex(t=>t.text===e);return n===-1?t:[...t.slice(0,n),...t.slice(n+1)]})}),o!==null&&(0,A.jsx)(`div`,{className:`chat-refused`,children:(0,A.jsx)(Nm,{children:o})}),u?(0,A.jsx)(`div`,{className:`chat-over`,children:`This chat has ended — it is on the session, whole.`}):(0,A.jsx)(Vw,{agent:e,call:t,onRefused:s,onSent:e=>{c.current+=1;let t={id:c.current,text:e};return a(e=>[...e,t]),()=>a(e=>e.filter(e=>e.id!==t.id))}})]})}function Vw({agent:e,call:t,onSent:n,onRefused:r}){let i=j(),[a,o]=(0,D.useState)(``),s=async s=>{s.preventDefault();let c=a.trim();if(c===``)return;o(``),r(null);let l=n(c);try{await Fw(i,e,t,c)}catch(e){l(),o(c),r(e instanceof na?e.message:String(e))}};return(0,A.jsxs)(`form`,{className:`chat-composer`,onSubmit:e=>void s(e),children:[(0,A.jsx)(`input`,{className:`chat-say`,value:a,autoFocus:!0,placeholder:`Ask the agent something`,onChange:e=>o(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`chat-send`,disabled:a.trim()===``,children:`Send`})]})}var Hw=z({golden:P(),model:P(),call:P()}),Uw=z({metric:P(),score:F(),passed:L(),reason:P(),criteria:P(),judge_calls:I()}),Ww=z({model:P(),golden:P(),scores:R(Uw),summary:fp(P(),Zf()).nullable()}),Gw=z({models:R(P()),goldens:R(P()),metrics:R(P()),judge_calls:I(),runs:R(Ww),failures:R(z({model:P(),golden:P(),metric:P()}))}),Kw=z({runs:R(z({id:P(),agent:P(),started_at:F(),finished_at:F().nullable(),status:mp([`running`,`done`,`failed`]),calls:R(Hw),matrix:Gw.nullable(),error:P().nullable()}))}),qw=200;async function Jw(e){return Kw.parse(await k(e,`/v1/evals/runs`,{limit:qw})).runs}async function Yw(e,t){return Kw.parse(await k(e,`/v1/evals/runs`,{agent:t,limit:qw})).runs}var Xw=z({held:I(),settled:I(),percent:F()}),Zw=z({judge:P(),before:Xw.nullable(),now:Xw.nullable(),delta:F().nullable()}),Qw=z({call:P(),judge:P(),seqs:R(I()),reason:P()}),$w=z({agent:P(),window:F(),baseline:F(),threshold:F(),drift:z({judges:R(Zw),notJudged:z({now:I(),before:I()}),broke:R(Qw),worst:F().nullable()})});async function eT(e,t,n,r){return $w.parse(await eC(e,t,`drift.read`,{agent:t,window:n,baseline:r}))}var tT=z({check:P(),status:P(),detail:P()}),nT=z({call:P(),agent:P(),passed:L(),verdicts:R(tT)});async function rT(e,t){return nT.parse(await sa(e,`/v1/evals/replay/${encodeURIComponent(t)}`,{}))}var iT=z({path:P(),candidate:z({name:P(),input:R(P())}),notes:R(P())});async function aT(e,t,n){return iT.parse(await eC(e,t,`promote.write`,{call:n}))}var oT=z({run:P(),folder:P(),goldens:R(P())}),sT=z({run:P(),agent:P(),golden:P(),model:P(),call:P(),declared:Zf(),verdicts:R(z({metric:P(),passed:L(),criteria:P(),reason:P()})),asked:Zf()});async function cT(e,t,n){return oT.parse(await eC(e,t,`reproductions.roster`,{run:n}))}async function lT(e,t,n,r){return sT.parse(await eC(e,t,`reproductions.read`,{run:n,golden:r}))}var uT=`minmax(0,1.2fr) minmax(0,1.3fr) 90px minmax(0,1fr) 80px`,dT=`minmax(0,1fr) 150px 70px minmax(0,2fr) 90px`;function fT(){let e=j(),{agents:t,lines:n}=Zy(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return Jw(e).then(e=>{t||i(e)},e=>{t||(i([]),o(e instanceof na?e.message:String(e)))}),()=>{t=!0}},[e]);let s=n.filter(e=>e.score!=null),c=s.filter(e=>e.score?.passed===!1),l=[...new Set([...t.map(e=>e.slug),...(r??[]).map(e=>e.agent),...s.map(e=>e.agent)])].sort().map(e=>pT(e,r??[],s)),u=s.length-c.length,d=l.filter(e=>e.suite!==null),f=d.filter(e=>e.suite!==null&&e.suite.held===e.suite.cells).length;return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Evals`,lede:`How every agent is doing: the suites run on purpose, and the real calls judged at hang-up.`}),(0,A.jsx)(Nm,{children:a}),(0,A.jsxs)(lh,{min:170,children:[(0,A.jsx)(uh,{size:`small`,label:`Calls judged`,value:s.length,of:`of the last ${n.length}`}),(0,A.jsx)(uh,{size:`small`,label:`Held`,value:s.length===0?`—`:ag(u/s.length),accent:!0}),(0,A.jsx)(uh,{size:`small`,label:`Did not hold`,value:c.length}),(0,A.jsx)(uh,{size:`small`,label:`Suites green`,value:d.length===0?`—`:`${f} of ${d.length}`})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`By agent`,meta:`a row opens that agent's Evals: its goldens, its runs, its drift`}),l.length===0?(0,A.jsx)(Mm,{children:`No agent is held here yet.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:uT,labels:[`Agent`,`Last suite`,`Judged`,`Held on real calls`,``]}),l.map(e=>(0,A.jsxs)(fh,{columns:uT,to:`/a/${e.slug}/evals`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.slug}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.suite===null?(0,A.jsx)(`span`,{className:`oev-none`,children:`no suite run in this world`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(Qm,{tone:e.suite.held===e.suite.cells?`green`:`red`,children:[e.suite.held,`/`,e.suite.cells]}),` `,(0,A.jsx)(`span`,{className:`oev-when`,children:eg(e.suite.at)})]})}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.judged}),(0,A.jsx)(`span`,{className:`oev-held`,children:e.judged===0?(0,A.jsx)(`span`,{className:`oev-none`,children:`nothing judged yet`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(oh,{share:e.held/e.judged}),(0,A.jsx)(`span`,{className:`oev-share`,children:ag(e.held/e.judged)})]})}),(0,A.jsx)(`span`,{className:`ui-cell-end oev-open`,children:`Open →`})]},e.slug))]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Calls that did not hold`,meta:`a judge answered broken — the reason is the judge's own`}),c.length===0?(0,A.jsx)(Mm,{children:s.length===0?`No call has been judged yet. Judging is turned on from Home.`:`Every judged call held.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:dT,labels:[`Caller`,`Agent`,`Score`,`Why`,`When>`]}),c.slice(0,40).map(e=>(0,A.jsxs)(fh,{columns:dT,to:`/sessions/${e.call}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:sg(e)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(`span`,{className:`ui-cell`,children:(0,A.jsxs)(Qm,{tone:`red`,children:[e.score?.held,`/`,e.score?.judged]})}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.score?.reason??`—`}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-cell-end`,children:eg(e.started_at)})]},e.call))]})]})]})}function pT(e,t,n){let r=t.find(t=>t.agent===e&&t.status===`done`&&t.matrix!==null),i=r?.matrix??null,a=n.filter(t=>t.agent===e);return{slug:e,suite:r===void 0||i===null?null:{at:r.started_at,cells:i.runs.length,held:i.runs.filter(e=>e.scores.every(e=>e.passed)).length,failing:[...new Set(i.failures.map(e=>e.golden))]},judged:a.length,held:a.filter(e=>e.score?.passed===!0).length}}var mT=z({agent:P().nullable(),golden:P().nullable(),questions:I(),cases:R(P())});async function hT(e,t){return oy.parse(await k(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function gT(e,t){return sy.parse(await ca(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function _T(e,t){return mT.parse(await eC(e,t,`memory.roster`,{agent:t}))}async function vT(e,t){return ly.parse(await eC(e,t,`memory.eval`,{agent:t}))}async function yT(e,t){return py.parse(await eC(e,t,`memory.extraction`,{agent:t}))}var bT=z({facts:R(z({id:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:ip([P(),F()]).nullish()});async function xT(e,t){try{return bT.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/memory`)).facts}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}async function ST(e,t){await ca(e,`/v1/memory/facts/${encodeURIComponent(t)}`)}var CT=z({facts:R(z({id:P(),agent:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:P().nullish()});async function wT(e,t,n){let r={};t!==``&&(r.q=t),n!==null&&(r.after=n);try{return CT.parse(await k(e,`/v1/memory`,r))}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}var TT=`150px 140px minmax(0,1fr) 100px 64px`;function ET(e){return e.startsWith(`+`)?og(e):e}function DT(e){return e instanceof Error?e.message:String(e)}function OT(){let e=j(),[t,n]=(0,D.useState)(``),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(void 0),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=window.setTimeout(()=>i(t.trim()),300);return()=>window.clearTimeout(e)},[t]),(0,D.useEffect)(()=>{let t=!1;return u(null),wT(e,r,null).then(e=>{t||(o(e===null?null:e.facts),c(e?.next??null))},e=>{t||u(DT(e))}),()=>{t=!0}},[e,r]);let d=async()=>{if(s!==null)try{let t=await wT(e,r,s);if(t===null)return;o(e=>[...e??[],...t.facts]),c(t.next??null)}catch(e){u(DT(e))}},f=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${ET(t.contact)} stays.`)){u(null);try{await ST(e,t.id),o(e=>(e??[]).filter(e=>e.id!==t.id))}catch(e){u(DT(e))}}};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Memory`,ledeWidth:640,lede:`What every agent carries between calls with the same caller — newest first, each fact with the agent whose call taught it, droppable one row at a time.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Remembered`,meta:a?`${a.length}${s===null?``:`+`} facts`:void 0,children:(0,A.jsx)(`div`,{className:`mem-look`,children:(0,A.jsx)(W,{size:`sm`,value:t,placeholder:`Search a caller, a word, a category`,onChange:e=>n(e.target.value)})})}),a===void 0?(0,A.jsx)(Mm,{children:`Asking the gateway what the agents remember…`}):a===null?(0,A.jsx)(Mm,{children:`This gateway keeps no memory: it runs without the database memory lives in.`}):a.length===0?(0,A.jsx)(Mm,{children:r===``?"No agent remembers anything about any caller yet. An agent that declares `memory` writes what it learns when a call hangs up.":`Nothing remembered matches.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:TT,labels:[`Caller`,`Agent`,`Remembered`,`Written`,`Action>`]}),a.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:TT},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:ET(e.contact)}),(0,A.jsx)(`span`,{className:`ui-clip`,children:(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e.agent)}/memory`,children:e.agent})}),(0,A.jsxs)(`span`,{className:`mem-fact`,children:[e.text,e.category?(0,A.jsxs)(`span`,{className:`mem-superseded`,children:[` · `,e.category]}):null]}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:$h(e.written_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void f(e),children:`Drop`})})]},e.id)),s!==null&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:(0,A.jsx)(U,{size:`sm`,onClick:()=>void d(),children:`Load more`})})]})]}),(0,A.jsx)(Nm,{children:l})]})}async function kT(e){let[t,n]=await Promise.all([ay.parse(await k(e,`/v1/knowledge`)),Sy.parse(await k(e,`/v1/knowledge/attached`))]),r=new Map(n.bases.map(e=>[e.base,e.agents]));return t.bases.map(e=>({...e,agents:r.get(e.base)??[]}))}var AT=`minmax(0,1fr) 90px 140px 150px minmax(0,1fr)`;function jT(e){return e instanceof Error?e.message:String(e)}function MT(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return kT(e).then(e=>{t||n(e)},e=>{t||i(jT(e))}),()=>{t=!0}},[e]),(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Docs`,ledeWidth:640,lede:"Every base pushed in this world, and which agents search it. A base is pushed from a project's docs/ folder (`pinecall docs push`) and attached to an agent in its Settings."}),(0,A.jsx)(Nm,{children:r}),(0,A.jsx)(V,{children:t===null?(0,A.jsx)(Mm,{children:r===null?`Asking the gateway…`:`The bases could not be read.`}):t.length===0?(0,A.jsx)(Mm,{children:"No base pushed yet. `pinecall docs push` from a project sends its folder here."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:AT,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,`Read by`]}),t.map(e=>(0,A.jsxs)(fh,{columns:AT,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.base}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.model}),(0,A.jsx)(`span`,{className:`ui-cell`,children:Qh(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.agents.length===0?`nobody`:e.agents.map((e,t)=>(0,A.jsxs)(`span`,{children:[t>0&&`, `,(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e)}/settings`,children:e})]},e))})]},e.base))]})})]})}var NT=`lk.transcription`,PT=`lk.transcription_final`,FT=`lk.chat`,IT=1500,LT=`→`,RT=`←`,zT=`✗`;function BT(e,t){let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[...e,t];let r=e.slice();return r[n]=t,r}function VT(e){return e.split(/(\s+)/).filter(e=>e.length>0)}function HT(e){let t=hw(e);if(t!==null)return{kind:`mark`,id:`mark-${e.seq}`,tone:`supervisor`,text:t.said};let n=e.data;switch(e.type){case`tool.call`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${LT} ${String(n.name)}(${WT(n.arguments)})`};case`tool.result`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${RT} ${String(n.name)} ${UT(n)}`};case`error`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`error`,text:`${zT} ${String(n.message)}`};default:return null}}function UT(e){return e.error!==void 0&&e.error!==null?`error: ${WT(e.error)}`:typeof e.summary==`string`?e.summary:e.output===void 0?`nothing`:WT(e.output)}function WT(e,t=80){let n=typeof e==`string`?e:JSON.stringify(e)??String(e);return n.length>t?`${n.slice(0,t-1)}…`:n}function GT({lines:e,mode:t,children:n}){let r=(0,D.useRef)(null);return(0,D.useEffect)(()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight)},[e]),(0,A.jsxs)(`div`,{className:t===`chat`?`talk-whole`:`ui-card`,children:[t===`talk`&&(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`This call`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`spoken or written, as the room says it`})]}),(0,A.jsxs)(`div`,{className:`talk-lines`,ref:r,children:[e.length===0&&(0,A.jsxs)(`p`,{className:`talk-quiet`,children:[`Nothing said yet. `,t===`talk`?`What you say and what you write both land here.`:`What you write and the agent's replies land here.`]}),e.map(e=>e.kind===`said`?(0,A.jsx)(KT,{line:e},e.id):(0,A.jsx)(qT,{mark:e},e.id))]}),n]})}function KT({line:e}){return(0,A.jsx)(`div`,{className:e.speaker===`user`?`talk-said talk-said-you`:`talk-said`,children:(0,A.jsxs)(`p`,{className:`talk-bubble${e.speaker===`user`?` talk-bubble-you`:``}${!e.final||e.pending===!0?` talk-bubble-unsettled`:``}`,children:[VT(e.text).map((e,t)=>(0,A.jsx)(`span`,{className:`talk-word`,children:e},t)),!e.final&&(0,A.jsx)(`span`,{className:`talk-cursor`,"aria-hidden":!0})]})})}function qT({mark:e}){return(0,A.jsx)(`p`,{className:`talk-mark talk-mark-${e.tone}`,children:e.text})}function JT({open:e,mode:t,onWrite:n}){let[r,i]=(0,D.useState)(``);return(0,A.jsxs)(`form`,{className:`talk-composer`,onSubmit:t=>{t.preventDefault();let a=r.trim();a!==``&&e&&(i(``),n(a))},children:[(0,A.jsx)(`input`,{className:`talk-write`,value:r,disabled:!e,placeholder:e?t===`talk`?`Write to the agent — or just speak`:`Write to the agent`:t===`talk`?`Press Call first — then speak or write`:`Press Chat first — then write`,onChange:e=>i(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`talk-send`,disabled:!e||r.trim()===``,children:`Send`})]})}function YT(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var XT=Object.defineProperty,ZT=(e,t,n)=>t in e?XT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,QT=(e,t,n)=>ZT(e,typeof t==`symbol`?t:t+``,n),$T=class{constructor(){QT(this,`_locking`),QT(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function eE(e,t){if(!e)throw Error(t)}var tE=34028234663852886e22,nE=-34028234663852886e22,rE=4294967295,iE=2147483647,aE=-2147483648;function oE(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>iE||e<aE)throw Error(`invalid int 32: `+e)}function sE(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>rE||e<0)throw Error(`invalid uint 32: `+e)}function cE(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>tE||e<nE))throw Error(`invalid float 32: `+e)}var lE=Symbol(`@bufbuild/protobuf/enum-type`);function uE(e){let t=e[lE];return eE(t,`missing enum type on enum object`),t}function dE(e,t,n,r){e[lE]=fE(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function fE(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=mE(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function pE(e,t,n){let r={};for(let e of t){let t=mE(e);r[t.localName]=t.no,r[t.no]=t.localName}return dE(r,e,t),r}function mE(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var hE=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function gE(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new hE),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function _E(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function vE(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var yE=4294967296;function bE(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=yE&&(i+=r/yE|0,r%=yE)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?TE(r,i):wE(r,i)}function xE(e,t){let n=wE(e,t),r=n.hi&2147483648;r&&(n=TE(n.lo,n.hi));let i=SE(n.lo,n.hi);return r?`-`+i:i}function SE(e,t){var n=CE(e,t);if(e=n.lo,t=n.hi,t<=2097151)return String(yE*t+e);let r=e&16777215,i=(e>>>24|t<<8)&16777215,a=t>>16&65535,o=r+i*6777216+a*6710656,s=i+a*8147497,c=a*2,l=1e7;return o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(c+=Math.floor(s/l),s%=l),c.toString()+EE(s)+EE(o)}function CE(e,t){return{lo:e>>>0,hi:t>>>0}}function wE(e,t){return{lo:e|0,hi:t|0}}function TE(e,t){return t=~t,e?e=~e+1:t+=1,wE(e,t)}var EE=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function DE(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function OE(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function kE(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||{}.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>eE(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>eE(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),bE(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),bE(e)},dec(e,t){return xE(e,t)},uDec(e,t){return SE(e,t)}}}var AE=kE(),G;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(G||={});var jE;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(jE||={});function ME(e,t,n){if(t===n)return!0;if(e==G.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return t==n}return!1}function NE(e,t){switch(e){case G.BOOL:return!1;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return t==0?AE.zero:`0`;case G.DOUBLE:case G.FLOAT:return 0;case G.BYTES:return new Uint8Array;case G.STRING:return``;default:return 0}}function PE(e,t){switch(e){case G.BOOL:return t===!1;case G.STRING:return t===``;case G.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}function FE(e,t){this.v=e,this.k=t}function IE(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function LE(e){if(Array.isArray(e))return e}function RE(e,t,n){return(t=JE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function zE(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function BE(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function VE(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
63
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function UE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?HE(Object(n),!0).forEach(function(t){RE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):HE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function WE(e,t){if(e==null)return{};var n,r,i=GE(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function GE(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function K(e,t){return LE(e)||BE(e,t)||YE(e,t)||VE()}function KE(e){return LE(e)||zE(e)||YE(e)||VE()}function qE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function JE(e){var t=qE(e,`string`);return typeof t==`symbol`?t:t+``}function YE(e,t){if(e){if(typeof e==`string`)return IE(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?IE(e,t):void 0}}function XE(e){return function(){return new ZE(e.apply(this,arguments))}}function ZE(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof FE;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}ZE.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},ZE.prototype.next=function(e){return this._invoke(`next`,e)},ZE.prototype.throw=function(e){return this._invoke(`throw`,e)},ZE.prototype.return=function(e){return this._invoke(`return`,e)};var QE;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(QE||={});var $E=class{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 t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].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 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(sE(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return oE(e),DE(e,this.buf),this}bool(e){return this.buf.push(+!!e),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){cE(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){sE(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){oE(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return oE(e),e=(e<<1^e>>31)>>>0,DE(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=AE.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=AE.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=AE.enc(e);return vE(t.lo,t.hi,this.buf),this}sint64(e){let t=AE.enc(e),n=t.hi>>31;return vE(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=AE.uEnc(e);return vE(t.lo,t.hi,this.buf),this}},eD=class{constructor(e,t){this.varint64=_E,this.uint32=OE,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,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case QE.Varint:for(;this.buf[this.pos++]&128;);break;case QE.Bit64:this.pos+=4;case QE.Bit32:this.pos+=4;break;case QE.LengthDelimited:let n=this.uint32();this.pos+=n;break;case QE.StartGroup:for(;;){let e=K(this.tag(),2),n=e[0],r=e[1];if(r===QE.EndGroup){if(t!==void 0&&n!==t)throw Error(`invalid end group tag`);break}this.skip(r,n)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return AE.dec(...this.varint64())}uint64(){return AE.uDec(...this.varint64())}sint64(){let e=K(this.varint64(),2),t=e[0],n=e[1],r=-(t&1);return t=(t>>>1|(n&1)<<31)^r,n=n>>>1^r,AE.dec(t,n)}bool(){let e=K(this.varint64(),2),t=e[0],n=e[1];return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return AE.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return AE.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 tD(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function nD(e){let t=e.field.localName,n=Object.create(null);return n[t]=rD(e),[n,()=>n[t]]}function rD(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return NE(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function iD(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var aD=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),oD=[];for(let e=0;e<aD.length;e++)oD[aD[e].charCodeAt(0)]=e;oD[45]=aD.indexOf(`+`),oD[95]=aD.indexOf(`/`);var sD={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=oD[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
64
+ `:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=aD[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=aD[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=aD[i|r>>6],t+=aD[r&63],n=0}return n&&(t+=aD[i],t+=`=`,n==1&&(t+=`=`)),t}};function cD(e,t,n){dD(t,e);let r=t.runtime.bin.makeReadOptions(n),i=iD(e.getType().runtime.bin.listUnknownFields(e),t.field),a=K(nD(t),2),o=a[0],s=a[1];for(let e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function lD(e,t,n,r){dD(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(uD(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let t=K(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function uD(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function dD(e,t){eE(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function fD(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!PE(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function pD(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?NE(e.T,e.L):void 0;break;case`message`:t[n]=void 0}}function mD(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(hE.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0||n.typeName==t.typeName}function hD(e,t){return mD(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}G.DOUBLE,G.FLOAT,G.INT64,G.UINT64,G.INT32,G.UINT32,G.BOOL,G.STRING,G.BYTES;var gD={ignoreUnknownFields:!1},_D={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function vD(e){return e?Object.assign(Object.assign({},gD),e):gD}function yD(e){return e?Object.assign(Object.assign({},_D),e):_D}var bD=Symbol(),xD=Symbol();function SD(){return{makeReadOptions:vD,makeWriteOptions:yD,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${CD(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let s of Object.entries(t)){var o=K(s,2);let t=o[0],c=o[1],l=e.fields.findJsonName(t);if(l){if(l.oneof){if(c===null&&l.kind==`scalar`)continue;let n=i.get(l.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${l.oneof.name}" present: "${n}", "${t}"`);i.set(l.oneof,t)}wD(r,c,l,n,e)}else{let i=!1;if(a?.findExtension&&t.startsWith(`[`)&&t.endsWith(`]`)){let o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;let e=K(nD(o),2),t=e[0],a=e[1];wD(t,c,o.field,n,o),lD(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${t}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!fD(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!OD(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=kD(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&uD(e,o)){let n=cD(e,o,t),i=kD(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return ED(e,t,n??jE.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||PE(e,t)))return jD(e,t)},debug:CD}}function CD(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function wD(e,t,n,r,i){let a=n.localName;if(n.repeated){if(eE(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${CD(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${CD(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=DD(n.T,e,r.ignoreUnknownFields,!0);t!==xD&&o.push(t);break;case`scalar`:try{o.push(ED(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${CD(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${CD(t)}`);let s=e[a];for(let e of Object.entries(t)){var o=K(e,2);let a=o[0],c=o[1];if(c===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let l;try{l=TD(n.K,a)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${CD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:s[l]=n.V.T.fromJson(c,r);break;case`enum`:let e=DD(n.V.T,c,r.ignoreUnknownFields,!0);e!==xD&&(s[l]=e);break;case`scalar`:try{s[l]=ED(n.V.T,c,jE.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${CD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];mD(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=DD(n.T,t,r.ignoreUnknownFields,!1);switch(c){case bD:pD(n,e);break;case xD:break;default:e[a]=c}break;case`scalar`:try{let r=ED(n.T,t,n.L,!1);switch(r){case bD:pD(n,e);break;default:e[a]=r}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${CD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}function TD(e,t){if(e===G.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1}return ED(e,t,jE.BIGINT,!0).toString()}function ED(e,t,n,r){if(t===null)return r?NE(e,n):bD;switch(e){case G.DOUBLE:case G.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==G.FLOAT&&cE(r),r;case G.INT32:case G.FIXED32:case G.SFIXED32:case G.SINT32:case G.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==G.UINT32||e==G.FIXED32?sE(i):oE(i),i;case G.INT64:case G.SFIXED64:case G.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=AE.parse(t);return n?a.toString():a;case G.FIXED64:case G.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=AE.uParse(t);return n?o.toString():o;case G.BOOL:if(typeof t!=`boolean`)break;return t;case G.STRING:if(typeof t!=`string`)break;return t;case G.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return sD.dec(t)}throw Error()}function DD(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:bD;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return xD}throw Error(`cannot decode enum ${e.typeName} from JSON: ${CD(t)}`)}function OD(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function kD(e,t,n){if(e.kind==`map`){eE(typeof t==`object`&&!!t);let o={},s=Object.entries(t);switch(e.V.kind){case`scalar`:for(let t of s){var r=K(t,2);let n=r[0],i=r[1];o[n.toString()]=jD(e.V.T,i)}break;case`message`:for(let e of s){var i=K(e,2);let t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case`enum`:let t=e.V.T;for(let e of s){var a=K(e,2);let r=a[0],i=a[1];o[r.toString()]=AD(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){eE(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(jD(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(AD(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return jD(e.T,t);case`enum`:return AD(e.T,t,n.enumAsInteger);case`message`:return hD(e.T,t).toJson(n)}}function AD(e,t,n){return eE(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function jD(e,t){switch(e){case G.INT32:case G.SFIXED32:case G.SINT32:case G.FIXED32:case G.UINT32:return eE(typeof t==`number`),t;case G.FLOAT:case G.DOUBLE:return eE(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case G.STRING:return eE(typeof t==`string`),t;case G.BOOL:return eE(typeof t==`boolean`),t;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return eE(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case G.BYTES:return eE(t instanceof Uint8Array),sD.enc(t)}}var MD=Symbol(`@bufbuild/protobuf/unknown-fields`),ND={readUnknownFields:!0,readerFactory:e=>new eD(e)},PD={writeUnknownFields:!0,writerFactory:()=>new $E};function FD(e){return e?Object.assign(Object.assign({},ND),e):ND}function ID(e){return e?Object.assign(Object.assign({},PD),e):PD}function LD(){return{makeReadOptions:FD,makeWriteOptions:ID,listUnknownFields(e){return e[MD]??[]},discardUnknownFields(e){delete e[MD]},writeUnknownFields(e,t){let n=e[MD];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[MD])||(i[MD]=[]),i[MD].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o;){var l=K(t.tag(),2);if(s=l[0],c=l[1],i===!0&&c==QE.EndGroup)break;let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}RD(e,t,n,c,r)}if(i&&(c!=QE.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:RD,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!fD(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}UD(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&UD(e,t,n,r)}}}function RD(e,t,n,r,i){let a=n.repeated,o=n.localName;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?G.INT32:n.T,c=HD;if(n.kind==`scalar`&&n.L>0&&(c=VD),a){let n=e[o];if(r==QE.LengthDelimited&&s!=G.STRING&&s!=G.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(zD(t,new l,i,n)):mD(e[o])?zD(t,e[o],i,n):(e[o]=zD(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let u=K(BD(n,t,i),2),d=u[0],f=u[1];e[o][d]=f}}function zD(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function BD(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;)switch(K(t.tag(),1)[0]){case 1:a=HD(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=HD(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=zD(t,new e.V.T,n,void 0)}}if(a===void 0&&(a=NE(e.K,jE.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=NE(e.V.T,jE.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T}return[a,o]}function VD(e,t){let n=HD(e,t);return typeof n==`bigint`?n.toString():n}function HD(e,t){switch(t){case G.STRING:return e.string();case G.BOOL:return e.bool();case G.DOUBLE:return e.double();case G.FLOAT:return e.float();case G.INT32:return e.int32();case G.INT64:return e.int64();case G.UINT64:return e.uint64();case G.FIXED64:return e.fixed64();case G.BYTES:return e.bytes();case G.FIXED32:return e.fixed32();case G.SFIXED32:return e.sfixed32();case G.SFIXED64:return e.sfixed64();case G.SINT64:return e.sint64();case G.UINT32:return e.uint32();case G.SINT32:return e.sint32()}}function UD(e,t,n,r){eE(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let o=e.kind==`enum`?G.INT32:e.T;if(i){if(eE(Array.isArray(t)),e.packed)qD(n,o,e.no,t);else for(let r of t)KD(n,o,e.no,r)}else KD(n,o,e.no,t);break;case`message`:if(i){eE(Array.isArray(t));for(let i of t)GD(n,r,e,i)}else GD(n,r,e,t);break;case`map`:eE(typeof t==`object`&&!!t);for(let i of Object.entries(t)){var a=K(i,2);let t=a[0],o=a[1];WD(n,r,e,t,o)}}}function WD(e,t,n,r,i){e.tag(n.no,QE.LengthDelimited),e.fork();let a=r;switch(n.K){case G.INT32:case G.FIXED32:case G.UINT32:case G.SFIXED32:case G.SINT32:a=Number.parseInt(r);break;case G.BOOL:eE(r==`true`||r==`false`),a=r==`true`}switch(KD(e,n.K,1,a),n.V.kind){case`scalar`:KD(e,n.V.T,2,i);break;case`enum`:KD(e,G.INT32,2,i);break;case`message`:eE(i!==void 0),e.tag(2,QE.LengthDelimited).bytes(i.toBinary(t))}e.join()}function GD(e,t,n,r){let i=hD(n.T,r);n.delimited?e.tag(n.no,QE.StartGroup).raw(i.toBinary(t)).tag(n.no,QE.EndGroup):e.tag(n.no,QE.LengthDelimited).bytes(i.toBinary(t))}function KD(e,t,n,r){eE(r!==void 0);let i=K(JD(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function qD(e,t,n,r){if(!r.length)return;e.tag(n,QE.LengthDelimited).fork();let i=K(JD(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function JD(e){let t=QE.Varint;switch(e){case G.BYTES:case G.STRING:t=QE.LengthDelimited;break;case G.DOUBLE:case G.FIXED64:case G.SFIXED64:t=QE.Bit64;break;case G.FIXED32:case G.SFIXED32:case G.FLOAT:t=QE.Bit32}let n=G[e].toLowerCase();return[t,n]}function YD(){return{setEnumType:dE,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let i of n.fields.byMember()){let n=i.localName,a=t,o=e;if(o[n]!=null)switch(i.kind){case`oneof`:let e=o[n].case;if(e===void 0)continue;let t=i.findField(e),s=o[n].value;t&&t.kind==`message`&&!mD(s,t.T)?s=new t.T(s):t&&t.kind===`scalar`&&t.T===G.BYTES&&(s=ZD(s)),a[n]={case:e,value:s};break;case`scalar`:case`enum`:let c=o[n];i.T===G.BYTES&&(c=i.repeated?c.map(ZD):ZD(c)),a[n]=c;break;case`map`:switch(i.V.kind){case`scalar`:case`enum`:if(i.V.T===G.BYTES)for(let e of Object.entries(o[n])){var r=K(e,2);let t=r[0],i=r[1];a[n][t]=ZD(i)}else Object.assign(a[n],o[n]);break;case`message`:let e=i.V.T;for(let t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case`message`:let l=i.T;if(i.repeated)a[n]=o[n].map(e=>mD(e,l)?e:new l(e));else{let e=o[n];a[n]=l.fieldWrapper?l.typeName===`google.protobuf.BytesValue`?ZD(e):e:mD(e,l)?e:new l(e)}}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>ME(e.T,t,i[n]));case`enum`:return r.every((e,t)=>ME(G.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!mD(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!mD(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return ME(G.INT32,r,i);case`scalar`:return ME(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return ME(G.INT32,r.value,i.value);case`scalar`:return ME(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>ME(G.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>ME(n,r[e],i[e]))}}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],a;if(n.repeated)a=t.map(XD);else if(n.kind==`map`){a=r[n.localName];for(let e of Object.entries(t)){var i=K(e,2);let t=i[0],n=i[1];a[t]=XD(n)}}else a=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:XD(t.value)}:{case:void 0}:XD(t);r[n.localName]=a}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function XD(e){if(e===void 0)return e;if(mD(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function ZD(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function QD(e,t,n){return{syntax:e,json:SD(),bin:LD(),util:Object.assign(Object.assign({},YD()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return gE(this,e,t,n)},makeEnum:pE,makeEnumType:fE,getEnumType:uE,makeExtension(e,t,n){return tD(this,e,t,n)}}}var $D=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function eO(e,t){let n=rO(e);return t?n:cO(sO(n))}function tO(e){return eO(e,!1)}var nO=rO;function rO(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join(``)}var iO=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),aO=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),oO=e=>`${e}\$`,sO=e=>aO.has(e)?oO(e):e,cO=e=>iO.has(e)?oO(e):e,lO=class{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=tO(e)}addField(e){eE(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function uO(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=eO(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??nO(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??jE.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=G.BYTES&&t.T!=G.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new lO(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var q=QD(`proto3`,e=>new $D(e,e=>uO(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=NE(t.T,t.L)}}}),dO=class e extends hE{constructor(e){super(),this.seconds=AE.zero,this.nanos=0,q.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${q.json.debug(e)}`);let n=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(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw 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 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=AE.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw 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 Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:AE.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return q.util.equals(e,t,n)}};dO.runtime=q,dO.typeName=`google.protobuf.Timestamp`,dO.fields=q.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var fO=q.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:dO},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:pO,repeated:!0},{no:5,name:`events`,kind:`message`,T:hO,repeated:!0}]),pO=q.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:mO,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),mO=q.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:dO},{no:3,name:`value`,kind:`scalar`,T:2}]),hO=q.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:dO},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:dO,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),gO=q.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),_O=q.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),vO=q.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`}]),yO=q.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),bO=q.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),xO=q.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),SO=q.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`},{no:16,name:`AGENT_ERROR`}]),CO=q.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`}]),wO=q.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),TO=q.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`}]),EO=q.makeEnum(`livekit.PacketTrailerFeature`,[{no:0,name:`PTF_USER_TIMESTAMP`},{no:1,name:`PTF_FRAME_ID`},{no:2,name:`PTF_USER_DATA`}]),DO=q.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:OO,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:vk}]),OO=q.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),kO=q.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:q.getEnumType(vO),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},{no:13,name:`can_manage_agent_session`,kind:`scalar`,T:8}]),AO=q.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:q.getEnumType(jO)},{no:4,name:`tracks`,kind:`message`,T:IO,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:kO},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:q.getEnumType(MO)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:q.getEnumType(SO)},{no:18,name:`kind_details`,kind:`enum`,T:q.getEnumType(NO),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:LO,repeated:!0},{no:20,name:`client_protocol`,kind:`scalar`,T:5},{no:21,name:`capabilities`,kind:`enum`,T:q.getEnumType(mk),repeated:!0}]),jO=q.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),MO=q.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`}]),NO=q.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`},{no:5,name:`SIMULATION`}]),PO=q.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),FO=q.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:KO,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(qO)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),IO=q.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:q.getEnumType(_O)},{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:q.getEnumType(vO)},{no:10,name:`layers`,kind:`message`,T:KO,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:FO,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:q.getEnumType(PO)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:vk},{no:19,name:`audio_features`,kind:`enum`,T:q.getEnumType(TO),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(gO)},{no:21,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(EO),repeated:!0}]),LO=q.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:q.getEnumType(PO)},{no:5,name:`frame_encoding`,kind:`message`,T:RO,opt:!0},{no:6,name:`schema`,kind:`message`,T:HO,opt:!0}]),RO=q.makeMessageType(`livekit.DataTrackFrameEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(zO),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),zO=q.makeEnum(`livekit.DataTrackFrameEncoding.WellKnownFrameEncoding`,[{no:0,name:`WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED`,localName:`UNSPECIFIED`},{no:1,name:`WELL_KNOWN_FRAME_ENCODING_ROS1`,localName:`ROS1`},{no:2,name:`WELL_KNOWN_FRAME_ENCODING_CDR`,localName:`CDR`},{no:3,name:`WELL_KNOWN_FRAME_ENCODING_PROTOBUF`,localName:`PROTOBUF`},{no:4,name:`WELL_KNOWN_FRAME_ENCODING_FLATBUFFER`,localName:`FLATBUFFER`},{no:5,name:`WELL_KNOWN_FRAME_ENCODING_CBOR`,localName:`CBOR`},{no:6,name:`WELL_KNOWN_FRAME_ENCODING_MSGPACK`,localName:`MSGPACK`},{no:7,name:`WELL_KNOWN_FRAME_ENCODING_JSON`,localName:`JSON`}]),BO=q.makeMessageType(`livekit.DataTrackSchemaEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(VO),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),VO=q.makeEnum(`livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding`,[{no:0,name:`WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED`,localName:`UNSPECIFIED`},{no:1,name:`WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF`,localName:`PROTOBUF`},{no:2,name:`WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER`,localName:`FLATBUFFER`},{no:3,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG`,localName:`ROS1_MSG`},{no:4,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG`,localName:`ROS2_MSG`},{no:5,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL`,localName:`ROS2_IDL`},{no:6,name:`WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL`,localName:`OMG_IDL`},{no:7,name:`WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA`,localName:`JSON_SCHEMA`}]),HO=q.makeMessageType(`livekit.DataTrackSchemaId`,()=>[{no:1,name:`name`,kind:`scalar`,T:9},{no:2,name:`encoding`,kind:`message`,T:BO}]),UO=q.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),WO=q.makeMessageType(`livekit.DataBlobKey`,()=>[{no:1,name:`generic`,kind:`scalar`,T:9,oneof:`key`},{no:2,name:`schema_id`,kind:`message`,T:HO,oneof:`key`}]),GO=q.makeMessageType(`livekit.DataBlob`,()=>[{no:1,name:`key`,kind:`message`,T:WO},{no:2,name:`contents`,kind:`scalar`,T:12}]),KO=q.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(yO)},{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}]),qO=q.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`}]),JO=q.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:q.getEnumType(YO)},{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:ek,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:QO,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:tk,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:nk,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:fO,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:ik,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:ak,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:ok,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:sk,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:Ck,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:wk,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:Tk,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:XO,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),YO=q.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),XO=q.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:q.getEnumType(PO)},{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}]),ZO=q.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:ek,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:ik,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:ak,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:ok,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:sk,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:Ck,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:wk,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:Tk,oneof:`value`}]),QO=q.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:$O,repeated:!0}]),$O=q.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}]),ek=q.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}]),tk=q.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),nk=q.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:rk,repeated:!0}]),rk=q.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}]),ik=q.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}]),ak=q.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},{no:6,name:`compressed_payload`,kind:`scalar`,T:12}]),ok=q.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),sk=q.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:ck,oneof:`value`},{no:4,name:`compressed_payload`,kind:`scalar`,T:12,oneof:`value`}]),ck=q.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}]),lk=q.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),uk=q.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:q.getEnumType(dk)},{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}]),dk=q.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),fk=q.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:q.getEnumType(pk)},{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},{no:12,name:`client_protocol`,kind:`scalar`,T:5},{no:13,name:`capabilities`,kind:`enum`,T:q.getEnumType(mk),repeated:!0}]),pk=q.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`}]),mk=q.makeEnum(`livekit.ClientInfo.Capability`,[{no:0,name:`CAP_UNUSED`},{no:1,name:`CAP_PACKET_TRAILER`},{no:2,name:`CAP_COMPRESSION_DEFLATE_RAW`}]),hk=q.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:gk},{no:2,name:`screen`,kind:`message`,T:gk},{no:3,name:`resume_connection`,kind:`enum`,T:q.getEnumType(xO)},{no:4,name:`disabled_codecs`,kind:`message`,T:_k},{no:5,name:`force_relay`,kind:`enum`,T:q.getEnumType(xO)}]),gk=q.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:q.getEnumType(xO)}]),_k=q.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:OO,repeated:!0},{no:2,name:`publish`,kind:`message`,T:OO,repeated:!0}]),vk=q.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),yk=q.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),bk=q.makeEnum(`livekit.DataStream.CompressionType`,[{no:0,name:`NONE`},{no:1,name:`DEFLATE_RAW`}]),xk=q.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:q.getEnumType(yk)},{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`}),Sk=q.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),Ck=q.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:q.getEnumType(PO)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:xk,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:Sk,oneof:`content_header`},{no:11,name:`inline_content`,kind:`scalar`,T:12,opt:!0},{no:12,name:`compression`,kind:`enum`,T:q.getEnumType(bk)}],{localName:`DataStream_Header`}),wk=q.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`}),Tk=q.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`}),Ek=q.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Dk=q.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),Ok=q.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),kk=q.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),Ak=q.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Kk,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Kk,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:Bk,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:Nk,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:Vk,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Jk,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:tA,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:iA,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:oA,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:bA,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:CA,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:EA,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:sA,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:DA,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:nA,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:rA,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:Pk,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:Ik,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Yk,oneof:`message`},{no:22,name:`store_data_blob_request`,kind:`message`,T:Zk,oneof:`message`},{no:23,name:`get_data_blob_request`,kind:`message`,T:$k,oneof:`message`}]),jk=q.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Hk,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Kk,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Kk,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:Bk,oneof:`message`},{no:5,name:`update`,kind:`message`,T:qk,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Wk,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:iA,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:Vk,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:lA,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:uA,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:fA,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:mA,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:_A,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:xA,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:Gk,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:Uk,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:OA,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:jA,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:MA,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:PA,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:SA,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:zA,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:vA,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:Fk,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:Lk,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Rk,oneof:`message`},{no:30,name:`store_data_blob_response`,kind:`message`,T:Qk,oneof:`message`},{no:31,name:`get_data_blob_response`,kind:`message`,T:eA,oneof:`message`}]),Mk=q.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:KO,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(qO)}]),Nk=q.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:q.getEnumType(_O)},{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:q.getEnumType(vO)},{no:9,name:`layers`,kind:`message`,T:KO,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:Mk,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:q.getEnumType(PO)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(gO)},{no:17,name:`audio_features`,kind:`enum`,T:q.getEnumType(TO),repeated:!0},{no:18,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(EO),repeated:!0}]),Pk=q.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:q.getEnumType(PO)},{no:4,name:`frame_encoding`,kind:`message`,T:RO,opt:!0},{no:5,name:`schema`,kind:`message`,T:HO,opt:!0}]),Fk=q.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:LO}]),Ik=q.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),Lk=q.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:LO}]),Rk=q.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:zk}}]),zk=q.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`}),Bk=q.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:q.getEnumType(Dk)},{no:3,name:`final`,kind:`scalar`,T:8}]),Vk=q.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Hk=q.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:DO},{no:2,name:`participant`,kind:`message`,T:AO},{no:3,name:`other_participants`,kind:`message`,T:AO,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:cA,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:hk},{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:uk},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:OO,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),Uk=q.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:cA,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:hk},{no:3,name:`server_info`,kind:`message`,T:uk},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Wk=q.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:IO}]),Gk=q.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Kk=q.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}}]),qk=q.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:AO,repeated:!0}]),Jk=q.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:lk,repeated:!0}]),Yk=q.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Xk,repeated:!0}]),Xk=q.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:UO}],{localName:`UpdateDataSubscription_Update`}),Zk=q.makeMessageType(`livekit.StoreDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:GO}]),Qk=q.makeMessageType(`livekit.StoreDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`key`,kind:`message`,T:WO}]),$k=q.makeMessageType(`livekit.GetDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:9},{no:3,name:`key`,kind:`message`,T:WO}]),eA=q.makeMessageType(`livekit.GetDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:GO}]),tA=q.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:q.getEnumType(yO)},{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}]),nA=q.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:q.getEnumType(TO),repeated:!0}]),rA=q.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}]),iA=q.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(SO)},{no:3,name:`action`,kind:`enum`,T:q.getEnumType(aA)},{no:4,name:`regions`,kind:`message`,T:kA}]),aA=q.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),oA=q.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:KO,repeated:!0}]),sA=q.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}]),cA=q.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}]),lA=q.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:$O,repeated:!0}]),uA=q.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:DO}]),dA=q.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:q.getEnumType(bO)},{no:3,name:`score`,kind:`scalar`,T:2}]),fA=q.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:dA,repeated:!0}]),pA=q.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:q.getEnumType(Ok)}]),mA=q.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:pA,repeated:!0}]),hA=q.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(yO)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),gA=q.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:hA,repeated:!0}]),_A=q.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:hA,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:gA,repeated:!0}]),vA=q.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:Ek,repeated:!0}]),yA=q.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}]),bA=q.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:yA,repeated:!0}]),xA=q.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}]),SA=q.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:DO},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:AO},{no:4,name:`other_participants`,kind:`message`,T:AO,repeated:!0}]),CA=q.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Kk},{no:2,name:`subscription`,kind:`message`,T:Jk},{no:3,name:`publish_tracks`,kind:`message`,T:Wk,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:TA,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Kk},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:wA,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:Fk,repeated:!0}]),wA=q.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),TA=q.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:q.getEnumType(Dk)}]),EA=q.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:q.getEnumType(kk),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`}]),DA=q.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),OA=q.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),kA=q.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:AA,repeated:!0}]),AA=q.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}]),jA=q.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:q.getEnumType(wO)}]),MA=q.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(NA)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:Bk,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:Nk,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:Vk,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:sA,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:nA,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:rA,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:Pk,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:Ik,oneof:`request`}]),NA=q.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`},{no:11,name:`INVALID_REQUEST`}]),PA=q.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),FA=q.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}]),IA=q.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:fk},{no:2,name:`connection_settings`,kind:`message`,T:FA},{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:Nk,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Kk},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:q.getEnumType(CO)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:CA}]),LA=q.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:q.getEnumType(RA)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),RA=q.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),zA=q.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function BA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var VA={exports:{}},HA=VA.exports,UA;function WA(){return UA?VA.exports:(UA=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(HA,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(typeof window!==t&&f){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(typeof window!==t&&f){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(typeof window!==t&&f){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(VA),VA.exports)}var GA=WA(),KA;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(KA||={});var qA;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`,e.Region=`livekit-region`,e.ICE=`livekit-ice`,e.Stats=`livekit-stats`})(qA||={});var JA=GA.getLogger(qA.Default);Object.values(qA).map(e=>GA.getLogger(e)),JA.setDefaultLevel(KA.info);function YA(e,t){let n=GA.getLogger(e);return n.setDefaultLevel(JA.getLevel()),t?XA(n,t):n}function XA(e,t){let n=n=>(r,i)=>{let a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n(`trace`),r.debug=n(`debug`),r.info=n(`info`),r.warn=n(`warn`),r.error=n(`error`),r}var ZA=GA.getLogger(qA.E2EE),QA=new Set,$A=ZA.setLevel.bind(ZA);ZA.setLevel=(e,t)=>{$A(e,t);let n=ZA.getLevel();QA.forEach(e=>e(n))};function ej(e){return QA.add(e),()=>{QA.delete(e)}}var tj=7e3,nj=[0,300,1200,2700,4800,tj,tj,tj,tj,tj],rj=class{constructor(e){this._retryDelays=e===void 0?nj:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function ij(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function J(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function aj(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function oj(e){return this instanceof oj?(this.v=e,this):new oj(e)}function sj(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof oj?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function cj(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:oj(e[r](t)),done:!1}:i?i(t):t}:i}}function lj(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof aj==`function`?aj(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var uj={exports:{}},dj;function fj(){if(dj)return uj.exports;dj=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}uj.exports=a,uj.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received `+e+`.`);o=e}}),a.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},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||e<0||i(e))throw RangeError(`The value of "n" is out of range. It must be a non-negative number. Received `+e+`.`);return this._maxListeners=e,this};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){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 d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);return this.removeAllListeners(`removeListener`),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t==`function`)this.removeListener(e,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return uj.exports}var pj=fj(),mj=!0,hj=!0;function gj(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function _j(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,`addEventListener`).writable){bj(`Unable to polyfill events`);return}let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function vj(e){return typeof e==`boolean`?(mj=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function yj(e){return typeof e==`boolean`?(hj=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function bj(){if(typeof window==`object`){if(mj)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function xj(e,t){hj&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function Sj(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e){let t=parseInt(e.version,10);if(t>=90)return{browser:`chrome`,version:t}}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(gj(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(gj(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(gj(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=gj(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function Cj(e){return Object.prototype.toString.call(e)===`[object Object]`}function wj(e){return Cj(e)?Object.keys(e).reduce(function(t,n){let r=Cj(e[n]),i=r?wj(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function Tj(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?Tj(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{Tj(e,e.get(t),n)})}))}function Ej(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&Tj(e,n,i)})}),i}var Dj=bj;function Oj(e,t){if(t.version>=64)return;let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),Dj(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return Dj(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function kj(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Aj(e,t){if(!(t.version>102)){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else _j(e,`track`,e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}}function jj(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(this._dtmf=t.kind===`audio`?e.createDTMFSender(t):null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this._dtmf=this.track.kind===`audio`?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function Mj(e,t){if(t.version>=67||!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>Ej(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),_j(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>Ej(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return n.apply(this,arguments)}}function Nj(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function Pj(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Nj(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))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(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function Fj(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function Ij(e,t){t.version>102||_j(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var Lj=Object.freeze({__proto__:null,fixNegotiationNeeded:Ij,shimAddTrackRemoveTrack:Pj,shimAddTrackRemoveTrackWithNative:Nj,shimGetSendersWithDtmf:jj,shimGetUserMedia:Oj,shimMediaStream:kj,shimOnTrack:Aj,shimPeerConnection:Fj,shimSenderReceiverGetStats:Mj});function Rj(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){xj(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function zj(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)}))}function Bj(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Vj(e,t){typeof e==`object`&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function Hj(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection)||t.version>=151)return;let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let e=Array.prototype.slice.call(arguments),i=e[0],a=e[1],o=e[2];return this.signalingState===`closed`?Promise.resolve(new Map):r.apply(this,[i||null]).then(e=>{if(t.version<53&&!a)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(a,o)}}function Uj(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Wj(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),_j(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Gj(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){xj(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Kj(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function qj(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let t=e.length>0;t&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=n.apply(this,arguments);if(t){let t=r.sender,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function Jj(e,t){if(!(typeof e==`object`&&e.RTCRtpSender)||t.version>=110)return;let n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){let e=n.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function Yj(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function Xj(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}var Zj=Object.freeze({__proto__:null,shimAddTransceiver:qj,shimCreateAnswer:Xj,shimCreateOffer:Yj,shimGetDisplayMedia:zj,shimGetParameters:Jj,shimGetStats:Hj,shimGetUserMedia:Rj,shimOnTrack:Bj,shimPeerConnection:Vj,shimRTCDataChannel:Kj,shimReceiverGetStats:Wj,shimRemoveStream:Gj,shimSenderGetStats:Uj});function Qj(e){if(typeof e==`object`&&e.RTCPeerConnection){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){var n=[...arguments].slice(1);return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function $j(e){if(typeof e==`object`&&e.RTCPeerConnection&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function eM(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function tM(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(nM(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function nM(e){return e&&e.video!==void 0?Object.assign({},e,{video:wj(e.video)}):e}function rM(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(xj(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function iM(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function aM(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function oM(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var sM=Object.freeze({__proto__:null,shimAudioContext:oM,shimCallbacksAPI:eM,shimConstraints:nM,shimCreateOfferLegacy:aM,shimGetUserMedia:tM,shimLocalStreamsAPI:Qj,shimRTCIceServerUrls:rM,shimRemoteStreamsAPI:$j,shimTrackEventTransceiver:iM}),cM={exports:{}},lM;function uM(){return lM?cM.exports:(lM=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
65
65
  `).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
66
66
  m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
67
67
  `)},t.getDescription=function(e){let n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){let n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>e.indexOf(n)===0)},t.parseCandidate=function(e){let t;t=e.indexOf(`a=candidate:`)===0?e.substring(12).split(` `):e.substring(10).split(` `);let n={foundation:t[0],component:{1:`rtp`,2:`rtcp`}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case`raddr`:n.relatedAddress=t[e+1];break;case`rport`:n.relatedPort=parseInt(t[e+1],10);break;case`tcptype`:n.tcpType=t[e+1];break;case`ufrag`:n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:n[t[e]]===void 0&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let n=e.component;n===`rtp`?t.push(1):n===`rtcp`?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let r=e.type;return t.push(`typ`),t.push(r),r!==`host`&&e.relatedAddress&&e.relatedPort!==void 0&&(t.push(`raddr`),t.push(e.relatedAddress),t.push(`rport`),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()===`tcp`&&(t.push(`tcptype`),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push(`ufrag`),t.push(e.usernameFragment||e.ufrag)),`candidate:`+t.join(` `)},t.parseIceOptions=function(e){return e.substring(14).split(` `)},t.parseRtpMap=function(e){let t=e.substring(9).split(` `),n={payloadType:parseInt(t.shift(),10)};return t=t[0].split(`/`),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=t.length===3?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);let n=e.channels||e.numChannels||1;return`a=rtpmap:`+t+` `+e.name+`/`+e.clockRate+(n===1?``:`/`+n)+`\r
@@ -92,15 +92,15 @@ a=ice-pwd:`+e.password+`\r
92
92
  o=`+(r||`thisisadapterortc`)+` `+i+` `+a+` IN IP4 127.0.0.1\r
93
93
  s=-\r
94
94
  t=0 0\r
95
- `},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(rM),rM.exports)}var oM=aM(),sM=FA(oM),cM=WT({__proto__:null,default:sM},[oM]);function lM(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=sM.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,fj(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function uM(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||fj(e,`icecandidate`,e=>{if(e.candidate){let t=sM.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function dM(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>102||t.browser===`firefox`&&t.version>=113)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=sM.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=sM.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=sM.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76&&this.getConfiguration().sdpSemantics===`plan-b`&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0}),n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,"maxMessageSize",{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function fM(e,t){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype)||t.browser===`chrome`&&t.version>=149||t.browser===`firefox`&&t.version>60)return;function n(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=r.apply(this,arguments);return n(e,this),e},fj(e,`datachannel`,e=>(n(e.channel,e.target),e))}function pM(e){if(!e.RTCPeerConnection||`connectionState`in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:`connected`,checking:`connecting`}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(`connectionstatechange`,this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(`connectionstatechange`,this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[`setLocalDescription`,`setRemoteDescription`].forEach(e=>{let n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function mM(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
95
+ `},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(cM),cM.exports)}var dM=uM(),fM=BA(dM),pM=YT({__proto__:null,default:fM},[dM]);function mM(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=fM.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,_j(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function hM(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||_j(e,`icecandidate`,e=>{if(e.candidate){let t=fM.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function gM(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>102||t.browser===`firefox`&&t.version>=113)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=fM.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=fM.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=fM.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76&&this.getConfiguration().sdpSemantics===`plan-b`&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0}),n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,"maxMessageSize",{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function _M(e,t){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype)||t.browser===`chrome`&&t.version>=149||t.browser===`firefox`&&t.version>60)return;function n(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=r.apply(this,arguments);return n(e,this),e},_j(e,`datachannel`,e=>(n(e.channel,e.target),e))}function vM(e){if(!e.RTCPeerConnection||`connectionState`in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:`connected`,checking:`connecting`}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(`connectionstatechange`,this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(`connectionstatechange`,this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[`setLocalDescription`,`setRemoteDescription`].forEach(e=>{let n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function yM(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
96
96
  a=extmap-allow-mixed`)!==-1){let n=t.sdp.split(`
97
97
  `).filter(e=>e.trim()!==`a=extmap-allow-mixed`).join(`
98
- `);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function hM(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;n&&n.length!==0&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function gM(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;n&&n.length!==0&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var _M=Object.freeze({__proto__:null,removeExtmapAllowMixed:mM,shimAddIceCandidateNullOrEmpty:hM,shimConnectionState:pM,shimMaxMessageSize:dM,shimParameterlessSetLocalDescription:gM,shimRTCIceCandidate:lM,shimRTCIceCandidateRelayProtocol:uM,shimSendThrowTypeError:fM});function vM(){let e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}).window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=hj,r=_j(e),i={browserDetails:r,commonShim:_M,extractVersion:dj,disableLog:pj,disableWarnings:mj,sdp:cM};switch(r.browser){case`chrome`:if(!Mj||!Aj||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=Mj,hM(e,r),gM(e),Cj(e,r),wj(e),Aj(e,r),Tj(e,r),kj(e,r),Ej(e),Dj(e,r),jj(e,r),lM(e),uM(e),pM(e),dM(e,r),fM(e,r),mM(e,r);break;case`firefox`:if(!Kj||!Ij||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Kj,hM(e,r),gM(e),Nj(e,r),Ij(e,r),Lj(e,r),Fj(e),Bj(e),Rj(e),zj(e),Vj(e),Hj(e,r),Uj(e,r),Wj(e,r),Gj(e,r),lM(e),pM(e),dM(e,r),fM(e,r);break;case`safari`:if(!nM||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=nM,hM(e,r),gM(e),Qj(e),eM(e),Yj(e),qj(e),Jj(e),$j(e),Xj(e),tM(e),lM(e),uM(e),dM(e,r),fM(e,r),mM(e,r);break;default:n(`Unsupported browser!`)}return i}vM({window:typeof window>`u`?void 0:window});var yM,bM,xM=class extends (bM=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};yM=xM,xM.resolve=e=>Reflect.get(bM,`resolve`,yM).call(yM,e);var SM=/version\/(\d+(\.?_?\d+)+)/i,CM;function wM(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(CM===void 0||t)&&(CM=TM.find(e=>e.test.test(n))?.describe(n)),CM}var TM=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:EM(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:DM(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:EM(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:DM(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:EM(SM,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:DM(e)}}}];function EM(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function DM(e){return e.includes(`mac os`)?EM(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var OM=`2.22.3`,kM=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},AM=class extends kM{},jM;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(jM||={});var MM=class e extends AM{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=jM[t]}static notAllowed(t,n,r){return new e(t,jM.NotAllowed,n,r)}static timeout(t){return new e(t,jM.Timeout)}static leaveRequest(t,n){return new e(t,jM.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,jM.InternalError,void 0,n)}static cancelled(t){return new e(t,jM.Cancelled)}static serverUnreachable(t,n){return new e(t,jM.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,jM.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,jM.ServiceNotFound,void 0,n)}},NM=class extends kM{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},PM=class extends kM{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},FM=class extends kM{constructor(e){super(10,e||`unsupported server`),this.name=`UnsupportedServer`}},IM=class extends kM{constructor(e){super(12,e||`unexpected connection state`),this.name=`UnexpectedConnectionState`}},LM=class extends kM{constructor(e){super(13,e||`unable to negotiate`),this.name=`NegotiationError`}},RM=class extends kM{constructor(e){super(14,e||`unable to publish data`),this.name=`PublishDataError`}},zM=class extends kM{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},BM=class extends AM{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:OA[t]}},VM;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`,e[e.HeaderTooLarge=9]=`HeaderTooLarge`,e[e.PayloadTooLarge=10]=`PayloadTooLarge`})(VM||={});var HM=class extends AM{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=VM[t]}},UM=class extends kM{constructor(e){super(18,e),this.name=`SignalReconnectError`}},WM;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(WM||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(WM||={});var GM=class{};GM.setTimeout=function(){return setTimeout(...arguments)},GM.setInterval=function(){return setInterval(...arguments)},GM.clearTimeout=function(){return clearTimeout(...arguments)},GM.clearInterval=function(){return clearInterval(...arguments)};var Y;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(Y||={});var X;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(X||={});var Z;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`,e.TokenRefreshed=`tokenRefreshed`,e.ServerRegionsReported=`serverRegionsReported`})(Z||={});var Q;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(Q||={});function KM(e){let t={};for(let r of Object.entries(e)){var n=K(r,2);let e=n[0],i=n[1];i!==void 0&&(t[e]=i)}return t}function qM(e,t){return e&&t?`${e}x${t}`:void 0}function JM(e){return Math.round(e*1e4)/1e4}function YM(e){let t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return t!==void 0&&n?JM(t/n):void 0}function XM(e,t){if(e.playoutDelay!==void 0)return JM(e.playoutDelay);let n=t?.totalPlayoutDelay,r=t?.totalSamplesCount;return n!==void 0&&r?JM(n/r):void 0}function ZM(e){let t=new Map,n=[],r=[],i=[],a;e.forEach(e=>t.set(e.id,e));let o=e=>e.codecId?t.get(e.codecId)?.mimeType:void 0,s=(e,n)=>e[n]?t.get(e[n]):void 0;e.forEach(e=>{switch(e.type){case`inbound-rtp`:{let t=s(e,`playoutId`);r.push(KM({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:o(e),decoder:e.decoderImplementation,resolution:qM(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:YM(e),playoutDelay:XM(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case`outbound-rtp`:{let t=s(e,`remoteId`),n=s(e,`mediaSourceId`);i.push(KM({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:n?.trackIdentifier,active:e.active,codec:o(e),encoder:e.encoderImplementation,resolution:qM(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:qM(n?.width,n?.height),captureFps:n?.framesPerSecond,audioLevel:n?.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:e.qualityLimitationReason===`none`?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:t?.packetsLost,remoteFractionLost:t?.fractionLost,remoteJitter:t?.jitter,remoteRoundTripTime:t?.roundTripTime}));break}case`transport`:a=e;break;case`candidate-pair`:n.push(e)}});let c=a?.selectedCandidatePairId,l=(c?t.get(c):void 0)??n.find(e=>e.selected)??n.find(e=>e.nominated),u=l?.localCandidateId?t.get(l.localCandidateId):void 0,d=l?.remoteCandidateId?t.get(l.remoteCandidateId):void 0,f=KM({ice:a?.iceState,dtls:a?.dtlsState,route:u&&d?`${u.candidateType}/${u.protocol} -> ${d.candidateType}`:void 0,network:u?.networkType,currentRoundTripTime:l?.currentRoundTripTime,availableOutgoingBitrate:l?.availableOutgoingBitrate,availableIncomingBitrate:l?.availableIncomingBitrate,bytesSent:l?.bytesSent,bytesReceived:l?.bytesReceived,candidatePairChanges:a?.selectedCandidatePairChanges});return{connection:Object.keys(f).length>0?f:void 0,outbound:i.length>0?i:void 0,inbound:r.length>0?r:void 0}}function QM(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var $M=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},eN=[`vp8`,`h264`],tN=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function nN(e){return!!eN.find(t=>t===e)}var rN=nN,iN;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(iN||={});var aN;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(aN||={});var oN={h90:new $M(160,90,9e4,20),h180:new $M(320,180,16e4,20),h216:new $M(384,216,18e4,20),h360:new $M(640,360,45e4,20),h540:new $M(960,540,8e5,25),h720:new $M(1280,720,17e5,30),h1080:new $M(1920,1080,3e6,30),h1440:new $M(2560,1440,5e6,30),h2160:new $M(3840,2160,8e6,30)},sN={h120:new $M(160,120,7e4,20),h180:new $M(240,180,125e3,20),h240:new $M(320,240,14e4,20),h360:new $M(480,360,33e4,20),h480:new $M(640,480,5e5,20),h540:new $M(720,540,6e5,25),h720:new $M(960,720,13e5,30),h1080:new $M(1440,1080,23e5,30),h1440:new $M(1920,1440,38e5,30)},cN={h360fps3:new $M(640,360,2e5,3,`medium`),h360fps15:new $M(640,360,4e5,15,`medium`),h720fps5:new $M(1280,720,8e5,5,`medium`),h720fps15:new $M(1280,720,15e5,15,`medium`),h720fps30:new $M(1280,720,2e6,30,`medium`),h1080fps15:new $M(1920,1080,25e5,15,`medium`),h1080fps30:new $M(1920,1080,5e6,30,`medium`),original:new $M(0,0,7e6,30,`medium`)};function lN(e,t,n){var r,i;let a=SN(e??{}),o=a.optionsWithoutProcessor,s=a.audioProcessor,c=a.videoProcessor,l=t?.processor,u=n?.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(uN(d.audio,t),(r=d.audio).deviceId??(r.deviceId={ideal:`default`}),(s||l)&&(d.audio.processor=s??l)),d.video&&(uN(d.video,n),(i=d.video).deviceId??(i.deviceId={ideal:`default`}),(c||u)&&(d.video.processor=c??u)),d}function uN(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function dN(e){var t,n;let r={};if(e.video){if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:uN(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1}else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function fN(e){return J(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=pN();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield PN(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function pN(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>J(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function mN(e){return e===`audioinput`?$.Source.Microphone:e===`videoinput`?$.Source.Camera:$.Source.Unknown}function hN(e){if(e===$.Source.Microphone)return`audioinput`;if(e===$.Source.Camera)return`videoinput`}function gN(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=XN()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function _N(e){return e.split(`/`)[1].toLowerCase()}function vN(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new zk({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function yN(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?yN(e.track):{})}}function bN(){return typeof RTCRtpReceiver<`u`&&typeof RTCRtpReceiver.prototype.getSynchronizationSources==`function`}function xN(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function SN(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:QM(t)}}function CN(e){switch(e){case pO.CAMERA:return $.Source.Camera;case pO.MICROPHONE:return $.Source.Microphone;case pO.SCREEN_SHARE:return $.Source.ScreenShare;case pO.SCREEN_SHARE_AUDIO:return $.Source.ScreenShareAudio;default:return $.Source.Unknown}}function wN(e,t){return e.width*e.height<t.width*t.height}function TN(e,t){return e.layers?.find(e=>e.quality===t)}var EN=5e3,DN=[],ON;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(ON||={});var $=class e extends cj.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug(`stream state changed: ${this._streamState} -> ${e}`),this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=UA,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),EN):this.handleAppVisibilityChanged()},this.loggerContextCb=r.loggerContextCb,this.log=WA(r.loggerName??HA.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),yN(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(DN.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&DN.splice(DN.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),kN(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?Q.AudioPlaybackStarted:Q.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?Q.AudioPlaybackFailed:Q.VideoPlaybackFailed,e):e.name===`AbortError`?this.log.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):this.log.warn(`could not playback ${i?`audio`:`video`}`,{error:e}),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(Q.ElementAttached,t),t}detach(e){try{if(e){AN(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Q.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{AN(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Q.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.log.debug(`stopping track`),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle!==void 0&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then(e=>{e&&this.log.info(`final track stats`,ZM(e))}).catch(e=>this.log.debug(`could not collect final track stats`,{error:e})))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=WA(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),DN.forEach(e=>{e.parentElement||(t=!1)}),t&&DN.push(e)}}handleAppVisibilityChanged(){return J(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){nP()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){nP()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function kN(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!XN()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(XN()||qN())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function AN(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),t.srcObject=n.getTracks().length>0?n:null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return fO.AUDIO;case t.Video:return fO.VIDEO;default:return fO.DATA}}e.kindToProto=i;function a(e){switch(e){case fO.AUDIO:return t.Audio;case fO.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return pO.CAMERA;case n.Microphone:return pO.MICROPHONE;case n.ScreenShare:return pO.SCREEN_SHARE;case n.ScreenShareAudio:return pO.SCREEN_SHARE_AUDIO;default:return pO.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case pO.CAMERA:return n.Camera;case pO.MICROPHONE:return n.Microphone;case pO.SCREEN_SHARE:return n.ScreenShare;case pO.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case Ck.ACTIVE:return r.Active;case Ck.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})($||={});var jN=`|`,MN=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function NN(e){let t=e.split(jN);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function PN(e){return new xM(t=>GM.setTimeout(t,e))}function FN(){return`addTransceiver`in RTCPeerConnection.prototype}function IN(){return`addTrack`in RTCPeerConnection.prototype}function LN(){if(!(`getCapabilities`in RTCRtpSender)||XN()||qN())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function RN(){if(!(`getCapabilities`in RTCRtpSender)||qN())return!1;if(XN()){let e=wM();if(e?.version&&lP(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&lP(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function zN(e){return e===`av1`||e===`vp9`}function BN(e){let t=e.getHeaderExtensionsToNegotiate?.call(e);if(!t||!e.setHeaderExtensionsToNegotiate)return!1;let n=t.find(e=>e.uri===MN);if(!n)return!1;if(n.direction!==`stopped`)return!0;n.direction=`sendrecv`;try{return e.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function VN(e,t){return zN(e)&&!!t?.simulcast&&!!t.scalabilityMode?.startsWith(`L1T`)}function HN(){let e=wM();return ZN()||rP()||e?.name===`Chrome`&&lP(e.version,`113`)<0}var UN=`1.13.6`;function WN(e){return e?lP(e,UN)>0:!1}function GN(e){return!document||ZN()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function KN(){return typeof RTCPeerConnection>`u`?!1:FN()||IN()}function qN(){return wM()?.name===`Firefox`}function JN(){let e=wM();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function YN(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0&&!JN()}function XN(){return wM()?.name===`Safari`}function ZN(){let e=wM();return e?.name===`Safari`||e?.os===`iOS`}function QN(){let e=wM();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&lP(e.osVersion,`17`)>=0}function $N(e){return e||=wM(),e?.name===`Safari`&&lP(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&lP(e.osVersion,`18.3`)>0}function eP(){return nP()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function tP(){let e=wM(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&lP(e.osVersion,t)>=0?!0:e.name===`Safari`&&lP(e.version,t)>=0}function nP(){return typeof document<`u`}function rP(){return navigator.product==`ReactNative`}function iP(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function aP(e){return iP(e)?e.hostname.split(`.`)[0]:null}function oP(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function sP(){if(!rP())return;let e=oP();if(e)return e.platform}function cP(){if(nP())return window.devicePixelRatio;if(rP()){let e=oP();if(e)return e.devicePixelRatio}return 1}function lP(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function uP(e){for(let t of e)t.target.handleResize(t)}function dP(e){for(let t of e)t.target.handleVisibilityChanged(t)}var fP=null,pP=()=>(fP||=new ResizeObserver(uP),fP),mP=null,hP=()=>(mP||=new IntersectionObserver(dP,{root:null,rootMargin:`0px`}),mP);function gP(e){let t=new sk({capabilities:e,sdk:ck.JS,protocol:17,clientProtocol:2,version:OM});return rP()&&(t.os=sP()??``),t}function _P(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let o=K(i.captureStream().getTracks(),1)[0];if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var vP;function yP(){if(!vP){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),vP=K(r.stream.getAudioTracks(),1)[0],!vP)throw Error(`Could not get empty media stream audio track`);vP.enabled=!1}return vP.clone()}var bP=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>J(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function xP(e){return tN.includes(e)}function SP(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function CP(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function wP(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function TP(e,t){return e.segments.map(e=>{let n=e.id,r=e.text,i=e.language,a=e.startTime,o=e.endTime,s=e.final,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function EP(e){let t=e.id,n=e.timestamp,r=e.message,i=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function DP(e){switch(e.reason){case jM.LeaveRequest:return e.context;case jM.Cancelled:return _O.CLIENT_INITIATED;case jM.NotAllowed:return _O.USER_REJECTED;case jM.ServerUnreachable:return _O.JOIN_FAILURE;default:return _O.UNKNOWN_REASON}}function OP(e){return e===void 0?void 0:Number(e)}function kP(e){return e===void 0?void 0:BigInt(e)}function AP(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function jP(e){return!!e&&e.kind==$.Kind.Audio}function MP(e){return!!e&&e.kind==$.Kind.Video}function NP(e){return AP(e)&&MP(e)}function PP(e){return AP(e)&&jP(e)}function FP(e){return!!e&&!e.isLocal}function IP(e){return!!e&&!e.isLocal}function LP(e){return FP(e)&&MP(e)}function RP(e){return e.isLocal}function zP(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function BP(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function VP(e,t){return nj(this,arguments,function*(){let n=e.getReader(),r=new Uint8Array;try{for(;;){let e=yield tj(n.read()),i=e.done,a=e.value;if(i)break;if(a.byteLength===0)continue;let o=new Uint8Array(r.byteLength+a.byteLength);for(o.set(r),o.set(a,r.byteLength),r=o;r.byteLength>=t;)yield yield tj(r.slice(0,t)),r=r.slice(t)}r.byteLength>0&&(yield yield tj(r))}finally{n.releaseLock()}})}function HP(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function UP(){return typeof CompressionStream<`u`}function WP(){return UP()&&!qN()}function GP(e,t){let n=K(NN(t.id),2)[1];if(n?.startsWith(`TR`))return n;if(e.id.startsWith(`TR`))return e.id}function KP(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=qP(e,t);return n?r:XP(r,`v1`)}function qP(e,t){let n=new URL(CP(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),XP(n,`rtc`)}function JP(e){return XP(new URL(wP(e)),`validate`)}function YP(e){return e.endsWith(`/`)?e:`${e}/`}function XP(e,t){return e.pathname=`${YP(e.pathname)}${t}`,e}function ZP(e){if(typeof e==`string`)return Ek.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return Ek.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function QP(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}function $P(e,t){return e instanceof Error?e.name&&e.message?`${e.name}: ${e.message}`:e.name:`Encountered unknown ${t} error: ${String(e)}`}var eF=`lk_e2ee`,tF=`lk_e2ee_track_id`,nF;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(nF||={});var rF;(function(e){e.KeyRatcheted=`keyRatcheted`})(rF||={});var iF;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(iF||={});var aF;(function(e){e.Error=`cryptorError`})(aF||={});function oF(){return cF()||sF()}function sF(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0}function cF(){return typeof window<`u`&&window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function lF(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new KO({value:e.value})}cj.EventEmitter;var uF;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(uF||={});var dF=class extends kM{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:uF.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}};function fF(){return YN()}function pF(e){return!!e?.worker&&(cF()||fF())}function mF(e){return!!(e?.timestamp||e?.frameId)}function hF(e){let t=[];return e?.timestamp&&t.push(xO.PTF_USER_TIMESTAMP),e?.frameId&&t.push(xO.PTF_FRAME_ID),t}function gF(e){if(!e||e.length===0)return;let t={};return e.includes(xO.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(xO.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}function _F(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){var t=[...arguments];let n=this;return new Promise((o,u)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let r=e.apply(n,t);a&&a(r),c.forEach(e=>{let t=e.resolve;return t(r)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&GM.clearTimeout(r),r=GM.setTimeout(d,l()),f){let r=e.apply(n,t);return a&&a(r),o(r)}c.push({resolve:o,reject:u})})};return u.cancel=function(e){r!==void 0&&GM.clearTimeout(r),c.forEach(t=>{let n=t.reject;return n(e)}),c=[]},u}var vF=2e3;function yF(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var bF=class extends ${constructor(e,t,n,r,i){super(e,n,i),this.timeSyncLoop=()=>{if(this.listenerCount(Q.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);let e=this.receiver?.getSynchronizationSources()[0];if(e){let t=e.timestamp,n=e.rtpTimestamp;n&&this.rtpTimestamp!==n&&(this.emit(Q.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}},this.onTimeSyncListenerAdded=e=>{e===Q.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Q.Muted:Q.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Q.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return J(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),vF),bN()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off(`newListener`,this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){let e=this;e.off(`newListener`,this.onTimeSyncListenerAdded),e.on(`newListener`,this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}},xF=100,SF=class extends bF{constructor(e,t,n,r,i){super(e,t,$.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>J(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=yF(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=_F(()=>{this.updateDimensions()},xF),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;return this.frameMetadataExtractor?.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===$.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?AN(this._mediaStreamTrack,t):kN(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new CF(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return J(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(this.lastVisible!==i||e){if(!i&&Date.now()-t<xF){GM.setTimeout(()=>{this.updateVisibility()},xF);return}this.lastVisible=i,this.emit(Q.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}(this.lastDimensions?.width!==e||this.lastDimensions?.height!==t)&&(this.lastDimensions={width:e,height:t},this.emit(Q.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?cP():e||(cP()>2?2:1)}},CF=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let n=e.target,r=e.isIntersecting;n===this.element&&(this.isIntersecting=r,this.isPiP=wF(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var e;this.isPiP=wF(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)})})},this.onLeavePiP=()=>{var e;this.isPiP=wF(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??TF(e),this.isPiP=nP()&&wF(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=TF(this.element),this.isPiP=wF(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,hP().observe(this.element),pP().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=hP())==null||e.unobserve(this.element),(t=pP())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function wF(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?TF(e,window.documentPictureInPicture?.window):!1}function TF(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,s=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var EF=class e extends cj.EventEmitter{get logContext(){return{room:this.room?.name,participant:this.room?.localParticipant.identity}}constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=WA(HA.E2EE,()=>this.logContext),this.onWorkerMessage=e=>{let t=e.data,n=t.kind,r=t.data;switch(n){case`error`:if(r.uuid){let e=this.decryptDataRequests.get(r.uuid);if(e?.reject){e.reject(r.error);break}let t=this.encryptDataRequests.get(r.uuid);if(t?.reject){t.reject(r.error);break}}this.log.error(r.error.message),this.emit(iF.EncryptionError,r.error,r.participantIdentity);break;case`initAck`:r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===this.room?.localParticipant.identity)this.emit(iF.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=this.room?.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${r.participantIdentity}`);this.emit(iF.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(nF.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(r.uuid);e?.resolve&&e.resolve(r);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(r.uuid);t?.resolve&&t.resolve(r);break;case`packetTrailerMetadata`:this.handleFrameMetadata(r.trackId,r.rtpTimestamp,r.ssrc,r.metadata);break;case`log`:KA[r.level](r.msg,r.context)}},this.onWorkerError=e=>{this.log.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(iF.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!oF())throw new NM(`tried to setup end-to-end encryption on an unsupported browser`);if(this.log.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:KA.getLevel()}};this.worker&&(this.log.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var t;(t=this.unsubscribeLogLevel)==null||t.call(this);let n;if(e.disposeRegistry){let t=new WeakRef(this.worker);n=YA(e=>{let r=t.deref();if(!r){n?.();return}r.postMessage({kind:`setLogLevel`,data:{level:e}})}),e.disposeRegistry.register(this,n,this)}else{let e=this.worker;n=YA(t=>{e.postMessage({kind:`setLogLevel`,data:{level:t}})})}this.unsubscribeLogLevel=n}dispose(){var t,n,r;(t=this.unsubscribeLogLevel)==null||t.call(this),this.unsubscribeLogLevel=void 0,e.disposeRegistry&&e.disposeRegistry.unregister(this);let i=new dF(`E2EEManager disposed`,uF.InternalError);for(let e of[...this.encryptDataRequests.values()])(n=e.reject)==null||n.call(e,i);for(let e of[...this.decryptDataRequests.values()])(r=e.reject)==null||r.call(e,i);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setParticipantCryptorEnabled(e,t){this.log.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?this.log.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(let i of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of i.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof SF&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(Z.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Y.TrackPublished,(e,t)=>this.setParticipantCryptorEnabledForPublication(e,t.identity)),e.on(Y.ConnectionStateChanged,t=>{t===MB.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabledForPublication(t,e.identity)})})}).on(Y.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(Y.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(Y.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(X.LocalSenderCreated,(e,t)=>J(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(X.LocalTrackPublished,e=>{if(!MP(e.track)||!ZN())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:_N(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)}),t.on(nF.SetKey,(e,t)=>this.postKey(e,t??!0)).on(nF.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return J(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new bP;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new bP;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,r=e.participantIdentity,i=e.keyIndex;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setParticipantCryptorEnabledForPublication(e,t){if(!e.trackInfo){this.log.warn(`skipping e2ee enabled update for publication without trackInfo`,{trackSid:e.trackSid});return}this.setParticipantCryptorEnabled(e.trackInfo.encryption!==kO.NONE,t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);let r=e.kind===`video`&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?_N(n.mimeType):void 0,r)}setupE2EESender(e,t){if(!AP(e)||!t){t||this.log.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0,MP(e)?e.publishOptions?.frameMetadata??e.publishOptions?.packetTrailer:void 0)}handleReceiver(e,t,n,r,i){return J(this,void 0,void 0,function*(){if(this.worker){if(YN()){let a={kind:`decode`,participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(eF in e&&tF in e){let a={kind:`updateCodec`,data:{trackId:t,previousTrackId:e[tF],codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(a),e[tF]=t;return}let a=e.writableStream,o=e.readableStream;if(!a||!o){let t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,o=t.readable}let s={kind:`decode`,data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(s,[o,a])}e[eF]=!0,e[tF]=t}})}handleSender(e,t,n,r){if(!(eF in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(YN()){this.log.info(`initialize script transform`);let i={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:mF(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{this.log.info(`initialize encoded streams`);let i=e.createEncodedStreams(),a={kind:`encode`,data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:mF(r),packetTrailer:r}};this.worker.postMessage(a,[i.readable,i.writable])}e[eF]=!0}}};EF.disposeRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});var DF=300,OF=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=DF;){let e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},kF=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{let t=e.data;if(t.kind===`metadata`){let e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{UA.error(`frame metadata worker encountered an error:`,{error:e.error})},this.worker=e?.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:`init`})),e.on(Y.TrackSubscribed,(e,t,n)=>{e.kind===`video`&&this.setupReceiver(e,t.trackInfo)}).on(Y.TrackUnsubscribed,e=>{this.teardownTrack(e)}).on(Y.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){let n=e.receiver;if(!n)return;if(!(t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){this.room?.hasE2EESetup||this.setupPassthroughReceiver(n,e.mediaStreamID);return}if(!pF(this.worker?{worker:this.worker}:void 0)&&!this.room?.hasE2EESetup){UA.warn(`frame metadata transform not supported; skipping extraction`);return}let r=new OF,i=e.mediaStreamID;this.extractors.set(i,r),e.frameMetadataExtractor=r,!this.room?.hasE2EESetup&&this.setupWorkerReceiver(n,i,!0)}setupPassthroughReceiver(e,t){if(fF()){`transform`in e&&(e.transform=null);return}if(this.worker&&pF({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(fF()){e.transform=new RTCRtpScriptTransform(r,{kind:`decode`,trackId:t});return}let i=this.workerPipelines.get(e);if(i){let a={kind:`updateTrackId`,data:{oldTrackId:i,newTrackId:t,hasPacketTrailer:n}};r.postMessage(a),this.workerPipelines.set(e,t);return}if(!(`createEncodedStreams`in e)){UA.warn(`createEncodedStreams not supported`);return}let a;try{a=e.createEncodedStreams()}catch(e){UA.warn(`failed to create encoded streams`,{error:e});return}let o={kind:`decode`,data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof SF&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)==null||e.terminate()}},AF=500,jF=15e3,MF=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=aP(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,PN(Math.min(AF*2**n,jF)))}getBackOffPromise(e){let t=new URL(e),n=t&&aP(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&aP(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};MF._instance=null;var NF=`default`,PF=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return J(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){UA.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{UA.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(XN()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=!t||e.kind===t;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return J(this,void 0,void 0,function*(){if(t!==NF)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===NF);if(!i){UA.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==NF&&e.groupId===(n??i.groupId));if(!a){UA.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};PF.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],PF.userMediaPromiseMap=new Map;var FF=65535,IF=4294967295,LF=class e{static u16(t){return new e(t,FF)}static u32(t){return new e(t,IF)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},RF=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*IF);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=LF.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},zF=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function BF(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var VF;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(VF||={});var HF=class e extends AM{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=VF[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,VF.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,VF.Reserved)}},UF={fromNumber(e){if(e===0)throw HF.reserved(e);if(e>FF)throw HF.tooLarge();return e}},WF=class{constructor(){this.value=0}get(){return this.value+=1,this.value>FF?null:this.value}reset(){this.value=0}},GF={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==kO.NONE}},toProtobuf(e){return new MO({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?kO.GCM:kO.NONE})}},KF;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(KF||={});var qF=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new JT,this.nextTaskIndex=0}run(e){return J(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:KF.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=KF.RUNNING,yield e()}finally{t.status=KF.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return J(this,void 0,void 0,function*(){return this.run(()=>J(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},JF=[`client`],YF=class{constructor(){NE(this,`listeners`,new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){let n=this.listeners.get(`*`);if(n)for(let r of n)r(e,t);let r=this.listeners.get(e);if(r)for(let e of r)e(t)}clear(){this.listeners.clear()}},XF=class extends Error{constructor(e,t){super(`non-serializable value at ${e} (${t})`),this.path=e,this.label=t}},ZF=(e,t)=>QF(e,t,new Set),QF=(e,t,n)=>{if(e===null)return null;switch(typeof e){case`string`:case`boolean`:return e;case`number`:if(!Number.isFinite(e))throw new XF(t,eI(e));return e;case`object`:return $F(e,t,n);default:throw new XF(t,typeof e)}},$F=(e,t,n)=>{if(n.has(e))throw new XF(t,`circular reference`);if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new XF(t,`sparse array or array with non-index properties`);n.add(e);let r=e.map((e,r)=>QF(e,`${t}[${r}]`,n));return n.delete(e),r}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new XF(t,e.constructor?.name??`object`);n.add(e);let i={};for(let r of Object.keys(e)){let a=QF(e[r],`${t}.${r}`,n);Object.defineProperty(i,r,{value:a,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),i},eI=e=>Number.isNaN(e)?`NaN`:e>0?`Infinity`:`-Infinity`,tI=function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new Set;if(typeof e!=`object`||!e||t.has(e))return e;if(Array.isArray(e)){t.add(e);let n=e.map(e=>tI(e,t));return t.delete(e),n}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;t.add(e);let r={};for(let n of Object.keys(e)){let i=tI(e[n],t);Object.defineProperty(r,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),r},nI=Symbol(`machina.type`),rI=20,iI=class{constructor(e){NE(this,`id`,void 0),NE(this,`initialState`,void 0),NE(this,nI,`BehavioralFsm`),NE(this,`states`,void 0),NE(this,`emitter`,new YF),NE(this,`clients`,new WeakMap),NE(this,`knownClients`,new Set),NE(this,`childSubscriptions`,[]),NE(this,`disposed`,!1),NE(this,`transitionDepth`,0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){if(this.disposed)return;let n=this.getOrCreateClientMeta(e);var r=[...arguments].slice(2);n.currentActionArgs=r;let i=this.states[n.state]?._child;if(i&&i.canHandle(e,t)){try{i.handle(e,t,...r)}finally{n.currentActionArgs=void 0}return}this.handleLocally(e,t,r,n)}canHandle(e,t){if(this.disposed)return!1;let n=this.clients.get(e)?.state??this.initialState,r=this.states[n];if(r?.[t]??r?.[`*`])return!0;let i=r?._child;return i?i.canHandle(e,t):!1}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){return this.clients.get(e)?.state}transition(e,t){if(this.disposed)return;let n=this.getOrCreateClientMeta(e),r=n.state;if(t!==r){if(!Object.hasOwn(this.states,t)){this.emitter.emit(`invalidstate`,{stateName:t,client:e});return}if(this.transitionDepth++,this.transitionDepth>rI)throw this.transitionDepth=0,Error(`Max transition depth (${rI}) exceeded in FSM "${this.id}". Likely an infinite _onEnter → transition loop.`);try{let i=this.states[r],a=this.states[t];if(i!=null&&i._onExit&&typeof i._onExit==`function`){let t=this.buildHandlerArgs(e,``,n);i._onExit(t)}n.state=t;let o={fromState:r,toState:t,client:e};this.emitter.emit(`transitioning`,o);let s;if(a!=null&&a._onEnter&&typeof a._onEnter==`function`){let t=this.buildHandlerArgs(e,``,n);s=a._onEnter(t)}this.emitter.emit(`transitioned`,o);let c=a?._child;c&&c.reset(e),this.processQueue(e,n),typeof s==`string`&&n.state===t&&this.transition(e,s)}finally{this.transitionDepth--}}}compositeState(e){let t=this.clients.get(e);if(!t)return``;let n=this.states[t.state]?._child;if(n){let r=n.compositeState(e);if(r)return`${t.state}.${r}`}return t.state}rehydrate(e,t){if(this.disposed)return;if(typeof t==`string`){this.rehydrateCompositePath(e,t);return}let n=this.planSnapshotWrites(e,t);for(let e of n)e()}dehydrate(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this.clients.get(e);if(!n)return;let r={state:n.state,deferred:n.deferredQueue.map(e=>this.snapshotDeferredInput(e))},i=this.collectChildSnapshots(e,n.state,t);return i&&(r.children=i),r}planSnapshotWrites(e,t){if(this.disposed)return[];let n=t.state,r=t.deferred,i=t.children;if(!Object.hasOwn(this.states,n))throw Error(`rehydrate: unknown state "${n}" in FSM "${this.id}". Valid states: ${Object.keys(this.states).join(`, `)}`);let a=[];if(i)for(let t of Object.keys(i)){if(!Object.hasOwn(this.states,t))throw Error(`rehydrate: unknown state "${t}" in FSM "${this.id}" referenced by snapshot.children.`);let n=this.states[t]?._child;if(!n)throw Error(`rehydrate: state "${t}" in FSM "${this.id}" has no _child, but the snapshot has a children["${t}"] entry.`);a.push(...n.planRehydrate(e,i[t]))}let o=r.map(e=>RE({inputName:e.inputName,args:tI(e.args)},e.untilState===void 0?{}:{untilState:e.untilState}));return a.push(()=>{this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:n,deferredQueue:o})}),a}rehydrateCompositePath(e,t){let n=VE(t.split(`.`)),r=n[0],i=jE(n).slice(1);if(!Object.hasOwn(this.states,r))throw Error(`rehydrate: unknown state "${r}" in FSM "${this.id}". Valid states: ${Object.keys(this.states).join(`, `)}`);if(i.length>0){let n=i.join(`.`),a=this.states[r]?._child;if(!a)throw Error(`rehydrate: state "${r}" in FSM "${this.id}" has no _child, but composite path "${t}" requires one.`);a.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:r,deferredQueue:[]})}collectChildSnapshots(e,t,n){let r=new Map;for(let e of Object.keys(this.states)){let t=this.states[e]?._child;if(!t)continue;let n=r.get(t.instance);n?n.stateNames.push(e):r.set(t.instance,{childLink:t,stateNames:[e]})}let i;for(let a of r.values()){let r=a.childLink,o=a.stateNames,s=n&&o.includes(t);if(r.instance[nI]===`Fsm`&&!s)continue;let c=r.dehydrate(e,s);if(c){i??={};for(let e of o)i[e]=c}}return i}snapshotDeferredInput(e){let t;try{t=ZF(e.args,`args`)}catch(t){if(!(t instanceof XF))throw t;let n=e.untilState?` (until "${e.untilState}")`:``;throw Error(`dehydrate: deferred input "${e.inputName}"${n} in FSM "${this.id}" has a non-serializable value at ${t.path} (${t.label})`)}let n={inputName:e.inputName,args:t};return e.untilState!==void 0&&(n.untilState=e.untilState),n}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(let e of this.childSubscriptions)e.off();if(!(e!=null&&e.preserveChildren)){let e=new Set;for(let t of Object.keys(this.states)){let n=this.states[t]?._child;n&&!e.has(n.instance)&&(e.add(n.instance),n.dispose())}}this.emitter.clear()}wrapChildLinks(){for(let e of Object.keys(this.states)){let t=this.states[e],n=t?._child;if(n){if(typeof n!=`object`)throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got ${String(n)}`);if(!(nI in n))throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got a plain object`);t._child=aI(n)}}}setupChildSubscriptions(){let e=new Set;for(let t of Object.keys(this.states)){let n=this.states[t]?._child;if(!n||e.has(n.instance))continue;e.add(n.instance);let r=n.onAny((e,t)=>{if(e===`nohandler`){let e=t;if(e.client!==void 0)this.bubbleNohandler(e.client,n,e.inputName,e.args??[]);else for(let t of this.knownClients){let r=t.deref();if(r===void 0){this.knownClients.delete(t);continue}this.bubbleNohandler(r,n,e.inputName,e.args??[])}return}let r=t;if(r&&typeof r==`object`&&`client`in r)this.isChildActiveForClient(r.client,n)&&this.emitter.emit(e,t);else for(let r of this.knownClients){let i=r.deref();if(!i){this.knownClients.delete(r);continue}if(this.isChildActiveForClient(i,n)){this.emitter.emit(e,t);break}}});this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,r){if(!this.isChildActiveForClient(e,t))return;let i=this.clients.get(e);i.currentActionArgs=r,this.handleLocally(e,n,r,i)}isChildActiveForClient(e,t){var n;let r=this.clients.get(e);return r?((n=this.states[r.state])==null||(n=n._child)==null?void 0:n.instance)===t.instance:!1}handleLocally(e,t,n,r){let i=this.states[r.state],a=i?.[t]??i?.[`*`];if(!a){this.emitter.emit(`nohandler`,{inputName:t,args:n,client:e}),r.currentActionArgs=void 0;return}try{this.emitter.emit(`handling`,{inputName:t,client:e});let i=this.buildHandlerArgs(e,t,r),o;typeof a==`string`?o=a:typeof a==`function`&&(o=a(i,...n)),this.emitter.emit(`handled`,{inputName:t,client:e}),typeof o==`string`&&this.transition(e,o)}finally{r.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new WeakRef(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:r=>{if(!n.currentActionArgs)return;let i={inputName:t,args:[...n.currentActionArgs],untilState:r?.until};n.deferredQueue.push(i),this.emitter.emit(`deferred`,{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){let n=[],r=[];for(let e of t.deferredQueue)e.untilState===void 0||e.untilState===t.state?n.push(e):r.push(e);t.deferredQueue=r;for(let t of n)this.handle(e,t.inputName,...t.args)}};function aI(e){if(!e||typeof e!=`object`)throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got ${String(e)}`);let t=e[nI];if(t===`BehavioralFsm`)return{instance:e,canHandle(t,n){return e.canHandle(t,n)},handle(t,n){var r=[...arguments].slice(2);e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny(t){return e.on(`*`,t)},compositeState(t){return e.compositeState(t)},rehydrate(t,n){e.rehydrate(t,n)},dehydrate(t,n){return e.dehydrate(t,n)},planRehydrate(t,n){return e.planSnapshotWrites(t,n)},dispose(){e.dispose()}};if(t===`Fsm`)return{instance:e,canHandle(t,n){return e.canHandle(n)},handle(t,n){var r=[...arguments].slice(2);e.handle(n,...r)},reset(t){e.reset()},onAny(t){return e.on(`*`,t)},compositeState(t){return e.compositeState()},rehydrate(e,t){throw Error(`rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.`)},dehydrate(e,t){throw Error(`dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.`)},planRehydrate(e,t){throw Error(`rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.`)},dispose(){e.dispose()}};throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ${String(t??`undefined`)}`)}var oI=class{constructor(e){NE(this,`id`,void 0),NE(this,`initialState`,void 0),NE(this,nI,`Fsm`),NE(this,`states`,void 0),NE(this,`bfsm`,void 0),NE(this,`context`,void 0),NE(this,`emitter`,new YF),NE(this,`disposed`,!1),this.id=e.id,this.initialState=e.initialState,this.context=e.context??{},this.bfsm=new iI(e),this.states=e.states,this.bfsm.on(`*`,(e,t)=>{if(t&&typeof t==`object`&&`client`in t){t.client;let n=zE(t,JF);this.emitter.emit(e,n)}else this.emitter.emit(e,t)}),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){var t=[...arguments].slice(1);this.bfsm.handle(this.context,e,...t)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function sI(e){return new oI(e)}function cI(e){return e}function lI(e,t){return t.attemptId===e.attemptId}var uI=cI((e,t)=>{let n=e.ctx;if(lI(n,t))return`connected`}),dI=cI(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`connecting`}),fI=cI(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`reconnecting`}),pI=cI((e,t)=>{let n=e.ctx;return n.closeReason=t.reason,`disconnecting`}),mI={new:{connect:dI,close:pI},connecting:{connectComplete:uI,connectFailed:cI((e,t)=>{let n=e.ctx;return n.lastError=t.error,`closed`}),close:pI},connected:{reconnect:fI,transportFailed:cI((e,t)=>{let n=e.ctx;if(lI(n,t))return n.lastError=t.reason,`offline`}),close:pI},offline:{connect:dI,reconnect:fI,close:pI},reconnecting:{reconnectComplete:uI,reconnectFailed:cI((e,t)=>{let n=e.ctx;return n.lastError=t.error,t.recoverable?`offline`:`closed`}),close:pI},disconnecting:{closeComplete:`closed`},closed:{connect:dI,reconnect:fI}};function hI(){return sI({id:`signal`,initialState:arguments.length>0&&arguments[0]!==void 0?arguments[0]:`new`,context:{attemptId:0},states:mI})}var gI=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.closeCode,r=e.reason;return n.close(t,r)};this.opened=new xM((e,t)=>{let i=()=>{t(MM.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let n=t.data;return e.enqueue(n)},n.onerror=t=>e.error(MM.websocket($P(t,`websocket`))),n.onclose=t=>{t.wasClean||t.code===1e3?e.close():e.error(MM.websocket(`WS closed unexpectedly with code ${t.code}`))}},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new xM((e,t)=>{let r=()=>J(this,void 0,void 0,function*(){let r=new xM(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield xM.race([PN(250),r]);i?e(i):t(MM.websocket(`Encountered unspecified websocket error without a timely close event`))});n.addEventListener(`close`,t=>{let i=t.code,a=t.reason;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)}),n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},_I=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function vI(e){return e instanceof MM?e.reason!==jM.LeaveRequest&&e.reason!==jM.NotAllowed:!0}function yI(e){let t=_I.indexOf(e.case)>=0;return UA.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var bI;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(bI||={});function xI(e){switch(e){case`connected`:return bI.CONNECTED;case`connecting`:return bI.CONNECTING;case`reconnecting`:return bI.RECONNECTING;case`disconnecting`:return bI.DISCONNECTING;default:return bI.DISCONNECTED}}var SI=250,CI=5e3,wI=class{get currentState(){return xI(this.lifecycleState)}get isDisconnected(){let e=this.currentState;return e===bI.DISCONNECTING||e===bI.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){let t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return J(this,void 0,void 0,function*(){this.log.debug(`waiting for an in-flight close to settle before establishing a session`),(yield this.closingLock.lock())()})}get isEstablishingConnection(){return this.lifecycleState===`connecting`||this.lifecycleState===`reconnecting`}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.log=UA,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=WA(t.loggerName??HA.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new qF,this.queuedRequests=[],this.closingLock=new JT,this.connectionLock=new JT,this.machine=hI(),this.machine.on(`transitioned`,e=>{let t=e.fromState,n=e.toState;this.log.debug(`signal lifecycle: ${t} -> ${n}`)}),this.machine.on(`nohandler`,e=>{let t=e.inputName;this.log.debug(`ignoring signal lifecycle input ${t} in state ${this.lifecycleState}`)}),this.machine}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){if(i.lifecycleState===`disconnecting`&&(yield i.settleInFlightClose()),!i.sendLifecycleInput({type:`connect`}))throw MM.internal(`cannot establish a signal session from '${i.lifecycleState}', close the current one first`);i.options=n;try{return yield i.connect(e,t,n,r,a,o)}catch(e){throw i.sendLifecycleInput({type:`connectFailed`,error:e}),e}}()})}reconnect(e,t,n,r){return J(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`);return}if(this.lifecycleState===`disconnecting`&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:`reconnect`}))throw MM.internal(`cannot resume the signal session from '${this.lifecycleState}'`);this.clearPingInterval();try{return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(e){throw this.sendLifecycleInput({type:`reconnectFailed`,error:e,recoverable:vI(e)}),e}})}connect(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=gP(n.clientInfoCapabilities),l=KP(e,a?DI(t,c,n):yield OI(t,c,n,o),a).toString(),u=JP(l).toString();return new Promise((e,t)=>J(i,void 0,void 0,function*(){try{let i=!1,a=e=>J(this,void 0,void 0,function*(){if(i)return;i=!0;let n=QP(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(e instanceof MM?e:MM.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(MM.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=new URL(l);if(c.searchParams.has(`access_token`)&&c.searchParams.set(`access_token`,`<redacted>`),this.ws){let e=performance.now();yield this.teardownTransport(`replaced by a new connection attempt`),this.log.debug(`closed previous ws connection in ${performance.now()-e}ms`)}let d=this.attemptId;this.log.info(`signal connecting to ${c}`,{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws=new gI(l);let f=!1;this.ws.opened.catch(()=>{f=!0});try{this.ws.closed.then(e=>{this.isEstablishingConnection&&!f&&t(MM.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),this.log.debug(`websocket closed`,{reason:e.reason,code:e.closeCode,attemptId:d,state:this.lifecycleState}),this.handleOnClose(e.reason||(e.closeCode===1e3?`server closed the signal connection`:`Unexpected WS error`),d)}).catch(e=>{this.isEstablishingConnection&&!f&&t(MM.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>J(this,void 0,void 0,function*(){if(this.lifecycleState!==`connected`){clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a,o;try{a=yield Promise.race([i.read(),new Promise((e,t)=>{o=setTimeout(()=>{t(MM.timeout(`signal connection timed out while waiting for the first message`))},CI)})])}catch(e){i.releaseLock(),t(e),this.close();return}finally{clearTimeout(o)}if(i.releaseLock(),!a.value)throw MM.internal(`no message received as first message`);let c=ZP(a.value),l=this.validateFirstMessage(c,n.reconnect??!1);if(!l.isValid){t(l.error);return}c.message?.case===`join`&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));let p=l.shouldProcessFirstMessage?c:void 0;this.handleSignalConnected(r,s,d,p),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return J(this,void 0,void 0,function*(){t&&this.handleSignalResponse(t);let n=this.attemptId;for(;;){this.signalLatency&&(yield PN(this.signalLatency));try{let t=yield e.read(),n=t.done,r=t.value;if(n)break;let i=ZP(r);this.handleSignalResponse(i)}catch(e){this.log.error(`error reading from signal stream`,{error:e}),yield this.handleOnClose(`error in reading loop`,n);break}}})}close(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){let r=t&&e.sendLifecycleInput({type:`close`,reason:n}),i=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{r&&e.sendLifecycleInput({type:`closeComplete`}),i()}}()})}teardownTransport(e){return J(this,void 0,void 0,function*(){try{if(this.clearPingInterval(),this.ws){this.ws.close({closeCode:1e3,reason:e});let t=this.ws.closed;this.ws=void 0,this.streamWriter=void 0,yield Promise.race([t,PN(SI)])}}catch(e){this.log.debug(`websocket error while closing`,{error:e})}})}sendOffer(e,t){this.log.debug(`sending offer`,{offerSdp:e.sdp}),this.sendRequest({case:`offer`,value:EI(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,{answerSdp:e.sdp}),this.sendRequest({case:`answer`,value:EI(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,{candidate:e}),this.sendRequest({case:`trickle`,value:new Fk({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new Ik({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new nA({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new tA({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new hA({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:TE.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new SA({timestamp:TE.parse(Date.now()),rtt:TE.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new Zk({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new $k({reason:_O.CLIENT_INITIATED,action:eA.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new kk({pubHandle:e,name:t,encryption:n?kO.GCM:kO.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new jk({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Wk({updates:[new Gk({trackSid:e,subscribe:t})]})})}sendRequest(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let r=!n&&!yI(e),i=t.lifecycleState===`reconnecting`||t.queuedRequests.length>0;if(r&&i){t.queuedRequests.push(()=>J(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}n||(yield t.requestQueue.flush()),t.signalLatency&&(yield PN(t.signalLatency));let a=e.case===`leave`&&!!t.streamWriter;if(t.isDisconnected&&!a){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`);return}let o=new Tk({message:e});try{t.useJSON?yield t.streamWriter.write(o.toJsonString()):yield t.streamWriter.write(o.toBinary().buffer)}catch(e){t.log.error(`error sending signal message`,{error:e})}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`);return}let n=!1;if(t.case===`answer`){let e=TI(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=TI(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,{msgCase:t.case}));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.attemptId;return function*(){let r=t.onClose;if(!t.sendLifecycleInput({type:`transportFailed`,attemptId:n,reason:e})){t.log.debug(`ignoring transport close in state ${t.lifecycleState}`,{reason:e,attemptId:n,currentAttemptId:t.attemptId});return}yield t.teardownTransport(e),t.log.info(`websocket connection closed: ${e}`,{reason:e}),r&&r(e)}()})}handleWSError(e){this.log.error(`websocket error`,{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`);return}this.pingTimeout=GM.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&GM.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`);return}this.log.debug(`start ping interval`),this.pingInterval=GM.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`),this.clearPingTimeout(),this.pingInterval&&GM.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n,r){if(clearTimeout(t),!this.sendLifecycleInput(this.lifecycleState===`reconnecting`?{type:`reconnectComplete`,attemptId:n}:{type:`connectComplete`,attemptId:n})){this.log.debug(`discarding a connection whose attempt no longer owns the session`,{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState});return}this.log.info(`signal connected`),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),r)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.lifecycleState===`reconnecting`&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:MM.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:MM.internal(`Unexpected first message`)}:{isValid:!1,error:MM.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return J(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:let e=yield n.text();return e.includes(`requested room does not exist`)?MM.notAllowed(e,n.status):MM.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let t=yield n.text();return MM.notAllowed(t,n.status)}return e instanceof MM?e:MM.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof MM?e:MM.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function TI(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type}return t}function EI(e,t){return new Vk({sdp:e.sdp,type:e.type,id:t})}function DI(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,rP()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),r.set(`client_protocol`,t.clientProtocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function OI(e,t,n,r){return J(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new jA({clientInfo:t,connectionSettings:new AA({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(UP()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let e=yield r.read(),t=e.done,i=e.value;if(t)break;n.push(i)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=NA.GZIP}else s=o,c=NA.NONE;let l=new MA({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var kI=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let n of this._map.entries()){var t=K(n,2);let r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let n of this._map.entries()){var t=K(n,2);let r=t[0],i=t[1];i.expiresAt>=Date.now()&&e(i.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let i of n.entries()){var r=K(i,2);let a=r[0],o=r[1];t.push(e(o,a,n))}return t}asValueMap(){let e=new Map;for(let n of this._map.entries()){var t=K(n,2);let r=t[0],i=t[1];i.expiresAt>=Date.now()&&e.set(r,i.value)}return e}},AI={},jI={},MI={exports:{}},NI;function PI(){if(NI)return MI.exports;NI=1;var e=MI.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),MI.exports}var FI;function II(){return FI?jI:(FI=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=PI(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(jI),jI)}var LI,RI;function zI(){if(RI)return LI;RI=1;var e=PI(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return LI=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
98
+ `);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function bM(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;n&&n.length!==0&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function xM(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;n&&n.length!==0&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var SM=Object.freeze({__proto__:null,removeExtmapAllowMixed:yM,shimAddIceCandidateNullOrEmpty:bM,shimConnectionState:vM,shimMaxMessageSize:gM,shimParameterlessSetLocalDescription:xM,shimRTCIceCandidate:mM,shimRTCIceCandidateRelayProtocol:hM,shimSendThrowTypeError:_M});function CM(){let e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}).window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=bj,r=Sj(e),i={browserDetails:r,commonShim:SM,extractVersion:gj,disableLog:vj,disableWarnings:yj,sdp:pM};switch(r.browser){case`chrome`:if(!Lj||!Fj||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=Lj,bM(e,r),xM(e),Oj(e,r),kj(e),Fj(e,r),Aj(e,r),Pj(e,r),jj(e),Mj(e,r),Ij(e,r),mM(e),hM(e),vM(e),gM(e,r),_M(e,r),yM(e,r);break;case`firefox`:if(!Zj||!Vj||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=Zj,bM(e,r),xM(e),Rj(e,r),Vj(e,r),Hj(e,r),Bj(e),Gj(e),Uj(e),Wj(e),Kj(e),qj(e,r),Jj(e,r),Yj(e,r),Xj(e,r),mM(e),vM(e),gM(e,r),_M(e,r);break;case`safari`:if(!sM||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=sM,bM(e,r),xM(e),rM(e),aM(e),eM(e),Qj(e),$j(e),iM(e),tM(e),oM(e),mM(e),hM(e),gM(e,r),_M(e,r),yM(e,r);break;default:n(`Unsupported browser!`)}return i}CM({window:typeof window>`u`?void 0:window});var wM,TM,EM=class extends (TM=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};wM=EM,EM.resolve=e=>Reflect.get(TM,`resolve`,wM).call(wM,e);var DM=/version\/(\d+(\.?_?\d+)+)/i,OM;function kM(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(OM===void 0||t)&&(OM=AM.find(e=>e.test.test(n))?.describe(n)),OM}var AM=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:jM(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:MM(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:jM(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:MM(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:jM(DM,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:MM(e)}}}];function jM(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function MM(e){return e.includes(`mac os`)?jM(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var NM=`2.22.3`,PM=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},FM=class extends PM{},IM;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(IM||={});var LM=class e extends FM{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=IM[t]}static notAllowed(t,n,r){return new e(t,IM.NotAllowed,n,r)}static timeout(t){return new e(t,IM.Timeout)}static leaveRequest(t,n){return new e(t,IM.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,IM.InternalError,void 0,n)}static cancelled(t){return new e(t,IM.Cancelled)}static serverUnreachable(t,n){return new e(t,IM.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,IM.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,IM.ServiceNotFound,void 0,n)}},RM=class extends PM{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},zM=class extends PM{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},BM=class extends PM{constructor(e){super(10,e||`unsupported server`),this.name=`UnsupportedServer`}},VM=class extends PM{constructor(e){super(12,e||`unexpected connection state`),this.name=`UnexpectedConnectionState`}},HM=class extends PM{constructor(e){super(13,e||`unable to negotiate`),this.name=`NegotiationError`}},UM=class extends PM{constructor(e){super(14,e||`unable to publish data`),this.name=`PublishDataError`}},WM=class extends PM{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},GM=class extends FM{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:NA[t]}},KM;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`,e[e.HeaderTooLarge=9]=`HeaderTooLarge`,e[e.PayloadTooLarge=10]=`PayloadTooLarge`})(KM||={});var qM=class extends FM{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=KM[t]}},JM=class extends PM{constructor(e){super(18,e),this.name=`SignalReconnectError`}},YM;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(YM||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(YM||={});var XM=class{};XM.setTimeout=function(){return setTimeout(...arguments)},XM.setInterval=function(){return setInterval(...arguments)},XM.clearTimeout=function(){return clearTimeout(...arguments)},XM.clearInterval=function(){return clearInterval(...arguments)};var Y;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(Y||={});var X;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(X||={});var Z;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`,e.TokenRefreshed=`tokenRefreshed`,e.ServerRegionsReported=`serverRegionsReported`})(Z||={});var Q;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(Q||={});function ZM(e){let t={};for(let r of Object.entries(e)){var n=K(r,2);let e=n[0],i=n[1];i!==void 0&&(t[e]=i)}return t}function QM(e,t){return e&&t?`${e}x${t}`:void 0}function $M(e){return Math.round(e*1e4)/1e4}function eN(e){let t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return t!==void 0&&n?$M(t/n):void 0}function tN(e,t){if(e.playoutDelay!==void 0)return $M(e.playoutDelay);let n=t?.totalPlayoutDelay,r=t?.totalSamplesCount;return n!==void 0&&r?$M(n/r):void 0}function nN(e){let t=new Map,n=[],r=[],i=[],a;e.forEach(e=>t.set(e.id,e));let o=e=>e.codecId?t.get(e.codecId)?.mimeType:void 0,s=(e,n)=>e[n]?t.get(e[n]):void 0;e.forEach(e=>{switch(e.type){case`inbound-rtp`:{let t=s(e,`playoutId`);r.push(ZM({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:o(e),decoder:e.decoderImplementation,resolution:QM(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:eN(e),playoutDelay:tN(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case`outbound-rtp`:{let t=s(e,`remoteId`),n=s(e,`mediaSourceId`);i.push(ZM({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:n?.trackIdentifier,active:e.active,codec:o(e),encoder:e.encoderImplementation,resolution:QM(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:QM(n?.width,n?.height),captureFps:n?.framesPerSecond,audioLevel:n?.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:e.qualityLimitationReason===`none`?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:t?.packetsLost,remoteFractionLost:t?.fractionLost,remoteJitter:t?.jitter,remoteRoundTripTime:t?.roundTripTime}));break}case`transport`:a=e;break;case`candidate-pair`:n.push(e)}});let c=a?.selectedCandidatePairId,l=(c?t.get(c):void 0)??n.find(e=>e.selected)??n.find(e=>e.nominated),u=l?.localCandidateId?t.get(l.localCandidateId):void 0,d=l?.remoteCandidateId?t.get(l.remoteCandidateId):void 0,f=ZM({ice:a?.iceState,dtls:a?.dtlsState,route:u&&d?`${u.candidateType}/${u.protocol} -> ${d.candidateType}`:void 0,network:u?.networkType,currentRoundTripTime:l?.currentRoundTripTime,availableOutgoingBitrate:l?.availableOutgoingBitrate,availableIncomingBitrate:l?.availableIncomingBitrate,bytesSent:l?.bytesSent,bytesReceived:l?.bytesReceived,candidatePairChanges:a?.selectedCandidatePairChanges});return{connection:Object.keys(f).length>0?f:void 0,outbound:i.length>0?i:void 0,inbound:r.length>0?r:void 0}}function rN(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var iN=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},aN=[`vp8`,`h264`],oN=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function sN(e){return!!aN.find(t=>t===e)}var cN=sN,lN;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(lN||={});var uN;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(uN||={});var dN={h90:new iN(160,90,9e4,20),h180:new iN(320,180,16e4,20),h216:new iN(384,216,18e4,20),h360:new iN(640,360,45e4,20),h540:new iN(960,540,8e5,25),h720:new iN(1280,720,17e5,30),h1080:new iN(1920,1080,3e6,30),h1440:new iN(2560,1440,5e6,30),h2160:new iN(3840,2160,8e6,30)},fN={h120:new iN(160,120,7e4,20),h180:new iN(240,180,125e3,20),h240:new iN(320,240,14e4,20),h360:new iN(480,360,33e4,20),h480:new iN(640,480,5e5,20),h540:new iN(720,540,6e5,25),h720:new iN(960,720,13e5,30),h1080:new iN(1440,1080,23e5,30),h1440:new iN(1920,1440,38e5,30)},pN={h360fps3:new iN(640,360,2e5,3,`medium`),h360fps15:new iN(640,360,4e5,15,`medium`),h720fps5:new iN(1280,720,8e5,5,`medium`),h720fps15:new iN(1280,720,15e5,15,`medium`),h720fps30:new iN(1280,720,2e6,30,`medium`),h1080fps15:new iN(1920,1080,25e5,15,`medium`),h1080fps30:new iN(1920,1080,5e6,30,`medium`),original:new iN(0,0,7e6,30,`medium`)};function mN(e,t,n){var r,i;let a=DN(e??{}),o=a.optionsWithoutProcessor,s=a.audioProcessor,c=a.videoProcessor,l=t?.processor,u=n?.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(hN(d.audio,t),(r=d.audio).deviceId??(r.deviceId={ideal:`default`}),(s||l)&&(d.audio.processor=s??l)),d.video&&(hN(d.video,n),(i=d.video).deviceId??(i.deviceId={ideal:`default`}),(c||u)&&(d.video.processor=c??u)),d}function hN(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function gN(e){var t,n;let r={};if(e.video){if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:hN(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1}else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function _N(e){return J(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=vN();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield zN(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function vN(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>J(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function yN(e){return e===`audioinput`?$.Source.Microphone:e===`videoinput`?$.Source.Camera:$.Source.Unknown}function bN(e){if(e===$.Source.Microphone)return`audioinput`;if(e===$.Source.Camera)return`videoinput`}function xN(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=tP()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function SN(e){return e.split(`/`)[1].toLowerCase()}function CN(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Wk({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function wN(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?wN(e.track):{})}}function TN(){return typeof RTCRtpReceiver<`u`&&typeof RTCRtpReceiver.prototype.getSynchronizationSources==`function`}function EN(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function DN(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:rN(t)}}function ON(e){switch(e){case vO.CAMERA:return $.Source.Camera;case vO.MICROPHONE:return $.Source.Microphone;case vO.SCREEN_SHARE:return $.Source.ScreenShare;case vO.SCREEN_SHARE_AUDIO:return $.Source.ScreenShareAudio;default:return $.Source.Unknown}}function kN(e,t){return e.width*e.height<t.width*t.height}function AN(e,t){return e.layers?.find(e=>e.quality===t)}var jN=5e3,MN=[],NN;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(NN||={});var $=class e extends pj.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug(`stream state changed: ${this._streamState} -> ${e}`),this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=JA,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),jN):this.handleAppVisibilityChanged()},this.loggerContextCb=r.loggerContextCb,this.log=YA(r.loggerName??qA.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),wN(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(MN.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&MN.splice(MN.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),PN(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?Q.AudioPlaybackStarted:Q.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?Q.AudioPlaybackFailed:Q.VideoPlaybackFailed,e):e.name===`AbortError`?this.log.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):this.log.warn(`could not playback ${i?`audio`:`video`}`,{error:e}),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(Q.ElementAttached,t),t}detach(e){try{if(e){FN(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Q.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{FN(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Q.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.log.debug(`stopping track`),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle!==void 0&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then(e=>{e&&this.log.info(`final track stats`,nN(e))}).catch(e=>this.log.debug(`could not collect final track stats`,{error:e})))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=YA(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),MN.forEach(e=>{e.parentElement||(t=!1)}),t&&MN.push(e)}}handleAppVisibilityChanged(){return J(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){sP()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){sP()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function PN(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!tP()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(tP()||QN())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function FN(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),t.srcObject=n.getTracks().length>0?n:null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return _O.AUDIO;case t.Video:return _O.VIDEO;default:return _O.DATA}}e.kindToProto=i;function a(e){switch(e){case _O.AUDIO:return t.Audio;case _O.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return vO.CAMERA;case n.Microphone:return vO.MICROPHONE;case n.ScreenShare:return vO.SCREEN_SHARE;case n.ScreenShareAudio:return vO.SCREEN_SHARE_AUDIO;default:return vO.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case vO.CAMERA:return n.Camera;case vO.MICROPHONE:return n.Microphone;case vO.SCREEN_SHARE:return n.ScreenShare;case vO.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case Ok.ACTIVE:return r.Active;case Ok.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})($||={});var IN=`|`,LN=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function RN(e){let t=e.split(IN);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function zN(e){return new EM(t=>XM.setTimeout(t,e))}function BN(){return`addTransceiver`in RTCPeerConnection.prototype}function VN(){return`addTrack`in RTCPeerConnection.prototype}function HN(){if(!(`getCapabilities`in RTCRtpSender)||tP()||QN())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function UN(){if(!(`getCapabilities`in RTCRtpSender)||QN())return!1;if(tP()){let e=kM();if(e?.version&&mP(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&mP(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function WN(e){return e===`av1`||e===`vp9`}function GN(e){let t=e.getHeaderExtensionsToNegotiate?.call(e);if(!t||!e.setHeaderExtensionsToNegotiate)return!1;let n=t.find(e=>e.uri===LN);if(!n)return!1;if(n.direction!==`stopped`)return!0;n.direction=`sendrecv`;try{return e.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function KN(e,t){return WN(e)&&!!t?.simulcast&&!!t.scalabilityMode?.startsWith(`L1T`)}function qN(){let e=kM();return nP()||cP()||e?.name===`Chrome`&&mP(e.version,`113`)<0}var JN=`1.13.6`;function YN(e){return e?mP(e,JN)>0:!1}function XN(e){return!document||nP()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function ZN(){return typeof RTCPeerConnection>`u`?!1:BN()||VN()}function QN(){return kM()?.name===`Firefox`}function $N(){let e=kM();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function eP(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0&&!$N()}function tP(){return kM()?.name===`Safari`}function nP(){let e=kM();return e?.name===`Safari`||e?.os===`iOS`}function rP(){let e=kM();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&mP(e.osVersion,`17`)>=0}function iP(e){return e||=kM(),e?.name===`Safari`&&mP(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&mP(e.osVersion,`18.3`)>0}function aP(){return sP()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function oP(){let e=kM(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&mP(e.osVersion,t)>=0?!0:e.name===`Safari`&&mP(e.version,t)>=0}function sP(){return typeof document<`u`}function cP(){return navigator.product==`ReactNative`}function lP(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function uP(e){return lP(e)?e.hostname.split(`.`)[0]:null}function dP(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function fP(){if(!cP())return;let e=dP();if(e)return e.platform}function pP(){if(sP())return window.devicePixelRatio;if(cP()){let e=dP();if(e)return e.devicePixelRatio}return 1}function mP(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function hP(e){for(let t of e)t.target.handleResize(t)}function gP(e){for(let t of e)t.target.handleVisibilityChanged(t)}var _P=null,vP=()=>(_P||=new ResizeObserver(hP),_P),yP=null,bP=()=>(yP||=new IntersectionObserver(gP,{root:null,rootMargin:`0px`}),yP);function xP(e){let t=new fk({capabilities:e,sdk:pk.JS,protocol:17,clientProtocol:2,version:NM});return cP()&&(t.os=fP()??``),t}function SP(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let o=K(i.captureStream().getTracks(),1)[0];if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var CP;function wP(){if(!CP){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),CP=K(r.stream.getAudioTracks(),1)[0],!CP)throw Error(`Could not get empty media stream audio track`);CP.enabled=!1}return CP.clone()}var TP=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>J(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function EP(e){return oN.includes(e)}function DP(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function OP(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function kP(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function AP(e,t){return e.segments.map(e=>{let n=e.id,r=e.text,i=e.language,a=e.startTime,o=e.endTime,s=e.final,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function jP(e){let t=e.id,n=e.timestamp,r=e.message,i=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function MP(e){switch(e.reason){case IM.LeaveRequest:return e.context;case IM.Cancelled:return SO.CLIENT_INITIATED;case IM.NotAllowed:return SO.USER_REJECTED;case IM.ServerUnreachable:return SO.JOIN_FAILURE;default:return SO.UNKNOWN_REASON}}function NP(e){return e===void 0?void 0:Number(e)}function PP(e){return e===void 0?void 0:BigInt(e)}function FP(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function IP(e){return!!e&&e.kind==$.Kind.Audio}function LP(e){return!!e&&e.kind==$.Kind.Video}function RP(e){return FP(e)&&LP(e)}function zP(e){return FP(e)&&IP(e)}function BP(e){return!!e&&!e.isLocal}function VP(e){return!!e&&!e.isLocal}function HP(e){return BP(e)&&LP(e)}function UP(e){return e.isLocal}function WP(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function GP(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function KP(e,t){return sj(this,arguments,function*(){let n=e.getReader(),r=new Uint8Array;try{for(;;){let e=yield oj(n.read()),i=e.done,a=e.value;if(i)break;if(a.byteLength===0)continue;let o=new Uint8Array(r.byteLength+a.byteLength);for(o.set(r),o.set(a,r.byteLength),r=o;r.byteLength>=t;)yield yield oj(r.slice(0,t)),r=r.slice(t)}r.byteLength>0&&(yield yield oj(r))}finally{n.releaseLock()}})}function qP(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function JP(){return typeof CompressionStream<`u`}function YP(){return JP()&&!QN()}function XP(e,t){let n=K(RN(t.id),2)[1];if(n?.startsWith(`TR`))return n;if(e.id.startsWith(`TR`))return e.id}function ZP(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=QP(e,t);return n?r:tF(r,`v1`)}function QP(e,t){let n=new URL(OP(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),tF(n,`rtc`)}function $P(e){return tF(new URL(kP(e)),`validate`)}function eF(e){return e.endsWith(`/`)?e:`${e}/`}function tF(e,t){return e.pathname=`${eF(e.pathname)}${t}`,e}function nF(e){if(typeof e==`string`)return jk.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return jk.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function rF(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}function iF(e,t){return e instanceof Error?e.name&&e.message?`${e.name}: ${e.message}`:e.name:`Encountered unknown ${t} error: ${String(e)}`}var aF=`lk_e2ee`,oF=`lk_e2ee_track_id`,sF;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(sF||={});var cF;(function(e){e.KeyRatcheted=`keyRatcheted`})(cF||={});var lF;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(lF||={});var uF;(function(e){e.Error=`cryptorError`})(uF||={});function dF(){return pF()||fF()}function fF(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0}function pF(){return typeof window<`u`&&window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function mF(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new ZO({value:e.value})}pj.EventEmitter;var hF;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(hF||={});var gF=class extends PM{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:hF.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}};function _F(){return eP()}function vF(e){return!!e?.worker&&(pF()||_F())}function yF(e){return!!(e?.timestamp||e?.frameId)}function bF(e){let t=[];return e?.timestamp&&t.push(EO.PTF_USER_TIMESTAMP),e?.frameId&&t.push(EO.PTF_FRAME_ID),t}function xF(e){if(!e||e.length===0)return;let t={};return e.includes(EO.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(EO.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}function SF(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){var t=[...arguments];let n=this;return new Promise((o,u)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let r=e.apply(n,t);a&&a(r),c.forEach(e=>{let t=e.resolve;return t(r)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&XM.clearTimeout(r),r=XM.setTimeout(d,l()),f){let r=e.apply(n,t);return a&&a(r),o(r)}c.push({resolve:o,reject:u})})};return u.cancel=function(e){r!==void 0&&XM.clearTimeout(r),c.forEach(t=>{let n=t.reject;return n(e)}),c=[]},u}var CF=2e3;function wF(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var TF=class extends ${constructor(e,t,n,r,i){super(e,n,i),this.timeSyncLoop=()=>{if(this.listenerCount(Q.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);let e=this.receiver?.getSynchronizationSources()[0];if(e){let t=e.timestamp,n=e.rtpTimestamp;n&&this.rtpTimestamp!==n&&(this.emit(Q.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}},this.onTimeSyncListenerAdded=e=>{e===Q.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Q.Muted:Q.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Q.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return J(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),CF),TN()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off(`newListener`,this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){let e=this;e.off(`newListener`,this.onTimeSyncListenerAdded),e.on(`newListener`,this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}},EF=100,DF=class extends TF{constructor(e,t,n,r,i){super(e,t,$.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>J(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=wF(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=SF(()=>{this.updateDimensions()},EF),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;return this.frameMetadataExtractor?.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===$.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?FN(this._mediaStreamTrack,t):PN(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new OF(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return J(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(this.lastVisible!==i||e){if(!i&&Date.now()-t<EF){XM.setTimeout(()=>{this.updateVisibility()},EF);return}this.lastVisible=i,this.emit(Q.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}(this.lastDimensions?.width!==e||this.lastDimensions?.height!==t)&&(this.lastDimensions={width:e,height:t},this.emit(Q.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?pP():e||(pP()>2?2:1)}},OF=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let n=e.target,r=e.isIntersecting;n===this.element&&(this.isIntersecting=r,this.isPiP=kF(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var e;this.isPiP=kF(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)})})},this.onLeavePiP=()=>{var e;this.isPiP=kF(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??AF(e),this.isPiP=sP()&&kF(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=AF(this.element),this.isPiP=kF(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,bP().observe(this.element),vP().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=bP())==null||e.unobserve(this.element),(t=vP())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function kF(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?AF(e,window.documentPictureInPicture?.window):!1}function AF(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,s=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var jF=class e extends pj.EventEmitter{get logContext(){return{room:this.room?.name,participant:this.room?.localParticipant.identity}}constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=YA(qA.E2EE,()=>this.logContext),this.onWorkerMessage=e=>{let t=e.data,n=t.kind,r=t.data;switch(n){case`error`:if(r.uuid){let e=this.decryptDataRequests.get(r.uuid);if(e?.reject){e.reject(r.error);break}let t=this.encryptDataRequests.get(r.uuid);if(t?.reject){t.reject(r.error);break}}this.log.error(r.error.message),this.emit(lF.EncryptionError,r.error,r.participantIdentity);break;case`initAck`:r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===this.room?.localParticipant.identity)this.emit(lF.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=this.room?.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${r.participantIdentity}`);this.emit(lF.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(sF.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(r.uuid);e?.resolve&&e.resolve(r);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(r.uuid);t?.resolve&&t.resolve(r);break;case`packetTrailerMetadata`:this.handleFrameMetadata(r.trackId,r.rtpTimestamp,r.ssrc,r.metadata);break;case`log`:ZA[r.level](r.msg,r.context)}},this.onWorkerError=e=>{this.log.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(lF.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!dF())throw new RM(`tried to setup end-to-end encryption on an unsupported browser`);if(this.log.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:ZA.getLevel()}};this.worker&&(this.log.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var t;(t=this.unsubscribeLogLevel)==null||t.call(this);let n;if(e.disposeRegistry){let t=new WeakRef(this.worker);n=ej(e=>{let r=t.deref();if(!r){n?.();return}r.postMessage({kind:`setLogLevel`,data:{level:e}})}),e.disposeRegistry.register(this,n,this)}else{let e=this.worker;n=ej(t=>{e.postMessage({kind:`setLogLevel`,data:{level:t}})})}this.unsubscribeLogLevel=n}dispose(){var t,n,r;(t=this.unsubscribeLogLevel)==null||t.call(this),this.unsubscribeLogLevel=void 0,e.disposeRegistry&&e.disposeRegistry.unregister(this);let i=new gF(`E2EEManager disposed`,hF.InternalError);for(let e of[...this.encryptDataRequests.values()])(n=e.reject)==null||n.call(e,i);for(let e of[...this.decryptDataRequests.values()])(r=e.reject)==null||r.call(e,i);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setParticipantCryptorEnabled(e,t){this.log.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?this.log.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(let i of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of i.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof DF&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(Z.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Y.TrackPublished,(e,t)=>this.setParticipantCryptorEnabledForPublication(e,t.identity)),e.on(Y.ConnectionStateChanged,t=>{t===LB.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabledForPublication(t,e.identity)})})}).on(Y.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(Y.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(Y.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(X.LocalSenderCreated,(e,t)=>J(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(X.LocalTrackPublished,e=>{if(!LP(e.track)||!nP())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:SN(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)}),t.on(sF.SetKey,(e,t)=>this.postKey(e,t??!0)).on(sF.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return J(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new TP;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new TP;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,r=e.participantIdentity,i=e.keyIndex;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setParticipantCryptorEnabledForPublication(e,t){if(!e.trackInfo){this.log.warn(`skipping e2ee enabled update for publication without trackInfo`,{trackSid:e.trackSid});return}this.setParticipantCryptorEnabled(e.trackInfo.encryption!==PO.NONE,t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);let r=e.kind===`video`&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?SN(n.mimeType):void 0,r)}setupE2EESender(e,t){if(!FP(e)||!t){t||this.log.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0,LP(e)?e.publishOptions?.frameMetadata??e.publishOptions?.packetTrailer:void 0)}handleReceiver(e,t,n,r,i){return J(this,void 0,void 0,function*(){if(this.worker){if(eP()){let a={kind:`decode`,participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(aF in e&&oF in e){let a={kind:`updateCodec`,data:{trackId:t,previousTrackId:e[oF],codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(a),e[oF]=t;return}let a=e.writableStream,o=e.readableStream;if(!a||!o){let t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,o=t.readable}let s={kind:`decode`,data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(s,[o,a])}e[aF]=!0,e[oF]=t}})}handleSender(e,t,n,r){if(!(aF in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(eP()){this.log.info(`initialize script transform`);let i={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:yF(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{this.log.info(`initialize encoded streams`);let i=e.createEncodedStreams(),a={kind:`encode`,data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:yF(r),packetTrailer:r}};this.worker.postMessage(a,[i.readable,i.writable])}e[aF]=!0}}};jF.disposeRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});var MF=300,NF=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=MF;){let e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},PF=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{let t=e.data;if(t.kind===`metadata`){let e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{JA.error(`frame metadata worker encountered an error:`,{error:e.error})},this.worker=e?.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:`init`})),e.on(Y.TrackSubscribed,(e,t,n)=>{e.kind===`video`&&this.setupReceiver(e,t.trackInfo)}).on(Y.TrackUnsubscribed,e=>{this.teardownTrack(e)}).on(Y.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){let n=e.receiver;if(!n)return;if(!(t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){this.room?.hasE2EESetup||this.setupPassthroughReceiver(n,e.mediaStreamID);return}if(!vF(this.worker?{worker:this.worker}:void 0)&&!this.room?.hasE2EESetup){JA.warn(`frame metadata transform not supported; skipping extraction`);return}let r=new NF,i=e.mediaStreamID;this.extractors.set(i,r),e.frameMetadataExtractor=r,!this.room?.hasE2EESetup&&this.setupWorkerReceiver(n,i,!0)}setupPassthroughReceiver(e,t){if(_F()){`transform`in e&&(e.transform=null);return}if(this.worker&&vF({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(_F()){e.transform=new RTCRtpScriptTransform(r,{kind:`decode`,trackId:t});return}let i=this.workerPipelines.get(e);if(i){let a={kind:`updateTrackId`,data:{oldTrackId:i,newTrackId:t,hasPacketTrailer:n}};r.postMessage(a),this.workerPipelines.set(e,t);return}if(!(`createEncodedStreams`in e)){JA.warn(`createEncodedStreams not supported`);return}let a;try{a=e.createEncodedStreams()}catch(e){JA.warn(`failed to create encoded streams`,{error:e});return}let o={kind:`decode`,data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof DF&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)==null||e.terminate()}},FF=500,IF=15e3,LF=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=uP(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,zN(Math.min(FF*2**n,IF)))}getBackOffPromise(e){let t=new URL(e),n=t&&uP(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&uP(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};LF._instance=null;var RF=`default`,zF=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return J(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){JA.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{JA.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(tP()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=!t||e.kind===t;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return J(this,void 0,void 0,function*(){if(t!==RF)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===RF);if(!i){JA.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==RF&&e.groupId===(n??i.groupId));if(!a){JA.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};zF.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],zF.userMediaPromiseMap=new Map;var BF=65535,VF=4294967295,HF=class e{static u16(t){return new e(t,BF)}static u32(t){return new e(t,VF)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},UF=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*VF);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=HF.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},WF=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function GF(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var KF;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(KF||={});var qF=class e extends FM{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=KF[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,KF.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,KF.Reserved)}},JF={fromNumber(e){if(e===0)throw qF.reserved(e);if(e>BF)throw qF.tooLarge();return e}},YF=class{constructor(){this.value=0}get(){return this.value+=1,this.value>BF?null:this.value}reset(){this.value=0}},XF={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==PO.NONE}},toProtobuf(e){return new LO({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?PO.GCM:PO.NONE})}},ZF;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(ZF||={});var QF=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new $T,this.nextTaskIndex=0}run(e){return J(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:ZF.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=ZF.RUNNING,yield e()}finally{t.status=ZF.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return J(this,void 0,void 0,function*(){return this.run(()=>J(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},$F=[`client`],eI=class{constructor(){RE(this,`listeners`,new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){let n=this.listeners.get(`*`);if(n)for(let r of n)r(e,t);let r=this.listeners.get(e);if(r)for(let e of r)e(t)}clear(){this.listeners.clear()}},tI=class extends Error{constructor(e,t){super(`non-serializable value at ${e} (${t})`),this.path=e,this.label=t}},nI=(e,t)=>rI(e,t,new Set),rI=(e,t,n)=>{if(e===null)return null;switch(typeof e){case`string`:case`boolean`:return e;case`number`:if(!Number.isFinite(e))throw new tI(t,aI(e));return e;case`object`:return iI(e,t,n);default:throw new tI(t,typeof e)}},iI=(e,t,n)=>{if(n.has(e))throw new tI(t,`circular reference`);if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new tI(t,`sparse array or array with non-index properties`);n.add(e);let r=e.map((e,r)=>rI(e,`${t}[${r}]`,n));return n.delete(e),r}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new tI(t,e.constructor?.name??`object`);n.add(e);let i={};for(let r of Object.keys(e)){let a=rI(e[r],`${t}.${r}`,n);Object.defineProperty(i,r,{value:a,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),i},aI=e=>Number.isNaN(e)?`NaN`:e>0?`Infinity`:`-Infinity`,oI=function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new Set;if(typeof e!=`object`||!e||t.has(e))return e;if(Array.isArray(e)){t.add(e);let n=e.map(e=>oI(e,t));return t.delete(e),n}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;t.add(e);let r={};for(let n of Object.keys(e)){let i=oI(e[n],t);Object.defineProperty(r,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),r},sI=Symbol(`machina.type`),cI=20,lI=class{constructor(e){RE(this,`id`,void 0),RE(this,`initialState`,void 0),RE(this,sI,`BehavioralFsm`),RE(this,`states`,void 0),RE(this,`emitter`,new eI),RE(this,`clients`,new WeakMap),RE(this,`knownClients`,new Set),RE(this,`childSubscriptions`,[]),RE(this,`disposed`,!1),RE(this,`transitionDepth`,0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){if(this.disposed)return;let n=this.getOrCreateClientMeta(e);var r=[...arguments].slice(2);n.currentActionArgs=r;let i=this.states[n.state]?._child;if(i&&i.canHandle(e,t)){try{i.handle(e,t,...r)}finally{n.currentActionArgs=void 0}return}this.handleLocally(e,t,r,n)}canHandle(e,t){if(this.disposed)return!1;let n=this.clients.get(e)?.state??this.initialState,r=this.states[n];if(r?.[t]??r?.[`*`])return!0;let i=r?._child;return i?i.canHandle(e,t):!1}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){return this.clients.get(e)?.state}transition(e,t){if(this.disposed)return;let n=this.getOrCreateClientMeta(e),r=n.state;if(t!==r){if(!Object.hasOwn(this.states,t)){this.emitter.emit(`invalidstate`,{stateName:t,client:e});return}if(this.transitionDepth++,this.transitionDepth>cI)throw this.transitionDepth=0,Error(`Max transition depth (${cI}) exceeded in FSM "${this.id}". Likely an infinite _onEnter → transition loop.`);try{let i=this.states[r],a=this.states[t];if(i!=null&&i._onExit&&typeof i._onExit==`function`){let t=this.buildHandlerArgs(e,``,n);i._onExit(t)}n.state=t;let o={fromState:r,toState:t,client:e};this.emitter.emit(`transitioning`,o);let s;if(a!=null&&a._onEnter&&typeof a._onEnter==`function`){let t=this.buildHandlerArgs(e,``,n);s=a._onEnter(t)}this.emitter.emit(`transitioned`,o);let c=a?._child;c&&c.reset(e),this.processQueue(e,n),typeof s==`string`&&n.state===t&&this.transition(e,s)}finally{this.transitionDepth--}}}compositeState(e){let t=this.clients.get(e);if(!t)return``;let n=this.states[t.state]?._child;if(n){let r=n.compositeState(e);if(r)return`${t.state}.${r}`}return t.state}rehydrate(e,t){if(this.disposed)return;if(typeof t==`string`){this.rehydrateCompositePath(e,t);return}let n=this.planSnapshotWrites(e,t);for(let e of n)e()}dehydrate(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this.clients.get(e);if(!n)return;let r={state:n.state,deferred:n.deferredQueue.map(e=>this.snapshotDeferredInput(e))},i=this.collectChildSnapshots(e,n.state,t);return i&&(r.children=i),r}planSnapshotWrites(e,t){if(this.disposed)return[];let n=t.state,r=t.deferred,i=t.children;if(!Object.hasOwn(this.states,n))throw Error(`rehydrate: unknown state "${n}" in FSM "${this.id}". Valid states: ${Object.keys(this.states).join(`, `)}`);let a=[];if(i)for(let t of Object.keys(i)){if(!Object.hasOwn(this.states,t))throw Error(`rehydrate: unknown state "${t}" in FSM "${this.id}" referenced by snapshot.children.`);let n=this.states[t]?._child;if(!n)throw Error(`rehydrate: state "${t}" in FSM "${this.id}" has no _child, but the snapshot has a children["${t}"] entry.`);a.push(...n.planRehydrate(e,i[t]))}let o=r.map(e=>UE({inputName:e.inputName,args:oI(e.args)},e.untilState===void 0?{}:{untilState:e.untilState}));return a.push(()=>{this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:n,deferredQueue:o})}),a}rehydrateCompositePath(e,t){let n=KE(t.split(`.`)),r=n[0],i=IE(n).slice(1);if(!Object.hasOwn(this.states,r))throw Error(`rehydrate: unknown state "${r}" in FSM "${this.id}". Valid states: ${Object.keys(this.states).join(`, `)}`);if(i.length>0){let n=i.join(`.`),a=this.states[r]?._child;if(!a)throw Error(`rehydrate: state "${r}" in FSM "${this.id}" has no _child, but composite path "${t}" requires one.`);a.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:r,deferredQueue:[]})}collectChildSnapshots(e,t,n){let r=new Map;for(let e of Object.keys(this.states)){let t=this.states[e]?._child;if(!t)continue;let n=r.get(t.instance);n?n.stateNames.push(e):r.set(t.instance,{childLink:t,stateNames:[e]})}let i;for(let a of r.values()){let r=a.childLink,o=a.stateNames,s=n&&o.includes(t);if(r.instance[sI]===`Fsm`&&!s)continue;let c=r.dehydrate(e,s);if(c){i??={};for(let e of o)i[e]=c}}return i}snapshotDeferredInput(e){let t;try{t=nI(e.args,`args`)}catch(t){if(!(t instanceof tI))throw t;let n=e.untilState?` (until "${e.untilState}")`:``;throw Error(`dehydrate: deferred input "${e.inputName}"${n} in FSM "${this.id}" has a non-serializable value at ${t.path} (${t.label})`)}let n={inputName:e.inputName,args:t};return e.untilState!==void 0&&(n.untilState=e.untilState),n}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(let e of this.childSubscriptions)e.off();if(!(e!=null&&e.preserveChildren)){let e=new Set;for(let t of Object.keys(this.states)){let n=this.states[t]?._child;n&&!e.has(n.instance)&&(e.add(n.instance),n.dispose())}}this.emitter.clear()}wrapChildLinks(){for(let e of Object.keys(this.states)){let t=this.states[e],n=t?._child;if(n){if(typeof n!=`object`)throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got ${String(n)}`);if(!(sI in n))throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got a plain object`);t._child=uI(n)}}}setupChildSubscriptions(){let e=new Set;for(let t of Object.keys(this.states)){let n=this.states[t]?._child;if(!n||e.has(n.instance))continue;e.add(n.instance);let r=n.onAny((e,t)=>{if(e===`nohandler`){let e=t;if(e.client!==void 0)this.bubbleNohandler(e.client,n,e.inputName,e.args??[]);else for(let t of this.knownClients){let r=t.deref();if(r===void 0){this.knownClients.delete(t);continue}this.bubbleNohandler(r,n,e.inputName,e.args??[])}return}let r=t;if(r&&typeof r==`object`&&`client`in r)this.isChildActiveForClient(r.client,n)&&this.emitter.emit(e,t);else for(let r of this.knownClients){let i=r.deref();if(!i){this.knownClients.delete(r);continue}if(this.isChildActiveForClient(i,n)){this.emitter.emit(e,t);break}}});this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,r){if(!this.isChildActiveForClient(e,t))return;let i=this.clients.get(e);i.currentActionArgs=r,this.handleLocally(e,n,r,i)}isChildActiveForClient(e,t){var n;let r=this.clients.get(e);return r?((n=this.states[r.state])==null||(n=n._child)==null?void 0:n.instance)===t.instance:!1}handleLocally(e,t,n,r){let i=this.states[r.state],a=i?.[t]??i?.[`*`];if(!a){this.emitter.emit(`nohandler`,{inputName:t,args:n,client:e}),r.currentActionArgs=void 0;return}try{this.emitter.emit(`handling`,{inputName:t,client:e});let i=this.buildHandlerArgs(e,t,r),o;typeof a==`string`?o=a:typeof a==`function`&&(o=a(i,...n)),this.emitter.emit(`handled`,{inputName:t,client:e}),typeof o==`string`&&this.transition(e,o)}finally{r.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new WeakRef(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:r=>{if(!n.currentActionArgs)return;let i={inputName:t,args:[...n.currentActionArgs],untilState:r?.until};n.deferredQueue.push(i),this.emitter.emit(`deferred`,{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){let n=[],r=[];for(let e of t.deferredQueue)e.untilState===void 0||e.untilState===t.state?n.push(e):r.push(e);t.deferredQueue=r;for(let t of n)this.handle(e,t.inputName,...t.args)}};function uI(e){if(!e||typeof e!=`object`)throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got ${String(e)}`);let t=e[sI];if(t===`BehavioralFsm`)return{instance:e,canHandle(t,n){return e.canHandle(t,n)},handle(t,n){var r=[...arguments].slice(2);e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny(t){return e.on(`*`,t)},compositeState(t){return e.compositeState(t)},rehydrate(t,n){e.rehydrate(t,n)},dehydrate(t,n){return e.dehydrate(t,n)},planRehydrate(t,n){return e.planSnapshotWrites(t,n)},dispose(){e.dispose()}};if(t===`Fsm`)return{instance:e,canHandle(t,n){return e.canHandle(n)},handle(t,n){var r=[...arguments].slice(2);e.handle(n,...r)},reset(t){e.reset()},onAny(t){return e.on(`*`,t)},compositeState(t){return e.compositeState()},rehydrate(e,t){throw Error(`rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.`)},dehydrate(e,t){throw Error(`dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.`)},planRehydrate(e,t){throw Error(`rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.`)},dispose(){e.dispose()}};throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ${String(t??`undefined`)}`)}var dI=class{constructor(e){RE(this,`id`,void 0),RE(this,`initialState`,void 0),RE(this,sI,`Fsm`),RE(this,`states`,void 0),RE(this,`bfsm`,void 0),RE(this,`context`,void 0),RE(this,`emitter`,new eI),RE(this,`disposed`,!1),this.id=e.id,this.initialState=e.initialState,this.context=e.context??{},this.bfsm=new lI(e),this.states=e.states,this.bfsm.on(`*`,(e,t)=>{if(t&&typeof t==`object`&&`client`in t){t.client;let n=WE(t,$F);this.emitter.emit(e,n)}else this.emitter.emit(e,t)}),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){var t=[...arguments].slice(1);this.bfsm.handle(this.context,e,...t)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function fI(e){return new dI(e)}function pI(e){return e}function mI(e,t){return t.attemptId===e.attemptId}var hI=pI((e,t)=>{let n=e.ctx;if(mI(n,t))return`connected`}),gI=pI(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`connecting`}),_I=pI(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`reconnecting`}),vI=pI((e,t)=>{let n=e.ctx;return n.closeReason=t.reason,`disconnecting`}),yI={new:{connect:gI,close:vI},connecting:{connectComplete:hI,connectFailed:pI((e,t)=>{let n=e.ctx;return n.lastError=t.error,`closed`}),close:vI},connected:{reconnect:_I,transportFailed:pI((e,t)=>{let n=e.ctx;if(mI(n,t))return n.lastError=t.reason,`offline`}),close:vI},offline:{connect:gI,reconnect:_I,close:vI},reconnecting:{reconnectComplete:hI,reconnectFailed:pI((e,t)=>{let n=e.ctx;return n.lastError=t.error,t.recoverable?`offline`:`closed`}),close:vI},disconnecting:{closeComplete:`closed`},closed:{connect:gI,reconnect:_I}};function bI(){return fI({id:`signal`,initialState:arguments.length>0&&arguments[0]!==void 0?arguments[0]:`new`,context:{attemptId:0},states:yI})}var xI=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.closeCode,r=e.reason;return n.close(t,r)};this.opened=new EM((e,t)=>{let i=()=>{t(LM.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let n=t.data;return e.enqueue(n)},n.onerror=t=>e.error(LM.websocket(iF(t,`websocket`))),n.onclose=t=>{t.wasClean||t.code===1e3?e.close():e.error(LM.websocket(`WS closed unexpectedly with code ${t.code}`))}},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new EM((e,t)=>{let r=()=>J(this,void 0,void 0,function*(){let r=new EM(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield EM.race([zN(250),r]);i?e(i):t(LM.websocket(`Encountered unspecified websocket error without a timely close event`))});n.addEventListener(`close`,t=>{let i=t.code,a=t.reason;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)}),n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},SI=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function CI(e){return e instanceof LM?e.reason!==IM.LeaveRequest&&e.reason!==IM.NotAllowed:!0}function wI(e){let t=SI.indexOf(e.case)>=0;return JA.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var TI;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(TI||={});function EI(e){switch(e){case`connected`:return TI.CONNECTED;case`connecting`:return TI.CONNECTING;case`reconnecting`:return TI.RECONNECTING;case`disconnecting`:return TI.DISCONNECTING;default:return TI.DISCONNECTED}}var DI=250,OI=5e3,kI=class{get currentState(){return EI(this.lifecycleState)}get isDisconnected(){let e=this.currentState;return e===TI.DISCONNECTING||e===TI.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){let t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return J(this,void 0,void 0,function*(){this.log.debug(`waiting for an in-flight close to settle before establishing a session`),(yield this.closingLock.lock())()})}get isEstablishingConnection(){return this.lifecycleState===`connecting`||this.lifecycleState===`reconnecting`}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.log=JA,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=YA(t.loggerName??qA.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new QF,this.queuedRequests=[],this.closingLock=new $T,this.connectionLock=new $T,this.machine=bI(),this.machine.on(`transitioned`,e=>{let t=e.fromState,n=e.toState;this.log.debug(`signal lifecycle: ${t} -> ${n}`)}),this.machine.on(`nohandler`,e=>{let t=e.inputName;this.log.debug(`ignoring signal lifecycle input ${t} in state ${this.lifecycleState}`)}),this.machine}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){if(i.lifecycleState===`disconnecting`&&(yield i.settleInFlightClose()),!i.sendLifecycleInput({type:`connect`}))throw LM.internal(`cannot establish a signal session from '${i.lifecycleState}', close the current one first`);i.options=n;try{return yield i.connect(e,t,n,r,a,o)}catch(e){throw i.sendLifecycleInput({type:`connectFailed`,error:e}),e}}()})}reconnect(e,t,n,r){return J(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`);return}if(this.lifecycleState===`disconnecting`&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:`reconnect`}))throw LM.internal(`cannot resume the signal session from '${this.lifecycleState}'`);this.clearPingInterval();try{return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(e){throw this.sendLifecycleInput({type:`reconnectFailed`,error:e,recoverable:CI(e)}),e}})}connect(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=xP(n.clientInfoCapabilities),l=ZP(e,a?MI(t,c,n):yield NI(t,c,n,o),a).toString(),u=$P(l).toString();return new Promise((e,t)=>J(i,void 0,void 0,function*(){try{let i=!1,a=e=>J(this,void 0,void 0,function*(){if(i)return;i=!0;let n=rF(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(e instanceof LM?e:LM.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(LM.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=new URL(l);if(c.searchParams.has(`access_token`)&&c.searchParams.set(`access_token`,`<redacted>`),this.ws){let e=performance.now();yield this.teardownTransport(`replaced by a new connection attempt`),this.log.debug(`closed previous ws connection in ${performance.now()-e}ms`)}let d=this.attemptId;this.log.info(`signal connecting to ${c}`,{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws=new xI(l);let f=!1;this.ws.opened.catch(()=>{f=!0});try{this.ws.closed.then(e=>{this.isEstablishingConnection&&!f&&t(LM.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),this.log.debug(`websocket closed`,{reason:e.reason,code:e.closeCode,attemptId:d,state:this.lifecycleState}),this.handleOnClose(e.reason||(e.closeCode===1e3?`server closed the signal connection`:`Unexpected WS error`),d)}).catch(e=>{this.isEstablishingConnection&&!f&&t(LM.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>J(this,void 0,void 0,function*(){if(this.lifecycleState!==`connected`){clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a,o;try{a=yield Promise.race([i.read(),new Promise((e,t)=>{o=setTimeout(()=>{t(LM.timeout(`signal connection timed out while waiting for the first message`))},OI)})])}catch(e){i.releaseLock(),t(e),this.close();return}finally{clearTimeout(o)}if(i.releaseLock(),!a.value)throw LM.internal(`no message received as first message`);let c=nF(a.value),l=this.validateFirstMessage(c,n.reconnect??!1);if(!l.isValid){t(l.error);return}c.message?.case===`join`&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));let p=l.shouldProcessFirstMessage?c:void 0;this.handleSignalConnected(r,s,d,p),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return J(this,void 0,void 0,function*(){t&&this.handleSignalResponse(t);let n=this.attemptId;for(;;){this.signalLatency&&(yield zN(this.signalLatency));try{let t=yield e.read(),n=t.done,r=t.value;if(n)break;let i=nF(r);this.handleSignalResponse(i)}catch(e){this.log.error(`error reading from signal stream`,{error:e}),yield this.handleOnClose(`error in reading loop`,n);break}}})}close(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){let r=t&&e.sendLifecycleInput({type:`close`,reason:n}),i=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{r&&e.sendLifecycleInput({type:`closeComplete`}),i()}}()})}teardownTransport(e){return J(this,void 0,void 0,function*(){try{if(this.clearPingInterval(),this.ws){this.ws.close({closeCode:1e3,reason:e});let t=this.ws.closed;this.ws=void 0,this.streamWriter=void 0,yield Promise.race([t,zN(DI)])}}catch(e){this.log.debug(`websocket error while closing`,{error:e})}})}sendOffer(e,t){this.log.debug(`sending offer`,{offerSdp:e.sdp}),this.sendRequest({case:`offer`,value:jI(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,{answerSdp:e.sdp}),this.sendRequest({case:`answer`,value:jI(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,{candidate:e}),this.sendRequest({case:`trickle`,value:new Bk({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new Vk({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new sA({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new oA({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new bA({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:AE.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new DA({timestamp:AE.parse(Date.now()),rtt:AE.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new nA({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new iA({reason:SO.CLIENT_INITIATED,action:aA.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new Pk({pubHandle:e,name:t,encryption:n?PO.GCM:PO.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new Ik({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Yk({updates:[new Xk({trackSid:e,subscribe:t})]})})}sendRequest(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let r=!n&&!wI(e),i=t.lifecycleState===`reconnecting`||t.queuedRequests.length>0;if(r&&i){t.queuedRequests.push(()=>J(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}n||(yield t.requestQueue.flush()),t.signalLatency&&(yield zN(t.signalLatency));let a=e.case===`leave`&&!!t.streamWriter;if(t.isDisconnected&&!a){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`);return}let o=new Ak({message:e});try{t.useJSON?yield t.streamWriter.write(o.toJsonString()):yield t.streamWriter.write(o.toBinary().buffer)}catch(e){t.log.error(`error sending signal message`,{error:e})}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`);return}let n=!1;if(t.case===`answer`){let e=AI(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=AI(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,{msgCase:t.case}));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.attemptId;return function*(){let r=t.onClose;if(!t.sendLifecycleInput({type:`transportFailed`,attemptId:n,reason:e})){t.log.debug(`ignoring transport close in state ${t.lifecycleState}`,{reason:e,attemptId:n,currentAttemptId:t.attemptId});return}yield t.teardownTransport(e),t.log.info(`websocket connection closed: ${e}`,{reason:e}),r&&r(e)}()})}handleWSError(e){this.log.error(`websocket error`,{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`);return}this.pingTimeout=XM.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&XM.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`);return}this.log.debug(`start ping interval`),this.pingInterval=XM.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`),this.clearPingTimeout(),this.pingInterval&&XM.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n,r){if(clearTimeout(t),!this.sendLifecycleInput(this.lifecycleState===`reconnecting`?{type:`reconnectComplete`,attemptId:n}:{type:`connectComplete`,attemptId:n})){this.log.debug(`discarding a connection whose attempt no longer owns the session`,{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState});return}this.log.info(`signal connected`),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),r)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.lifecycleState===`reconnecting`&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:LM.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:LM.internal(`Unexpected first message`)}:{isValid:!1,error:LM.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return J(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:let e=yield n.text();return e.includes(`requested room does not exist`)?LM.notAllowed(e,n.status):LM.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let t=yield n.text();return LM.notAllowed(t,n.status)}return e instanceof LM?e:LM.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof LM?e:LM.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function AI(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type}return t}function jI(e,t){return new Kk({sdp:e.sdp,type:e.type,id:t})}function MI(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,cP()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),r.set(`client_protocol`,t.clientProtocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function NI(e,t,n,r){return J(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new IA({clientInfo:t,connectionSettings:new FA({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(JP()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let e=yield r.read(),t=e.done,i=e.value;if(t)break;n.push(i)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=RA.GZIP}else s=o,c=RA.NONE;let l=new LA({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var PI=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let n of this._map.entries()){var t=K(n,2);let r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let n of this._map.entries()){var t=K(n,2);let r=t[0],i=t[1];i.expiresAt>=Date.now()&&e(i.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let i of n.entries()){var r=K(i,2);let a=r[0],o=r[1];t.push(e(o,a,n))}return t}asValueMap(){let e=new Map;for(let n of this._map.entries()){var t=K(n,2);let r=t[0],i=t[1];i.expiresAt>=Date.now()&&e.set(r,i.value)}return e}},FI={},II={},LI={exports:{}},RI;function zI(){if(RI)return LI.exports;RI=1;var e=LI.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),LI.exports}var BI;function VI(){return BI?II:(BI=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=zI(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(II),II)}var HI,UI;function WI(){if(UI)return HI;UI=1;var e=zI(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return HI=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
99
99
  `)+`\r
100
- `},LI}var BI;function VI(){if(BI)return AI;BI=1;var e=II(),t=zI();return AI.grammar=PI(),AI.write=t,AI.parse=e.parse,AI.parseParams=e.parseParams,AI.parseFmtpConfig=e.parseFmtpConfig,AI.parsePayloads=e.parsePayloads,AI.parseRemoteCandidates=e.parseRemoteCandidates,AI.parseImageAttributes=e.parseImageAttributes,AI.parseSimulcastStreamList=e.parseSimulcastStreamList,AI}var HI=VI(),UI=.9,WI=1e3,GI=20;function KI(e,t,n,r){let i=arguments.length>4&&arguments[4]!==void 0&&arguments[4];if(!e.msid?.includes(t))return;let a=e.rtp.find(e=>e.codec.toUpperCase()===n.toUpperCase())?.payload??0;if(a===0)return 0;let o=Math.round(r*UI),s=i?o:Math.min(o,WI),c=e.fmtp.find(e=>e.payload===a);return c?c.config.includes(`x-google-start-bitrate`)||(c.config+=`;x-google-start-bitrate=${s}`):e.fmtp.push({payload:a,config:`x-google-start-bitrate=${s}`}),a}var qI={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,OfferAnswered:`offerAnswered`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},JI=class extends cj.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=UA,this.iceLog=UA,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=_F(e=>J(this,void 0,void 0,function*(){this.emit(qI.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),GI),this.close=()=>{this._pc&&=(this.log.debug(`closing peer connection`),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.loggerOptions=t,this.log=WA(t.loggerName??HA.PCTransport,()=>this.logContext),this.iceLog=WA(HA.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new JT}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug(`local ICE candidate gathered`,{candidate:e.candidate.candidate}),(t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug(`ICE candidate error`,{event:e}),(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug(`ICE connection state: ${e.iceConnectionState}`),(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug(`signaling state: ${e.signalingState}`),(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug(`connection state: ${e.connectionState}`),(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug(`data channel opened by peer`,{label:e.channel.label,id:e.channel.id}),(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return J(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug(`queuing remote ICE candidate until remote description applied`,{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return J(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,{offerId:t,latestOfferId:this.latestOfferId}),!1;let n;if(e.type===`offer`){let t=iL(e),n=t.stereoMids,r=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=r}else if(e.type===`answer`){if(this.pendingInitialOffer&&this._pc){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=HI.parse(e.sdp??``);t.media.forEach(e=>{aL(e)}),this.log.debug(`setting pending initial offer before processing answer`),yield this.setMungedSDP(e,HI.write(t))}let t=HI.parse(e.sdp??``);t.media.forEach(e=>{let t=oL(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(r=e.payload,!0)),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})});let r=this.getPlaceholderMids();r.size>0&&rL(t.media,e=>r.has(oL(e.mid))),n=HI.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.length>0&&this.iceLog.debug(`flushing queued ICE candidates`,{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,e.type===`answer`&&(this.latestAcknowledgedOfferId=t,this.emit(qI.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(qI.NegotiationComplete),e.sdp&&HI.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(qI.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return J(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=HI.parse(t.sdp??``);return n.media.forEach(e=>{aL(e)}),t.sdp=HI.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return J(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug(`restarting ICE`),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else if(e?.iceRestart)throw new LM(`ICE restart requested without a remote description, peer connection must be recreated`);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`);return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`);return}this.log.debug(`starting to negotiate`);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,{sdp:n.sdp});let r=HI.parse(n.sdp??``);r.media.forEach(e=>{aL(e),e.type===`audio`?tL(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!t.cid)return!1;let n=KI(e,t.cid,t.codec,t.maxbr,t.isScreenShare);return n!==void 0&&(n>0&&zN(t.codec)&&!XN()&&(this.ddExtID=YI(e,r,this.ddExtID)),!0)})});let i=this.getPlaceholderMids();if(i.size>0&&rL(r.media,e=>i.has(oL(e.mid))),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,{latestOfferId:this.latestOfferId,offerId:t});return}yield this.setMungedSDP(n,HI.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return J(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=HI.parse(e.sdp??``);return t.media.forEach(e=>{aL(e),e.type===`audio`&&tL(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,HI.write(t)),e})}getPlaceholderMids(){return nL(this._pc?.getTransceivers()??[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new IM(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new IM(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this._pc?.getStats()}getMaxMessageSize(){return this._pc?.sctp?.maxMessageSize}getConnectedAddress(){return J(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`)}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return J(this,void 0,void 0,function*(){let r=e.sdp;if(t){e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,{error:n,mungedSdp:t,originalSdp:r}),e.sdp=r}}try{n?yield this._pc?.setRemoteDescription(e):yield this._pc?.setLocalDescription(e)}catch(i){let a=`unknown error`;i instanceof Error?a=i.message:typeof i==`string`&&(a=i);let o={error:a,sdp:e.sdp};throw t&&t!==r&&(o.mungedSdp=t),!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,{fields:o}),new LM(a)}})}};function YI(e,t,n){let r=XI(t,n);return r===void 0?n:(e.ext?.some(e=>e.uri===MN)||(e.ext??=[],e.ext.push({value:r,uri:MN})),r)}function XI(e,t){let n=ZI(e,MN);return n===void 0?t!==0&&!QI(e,t,MN)?t:$I(e):QI(e,n,MN)?void 0:n}function ZI(e,t){for(let n of e.media){let e=n.ext?.find(e=>e.uri===t);if(e)return e.value}}function QI(e,t,n){return e.media.some(e=>e.ext?.some(e=>e.value===t&&e.uri!==n))}function $I(e){let t=0;return e.media.forEach(e=>{var n;(n=e.ext)==null||n.forEach(e=>{e.value>t&&(t=e.value)})}),t+1===15?16:t+1}function eL(e,t){return e.split(`;`).some(e=>e.trim()===t)}function tL(e,t,n){let r=oL(e.mid),i=0;e.rtp.some(e=>e.codec.toLowerCase()===`opus`&&(i=e.payload,!0)),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i&&(eL(e.config,`stereo=1`)||(e.config+=`;stereo=1`),!0)))}function nL(e){let t=new Set;for(let n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}function rL(e,t){let n=new Map,r=new Set;for(let i of e){let e=t(i);for(let t of i.fmtp??[])e?n.has(t.payload)||n.set(t.payload,t.config):(n.set(t.payload,t.config),r.add(t.payload))}if(n.size!==0){for(let r of e)if(t(r))for(let e of r.fmtp??[]){let t=n.get(e.payload);t!==void 0&&e.config!==t&&(e.config=t)}}}function iL(e){let t=[],n=[],r=HI.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=oL(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec.toLowerCase()===`opus`&&(i=e.payload,!0)),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i&&(eL(e.config,`sprop-stereo=1`)&&t.push(r),!0)))}),{stereoMids:t,nackMids:n}}function aL(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function oL(e){return typeof e==`number`?e.toFixed(0):e}var sL=`vp8`,cL={audioPreset:aN.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:cN.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:sL,backupCodec:!0,preConnectBuffer:!1},lL={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},uL={deviceId:{ideal:`default`},resolution:oN.h720.resolution},dL={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new QA,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},fL={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},pL;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(pL||={});var mL=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=fL.peerConnectionTimeout,this.log=UA,this.iceLog=UA,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=pL.CONNECTED:n.some(e=>e===`failed`)?this.state=pL.FAILED:n.some(e=>e===`connecting`)?this.state=pL.CONNECTING:n.every(e=>e===`closed`)?this.state=pL.CLOSED:n.some(e=>e===`closed`)?this.state=pL.CLOSING:n.every(e=>e===`new`)&&(this.state=pL.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${pL[t]} to ${pL[this.state]}`),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.loggerOptions=t,this.log=WA(t.loggerName??HA.PCManager,()=>this.logContext),this.iceLog=WA(HA.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new JI(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new JI(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,Sk.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,Sk.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=pL.NEW,this.connectionLock=new JT,this.remoteOfferLock=new JT}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return J(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,{error:e})}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return J(this,void 0,void 0,function*(){this.iceLog.warn(`triggering ICE restart`),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return J(this,void 0,void 0,function*(){this.iceLog.debug(`adding remote ICE candidate`,{target:t,candidate:e}),t===Sk.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return J(this,void 0,void 0,function*(){this.log.debug(`received server offer`,{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()});let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.log.debug(`updating rtc configuration`,{iceRestart:t}),this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return J(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return J(this,void 0,void 0,function*(){return new xM((t,n)=>{let r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug(`negotiation already handled in more recent acknowledged offer`,this.logContext),t();return}let i=!1,a=()=>{i||(i=!0,clearTimeout(c),this.publisher.off(qI.OfferAnswered,o),e.signal.removeEventListener(`abort`,s))},o=e=>{e>r&&(a(),t())},s=()=>{a(),n(new LM(`negotiation aborted`))},c=setTimeout(()=>{a(),n(new LM(`negotiation timed out`))},this.peerConnectionTimeout);e.signal.addEventListener(`abort`,s),this.publisher.on(qI.OfferAnswered,o),this.publisher.negotiate(e=>{a(),e instanceof Error?n(e):n(Error(String(e)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Sk.PUBLISHER||e===Sk.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>J(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`),GM.clearTimeout(a),i(MM.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=GM.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(MM.internal(`could not establish pc connection`))},r);for(;this.state!==pL.CONNECTED;)if(yield PN(50),t?.signal.aborted){i(MM.cancelled(`room connection has been cancelled`));return}GM.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},hL=class{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new JT,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters(`data channel replaced`),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`data channel torn down`;this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return J(this,void 0,void 0,function*(){let e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return J(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new IM(`engine closed`);let e=this.getChannel();if(!e)throw new IM(`DataChannel not found, kind: ${this.kind}`);if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new xM((n,r)=>{let i=()=>{s(),n()},a=()=>{s(),r(new IM(`DataChannel ${this.kind} closed while draining the buffer`))},o=()=>{s(),r(new IM(`DataChannel ${this.kind} was replaced or torn down while waiting for headroom`))},s=()=>{e.removeEventListener(`bufferedamountlow`,i),e.removeEventListener(`close`,a),t.removeEventListener(`abort`,o)};if(t.aborted){o();return}e.addEventListener(`bufferedamountlow`,i),e.addEventListener(`close`,a),t.addEventListener(`abort`,o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;let t=this.getChannel();if(!t)return;let n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,(e=this.onBufferStatusChanged)==null||e.call(this,n))}},gL=class extends hL{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return J(this,void 0,void 0,function*(){let t=this.getChannel();if(t){switch(this.bufferFullBehavior){case`wait`:this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case`drop`:if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100==0&&UA.warn(`dropping lossy data channel messages, total dropped: ${this.dropCount}`);return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(e){if(e instanceof TypeError)UA.error(e);else throw e}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=GM.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;let e=this.getChannel();if(e){let t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&=(GM.clearInterval(this.statInterval),void 0),this.dropCount=0}},_L=class{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(let e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},vL=class extends hL{constructor(e){super(e),this.messageBuffer=new _L,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){let e=this.sequence;return this.sequence+=1,e}send(e,t){return J(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}let n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(n){if(this.isEngineClosed())throw n;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus()}})}replay(e){return J(this,void 0,void 0,function*(){let t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);let n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let e=this.messageBuffer.getUnsent();e.length>0;e=this.messageBuffer.getUnsent())for(let n of e)yield this.waitForHeadroomWithoutLock(),t.send(n.data),this.messageBuffer.markSent(n)}finally{n()}this.refreshBufferStatus()})}refreshBufferStatus(){let e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new _L,this.sequence=1}},yL;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(yL||={});var bL=65536,xL=1048576,SL=8192,CL=262144;function wL(e){return e===yL.RELIABLE?bL:SL}function TL(e){return e===yL.RELIABLE?xL:CL}var EL=`_lossy`,DL=`_reliable`,OL=`_data_track`,kL=class{constructor(e){this.opts=e;let t=t=>({kind:t,lowWaterMark:wL(t),highWaterMark:TL(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new vL(Object.assign(Object.assign({},t(yL.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new gL(Object.assign(Object.assign({},t(yL.LOSSY)),{bufferFullBehavior:`drop`,shouldSkipSends:e.isReconnecting})),this.dataTrack=new gL(Object.assign(Object.assign({},t(yL.DATA_TRACK_LOSSY)),{bufferFullBehavior:`wait`,shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case yL.RELIABLE:return this.reliable;case yL.LOSSY:return this.lossy;case yL.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case yL.RELIABLE:return this.reliableSub;case yL.LOSSY:return this.lossySub;case yL.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(let e of[this.lossy,this.reliable,this.dataTrack]){let t=e.channelHandle;t&&(t.onmessage=null,t.onerror=null,t.onclose=null)}let t=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)};t(this.lossy,e.createPublisherDataChannel(EL,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(DL,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(OL,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===DL)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===EL)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===OL)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){let e=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};for(let t of[this.lossy,this.reliable,this.dataTrack]){let n=t.channelHandle;t.detach(`peer connections cleaned up`),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}},AL=typeof MediaRecorder<`u`,jL=AL?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},ML=class extends jL{constructor(e,t){if(!AL)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>J(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function NL(){return AL}var PL=1e3,FL=1e4,IL=class extends ${get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=_F(()=>J(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>J(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(Q.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new JT,this.pauseUpstreamLock=new JT,this.trackChangeLock=new JT,this.trackChangeLock.lock().then(t=>J(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==$.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return J(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{AN(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(kN(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{kN(r??e,t)}))})}waitForDimensions(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:PL;return function*(){if(e.kind===$.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);wM()?.os===`iOS`&&(yield PN(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield PN(50)}throw new PM(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return J(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===SP(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),SP(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===$.Source.ScreenShare)return;let n=e._mediaStreamTrack.getSettings(),r=n.deviceId,i=n.groupId,a=e.kind===$.Kind.Audio?`audioinput`:`videoinput`;return t?PF.getInstance().normalizeDeviceId(a,r,i):r}()})}mute(){return J(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return J(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return J(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new PM(`unable to replace an unpublished track`);let n,r;typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return J(this,void 0,void 0,function*(){})}restart(e,t){return J(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let n=e,r=n.deviceId,i=n.facingMode,a=$A(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let o={audio:!1,video:!1};this.kind===$.Kind.Video?o.video=r||i?{deviceId:r,facingMode:i}:!0:o.audio=!r||Object.assign({deviceId:r},a),this.attachedElements.forEach(e=>{AN(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===$.Kind.Video&&(yield s.applyConstraints(a)),s.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(s,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(Q.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),(this.isMuted!==e||this._mediaStreamTrack.enabled===e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Q.Muted:Q.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),eP()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return J(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(Q.UpstreamPaused,this);let e=wM();if(e?.name===`Safari`&&lP(e.version,`12.0`)<0)throw new NM(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return J(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(Q.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return J(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext,localTrack:t};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(kN(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(AN(t._mediaStreamTrack,e),kN(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(Q.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Q.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!NL()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new ML(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},FL)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},LL=class extends IL{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,$.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>J(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=yF(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,bO.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,bO.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===$.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===$.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return J(this,void 0,void 0,function*(){let t;if(e){let n=dN({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}applyConstraints(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{let t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return J(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){nP()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},vF))}setProcessor(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!rP()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(Q.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return J(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(n=>{if(n.type===`outbound-rtp`){t={type:`audio`,streamId:n.id,packetsSent:n.packetsSent,bytesSent:n.bytesSent,timestamp:n.timestamp};let r=e.get(n.remoteId);r&&(t.packetsLost=r.packetsLost,t.jitter=r.jitter,t.roundTripTime=r.roundTripTime)}}),t})}checkForSilence(){return J(this,void 0,void 0,function*(){let e=yield fN(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(Q.AudioSilenceDetected)),e})}};function RL(e,t,n){switch(e.kind){case`audio`:return new LL(e,t,!1,void 0,n);case`video`:return new rR(e,t,!1,n);default:throw new PM(`unsupported track type: ${e.kind}`)}}var zL=Object.values(oN),BL=Object.values(sN),VL=Object.values(cN),HL=[oN.h180,oN.h360],UL=[sN.h180,sN.h360],WL=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new $M(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),GL=[`q`,`h`,`f`];function KL(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec,c=VN(s,r);if(!i&&!a&&!o||!t||!n)return[{}];i||(i=YL(e,t,n,s),UA.debug(`using video encoding`,i));let l=i.maxFramerate,u=new $M(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&zN(s)&&!c){let e=new eR(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=wM();if(HN()){let r=e.suffix==`h`?2:3,a=$N(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:GL[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:o});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),UA.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let d=e=>(c&&e.forEach(e=>{e.scalabilityMode=o}),e),f;f=e?$L(r?.screenShareSimulcastLayers)??ZL(e,u):$L(r?.videoSimulcastLayers)??ZL(e,u);let p;if(f.length>0){let e=f[0];f.length>1&&(p=K(f,2)[1]);let r=Math.max(t,n);if(r>=960&&p)return d(QL(t,n,[e,p,u],l));if(r>=480)return d(QL(t,n,[e,u],l))}return d(QL(t,n,[u]))}function qL(e,t,n){return zN(e)&&!VN(e,t)?n[0]?.maxBitrate??0:n.reduce((e,t)=>e+(t.maxBitrate??0),0)}function JL(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&UA.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===$.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),KL(e.source===$.Source.ScreenShare,i,a,n)}function YL(e,t,n,r){let i=XL(e,t,n),a=i[0].encoding,o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85}return a}function XL(e,t,n){if(e)return VL;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?zL:BL}function ZL(e,t){if(e)return WL(t);let n=t.width,r=t.height,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?HL:UL}function QL(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=GL.length)return;let o=Math.min(e,t),s={rid:GL[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=wM(),u=l?.name===`Firefox`&&l.os!==`iOS`||a===0;n.encoding.priority&&u&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),rP()&&sP()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,UA.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),UA.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function $L(e){if(e)return e.slice().sort((e,t)=>{let n=e.encoding,r=t.encoding;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var eR=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function tR(e){switch(e.source){case $.Source.Camera:return`maintain-framerate`;case $.Source.ScreenShare:return`maintain-resolution`;default:return`balanced`}}var nR=5e3,rR=class extends IL{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,$.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>J(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(Q.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=yF(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new JT}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!nP())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},vF))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return J(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=ij(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return J(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=ij(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===$.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===$.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return J(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}isSvcPublish(e){return zN(e)&&!VN(e,this.publishOptions)}setPublishingQuality(e){let t=[];for(let n=ON.LOW;n<=ON.HIGH;n+=1)t.push(new uA({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(this.isSvcPublish(this.codec),t)}restartTrack(e){return J(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=dN({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=ij(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return J(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return J(this,void 0,void 0,function*(){if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let e=yield this.senderLock.lock();try{let e;try{e=yield this.waitForDimensions()}catch(e){this.log.warn(`could not determine new track dimensions, skipping encoding recompute`,Object.assign(Object.assign({},this.logContext),{error:e}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===e.width&&this.lastEncodedDimensions.height===e.height)return;let n=KL(this.source===$.Source.ScreenShare,e.width,e.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=e;for(let e of this.simulcastCodecs){var t=K(e,2);let n=t[0],r=t[1];if(!r.sender||r.sender.transport?.state===`closed`||!nN(n))continue;let i=Object.assign({},this.publishOptions),a=JL(this,n,i);a&&(yield this.applyEncodingsToSender(r.sender,a),r.encodings=a)}}catch(e){this.log.warn(`failed to apply recomputed encodings`,Object.assign(Object.assign({},this.logContext),{error:e}))}finally{e()}})}applyEncodingsToSender(e,t){return J(this,void 0,void 0,function*(){let n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach((e,n)=>{if(e.active===!1)return;let r=t[n];r.scaleResolutionDownBy!==void 0&&(e.scaleResolutionDownBy=r.scaleResolutionDownBy),r.maxBitrate!==void 0&&(e.maxBitrate=r.maxBitrate),r.maxFramerate!==void 0&&(e.maxFramerate=r.maxFramerate),r.priority!==void 0&&(e.priority=r.priority,e.networkPriority=r.priority)}),this.log.debug(`updating sender encodings after track restart`,Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return J(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=ij(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return J(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(let e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)})}applyDegradationPreference(e){return J(this,void 0,void 0,function*(){if(e)try{this.log.debug(`setting degradationPreference to ${this.degradationPreference}`,this.logContext);let t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){return J(this,void 0,void 0,function*(){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},nR))})}setPublishingCodecs(e){return J(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(this.isSvcPublish(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=ij(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(this.isSvcPublish(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield iR(t.sender,t.encodings,e.qualities,this.senderLock,this.isSvcPublish(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return J(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield iR(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return J(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&zN(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),eP()&&this.isInBackground&&this.source===$.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function iR(e,t,n,r,i,a,o){return J(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),s=r.encodings;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=aR(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),qN()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function aR(e){switch(e){case`f`:return ON.HIGH;case`h`:return ON.MEDIUM;case`q`:return ON.LOW;default:return ON.HIGH}}function oR(e,t,n,r){if(!n)return[new VO({quality:ON.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new eR(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new VO({quality:Math.min(ON.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new VO({quality:aR(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var sR=2e3,cR=`leave-reconnect`,lR=1e4,uR=3e4,dR=3,fR=3,pR;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(pR||={});var mR=64e3,hR=class extends cj.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get serverVersion(){return this.latestJoinResponse?.serverInfo?.version||this.latestJoinResponse?.serverVersion||void 0}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=fL.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=pR.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=UA,this.reliableReceivedState=new kI(uR),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>J(this,[e],void 0,function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug(`on data channel ${n.id}, ${n.label}`)}()}),this.handleDataMessage=e=>J(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t=yield this.decodeDataMessage(e);if(!t)return;let n=UO.fromBinary(t);if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(Z.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`);return}let e;try{e=yield this.e2eeManager.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex)}catch(e){this.log.debug(`failed to decrypt data packet`,{error:e,participantIdentity:n.participantIdentity});return}let t=new UO({value:KO.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&gR(t,t.value.value),this.emit(Z.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&gR(n,n.value.value),this.emit(Z.DataPacketReceived,n,kO.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>J(this,void 0,void 0,function*(){let t=yield this.decodeDataMessage(e);t&&this.emit(`dataTrackPacketReceived`,t)}),this.handleDataError=e=>{if(this._isClosed)return;let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(typeof RTCErrorEvent<`u`&&e instanceof RTCErrorEvent&&e.error){let n=e.error;this.log.error(`DataChannel error on ${t}: ${n.message}`,{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error(`Unknown DataChannel error on ${t}`,{event:e})},this.handleDataChannelClose=e=>()=>{!this._isClosed&&this.pcManager?.publisher.getConnectionState()===`connected`&&this.log.error(`publisher data channel '${yL[e]}' closed unexpectedly`,this.logContext)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`),this.emit(Z.Disconnected),this.close(`gave up reconnecting after ${this.reconnectAttempts} attempts, ${e}ms`)},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===cR&&(i=0),this.log.debug(`reconnecting in ${i}ms`),this.clearReconnectTimeout(),this.token&&this.emit(Z.TokenRefreshed,this.token),this.reconnectTimeout=GM.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===pR.Connected&&e();let n=()=>{this.off(Z.Disconnected,r),e()},r=()=>{this.off(Z.Restarted,n),t()};this.once(Z.Restarted,n),this.once(Z.Disconnected,r)}),this.onRtpMapAvailable=e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();xP(n)&&t.set(e.payload,n)}),this.emit(Z.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>J(this,void 0,void 0,function*(){this.url&&(yield fetch(wP(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===bI.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===bI.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(vO.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>J(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(wP(this.url),{method:`HEAD`}),PN(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=WA(e.loggerName??HA.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new wI(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new JT,this.dataProcessLock=new JT,this.dataChannels=new kL({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(e,t)=>this.emit(Z.DCBufferStatusChanged,t,e)}),this.client.onParticipantUpdate=e=>this.emit(Z.ParticipantUpdate,e),this.client.onConnectionQuality=e=>{this.handleLocalConnectionQuality(e),this.emit(Z.ConnectionQualityUpdate,e)},this.client.onRoomUpdate=e=>this.emit(Z.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Z.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Z.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Z.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Z.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Z.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(Z.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(Z.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s=!a&&WP(),c;if(s){i.pcManager||(yield i.configure(),i.applyInitialPublisherLayout());let e=yield i.pcManager?.publisher.createInitialOffer();e&&(c=EI(e.offer,e.offerId))}if(r?.aborted)throw MM.cancelled(`Connection aborted`);if(!a&&i.shouldFailOnV1Path)throw i.shouldFailOnV1Path=!1,MM.serviceNotFound(`Simulated v1 path failure`,`v0-rtc`);let l=yield i.client.join(e,t,n,r,a,c);i._isClosed=!1,i.latestJoinResponse=l,i.participantSid=l.participant?.sid,i.subscriberPrimary=l.subscriberPrimary,s?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(l)):(i.pcManager||(yield i.configure(l,!a),a||i.applyInitialPublisherLayout()),(!i.subscriberPrimary||l.fastPublish)&&i.negotiate().catch(e=>{i.log.error(e)})),i.registerOnLineListener(),i.clientConfiguration=l.clientConfiguration,i.emit(Z.SignalConnected,l);let u=l.serverInfo;return u||={version:l.serverVersion,region:l.serverRegion},i.log.info(`connected to Livekit Server ${Object.entries(u).map(e=>{let t=K(e,2);return`${t[0]}: ${t[1]}`}).join(`, `)}`),{joinResponse:l,serverInfo:u}}catch(o){if(o instanceof MM){if(o.reason===jM.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===jM.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.pcManager&&(i.pcManager.onStateChange=void 0,yield i.cleanupPeerConnections()),i.join(e,t,n,r,!0)}throw o}}()})}close(e){return J(this,void 0,void 0,function*(){let t=yield this.closingLock.lock();if(this.isClosed){t();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(Z.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(e)}finally{t()}})}cleanupPeerConnections(){return J(this,void 0,void 0,function*(){this.dataChannels.teardown(),yield this.pcManager?.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return J(this,void 0,void 0,function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(let e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new PM(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=GM.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(MM.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{GM.clearTimeout(r),t(e)},reject:()=>{GM.clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,{error:e})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.dataChannelForKind(yL.RELIABLE,!0)?.readyState}getConnectedServerAddress(){return J(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return J(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==pL.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new mL(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new mL(`publisher-only`,this.loggerOptions,e)}this.emit(Z.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>J(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`),this.transportConnectingSince=e===pL.CONNECTING?Date.now():void 0,[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===pL.CONNECTED){let e=this.pcState===pR.New;this.pcState=pR.Connected,e&&this.emit(Z.Connected,this.latestJoinResponse)}else e===pL.FAILED&&(this.pcState===pR.Connected||this.pcState===pR.Reconnecting)&&(this.pcState=pR.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?vO.RR_SUBSCRIBER_FAILED:vO.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===bI.RECONNECTING,i=[pL.FAILED,pL.CLOSING,pL.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(Z.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(Z.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>J(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.pcManager.mode===`publisher-only`&&(this.midToTrackId=n),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>J(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,{cid:e.cid,track:e.track?.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,{cid:e.cid});return}let t=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Z.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Z.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(Z.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Z.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Z.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Z.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(Z.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(Z.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(Z.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,vO.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info(`client leave request received (action=${e?.action})`,{reason:e?.reason}),e.regions&&(this.log.debug(`updating regions`),this.emit(Z.ServerRegionsReported,e.regions)),e.action){case eA.DISCONNECT:this.emit(Z.Disconnected,e?.reason),this.close(`server leave: ${_O[e.reason]??e.reason}`);break;case eA.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(cR);break;case eA.RESUME:this.handleDisconnect(cR)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if((this.signalOpts?.e2eeEnabled||this.frameMetadataWorker&&!fF())&&cF()&&(this.log.debug(`E2EE - setting up transports with insertable streams`),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===gO.ENABLED&&(t.iceTransportPolicy=`relay`),t}applyInitialPublisherLayout(){this.createDataChannels(),rP()||this.addMediaSections(dR,fR)}addMediaSections(e,t){var n;let r={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,r);let i=this.pcManager?.mode===`publisher-only`;for(let e=0;e<t;e++){let e=this.pcManager?.addPublisherTransceiverOfKind(`video`,r);if(i&&e){let t=BN(e);this.log.debug(`dependency descriptor negotiated for received video`,{negotiated:t})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return J(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error(`unsupported data type`,{data:e.data})})}createSender(e,t,n){return J(this,void 0,void 0,function*(){let r;if(FN())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(IN())this.log.warn(`using add-track fallback`),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new IM(`Required webRTC APIs not supported on this device`);return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return J(this,void 0,void 0,function*(){let i;if(FN())i=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(IN())this.log.debug(`using add-track fallback`),i=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new IM(`Cannot stream on this device`);return i&&this.setupFrameMetadataSender(i,n),i})}get frameMetadataWorker(){return(this.options.frameMetadata??this.options.packetTrailer)?.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=this.frameMetadataWorker;if(!n||this.signalOpts?.e2eeEnabled)return;let r=t.frameMetadata??t.packetTrailer,i=mF(r);if(fF()){i&&(e.transform=new RTCRtpScriptTransform(n,{kind:`encode`,packetTrailer:r}));return}if(!pF(this.options.frameMetadata??this.options.packetTrailer)||!(`createEncodedStreams`in e)){i&&this.log.warn(`frame metadata transform not supported; skipping write`,this.logContext);return}let a=e.createEncodedStreams(),o=a.readable,s=a.writable;i?n.postMessage({kind:`encode`,data:{readableStream:o,writableStream:s,packetTrailer:r}},[o,s]):o.pipeTo(s)}createTransceiverRTCRtpSender(e,t,n){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new IM(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),MP(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new IM(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new IM(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;let t=e.updates.find(e=>e.participantSid===this.participantSid);t&&(t.quality===hO.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||=GM.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==pR.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn(`local connection quality lost while publishing, triggering full reconnect`,this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect(`connection quality lost`,vO.RR_PUBLISHER_FAILED))},lR)}clearLostQualityTimeout(){this.lostQualityTimeout&&=(GM.clearTimeout(this.lostQualityTimeout),void 0)}hasActivePublisherSenders(){return this.pcManager?.publisher.getSenders().some(e=>!!e.track&&e.track.readyState===`live`)??!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vO.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect(`reconcile`,e)}attemptReconnect(e){return J(this,void 0,void 0,function*(){if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn(`already attempting reconnect, returning early`);return}this.clearLostQualityTimeout(),(this.clientConfiguration?.resumeConnection===gO.DISABLED||(this.pcManager?.currentState??pL.NEW)===pL.NEW)&&(this.fullReconnectOnNext=!0);let t=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let n=!1;try{this.attemptingReconnect=!0,t?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),n=!0}catch(e){this.reconnectAttempts+=1;let n=!0;e instanceof IM?(this.log.debug(`received unrecoverable error`,{error:e}),n=!1):(t||!(e instanceof UM))&&(this.fullReconnectOnNext=!0),n?this.handleDisconnect(`reconnect`,vO.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`),this.emit(Z.Disconnected),yield this.close(`gave up reconnecting after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms`))}finally{this.attemptingReconnect=!1,n&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug(`full reconnect requested during in-progress attempt, dispatching`),this.handleDisconnect(`reconnect`))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,{error:e})}return null}restartConnection(e){return J(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new IM(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`),this.emit(Z.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`),new UM;n=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){throw e instanceof MM&&e.reason===jM.NotAllowed?new IM(`could not reconnect, token might be expired`):new UM}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(Z.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==bI.CONNECTED)throw new UM(`Signal connection got severed during reconnect`);(t=this.regionStrategy)==null||t.resetAttempts(),this.emit(Z.Restarted)}catch(e){let t=yield this.regionStrategy?.getNextUrl();if(t){yield this.restartConnection(t);return}throw(n=this.regionStrategy)==null||n.resetAttempts(),e}})}resumeConnection(e){return J(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new IM(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new IM(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`),this.emit(Z.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,{error:e})),e instanceof MM&&e.reason===jM.NotAllowed?new IM(`could not reconnect, token might be expired`):e instanceof MM&&e.reason===jM.LeaveRequest?e:new UM(t)}if(this.emit(Z.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==bI.CONNECTED)throw new UM(`Signal connection got severed during reconnect`);this.client.setReconnected();let n=this.dataChannelForKind(yL.RELIABLE);n?.readyState===`open`&&n.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(e=>{this.log.warn(`failed to resend reliable messages after resume`,Object.assign(Object.assign({},this.logContext),{error:e}))}),this.emit(Z.Resumed)})}waitForPCInitialConnection(e,t){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new IM(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return J(this,void 0,void 0,function*(){this.pcState=pR.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`);try{if(yield PN(sR),!this.pcManager)throw new IM(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=pR.Connected}catch(e){throw this.pcState=pR.Disconnected,MM.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcAck(e,t){return J(this,void 0,void 0,function*(){let n=new UO({destinationIdentities:[e],kind:WO.RELIABLE,value:{case:`rpcAck`,value:new tk({requestId:t})}});yield this.sendDataPacket(n,yL.RELIABLE)})}sendDataPacket(e,t){return J(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=lF(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new GO({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===yL.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let n=e.toBinary(),r=Math.min(this.pcManager?.getMaxPublisherMessageSize()??mR,mR);if(r!==void 0&&r!==0&&n.byteLength>r)throw new RM(`cannot publish data packet larger than ${r} bytes (got ${n.byteLength})`);t===yL.RELIABLE?yield this.reliableChannel.send(n,e.sequence):yield this.lossyChannel.send(n)})}sendDataTrackFrame(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(yL.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(yL.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return J(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new IM(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw MM.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{t.log.error(e)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield PN(50)}throw MM.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return J(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;let e=this.pcManager.currentState;return![pL.CONNECTING,pL.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===pL.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn(`transport stuck in connecting state`,this.logContext),!1):!0}negotiate(){return J(this,void 0,void 0,function*(){return new xM((e,t)=>J(this,void 0,void 0,function*(){if(!this.pcManager){t(new LM(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`),e()};this.isClosed&&t(new LM(`cannot negotiate on closed engine`)),this.on(Z.Closing,r),this.on(Z.Restarting,r),this.pcManager.publisher.off(qI.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(qI.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof LM&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,vO.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(Z.Closing,r),this.off(Z.Restarting,r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new vA({answer:this.pcManager.mode===`publisher-only`?i?EI({sdp:i.sdp,type:i.type}):void 0:o?EI({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?EI({sdp:r.sdp,type:r.type}):void 0:a?EI({sdp:a.sdp,type:a.type}):void 0,subscription:new Uk({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:vN(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new yA({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new Ak({info:GF.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new bA({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(yL.LOSSY),Sk.PUBLISHER),t(this.dataChannelForKind(yL.RELIABLE),Sk.PUBLISHER),t(this.dataChannelForKind(yL.LOSSY,!0),Sk.SUBSCRIBER),t(this.dataChannelForKind(yL.RELIABLE,!0),Sk.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&GM.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){nP()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){nP()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>K(e,1)[0]===t);if(e)return e[1]}}};function gR(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var _R=WA(HA.Region),vR=5e3,yR=3e4,bR=class e{static fetchRegionSettings(t,n,r){return J(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${xR(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=HP(e.headers),n=t?t*1e3:vR;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}throw e.status===401?MM.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status):MM.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof MM?e:r?.aborted?MM.cancelled(`Region fetching was aborted`):MM.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return J(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>J(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof MM&&i.reason===jM.NotAllowed){_R.debug(`token is not valid, cancelling auto region refresh`);return}_R.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(_R.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},yR))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(t){this.token=t;let n=this.getServerUrl(),r=e.cache.get(n.hostname);e.scheduleRefetch(this.serverUrl,this.token,r?.maxAgeInMs??vR)}isCloud(){return iP(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return J(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return J(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),_R.info(`switching to region: ${e.region}`,{region:e.region}),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};bR.cache=new Map,bR.settingsTimeouts=new Map,bR.connectionTrackers=new Map,bR.fetchLock=new JT;function xR(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}function SR(){return new CompressionStream(`deflate-raw`)}function CR(){return new DecompressionStream(`deflate-raw`)}function wR(e,t){return J(this,void 0,void 0,function*(){let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();return r.write(e).catch(()=>{}),r.close().catch(()=>{}),TR(n.readable,t)})}function TR(e,t){return J(this,void 0,void 0,function*(){let n=e.getReader(),r=[],i=0;for(;;){let e=yield n.read(),a=e.done,o=e.value;if(a)break;if(r.push(o),i+=o.byteLength,typeof t==`number`&&i>t)throw yield n.cancel(),new HM(`Decompressed payload exceeds the maximum payload size of ${t} bytes`,VM.PayloadTooLarge)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a})}var ER=15e3,DR=5e9,OR=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(typeof this.totalByteSize==`number`&&this.totalByteSize!==0){if(e&&this.bytesReceived<this.totalByteSize)throw new HM(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,VM.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new HM(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,VM.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}},kR=class extends OR{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>J(this,void 0,void 0,function*(){var n;try{let t=this.signal;if(t?.aborted)throw t.reason;let r=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return r.done?(this.validateBytesReceived(!0),typeof this.totalByteSize==`number`&&((n=this.onProgress)==null||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(e){throw t(),e}}),return(){return J(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=ij(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},AR=class extends OR{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>J(this,void 0,void 0,function*(){var i;try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),typeof this.totalByteSize==`number`&&((i=this.onProgress)==null||i.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new HM(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,VM.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return J(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=ij(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},jR=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:DR;this.log=UA,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new HM(`A text stream handler for topic "${e}" has already been set.`,VM.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new HM(`A byte stream handler for topic "${e}" has already been set.`,VM.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let a=new HM(`Participant ${e} unexpectedly disconnected in the middle of sending data`,VM.AbnormalEnd);for(let e of n){var r=K(e,2);let t=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(t)}for(let e of t){var i=K(e,2);let t=i[0];i[1].controller.error(a),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}}handleStreamHeader(e,t,n){switch(e.contentHeader.case){case`byteHeader`:{let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:OP(e.timestamp),attributes:e.attributes,encryptionType:n},o;switch(e.compression){case hk.DEFLATE_RAW:if(!UP()){UA.warn(`Data stream ${e.streamId} received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping...`);return}o=!0;break;case hk.NONE:o=!1;break;default:UA.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){r(new kR(a,MR(e.streamId,o?wR(s,this.maxPayloadByteLength):s),OP(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.byteStreamControllers.has(e.streamId))throw new HM(`A data stream read is already in progress for a stream with id ${e.streamId}.`,VM.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new kR(a,o?LR(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(NR(e.streamId)),OP(e.totalLength)),{identity:t});return}case`textHeader`:{let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds},o;switch(e.compression){case hk.DEFLATE_RAW:if(!UP()){UA.warn(`Data stream ${e.streamId} received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping...`);return}o=!0;break;case hk.NONE:o=!1;break;default:UA.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){let n=o?wR(s,this.maxPayloadByteLength):s;r(new AR(a,MR(e.streamId,n),OP(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new HM(`A data stream read is already in progress for a stream with id ${e.streamId}.`,VM.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new AR(a,o?RR(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(NR(e.streamId)),OP(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?n.controller.enqueue(e):(n.controller.error(new HM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,VM.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?r.controller.enqueue(e):(r.controller.error(new HM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,VM.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new HM(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,VM.AbnormalEnd)):n.controller.close()):n.controller.error(new HM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,VM.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new HM(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,VM.AbnormalEnd)):r.controller.close()):r.controller.error(new HM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,VM.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}};function MR(e,t){return new ReadableStream({start:n=>J(this,void 0,void 0,function*(){let r=yield t;n.enqueue(new yk({streamId:e,chunkIndex:BigInt(0),content:r})),n.close()})})}function NR(e){let t=-1;return new TransformStream({transform:(n,r)=>{let i=OP(n.chunkIndex);if(i<=t){UA.warn(`ignoring duplicate chunk ${i} ${n.version>0?`(version ${n.version})`:``} for data stream ${e} (last processed: ${t})`);return}if(i>t+1)throw new HM(`Missing chunk(s) ${t+1}..${i-1} for data stream ${e} - cannot reassemble payload`,VM.Incomplete);t=i,n.content.length!==0&&r.enqueue(n)}})}function PR(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function FR(e){let t=0;return new TransformStream({transform:(n,r)=>{n.byteLength>0&&(r.enqueue(new yk({streamId:e,chunkIndex:kP(t),content:n})),t+=1)}})}function IR(e){let t=new TextDecoder(`utf-8`),n=new TextEncoder,r=0,i=n=>{try{return n?t.decode(n,{stream:!0}):t.decode()}catch(t){throw new HM(`Cannot decode compressed data stream ${e} as text: ${t}`,VM.DecodeFailed)}};return new TransformStream({transform:(t,a)=>{let o=i(t);o.length>0&&(a.enqueue(new yk({streamId:e,chunkIndex:kP(r),content:n.encode(o)})),r+=1)},flush:t=>{let a=i();a.length>0&&(t.enqueue(new yk({streamId:e,chunkIndex:kP(r),content:n.encode(a)})),r+=1)}})}function LR(e,t,n){return e.pipeThrough(NR(t)).pipeThrough(PR()).pipeThrough(CR()).pipeThrough(zR(t,n)).pipeThrough(FR(t))}function RR(e,t,n){return e.pipeThrough(NR(t)).pipeThrough(PR()).pipeThrough(CR()).pipeThrough(zR(t,n)).pipeThrough(IR(t))}function zR(e,t){let n=0;return new TransformStream({transform:(r,i)=>{if(n+=r.byteLength,n>t)throw new HM(`Data stream ${e} exceeds the maximum payload size of ${t} bytes`,VM.PayloadTooLarge);i.enqueue(r)}})}var BR=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return J(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},VR=class extends BR{},HR=class extends BR{};function UR(e,t,n){return new vk({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:kP(e.timestamp),totalLength:kP(e.size),attributes:e.attributes,compression:n?.compression??hk.NONE,inlineContent:n?.inlineContent,contentHeader:{case:`textHeader`,value:new gk({version:t?.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:t?.replyToStreamId,operationType:t?.type===`update`?mk.UPDATE:mk.CREATE})}})}function WR(e,t){return new vk({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:kP(e.timestamp),totalLength:kP(e.size),attributes:e.attributes,compression:t?.compression??hk.NONE,inlineContent:t?.inlineContent,contentHeader:{case:`byteHeader`,value:new _k({name:e.name})}})}function GR(e,t){return new UO({destinationIdentities:t,value:{case:`streamHeader`,value:e}})}var KR=new TextEncoder,qR=class{constructor(e,t,n,r,i){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=i}setupEngine(e){this.engine=e}sendText(e,t){return J(this,void 0,void 0,function*(){var n;let r=crypto.randomUUID(),i=KR.encode(e),a=i.byteLength,o=t?.compress??!0,s={id:r,mimeType:`text/plain`,timestamp:Date.now(),topic:t?.topic??``,size:a,attributes:t?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?kO.GCM:kO.NONE},c=o&&UP()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?JR.fromStream(BP(i).pipeThrough(SR())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let e=i,r=hk.NONE;if(c){let t=yield c.collect();t.byteLength<i.byteLength&&(e=t,r=hk.DEFLATE_RAW)}let a=GR(UR(s,void 0,{compression:r,inlineContent:e}),t?.destinationIdentities);if(a.toBinary().byteLength<=ER)return yield this.engine.sendDataPacket(a,yL.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let l=(t?.attachments)?.map(()=>crypto.randomUUID()),u=l?l.length+1:1,d=Array(u).fill(0),f=(e,n)=>{var r;d[n]=e,(r=t?.onProgress)==null||r.call(t,d.reduce((e,t)=>e+t,0)/u)};if(c){s.attachedStreamIds=l;let e=GR(UR(s,void 0,{compression:hk.DEFLATE_RAW}),t?.destinationIdentities);yield this.sendChunkedByteStream(e,r,t?.destinationIdentities,c.stream().pipeThrough(YR(i.length,e=>f(e,0)))),i.length===0&&f(1,0)}else{let n=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:l,attributes:t?.attributes});yield n.write(e),f(1,0),yield n.close(),s=n.info}return t?.attachments&&l&&(yield Promise.all(t.attachments.map((e,n)=>J(this,void 0,void 0,function*(){return this._sendFile(l[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{f(e,n+1)}})})))),s})}sendBytes(e,t){return J(this,void 0,void 0,function*(){var n,r;let i=crypto.randomUUID(),a=t?.destinationIdentities,o=t?.compress??!0,s={id:i,name:t?.name??`unknown`,mimeType:t?.mimeType??`application/octet-stream`,timestamp:Date.now(),topic:t?.topic??``,size:e.byteLength,attributes:t?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?kO.GCM:kO.NONE},c=YR(e.length,t?.onProgress),l=o&&UP()&&this.allRecipientsSupportV2(a)&&this.allRecipientsSupportCompression(a)?JR.fromStream(BP(e).pipeThrough(c).pipeThrough(SR())):null;if(this.allRecipientsSupportV2(a)){let r=e,i=hk.NONE;if(l){let t=yield l.collect();t.byteLength<e.byteLength&&(r=t,i=hk.DEFLATE_RAW)}let o=GR(WR(s,{compression:i,inlineContent:r}),a);if(o.toBinary().byteLength<=ER)return yield this.engine.sendDataPacket(o,yL.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let u=GR(WR(s,{compression:l?hk.DEFLATE_RAW:hk.NONE}),a),d=l?l.stream():BP(e).pipeThrough(c);return yield this.sendChunkedByteStream(u,i,a,d),e.length===0&&((r=t?.onProgress)==null||r.call(t,1)),s})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantClientProtocol(e)>=2)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantCapabilities(e).includes(lk.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,n,r){return J(this,void 0,void 0,function*(){var i,a,o,s;let c=this.engine;yield XR(c,e);let l=0;try{for(var u=!0,d=ij(VP(r,ER)),f;f=yield d.next(),i=f.done,!i;u=!0){s=f.value,u=!1;let e=new UO({destinationIdentities:n,value:{case:`streamChunk`,value:new yk({content:s,streamId:t,chunkIndex:kP(l)})}});yield c.sendDataPacket(e,yL.RELIABLE),l+=1}}catch(e){a={error:e}}finally{try{!u&&!i&&(o=d.return)&&(yield o.call(d))}finally{if(a)throw a.error}}yield ZR(t,n,c)})}streamText(e){return J(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?kO.GCM:kO.NONE,attachedStreamIds:e?.attachedStreamIds},i=GR(UR(r,e),n);yield XR(this.engine,i);let a=0,o=this.engine,s=new WritableStream({write(e){return J(this,void 0,void 0,function*(){for(let r of zP(e,ER)){let e=new yk({content:r,streamId:t,chunkIndex:kP(a)}),i=new UO({destinationIdentities:n,value:{case:`streamChunk`,value:e}});yield o.sendDataPacket(i,yL.RELIABLE),a+=1}})},close(){return J(this,void 0,void 0,function*(){yield ZR(t,n,o)})},abort(e){console.log(`Sink error:`,e)}}),c=()=>J(this,void 0,void 0,function*(){yield l.close()});o.once(Z.Closing,c);let l=new VR(s,r,()=>this.engine.off(Z.Closing,c));return l})}sendFile(e,t){return J(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return J(this,void 0,void 0,function*(){var r;let i=n?.destinationIdentities,a=(n?.compress??!0)&&UP()&&this.allRecipientsSupportV2(i)&&this.allRecipientsSupportCompression(i),o={id:e,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic??``,timestamp:Date.now(),size:t.size,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?kO.GCM:kO.NONE},s=GR(WR(o,{compression:a?hk.DEFLATE_RAW:hk.NONE}),i),c=t.stream().pipeThrough(YR(t.size,n?.onProgress)),l=a?c.pipeThrough(SR()):c;return yield this.sendChunkedByteStream(s,e,i,l),t.size===0&&((r=n?.onProgress)==null||r.call(n,1)),o})}streamBytes(e){return J(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?kO.GCM:kO.NONE},i=GR(WR(r),n);yield XR(this.engine,i);let a=0,o=new JT,s=this.engine,c=this.log;return new HR(new WritableStream({write(e){return J(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+ER),o=new UO({destinationIdentities:n,value:{case:`streamChunk`,value:new yk({content:r,streamId:t,chunkIndex:kP(a)})}});yield s.sendDataPacket(o,yL.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return J(this,void 0,void 0,function*(){yield ZR(t,n,s)})},abort(e){c.error(`Sink error:`,e)}}),r)})}},JR=class e{constructor(e){this.state=e}static fromStream(t){return new e({type:`stream`,stream:t})}collect(){return J(this,void 0,void 0,function*(){switch(this.state.type){case`stream`:let e=yield TR(this.state.stream);return this.state={type:`collected`,bytes:e},e;case`collected`:return this.state.bytes}})}stream(){switch(this.state.type){case`stream`:return this.state.stream;case`collected`:return BP(this.state.bytes)}}};function YR(e,t){let n=0;return new TransformStream({transform(r,i){n+=r.byteLength,t&&typeof e==`number`&&e>0&&t(Math.min(n/e,1)),i.enqueue(r)}})}function XR(e,t){return J(this,void 0,void 0,function*(){if(t.toBinary().byteLength>ER)throw new HM(`data stream header exceeds the ${ER}-byte limit; reduce attribute size`,VM.HeaderTooLarge);yield e.sendDataPacket(t,yL.RELIABLE)})}function ZR(e,t,n){return J(this,void 0,void 0,function*(){let r=new UO({destinationIdentities:t,value:{case:`streamTrailer`,value:new bk({streamId:e})}});yield n.sendDataPacket(r,yL.RELIABLE)})}function QR(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function $R(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var ez=1,tz=2,nz=4,rz=8,iz=0,az=12,oz=5,sz=7,cz=3,lz=3,uz=2,dz=1,fz=0,pz=3,mz=2,hz=2,gz=1,_z=0,vz;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(vz||={});var yz=class e extends AM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=vz[t]}static tooShort(){return new e(`Too short to contain a valid header`,vz.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,vz.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,vz.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,vz.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,vz.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,vz.MalformedExt)}},bz;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(bz||={});var xz=class e extends AM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=bz[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,bz.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,bz.TooSmallForPayload)}},Sz=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},Cz;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(Cz||={});var wz=class extends Sz{},Tz=class e extends wz{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=ez,t.setUint8(n,e.lengthBytes),n+=ez,t.setBigUint64(n,this.timestamp),n+=rz;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};Tz.tag=Cz.UserTimestamp,Tz.lengthBytes=8;var Ez=class e extends wz{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=ez,t.setUint8(n,e.lengthBytes),n+=ez,t.setUint8(n,this.keyIndex),n+=ez;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=ez;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};Ez.tag=Cz.E2ee,Ez.lengthBytes=13;var Dz=class e extends Sz{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=BF(t),r,i,a=0;for(;n.byteLength-a>=2;){let e=n.getUint8(a);a+=ez;let t=n.getUint8(a);if(a+=ez,e!==_z)switch(e){case Cz.UserTimestamp:if(n.byteLength-a<Tz.lengthBytes)throw yz.malformedExt(e);r=new Tz(n.getBigUint64(a)),a+=t;break;case Cz.E2ee:if(n.byteLength-a<Ez.lengthBytes)throw yz.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=ez,t+=e*ez,s[e]=n.getUint8(t)}i=new Ez(o,s),a+=t;break;default:if(n.byteLength-a<t)throw yz.malformedExt(e);a+=t}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},Oz={from(e){return{payload:e.payload,extensions:new Dz({userTimestamp:e.userTimestamp?new Tz(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},kz=Symbol.for(`lk.track`),Az=Symbol.for(`lk.data-track`),jz=class{constructor(e,t,n){this.trackSymbol=kz,this.isLocal=!1,this.typeSymbol=Az,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let t=K(this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),2),n=t[0];return t[1].catch(()=>{}),n}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},Mz=class e extends Sz{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new Dz}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((mz+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-mz-e}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=az;return t>0&&(r+=mz+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw xz.tooSmallForHeader();let t=0,n;switch(this.marker){case Nz.Inter:n=fz;break;case Nz.Final:n=dz;break;case Nz.Start:n=uz;break;case Nz.Single:n=pz}t|=n<<cz;let r=this.extensionsMetrics(),i=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;i>0&&(t|=4);let s=0;if(e.setUint8(s,t),s+=ez,e.setUint8(s,0),s+=ez,e.setUint16(s,this.trackHandle),s+=tz,e.setUint16(s,this.sequence.value),s+=tz,e.setUint16(s,this.frameNumber.value),s+=tz,e.setUint32(s,this.timestamp.asTicks()),s+=nz,i>0){let t=a-1;e.setUint16(s,t),s+=tz;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+s));s+=n;for(let t=0;t<o;t+=1)e.setUint8(s,0),s+=ez}let c=this.toBinaryLengthBytes();if(s!==c)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${s} bytes but expected length was ${c} bytes`);return c}static fromBinary(t){let n=BF(t);if(n.byteLength<az)throw yz.tooShort();let r=0,i=n.getUint8(r);r+=ez;let a=i>>oz&sz;if(a>iz)throw yz.unsupportedVersion(a);let o;switch(i>>cz&lz){case uz:o=Nz.Start;break;case dz:o=Nz.Final;break;case pz:o=Nz.Single;break;case fz:default:o=Nz.Inter}let s=(i>>hz&gz)>0;r+=ez;let c;try{c=UF.fromNumber(n.getUint16(r))}catch(e){throw e instanceof HF&&(e.isReason(VF.Reserved)||e.isReason(VF.TooLarge))?yz.invalidHandle(e):e}r+=tz;let l=LF.u16(n.getUint16(r));r+=tz;let u=LF.u16(n.getUint16(r));r+=tz;let d=RF.fromRtpTicks(n.getUint32(r));r+=nz;let f=new Dz;if(s){if(n.byteLength-r<tz)throw yz.missingExtWords();let e=n.getUint16(r);r+=tz;let t=4*(e+1)-mz;if(r+t>n.byteLength)throw yz.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),a=K(Dz.fromBinary(i),2),o=a[0],s=a[1];f=o,r+=s}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},Nz;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(Nz||={});var Pz=class e extends Sz{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw xz.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=ez;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=BF(t),r=K(Mz.fromBinary(n),2),i=r[0],a=r[1],o=n.buffer.slice(n.byteOffset+a,n.byteOffset+n.byteLength);return[new e(i,new Uint8Array(o)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Fz=WA(HA.DataTracks),Iz=class e extends AM{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=Lz[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,Lz.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,Lz.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,Lz.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,Lz.Incomplete,t)}},Lz;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(Lz||={});var Rz=class e{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Nz.Single:return this.frameFromSingle(e,t);case Nz.Start:return this.beginPartial(e,t);case Nz.Inter:case Nz.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){if(e.header.marker!==Nz.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);let n=t?.maxPartialFrames??1;if(this.partials.size>=n){let n=this.peekOldestPartialFrameNumber();if(typeof n!=`number`)throw Error(`Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ${this.partials.size}.`);if(this.partials.delete(n),t?.throwOnInterruption)throw Iz.interrupted(n,e.header.frameNumber.value);Fz.warn(`Data track frame ${n} was interrupted by single-packet frame ${e.header.frameNumber.value}, dropping.`)}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==Nz.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);let n=e.header.sequence,r=e.header.frameNumber.value,i={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},a=t?.maxPartialFrames??1;for(;this.partials.size>=a;){let e=this.peekOldestPartialFrameNumber();if(typeof e!=`number`)break;if(this.partials.delete(e),t?.throwOnInterruption)throw Iz.interrupted(e,r);Fz.warn(`Data track partials full (max ${a}), evicted oldest frame ${e} to make room for new frame ${r}.`)}return this.partials.set(r,i),null}pushToPartial(t){if(t.header.marker!==Nz.Inter&&t.header.marker!==Nz.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);let n=t.header.frameNumber.value,r=this.partials.get(n);if(!r)throw this.partials.delete(n),Iz.unknownFrame(n);if(r.payloads.size>=e.MAX_BUFFER_PACKETS)throw this.partials.delete(n),Iz.bufferFull(n);return r.payloads.has(t.header.sequence.value)&&Fz.warn(`Data track frame ${n} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),r.payloads.set(t.header.sequence.value,t.payload),t.header.marker===Nz.Final?this.finalize(n,r,t.header.sequence.value):null}finalize(e,t,n){let r=t.payloads.size,i=0;for(let e of t.payloads.values())i+=e.length;let a=new Uint8Array(i),o=t.startSequence.clone(),s=0;for(;;){let r=t.payloads.get(o.value);if(!r)break;t.payloads.delete(o.value);let i=a.length-s;if(r.length>i)throw Error(`Depacketizer.finalize: Expected at least ${r.length} more bytes left in the payload buffer, only got ${i} bytes.`);if(a.set(r,s),s+=r.length,o.value!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),Iz.incomplete(e,r,n-t.startSequence.value+1)}};Rz.MAX_BUFFER_PACKETS=128;var zz;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(zz||={});var Bz=class e extends AM{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=zz[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,zz.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,zz.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,zz.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,zz.Cancelled)}},Vz=WA(HA.DataTracks),Hz=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new Rz;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n,this.options=e.pipelineOptions??{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return J(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return Vz.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return J(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return Vz.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return Vz.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},Uz=WA(HA.DataTracks),Wz=1e4,Gz=16,Kz=class extends cj.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let n=this.descriptors.get(e);if(!n){Uz.warn(`Unknown track ${e}, cannot set pipeline options.`);return}n.pipelineOptions=t,n.subscription.type===`active`&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Gz,r=null,i=new bP,a=this.descriptors.get(e),o=()=>{t?.removeEventListener(`abort`,c)},s=()=>{if(o(),!r){Uz.warn(`ReadableStream subscribed to ${e} was not started.`);return}if(!a||this.descriptors.get(a.info.sid)!==a){Uz.warn(`Unknown track ${e}, skipping cancel...`);return}if(a.subscription.type!==`active`){Uz.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},c=()=>{var e;r&&(a?.subscription.type===`active`&&a.subscription.streamControllers.delete(r),r.error(Bz.cancelled()),(e=i.reject)==null||e.call(i,Bz.cancelled()),s())};return[new ReadableStream({start:n=>{r=n,this.subscribeRequest(e,t).then(()=>J(this,void 0,void 0,function*(){var r,s,l;if(!a||this.descriptors.get(a.info.sid)!==a){Uz.error(`Unknown track ${e}`);let t=Bz.disconnected();n.error(t),(r=i.reject)==null||r.call(i,t);return}if(a.subscription.type!==`active`){Uz.error(`Subscription for track ${e} is not active`);let t=Bz.disconnected();n.error(t),(s=i.reject)==null||s.call(i,t);return}if(t?.aborted){c();return}t?.addEventListener(`abort`,c),a.subscription.streamControllers.set(n,o),(l=i.resolve)==null||l.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)})},cancel:()=>{s()}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return J(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>J(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=QR([n,r].filter(e=>e!==void 0)),a=new bP;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,Bz.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new bP,pendingRequestCount:1,cancel:()=>{var e,t;let r=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:n.info.sid,subscribe:!1}),r.type===`pending`&&((t=(e=r.completionFuture).reject)==null||t.call(e,i.aborted?Bz.timeout():Bz.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=$R(Wz);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return J(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){Uz.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}this.closeStreamControllers(t.subscription.streamControllers,e);let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var n=K(r,2);let e=n[0],i=n[1];i();try{e.close()}catch(e){Uz.warn(`Failed to close readable stream for track ${t}: ${e}`)}}}receiveSfuPublicationUpdates(e){return J(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let r of e.entries()){var n=K(r,2);let e=n[0],i=n[1],a=new Set;for(let t of i)a.add(t.sid),!this.descriptors.has(t.sid)&&(this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t)));t.set(e,a)}for(let e of t.entries()){var r=K(e,2);let t=r[0],n=r[1],i=Array.from(this.descriptors.entries()).filter(e=>{let n=K(e,2);return n[0],n[1].publisherIdentity===t}).map(e=>K(e,1)[0]).filter(e=>!n.has(e));for(let e of i)this.handleTrackUnpublished(e)}})}queryPublications(){return J(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return J(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){Uz.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);let r=new jz(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleSidReassigned(e,t){let n=Array.from(this.descriptors.entries()).find(n=>{let r=K(n,2);r[0];let i=r[1];return i.publisherIdentity===e&&i.info.pubHandle===t.pubHandle});if(!n)return!1;let r=K(n,2),i=r[0],a=r[1],o=a.info,s=o.name,c=o.usesE2ee;if(s!==t.name||c!==t.usesE2ee)return Uz.warn(`Info mismatch for ${i}, treating as new publication`),!1;let l=t.sid;if(Uz.debug(`SID reassigned: ${i} -> ${l}`),!this.descriptors.delete(i))return!1;switch(a.info.sid=l,a.subscription.type){case`none`:break;case`pending`:case`active`:this.emit(`sfuUpdateSubscription`,{sid:l,subscribe:!0})}return a.subscription.type===`active`&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){Uz.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let n of e.entries()){var t=K(n,2);let e=t[0],r=t[1];this.registerSubscriberHandle(e,r)}}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){Uz.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:Uz.warn(`No subscription for ${t}`);return;case`active`:this.subscriptionHandles.delete(i.subscription.subcriptionHandle),i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{Uz.debug(`data track subscription activated`,{sid:t,handle:e});let a=new Hz({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:i.pipelineOptions}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return J(this,void 0,void 0,function*(){let t;try{t=K(Pz.fromBinary(e),1)[0]}catch(e){Uz.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){Uz.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){Uz.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){Uz.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers.keys()){if(e.desiredSize!==null&&e.desiredSize<=0){Uz.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=Oz.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=K(t,2);let n=e[0];e[1].subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,Bz.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid)}}reset(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,Bz.disconnected())),n.subscription.type===`active`&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},qz=class e extends AM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=Jz[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,Jz.MtuTooShort)}},Jz;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(Jz||={});var Yz=class e{constructor(e,t){this.sequence=LF.u16(0),this.frameNumber=LF.u16(0),this.clock=zF.rtpStartingNow(RF.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Nz.Single:e===0?Nz.Start:e===t-1?Nz.Final:Nz.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:Nz.Inter,trackHandle:this.handle,sequence:LF.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new Mz(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw qz.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;c=[n+1,r+o],n=c[0],r=c[1]){var c;let a=this.sequence.getThenIncrement(),l=new Mz(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),u=Math.min(o,t.payload.byteLength-r);yield new Pz(l,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,u))}}},Xz;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(Xz||={});var Zz=class e extends AM{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=Xz[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,Xz.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,Xz.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,Xz.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,Xz.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,Xz.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,Xz.Unknown)}static disconnected(){return new e(`Room disconnected`,Xz.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,Xz.Cancelled)}},Qz;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(Qz||={});var $z=class e extends AM{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=Qz[t]}static trackUnpublished(){return new e(`Track is no longer published`,Qz.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,Qz.Dropped,{cause:t})}},eB;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(eB||={});var tB=class e extends AM{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=eB[t]}static packetizer(t){return new e(`Error packetizing frame`,eB.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,eB.Encryption,{cause:t})}},nB=class e{constructor(e,t){this.trackSymbol=kz,this.isLocal=!0,this.typeSymbol=Az,this.handle=null,this.log=UA,this.flushedFuture=new bP,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;(t=(e=this.flushedFuture).resolve)==null||t.call(e),this.manager.off(`packetsFlushedChange`,this.handleManagerPacketsFlushedChange),this.manager.off(`reset`,this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&((n=(t=this.flushedFuture).resolve)==null||n.call(t),this.flushedFuture=new bP)},this.options=e,this.manager=t,this.log=WA(HA.DataTracks),this.manager.on(`packetsFlushedChange`,this.handleManagerPacketsFlushedChange),this.manager.on(`reset`,this.handleManagerReset)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return J(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw $z.trackUnpublished();let t=Oz.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return J(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return J(this,void 0,void 0,function*(){if(!this.handle){UA.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},rB=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new Yz(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return nj(this,arguments,function*(){let t=yield tj(this.encryptIfNeeded(e));try{yield tj(yield*rj(ij(this.packetizer.packetize(t))))}catch(e){throw e instanceof qz?tB.packetizer(e):e}})}encryptIfNeeded(e){return J(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw tB.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new Ez(t.keyIndex,t.iv),e})}};rB.TRANSPORT_MTU_BYTES=16e3;var iB=WA(HA.DataTracks),aB={pending(){return{type:`pending`,completionFuture:new bP}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new rB({info:e,e2eeManager:t}),unpublishingFuture:new bP}}},oB=1e4,sB=class e extends cj.EventEmitter{constructor(e){super(),this.handleAllocator=new WF,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return J(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw $z.trackUnpublished();if(o.publishState===`republishing`)throw $z.dropped(`Data track republishing`);try{try{for(var s=!0,c=ij(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let t=a,n=this.inFlightPacketCounter.get(e)??0;this.inFlightPacketCounter.set(e,n+1),n===0&&this.emit(`packetsFlushedChange`,{handle:e,isFlushed:!1}),this.emit(`packetAvailable`,{handle:e,bytes:t.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw $z.dropped(e)}})}handlePacketSendComplete(e){let t=(this.inFlightPacketCounter.get(e)??0)-1;t<0&&(iB.warn(`OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ${this.inFlightPacketCounter} - resetting to 0. Were more packets send than were emitted?`),t=0),this.inFlightPacketCounter.set(e,t),t===0&&this.emit(`packetsFlushedChange`,{handle:e,isFlushed:!0})}publishRequest(e,t){return J(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Zz.limitReached();let r=$R(oB),i=t?QR([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=aB.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){iB.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?Zz.timeout():Zz.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:nB.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return J(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){iB.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){iB.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){iB.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let i=t.data;iB.debug(`SFU accepted publish request for handle ${e}`,{sid:i.sid});let a=i.usesE2ee?this.e2eeManager:null;this.descriptors.set(i.pubHandle,aB.active(i,a)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else iB.debug(`SFU rejected publish request for handle ${e}`,{error:t.error}),(a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){iB.warn(`Track ${e} already active`);return}if(t.type===`error`){iB.warn(`Republish failed for track ${e}`);return}iB.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){iB.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){iB.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var n=K(r,2);let i=n[0],a=n[1];switch(a.type){case`pending`:this.descriptors.delete(i),(t=(e=a.completionFuture).reject)==null||t.call(e,Zz.disconnected());break;case`active`:a.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return J(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,Zz.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit(`reset`)})}},cB=class e extends Error{constructor(t,n,r,i){super(n),this.code=t,this.message=gB(n,e.MAX_MESSAGE_BYTES),this.data=r?gB(r,e.MAX_DATA_BYTES):void 0,i?.cause!==void 0&&(this.cause=i?.cause)}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new rk({code:this.code,message:this.message,data:this.data})}static builtIn(t,n,r){return new e(e.ErrorCode[t],e.ErrorMessage[t],n,r)}};cB.MAX_MESSAGE_BYTES=256,cB.MAX_DATA_BYTES=15360,cB.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},cB.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var lB=15360,uB=`lk.rpc_request`,dB=`lk.rpc_response`,fB;(function(e){e.RPC_REQUEST_ID=`lk.rpc_request_id`,e.RPC_REQUEST_METHOD=`lk.rpc_request_method`,e.RPC_REQUEST_RESPONSE_TIMEOUT_MS=`lk.rpc_request_response_timeout_ms`,e.RPC_REQUEST_VERSION=`lk.rpc_request_version`})(fB||={});var pB=1,mB=2;function hB(e){return new TextEncoder().encode(e).length}function gB(e,t){if(hB(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var _B=class extends cj.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return J(this,arguments,void 0,function(e){var t=this;let n=e.destinationIdentity,r=e.method,i=e.payload,a=e.responseTimeout,o=a===void 0?15e3:a;return function*(){let e=t.getRemoteParticipantClientProtocol(n);if(hB(i)>lB&&e<1)throw cB.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`);let a=t.getServerVersion();if(a&&lP(a,`1.8.0`)<0)throw cB.builtIn(`UNSUPPORTED_SERVER`);let s=Math.max(o,8e3),c=crypto.randomUUID(),l=new bP,u=null,d=setTimeout(()=>{var e;t.pendingAcks.delete(c),(e=l.reject)==null||e.call(l,cB.builtIn(`CONNECTION_TIMEOUT`)),t.pendingResponses.delete(c),u!==null&&clearTimeout(u)},7e3);return t.pendingAcks.set(c,{resolve:()=>{clearTimeout(d)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:l,participantIdentity:n}),yield t.publishRpcRequest(n,c,r,i,s,e),u=setTimeout(()=>{var e;t.pendingResponses.delete(c),(e=l.reject)==null||e.call(l,cB.builtIn(`RESPONSE_TIMEOUT`))},o),[c,l.promise.finally(()=>{clearTimeout(u),t.pendingAcks.has(c)&&(t.log.warn(`RPC response received before ack`,c),t.pendingAcks.delete(c),clearTimeout(d))})]}()})}publishRpcRequest(e,t,n,r,i,a){return J(this,void 0,void 0,function*(){if(a>=1){yield this.outgoingDataStreamManager.sendText(r,{topic:uB,destinationIdentities:[e],attributes:{[fB.RPC_REQUEST_ID]:t,[fB.RPC_REQUEST_METHOD]:n,[fB.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:`${i}`,[fB.RPC_REQUEST_VERSION]:`${mB}`}});return}this.emit(`sendDataPacket`,{packet:new UO({destinationIdentities:[e],kind:WO.RELIABLE,value:{case:`rpcRequest`,value:new ek({id:t,method:n,payload:r,responseTimeoutMs:i,version:pB})}})})})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[fB.RPC_REQUEST_ID];if(!r){this.log.warn(`RPC data stream malformed: ${fB.RPC_REQUEST_ID} not set.`);return}let i=this.pendingResponses.get(r);if(i&&i.participantIdentity!==t){this.log.warn(`RPC response stream for ${r} arrived from unexpected sender ${t}, expected ${i.participantIdentity}. Ignoring.`);return}let a;try{a=yield e.readAll()}catch(e){this.log.warn(`Error reading RPC response payload: ${e}`),this.handleIncomingRpcResponseFailure(r,cB.builtIn(`APPLICATION_ERROR`,`Error reading RPC response payload`,{cause:e}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var n,r;let i=this.pendingResponses.get(e);i?((r=(n=i.completionFuture).resolve)==null||r.call(n,t),this.pendingResponses.delete(e)):this.log.error(`Response received for unexpected RPC request`,e)}handleIncomingRpcResponseFailure(e,t){var n,r;let i=this.pendingResponses.get(e);i?((r=(n=i.completionFuture).reject)==null||r.call(n,t),this.pendingResponses.delete(e)):this.log.error(`Response received for unexpected RPC request`,e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error(`Ack received for unexpected RPC request: ${e}`)}handleParticipantDisconnected(e){var t;for(let t of this.pendingAcks){var n=K(t,2);let r=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(r)}for(let n of this.pendingResponses){var r=K(n,2);let a=r[0];var i=r[1];let o=i.participantIdentity,s=i.completionFuture;o===e&&((t=s.reject)==null||t.call(s,cB.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(a))}}},vB=class extends cj.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return J(this,void 0,void 0,function*(){if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,cB.builtIn(`UNSUPPORTED_VERSION`));return}let n=this.rpcHandlers.get(t.method);if(!n){this.publishRpcResponsePacket(e,t.id,null,cB.builtIn(`UNSUPPORTED_METHOD`));return}let r;try{r=yield n({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(n){let r;n instanceof cB?r=n:(this.log.warn(`Uncaught error returned by RPC handler for ${t.method}. Returning APPLICATION_ERROR instead.`,n),r=cB.builtIn(`APPLICATION_ERROR`,`Uncaught error: ${n?.message??n}`,{cause:n})),this.publishRpcResponsePacket(e,t.id,null,r);return}yield this.publishRpcResponse(e,t.id,r??``)})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[fB.RPC_REQUEST_ID],i=n[fB.RPC_REQUEST_METHOD],a=parseInt(n[fB.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[fB.RPC_REQUEST_VERSION],10);if(!r||!i||Number.isNaN(a)||Number.isNaN(o)){this.log.warn(`RPC data stream malformed: ${fB.RPC_REQUEST_ID} / ${fB.RPC_REQUEST_METHOD} / ${fB.RPC_REQUEST_RESPONSE_TIMEOUT_MS} / ${fB.RPC_REQUEST_VERSION} not set.`),this.publishRpcResponsePacket(t,r,null,cB.builtIn(`APPLICATION_ERROR`,`RPC data stream malformed`));return}if(this.publishRpcAck(t,r),o!==mB){this.publishRpcResponsePacket(t,r,null,cB.builtIn(`UNSUPPORTED_VERSION`));return}let s;try{s=yield e.readAll()}catch(e){this.log.warn(`Error reading RPC request payload: ${e}`),this.publishRpcResponsePacket(t,r,null,cB.builtIn(`APPLICATION_ERROR`,`Error reading RPC request payload`,{cause:e}));return}let c=this.rpcHandlers.get(i);if(!c){this.publishRpcResponsePacket(t,r,null,cB.builtIn(`UNSUPPORTED_METHOD`));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:s,responseTimeout:a})}catch(e){let n;e instanceof cB?n=e:(this.log.warn(`Uncaught error returned by RPC handler for ${i}. Returning APPLICATION_ERROR instead.`,e),n=cB.builtIn(`APPLICATION_ERROR`)),this.publishRpcResponsePacket(t,r,null,n);return}yield this.publishRpcResponse(t,r,l??``)})}publishRpcAck(e,t){this.emit(`sendDataPacket`,{packet:new UO({destinationIdentities:[e],kind:WO.RELIABLE,value:{case:`rpcAck`,value:new tk({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit(`sendDataPacket`,{packet:new UO({destinationIdentities:[e],kind:WO.RELIABLE,value:{case:`rpcResponse`,value:new nk({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}})})}publishRpcResponse(e,t,n){return J(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){yield this.outgoingDataStreamManager.sendText(n,{topic:dB,destinationIdentities:[e],attributes:{[fB.RPC_REQUEST_ID]:t}});return}if(hB(n)>lB){this.log.warn(`RPC Response payload too large for request ${t}. To send larger responses, consider updating the sending client.`),this.publishRpcResponsePacket(e,t,null,cB.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`));return}this.publishRpcResponsePacket(e,t,n,null)})}},yB=class extends bF{constructor(e,t,n,r,i,a){super(e,t,$.Kind.Audio,n,a),this.monitorReceiver=()=>J(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=yF(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;rP()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(rP())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return J(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(GN(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&GN(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(Q.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(Q.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return J(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},bB=class extends cj.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=kO.NONE,this.log=UA,this.handleMuted=()=>{this.emit(Q.Muted)},this.handleUnmuted=()=>{this.emit(Q.Unmuted)},this.log=WA(r?.loggerName??HA.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=$.Source.Unknown}setTrack(e){this.track&&(this.track.off(Q.Muted,this.handleMuted),this.track.off(Q.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Q.Muted,this.handleMuted),e.on(Q.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),yN(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==kO.NONE}get audioTrack(){if(jP(this.track))return this.track}get videoTrack(){if(MP(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=$.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===$.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(bB||={});var xB=class extends bB{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Q.Ended)},this.handleCpuConstrained=()=>{this.track&&MP(this.track)&&this.emit(Q.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(Q.Ended,this.handleTrackEnded),this.track.off(Q.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Q.Ended,this.handleTrackEnded),e.on(Q.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return J(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return J(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return J(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return J(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(jP(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(bO.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(bO.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(bO.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(bO.TF_STEREO),this.options?.dtx||t.add(bO.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(bO.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}return[]}};function SB(e,t){return J(this,void 0,void 0,function*(){e??={};let n=!1,r=SN(e),i=r.audioProcessor,a=r.videoProcessor,o=r.optionsWithoutProcessor,s=o.audio,c=o.video;if(i&&typeof o.audio==`object`&&(o.audio.processor=i),a&&typeof o.video==`object`&&(o.video.processor=a),e.audio&&typeof o.audio==`object`&&typeof o.audio.deviceId==`string`){let e=o.audio.deviceId;o.audio.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&typeof o.video==`object`&&typeof o.video.deviceId==`string`){let e=o.video.deviceId;o.video.deviceId={exact:e},n=!0,c=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}o.audio===!0?o.audio={deviceId:`default`}:typeof o.audio==`object`&&o.audio!==null&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||`default`})),o.video===!0?o.video={deviceId:`default`}:typeof o.video==`object`&&!o.video.deviceId&&(o.video.deviceId=`default`);let l=dN(lN(o,lL,uL)),u=navigator.mediaDevices.getUserMedia(l);o.audio&&(PF.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>PF.userMediaPromiseMap.delete(`audioinput`))),o.video&&(PF.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>PF.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>J(this,void 0,void 0,function*(){let r=n.kind===`audio`,o,s=r?l.audio:l.video;typeof s!=`boolean`&&(o=s);let c=n.getSettings().deviceId;o?.deviceId&&SP(o.deviceId)!==c?o.deviceId=c:o||={deviceId:c};let u=RL(n,o,t);return u.kind===$.Kind.Video?u.source=$.Source.Camera:u.kind===$.Kind.Audio&&(u.source=$.Source.Microphone),u.mediaStream=e,jP(u)&&i?yield u.setProcessor(i):MP(u)&&a&&(yield u.setProcessor(a)),u})))}catch(r){if(!n)throw r;return SB(Object.assign(Object.assign({},e),{audio:s,video:c}),t)}})}var CB;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(CB||={});function wB(e){switch(e){case hO.EXCELLENT:return CB.Excellent;case hO.GOOD:return CB.Good;case hO.POOR:return CB.Poor;case hO.LOST:return CB.Lost;default:return CB.Unknown}}var TB=class extends cj.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===DO.AGENT}get isActive(){return this.participantInfo?.state===EO.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:DO.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=CB.Unknown,this.log=UA,this.loggerOptions=a,this.log=WA(a?.loggerName??HA.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let t of this.trackPublications){let n=K(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(let t of this.trackPublications){let n=K(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new bP,this.once(X.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication($.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication($.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication($.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===EO.ACTIVE&&this.participantInfo?.state!==EO.ACTIVE&&this.emit(X.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(X.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(X.ParticipantNameChanged,e)}_setAttributes(e){let t=xN(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(X.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(X.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(X.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=wB(e),t!==this._connectionQuality&&this.emit(X.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>jP(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug(`adding track publication`,{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(Q.Muted,()=>{this.emit(X.TrackMuted,e)}),e.on(Q.Unmuted,()=>{this.emit(X.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case $.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case $.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}};function EB(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new mA({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var DB=class extends TB{constructor(e,t,n,r,i,a,o,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=kO.NONE,this.e2eeStateMutex=new JT,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||=new bP},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new bP,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let t=e.requestId,n=e.reason,r=e.message,i=this.pendingSignalRequests.get(t);switch(i&&(n!==OA.OK&&i.reject(new BM(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case OA.NOT_ALLOWED:t=Zz.notAllowed(e.message);break;case OA.DUPLICATE_NAME:t=Zz.duplicateName(e.message);break;case OA.INVALID_NAME:t=Zz.invalidName(e.message);break;case OA.LIMIT_EXCEEDED:t=Zz.limitReached(e.message);break;default:t=Zz.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>EB(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,yN(e));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,yN(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,yN(e)),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,yN(t)),this.emit(X.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>J(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,{trackSid:e.trackSid});return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=ij(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;rN(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,yN(a)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,{trackSid:e.trackSid});return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>J(this,void 0,void 0,function*(){if(e.source===$.Source.ScreenShare||e.source===$.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,yN(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(PP(e)||NP(e))try{if(nP())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===$.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,yN(e)),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,yN(e)),PP(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,yN(e)),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=i,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==kO.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Z.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(Z.Connected,this.handleReconnected).on(Z.SignalConnected,this.handleSignalConnected).on(Z.SignalRestarted,this.handleReconnected).on(Z.SignalResumed,this.handleReconnected).on(Z.Restarting,this.handleReconnecting).on(Z.Resuming,this.handleReconnecting).on(Z.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Z.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Z.Closing,this.handleClosing).on(Z.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return J(this,arguments,void 0,function(e){var t=this;let n=e.metadata,r=e.name,i=e.attributes;return function*(){return new xM((e,a)=>J(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let t=K(e,2),n=t[0],r=t[1];return this.attributes[n]===r||r===``&&!this.attributes[n]}))){this.pendingSignalRequests.delete(o),e();return}yield PN(50)}a(new BM(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled($.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled($.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled($.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return J(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?kO.GCM:kO.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(t=>t.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return J(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t){if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,{source:e}),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case $.Source.Camera:t=yield this.createTracks({video:n??!0});break;case $.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case $.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new PM(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(X.MediaDevicesError,n,hN(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===$.Source.Microphone&&jP(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,yN(n)),e.push(this.publishTrack(n,r));i=K(yield Promise.all(e),1)[0]}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,{source:e})),i&&i.track){if(e===$.Source.ScreenShare){let e=[this.unpublishTrack(i.track)],t=this.getTrackPublication($.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),i=K(yield Promise.all(e),1)[0]}else yield i.mute()}return i})}enableCameraAndMicrophone(){return J(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has($.Source.Camera)||this.pendingPublishing.has($.Source.Microphone))){this.pendingPublishing.add($.Source.Camera),this.pendingPublishing.add($.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete($.Source.Camera),this.pendingPublishing.delete($.Source.Microphone)}}})}createTracks(e){return J(this,void 0,void 0,function*(){e??={};let t=lN(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield SB(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(jP(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=$.Source.Microphone,this.emit(X.AudioStreamAcquired)),MP(e)&&(this.cameraError=void 0,e.source=$.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return J(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new NM(`getDisplayMedia not supported`);e.resolution===void 0&&!QN()&&(e.resolution=cN.h1080fps30.resolution);let t=gN(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new PM(`no video track found`);let i=new rR(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=$.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(X.AudioStreamAcquired);let e=new LL(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=$.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return J(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,n)=>{let r=()=>{clearTimeout(o),this.engine.off(Z.Restarted,i),this.engine.off(Z.Closing,a)},i=()=>{r(),t()},a=()=>{r(),n(Error(`engine closed before restart completed`))},o=setTimeout(()=>{r(),n(Error(`timed out waiting for engine restart`))},e);this.engine.once(Z.Restarted,i),this.engine.once(Z.Closing,a)})}publishOrRepublishTrack(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0&&arguments[2],i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return function*(){PP(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),AP(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let a;if(e instanceof MediaStreamTrack)a=e.getConstraints();else{a=e.constraints;let t;switch(e.source){case $.Source.Microphone:t=`audioinput`;break;case $.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(a=Object.assign(Object.assign({},a),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new LL(e,a,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new rR(e,a,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new PM(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let o;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return n.log.warn(`track has already been published, skipping`,yN(o)),o;let s=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),c=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,l=s.forceStereo??c;l&&(s.dtx===void 0&&n.log.debug(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,yN(e)),s.red===void 0&&n.log.debug(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),s.dtx??=!1,s.red??=!1),!tP()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`),s.simulcast=!1),s.source&&(e.source=s.source);let u=new Promise((t,r)=>J(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==bI.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,{track:yN(e)});let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new zM(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,s,l))}else try{t(yield this.publish(e,s,l))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,u);try{return yield u}catch(a){if(!i&&a instanceof LM)return n.log.warn(`negotiation due to track publish failed, retrying after reconnect`,{error:a}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,r,!0);throw a}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new bP,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,yN(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(e=>CN(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,yN(e)),!1)}publish(e,t,n){return J(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new zM(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>AP(e)&&t.source===e.source)&&e.source!==$.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,yN(e)),t.stopMicTrackOnMute&&jP(e)&&(e.stopOnMute=!0),e.source===$.Source.ScreenShare&&qN()&&(t.simulcast=!1),t.videoCodec===`av1`&&!LN()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!RN()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=sL),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===_N(e.mime))||(t.videoCodec=_N(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(Q.Muted,this.onTrackMuted),e.on(Q.Unmuted,this.onTrackUnmuted),e.on(Q.Ended,this.handleTrackEnded),e.on(Q.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Q.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Q.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(bO.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(bO.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(bO.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(bO.TF_STEREO),a&&i.push(bO.TF_NO_DTX),PP(e)&&e.hasPreConnectBuffer&&i.push(bO.TF_PRECONNECT_BUFFER);let s=this.normalizeRequestedFrameMetadataOptions(e,t),c=new Ok({cid:e.mediaStreamTrack.id,name:t.name,type:$.kindToProto(e.kind),muted:e.isMuted,source:$.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i,packetTrailerFeatures:s}),l;if(e.kind===$.Kind.Video){let n;try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??oN.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign({},yN(e)),{dims:n}))}if(c.width=n.width,c.height=n.height,NP(e)){VN(r,t)&&(HN()||!WN(this.engine?.serverVersion))&&(t.simulcast=!1,this.log.info(`SVC simulcast is not supported, disabling simulcast.`,yN(e)));let n=VN(r,t);zN(r)&&!n&&(e.source===$.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.debug(`forcing contentHint to motion for screenshare with SVC codecs`,yN(e)))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`);let i=new Dk({codec:r,cid:e.mediaStreamTrack.id});n&&(i.videoLayerMode=HO.ONE_SPATIAL_LAYER_PER_STREAM),c.simulcastCodecs=[i],t.backupCodec===!0&&(t.backupCodec={codec:sL}),t.backupCodec&&r!==t.backupCodec.codec&&c.encryption===kO.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),c.simulcastCodecs.push(new Dk({codec:t.backupCodec.codec,cid:``})))}l=KL(e.source===$.Source.ScreenShare,c.width,c.height,t),c.layers=oR(c.width,c.height,l,zN(t.videoCodec)&&!VN(t.videoCodec,t))}else e.kind===$.Kind.Audio&&(l=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new IM(`cannot publish track when not connected`);let u=()=>J(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new IM(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,l),NP(e)&&(e.publishOptions=t),this.emit(X.LocalSenderCreated,e.sender,e),NP(e)&&(t.degradationPreference??=tR(e),e.setDegradationPreference(t.degradationPreference)),l){if(qN()&&e.kind===$.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:l[0]?.maxBitrate?l[0].maxBitrate/1e3:0})}else if(e.codec&&xP(e.codec)){let n=qL(e.codec,t,l);n>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:c.cid,codec:e.codec,maxbr:n/1e3,isScreenShare:e.source===$.Source.ScreenShare})}}yield this.engine.negotiate()}),d,f=new Promise((t,n)=>J(this,void 0,void 0,function*(){try{d=yield this.engine.addTrack(c),t(d)}catch(t){if(e.sender&&this.engine.pcManager?.publisher){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign({},yN(e)),{error:t}))})}n(t)}}));if(this.enabledPublishVideoCodecs.length>0&&s.length===0)d=(yield Promise.all([f,u()]))[0];else{d=yield f;let n;if(d.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===$.Kind.Video){let i=_N(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign({},yN(e)),{codec:i})),t.videoCodec=i,l=KL(e.source===$.Source.ScreenShare,c.width,c.height,t))}yield u()}let p=new xB(e.kind,d,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(p.on(Q.CpuConstrained,e=>this.onTrackCpuConstrained(e,p)),p.options=t,e.sid=d.sid,NP(e)&&(e.publishOptions=t,c.width&&c.height&&(e.lastEncodedDimensions={width:c.width,height:c.height})),this.log.debug(`publishing ${e.kind} with encodings`,{encodings:l,trackInfo:d}),NP(e)?e.startMonitor(this.engine.client):PP(e)&&e.startMonitor(),this.addTrackPublication(p),this.emit(X.LocalTrackPublished,p),PP(e)&&d.audioFeatures.includes(bO.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(X.LocalTrackSubscribed,t=>{if(t.trackSid===d.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`);return}this.log.debug(`finished recording preconnect buffer`,yN(e)),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>J(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,yN(e));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,yN(e));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:p.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=ij(t),f;f=yield d.next(),a=f.done,!a;u=!0){l=f.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,yN(e))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign({},yN(e)),{error:t}))})}return p})}canPublishFrameMetadata(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||pF(this.roomOptions.frameMetadata??this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){let n=t.frameMetadata??t.packetTrailer;if(e.kind!==$.Kind.Video||!mF(n))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn(`frame metadata transform not supported; not advertising features`,Object.assign(Object.assign({},this.logContext),yN(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let r=hF(n),i=gF(r);return t.frameMetadata=i,t.packetTrailer=i,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return J(this,void 0,void 0,function*(){if(this.encryptionType!==kO.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new PM(`track is not published`);if(!NP(e))throw new PM(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=JL(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,yN(e));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=this.normalizeRequestedFrameMetadataOptions(e,i),c=new Ok({cid:o.mediaStreamTrack.id,type:$.kindToProto(e.kind),muted:e.isMuted,source:$.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:s,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=oR(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new IM(`cannot publish track when not connected`);let l=(yield Promise.all([this.engine.addTrack(c),J(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,{encodings:a,trackInfo:l})})}unpublishTrack(e,t){return J(this,void 0,void 0,function*(){if(AP(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.debug(`awaiting publish promise before attempting to unpublish`,yN(e)),yield t)}let n=this.getPublicationForTrack(e),r=n?yN(n):void 0;if(this.log.info(`unpublishing track`,r),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,r);return}e=n.track,e.off(Q.Muted,this.onTrackMuted),e.off(Q.Unmuted,this.onTrackUnmuted),e.off(Q.Ended,this.handleTrackEnded),e.off(Q.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Q.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Q.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<pL.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);try{i=this.engine.removeTrack(a)}catch(e){this.log.warn(e),i=!0}if(NP(e)){for(let t of e.simulcastCodecs){let e=K(t,2)[1];if(e.sender){try{i=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),i=!0}e.sender=void 0}}e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign({},r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case $.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case $.Kind.Video:this.videoTrackPublications.delete(n.trackSid)}return this.emit(X.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return J(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new xM((r,i)=>J(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>J(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==$.Source.ScreenShare&&t.source!==$.Source.ScreenShareAudio&&(PP(t)||NP(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?yL.RELIABLE:yL.LOSSY,i=n.reliable?WO.RELIABLE:WO.LOSSY,a=n.destinationIdentities,o=n.topic,s=new UO({kind:i,value:{case:`user`,value:new YO({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return J(this,void 0,void 0,function*(){let n=new UO({kind:WO.RELIABLE,value:{case:`sipDtmf`,value:new XO({code:e,digit:t})}});yield this.engine.sendDataPacket(n,yL.RELIABLE)})}sendChatMessage(e,t){return J(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new UO({value:{case:`chatMessage`,value:new $O(Object.assign(Object.assign({},n),{timestamp:TE.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,yL.RELIABLE),this.emit(X.ChatMessage,n),n})}editChatMessage(e,t){return J(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new UO({value:{case:`chatMessage`,value:new $O(Object.assign(Object.assign({},n),{timestamp:TE.parse(n.timestamp),editTimestamp:TE.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,yL.RELIABLE),this.emit(X.ChatMessage,n),n})}sendText(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(e=>{let t=K(e,2);return t[0],t[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign({},yN(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new bP,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(PP(r)||NP(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return J(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>K(t,1)[0].source===e);if(t)return t[1];yield PN(20)}})}publishDataTrack(e){return J(this,void 0,void 0,function*(){let t=new nB(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},OB=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},kB=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending?.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`DeferrableMap`}getDeferred(e,t){return J(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new OB(`The operation was aborted.`,t.reason);let r=new bP(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new OB(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},AB=class extends bB{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Q.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Uk({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ik({participantSid:``,trackSids:[this.trackSid]})]});this.emit(Q.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?bB.SubscriptionStatus.Unsubscribed:super.isSubscribed?bB.SubscriptionStatus.Subscribed:bB.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bB.PermissionStatus.Allowed:bB.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed!==!1&&super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?!this.isAdaptiveStream||this.visible:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width!==e.width||this.requestedVideoDimensions?.height!==e.height)&&(LP(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&LP(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??ON.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(Q.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(Q.VisibilityChanged,this.handleVisibilityChange),r.off(Q.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(Q.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Q.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Q.VisibilityChanged,this.handleVisibilityChange),e.on(Q.Ended,this.handleEnded),this.emit(Q.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Q.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Q.Muted:Q.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(Q.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Q.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return LP(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new Xk({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===$.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0){if(t)wN(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=TN(this.trackInfo,this.requestedMaxQuality);e&&wN(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream}t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:ON.HIGH})),e.quality=ON.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(Q.UpdateSettings,e)}},jB=class e extends TB{static fromParticipantInfo(t,n,r,i){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind,n.dataTracks.map(e=>new jz(GF.from(e),i,{publisherIdentity:n.identity})),n.clientProtocol,n.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:DO.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:0,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new kB(c.map(e=>[e.info.name,e])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(Q.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),yN(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Q.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Q.SubscriptionPermissionChanged,t=>{this.emit(X.TrackSubscriptionPermissionChanged,e,t)}),e.on(Q.SubscriptionStatusChanged,t=>{this.emit(X.TrackSubscriptionStatusChanged,e,t)}),e.on(Q.Subscribed,t=>{this.emit(X.TrackSubscribed,t,e)}),e.on(Q.Unsubscribed,t=>{this.emit(X.TrackUnsubscribed,t,e)}),e.on(Q.SubscriptionFailed,t=>{this.emit(X.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:$.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(X.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),yN(o))),this.emit(X.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new SF(e,t,r,i):new yB(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&FP(c)&&jP(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=$.kindFromProto(e.type);if(!t)return;r=new AB(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==$.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:yN(i),newTrack:yN(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),yN(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(X.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case $.Kind.Audio:this.audioTrackPublications.delete(e);break;case $.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(X.TrackUnpublished,n)}setAudioOutput(e){return J(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{jP(n.track)&&FP(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let n of this.dataTracks.entries()){var t=K(n,2);let r=t[0];e===t[1].info.sid&&this.dataTracks.delete(r)}}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},MB;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(MB||={});var NB=4e3,PB=3e4,FB=class e extends cj.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=MB.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new JT,this.isVideoPlaybackBlocked=!1,this.log=UA,this.statsLog=UA,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(e,t,n)=>J(this,void 0,void 0,function*(){if(!KN())throw rP()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===MB.Connected)return this.log.info(`already connected to room ${this.name}`),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(MB.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==YP(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),iP(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new bR(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,{error:e})}));let i=(a,o,s)=>J(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield MF.getInstance().getBackOffPromise(e),c.signal.aborted)throw MM.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof MM&&t.reason!==jM.Cancelled&&t.reason!==jM.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof MM&&(e.status===401||e.reason===jM.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[jM.InternalError,jM.ServerUnreachable,jM.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),MF.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,DP(t)),o(t))}else{let e=_O.UNKNOWN_REASON;t instanceof MM&&(e=DP(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new bP((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>J(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`||i.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(i),maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.joinResponse,c=o.serverInfo;if(this.serverInfo=c,!c.version)throw new FM(`unknown server version`);return c.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`),i.dynacast=!1),s}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>J(this,void 0,void 0,function*(){this.state===MB.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},fL),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?MM.cancelled(`Signal connection aborted`):MM.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof MM&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),MM.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}nP()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),nP()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(MB.Connected),this.emit(Y.Connected),MF.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return J(n,[...arguments],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===MB.Disconnected){e.log.debug(`already disconnected`);return}if(e.log.info(`disconnect from room`),e.state===MB.Connecting||e.state===MB.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,MM.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,_O.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>J(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`),yield this.disconnect()}),this.startAudio=()=>J(this,void 0,void 0,function*(){let e=[],t=wM();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=yP();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`),this.startAudio()))}),document.body.append(n),this.once(Y.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(this.options.webAudioMix||(e.muted=!1),e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>J(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(MB.Reconnecting)&&this.emit(Y.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>J(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,{region:e.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,{region:e.serverRegion})}catch{return}this.setAndEmitConnectionState(MB.Connected),this.emit(Y.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===EO.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e,t.disconnectReason===_O.UNKNOWN_REASON?void 0:t.disconnectReason):this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>GF.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Y.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(Y.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=$.streamStateFromProto(e.state),i=n.track.streamState;n.track.setStreamState(r),r!==i&&(t.emit(X.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(Y.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{this.cancelPendingTrackAdded(e.trackSid);let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if(e.value.case===`rpcResponse`){let t=e.value.value;switch(t.value.case){case`payload`:this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case`error`:this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,cB.fromProto(t.value.value));break;default:this.log.warn(`Unknown rpcResponse.value.case: ${t.value.case}`,this.logContext)}}else e.value.case===`rpcAck`&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(e,t,n,r)=>{this.emit(Y.DataReceived,t.payload,e,n,t.topic,r),e?.emit(X.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(Y.SipDTMFReceived,t,e),e?.emit(X.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=TP(t,this.transcriptionReceivedTimes);r?.emit(Q.TranscriptionReceived,i),n?.emit(X.TranscriptionReceived,i,r),this.emit(Y.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=EP(t);this.emit(Y.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(Y.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Y.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Y.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Y.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Y.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>J(this,void 0,void 0,function*(){wM()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(Y.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Y.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(Y.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.getRemoteParticipantClientProtocol=e=>this.remoteParticipants.get(e)?.clientProtocol??0,this.getRemoteParticipantCapabilities=e=>this.remoteParticipants.get(e)?.capabilities??[],this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.logWebRTCStats=()=>J(this,void 0,void 0,function*(){let e=this.engine?.pcManager;if(e)try{let t=K(yield Promise.all([e.publisher.getStats(),e.subscriber?.getStats()]),2),n=t[0],r=t[1],i=n&&ZM(n),a=r&&ZM(r);this.statsLog.info(`webrtc stats`,{publisher:i?.connection,subscriber:a?.connection,inbound:[...i?.inbound??[],...a?.inbound??[]],outbound:i?.outbound})}catch(e){this.statsLog.debug(`could not collect webrtc stats`,{error:e})}}),this.onLocalParticipantMetadataChanged=e=>{this.emit(Y.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Y.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Y.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Y.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Y.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>J(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(Q.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(Q.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(Y.LocalTrackPublished,e,this.localParticipant),PP(e.track)&&(yield e.track.checkForSilence())&&this.emit(Y.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=hN(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(Y.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(Q.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(Q.Restarted,this.onLocalTrackRestarted),this.emit(Y.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>J(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=hN(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`),this.localParticipant.activeDeviceMap.set(n,t),this.emit(Y.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Y.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Y.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Y.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Y.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},dL),t),this.log=WA(this.options.loggerName??HA.Room,()=>this.logContext),this.statsLog=WA(HA.Stats,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},lL),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},uL),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},cL),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new jR(this.options.dataStream?.maxPayloadByteLength),this.outgoingDataStreamManager=new qR(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new Kz({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(Y.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(Y.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new sB({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(Y.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(Y.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let t=e.handle,n=e.bytes;this.engine.sendDataTrackFrame(n).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(t))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new _B(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>this.engine?.serverVersion),this.rpcClientManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,yL.RELIABLE)}),this.rpcServerManager=new vB(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,yL.RELIABLE)}),this.disconnectLock=new JT,this.localParticipant=new DB(``,``,this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,SP(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,SP(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,SP(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),nP()){let t=new AbortController,n;if(e.cleanupRegistry){let r=new WeakRef(this);n=()=>{let e=r.deref();e&&e.handleDeviceChange()},e.cleanupRegistry.register(this,()=>{t.abort()})}else n=this.handleDeviceChange;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,n,{signal:t.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return J(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error(`e2ee not configured, please set e2ee settings within the room options`)}finally{t()}})}setupE2EE(){var e,t;let n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&(`e2eeManager`in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new EF(r,n),this.e2eeManager.on(iF.ParticipantEncryptionStatusChanged,(e,t)=>{RP(t)&&(this.isE2EEEnabled=e),this.emit(Y.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(iF.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(Y.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this),(t=this.e2eeManager)==null||t.setupEngine(this.engine))}setupFrameMetadata(){let e=this.options.frameMetadata??this.options.packetTrailer;this.frameMetadataManager=new kF(e),this.frameMetadataManager.setup(this)}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant?.identity,participantID:this.localParticipant?.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===MB.Disconnected?xM.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?xM.resolve(this.roomInfo.sid):new xM((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(Z.RoomUpdate,n),e(t.sid))};this.engine.on(Z.RoomUpdate,n),this.once(Y.Disconnected,()=>{this.engine.off(Z.RoomUpdate,n),t(new IM(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){(!this.engine||!this.engine.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new hR(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Z.ParticipantUpdate,this.handleParticipantUpdates).on(Z.RoomUpdate,this.handleRoomUpdate).on(Z.SpeakersChanged,this.handleSpeakersChanged).on(Z.StreamStateChanged,this.handleStreamStateUpdate).on(Z.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Z.SubscriptionError,this.handleSubscriptionError).on(Z.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Z.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(Z.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Z.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Z.DataPacketReceived,this.handleDataPacket).on(Z.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug(`Resuming signal connection`),this.setAndEmitConnectionState(MB.SignalReconnecting)&&this.emit(Y.SignalReconnecting)}).on(Z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug(`Resumed signal connection`),this.updateSubscriptions(),this.setAndEmitConnectionState(MB.Connected)&&this.emit(Y.Reconnected),this.emitBufferedEvents()}).on(Z.SignalResumed,()=>{(this.state===MB.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(Z.Restarting,this.handleRestarting).on(Z.Restarted,this.handleRestarted).on(Z.SignalRestarted,this.handleSignalRestarted).on(Z.Offline,()=>{this.setAndEmitConnectionState(MB.Reconnecting)&&this.emit(Y.Reconnecting)}).on(Z.DCBufferStatusChanged,(e,t)=>{this.emit(Y.DCBufferStatusChanged,e,t)}).on(Z.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(Z.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Y.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(Z.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==kO.NONE}})}).on(Z.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(Z.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let t=K(e,2),n=t[0],r=t[1];return[parseInt(n,10),r.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(Z.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(Z.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>GF.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(Z.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)==null||t.updateToken(e)}).on(Z.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:vR})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>J(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>this.regionUrlProvider?.resetAttempts()}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return PF.getInstance().getDevices(e,t)}prepareConnection(e,t){return J(this,void 0,void 0,function*(){if(this.state===MB.Disconnected){this.log.debug(`prepareConnection to ${e}`);try{if(iP(new URL(e))&&t){this.regionUrlProvider=new bR(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===MB.Disconnected&&(this.regionUrl=n,yield fetch(wP(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`))}else yield fetch(wP(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,{error:e})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return J(this,void 0,void 0,function*(){let n=()=>J(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`fail-on-v1-path`:this.engine.failNextV1Path();break;case`speaker`:r=new xA({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new xA({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new xA({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new xA({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>J(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new xA({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>J(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new xA({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new xA({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>J(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new $k({reason:_O.CLIENT_INITIATED,action:eA.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new xA({scenario:{case:`subscriberBandwidth`,value:kP(t)}});break;case`leave-full-reconnect`:r=new xA({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===$.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===$.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!GN()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield PF.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(Y.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(X.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(X.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(X.AttributesChanged,this.onLocalAttributesChanged).on(X.TrackMuted,this.onLocalTrackMuted).on(X.TrackUnmuted,this.onLocalTrackUnmuted).on(X.LocalTrackPublished,this.onLocalTrackPublished).on(X.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(X.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(X.MediaDevicesError,this.onMediaDevicesError).on(X.AudioStreamAcquired,this.startAudio).on(X.ChatMessage,this.onLocalChatMessageSent).on(X.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if([MB.Connecting,MB.Reconnecting].includes(this.state)){let r=GP(e,t);this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)});let i=()=>{a(),this.onTrackAdded(e,t,n)},a=()=>{if(this.off(Y.Reconnected,i),this.off(Y.Connected,i),this.off(Y.Disconnected,a),r){let e=this.pendingTrackAddedCallbacks.get(r);e?.delete(a),e?.size===0&&this.pendingTrackAddedCallbacks.delete(r)}};if(this.once(Y.Reconnected,i),this.once(Y.Connected,i),this.once(Y.Disconnected,a),r){let e=this.pendingTrackAddedCallbacks.get(r)??new Set;e.add(a),this.pendingTrackAddedCallbacks.set(r,e)}return}if(this.state===MB.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`);return}if(e.readyState===`ended`){this.log.debug(`skipping incoming track as it already ended`);return}let r=NN(t.id),i=r[0],a=r[1],o=GP(e,t)??e.id;if(i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,{remoteParticipantID:i,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(Y.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))==null||t.forEach(e=>e())}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(t=>t.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug(`deferring LocalTrackSubscribed, publication not yet available`,{subscribedSid:e});let r,i=t=>{t.trackSid===e&&(a(),this.emitLocalTrackSubscribed(t))},a=()=>{clearTimeout(r),this.localParticipant.off(X.LocalTrackPublished,i),this.off(Y.Disconnected,a)};this.localParticipant.on(X.LocalTrackPublished,i),this.once(Y.Disconnected,a),r=setTimeout(()=>{a();let n=t();n?this.emitLocalTrackSubscribed(n):this.log.warn(`could not find local track publication for LocalTrackSubscribed event after timeout`,{subscribedSid:e})},1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(X.LocalTrackSubscribed,e),this.emitWhenConnected(Y.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==MB.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(X.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(X.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(X.AttributesChanged,this.onLocalAttributesChanged).off(X.TrackMuted,this.onLocalTrackMuted).off(X.TrackUnmuted,this.onLocalTrackUnmuted).off(X.LocalTrackPublished,this.onLocalTrackPublished).off(X.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(X.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(X.MediaDevicesError,this.onMediaDevicesError).off(X.AudioStreamAcquired,this.startAudio).off(X.ChatMessage,this.onLocalChatMessageSent).off(X.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),nP()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(MB.Disconnected),this.emit(Y.Disconnected,t)}}}handleParticipantDisconnected(e,t,n){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Y.ParticipantDisconnected,t,n),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return J(this,void 0,void 0,function*(){let e=PF.getInstance().previousDevices,t=yield PF.getInstance().getDevices(void 0,!1),n=wM();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)==="default"&&this.emit(Y.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=mN(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!ZN()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!ZN())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return J(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=pN()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),PN(200)])}catch(e){this.log.warn(`Could not resume audio context`,{error:e})}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(Y.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?jB.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new jB(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Y.ParticipantConnected,n),n.on(X.TrackPublished,e=>{this.emitWhenConnected(Y.TrackPublished,e,n)}).on(X.TrackSubscribed,(e,t)=>{e.kind===$.Kind.Audio?(e.on(Q.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Q.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===$.Kind.Video&&(e.on(Q.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Q.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(Y.TrackSubscribed,e,t,n)}).on(X.TrackUnpublished,e=>{this.cancelPendingTrackAdded(e.trackSid),this.emit(Y.TrackUnpublished,e,n)}).on(X.TrackUnsubscribed,(e,t)=>{this.emit(Y.TrackUnsubscribed,e,t,n)}).on(X.TrackMuted,e=>{this.emitWhenConnected(Y.TrackMuted,e,n)}).on(X.TrackUnmuted,e=>{this.emitWhenConnected(Y.TrackUnmuted,e,n)}).on(X.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Y.ParticipantMetadataChanged,e,n)}).on(X.ParticipantNameChanged,e=>{this.emitWhenConnected(Y.ParticipantNameChanged,e,n)}).on(X.AttributesChanged,e=>{this.emitWhenConnected(Y.ParticipantAttributesChanged,e,n)}).on(X.ConnectionQualityChanged,e=>{this.emitWhenConnected(Y.ConnectionQualityChanged,e,n)}).on(X.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Y.ParticipantPermissionsChanged,e,n)}).on(X.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Y.TrackSubscriptionStatusChanged,e,t,n)}).on(X.TrackSubscriptionFailed,(e,t)=>{this.emit(Y.TrackSubscriptionFailed,e,n,t)}).on(X.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Y.TrackSubscriptionPermissionChanged,e,t,n)}).on(X.Active,()=>{this.emitWhenConnected(Y.ParticipantActive,n),n.kind===DO.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&IP(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){let t=[];return(pF(e.frameMetadata??e.packetTrailer)||this.e2eeManager)&&t.push(lk.CAP_PACKET_TRAILER),UP()&&t.push(lk.CAP_COMPRESSION_DEFLATE_RAW),t}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(uB,(e,t)=>J(this,[e,t],void 0,function(e,t){var n=this;let r=t.identity;return function*(){let t=e.info.attributes??{};yield n.rpcServerManager.handleIncomingDataStream(e,r,t)}()})),this.incomingDataStreamManager.registerTextStreamHandler(dB,(e,t)=>J(this,[e,t],void 0,function(e,t){var n=this;let r=t.identity;return function*(){let t=e.info.attributes??{};yield n.rpcClientManager.handleIncomingDataStream(e,r,t)}()}))}setStatsLogging(e){e?this.statsLogInterval||=GM.setInterval(()=>{this.logWebRTCStats()},PB):this.statsLogInterval&&=(GM.clearInterval(this.statsLogInterval),void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=GM.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn(`detected connection state mismatch, attempting full reconnect`),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,_O.STATE_MISMATCH)))):e=0},NB)}clearConnectionReconcile(){this.connectionReconcileInterval&&GM.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info(`connection state changed: ${this.state} -> ${e}`),this.state=e,this.incomingDataStreamManager.setConnected(e===MB.Connected),this.setStatsLogging(e===MB.Connected),this.emit(Y.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=K(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===MB.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===MB.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return J(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new SO({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:TE.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new TO({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected),this.emit(Y.Connected),this.setAndEmitConnectionState(MB.Connected),t.video){let e=new xB($.Kind.Video,new jO({source:pO.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:fO.AUDIO,name:`video-dummy`}),new rR(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:_P(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(X.LocalTrackPublished,e)}if(t.audio){let e=new xB($.Kind.Audio,new jO({source:pO.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:fO.AUDIO}),new LL(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:yP(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(X.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new TO({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:EO.ACTIVE,tracks:[],joinedAt:TE.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=_P(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new jO({source:pO.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:fO.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=yP(),n=new jO({source:pO.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:fO.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==Y.ActiveSpeakersChanged&&e!==Y.TranscriptionReceived){let n=IB(t).filter(e=>e!==void 0);(e===Y.TrackSubscribed||e===Y.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,{event:e,args:n}),this.log.debug(`room event ${e}`,{event:e,args:n})}return super.emit(e,...t)}};FB.cleanupRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});function IB(e){return e.map(e=>{if(e)return Array.isArray(e)?IB(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var LB;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(LB||={}),cj.EventEmitter,cj.EventEmitter,new TextEncoder,new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});var RB=class extends Error{constructor(e,t){var n;super(e,t),NE(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};NE(RB,`code`,`ERR_JOSE_GENERIC`),NE(class extends RB{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),NE(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),NE(this,`claim`,void 0),NE(this,`reason`,void 0),NE(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),NE(class extends RB{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),NE(this,`code`,`ERR_JWT_EXPIRED`),NE(this,`claim`,void 0),NE(this,`reason`,void 0),NE(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),NE(class extends RB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),NE(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),NE(class extends RB{constructor(){super(...arguments),NE(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),NE(class extends RB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),NE(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),NE(class extends RB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),NE(this,Symbol.asyncIterator,GE(function*(){})),NE(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),NE(class extends RB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),NE(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),NE(class extends RB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),NE(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);var zB=new Set;function BB(e){zB.add(e)}function VB(e){return zB.has(e)}var HB=z({server_url:P(),participant_token:P(),call:P()});function UB(e){let t=j(),[n,r]=(0,D.useState)(`idle`),[i,a]=(0,D.useState)(`talk`),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(null),[f,p]=(0,D.useState)([]),[m,h]=(0,D.useState)(null),g=(0,D.useRef)(null),_=(0,D.useRef)(new Set),v=(0,D.useRef)(null),y=(0,D.useRef)([]),b=(0,D.useRef)(null),x=(0,D.useCallback)(()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null);let e=y.current;y.current=[],e.length>0&&p(t=>[...t,...e])},[]),S=(0,D.useCallback)(e=>{if(!_.current.has(e.id)){_.current.add(e.id),e.speaker===`user`&&x(),p(t=>FT(t,e)),v.current=e.speaker,e.speaker===`agent`&&x();return}p(t=>FT(t,e))},[x]),C=(0,D.useRef)(0),w=(0,D.useCallback)(async e=>{let t=g.current;if(t===null)return;C.current+=1;let n=`typed-${C.current}`;x(),p(t=>[...t,{kind:`said`,id:n,speaker:`user`,text:e,final:!0,pending:!0}]),v.current=`user`;try{await t.localParticipant.sendText(e,{topic:AT})}catch(e){p(e=>e.filter(e=>e.id!==n)),h(e instanceof Error?e.message:String(e))}},[x]),T=(0,D.useCallback)(e=>{if(e.type===`turn.user`){let t=String(e.data.text??``).trim();p(e=>{let n=e.findIndex(e=>e.kind===`said`&&e.pending===!0&&e.text.trim()===t);if(n===-1)return e;let r=e.slice();return r[n]={...e[n],pending:!1},r});return}let t=LT(e);if(t!==null){if(v.current===`agent`){p(e=>[...e,t]);return}y.current.push(t),b.current!==null&&window.clearTimeout(b.current),b.current=window.setTimeout(x,jT)}},[x]),ee=(0,D.useCallback)(async n=>{r(`connecting`),a(n),l(!1),s(null),h(null),p([]),_.current.clear(),v.current=null,y.current=[];try{let i=HB.parse(await sa(t,`/v1/tokens`,{agent:e,scope:n})),a=new FB;g.current=a,a.registerTextStreamHandler(OT,(e,t)=>{WB(a,e,t.identity,S)}),n===`talk`&&a.on(Y.TrackSubscribed,GB),a.on(Y.TrackUnsubscribed,e=>e.detach().forEach(e=>e.remove())),a.on(Y.Disconnected,()=>r(`ended`)),BB(i.call),d(i.call),await a.connect(i.server_url,i.participant_token),n===`talk`&&await a.localParticipant.setMicrophoneEnabled(!0),s(Date.now()/1e3),r(`live`)}catch(e){h(e instanceof Error?e.message:String(e)),r(`failed`)}},[e,t,S]),te=(0,D.useCallback)(async()=>{await g.current?.disconnect()},[]),ne=(0,D.useCallback)(async()=>{let e=g.current;e!==null&&(await e.localParticipant.setMicrophoneEnabled(c),l(!c))},[c]);return(0,D.useEffect)(()=>()=>{g.current?.disconnect()},[]),{phase:n,mode:i,call:u,lines:f,error:m,since:o,muted:c,open:ee,close:te,toggleMic:ne,write:w,heard:T}}async function WB(e,t,n,r){let i=t.info.attributes?.[`lk.segment_id`]??t.info.id,a=e.remoteParticipants.get(n)?.kind===DO.AGENT?`agent`:`user`,o=``;for await(let e of t)o+=e,r({kind:`said`,id:i,speaker:a,text:o,final:!1});r({kind:`said`,id:i,speaker:a,text:o,final:t.info.attributes?.[kT]===`true`})}function GB(e){if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.style.display=`none`,document.body.append(t)}function KB(){let e=Sr().agent??``,t=UB(e),n=wh(),{world:r}=kh(),i=t.phase===`live`||t.phase===`connecting`,a=vh({name:`agent.inspector`,initial:330,min:260,max:620,side:`right`}),o=n?.name??n?.label??`this key`;return(0,A.jsxs)(`div`,{className:`talk-grid`,style:a.style,children:[a.handle,(0,A.jsxs)(sh,{width:760,children:[(0,A.jsx)(ch,{title:`Talk to ${e}`,lede:`This machine's microphone reaches the agent, and it answers out loud. You can write into the same call too — a number, an address, a name nobody spells out loud.`}),(0,A.jsxs)(`div`,{className:`talk-card`,children:[(0,A.jsx)(qB,{live:t}),(0,A.jsxs)(`div`,{className:`talk-standing`,children:[(0,A.jsx)(`div`,{className:`talk-phase`,children:YB(t)}),(0,A.jsx)(`div`,{className:`talk-hint`,children:XB(t)})]}),t.phase===`live`&&(0,A.jsxs)(`div`,{className:`talk-mic`,children:[(0,A.jsxs)(`span`,{className:t.muted?`talk-bars`:`talk-bars talk-bars-on`,"aria-hidden":!0,children:[(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{})]}),(0,A.jsx)(U,{size:`sm`,onClick:()=>void t.toggleMic(),children:t.muted?`Unmute`:`Mute`})]}),t.phase===`ended`&&t.call!==null&&(0,A.jsx)(zm,{size:`sm`,to:`/a/${e}/sessions/${t.call}`,children:`Open the session`}),i&&t.call!==null&&(0,A.jsx)(`div`,{className:`talk-call`,children:t.call})]}),(0,A.jsxs)(`div`,{className:`talk-facts`,children:[(0,A.jsxs)(`div`,{className:`talk-fact`,children:[(0,A.jsx)(`div`,{className:`talk-fact-label`,children:`Speaking as`}),(0,A.jsxs)(`div`,{className:`talk-fact-value`,children:[o,` · you`]})]}),(0,A.jsxs)(`div`,{className:`talk-fact`,children:[(0,A.jsx)(`div`,{className:`talk-fact-label`,children:`Lands in`}),(0,A.jsxs)(`div`,{className:`talk-fact-value`,children:[r,` · counts in usage`]})]})]}),(0,A.jsx)(Nm,{children:t.error}),(0,A.jsx)(BT,{lines:i?t.lines:[],mode:`talk`,children:(0,A.jsx)(UT,{open:t.phase===`live`,mode:`talk`,onWrite:t.write})}),t.call!==null&&(0,A.jsx)(JB,{call:t.call,heard:t.heard})]}),(0,A.jsx)(iw,{agent:e,call:t.call})]})}function qB({live:e}){let t=ZB(e.phase===`live`);return e.phase===`live`||e.phase===`connecting`?(0,A.jsxs)(`button`,{type:`button`,className:`talk-door talk-door-on`,disabled:e.phase===`connecting`,onClick:()=>void e.close(),children:[(0,A.jsx)(`span`,{children:`Hang up`}),e.phase===`live`&&(0,A.jsx)(`span`,{className:`talk-door-clock`,children:Jh(e.since,t)})]}):(0,A.jsx)(`button`,{type:`button`,className:`talk-door`,onClick:()=>void e.open(`talk`),children:`Call`})}function JB({call:e,heard:t}){return ew(e,{onEntry:t}),null}function YB(e){switch(e.phase){case`idle`:return`Ready — press Call`;case`connecting`:return`Joining the room…`;case`live`:return e.muted?`On the call — muted`:`On the call — speak or write`;case`ended`:return`The call ended`;case`failed`:return`The room did not open`}}function XB(e){switch(e.phase){case`idle`:return`The browser asks for the microphone, and the agent answers straight away.`;case`connecting`:return`The microphone opens as soon as the room does.`;case`live`:return`Everything said lands in the log beside you.`;case`ended`:return`Judged at hang-up. Press the button to call again.`;case`failed`:return`Nothing reached the agent. The reason is under the facts.`}}function ZB(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}function QB(){let e=Sr().agent??``,t=UB(e),{world:n}=kh(),r=t.phase===`live`||t.phase===`connecting`,i=vh({name:`agent.inspector`,initial:330,min:260,max:620,side:`right`}),a=(0,D.useRef)(``);return(0,D.useEffect)(()=>{e!==``&&a.current!==e&&(a.current=e,t.open(`chat`))},[e,t]),(0,A.jsxs)(`div`,{className:`rchat-grid`,style:i.style,children:[i.handle,(0,A.jsx)(`div`,{className:`rchat-stage`,children:(0,A.jsxs)(`section`,{className:`rchat`,"aria-label":`Chat with ${e}`,children:[(0,A.jsx)($B,{agent:e,live:t,world:n}),r||t.lines.length>0?(0,A.jsx)(BT,{lines:t.lines,mode:`chat`}):(0,A.jsx)(eV,{agent:e,live:t}),t.error!==null&&(0,A.jsx)(`p`,{className:`rchat-refused`,children:t.error}),(0,A.jsx)(UT,{open:t.phase===`live`,mode:`chat`,onWrite:t.write}),t.call!==null&&(0,A.jsx)(nV,{call:t.call,heard:t.heard})]})}),(0,A.jsx)(iw,{agent:e,call:t.call})]})}function $B({agent:e,live:t,world:n}){let r=rV(t.phase===`live`);return(0,A.jsxs)(`header`,{className:`rchat-bar`,children:[(0,A.jsx)(`span`,{className:t.phase===`live`?`rchat-light rchat-light-on`:`rchat-light`,"aria-hidden":!0}),(0,A.jsxs)(`div`,{className:`rchat-words`,children:[(0,A.jsxs)(`div`,{className:`rchat-title`,children:[`Chat with `,e]}),(0,A.jsx)(`div`,{className:`rchat-standing`,children:tV(t,r,n)})]}),(0,A.jsxs)(`div`,{className:`rchat-moves`,children:[t.phase===`ended`&&t.call!==null&&(0,A.jsx)(zm,{size:`sm`,to:`/a/${e}/sessions/${t.call}`,children:`Open the session`}),t.phase===`live`||t.phase===`connecting`?(0,A.jsx)(U,{kind:`danger`,size:`sm`,disabled:t.phase===`connecting`,onClick:()=>void t.close(),children:`End chat`}):(0,A.jsx)(U,{kind:`primary`,size:`sm`,onClick:()=>void t.open(`chat`),children:t.lines.length===0?`Start a chat`:`Start another`})]})]})}function eV({agent:e,live:t}){return(0,A.jsxs)(`div`,{className:`rchat-empty`,children:[(0,A.jsx)(`p`,{className:`rchat-empty-words`,children:t.phase===`connecting`?`Opening a written room with ${e}…`:`Write to ${e} as a visitor would. No microphone and no voice: the agent answers in writing, with the same tools, memory and knowledge, and the call is judged at hang-up like any other.`}),t.phase===`failed`&&(0,A.jsx)(`p`,{className:`rchat-empty-failed`,children:`The room did not open. The reason is below.`})]})}function tV(e,t,n){switch(e.phase){case`idle`:return`Not started — it lands in ${n} and counts in usage`;case`connecting`:return`Opening the room…`;case`live`:return`Chatting · ${Jh(e.since,t)}`;case`ended`:return`The chat ended — judged at hang-up, in Sessions`;case`failed`:return`The room did not open`}}function nV({call:e,heard:t}){return ew(e,{onEntry:t}),null}function rV(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}async function iV(e,t,n){if(n<=0)return null;let r=Bv.parse(await k(e,`/v1/calls/${encodeURIComponent(t)}/events`,{after:n-1,types:Fv,limit:1})).entries.find(e=>e.type===Fv);return r===void 0?null:Y_.parse(r.data)}var aV=20;function oV(e){let t=j(),n=(0,D.useRef)(new Map),[r,i]=(0,D.useState)(n.current),a=e.filter(e=>!BS(e)).slice(0,aV),o=a.map(e=>`${e.call}@${e.last_seq}`).join(` `);return(0,D.useEffect)(()=>{let e=!1,r=a.filter(e=>!n.current.has(e.call));return(async()=>{let a=await Promise.all(r.map(e=>sV(t,e)));if(!(e||a.length===0)){for(let e of a)n.current.set(e.line.call,e);i(new Map(n.current))}})(),()=>{e=!0}},[o,t]),a.map(e=>r.get(e.call)??cV(e))}async function sV(e,t){try{return{line:t,read:!0,score:await iV(e,t.call,t.last_seq),refused:null}}catch(e){return{line:t,read:!0,score:null,refused:String(e)}}}function cV(e){return{line:e,read:!1,score:null,refused:null}}function lV(e){let{lines:t,error:n}=zS(e);return{rows:oV(t),error:n}}function uV({call:e}){let t=j(),n=Sr().agent??``,[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),d=async r=>{i(r),u(null);try{r===`check`?o(await nT(t,e)):c(await iT(t,n,e))}catch(e){u(e instanceof na?e.message:String(e))}finally{i(``)}};return(0,A.jsxs)(`div`,{className:`ev-acts`,children:[(0,A.jsxs)(`div`,{className:`ev-acts-buttons`,children:[(0,A.jsx)(U,{size:`md`,disabled:r!==``,onClick:()=>void d(`check`),children:r===`check`?`Checking…`:`Re-check by code`}),(0,A.jsx)(U,{size:`md`,disabled:r!==``,onClick:()=>void d(`promote`),children:r===`promote`?`Writing…`:`Promote to a golden`})]}),a!==null&&(0,A.jsx)(`div`,{className:`ui-tags`,children:a.verdicts.map(e=>(0,A.jsx)(`span`,{title:e.detail,children:(0,A.jsxs)(Qm,{tone:e.status===`passed`?`green`:e.status===`failed`?`red`:`muted`,children:[e.check,` `,e.status]})},e.check))}),s!==null&&(0,A.jsxs)(`div`,{className:`ui-note`,children:[`Written to `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:s.path}),` · `,s.candidate.input.length,` caller turn(s)`,s.notes.map(e=>(0,A.jsx)(`div`,{children:e},e))]}),(0,A.jsx)(Nm,{children:l})]})}var dV=`minmax(0,1.2fr) 120px 104px minmax(0,1.7fr) 70px 84px`;function fV({agent:e,rows:t}){let[n,r]=(0,D.useState)(null);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:dV,labels:[`Call`,`Started`,`Verdict`,`Judges`,`Calls>`,`Cost>`]}),t.map(t=>(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:t.line.call===n?`ui-table-row ui-table-row-link ev-row-open`:`ui-table-row ui-table-row-link`,style:{gridTemplateColumns:dV},onClick:()=>r(t.line.call===n?null:t.line.call),children:[(0,A.jsx)(`span`,{className:`ui-cell-link ui-clip`,children:t.line.call}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:Qh(t.line.started_at)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(pV,{row:t})}),(0,A.jsx)(`span`,{className:`ui-tags`,children:t.score?.judges.map(e=>(0,A.jsx)(`span`,{className:e.verdict===`held`?`ev-judge`:`ev-judge ev-judge-bad`,children:e.name},e.name))}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:t.score?.judge_calls??`—`}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:Yh(t.score?.judge_cost_eur)})]}),t.line.call===n&&(0,A.jsx)(mV,{agent:e,row:t})]},t.line.call))]})}function pV({row:e}){return e.read?e.refused===null?e.score?.passed==null?(0,A.jsx)(Qm,{tone:`muted`,children:`not judged`}):e.score.passed?(0,A.jsx)(Qm,{tone:`green`,children:`passed`}):(0,A.jsx)(Qm,{tone:`red`,children:`did not pass`}):(0,A.jsx)(`span`,{title:e.refused,children:(0,A.jsx)(Qm,{tone:`red`,children:`unreadable`})}):(0,A.jsx)(Qm,{tone:`muted`,children:`reading…`})}function mV({agent:e,row:t}){let n=t.score;return(0,A.jsxs)(`div`,{className:`ev-evidence`,children:[(0,A.jsx)(`div`,{className:`ev-evidence-head`,children:(0,A.jsx)(Wi,{className:`ui-cell-link`,to:`/a/${e}/sessions/${t.line.call}`,children:`Open the session`})}),(0,A.jsx)(uV,{call:t.line.call}),n===null&&(0,A.jsx)(`div`,{className:`ui-note`,children:`This call's log carries no verdict.`}),n?.not_judged!=null&&(0,A.jsx)(`div`,{className:`ev-warn`,children:n.not_judged}),n!==null&&(0,A.jsx)(hV,{score:n}),n?.judges.filter(e=>e.verdict!==`held`).map(n=>(0,A.jsx)(gV,{agent:e,call:t.line.call,judgment:n},n.name)),n!==null&&n.judges.length>0&&n.judges.every(e=>e.verdict===`held`)&&(0,A.jsxs)(`div`,{className:`ui-note`,children:[`Every judge on the panel held: `,n.judges.map(e=>e.name).join(`, `),`.`]})]})}function hV({score:e}){let t=new Set(e.judges.map(e=>e.name)),n=(e.panel??[]).filter(e=>!t.has(e));return n.length===0?null:(0,A.jsxs)(`div`,{className:`ev-warn`,children:[n.join(`, `),` was run over this call and answered nothing; the panel was `,e.panel?.join(`, `),`.`]})}function gV({agent:e,call:t,judgment:n}){let r=n.evidence.seqs;return(0,A.jsxs)(`div`,{className:`ev-said`,children:[(0,A.jsxs)(Im,{children:[n.name,` · `,n.verdict]}),(0,A.jsxs)(`div`,{className:`ev-said-body`,children:[(0,A.jsx)(`div`,{className:`ev-reason`,children:n.reason}),(0,A.jsx)(`div`,{className:`ui-cell-faint`,children:n.criteria}),n.evidence.said!=null&&(0,A.jsxs)(`div`,{className:`ev-quote`,children:[`“`,n.evidence.said,`”`]}),r.length>0&&(0,A.jsx)(`div`,{className:`ui-tags`,children:r.map(n=>(0,A.jsxs)(Wi,{className:`ui-tag`,to:`/a/${e}/sessions/${t}#seq-${n}`,children:[`seq `,n]},n))})]})]})}var _V=86400,vV=7,yV=30,bV=`minmax(0,1fr) 150px 150px 90px`;function xV({agent:e}){let t=j(),[n,r]=(0,D.useState)(vV),[i,a]=(0,D.useState)(yV),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!0),[u,d]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let r=!1;return l(!0),$w(t,e,n*_V,i*_V).then(e=>{r||(s(e),l(!1))},e=>{r||(d(e instanceof na?e.message:String(e)),l(!1))}),()=>{r=!0}},[t,e,n,i]),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Drift`,meta:c?`reading…`:`held-rate per judge, over two windows`,children:(0,A.jsxs)(`span`,{className:`ev-drift-windows`,children:[(0,A.jsxs)(`label`,{className:`ev-drift-field`,children:[(0,A.jsx)(`span`,{children:`now, days`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:365,value:n,onChange:e=>r(Number(e.target.value))})]}),(0,A.jsxs)(`label`,{className:`ev-drift-field`,children:[(0,A.jsx)(`span`,{children:`against the last`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:365,value:i,onChange:e=>a(Number(e.target.value))})]})]})}),(0,A.jsx)(Nm,{children:u}),o!==null&&o.drift.judges.length===0&&(0,A.jsx)(Mm,{children:`No finished call of this agent carries a verdict in either window.`}),o!==null&&o.drift.judges.length>0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:bV,labels:[`Judge`,`Before>`,`Now>`,`Points>`]}),o.drift.judges.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:bV},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.judge}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:SV(e,`before`)}),(0,A.jsx)(`span`,{className:`ev-num`,children:SV(e,`now`)}),(0,A.jsx)(`span`,{className:CV(e,o.threshold)?`ev-num ev-num-bad`:`ev-num ev-num-faint`,children:e.delta===null?`—`:`${e.delta>0?`+`:``}${e.delta.toFixed(0)}`})]},e.judge)),(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[o.drift.notJudged.now,` call`,o.drift.notJudged.now===1?``:`s`,` in this window carried no verdict at all (`,o.drift.notJudged.before,` before it). A judge may fall `,o.threshold.toFixed(0)," points before `pinecall runs drift` fails the night."]}),o.drift.broke.map(t=>(0,A.jsxs)(`div`,{className:`ev-broke`,children:[(0,A.jsx)(Wi,{className:`ui-cell-link ui-clip`,to:`/a/${e}/sessions/${t.call}`,children:t.call}),(0,A.jsx)(`span`,{className:`ev-judge ev-judge-bad`,children:t.judge}),(0,A.jsx)(`span`,{className:`ev-reason`,children:t.reason})]},`${t.call}-${t.judge}`))]})]})}function SV(e,t){let n=e[t];return n===null?`—`:`${n.percent.toFixed(0)}% · ${n.held}/${n.settled}`}function CV(e,t){return e.delta!==null&&e.delta<-Math.abs(t)}var wV=` · `;function TV(e,t,n){return[t,e,n].join(wV)}function EV(e){if(e===null)return{held:0,judgments:0};let t=e.runs.flatMap(e=>e.scores);return{held:t.filter(e=>e.passed).length,judgments:t.length}}function DV(e,t){if(t?.matrix==null||e.matrix===null)return null;let n=OV(t.matrix),r=OV(e.matrix),i=[...r.keys()].filter(e=>n.has(e));return{broke:i.filter(e=>n.get(e)===!0&&r.get(e)===!1),recovered:i.filter(e=>n.get(e)===!1&&r.get(e)===!0)}}function OV(e){let t=new Map;for(let n of e.runs)for(let e of n.scores)t.set(TV(n.model,n.golden,e.metric),e.passed);return t}function kV({run:e}){let t=j(),n=Sr().agent??``,[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);if((0,D.useEffect)(()=>{let r=!1;return c(null),u(null),sT(t,n,e).then(e=>{r||(i(e.goldens),o(e.folder))},()=>{r||i([])}),()=>{r=!0}},[t,n,e]),r===null||r.length===0)return null;let d=async r=>{u(null);try{c(await cT(t,n,e,r))}catch(e){u(e instanceof na?e.message:String(e))}};return(0,A.jsxs)(`div`,{className:`ev-repro`,children:[(0,A.jsx)(Im,{ruled:!0,children:`Reproductions`}),(0,A.jsxs)(`div`,{className:`ev-repro-body`,children:[(0,A.jsxs)(`div`,{className:`ui-note`,children:[r.length,` in `,(0,A.jsxs)(`span`,{className:`ui-fixed`,children:[a,`/`]}),` — the golden as written, every verdict on it, and the requests the model answered.`]}),(0,A.jsx)(`div`,{className:`ui-chips`,children:r.map(e=>(0,A.jsx)(`button`,{type:`button`,className:s?.golden===e?`ui-chip ui-chip-on`:`ui-chip`,onClick:()=>void d(e),children:e},e))}),(0,A.jsx)(Nm,{children:l}),s!==null&&(0,A.jsxs)(`div`,{className:`ev-repro-open`,children:[(0,A.jsxs)(`div`,{className:`ev-repro-title`,children:[s.golden,` · `,s.model,` `,(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:s.call})]}),s.verdicts.filter(e=>!e.passed).map(e=>(0,A.jsxs)(`div`,{className:`ev-repro-verdict`,children:[(0,A.jsx)(Qm,{tone:`red`,small:!0,children:e.metric}),(0,A.jsx)(`span`,{className:`ev-reason`,children:e.reason})]},e.metric)),(0,A.jsx)(`pre`,{className:`ui-code ev-asked`,children:JSON.stringify(s.asked,null,2)})]})]})]})}var AV=`minmax(0,1.1fr) 120px 84px 70px 80px minmax(0,1.6fr)`,jV={done:`green`,running:`amber`,failed:`red`};function MV({runs:e,selected:t,onSelect:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:AV,labels:[`Run`,`Started`,`Status`,`Held>`,`Judge calls>`,`Since the run before`]}),e.map((r,i)=>{let a=EV(r.matrix),o=r.id===t;return(0,A.jsxs)(`div`,{className:o?`ui-table-row ui-table-row-link ev-row-open`:`ui-table-row ui-table-row-link`,style:{gridTemplateColumns:AV},onClick:()=>n(r.id),children:[(0,A.jsx)(`span`,{className:`ui-cell-link ui-clip`,children:r.id}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:Qh(r.started_at)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:jV[r.status],children:r.status})}),(0,A.jsx)(`span`,{className:a.judgments>0&&a.held<a.judgments?`ev-num ev-num-bad`:`ev-num`,children:a.judgments===0?`—`:`${a.held}/${a.judgments}`}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:r.matrix?.judge_calls??`—`}),(0,A.jsx)(NV,{delta:DV(r,e[i+1])})]},r.id)})]})}function NV({delta:e}){return e===null?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`first of its kind`}):e.broke.length===0&&e.recovered.length===0?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`±0`}):(0,A.jsxs)(`span`,{className:`ui-tags`,children:[e.broke.map(e=>(0,A.jsxs)(Qm,{tone:`red`,small:!0,children:[`broke · `,e]},`broke-${e}`)),e.recovered.map(e=>(0,A.jsxs)(Qm,{tone:`green`,small:!0,children:[`held again · `,e]},`held-${e}`))]})}var PV=`minmax(0,1.1fr) minmax(0,.8fr) 110px 120px 84px minmax(0,1.6fr)`,FV={done:`green`,running:`amber`,failed:`red`};function IV({run:e,before:t}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:e.id,meta:`${e.agent} · ${e.matrix?.judge_calls??0} judge calls`,children:(0,A.jsx)(`span`,{className:`ev-head-end`,children:(0,A.jsx)(Qm,{tone:FV[e.status],children:e.status})})}),(0,A.jsxs)(`div`,{className:`ev-facts`,children:[(0,A.jsx)(Lm,{label:`Started`,children:Qh(e.started_at)}),(0,A.jsx)(Lm,{label:`Finished`,children:Qh(e.finished_at)}),e.error!==null&&(0,A.jsx)(Lm,{label:`Error`,children:e.error}),(0,A.jsx)(Lm,{label:`Since before`,children:(0,A.jsx)(NV,{delta:DV(e,t)})})]}),e.matrix===null?(0,A.jsx)(Mm,{children:`No matrix yet — the run is still opening its calls, or it failed before a judge answered.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:PV,labels:[`Golden`,`Model`,`Metric`,`Score`,`Held`,`The judge's own sentence`]}),e.matrix.runs.flatMap(t=>t.scores.map(n=>(0,A.jsx)(LV,{run:e,cell:t,score:n},`${t.golden}/${t.model}/${n.metric}`))),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`A hard policy writes the seqs into its reason on purpose, so the sentence is the way into the log.`})]}),(0,A.jsx)(kV,{run:e.id})]})}function LV({run:e,cell:t,score:n}){let r=e.calls.find(e=>e.golden===t.golden&&e.model===t.model);return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:PV},children:[(0,A.jsxs)(`span`,{className:`ev-golden`,children:[(0,A.jsx)(`span`,{className:`ev-golden-says ui-clip`,children:t.golden}),r!==void 0&&(0,A.jsx)(Wi,{className:`ev-golden-call ui-clip`,to:`/a/${e.agent}/sessions/${r.call}`,children:r.call})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip`,children:t.model}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:n.metric}),(0,A.jsxs)(`span`,{className:`ev-score`,children:[(0,A.jsx)(`span`,{className:`ev-score-value`,children:n.score.toFixed(2)}),(0,A.jsx)(oh,{share:n.score,color:n.passed?`var(--green-dot)`:`var(--red)`,height:5})]}),(0,A.jsx)(`span`,{children:n.passed?(0,A.jsx)(Qm,{tone:`green`,children:`held`}):(0,A.jsx)(Qm,{tone:`red`,children:`did not hold`})}),(0,A.jsx)(`span`,{className:`ev-reason`,title:n.criteria,children:n.reason})]})}var RV=z({name:P(),input:R(P()),expect:fp(P(),Zf())}),zV=z({agent:P().nullable(),goldens:R(RV)}),BV=z({run:P()});async function VV(e,t){return zV.parse(await $S(e,t,`goldens.roster`))}async function HV(e,t){return BV.parse(await $S(e,t.agent,`goldens.run`,t)).run}var UV=15,WV=0;function GV({agent:e,roster:t,onOpened:n}){let r=j(),[i,a]=(0,D.useState)(()=>new Set(t.goldens.map(e=>e.name))),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(UV),[m,h]=(0,D.useState)(WV),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),b=(e,t)=>{let n=new Set(i);t?n.add(e):n.delete(e),a(n)},x=i.size===t.goldens.length,S=async a=>{a.preventDefault(),_(!0),y(null);try{let a=o.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(await HV(r,{agent:e,goldens:t.goldens.map(e=>e.name).filter(e=>i.has(e)),...a.length===0?{}:{models:a},voice:c,...c&&u?{background_noise:f,packet_loss:m/100}:{}}))}catch(e){y(e instanceof na?e.message:String(e))}finally{_(!1)}};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Run a suite`,meta:`through the class in the directory pinecall start runs in, scored by this gateway`}),(0,A.jsxs)(`form`,{onSubmit:e=>void S(e),children:[(0,A.jsxs)(`div`,{className:`ev-suite-controls`,children:[(0,A.jsxs)(`div`,{className:`ev-suite-models`,children:[(0,A.jsx)(Vm,{children:`Models`}),(0,A.jsx)(W,{size:`sm`,value:o,placeholder:`the one the class declared · vendor/model, comma separated`,onChange:e=>s(e.target.value)})]}),(0,A.jsx)(Ym,{checked:c,onChange:l,children:`Voice — ring 2, a real line`}),c&&(0,A.jsx)(Ym,{checked:u,onChange:d,children:`Noisy line`}),c&&u&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ev-suite-number`,children:[(0,A.jsx)(Vm,{children:`Noise, dB under`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:60,value:f,onChange:e=>p(Number(e.target.value))})]}),(0,A.jsxs)(`div`,{className:`ev-suite-number`,children:[(0,A.jsx)(Vm,{children:`Packets lost, %`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:100,value:m,onChange:e=>h(Number(e.target.value))})]})]}),(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,className:`ev-suite-go`,disabled:g||i.size===0,children:g?`Opening…`:`Run ${x?`the suite`:`${i.size} golden${i.size===1?``:`s`}`}`})]}),(0,A.jsx)(`div`,{className:`ev-suite-all`,children:(0,A.jsxs)(Ym,{checked:x,onChange:e=>a(new Set(e?t.goldens.map(e=>e.name):[])),children:[i.size,` of `,t.goldens.length]})}),t.goldens.map(e=>(0,A.jsxs)(`div`,{className:`ev-suite-golden`,children:[(0,A.jsx)(Ym,{checked:i.has(e.name),onChange:t=>b(e.name,t),children:(0,A.jsx)(`span`,{className:`ev-suite-name`,children:e.name})}),(0,A.jsx)(`span`,{className:`ev-suite-says ui-clip`,children:e.input[0]??``}),(0,A.jsx)(`span`,{className:`ev-suite-expects ui-clip`,children:KV(e)})]},e.name))]}),(0,A.jsx)(Nm,{children:v})]})}function KV(e){let t=Object.entries(e.expect).map(([e,t])=>`${e}: ${qV(t)}`);return t.length===0?`consent only`:t.join(` · `)}function qV(e){return Array.isArray(e)?e.map(String).join(`, `):String(e)}var JV=3e3;function YV(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(!0),[o,s]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=await Jw(t,e);n||(r(i),s(null))}catch(e){n||s(String(e))}finally{n||a(!1)}};i();let o=window.setInterval(()=>void i(),JV);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{runs:n,reading:i,error:o}}var XV=`minmax(0,1fr) 110px 90px`;function ZV(e){let t=Object.keys(e.expect);return t.includes(`tools`)||t.includes(`not_tools`)?`tool call`:t.includes(`says`)||t.includes(`not`)?`exact phrase`:t.includes(`grounded`)||t.includes(`register`)?`judge`:t.includes(`replies`)?`a reply`:t.length===0?`consent`:t[0]??`—`}function QV(e){let t=new Map;for(let n of e?.matrix?.runs??[]){let e=n.scores.every(e=>e.passed);t.set(n.golden,(t.get(n.golden)??!0)&&e)}return t}function $V(){let e=Sr().agent??``,t=j(),[n,r]=Xi(),i=YV(e),a=lV(e),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(null),m=fm===`local`;(0,D.useEffect)(()=>{let n=!1;return VV(t,e).then(e=>{n||s(e)},e=>{n||l(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[t,e]);let h=n.get(`view`),g=h===`calls`||h===`drift`?h:h===`runs`&&m||m?`runs`:`calls`,_=n.get(`run`),v=i.runs.find(e=>e.id===_)??null,y=i.runs.find(e=>e.matrix!==null),b=QV(y),x=o!==null&&o.agent===e?o.goldens:[],S=x.length>0?x.map(e=>e.name):[...b.keys()],C=[...b.values()].filter(Boolean).length,w=b.size-C,T=e=>{let t=new URLSearchParams(n);for(let[n,r]of Object.entries(e))r===null?t.delete(n):t.set(n,r);r(t)},ee=async()=>{d(!0),p(null);try{let n=await HV(t,{agent:e,goldens:x.map(e=>e.name),voice:!1});T({view:null,run:n})}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}},te=[...m?[{value:`runs`,label:`Runs`}]:[],{value:`calls`,label:`Scored calls`},{value:`drift`,label:`Drift`}];return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Evals`,ledeWidth:620,lede:`Golden sessions replayed against the agent as it is now. A golden is fixed and the agent is the variable: never soften a golden so a change can pass.`}),(0,A.jsxs)(lh,{min:150,children:[(0,A.jsx)(uh,{size:`small`,label:`Goldens`,value:S.length===0?`—`:S.length}),(0,A.jsx)(uh,{size:`small`,label:`Passing`,value:y===void 0?`—`:C,tone:y===void 0?void 0:`green`}),(0,A.jsx)(uh,{size:`small`,label:`Failing`,value:y===void 0?`—`:w,tone:y===void 0||w===0?void 0:`red`}),(0,A.jsxs)(`div`,{className:`ui-stat ui-stat-small`,children:[(0,A.jsx)(`div`,{className:`ui-stat-label`,children:`Last run`}),(0,A.jsx)(`div`,{className:`ev-last`,children:i.runs[0]===void 0?`never`:Qh(i.runs[0].started_at)})]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Golden questions`,children:m&&x.length>0&&(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ev-run-all`,disabled:u,onClick:()=>void ee(),children:u?`Opening…`:`Run all`})}),S.length===0&&(0,A.jsx)(Mm,{children:o!==null&&o.agent!==e?o.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so no goldens to read.":`The process holding the agent runs in ${o.agent}'s directory; its goldens are that agent's.`:c!==null&&i.runs.length===0?`The goldens are files beside the class, read by the process holding the agent — and no run has been stored yet to list them from.`:`No goldens for this agent yet: write one in its goldens folder — test/goldens, or test/goldens/<name> in a project of several.`}),(0,A.jsx)(`div`,{className:`ev-goldens`,children:S.map(e=>{let t=x.find(t=>t.name===e),n=b.get(e);return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:XV},children:[(0,A.jsx)(`span`,{className:`ev-golden-says ui-clip`,title:e,children:t?.input[0]??e}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:t===void 0?`—`:ZV(t)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:n===void 0?(0,A.jsx)(Qm,{tone:`muted`,children:`not run`}):n?(0,A.jsx)(Qm,{tone:`green`,children:`pass`}):(0,A.jsx)(Qm,{tone:`red`,children:`fail`})})]},e)})})]}),(0,A.jsx)(Nm,{children:f}),(0,A.jsx)(`div`,{className:`ev-views`,children:(0,A.jsx)(Gm,{options:te,value:g,onChange:e=>T({view:e===(m?`runs`:`calls`)?null:e,run:null})})}),g===`runs`&&(0,A.jsxs)(A.Fragment,{children:[o!==null&&o.agent===e&&x.length>0&&(0,A.jsx)(GV,{agent:e,roster:o,onOpened:e=>T({run:e})}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Runs`,meta:`${i.runs.length} · the same rows pinecall runs list prints`}),(0,A.jsx)(Nm,{children:i.error}),i.runs.length>0?(0,A.jsx)(MV,{runs:i.runs,selected:_,onSelect:e=>T({run:e})}):(0,A.jsx)(Mm,{children:i.reading?`Reading…`:`No run has been stored yet. A run appears here the moment one opens — from this page, a laptop or CI.`})]}),v!==null&&(0,A.jsx)(IV,{run:v,before:i.runs[i.runs.indexOf(v)+1]})]}),g===`drift`&&(0,A.jsx)(xV,{agent:e}),g===`calls`&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Scored calls`,meta:`the verdict is the call.score entry the log seals on`}),(0,A.jsx)(Nm,{children:a.error}),a.rows.length>0?(0,A.jsx)(fV,{agent:e,rows:a.rows}):(0,A.jsx)(Mm,{children:`No call of this agent has finished yet. The judges seal a call's log with its verdict when the caller hangs up; the first one lands here.`})]})]})}var eH=z({state_fields:fp(P(),mp([`public`,`tenant`,`pii`])).default({})});function tH(e){let t=j(),[n,r]=(0,D.useState)({});return(0,D.useEffect)(()=>{let n=!1;if(e!==``)return(async()=>{try{let i=eH.parse(await k(t,`/v1/agents/${e}/config`));n||r(i.state_fields)}catch{n||r({})}})(),()=>{n=!0}},[e,t]),n}function nH(e){let t=e?.recording;return typeof t==`string`&&t!==``?t:null}function rH({call:e,path:t}){let[n,r]=(0,D.useState)(!1),i=(0,D.useCallback)(()=>r(!0),[]);return t===null||n?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Listen to this call`}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(iH,{call:e,onNothing:i})})]})}function iH({call:e,onNothing:t}){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let r=null,a=!1;return(async()=>{try{let o=await fetch(la(n,`/v1/calls/${e}/recording`),{headers:ra(n)});if(o.status===404&&t!==void 0){a||t();return}if(!o.ok)throw Error(await aH(o));r=URL.createObjectURL(await o.blob()),a?URL.revokeObjectURL(r):i(r)}catch(e){a||o(e instanceof Error?e.message:String(e))}})(),()=>{a=!0,r!==null&&URL.revokeObjectURL(r)}},[e,n,t]),a===null?r===null?(0,A.jsx)(`p`,{className:`session-sentence`,children:`Reading the recording…`}):(0,A.jsx)(`audio`,{className:`session-player`,controls:!0,preload:`none`,src:r}):(0,A.jsx)(`p`,{className:`session-sentence`,children:a})}async function aH(e){try{let t=(await e.json()).detail;if(typeof t==`string`)return t}catch{}return`the recording answered ${e.status}`}var oH=z({server_url:P(),participant_token:P(),identity:P()});async function sH(e,t,n){return oH.parse(await sa(e,`/v1/calls/${t}/${n}`,{}))}function cH(e){let t=j(),[n,r]=(0,D.useState)(`off`),[i,a]=(0,D.useState)(null),o=(0,D.useRef)(null),s=(0,D.useRef)([]),c=(0,D.useCallback)(async()=>{r(`joining`),a(null);try{let n=await sH(t,e,`listen`),i=new FB;o.current=i,i.on(Y.TrackSubscribed,e=>{if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.muted=!0,t.style.display=`none`,document.body.append(t),s.current.push(t)}),i.on(Y.TrackUnsubscribed,e=>{for(let t of e.detach())t.remove(),s.current=s.current.filter(e=>e!==t)}),i.on(Y.Disconnected,()=>r(`off`)),await i.connect(n.server_url,n.participant_token),r(`muted`)}catch(e){a(e instanceof Error?e.message:String(e)),r(`failed`)}},[e,t]),l=(0,D.useCallback)(e=>{for(let t of s.current)t.muted=!e;r(e?`on`:`muted`)},[]),u=(0,D.useCallback)(async()=>{await o.current?.disconnect(),o.current=null},[]);return(0,D.useEffect)(()=>()=>{o.current?.disconnect()},[]),{listening:n,error:i,join:c,hear:l,leave:u}}var lH=`cold`,uH=class{#e;#t;#n=null;constructor(e,t){this.#e=e,this.#t=t}async send(e){await sa(this.#e,`/v1/calls/${this.#t}/verbs`,n_.parse(e))}async take(){await(await this.#r()).localParticipant.setMicrophoneEnabled(!0),await this.send({verb:`takeover`})}async give(){await this.send({verb:`release`}),await this.#i()}async leave(){await this.#i(),await this.#n?.disconnect(),this.#n=null}async#r(){if(this.#n!==null)return this.#n;let e=await sH(this.#e,this.#t,`supervise`),t=new FB;return await t.connect(e.server_url,e.participant_token,{autoSubscribe:!1}),this.#n=t,t}async#i(){let e=this.#n?.localParticipant,t=e?.getTrackPublication($.Source.Microphone);e!==void 0&&t?.track!==void 0&&await e.unpublishTrack(t.track,!0)}};function dH(e){let t=j(),[n,r]=(0,D.useState)(!1),[i,a]=(0,D.useState)(null),o=(0,D.useRef)(null),s=(0,D.useCallback)(()=>(o.current??=new uH(t,e),o.current),[e,t]),c=(0,D.useCallback)(async(e,t)=>{a(null);try{await e(s()),t!==null&&r(t)}catch(e){a(e instanceof Error?e.message:String(e))}},[s]),l=(0,D.useCallback)(e=>c(t=>t.send({verb:`whisper`,text:e}),null),[c]),u=(0,D.useCallback)(e=>c(t=>t.send({verb:`say`,text:e}),null),[c]),d=(0,D.useCallback)(()=>c(e=>e.take(),!0),[c]),f=(0,D.useCallback)(()=>c(e=>e.give(),!1),[c]),p=(0,D.useCallback)(e=>c(t=>t.send({verb:`transfer`,to:e,mode:lH}),null),[c]),m=(0,D.useCallback)(()=>c(e=>e.send({verb:`end`}),null),[c]);return(0,D.useEffect)(()=>()=>{o.current?.leave(),o.current=null},[]),{whisper:l,say:u,takeOver:d,release:f,transfer:p,end:m,holding:n,error:i}}var fH={whisper:`Whisper to the agent — the caller never hears it`,say:`Say it to the caller, in the agent's voice, verbatim`};function pH({call:e,live:t}){let n=cH(e),r=dH(e),i=(0,D.useRef)(!1);(0,D.useEffect)(()=>{t&&!i.current&&(i.current=!0,n.join())},[t,n]);let a=n.error??r.error;return(0,A.jsxs)(`div`,{className:`lv-desk`,role:`group`,"aria-label":`the supervisor's desk`,children:[(0,A.jsx)(mH,{ear:n,live:t}),t?(0,A.jsx)(hH,{desk:r}):(0,A.jsx)(`span`,{className:`lv-desk-note`,children:`The call is over: nothing is left to supervise. Read its log below, or play its recording.`}),a!==null&&(0,A.jsx)(`span`,{className:`lv-desk-refused`,children:a})]})}function mH({ear:e,live:t}){if(!t)return null;switch(e.listening){case`off`:case`failed`:return(0,A.jsxs)(U,{size:`sm`,pill:!0,onClick:()=>void e.join(),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot`}),`Listen`]});case`joining`:return(0,A.jsxs)(U,{size:`sm`,pill:!0,disabled:!0,children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-warm`}),`Joining…`]});case`muted`:return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(U,{size:`sm`,pill:!0,onClick:()=>e.hear(!0),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-warm`}),`Hear it`]}),(0,A.jsx)(U,{size:`sm`,pill:!0,onClick:()=>void e.leave(),children:`Stop`})]});case`on`:return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(U,{size:`sm`,pill:!0,onClick:()=>e.hear(!1),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-on`}),`Listening · mute`]}),(0,A.jsx)(U,{size:`sm`,pill:!0,onClick:()=>void e.leave(),children:`Stop`})]})}}function hH({desk:e}){let[t,n]=(0,D.useState)(`whisper`),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1),l=()=>{r.trim()!==``&&(t===`whisper`?e.whisper(r):e.say(r),i(``))},u=()=>{a!==null&&a.trim()!==``&&(e.transfer(a.trim()),o(null))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`lv-desk-say`,children:[(0,A.jsx)(Gm,{options:[{value:`whisper`,label:`Whisper`},{value:`say`,label:`Say`}],value:t,onChange:n}),(0,A.jsx)(W,{size:`sm`,className:`lv-desk-text`,value:r,placeholder:fH[t],onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&l()}}),(0,A.jsx)(U,{size:`sm`,kind:`primary`,disabled:r.trim()===``,onClick:l,children:`Send`})]}),(0,A.jsx)(U,{size:`sm`,className:e.holding?`lv-desk-holding`:void 0,title:e.holding?`the agent hears and speaks again, and your microphone stops`:`your microphone takes the line: the agent stops speaking`,onClick:()=>void(e.holding?e.release():e.takeOver()),children:e.holding?`Hand back`:`Take the line`}),a===null?(0,A.jsx)(U,{size:`sm`,onClick:()=>o(``),children:`Transfer`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(W,{size:`sm`,className:`lv-desk-number`,autoFocus:!0,value:a,placeholder:`+34… then Enter`,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u(),e.key===`Escape`&&o(null)}}),(0,A.jsx)(U,{size:`sm`,disabled:a.trim()===``,onClick:u,children:`Transfer`}),(0,A.jsx)(U,{size:`sm`,onClick:()=>o(null),children:`Cancel`})]}),(0,A.jsx)(U,{size:`sm`,kind:`danger`,className:s?`lv-desk-armed`:void 0,onClick:()=>{s&&e.end(),c(!s)},onBlur:()=>c(!1),children:s?`End · sure?`:`End call`})]})}var gH=new Set([`tag`,`name`,`id`,`flag`]);function _H({rows:e}){return(0,A.jsx)(`div`,{className:`lv-readings`,children:e.map(e=>(0,A.jsxs)(`div`,{className:`lv-reading`,children:[(0,A.jsx)(`span`,{className:`lv-reading-name`,children:e.field}),(0,A.jsxs)(`span`,{className:`lv-reading-value`,title:String(e.value),children:[vH(String(e.value)),e.unit!==null&&!gH.has(e.unit)&&(0,A.jsxs)(`span`,{className:`lv-seen`,children:[` `,e.unit]})]})]},e.field))})}function vH(e){return/^-?\d+\.\d{4,}$/.test(e)?Number(e).toFixed(3):e}function yH({metrics:e,entries:t}){let n=YC(t),r=Math.max(...n.map(e=>e.seconds),0),i=UC();return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{ruled:!0,children:`Metrics`}),(0,A.jsxs)(`div`,{className:`lv-pane-body`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`lv-sub`,children:`Nothing measured yet: the first turn fills this in.`}),n.map(e=>(0,A.jsxs)(`div`,{className:`lv-meter`,title:`median over ${String(e.turns)} turns`,children:[(0,A.jsx)(`span`,{className:`lv-meter-name`,children:e.name}),(0,A.jsx)(oh,{share:r===0?0:e.seconds/r}),(0,A.jsx)(`span`,{className:`lv-meter-value`,children:WC(e.seconds)})]},e.name)),Object.entries(e).map(([e,t])=>(0,A.jsx)(bH,{kind:e,blocks:t,shape:i.get(e)},e))]})]})}function bH({kind:e,blocks:t,shape:n}){return t.length===0?null:(0,A.jsxs)(`details`,{className:`lv-blocks`,children:[(0,A.jsxs)(`summary`,{children:[`metrics.`,e,` · `,t.length]}),t.map((t,r)=>(0,A.jsx)(_H,{rows:HC(t,n)},`${e}-${String(r)}`))]})}function xH({prompt:e,cost:t}){let n=Object.entries(e);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{ruled:!0,children:`Prompt`}),(0,A.jsxs)(`div`,{className:`lv-pane-body lv-pane-body-tight`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`lv-sub`,children:`The app has written no block yet.`}),n.map(([e,t])=>(0,A.jsxs)(`div`,{className:`lv-prompt-row`,children:[(0,A.jsx)(`span`,{className:`lv-prompt-name`,children:e}),(0,A.jsx)(`span`,{className:`lv-prompt-hash`,title:t.hash,children:t.hash.slice(0,8)}),(0,A.jsxs)(`span`,{className:`lv-prompt-chars`,children:[t.chars.toLocaleString(`en`).replace(/,/g,` `),` chars`]})]},e)),t!==null&&(0,A.jsx)(Lm,{label:`cost so far`,children:Yh(t.eur)})]})]})}function SH({room:e,from:t,over:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{ruled:!0,children:`Room`}),e===null?(0,A.jsx)(`div`,{className:`lv-pane-text`,children:`No room: this session carries no media.`}):(0,A.jsxs)(`div`,{className:`lv-pane-text`,children:[n?`Audio room closed`:`Audio room open`,` · `,e.participants.length,` `,e.participants.length===1?`participant`:`participants`,t!==null&&(0,A.jsxs)(A.Fragment,{children:[` · rang from `,t]}),(0,A.jsx)(`ul`,{className:`lv-people`,children:e.participants.map(e=>(0,A.jsx)(`li`,{className:`lv-person`,children:(0,A.jsxs)(`details`,{children:[(0,A.jsxs)(`summary`,{children:[(0,A.jsx)(eh,{tone:e.speaking?`green`:void 0,small:!0}),(0,A.jsx)(`span`,{children:e.name??e.identity}),(0,A.jsx)(`span`,{className:`lv-person-kind`,children:e.kind})]}),(0,A.jsx)(`pre`,{className:`lv-data`,children:JSON.stringify(e.attributes,null,2)})]})},e.identity))})]})]})}var CH=`***`,wH=`tenant`;function TH({fields:e,declared:t}){let n=Object.keys(e).sort();return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{children:`State`}),n.length===0?(0,A.jsx)(`div`,{className:`lv-pane-text`,children:`The app has declared no state yet.`}):(0,A.jsx)(`div`,{className:`lv-pane-body`,children:n.map(n=>{let r=EH(e[n],t[n]);return(0,A.jsxs)(Lm,{label:n,children:[DH(e[n]),r!==wH&&(0,A.jsx)(`span`,{className:r===`pii`?`lv-seen lv-seen-pii`:`lv-seen`,children:r})]},n)})})]})}function EH(e,t){return e===CH?`pii`:t===`public`?`public`:wH}function DH(e){return typeof e==`string`?e:JSON.stringify(e)}function OH({seq:e,kind:t,tone:n,who:r,said:i,note:a=[],children:o}){let s=a.filter(e=>e!=null&&e!==``),c=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`lv-seq`,children:e}),(0,A.jsx)(`span`,{className:`lv-kind lv-kind-${n}`,children:t}),(0,A.jsxs)(`span`,{className:n===`turn`?`lv-text lv-text-turn`:n===`quiet`?`lv-text lv-text-quiet`:`lv-text`,children:[r!==void 0&&(0,A.jsx)(`span`,{className:r===`agent`?`lv-who lv-who-agent`:`lv-who`,children:r}),i,s.length>0&&(0,A.jsx)(`span`,{className:`lv-note`,children:s.map((e,t)=>(0,A.jsxs)(`span`,{children:[t>0&&` · `,e]},t))})]})]}),l=`lv-row lv-${n}`;return o==null||o===!1?(0,A.jsx)(`div`,{className:l,children:(0,A.jsx)(`div`,{className:`lv-line`,children:c})}):(0,A.jsxs)(`details`,{className:l,children:[(0,A.jsx)(`summary`,{className:`lv-line`,children:c}),(0,A.jsx)(`div`,{className:`lv-more`,children:o})]})}function kH(e){return e.ops.map(NH).join(`; `)}function AH(e){return e.ops.flatMap(e=>e.facts.map(e=>e.category?`${e.text} (${e.category})`:e.text))}function jH(e){return`${e.sources.length} sources · ${PH(e.took_ms)}`}function MH(e){return e.sources.map(e=>`${e.heading?`${e.path} › ${e.heading}`:e.path} · ${e.score.toFixed(3)}`)}function NH(e){return`${e.op} · ${e.facts.length} facts · ${PH(e.took_ms)}`}function PH(e){return`${Math.round(e)} ms`}function FH({ops:e,seq:t}){return(0,A.jsx)(LH,{kind:`memory`,said:kH(e),lines:AH(e),seq:t})}function IH({sources:e,seq:t}){return(0,A.jsx)(LH,{kind:`sources`,said:jH(e),lines:MH(e),seq:t})}function LH({kind:e,said:t,lines:n,seq:r}){return(0,A.jsx)(OH,{seq:r,kind:e,tone:`lookup`,said:t,children:(0,A.jsx)(`ul`,{className:`lv-list`,children:n.map(e=>(0,A.jsx)(`li`,{children:e},e))})})}function RH({changed:e,cause:t,seq:n}){return(0,A.jsx)(OH,{seq:n,kind:`state`,tone:`state`,said:`${e.join(`, `)} ← ${UH(t)}`})}function zH({mark:e,seq:t}){return(0,A.jsx)(OH,{seq:t,kind:`supervisor`,tone:`supervisor`,said:e.said,note:[e.by]})}function BH({confirm:e,seq:t}){let n=[{field:`tool`,value:e.tool,unit:null},{field:`audience`,value:e.audience,unit:null},...e.said==null?[]:[{field:`said`,value:e.said,unit:null}],...e.reason==null?[]:[{field:`reason`,value:e.reason,unit:null}]];return(0,A.jsx)(OH,{seq:t,kind:`confirm`,tone:`confirm`,said:e.phrase,note:[e.status],children:(0,A.jsx)(_H,{rows:n})})}function VH({name:e,source:t,data:n,seq:r}){return(0,A.jsx)(OH,{seq:r,kind:`event`,tone:`event`,said:e,note:[t],children:(0,A.jsx)(`pre`,{className:`lv-data`,children:JSON.stringify(n,null,2)})})}function HH({entries:e}){return(0,A.jsx)(OH,{seq:e[0]?.seq,kind:`quiet`,tone:`quiet`,said:e.length===1?`1 entry`:`${e.length} entries`,children:(0,A.jsx)(`ul`,{className:`lv-list`,children:e.map(e=>(0,A.jsxs)(`li`,{children:[e.seq,` `,e.type]},`${String(e.seq)}-${e.type}`))})})}function UH(e){return e===null?`the app`:e.kind===`tool`?e.tool:`${e.name} (seq ${String(e.seq)})`}function WH({run:e,seq:t}){let n=[{field:`arguments`,value:JSON.stringify(e.arguments,null,2),unit:null},...GH(e.output)?[{field:`output`,value:JSON.stringify(e.output,null,2),unit:null}]:[],...GH(e.error)?[{field:`error`,value:e.error,unit:null}]:[],...GH(e.duration_s)?[{field:`duration_s`,value:WC(e.duration_s),unit:null}]:[]];return(0,A.jsx)(OH,{seq:t,kind:`tool`,tone:`tool`,said:`${e.name}(${KH(e)})`,note:[(0,A.jsx)(`span`,{className:e.status===`failed`?`lv-failed`:``,children:qH(e)})],children:(0,A.jsx)(_H,{rows:n})})}function GH(e){return e!=null}function KH(e){return Object.entries(e.arguments).map(([e,t])=>`${e}=${JH(t)}`).join(`, `)}function qH(e){return e.status===`running`?`…`:e.error??e.summary??JH(e.output)}function JH(e){let t=typeof e==`string`?e:JSON.stringify(e);return t===void 0?``:t.slice(0,60)}var YH={transcription_delay:`stt`,end_of_turn_delay:`eot`,llm_node_ttft:`ttft`,tts_node_ttfb:`ttfb`,e2e_latency:`e2e`};function XH({turn:e,seq:t,metrics:n}){let r=qC(n,e.speech_id),i=VC(e).map(e=>`${YH[e.field]??e.field} ${e.value}`),a=[...e.role===`agent`&&e.interrupted?[`interrupted`]:[],...e.role===`user`&&e.language!==void 0&&e.language!==null?[e.language]:[]],o=e.role===`user`?[...i,e.speech_id,...a]:[...i,...a];return(0,A.jsx)(OH,{seq:t,kind:`turn`,tone:`turn`,who:e.role===`agent`?`agent`:`caller`,said:e.text,note:o,children:r.length===0?null:r.map((e,t)=>(0,A.jsxs)(`section`,{children:[(0,A.jsxs)(`h4`,{className:`lv-block-name`,children:[`metrics.`,e.kind]}),(0,A.jsx)(_H,{rows:e.readings})]},`${e.kind}-${String(t)}`))})}var ZH=80;function QH({entries:e,state:t,after:n}){let r=t.live.agent,i=(0,D.useRef)(null),a=(0,D.useRef)(!0);return(0,D.useEffect)(()=>{let e=i.current;e!==null&&a.current&&(e.scrollTop=e.scrollHeight)},[e,t.live.user,r]),(0,A.jsxs)(`div`,{className:`lv-rows`,ref:i,onScroll:e=>{let t=e.currentTarget;a.current=t.scrollHeight-t.scrollTop-t.clientHeight<ZH},children:[_w(e,t).map(e=>(0,A.jsx)($H,{row:e,state:t},`${e.kind}-${String(e.seq)}`)),(0,A.jsx)(eU,{said:t.live.user,who:`caller`}),(0,A.jsx)(eU,{said:r,who:`agent`}),n]})}function $H({row:e,state:t}){switch(e.kind){case`turn`:return(0,A.jsx)(XH,{turn:e.turn,seq:e.seq,metrics:t.metrics});case`tool`:return(0,A.jsx)(WH,{run:e.run,seq:e.seq});case`state`:return(0,A.jsx)(RH,{changed:e.changed,cause:e.cause,seq:e.seq});case`confirm`:return(0,A.jsx)(BH,{confirm:e.confirm,seq:e.seq});case`event`:return(0,A.jsx)(VH,{name:e.name,source:e.source,data:e.data,seq:e.seq});case`supervisor`:return(0,A.jsx)(zH,{mark:e.mark,seq:e.seq});case`memory`:return(0,A.jsx)(FH,{ops:e.ops,seq:e.seq});case`sources`:return(0,A.jsx)(IH,{sources:e.sources,seq:e.seq});case`quiet`:return(0,A.jsx)(HH,{entries:e.entries})}}function eU({said:e,who:t}){if(e===null)return null;let n=e.split(/\s+/).filter(e=>e!==``);return(0,A.jsx)(`div`,{className:`lv-saying`,children:(0,A.jsx)(OH,{seq:void 0,kind:`turn`,tone:`turn`,who:t,said:(0,A.jsxs)(A.Fragment,{children:[n.map((e,t)=>(0,A.jsxs)(`span`,{className:t===n.length-1?`lv-word lv-word-now`:`lv-word`,children:[e,` `]},t)),(0,A.jsx)(`span`,{className:`lv-caret`,"aria-hidden":!0})]})})})}function tU({call:e,agent:t}){let n=rw(e),r=n.state,i=tH(r.agent),a=Eh(),[o,s]=(0,D.useState)(!1),c=r.status===`ended`,l=nH(aU(n.entries)),u=a===null||a.includes(`supervise`),d=vh({name:`live.call`,initial:360,min:280,max:640,side:`right`});return(0,D.useEffect)(()=>s(!1),[e]),(0,A.jsxs)(`div`,{className:`lv`,style:d.style,children:[d.handle,(0,A.jsxs)(`div`,{className:`lv-middle`,children:[(0,A.jsxs)(nU,{call:e,agent:t,state:r,connection:n.error??n.connection,failed:n.error!==null,children:[(0,A.jsx)(Wi,{to:`/sessions/${e}`,className:`lv-session`,children:`Open session`}),u&&(0,A.jsxs)(`button`,{type:`button`,className:o?`lv-listen lv-listen-open`:`lv-listen`,disabled:c&&!o,title:c?`the call is over`:void 0,onClick:()=>s(!o),"aria-expanded":o,children:[(0,A.jsx)(`span`,{className:c?`ui-dot ui-dot-small`:`ui-dot ui-dot-small ui-dot-green`}),o?`Close the desk`:`Listen in`]})]}),o&&(0,A.jsx)(pH,{call:e,live:!c}),(0,A.jsx)(QH,{entries:n.entries,state:r,after:l===null?void 0:(0,A.jsx)(oU,{call:e})})]}),(0,A.jsxs)(`aside`,{className:`lv-pane`,"aria-label":`what the call holds`,children:[(0,A.jsx)(TH,{fields:r.app_state,declared:i}),(0,A.jsx)(SH,{room:r.room,from:r.from,over:c}),(0,A.jsx)(xH,{prompt:r.prompt,cost:r.cost}),(0,A.jsx)(yH,{metrics:r.metrics,entries:n.entries})]})]})}function nU({call:e,agent:t,state:n,connection:r,failed:i,children:a}){let o=iU(n.status!==`ended`),s=n.status===`ended`,c=n.caller?.name??rU(n.direction===`outbound`?n.to:n.from);return(0,A.jsxs)(`div`,{className:`lv-head`,children:[(0,A.jsx)(`span`,{className:`lv-call`,children:e}),n.channel!==null&&(0,A.jsx)(`span`,{className:`lv-tag`,children:n.channel}),n.direction!==null&&(0,A.jsx)(`span`,{className:`lv-tag`,children:n.direction}),(0,A.jsx)(`span`,{className:s?`lv-status lv-status-over`:`lv-status`,children:s?(n.end_reason??`ended`).replace(/_/g,` `):n.status===`active`?`on a call · ${Jh(n.started_at,o)}`:n.status}),(0,A.jsxs)(`span`,{className:`lv-sub`,children:[c,` → `,n.agent||t||`—`,` · seq `,n.seq,n.agent_state!==null&&` · agent ${n.agent_state}`,n.user_state!==null&&` · caller ${n.user_state}`,` · `,(0,A.jsx)(`span`,{className:i?`lv-connection-bad`:void 0,children:r})]}),a]})}function rU(e){return e===null?`—`:e.startsWith(`+`)?og(e):e}function iU(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}function aU(e){return[...e].reverse().find(e=>e.type===`call.summary`)?.data}function oU({call:e}){let[t,n]=(0,D.useState)(!1),r=(0,D.useCallback)(()=>n(!0),[]);return t?null:(0,A.jsx)(`div`,{className:`lv-recording`,children:(0,A.jsx)(iH,{call:e,onNothing:r})})}var sU=Uv.loose(),cU=50,lU=250;function uU(e,t,n,r){let i=j(),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(s)return;let r=!1,a=window.setTimeout(()=>{(async()=>{let a=e===``?`/v1/sessions`:`/v1/agents/${encodeURIComponent(e)}/sessions`,s={limit:cU};t.query.trim()!==``&&(s.q=t.query.trim()),t.agent!==``&&(s.agent=t.agent),t.channel!==``&&(s.channel=t.channel);try{let e=[],t=0,l=null;for(let o=0;o<n&&!(o>0&&l===null);o+=1){let n=await k(i,a,l===null?s:{...s,before:l});if(r)return;if(typeof n.total!=`number`){c(!0);return}let o=Array.isArray(n.calls)?n.calls:[];e.push(...o.map(e=>sU.parse(e))),t=n.total,l=typeof n.next==`string`?n.next:null}o({rows:e,total:t,next:l})}catch{r||c(!0)}})()},lU);return()=>{r=!0,window.clearTimeout(a)}},[i,e,t.query,t.agent,t.channel,n,s,r]),s?null:a}function dU(e,t){let n=t.trim().toLowerCase();if(n===``)return!0;let r=n.replace(/[^\d]/g,``);if([e.call,e.agent,e.from,e.to,e.caller?.name,e.outcome,e.channel].filter(Boolean).join(` `).toLowerCase().includes(n))return!0;if(r.length>=3){let t=`${e.from??``} ${e.to??``} ${e.call}`.replace(/[^\d ]/g,``);return t.replace(/ /g,``).includes(r)||t.includes(r)}return!1}var fU=80;function pU(){let{lines:e,agents:t,floorError:n}=Xy(),r=Sr().call,[i,a]=Xi(),o=i.get(`agent`),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(``),d=vh({name:`live.calls`,initial:300,min:220,max:520,side:`left`}),f=hU(),p=e.filter(e=>(o===null||e.agent===o)&&dU(e,l)),m=p.filter(BS),h=p.filter(e=>!BS(e)).slice(0,fU),g=[...m,...h],_=r??m[0]?.call??g[0]?.call,v=o===null?``:`?agent=${encodeURIComponent(o)}`;return(0,A.jsxs)(`div`,{className:`fl`,style:d.style,children:[d.handle,(0,A.jsxs)(`nav`,{className:`fl-side`,"aria-label":`the floor's calls`,children:[(0,A.jsxs)(`div`,{className:`fl-side-head`,children:[(0,A.jsxs)(`div`,{className:`fl-standing`,children:[(0,A.jsx)(eh,{tone:m.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`fl-count`,children:m.length===1?`1 call up`:`${m.length} calls up`}),(0,A.jsxs)(`span`,{className:`fl-asked`,title:`re-asked every ${RS/1e3} s`,children:[p.length,` listed`]})]}),(0,A.jsx)(W,{size:`sm`,className:`fl-search`,placeholder:`Search a number, agent or outcome`,"aria-label":`Search the floor's calls`,value:l,onChange:e=>u(e.target.value)}),o!==null&&(0,A.jsxs)(`div`,{className:`fl-only`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:o}),(0,A.jsx)(`button`,{type:`button`,className:`fl-only-clear`,onClick:()=>{i.delete(`agent`),a(i)},children:`every agent`})]}),(0,A.jsx)(`button`,{type:`button`,className:`fl-simulate`,onClick:()=>c(!s),"aria-expanded":s,children:`Simulate a caller`}),s&&(0,A.jsx)(`div`,{className:`fl-sim`,children:(0,A.jsx)(cC,{agents:o===null?t.map(e=>e.slug):[o],onClose:()=>c(!1)})})]}),(0,A.jsxs)(`div`,{className:`fl-list`,children:[n!==null&&(0,A.jsx)(`p`,{className:`fl-empty fl-refused`,children:n}),g.length===0&&n===null&&(0,A.jsx)(`p`,{className:`fl-empty`,children:l===``?`No calls yet. Leave this open — a call that reaches any agent shows up here as it rings.`:`No call here matches.`}),m.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`On a call now`}),m.map(e=>(0,A.jsx)(mU,{line:e,on:e.call===_,now:f,to:`/live/${e.call}${v}`},e.call)),h.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`Recent`}),h.map(e=>(0,A.jsx)(mU,{line:e,on:e.call===_,now:f,to:`/live/${e.call}${v}`},e.call)),h.length>0&&(0,A.jsx)(Wi,{to:`/sessions`,className:`fl-all`,children:`Every session →`})]})]}),_===void 0?(0,A.jsx)(`div`,{className:`fl-nothing`,children:`Nothing to watch yet: the first call the org takes appears on the left, and opens here.`}):(0,A.jsx)(tU,{call:_,agent:g.find(e=>e.call===_)?.agent},_)]})}function mU({line:e,on:t,now:n,to:r}){let i=BS(e);return(0,A.jsxs)(Wi,{to:r,className:t?`fl-row fl-row-on`:`fl-row`,title:e.call,children:[(0,A.jsx)(`span`,{className:i?`fl-dot fl-dot-live`:`fl-dot`}),(0,A.jsxs)(`span`,{className:`fl-row-words`,children:[(0,A.jsxs)(`span`,{className:`fl-row-top`,children:[(0,A.jsx)(`span`,{className:`fl-id`,children:sg(e)}),(0,A.jsx)(`span`,{className:i?`fl-meta fl-meta-live`:`fl-meta`,children:i?e.status===`active`?Jh(e.started_at,n):e.status:eg(e.started_at,n)})]}),(0,A.jsxs)(`span`,{className:`fl-row-sub`,children:[(0,A.jsxs)(`span`,{className:`ui-clip`,children:[e.agent,e.channel!==null&&` · ${e.channel}`,e.direction===`outbound`&&` · outbound`,!i&&` · ${qh(e)}`]}),e.score!=null&&(0,A.jsx)(`span`,{className:`fl-score`,children:(0,A.jsxs)(Qm,{tone:e.score.passed?`green`:`red`,children:[e.score.held,`/`,e.score.judged]})}),e.score==null&&(e.flags??[]).includes(`escalated`)&&(0,A.jsx)(`span`,{className:`fl-score`,children:(0,A.jsx)(Qm,{tone:`amber`,children:`escalated`})})]}),!i&&e.outcome!==null&&(0,A.jsx)(`span`,{className:`fl-outcome`,children:e.outcome})]})]})}function hU(){let[e,t]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{let e=window.setInterval(()=>t(Date.now()/1e3),1e3);return()=>window.clearInterval(e)},[]),e}var gU=/^call[_-][\w+-]{6,}$/,_U=`minmax(0,1.3fr) 128px 84px 78px 74px minmax(0,1.5fr)`,vU=`minmax(0,1.3fr) 84px 78px 74px minmax(0,1.6fr)`,yU=[`web`,`phone`,`whatsapp`];function bU({lines:e,error:t,agent:n,agents:r}){let i=vr(),[a,o]=(0,D.useState)({query:``,agent:``,channel:``}),[s,c]=(0,D.useState)(1),l=uU(n,a,s,`${e.length}:${e[0]?.call??``}:${e.filter(BS).length}`),u=n===``,d=l===null?e.filter(e=>dU(e,a.query)&&(a.agent===``||e.agent===a.agent)&&(a.channel===``||e.channel===a.channel)):l.rows,f=[...d.filter(BS),...d.filter(e=>!BS(e))],p=e=>u?`/sessions/${e}`:`/a/${n}/sessions/${e}`,m=e=>{let t=a.query.trim();e.key===`Enter`&&gU.test(t)&&i(p(t))},h=u?_U:vU,g=a.query!==``||a.agent!==``||a.channel!==``;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`sessions-filters`,children:[(0,A.jsx)(W,{size:`sm`,className:`sessions-search`,placeholder:`Search a session id, number or outcome`,"aria-label":`Search a session id, number or outcome`,value:a.query,onChange:e=>o({...a,query:e.target.value}),onKeyDown:m}),u&&(0,A.jsxs)(Hm,{size:`sm`,className:`sessions-select`,value:a.agent,onChange:e=>o({...a,agent:e.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Every agent`}),r.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}),u&&(0,A.jsxs)(Hm,{size:`sm`,className:`sessions-select`,value:a.channel,onChange:e=>o({...a,channel:e.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Every channel`}),yU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]})]}),(0,A.jsx)(Nm,{children:t}),(0,A.jsxs)(V,{children:[f.length===0?(0,A.jsx)(Mm,{children:g?gU.test(a.query.trim())?(0,A.jsxs)(A.Fragment,{children:[`Not on this page — press Enter to open `,a.query.trim(),` by its id.`]}):(0,A.jsx)(A.Fragment,{children:`No session here matches. The search reads the sessions this page has listed.`}):(0,A.jsxs)(A.Fragment,{children:[`No session recorded yet. The log is written during the call, so one appears here the moment it starts — from the browser, from`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall chat`}),`, or from the telephone.`]})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:h,labels:u?[`Session`,`Agent`,`Channel`,`Started`,`Duration`,`Outcome`]:[`Session`,`Channel`,`Started`,`Duration`,`Outcome`]}),f.map(e=>(0,A.jsxs)(fh,{columns:h,to:p(e.call),children:[(0,A.jsxs)(`div`,{className:`sessions-id`,children:[(0,A.jsxs)(`div`,{className:`sessions-call`,children:[BS(e)&&(0,A.jsx)(eh,{tone:`green`,small:!0}),(0,A.jsx)(`span`,{className:`ui-clip`,children:e.call})]}),(0,A.jsx)(`div`,{className:`sessions-from ui-clip`,children:sg(e)})]}),u&&(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.channel??`—`}),(0,A.jsx)(`span`,{className:`ui-cell`,children:Zh(e.started_at)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:BS(e)?(0,A.jsx)(`span`,{className:`sessions-live`,children:`live`}):qh(e)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.outcome??xU(e)})]},e.call))]}),l!==null&&l.total>l.rows.length&&(0,A.jsxs)(jm,{children:[(0,A.jsxs)(`span`,{children:[l.rows.length,` of `,l.total]}),(0,A.jsx)(`span`,{className:`sessions-more`,children:(0,A.jsx)(U,{size:`sm`,onClick:()=>c(s+1),children:`Load more`})})]})]})]})}function xU(e){return BS(e)?`on a call`:e.end_reason===null?`—`:e.end_reason.replace(/_/g,` `)}function SU(){let{lines:e,floorError:t,agents:n}=Xy(),r=[...new Set([...n.map(e=>e.slug),...e.map(e=>e.agent)])].sort();return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Sessions`,lede:`Every conversation the org has had, newest first, whichever agent handled it.`}),(0,A.jsx)(bU,{lines:e,error:t,agent:``,agents:r})]})}var CU=[`qa`,`supervisor`,`manager`,`admin`,`developer`],wU=z({id:P(),email:P(),name:P(),role:mp(CU),agents:R(P()),status:mp([`invited`,`active`,`disabled`]),scopes:R(P()),production:L()}),TU=z({member:wU,token:P(),expires_at:P()});async function EU(e){return z({members:R(wU)}).parse(await k(e,`/v1/members`)).members}async function DU(e,t){return TU.parse(await sa(e,`/v1/members`,t))}async function OU(e,t){return TU.parse(await sa(e,`/v1/members/${encodeURIComponent(t)}/reset`,{}))}async function kU(e,t){await ca(e,`/v1/members/${encodeURIComponent(t)}`)}async function AU(e,t,n){let r=await fetch(new URL(`${e.base.replace(/\/$/,``)}/v1/members/${encodeURIComponent(t)}`,window.location.origin),{method:`PATCH`,headers:{...ra(e),"content-type":`application/json`},body:JSON.stringify(n)});return wU.parse(await fa(r))}var jU=z({configured:L(),issuer:P().nullish(),client_id:P().nullish(),domains:R(P()),role:P().nullish(),required:L(),redirect_uri:P()});async function MU(e){try{return jU.parse(await k(e,`/v1/org/sso`))}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}async function NU(e,t){return jU.parse(await oa(e,`/v1/org/sso`,t))}async function PU(e){await ca(e,`/v1/org/sso`)}var FU=z({on:L(),ceiling_eur:F().nullable()});function IU(){let e=j(),t=Eh(),[n,r]=(0,D.useState)(null),i=Sm(vm,`numbers`)&&t!==null&&Qy(t,`numbers`),a=Sm(vm,`team`)&&t!==null&&Qy(t,`team`),[o,s]=(0,D.useState)(0);return(0,D.useEffect)(()=>{if(t===null)return;let n=!1;return(async()=>{let o=[];if(i){let[t,n]=await Promise.all([hb(e).catch(()=>null),mb(e).catch(()=>[])]);o.push({done:t!==null,name:`Connect a phone carrier`,action:`Connect`,to:`/numbers`});let r=n.filter(e=>e.route.number!==null).length;o.push({done:r>0,name:r>1?`Point ${r} numbers at an agent`:`Point a number at an agent`,action:`Add`,to:`/numbers`})}let c=await k(e,`/v1/org/judging`).then(e=>FU.parse(e),()=>null);if(c!==null&&t!==null&&t.includes(`usage`)&&o.push({done:c.on,name:`Add a judge so calls get scored`,action:`Turn on`,run:async()=>{await oa(e,`/v1/org/judging`,{on:!0}),s(e=>e+1)}}),a){let t=await EU(e).catch(()=>[]);o.push({done:t.filter(e=>e.status!==`disabled`).length>1,name:`Invite your team`,action:`Invite`,to:`/team`})}n||r(o)})(),()=>{n=!0}},[e,i,a,t,o]),n===null||n.length===0||n.every(e=>e.done)?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Finish setting up`})}),(0,A.jsx)(`div`,{className:`home-steps`,children:n.map(e=>e.done?(0,A.jsxs)(`div`,{className:`home-step`,children:[(0,A.jsx)(`span`,{className:`home-step-done`,children:`✓`}),(0,A.jsx)(`span`,{className:`home-step-name home-step-name-done`,children:e.name})]},e.name):e.run===void 0?(0,A.jsxs)(Wi,{to:e.to??`/`,className:`home-step home-step-open`,children:[(0,A.jsx)(`span`,{className:`home-step-todo`}),(0,A.jsx)(`span`,{className:`home-step-name`,children:e.name}),(0,A.jsx)(`span`,{className:`home-step-action`,children:e.action})]},e.name):(0,A.jsxs)(`button`,{type:`button`,className:`home-step home-step-open home-step-button`,onClick:()=>void e.run?.(),children:[(0,A.jsx)(`span`,{className:`home-step-todo`}),(0,A.jsx)(`span`,{className:`home-step-name`,children:e.name}),(0,A.jsx)(`span`,{className:`home-step-action`,children:e.action})]},e.name))})]})}var LU=new Set([`transferred`,`supervisor_ended`]),RU={escalated:{pill:`red`,tint:`red`},"low score":{pill:`amber`,tint:`amber`},"promise made":{pill:`indigo`,tint:`indigo`}},zU={escalated:`escalated`,low_score:`low score`,promise:`promise made`};function BU(){let e=new Date().getHours();return e<12?`Good morning`:e<19?`Good afternoon`:`Good evening`}function VU(e){let t=[];for(let n of e){let{score:e}=n,r=n.line;if(r.flags!==void 0&&r.flags!==null){let e=r.flags.map(e=>zU[e]).find(e=>e!==void 0);e!==void 0&&t.push({row:n,flag:e,reason:r.score?.reason??r.outcome??``});continue}if(r.end_reason!==null&&LU.has(r.end_reason))t.push({row:n,flag:`escalated`,reason:r.outcome??(r.end_reason===`transferred`?`Handed to a person`:`A supervisor ended it`)});else if(e!==null&&e.passed===!1){let i=e.judges.find(e=>e.verdict===`broken`);t.push({row:n,flag:`low score`,reason:i?.reason??r.outcome??`A judge did not hold`})}}return t}function HU(e){let t=e.filter(e=>!e.live);return t.length===0?null:t.filter(e=>e.end_reason===null||!LU.has(e.end_reason)).length/t.length}function UU(){let e=wh(),{lines:t,live:n,insights:r}=Xy(),i=ng(),a=rg(t,i.today),o=rg(t,i.yesterday),s=VU(oV(a)),c=(e?.name??``).split(` `)[0]??``,l=ug(i.yesterday),u=r?.conversations.today??a.length,d=ig(u,r?.conversations.yesterday??o.length),f=r===null?HU(a):r.resolved_rate,p=r===null?HU(o):l?.resolved_rate??null,m=f===null||p===null?null:Math.round((f-p)*100),h=r?.spend_eur??a.reduce((e,t)=>e+(t.cost?.eur??0),0),g=r?.budget.limit_eur??null,_=n.length===0?`Nobody on a call right now`:n.length===1?`One call on the floor`:`${n.length} calls on the floor`,v=s.length===0?`nothing needs a look`:s.length===1?`one conversation needs a look`:`${s.length} conversations need a look`;return(0,A.jsxs)(sh,{children:[(0,A.jsx)(ch,{title:c===``?BU():`${BU()}, ${c}`,lede:`${_}, ${v}, everything else handled.`}),(0,A.jsxs)(lh,{min:190,children:[(0,A.jsx)(uh,{size:`big`,label:`Conversations`,value:a.length,delta:d?.text,tone:d?.tone}),(0,A.jsx)(uh,{size:`big`,label:`Resolved without a human`,value:f===null?`—`:ag(f),delta:m===null?void 0:m===0?`steady`:`${m>0?`+`:`−`}${Math.abs(m)} pts`,tone:m===null||m===0?`flat`:m>0?`up`:`down`}),r!==null&&(0,A.jsx)(GU,{insights:r,before:l}),(0,A.jsx)(uh,{size:`big`,label:`Spend today`,value:Xh(h),delta:g===null?`today`:`of €${g}`,tone:`flat`})]}),(0,A.jsxs)(`div`,{className:`home-split`,children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Needs a look`,meta:`${s.length} of ${u} today`,action:(0,A.jsx)(Am,{to:`/sessions`,children:`All sessions`})}),s.length===0&&(0,A.jsx)(Mm,{children:`Nothing today needs a look: no call went to a person, and no judge said no.`}),s.map(e=>(0,A.jsx)(Pm,{to:`/sessions/${e.row.line.call}`,lead:(0,A.jsx)(ah,{name:sg(e.row.line),tint:RU[e.flag].tint}),name:sg(e.row.line),tag:(0,A.jsx)(Qm,{tone:RU[e.flag].pill,small:!0,children:e.flag}),sub:e.reason,end:(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ui-row-end-1`,children:[e.row.line.channel??`—`,` · `,qh(e.row.line)]}),(0,A.jsx)(`div`,{className:`ui-row-end-2`,children:eg(e.row.line.started_at)})]})},e.row.line.call)),(0,A.jsxs)(jm,{children:[(0,A.jsxs)(`span`,{children:[Math.max(0,u-s.length),` more handled cleanly`]}),(0,A.jsx)(Am,{to:`/sessions`,children:`See all sessions`})]})]}),(0,A.jsxs)(`div`,{className:`home-side`,children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:(0,A.jsxs)(`span`,{className:`home-floor-title`,children:[(0,A.jsx)(eh,{tone:n.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`ui-card-title`,children:`On the floor now`})]})}),(0,A.jsxs)(`div`,{className:`home-floor`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`home-quiet`,children:`Nobody is on a call. A call that rings appears here the moment it does.`}),n.slice(0,4).map(e=>(0,A.jsxs)(`div`,{className:`home-live`,children:[(0,A.jsx)(ah,{name:sg(e),tint:`green`}),(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`home-live-name`,children:sg(e)}),(0,A.jsxs)(`div`,{className:`home-live-sub`,children:[e.agent,` · `,e.channel??`—`,` · `,Jh(e.started_at)]})]}),(0,A.jsx)(zm,{to:`/live/${e.call}`,size:`xs`,children:`Listen`})]},e.call))]})]}),(0,A.jsx)(KU,{lines:a.length>0?a:t,counted:r!==null&&u>0?r.channels:null}),(0,A.jsx)(IU,{})]})]})]})}var WU=[{channel:`phone`,name:`Phone`,color:`var(--accent)`},{channel:`web`,name:`Web`,color:`var(--accent-2)`},{channel:`whatsapp`,name:`WhatsApp`,color:`var(--accent-3)`}];function GU({insights:e,before:t}){let n=e.median_e2e_s,r=t?.median_e2e_s??null,i=`today`,a=`flat`;if(n!==null&&r!==null){let e=Math.round((n-r)*10)/10;Math.abs(e)<.1?i=`steady`:(i=`${e>0?`+`:`−`}${Math.abs(e).toFixed(1)}s`,a=e>0?`down`:`up`)}return(0,A.jsx)(uh,{size:`big`,label:`Median answer`,value:n===null?`—`:`${n.toFixed(1)}s`,delta:i,tone:a})}function KU({lines:e,counted:t}){let n=t===null?e.length:t.phone+t.web+t.whatsapp,r=n=>t===null?e.filter(e=>e.channel===n).length:t[n]??0;return(0,A.jsxs)(V,{children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Where calls arrive`})}),(0,A.jsx)(`div`,{className:`home-channels`,children:WU.map(({channel:e,name:t,color:i})=>{let a=n===0?0:r(e)/n;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`home-channel-line`,children:[(0,A.jsx)(`span`,{className:`home-channel-name`,children:t}),(0,A.jsx)(`span`,{className:`home-channel-share`,children:ag(a)})]}),(0,A.jsx)(oh,{share:a,color:i})]},e)})})]})}var qU=`minmax(0,1.2fr) 96px minmax(0,1fr) 150px 92px`;function JU(){let e=j(),t=wh(),n=Eh(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(`production`),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),_=n!==null&&n.includes(`app`),v=t?.production===!0,y=v?s:`sandbox`,b=async()=>i(await rb(e));(0,D.useEffect)(()=>{let t=!1;return rb(e).then(e=>{t||i(e)},e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let x=async t=>{if(t.preventDefault(),a.trim()===``){g(`Name what the token is for — the server or the job it will run on.`);return}u(!0),g(null);try{f(await ib(e,{label:a.trim(),env:y})),m(!1),o(``),await b()}catch(e){g(e instanceof na?e.message:String(e))}finally{u(!1)}},S=async t=>{g(null);try{await ab(e,t),await b()}catch(e){g(e instanceof na?e.message:String(e))}},C=async e=>{try{await navigator.clipboard.writeText(e),m(!0)}catch{m(!1)}};return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Tokens`,ledeWidth:640,lede:"Your own keys — one per device, what `pinecall link` writes into a project — and the tokens this org's servers run on. A server's token is the org's: it opens one world, and it stays when the person who made it leaves."}),_&&(0,A.jsx)(V,{pad:!0,children:(0,A.jsxs)(`form`,{className:`keys-form`,onSubmit:e=>void x(e),children:[(0,A.jsxs)(`div`,{className:`keys-label-field`,children:[(0,A.jsx)(`label`,{className:`ui-label`,htmlFor:`token-label`,children:`New server token`}),(0,A.jsx)(W,{id:`token-label`,value:a,placeholder:`maravilla web`,onChange:e=>o(e.target.value)})]}),(0,A.jsxs)(Hm,{className:`keys-env-select`,value:y,onChange:e=>c(e.target.value),"aria-label":`which world it opens`,children:[(0,A.jsx)(`option`,{value:`production`,disabled:!v,children:`production`}),(0,A.jsx)(`option`,{value:`sandbox`,children:`sandbox`})]}),(0,A.jsx)(U,{type:`submit`,kind:`primary`,size:`form`,disabled:l,children:l?`Making…`:`Create`}),(0,A.jsx)(`div`,{className:`keys-form-note`,children:v?`It holds the agent in that world and pushes its knowledge base in a release — nothing else.`:`Production's is made by somebody your org lets act in production.`})]})}),d!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`${d.label??`A new token`} · ${d.env}`,meta:`shown once`,action:(0,A.jsxs)(`span`,{className:`keys-minted-actions`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>void C(`PINECALL_KEY=${d.key}`),children:p?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>f(null),children:`Done`})]})}),(0,A.jsxs)(`pre`,{className:`ui-code`,children:[`PINECALL_KEY=`,d.key]}),(0,A.jsx)(`div`,{className:`keys-minted-warn`,children:`Copy it now and put it in your server's secrets: the gateway keeps its fingerprint, and this token is never shown again.`})]}),(0,A.jsx)(Nm,{children:h}),(0,A.jsx)(V,{children:r!==null&&r.length===0?(0,A.jsx)(Mm,{children:"No token yet. A server's is made above; yours is made by `pinecall link`."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:qU,labels:[`Name`,`World`,`Whose`,`Last used`,`Status>`]}),(r??[]).map(e=>(0,A.jsx)(YU,{row:e,stop:S},e.fingerprint))]})})]})}function YU({row:e,stop:t}){let[n,r]=(0,D.useState)(!1),i=e.revoked_at!==null,a=e.kind===`person`?`${e.name??`a person`} · their own`:`the org's${e.created_by===null?``:` · made by ${e.created_by}`}`;return(0,A.jsxs)(`div`,{className:`ui-table-row keys-row`,style:{gridTemplateColumns:qU},onMouseLeave:()=>r(!1),children:[(0,A.jsx)(`span`,{className:i?`keys-name keys-name-gone`:`keys-name`,title:e.fingerprint,children:e.label??e.fingerprint.slice(0,12)}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:e.env??`—`}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:a}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:e.last_used_at===null?`never`:Qh(Date.parse(e.last_used_at)/1e3)}),(0,A.jsxs)(`span`,{className:`ui-cell-end`,children:[!i&&(0,A.jsx)(`span`,{className:n?`keys-revoke keys-revoke-sure`:`keys-revoke`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>n?void t(e.fingerprint):r(!0),children:n?`Revoke it`:`Revoke`})}),i?(0,A.jsx)(Qm,{tone:`gray`,children:`revoked`}):(0,A.jsx)(Qm,{tone:`green`,children:`active`})]})]})}var XU=`/v1/lexicon`;async function ZU(e){return xy.parse(await k(e,XU))}async function QU(e,t,n,r,i){return xy.parse(await oa(e,XU,{lexicon:t,if_version:n,note:r,team:i}))}function $U(e){return e instanceof Error?e.message:String(e)}function eW(e){return{said:[...e?.lexicon.said??[]],heard:[...e?.lexicon.heard??[]]}}function tW(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)({said:[],heard:[]}),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(``),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(null),[y,b]=(0,D.useState)(null),x=fm===`hosted`;(0,D.useEffect)(()=>{let t=!1;return ZU(e).then(e=>{t||(n(e),i(eW(x?e.production:e.yours??e.team)))},e=>!t&&v($U(e))),()=>{t=!0}},[e]);let S=t===null?null:x?t.production:a?t.team:t.yours,C=async o=>{if(o.preventDefault(),t===null)return;g(`Saving…`),v(null);let s={said:r.said,heard:r.heard};try{let t=await QU(e,s,S?.version??null,p.trim()===``?null:p.trim(),a);n(t),i(eW(x?t.production:a?t.team:t.yours??t.team)),m(``),b(`Kept as the next version. Every agent of the org says it from its next call in this corner.`)}catch(e){v($U(e))}finally{g(null)}};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Lexicon`,ledeWidth:640,lede:`The org's words, laid over every agent's own: how the voice says a brand, a surname, an acronym, and which words the ears must know. Whole and versioned; a word said wrong is fixed by whoever hears it.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Where every corner is`,meta:t?.world}),t===null?(0,A.jsx)(Mm,{children:_??`Asking the gateway…`}):(0,A.jsx)(`div`,{className:`lex-corners`,children:[`yours`,`team`,`production`].map(e=>(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:e}),` `,t[e]===null?`nothing set`:`v${t[e].version} · ${t[e].author} · ${Qh(t[e].set_at)}`]},e))})]}),t!==null&&(0,A.jsxs)(`form`,{className:`ui-card`,onSubmit:e=>void C(e),children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:x?`What production says`:`The words`}),!x&&(0,A.jsx)(Ym,{checked:a,onChange:e=>{o(e),i(eW(e?t.team:t.yours??t.team))},children:`the team's corner`})]}),(0,A.jsxs)(`div`,{className:`lex-body`,children:[(0,A.jsxs)(`div`,{className:`lex-said`,children:[(0,A.jsx)(`div`,{className:`ui-label`,children:`Said`}),r.said.length===0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:`No word is said any other way than written.`}),r.said.map(e=>(0,A.jsxs)(`div`,{className:`lex-pair`,children:[(0,A.jsx)(`span`,{className:`lex-word`,children:e.word}),(0,A.jsx)(`span`,{className:`lex-arrow`,children:`→`}),(0,A.jsxs)(`span`,{className:`lex-spoken`,children:[`“`,e.spoken,`”`]}),(0,A.jsx)(Bm,{danger:!0,onClick:()=>i({...r,said:r.said.filter(t=>t.word!==e.word)}),children:`Remove`})]},e.word)),(0,A.jsxs)(`div`,{className:`lex-add`,children:[(0,A.jsx)(W,{size:`sm`,value:s,placeholder:`the word, as written`,onChange:e=>c(e.target.value)}),(0,A.jsx)(W,{size:`sm`,value:l,placeholder:`how it is said`,onChange:e=>u(e.target.value)}),(0,A.jsx)(U,{size:`sm`,onClick:()=>{s.trim()!==``&&l.trim()!==``&&(i({...r,said:[...r.said.filter(e=>e.word!==s.trim()),{word:s.trim(),spoken:l.trim()}]}),c(``),u(``))},children:`Add`})]})]}),(0,A.jsxs)(`div`,{className:`lex-heard`,children:[(0,A.jsx)(`div`,{className:`ui-label`,children:`Heard`}),r.heard.length===0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:`The ears know only what each class declares.`}),(0,A.jsx)(`div`,{className:`lex-chips`,children:r.heard.map(e=>(0,A.jsxs)(`span`,{className:`ui-pill-muted lex-chip`,children:[e,(0,A.jsx)(Bm,{onClick:()=>i({...r,heard:r.heard.filter(t=>t!==e)}),children:`×`})]},e))}),(0,A.jsxs)(`div`,{className:`lex-add`,children:[(0,A.jsx)(W,{size:`sm`,value:d,placeholder:`words the ears must know, comma-separated`,onChange:e=>f(e.target.value)}),(0,A.jsx)(U,{size:`sm`,onClick:()=>{let e=d.split(/[,\n]/).map(e=>e.trim()).filter(e=>e!==``&&!r.heard.includes(e));e.length>0&&i({...r,heard:[...r.heard,...e]}),f(``)},children:`Add`})]})]})]}),(0,A.jsxs)(`div`,{className:`pipe-save`,children:[(0,A.jsx)(W,{value:p,placeholder:`why, for the history`,onChange:e=>m(e.target.value)}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:h!==null,children:h??`Save as the next version`})]})]}),y!==null&&(0,A.jsx)(`div`,{className:`ui-empty`,children:y}),(0,A.jsx)(Nm,{children:_})]})}var nW=[`all`,...Fh],rW=`130px minmax(0,1.6fr) 110px 92px`,iW={[Ah]:0,[Mh]:1,[Nh]:2,[jh]:3};function aW(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(`all`),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(null),h=async()=>i(await Ab(e));(0,D.useEffect)(()=>{let t=!1,r=e=>{t||m(e instanceof Error?e.message:String(e))};return Lh(e).then(e=>{t||n(e)},r),Ab(e).then(e=>{t||i(e)},r),()=>{t=!0}},[e]);let g=async t=>{t.preventDefault(),f(!0),m(null);try{await jb(e,a.trim(),s),c(``),o(``),await h()}catch(e){m(e instanceof na?e.message:String(e))}finally{f(!1)}},_=async t=>{m(null);try{await Mb(e,t),await h()}catch(e){m(e instanceof na?e.message:String(e))}},v=t?.providers??[],y=new Set(r??[]),b=(l===`all`?v:Rh(v,l)).slice().sort((e,t)=>Number(y.has(t.name))-Number(y.has(e.name))||iW[e.standing]-iW[t.standing]||e.name.localeCompare(t.name));return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Providers`,ledeWidth:660,lede:`Every vendor the runtime can reach, and what each one still wants on this box. Nothing reads a key back — not this page, not the CLI, not the log.`}),(0,A.jsxs)(V,{pad:!0,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void g(e),children:[(0,A.jsx)(Wm,{label:`Bring one`,minWidth:180,children:(0,A.jsxs)(Hm,{value:a,onChange:e=>o(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Choose a vendor…`}),v.filter(e=>e.env!==null).map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,` · `,e.does.join(` `)]},e.name))]})}),(0,A.jsx)(Wm,{label:`The key, sent once`,grow:!0,minWidth:220,children:(0,A.jsx)(W,{type:`password`,value:s,placeholder:`sk-…`,autoComplete:`off`,onChange:e=>c(e.target.value)})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:d||a.trim()===``||s===``,children:d?`Sending…`:`Bring it`})]}),(0,A.jsx)(`div`,{className:`prov-hint`,children:`A key brought here runs every call of this org from the next one; every vendor nobody brought runs on the box's own key.`})]}),(0,A.jsx)(Nm,{children:p}),(0,A.jsx)(Km,{options:nW.map(e=>({value:e,label:e===`all`?`All ${v.length}`:`${e.toUpperCase()} ${Rh(v,e).length}`})),value:l,onChange:u}),(0,A.jsx)(V,{children:b.map(e=>(0,A.jsxs)(`div`,{className:`prov-row`,style:{gridTemplateColumns:rW},title:e.aliases.length>0?`also ${e.aliases.join(` · `)}`:void 0,children:[(0,A.jsx)(`span`,{className:`prov-name`,children:e.name}),(0,A.jsxs)(`span`,{className:`prov-note`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:zh(e)}),y.has(e.name)&&(0,A.jsx)(Bm,{danger:!0,onClick:()=>void _(e.name),children:`Give back`})]}),(0,A.jsx)(`span`,{className:`prov-kinds`,children:e.does.join(` `)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(oW,{provider:e,brought:y.has(e.name)})})]},e.name))})]})}function oW({provider:e,brought:t}){return t?(0,A.jsx)(Qm,{tone:`green`,children:`your key`}):e.standing===`ready`?(0,A.jsx)(Qm,{tone:`green`,children:`ready`}):(0,A.jsx)(Qm,{tone:`gray`,children:e.standing})}var sW=z({agent:P().nullable(),base:P().nullable(),directory:P().nullable(),files:I(),golden:P().nullable(),questions:I()}),cW=iy.extend({files:I()});async function lW(e){return ay.parse(await k(e,`/v1/knowledge`))}async function uW(e,t){return sW.parse(await $S(e,t,`knowledge.roster`,{agent:t}))}async function dW(e,t,n){return cW.parse(await $S(e,t,`knowledge.push`,{agent:t,...n===``?{}:{base:n}}))}async function fW(e,t,n){return ry.parse(await $S(e,t,`knowledge.eval`,{agent:t,...n===``?{}:{base:n}}))}async function pW(e,t){await ca(e,`/v1/knowledge/${encodeURIComponent(t)}`)}var mW=`minmax(0,1fr) 90px 140px 150px 80px`;function hW(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(null),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useCallback)(async()=>{s((await lW(e)).bases)},[e]);(0,D.useEffect)(()=>{let n=!1;return v().catch(e=>{n||_(_W(e))}),uW(e,t).then(e=>{n||(r(e),l(e.base??t))},e=>{n||a(_W(e))}),()=>{n=!0}},[e,t,v]);let y=async n=>{d(n),_(null);try{n===`push`?(p(await dW(e,t,c)),await v()):h(await fW(e,t,c))}catch(e){_(_W(e))}finally{d(``)}},b=async t=>{if(window.confirm(`Drop the base ${t}? Nothing brings it back but another push.`)){_(null);try{await pW(e,t),await v()}catch(e){_(_W(e))}}},x=n!==null&&n.agent===t;return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Knowledge`,ledeWidth:620,lede:`What this agent answers from. The folder is pushed whole and the base is replaced, never merged.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`This directory`,children:x&&(0,A.jsxs)(`label`,{className:`kb-base`,children:[(0,A.jsx)(`span`,{className:`kb-base-label`,children:`base`}),(0,A.jsx)(`input`,{className:`kb-base-input`,value:c,size:Math.max(6,c.length),onChange:e=>l(e.target.value)})]})}),n===null&&i===null&&(0,A.jsxs)(Mm,{children:[`Asking the process that holds `,t,`…`]}),n===null&&i!==null&&(0,A.jsxs)(Mm,{children:[`The directory is read by the process holding `,t,`, and it did not answer: `,i,`. Bases already pushed are listed below.`]}),n!==null&&!x&&(0,A.jsx)(Mm,{children:n.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so there is nothing here to push.":`The process holding the agent runs in ${n.agent}'s directory: to push ${t}'s knowledge, run \`pinecall start\` there.`}),x&&(0,A.jsxs)(`div`,{className:`kb-here`,children:[(0,A.jsx)(`span`,{className:`kb-path`,children:n.directory??`—`}),(0,A.jsxs)(`span`,{className:`kb-count`,children:[n.files,` markdown file`,n.files===1?``:`s`]}),(0,A.jsx)(U,{size:`md`,disabled:u!==``||n.files===0,onClick:()=>void y(`push`),children:u===`push`?`Pushing…`:`Push the folder`}),(0,A.jsx)(`span`,{className:`kb-path`,children:n.golden===null?`no golden beside it`:`${n.questions} questions`}),(0,A.jsx)(U,{size:`md`,disabled:u!==``||n.golden===null,onClick:()=>void y(`eval`),children:u===`eval`?`Asking…`:`Run the golden`})]}),f!==null&&(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[`Pushed `,f.base,` · `,f.files,` files · `,f.chunks,` chunks · `,Math.round(f.took_ms),` ms`]})]}),(0,A.jsx)(Nm,{children:g}),m!==null&&(0,A.jsx)(gW,{score:m}),(0,A.jsx)(V,{children:o!==null&&o.length===0?(0,A.jsx)(Mm,{children:"No base pushed yet. Push the folder above, or `pinecall knowledge push` from the project."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:mW,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,`Action>`]}),(o??[]).map(e=>(0,A.jsxs)(fh,{columns:mW,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.base}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.model}),(0,A.jsx)(`span`,{className:`ui-cell`,children:Qh(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void b(e.base),children:`Drop`})})]},e.base))]})})]})}function gW({score:e}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The golden`,meta:`${e.base} · ${e.model} · ${e.questions} questions · ${Math.round(e.took_ms)} ms`}),(0,A.jsxs)(`div`,{className:`kb-figures`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`kb-figure-label`,children:[`recall@`,e.k]}),(0,A.jsx)(`div`,{className:`kb-figure`,children:e.recall_at_k.toFixed(2)})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`kb-figure-label`,children:`nDCG@10`}),(0,A.jsx)(`div`,{className:`kb-figure`,children:e.ndcg_at_10.toFixed(2)})]})]}),e.misses.length===0?(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`Every question found what it asked for.`}):e.misses.map(e=>(0,A.jsxs)(`div`,{className:`kb-miss`,children:[(0,A.jsx)(`div`,{className:`kb-miss-asks`,children:e.asks}),(0,A.jsxs)(`div`,{className:`kb-miss-why`,children:[`wanted `,e.expects,` · got `,e.found[0]??`nothing`]})]},e.asks))]})}function _W(e){return e instanceof na||e instanceof Error?e.message:String(e)}var vW=`150px minmax(0,1fr) 110px 76px`;function yW(e){return e.startsWith(`+`)?og(e):e}function bW(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(void 0),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(null),f=(0,D.useCallback)(async()=>{r(await bT(e,t))},[e,t]);(0,D.useEffect)(()=>{let n=!1;return bT(e,t).then(e=>{n||r(e)},e=>{n||(r(null),d(CW(e)))}),()=>{n=!0}},[e,t]);let p=async t=>{t.preventDefault();let n=i.trim();d(null),l(null);try{s({contact:n,facts:(await mT(e,n)).facts})}catch(e){d(CW(e))}},m=async t=>{if(window.confirm(`Erase everything memory kept about ${t}? There is no undo.`)){d(null);try{let r=(await hT(e,t)).forgotten;l(`${r} fact${r===1?``:`s`} about ${yW(t)} forgotten.`),s({contact:t,facts:[]}),n!=null&&await f()}catch(e){d(CW(e))}}},h=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${yW(t.contact)} stays.`)){d(null);try{await xT(e,t.id),await f()}catch(e){d(CW(e))}}},g=n!=null,_=g?n.filter(e=>i.trim()===``||e.contact.includes(i.trim())):[];return(0,A.jsxs)(sh,{width:900,tight:!0,children:[(0,A.jsx)(ch,{title:`Memory`,ledeWidth:620,lede:`What this agent carries between calls with the same caller — written by the agent, readable here, and droppable one row at a time.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Callers`,children:(0,A.jsxs)(`form`,{className:`mem-look`,onSubmit:e=>void p(e),children:[(0,A.jsx)(W,{size:`sm`,value:i,placeholder:`Look up a caller — a number or an id`,onChange:e=>a(e.target.value)}),!g&&(0,A.jsx)(U,{size:`sm`,type:`submit`,disabled:i.trim()===``,children:`Look up`}),o!==null&&o.facts.length>0&&(0,A.jsx)(U,{size:`sm`,kind:`danger`,onClick:()=>void m(o.contact),children:`Forget`})]})}),c!==null&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:c}),g?_.length===0?(0,A.jsx)(Mm,{children:n.length===0?`Memory keeps nothing about any caller of this agent yet.`:`No caller matches.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:vW,labels:[`Caller`,`Remembered`,`Written`,`Action>`]}),_.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:vW},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:yW(e.contact)}),(0,A.jsx)(`span`,{className:`mem-fact`,children:e.text}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:$h(e.written_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void h(e),children:`Drop`})})]},e.id))]}):o===null?(0,A.jsx)(Mm,{children:`Look up a caller by the number they called from, or by the id your app named them with, to read what memory keeps about them.`}):o.facts.length===0?(0,A.jsxs)(Mm,{children:[`Memory keeps nothing about `,yW(o.contact),`.`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:vW,labels:[`Caller`,`Remembered`,`Written`,`Category>`]}),o.facts.map((e,t)=>(0,A.jsxs)(`div`,{className:e.invalidated_at===null?`ui-table-row`:`ui-table-row mem-gone`,style:{gridTemplateColumns:vW},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,children:yW(o.contact)}),(0,A.jsxs)(`span`,{className:`mem-fact`,children:[e.text,e.invalidated_at!==null&&(0,A.jsxs)(`span`,{className:`mem-superseded`,children:[` · superseded `,$h(e.invalidated_at)]})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:$h(e.valid_from)}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip mem-category`,children:e.category??`—`})]},e.id??`${t}`))]})]}),(0,A.jsx)(Nm,{children:u}),(0,A.jsx)(xW,{agent:t})]})}function xW({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(null),[f,p]=(0,D.useState)(null);(0,D.useEffect)(()=>{let n=!1;return gT(t,e).then(e=>{n||r(e)},e=>{n||a(CW(e))}),()=>{n=!0}},[t,e]);let m=async n=>{s(n),p(null);try{n===`recall`?l(await _T(t,e)):d(await vT(t,e))}catch(e){p(CW(e))}finally{s(``)}};return n===null?i===null?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The goldens of this directory`}),(0,A.jsxs)(Mm,{children:[`They are read by the process holding `,e,`, and it did not answer: `,i,`.`]})]}):n.agent===e?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-goldens`,children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Recall`,meta:`${n.questions} questions`}),(0,A.jsxs)(`div`,{className:`mem-run`,children:[(0,A.jsx)(`p`,{className:`mem-say`,children:`Every question asked of the ranking, scored by code with no model. No contact of yours is read: each question brings its own facts to a scratch contact.`}),(0,A.jsx)(U,{size:`md`,disabled:o!==``||n.questions===0,onClick:()=>void m(`recall`),children:o===`recall`?`Asking…`:`Run it`})]}),c!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-figures`,children:[(0,A.jsx)(SW,{label:`recall@${c.k}`,value:c.recall_at_k.toFixed(2)}),(0,A.jsx)(SW,{label:`nDCG@10`,value:c.ndcg_at_10.toFixed(2)}),(0,A.jsx)(SW,{label:`missed`,value:String(c.misses.length)})]}),c.misses.map(e=>(0,A.jsxs)(`div`,{className:`mem-miss`,children:[(0,A.jsx)(`div`,{className:`mem-miss-asks`,children:e.asks}),(0,A.jsxs)(`div`,{className:`mem-miss-why`,children:[`wanted `,e.missing.join(`, `),` · got `,e.found[0]??`nothing`]})]},e.asks))]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Extraction`,meta:`${n.cases.length} cases`}),(0,A.jsxs)(`div`,{className:`mem-run`,children:[(0,A.jsx)(`p`,{className:`mem-say`,children:`One call written down per case, and one model call each — the very one a hang-up makes. Which categories got a fact, which never did, what must not survive.`}),(0,A.jsx)(U,{size:`md`,disabled:o!==``||n.cases.length===0,onClick:()=>void m(`extraction`),children:o===`extraction`?`Running…`:`Run them`})]}),u!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-figures`,children:[(0,A.jsx)(SW,{label:`held`,value:`${u.held}/${u.cases}`}),(0,A.jsx)(SW,{label:`model`,value:u.model})]}),u.results.filter(e=>!e.held).map(e=>(0,A.jsxs)(`div`,{className:`mem-miss`,children:[(0,A.jsx)(`div`,{className:`mem-miss-asks`,children:e.name}),(0,A.jsx)(`div`,{className:`mem-miss-why`,children:(e.broke??[]).map(e=>`${e.check}: ${e.detail}`).join(` · `)})]},e.name))]})]})]}),(0,A.jsx)(Nm,{children:f})]}):(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The goldens of this directory`}),(0,A.jsx)(Mm,{children:n.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so its goldens are not here.":`The process holding the agent runs in ${n.agent}'s directory: to run ${e}'s memory goldens, run \`pinecall start\` there.`})]})}function SW({label:e,value:t}){return(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`mem-figure-label`,children:e}),(0,A.jsx)(`div`,{className:`mem-figure ui-clip`,children:t})]})}function CW(e){return e instanceof na||e instanceof Error?e.message:String(e)}function wW({carrier:e,agents:t,available:n,busy:r,onImport:i,onBuy:a,onDone:o,onClose:s}){let[c,l]=(0,D.useState)(e===null?`buy`:`import`),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(`US`),[m,h]=(0,D.useState)(``),[g,_]=(0,D.useState)(t[0]?.slug??``),[v,y]=(0,D.useState)(null);(0,D.useEffect)(()=>{g===``&&t[0]!==void 0&&_(t[0].slug)},[t,g]);let b=()=>y(null),x=async e=>c===`import`?i({number:u.trim(),agent:g},e):a({country:f.trim().toUpperCase(),...m.trim()===``?{}:{area_code:m.trim()},agent:g},e),S=async e=>{e.preventDefault(),y(await x(!0).catch(()=>null))},C=async()=>{let e=await x(!1).catch(()=>null);e!==null&&(y(null),d(``),o(e))},w=n!==null&&n.kind===`twilio`?n.numbers.filter(e=>!e.imported):[],T=e=>{l(e),b()};return(0,A.jsxs)(`div`,{className:`num-add`,children:[(0,A.jsxs)(`div`,{className:`num-add-head`,children:[(0,A.jsxs)(`div`,{className:`ui-segmented`,role:`group`,children:[(0,A.jsx)(`button`,{type:`button`,className:c===`import`?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":c===`import`,onClick:()=>T(`import`),disabled:e===null,title:e===null?`connect your phone carrier first, in the Carrier tab`:void 0,children:w.length>0?`I already have one · ${w.length}`:`I already have one`}),(0,A.jsx)(`button`,{type:`button`,className:c===`buy`?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":c===`buy`,onClick:()=>T(`buy`),children:`Buy a new one`})]}),(0,A.jsx)(`button`,{type:`button`,className:`ui-text-action num-add-close`,onClick:s,children:`Close`})]}),(0,A.jsxs)(`form`,{onSubmit:e=>void S(e),children:[(0,A.jsxs)(`div`,{className:c===`buy`?`num-fields num-fields-3`:`num-fields`,children:[c===`import`?(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Number`}),w.length>0?(0,A.jsxs)(Hm,{value:u,onChange:e=>{d(e.target.value),b()},required:!0,children:[(0,A.jsx)(`option`,{value:``,children:`Choose a number…`}),w.map(e=>(0,A.jsxs)(`option`,{value:e.number,children:[og(e.number),` — `,e.name]},e.number))]}):(0,A.jsx)(W,{value:u,onChange:e=>{d(e.target.value),b()},placeholder:`+14176743169`,required:!0,autoComplete:`off`})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Country · two letters`}),(0,A.jsx)(W,{value:f,onChange:e=>{p(e.target.value),b()},maxLength:2,required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Area code · optional`}),(0,A.jsx)(W,{value:m,onChange:e=>{h(e.target.value),b()},placeholder:`417`,autoComplete:`off`})]})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Agent that answers`}),t.length>0?(0,A.jsx)(Hm,{value:g,onChange:e=>{_(e.target.value),b()},required:!0,children:t.map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.slug))}):(0,A.jsx)(W,{value:g,onChange:e=>{_(e.target.value),b()},placeholder:`the agent's slug`,required:!0,autoComplete:`off`})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(U,{kind:`primary`,type:`submit`,disabled:r||v!==null,children:r&&v===null?`Checking…`:`Review`}),(0,A.jsx)(`span`,{className:`num-note`,children:c===`import`?`Nothing changes yet — you will see exactly what is going to happen, and confirm.`:`Nothing is bought yet — you will see the number that was found, and confirm.`})]})]}),v!==null&&(0,A.jsxs)(`div`,{className:`num-plan`,children:[(0,A.jsxs)(`div`,{className:`num-plan-title`,children:[`This is what will happen`,c===`buy`&&v.route.number!==null?(0,A.jsxs)(A.Fragment,{children:[` with `,og(v.route.number)]}):null,`. Nothing is deleted.`]}),(0,A.jsx)(TW,{steps:v.steps}),(0,A.jsxs)(`div`,{className:`num-plan-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,onClick:()=>void C(),disabled:r,children:r?`Working…`:c===`buy`?`Buy it and connect it`:`Confirm`}),(0,A.jsx)(U,{size:`md`,onClick:b,disabled:r,children:`Cancel`})]})]})]})}function TW({steps:e}){return(0,A.jsx)(`ol`,{className:`num-steps`,children:e.map((e,t)=>{let[n,...r]=e.split(/\s+/);return(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`num-step-kind`,children:n}),(0,A.jsx)(`span`,{className:`num-step-text`,children:r.join(` `)})]},t)})})}function EW({carrier:e,busy:t,onBring:n,onDrop:r}){let[i,a]=(0,D.useState)(!1);return e!==null&&!i?(0,A.jsxs)(`div`,{className:`ui-card num-carrier`,children:[(0,A.jsx)(`span`,{className:`num-kind`,children:e.kind.toUpperCase()}),(0,A.jsx)(`span`,{className:`num-carrier-standing`,children:e.kind===`twilio`?`Account connected`:`SIP peer connected`}),(0,A.jsx)(`span`,{className:`num-carrier-account`,children:e.account}),(0,A.jsxs)(`span`,{className:`num-carrier-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>a(!0),disabled:t,children:`Change`}),(0,A.jsx)(U,{size:`xs`,kind:`danger`,onClick:()=>void r(),disabled:t,children:`Disconnect`})]})]}):(0,A.jsx)(DW,{busy:t,onBring:async e=>{await n(e),a(!1)},onCancel:e===null?null:()=>a(!1)})}function DW({busy:e,onBring:t,onCancel:n}){let[r,i]=(0,D.useState)(`twilio`),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(``),[h,g]=(0,D.useState)(``),[_,v]=(0,D.useState)(``),[y,b]=(0,D.useState)(`auto`),[x,S]=(0,D.useState)(``),[C,w]=(0,D.useState)(``);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Connect your phone carrier`,children:(0,A.jsxs)(`div`,{className:`ui-segmented num-ways`,role:`group`,children:[(0,A.jsx)(`button`,{type:`button`,className:r===`twilio`?`ui-segment ui-segment-on`:`ui-segment`,onClick:()=>i(`twilio`),children:`Twilio`}),(0,A.jsx)(`button`,{type:`button`,className:r===`sip`?`ui-segment ui-segment-on`:`ui-segment`,onClick:()=>i(`sip`),children:`SIP peer`})]})}),(0,A.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),t(r===`twilio`?{kind:r,account_sid:a.trim(),user:s.trim()||a.trim(),secret:l}:{kind:r,username:d.trim(),password:p,addresses:h.split(/[\s,]+/).filter(Boolean),..._.trim()===``?{}:{outbound_host:_.trim(),outbound_transport:y,...x.trim()===``?{}:{outbound_username:x.trim()},...C===``?{}:{outbound_password:C}}})},children:[(0,A.jsx)(`div`,{className:`num-fields num-fields-3`,children:r===`twilio`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Account SID`}),(0,A.jsx)(W,{value:a,onChange:e=>o(e.target.value),placeholder:`AC…`,required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`API key SID · or the account SID`}),(0,A.jsx)(W,{value:s,onChange:e=>c(e.target.value),placeholder:`SK…`,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Secret · the key's, or the auth token`}),(0,A.jsx)(W,{type:`password`,value:l,onChange:e=>u(e.target.value),required:!0,autoComplete:`off`})]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Username`}),(0,A.jsx)(W,{value:d,onChange:e=>f(e.target.value),required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Password`}),(0,A.jsx)(W,{type:`password`,value:p,onChange:e=>m(e.target.value),required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Networks its calls come from · CIDR`}),(0,A.jsx)(W,{value:h,onChange:e=>g(e.target.value),placeholder:`203.0.113.0/24`,required:!0,autoComplete:`off`})]})]})}),r===`sip`&&(0,A.jsxs)(`div`,{className:`num-outbound-group`,children:[(0,A.jsx)(`div`,{className:`num-outbound-title`,children:`Outbound`}),(0,A.jsx)(`div`,{className:`num-outbound-say`,children:`Where this box sends a call it places. Leave empty for a peer you only receive from.`}),(0,A.jsxs)(`div`,{className:`num-fields num-fields-4 num-fields-flush`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Host · and port`}),(0,A.jsx)(W,{value:_,onChange:e=>v(e.target.value),placeholder:`sip.carrier.example:5060`,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Transport`}),(0,A.jsxs)(Hm,{value:y,onChange:e=>b(e.target.value),children:[(0,A.jsx)(`option`,{value:`auto`,children:`auto`}),(0,A.jsx)(`option`,{value:`udp`,children:`udp`}),(0,A.jsx)(`option`,{value:`tcp`,children:`tcp`}),(0,A.jsx)(`option`,{value:`tls`,children:`tls`})]})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Username · else the one above`}),(0,A.jsx)(W,{value:x,onChange:e=>S(e.target.value),autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Password · else the one above`}),(0,A.jsx)(W,{type:`password`,value:C,onChange:e=>w(e.target.value),autoComplete:`off`})]})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(U,{kind:`primary`,type:`submit`,disabled:e,children:e?`Connecting…`:`Connect`}),n!==null&&(0,A.jsx)(U,{onClick:n,children:`Cancel`}),(0,A.jsx)(`span`,{className:`num-note`,children:r===`twilio`?`The account is checked once. The credentials are stored encrypted and never shown again.`:`Calls are accepted only from these networks, with this username and password.`})]})]})]})}var OW=/^\+[1-9]\d{6,14}$/;function kW(e){let t=e.toLowerCase();return t.includes(`no outbound trunk`)?`Outbound calls are not turned on yet.`:t.includes(`carrier`)?(0,A.jsxs)(A.Fragment,{children:[`Connect a carrier first — `,(0,A.jsx)(Wi,{to:`/numbers?tab=carrier`,children:`Carrier`}),`.`]}):t.includes(`number`)?(0,A.jsxs)(A.Fragment,{children:[`Add a number first — `,(0,A.jsx)(Wi,{to:`/numbers`,children:`Numbers`}),`.`]}):e.replace(/:?\s*(POST|PUT|GET|DELETE) \/v1\/\S+.*$/,``).trim()}function AW(e){return[e.dial_anywhere?`Agents can call any number`:`Agents can only call numbers that already contacted you`,`${e.per_minute} a minute`,`${e.per_day} a day`,`${Math.round(e.max_duration_s/60)} min per call`].join(` · `)}function jW({outbound:e,agents:t,busy:n,onProvision:r}){let[i,a]=(0,D.useState)(null);if(e===null)return(0,A.jsx)(V,{children:(0,A.jsxs)(`div`,{className:`num-hero`,children:[(0,A.jsx)(`div`,{className:`num-hero-title`,children:`Let your agents call people back`}),(0,A.jsxs)(`p`,{className:`num-hero-say`,children:[`Calls go out from your own numbers through your carrier account. Connect a carrier first — `,(0,A.jsx)(Wi,{to:`/numbers?tab=carrier`,children:`Carrier`}),`.`]})]})});let o=()=>void r(!0).then(a,()=>void 0),s=i!==null&&(0,A.jsxs)(`div`,{className:`num-plan`,children:[(0,A.jsx)(`div`,{className:`num-plan-title`,children:`What will happen — on your carrier account and on this gateway. Nothing is deleted.`}),(0,A.jsx)(TW,{steps:i.steps}),(0,A.jsxs)(`div`,{className:`num-plan-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,onClick:()=>void r(!1).then(()=>a(null),()=>void 0),disabled:n,children:n?`Working…`:`Confirm`}),(0,A.jsx)(U,{size:`md`,onClick:()=>a(null),disabled:n,children:`Cancel`})]})]});if(!e.ready){let t=e.steps_missing.every(e=>e.toLowerCase().includes(`no outbound trunk`));return(0,A.jsxs)(V,{children:[(0,A.jsxs)(`div`,{className:`num-hero`,children:[(0,A.jsx)(`div`,{className:`num-hero-title`,children:`Let your agents call people back`}),(0,A.jsx)(`p`,{className:`num-hero-say`,children:`Calls go out from your own numbers through your carrier account.`}),e.steps_missing.filter(e=>!e.toLowerCase().includes(`no outbound trunk`)).map(e=>(0,A.jsx)(`p`,{className:`num-hero-missing`,children:kW(e)},e)),t&&(0,A.jsxs)(`div`,{className:`num-hero-move`,children:[(0,A.jsx)(U,{kind:`primary`,onClick:o,disabled:n||i!==null,children:n&&i===null?`Checking…`:`Turn on outbound calls`}),(0,A.jsx)(`span`,{className:`num-note`,children:`You will see what is going to happen, and confirm.`})]})]}),s]})}let[c,...l]=e.from_numbers;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`num-on`,children:[(0,A.jsx)(eh,{tone:`green`}),(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:`On`}),` — agents call from `,og(c),l.length>0&&` and ${l.length} more`]})]}),(0,A.jsx)(MW,{agents:t,from:e.from_numbers}),(0,A.jsxs)(`div`,{className:`num-limits`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`num-limits-say`,children:AW(e.guards)}),(0,A.jsx)(`div`,{className:`num-limits-who`,children:`Limits are set by whoever runs this gateway.`})]}),(0,A.jsx)(Bm,{onClick:o,disabled:n||i!==null,children:`Repair the setup`})]}),i!==null&&(0,A.jsx)(V,{children:s})]})}function MW({agents:e,from:t}){let n=j(),[r,i]=(0,D.useState)(e[0]?.slug??``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(t[0]??``),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(null);(0,D.useEffect)(()=>{r===``&&e[0]!==void 0&&i(e[0].slug)},[e,r]);let h=async e=>{e.preventDefault();let i=a.replace(/[\s()-]/g,``);if(f(null),!OW.test(i)){m(`Write the number with its country code, like +34600000000.`);return}u(!0),m(null);try{f(await Db(n,r,i,t.length>1?s:void 0))}catch(e){m(e instanceof na?e.message:String(e))}finally{u(!1)}};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Make a test call`,meta:`the agent rings the number and talks when it is answered`}),(0,A.jsxs)(`form`,{onSubmit:e=>void h(e),children:[(0,A.jsxs)(`div`,{className:t.length>1?`num-fields num-fields-3`:`num-fields`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Agent`}),(0,A.jsx)(Hm,{value:r,onChange:e=>i(e.target.value),required:!0,children:e.map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.slug))})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Number to call`}),(0,A.jsx)(W,{value:a,onChange:e=>o(e.target.value),placeholder:`+34 600 000 000`,required:!0,autoComplete:`off`})]}),t.length>1&&(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`From`}),(0,A.jsx)(Hm,{value:s,onChange:e=>c(e.target.value),children:t.map(e=>(0,A.jsx)(`option`,{value:e,children:og(e)},e))})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(U,{kind:`primary`,type:`submit`,disabled:l||r===``,children:l?`Calling…`:`Call`}),d!==null&&(0,A.jsxs)(`span`,{className:`num-placed`,children:[`Ringing. `,(0,A.jsx)(Wi,{to:`/live/${d}`,children:`Watch it live`})]})]}),p!==null&&(0,A.jsx)(`div`,{className:`num-refused`,children:(0,A.jsx)(Nm,{children:p})})]})]})}var NW=[{tab:`numbers`,name:`Numbers`},{tab:`outbound`,name:`Outbound calls`},{tab:`carrier`,name:`Carrier`}];function PW(){let e=j(),{agents:t}=Xy(),[n,r]=Xi(),i=NW.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`numbers`,[a,o]=(0,D.useState)(void 0),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),{world:p}=kh(),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!1),[b,x]=(0,D.useState)(null),S=(0,D.useCallback)(async()=>{let[t,n]=await Promise.all([hb(e),mb(e)]);o(t),c(n),u(t===null?null:await vb(e)),f(t===null?null:await wb(e).catch(()=>null))},[e]);(0,D.useEffect)(()=>{let e=!1;return S().catch(t=>{e||_(FW(t))}),()=>{e=!0}},[S]);let C=async e=>{h(!0),_(null);try{let t=await e();return await S(),t}catch(e){throw _(FW(e)),e}finally{h(!1)}},w=(s??[]).filter(e=>e.route.number!==null),T=(s??[]).filter(e=>e.route.number===null);return(0,A.jsxs)(sh,{width:900,children:[(0,A.jsx)(ch,{title:`Phone numbers`,lede:`The numbers people call, which agent picks up, and the calls your agents place.`}),(0,A.jsx)(yh,{label:`Phone numbers`,tabs:NW.map(e=>e.tab===`outbound`&&a!==void 0?{...e,mark:(0,A.jsx)(eh,{tone:d?.ready?`green`:`amber`,small:!0})}:e),on:i,onPick:e=>r(e===`numbers`?{}:{tab:e})}),(0,A.jsx)(Nm,{children:g}),i===`numbers`&&s!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Numbers in ${p}`,action:!v&&a!==void 0?(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>{x(null),y(!0)},children:`Add a number`}):void 0}),w.length===0&&(0,A.jsxs)(Mm,{children:[`No phone number rings in `,p,` yet.`]}),w.map(t=>(0,A.jsxs)(`div`,{className:`num-row`,children:[(0,A.jsx)(`span`,{className:`num-number`,children:og(t.route.number)}),(0,A.jsx)(`span`,{className:`num-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(`span`,{className:`num-agent`,children:t.route.agent}),t.route.managed&&(0,A.jsx)(`span`,{title:`bought by the box for this org`,children:(0,A.jsx)(Qm,{tone:`violet`,children:`bought`})}),t.source===`operator`&&(0,A.jsx)(U,{kind:`danger`,size:`xs`,className:`num-remove`,disabled:m,title:`The number stops ringing this agent. It stays in your carrier account.`,onClick:()=>void C(()=>xb(e,t.route.number??``)).catch(()=>void 0),children:`Remove`})]},t.route.number)),b!==null&&(0,A.jsxs)(`div`,{className:`num-added`,children:[`Done. `,og(b.route.number),` now rings `,b.route.agent,`.`]}),v&&a!==void 0&&(0,A.jsx)(wW,{carrier:a,agents:t,available:l,busy:m,onImport:(t,n)=>C(()=>yb(e,{...t,channel:`phone`},n)),onBuy:(t,n)=>C(()=>bb(e,{...t,channel:`phone`},n)),onDone:e=>{x(e),y(!1)},onClose:()=>y(!1)}),T.length>0&&(0,A.jsxs)(`div`,{className:`num-foot`,children:[`Also on the web, with no number needed: `,[...new Set(T.map(e=>e.route.agent))].join(`, `),`.`]})]}),i===`outbound`&&a!==void 0&&(0,A.jsx)(jW,{outbound:d,agents:t,busy:m,onProvision:t=>C(()=>Tb(e,t))}),i===`carrier`&&a!==void 0&&(0,A.jsx)(EW,{carrier:a,busy:m,onBring:async t=>{await C(()=>gb(e,t)).catch(()=>void 0)},onDrop:async()=>{await C(()=>_b(e)).catch(()=>void 0)}})]})}function FW(e){return e instanceof na?e.message:String(e)}function IW(){let e=j(),t=Gh(wh()),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)([]);(0,D.useEffect)(()=>{let t=!1;return k(e,`/v1/line/numbers`).then(e=>{if(t)return;let n=e;r(n.numbers),a(n.calling??[])},()=>void 0),()=>{t=!0}},[e]);let o=Xy().held.filter(e=>t!==null&&e.holder?.holder===t);return(0,A.jsxs)(sh,{width:900,children:[(0,A.jsx)(ch,{title:`Phone testing`,ledeWidth:660,lede:(0,A.jsxs)(A.Fragment,{children:[`Call the number your customers call, from your own mobile, and `,(0,A.jsx)(`b`,{children:`your copy answers`}),`. Everybody else who calls still reaches production. You do not need a sandbox number.`]})}),(0,A.jsxs)(V,{children:[(0,A.jsx)(Im,{children:`Once per machine`}),(0,A.jsx)(`pre`,{className:`ui-code`,children:`pinecall line from +1XXXXXXXXXX # this mobile is mine`}),(0,A.jsx)(Im,{ruled:!0,children:`While you work`}),(0,A.jsx)(`pre`,{className:`ui-code`,children:`pinecall start --serve # your copies up, and this console
101
- pinecall line forget # give your calls back to production`}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:(0,A.jsxs)(`span`,{children:[`The call shows up here, in Sessions, marked `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`diverted_from: production`}),`.`]})})]}),n!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The numbers to call`}),n.length===0&&(0,A.jsx)(Mm,{children:`This org has no phone number in production yet. The gateway's console adds one, under Numbers.`}),n.map(e=>{let t=o.some(t=>t.slug===e.agent),n=t&&i.length>0;return(0,A.jsxs)(`div`,{className:`num-row`,children:[(0,A.jsx)(`span`,{className:`num-number`,children:og(e.number)}),(0,A.jsx)(`span`,{className:`num-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(`span`,{className:`num-agent`,children:e.agent}),(0,A.jsx)(`span`,{className:`num-end`,children:n?(0,A.jsxs)(Qm,{tone:`green`,children:[`your copy answers `,i.map(og).join(`, `)]}):t?(0,A.jsx)(Qm,{tone:`amber`,children:`production answers: say which phone is yours`}):(0,A.jsx)(Qm,{tone:`gray`,children:`production answers: you are not running it`})})]},e.number)})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`What a call from your phone reaches right now`}),(0,A.jsx)(`div`,{className:`num-body`,children:o.length===0?(0,A.jsxs)(A.Fragment,{children:[`Nothing: no copy of yours is running, so your calls reach production. Start `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in the project.`]}):i.length===0?(0,A.jsxs)(A.Fragment,{children:[`Production, still: you are running `,o.map(e=>e.slug).join(`, `),`, and the gateway does not know which phone is yours.`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall line from +1…`}),`, once.`]}):(0,A.jsxs)(A.Fragment,{children:[`Your copy of `,o.map(e=>e.slug).join(`, `),`, from `,i.map(og).join(`, `),` — for as long as`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` stays up.`]})})]})]})}var LW=z({vendor:P(),model:P().nullable(),voice_id:P().nullable(),language:P().nullable()}),RW=z({voice:P().nullable(),tts:P().nullable(),tts_model:P().nullable(),stt:P().nullable(),llm:P().nullable(),greeting:P().nullable()}),zW=z({name:mp(BC),seconds:F(),turns:I()}),BW=z({say:P().nullable(),reply:P().nullable(),allow_interruptions:L().nullable()}),VW=z({agent:P(),hears:LW,decides:LW,speaks:LW,greeting:BW.nullable(),overrides:RW,voices:R(P()),providers:R(Ph),calls:I(),medians:R(zW),unavailable_reasons:fp(P(),P())});async function HW(e,t){return VW.parse(await k(e,UW(t)))}function UW(e){return`/v1/agents/${encodeURIComponent(e)}/pipeline`}var WW=z({played:mp([`default`,`off`,`custom`]),name:P().nullable(),seconds:F().nullable(),sha256:P().nullable()});async function GW(e,t){return WW.parse(await k(e,`${UW(t)}/hold-audio`))}async function KW(e,t,n){let r=await fetch(la(e,`${UW(t)}/hold-audio`,{name:n.name}),{method:`PUT`,headers:{...ra(e),"content-type":n.type||`application/octet-stream`},body:n});return WW.parse(await fa(r))}async function qW(e,t,n){return WW.parse(await oa(e,`${UW(t)}/hold-audio/played`,{played:n}))}async function JW(e,t){let n=await fetch(la(e,`${UW(t)}/hold-audio/audio`),{headers:ra(e)});return n.ok||await fa(n),URL.createObjectURL(await n.blob())}function YW({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),u=(0,D.useRef)(null);(0,D.useEffect)(()=>{let n=!1;return GW(t,e).then(e=>!n&&r(e),e=>!n&&s(e instanceof Error?e.message:String(e))),()=>{n=!0}},[t,e]),(0,D.useEffect)(()=>()=>{c!==null&&URL.revokeObjectURL(c)},[c]);let d=async(e,t)=>{a(e),s(null);try{r(await t()),l(null)}catch(e){s(e instanceof Error?e.message:String(e))}finally{a(null)}},f=async()=>{s(null);try{l(await JW(t,e))}catch(e){s(e instanceof Error?e.message:String(e))}},p=n=>{n!==void 0&&(d(`Converting…`,()=>KW(t,e,n)),u.current!==null&&(u.current.value=``))};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Hold melody`,meta:`what the caller hears while a tool runs — phone and web alike, from the next call`}),(0,A.jsxs)(`div`,{className:`pipe-hold`,children:[(0,A.jsxs)(`div`,{className:`pipe-hold-now`,children:[(0,A.jsx)(`b`,{children:n===null?`…`:n.played===`off`?`Off`:n.name??`Your file`}),(0,A.jsx)(`span`,{className:`pipe-note`,children:n===null?`Asking the gateway.`:n.played===`off`?`Silence while a tool runs.`:`${n.played==="default"?`The runtime's own`:`Uploaded`} · ${n.seconds??`?`} s, looped under the wait at 60 %, after 0.6 s.`})]}),(0,A.jsxs)(`div`,{className:`pipe-hold-actions`,children:[n!==null&&n.played!==`off`&&(0,A.jsx)(U,{size:`sm`,onClick:()=>void f(),disabled:i!==null,children:`Listen`}),(0,A.jsx)(U,{size:`sm`,onClick:()=>u.current?.click(),disabled:i!==null,children:i??`Upload a file…`}),n!==null&&n.played!=="default"&&(0,A.jsx)(U,{size:`sm`,onClick:()=>void d(`Saving…`,()=>qW(t,e,`default`)),disabled:i!==null,children:`Use the default`}),n!==null&&n.played!==`off`&&(0,A.jsx)(U,{size:`sm`,onClick:()=>void d(`Saving…`,()=>qW(t,e,`off`)),disabled:i!==null,children:`Turn off`}),(0,A.jsx)(`input`,{ref:u,type:`file`,accept:`audio/*,.mp3,.wav,.ogg,.m4a`,hidden:!0,onChange:e=>p(e.target.files?.[0])})]}),c!==null&&(0,A.jsx)(`audio`,{className:`pipe-hold-player`,controls:!0,autoPlay:!0,src:c}),o===null?(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`A wav, an mp3, an ogg or an m4a, up to 20 MB and five minutes: the gateway converts it.`}):(0,A.jsx)(`span`,{className:`pipe-save-error`,children:o})]})]})}function XW({stage:e,unavailable:t,turned:n}){return(0,A.jsxs)($W,{job:`hears`,stage:e,unavailable:t,turned:n,children:[(0,A.jsx)(eG,{label:`Language`,value:e.language??`the vendor's default`,note:`What the ear is told to expect; the runtime adds the names the state carries.`}),e.model!==null&&e.model!==``&&(0,A.jsx)(eG,{label:`Model`,value:e.model}),(0,A.jsx)(eG,{label:`Switchable to`,value:`Any STT provider on file`,note:`Effective on the next session.`})]})}function ZW({stage:e,unavailable:t,turned:n}){return(0,A.jsxs)($W,{job:`decides`,stage:e,unavailable:t,turned:n,children:[(0,A.jsx)(eG,{label:`Model`,value:e.model??`the vendor's default`}),(0,A.jsx)(eG,{label:`Prompt`,value:`identity · knowledge · tools · history · view`,note:`Named blocks in two regions, never reordered: the static ones are cached, the dynamic ones rewritten every turn.`}),(0,A.jsx)(eG,{label:`Tools`,value:`The class's @tool methods`})]})}function QW({stage:e,unavailable:t,turned:n}){return(0,A.jsxs)($W,{job:`speaks`,stage:e,unavailable:t,turned:n,children:[(0,A.jsx)(eG,{label:`Voice`,value:e.voice_id??`the vendor's default`,note:`One of the voices this build curates, by name; the id is the vendor's.`}),e.model!==null&&e.model!==``&&(0,A.jsx)(eG,{label:`Model`,value:e.model}),(0,A.jsx)(eG,{label:`Aligned transcript`,value:`On`,note:`Timed words, so the log knows when each word was spoken.`})]})}function $W({job:e,stage:t,unavailable:n,turned:r,children:i}){return(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`pipe-leg-head`,children:[(0,A.jsx)(`span`,{className:`pipe-leg-vendor`,children:t.vendor}),r&&(0,A.jsx)(Qm,{tone:`violet`,small:!0,children:`turned`}),(0,A.jsx)(`span`,{className:`pipe-leg-job`,children:e})]}),(0,A.jsxs)(`div`,{className:`pipe-leg-body`,children:[i,n!==null&&(0,A.jsxs)(`div`,{className:`pipe-field`,children:[(0,A.jsx)(`div`,{className:`pipe-label`,children:`Not right now`}),(0,A.jsx)(`div`,{className:`pipe-refused`,children:n})]})]})]})}function eG({label:e,value:t,note:n}){return(0,A.jsxs)(`div`,{className:`pipe-field`,children:[(0,A.jsx)(`div`,{className:`pipe-label`,children:e}),(0,A.jsx)(`div`,{className:`pipe-value`,children:t}),n!==void 0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:n})]})}function tG(e){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return r(null),HW(t,e).then(e=>{n||r(e)},e=>{n||a(String(e))}),()=>{n=!0}},[e,t]),{report:n,error:i}}var nG={transcription_delay:{label:`Transcription`,note:`from the end of speech to the ear's final transcript`,color:`var(--accent-3)`},end_of_turn_delay:{label:`End of turn`,note:`silence the turn detector waits through before it believes the caller stopped`,color:`var(--accent-3)`},llm_node_ttft:{label:`LLM first token`,note:`to the model's first token`,color:`var(--accent)`},tts_node_ttfb:{label:`Speech starts`,note:`to the voice's first audio byte`,color:`var(--accent-2)`},e2e_latency:{label:`End to end`,note:`what the caller actually waits: their last word to the agent's first audio`,color:`var(--accent-hover)`}};function rG({medians:e,calls:t,agent:n}){let r=new Map(e.map(e=>[e.name,e])),i=Math.max(0,...e.map(e=>e.seconds)),a=Math.max(0,...e.map(e=>e.turns));return(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Anatomy of a turn`}),i>0&&(0,A.jsxs)(`span`,{className:`ui-card-meta`,children:[`medians over the last `,t,` call`,t===1?``:`s`,` · `,a,` turns`]})]}),(0,A.jsx)(`div`,{className:`pipe-anatomy`,children:BC.map((e,t)=>{let n=nG[e],a=r.get(e)?.seconds??null;return(0,A.jsxs)(`div`,{className:t===BC.length-1?`pipe-turn-row pipe-turn-row-last`:`pipe-turn-row`,title:n.note,children:[(0,A.jsx)(`span`,{className:`pipe-turn-label`,children:n.label}),(0,A.jsx)(`span`,{className:`pipe-track`,children:a!==null&&i>0&&(0,A.jsx)(`span`,{className:`pipe-bar`,style:{width:`${Math.max(a/i*100,.8)}%`,background:n.color}})}),(0,A.jsx)(`span`,{className:a===null?`pipe-ms pipe-ms-none`:`pipe-ms`,children:a===null?`—`:`${Math.round(a*1e3)} ms`})]},e)})}),i===0&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:iG(t,n)})]})}function iG(e,t){return e===0?`No call stored for ${t} yet — place one and the bars fill.`:`${e} stored call${e===1?``:`s`} for ${t}, and not one turn carries a latency — a text session measures none.`}function aG(){let e=Sr().agent??``,{report:t,error:n}=tG(e);return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Pipeline`,ledeWidth:660,lede:`The three legs of a voice turn as data, not prose: what hears, what decides, what speaks — every value read from the gateway with this agent's settings already laid over the class.`}),t===null?(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:n??`Asking the gateway what ${e} runs on…`})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`pipe-legs`,children:[(0,A.jsx)(XW,{stage:t.hears,unavailable:t.unavailable_reasons.hears??null,turned:t.overrides.stt!==null}),(0,A.jsx)(ZW,{stage:t.decides,unavailable:t.unavailable_reasons.decides??null,turned:t.overrides.llm!==null}),(0,A.jsx)(QW,{stage:t.speaks,unavailable:t.unavailable_reasons.speaks??null,turned:t.overrides.tts!==null||t.overrides.voice!==null||t.overrides.tts_model!==null})]}),(0,A.jsx)(rG,{medians:t.medians,calls:t.calls,agent:e}),(0,A.jsx)(V,{children:(0,A.jsxs)(Mm,{children:[`Changing any of it is the `,(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),` tab: the vendors and models with the opening, the cut of a turn and what is remembered, per corner and versioned.`]})}),(0,A.jsx)(YW,{agent:e},`hold-${e}`)]})]})}function oG(){let e=Sr().agent??``,{lines:t,error:n}=zS(e);return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Sessions`,lede:`Only what ${e} handled, newest first.`}),(0,A.jsx)(bU,{lines:t,error:n,agent:e,agents:[]})]})}var sG={passed:`green`,failed:`red`,deferred:`amber`,skipped:`muted`};function cG({agent:e,call:t}){let n=j(),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),d=async r=>{i(r),u(null);try{r===`check`?o(await nT(n,t)):c(await iT(n,e,t))}catch(e){u(e instanceof na?e.message:String(e))}finally{i(``)}};return(0,A.jsxs)(`div`,{className:`session-acts`,children:[(0,A.jsxs)(`div`,{className:`session-buttons`,children:[(0,A.jsx)(U,{size:`md`,disabled:r!==``,onClick:()=>void d(`check`),children:r===`check`?`Checking…`:`Re-check by code`}),(0,A.jsx)(U,{size:`md`,disabled:r!==``||e===``,onClick:()=>void d(`promote`),children:r===`promote`?`Writing…`:`Promote to a golden`})]}),a!==null&&(0,A.jsxs)(`div`,{className:`session-result`,children:[(0,A.jsx)(`span`,{className:`session-result-lead`,children:a.passed?`Holds by code`:`Does not hold by code`}),a.verdicts.map(e=>(0,A.jsxs)(Qm,{tone:sG[e.status]??`muted`,children:[e.check,` `,e.status]},e.check))]}),s!==null&&(0,A.jsxs)(`div`,{className:`session-result`,children:[(0,A.jsx)(`span`,{className:`session-result-lead`,children:`Written down`}),(0,A.jsx)(`span`,{className:`ui-fixed session-path`,children:s.path}),(0,A.jsxs)(`span`,{className:`session-result-note`,children:[s.candidate.input.length,` caller `,s.candidate.input.length===1?`turn`:`turns`]}),s.notes.map(e=>(0,A.jsx)(`span`,{className:`session-result-note session-result-line`,children:e},e))]}),l!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:l})]})}var lG=`confirm.`,uG=`tool.call`;function dG(e){let t=new Map;for(let n of e){if(!n.type.startsWith(lG))continue;let e=bG(n,`call_id`),r=t.get(e)??vG(e,bG(n,`tool`));t.set(e,{...r,..._G(n)})}for(let n of e){let e=n.type===uG?t.get(bG(n,`call_id`)):void 0;e!==void 0&&(e.ran=n)}return[...t.values()]}function fG({rows:e}){return e.length===0?null:(0,A.jsx)(`div`,{className:`session-consents`,children:e.map(e=>(0,A.jsx)(pG,{consent:e},e.callId))})}function pG({consent:e}){let t=hG(e);return(0,A.jsxs)(`div`,{className:`session-consent`,children:[(0,A.jsxs)(`div`,{className:`session-consent-join`,children:[(0,A.jsx)(`span`,{className:`session-consent-tool`,children:e.tool}),(0,A.jsx)(`span`,{className:`session-consent-seqs`,children:mG(e)}),(0,A.jsx)(`span`,{className:`session-consent-id ui-fixed`,children:e.callId})]}),e.requested!==null&&(0,A.jsx)(`div`,{className:`session-consent-said`,children:bG(e.requested,`phrase`)}),e.granted!==null&&(0,A.jsxs)(`div`,{className:`session-consent-said`,children:[`“`,bG(e.granted,`said`),`”`]}),(0,A.jsxs)(`div`,{className:`session-consent-audience`,children:[`audience `,gG(e)]}),t!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:t})]})}function mG(e){return e.granted===null?e.declined===null?`seq ${yG(e.requested)} asked and nothing answered`:`seq ${yG(e.declined)} declined seq ${yG(e.ran)}`:`seq ${e.granted.seq} authorised seq ${yG(e.ran)}`}function hG(e){let{granted:t,ran:n,requested:r}=e;if(t===null||n===null)return null;if(t.seq>n.seq)return`${e.tool} ran at seq ${n.seq}, before its confirm.granted at seq ${t.seq}`;let i=r===null?null:bG(r,`audience`);return i!==null&&i!==bG(t,`audience`)?`${e.tool} was confirmed by another audience than the one asked at seq ${r?.seq??0}`:null}function gG(e){let t=e.granted??e.declined??e.requested;return t===null?`—`:bG(t,`audience`)}function _G(e){return e.type===`confirm.granted`?{granted:e}:e.type===`confirm.declined`?{declined:e}:{requested:e}}function vG(e,t){return{callId:e,tool:t,requested:null,granted:null,declined:null,ran:null}}function yG(e){return e===null?`—`:String(e.seq)}function bG(e,t){let n=e.data[t];return typeof n==`string`?n:``}var xG={held:`green`,broken:`red`,deferred:`amber`,skipped:`muted`};function SG({call:e,back:t,score:n,turns:r,ended:i}){let[a,o]=(0,D.useState)(null),s=a??n;return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Score`,meta:s!==null&&s.passed!=null?`${TG(s)} of ${s.judges.length} held`:void 0}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:s===null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`session-standing session-standing-amber`,children:`Not scored yet`}),(0,A.jsxs)(`p`,{className:`session-sentence`,children:[`The call is still running, or its log was sealed before the judges existed. Ask for one with`,` `,(0,A.jsxs)(`span`,{className:`ui-fixed`,children:[`pinecall eval `,e]}),`.`]}),i&&(0,A.jsx)(DG,{call:e,onJudged:o})]}):s.passed==null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`session-standing session-standing-amber`,children:`No judge was given to this session`}),wG(s.not_judged)&&(0,A.jsx)(`p`,{className:`session-sentence`,children:s.not_judged}),(0,A.jsx)(`p`,{className:`session-sentence`,children:EG(s,r)}),i&&(0,A.jsx)(DG,{call:e,onJudged:o})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:s.passed?`session-standing session-standing-green`:`session-standing session-standing-red`,children:s.passed?`Passed`:`Did not pass`}),(0,A.jsxs)(`div`,{className:`session-judges`,children:[s.judges.map(n=>(0,A.jsx)(CG,{back:t,call:e,judgment:n},n.name)),(s.panel??[]).filter(e=>!s.judges.some(t=>t.name===e)).map(e=>(0,A.jsxs)(`div`,{className:`session-judge`,children:[(0,A.jsxs)(`div`,{className:`session-judge-line`,children:[(0,A.jsx)(`span`,{className:`session-judge-name`,children:e}),(0,A.jsx)(Qm,{tone:`muted`,children:`on the panel`})]}),(0,A.jsx)(`div`,{className:`session-judge-reason`,children:`Was run over this call and answered nothing.`})]},e))]}),(0,A.jsx)(`p`,{className:`session-sentence`,children:EG(s,r)})]})})]})}function CG({back:e,call:t,judgment:n}){return(0,A.jsxs)(`div`,{className:`session-judge`,children:[(0,A.jsxs)(`div`,{className:`session-judge-line`,children:[(0,A.jsx)(`span`,{className:`session-judge-name`,children:n.name}),(0,A.jsx)(Qm,{tone:xG[n.verdict]??`muted`,children:n.verdict}),n.evidence.seqs.map(n=>(0,A.jsxs)(Wi,{className:`session-seq`,to:`${e}/${t}#seq-${n}`,children:[`seq `,n]},n))]}),(0,A.jsxs)(`div`,{className:`session-judge-reason`,children:[n.reason,n.evidence.said!=null&&(0,A.jsxs)(`span`,{className:`session-judge-said`,children:[` “`,n.evidence.said,`”`]})]})]})}function wG(e){return e!=null&&e.trim().toLowerCase()!==`no judge was given to this session`}function TG(e){return e.judges.filter(e=>e.verdict===`held`).length}function EG(e,t){let n=`${t===1?`One turn`:`${t} turns`} replayed from the log`;return e.judge_calls===0?`${n}; the hard policies alone, and they cost nothing.`:`${n}; ${e.judge_calls} judge call${e.judge_calls===1?``:`s`} for ${Yh(e.judge_cost_eur)}.`}function DG({call:e,onJudged:t}){let n=j(),r=Eh(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null);if(r!==null&&!r.includes(`evals`))return null;let c=async()=>{a(!0),s(null);try{t(Y_.parse(await sa(n,`/v1/evals/judge/${encodeURIComponent(e)}`,{})))}catch(e){s(e instanceof na?e.message:String(e))}finally{a(!1)}};return(0,A.jsxs)(`div`,{className:`session-attach`,children:[(0,A.jsx)(U,{size:`md`,disabled:i,onClick:()=>void c(),children:i?`Judging…`:`Attach a judge`}),o!==null&&(0,A.jsx)(`p`,{className:`session-sentence session-refused-line`,children:o})]})}var OG={llm_node_ttft:`LLM first token`,e2e_latency:`End to end`,tts_node_ttfb:`Speech starts`,transcription_delay:`Transcription`,end_of_turn_delay:`End of turn`},kG=[`llm_node_ttft`,`e2e_latency`];function AG({rows:e}){let t=[...e.filter(e=>kG.includes(e.name)).sort((e,t)=>kG.indexOf(e.name)-kG.indexOf(t.name)),...e.filter(e=>!kG.includes(e.name))];return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Latency across this call`}),t.length===0?(0,A.jsx)(`p`,{className:`session-sentence session-latency-none`,children:`No turn in this session carried a metric — a chat session times nothing, and a voice call that dropped before its first answer has nothing to time.`}):(0,A.jsx)(`div`,{className:`session-latency`,children:t.map(e=>(0,A.jsxs)(`div`,{title:`${e.name} · median over ${e.turns} ${e.turns===1?`turn`:`turns`}`,children:[(0,A.jsx)(`div`,{className:`session-latency-label`,children:OG[e.name]??e.name}),(0,A.jsx)(`div`,{className:`session-latency-value`,children:WC(e.seconds)}),(0,A.jsxs)(`div`,{className:`session-latency-max`,children:[`max `,WC(e.max)]})]},e.name))})]})}var jG={"turn.user":`user`,"turn.agent":`agent`},MG=/^#seq-(\d+)$/;function NG({lines:e,turns:t}){let[n,r]=(0,D.useState)(new Set),[i,a]=(0,D.useState)(!1),o=zG(t),s=PG(gr().hash),c=e.length;(0,D.useEffect)(()=>{s!==null&&c>0&&document.getElementById(FG(s))?.scrollIntoView({block:`center`})},[s,c]);let l=e=>r(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n});return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The log`,meta:`${e.length} entries, append-only, numbered by seq`,action:(0,A.jsx)(`span`,{className:`session-log-action`,children:(0,A.jsx)(U,{size:`sm`,onClick:()=>a(!i),children:i?`Hide the fields`:`Show every field`})})}),(0,A.jsx)(`div`,{className:`session-log`,children:e.map(e=>(0,A.jsx)(IG,{line:e,turn:o.get(BG(e.entry.type,e.entry.data)),open:i||n.has(e.entry.seq),cited:e.entry.seq===s,onToggle:()=>l(e.entry.seq)},e.entry.seq))})]})}function PG(e){let t=MG.exec(e)?.[1];return t===void 0?null:Number(t)}function FG(e){return`seq-${e}`}function IG({line:e,turn:t,open:n,cited:r,onToggle:i}){let a=e.fields.length>0,o=[`session-entry`,`session-entry-${LG(e.entry.type)}`];return a&&o.push(`session-entry-opens`),r&&o.push(`session-entry-cited`),(0,A.jsxs)(`div`,{id:FG(e.entry.seq),className:o.join(` `),onClick:a?i:void 0,children:[(0,A.jsx)(`span`,{className:`session-entry-seq`,children:e.entry.seq}),(0,A.jsx)(`span`,{className:`session-entry-since`,children:e.since}),(0,A.jsxs)(`span`,{className:`session-entry-type`,children:[e.mark!==``&&(0,A.jsxs)(`span`,{className:`session-entry-mark`,children:[e.mark,` `]}),e.entry.type]}),(0,A.jsxs)(`span`,{className:`session-entry-payload`,children:[e.payload,a&&(0,A.jsxs)(`span`,{className:`session-entry-caret`,children:[` `,n?`▾`:`▸`]}),t!==void 0&&(0,A.jsx)(RG,{turn:t}),n&&(0,A.jsx)(`span`,{className:`session-fields`,children:e.fields.map(e=>(0,A.jsxs)(`span`,{className:`session-field`,children:[(0,A.jsx)(`span`,{className:`session-field-name`,children:e.name}),(0,A.jsx)(`span`,{className:`session-field-value`,children:e.value})]},e.name))})]})]})}function LG(e){return e.startsWith(`turn.`)?`turn`:e.startsWith(`state.`)?`state`:e.startsWith(`tool.`)||e.startsWith(`confirm.`)?`tool`:e.startsWith(`call.`)?`call`:`quiet`}function RG({turn:e}){return(0,A.jsx)(`span`,{className:`session-chips`,children:VC(e).map(e=>(0,A.jsxs)(`span`,{className:`session-chip`,children:[e.field,` `,(0,A.jsx)(`b`,{children:e.value})]},e.field))})}function zG(e){return new Map(e.map(e=>[`${e.role}:${e.speech_id}`,e]))}function BG(e,t){let n=t.speech_id;return`${jG[e]??``}:${typeof n==`string`?n:``}`}var VG=[`turn.user`,`turn.agent`],HG=`metrics.`,UG=`memory.ops`,WG=`docs.sources`,GG={"tool.call":`→`,"tool.result":`←`},KG=`!`;function qG(e){let t=jC(e.map(e=>e.type)),n=e[0]?.ts??0;return e.map(e=>YG(e,n,t.get(e.type)))}function JG(e,t){return`+${(e-t).toFixed(3)}`}function YG(e,t,n){return{entry:e,mark:XG(e.type),since:JG(e.ts,t),payload:ZG(e,n),fields:QG(e,n)}}function XG(e){return e.startsWith(`confirm.`)?KG:GG[e]??``}function ZG(e,t){return VG.includes(e.type)?MC(Object.fromEntries(Object.entries(e.data).filter(([e])=>e!==`metrics`)),t):e.type.startsWith(HG)?``:e.type===UG?kH(e.data):e.type===WG?jH(e.data):MC(e.data,t)}function QG(e,t){if(VG.includes(e.type)){let n=e.data.metrics,r=t?.properties?.metrics;return nK(n)?$G(n,HG,r):[]}return e.type.startsWith(HG)?$G(e.data,``,t):e.type===UG?AH(e.data).map(e=>({name:`fact`,value:e})):e.type===WG?MH(e.data).map(e=>({name:`source`,value:e})):[]}function $G(e,t,n){return eK(e,t,n,tK(e,n))}function eK(e,t,n,r){let i=[];for(let a of r){let r=e[a],o=n?.properties?.[a];nK(r)?i.push(...eK(r,`${t}${a}.`,o,Object.keys(r))):i.push({name:`${t}${a}`,value:NC(r,o)})}return i}function tK(e,t){let n=Object.keys(t?.properties??{}).filter(t=>t in e);return[...n,...Object.keys(e).filter(e=>!n.includes(e))]}function nK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rK(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(!0),[o,s]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return r([]),a(!0),s(null),(async()=>{try{let i=await bC(t,e);n||r(i)}catch(e){n||s(String(e))}finally{n||a(!1)}})(),()=>{n=!0}},[e,t]),{entries:n,reading:i,error:o}}var iK=`call.summary`;function aK(){let{agent:e=``,call:t=``}=Sr(),{entries:n,reading:r,error:i}=rK(t),a=(0,D.useMemo)(()=>({state:Cy(n),lines:qG(n),latencies:YC(n),consented:dG(n),recording:nH(pK(n)?.data),score:mK(n)}),[n]),o=e===``?`/sessions`:`/a/${e}/sessions`,s=e===``?a.state.agent:e;return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Wi,{to:o,className:`ui-back`,children:`← Sessions`}),(0,A.jsx)(`h1`,{className:`session-title`,children:t}),(0,A.jsx)(cG,{agent:s,call:t})]}),i!==null&&(0,A.jsx)(V,{children:(0,A.jsxs)(Mm,{children:[`That session did not load. `,(0,A.jsx)(Nm,{children:i})]})}),i===null&&n.length===0&&(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:r?`Reading ${t}…`:`No call ${t} in the log.`})}),n.length>0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(cK,{state:a.state,events:n.length}),(0,A.jsxs)(V,{pad:!0,children:[(0,A.jsx)(`div`,{className:`session-outcome-label`,children:`Outcome`}),(0,A.jsx)(`div`,{className:`session-outcome`,children:a.state.outcome??(a.state.end_reason===null?`The call is still going.`:`The call left no outcome sentence.`)})]}),(0,A.jsx)(rH,{call:t,path:a.recording}),(0,A.jsxs)(`div`,{className:`session-split`,children:[(0,A.jsx)(lK,{state:a.state}),(0,A.jsxs)(`div`,{className:`session-side`,children:[(0,A.jsx)(AG,{rows:a.latencies}),(0,A.jsx)(SG,{call:t,back:o,score:a.score,turns:a.state.turns.length,ended:a.state.status===`ended`})]})]}),a.state.cost!==null&&a.state.cost.rows.length>0&&(0,A.jsx)(uK,{cost:a.state.cost}),(0,A.jsxs)(sK,{children:[a.consented.length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Consent proof`,meta:`each grant joined to the tool call it authorised`}),(0,A.jsx)(fG,{rows:a.consented})]}),Object.keys(a.state.prompt).length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The prompt, block by block`,meta:`by name, hash and length — the text never enters the log`}),(0,A.jsx)(`div`,{className:`session-prompt`,children:Object.entries(a.state.prompt).map(([e,t])=>(0,A.jsxs)(Lm,{label:e,children:[(0,A.jsx)(`span`,{className:`ui-fixed session-hash`,children:t.hash}),` · `,t.chars,` chars · seq `,t.seq]},e))}),(0,A.jsxs)(`div`,{className:`session-note`,children:[(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall prompt --state`}),` prints the text offline.`]})]}),(0,A.jsx)(NG,{lines:a.lines,turns:a.state.turns})]})]})]})}var oK=/^#seq-\d+$/;function sK({children:e}){let{hash:t}=gr(),[n,r]=(0,D.useState)(()=>oK.test(t));return(0,D.useEffect)(()=>{oK.test(t)&&r(!0)},[t]),(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(V,{children:(0,A.jsxs)(`button`,{type:`button`,className:`session-details`,"aria-expanded":n,onClick:()=>r(!n),children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Details`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`consent, prompt blocks, the full log`}),(0,A.jsx)(`span`,{className:`session-details-caret`,children:n?`Hide ▴`:`Show ▾`})]})}),n&&e]})}function cK({state:e,events:t}){return(0,A.jsx)(`div`,{className:`session-facts`,children:(0,A.jsxs)(lh,{min:150,children:[(0,A.jsx)(uh,{size:`fact`,label:`Agent`,value:e.agent}),(0,A.jsx)(uh,{size:`fact`,label:`Channel`,value:e.direction===`outbound`?`${e.channel??`—`} · outbound`:e.channel??`—`}),(0,A.jsx)(uh,{size:`fact`,label:`Started`,value:Qh(e.started_at)}),(0,A.jsx)(uh,{size:`fact`,label:`Duration`,value:e.ended_at===null?`still going`:qh(e)}),(0,A.jsx)(uh,{size:`fact`,label:`Ended`,value:e.end_reason===null?`not yet`:e.end_reason.replace(/_/g,` `)}),(0,A.jsx)(uh,{size:`fact`,label:`Cost`,value:Yh(e.cost?.eur)}),(0,A.jsx)(uh,{size:`fact`,label:`Turns · events`,value:`${e.turns.length} · ${t}`})]})})}function lK({state:e}){let t=fK(e);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Transcript · ${e.turns.length} ${e.turns.length===1?`turn`:`turns`}`,meta:t===null?void 0:`with ${t}`}),e.turns.length===0?(0,A.jsx)(Mm,{children:`Nobody said anything a turn was written for.`}):(0,A.jsx)(`div`,{className:`session-turns`,children:e.turns.map((e,t)=>(0,A.jsxs)(`div`,{className:`session-turn`,children:[(0,A.jsx)(`span`,{className:e.role===`agent`?`session-who session-who-agent`:`session-who`,children:e.role===`agent`?`agent`:`caller`}),(0,A.jsxs)(`span`,{className:e.role===`agent`?`session-said session-said-agent`:`session-said`,children:[e.text,e.role===`agent`&&e.interrupted&&(0,A.jsx)(`span`,{className:`session-interrupted`,children:` · interrupted`})]})]},`${t}:${e.role}:${e.speech_id}`))})]})}function uK({cost:e}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Cost by model`,children:(0,A.jsx)(`span`,{className:`session-total`,children:Yh(e.eur)})}),(0,A.jsx)(`div`,{children:e.rows.map(e=>(0,A.jsxs)(`div`,{className:`session-cost`,children:[(0,A.jsxs)(`span`,{className:`session-cost-model`,children:[e.model,` `,(0,A.jsxs)(`span`,{className:`session-cost-kind`,children:[`· `,e.unit.replace(/_/g,` `)]})]}),(0,A.jsx)(`span`,{className:`session-cost-units`,children:dK(e.quantity)}),(0,A.jsx)(`span`,{className:`session-cost-eur`,children:Yh(e.eur)})]},`${e.provider}/${e.model}/${e.unit}`))}),(0,A.jsxs)(`div`,{className:`session-note`,children:[`EUR at `,e.rate.usd_to_eur,` per USD, as of `,e.rate.as_of,e.unpriced.length>0&&` · unpriced: ${e.unpriced.map(e=>`${e.provider}/${e.model}`).join(`, `)}`]})]})}function dK(e){let[t,n]=String(Math.round(e*100)/100).split(`.`),r=(t??``).replace(/\B(?=(\d{3})+(?!\d))/g,` `);return n===void 0?r:`${r}.${n}`}function fK(e){let t=e.caller?.name;if(t!=null&&t!==``)return t;let n=e.direction===`outbound`?e.to:e.from;return n===null?null:n.startsWith(`+`)?og(n):n}function pK(e){return[...e].reverse().find(e=>e.type===iK)}function mK(e){let t=[...e].reverse().find(e=>e.type===Fv);return t===void 0?null:Y_.parse(t.data)}function hK(e){return`/v1/agents/${encodeURIComponent(e)}/settings`}async function gK(e,t){return _y.parse(await k(e,hK(t)))}async function _K(e,t,n){return _y.parse(await oa(e,hK(t),n))}async function vK(e,t,n){return vy.parse(await k(e,`${hK(t)}/history`,{team:String(n)}))}async function yK(e,t,n,r){return _y.parse(await sa(e,`${hK(t)}/rollback`,{version:n,team:r}))}var bK=[`voice`,`tts`,`tts_model`,`stt`,`llm`,`greeting`,`hangup`,`turn`,`memory`,`knowledge`],xK={voice:`voice`,tts:`speaks with`,tts_model:`tts model`,stt:`hears with`,llm:`decides with`,greeting:`greeting`,hangup:`hangup`,turn:`turn`,memory:`memory`,knowledge:`knowledge`};function SK(e,t){if(t===`greeting`){let t=e.greeting??void 0;if(t===void 0)return;let n=t.say??void 0;return n===void 0?`reply: ${t.reply??``}`:`"${n}"`}if(t===`hangup`){let t=e.hangup??void 0;return t===void 0?void 0:t.when?`when ${t.when}`:`may hang up`}if(t===`turn`){let t=e.turn??void 0;if(t===void 0)return;let n=[];return typeof t.endpointing_ms==`number`&&n.push(`endpointing ${t.endpointing_ms} ms`),typeof t.min_interruption_words==`number`&&n.push(`interrupt at ${t.min_interruption_words} words`),n.join(` · `)}if(t===`memory`){let t=e.memory??void 0;return t===void 0?void 0:`remember ${t.remember?.length??0} · forget ${t.forget?.length??0}`}if(t===`knowledge`){let t=e.knowledge??void 0;return t===void 0||t.length===0?void 0:t.map(e=>`${e.base}${typeof e.k==`number`?` (k ${e.k})`:``}`).join(` · `)}let n=e[t];return typeof n==`string`?n:void 0}function CK(e,t){let n=[];for(let r of bK){let i=SK(e,r),a=SK(t,r);i!==a&&n.push(`${xK[r]} ${i??`—`} → ${a??`—`}`)}return n}function wK(e,t){return t?e.team:e.yours}var TK=[{field:`stt`,modality:`stt`,label:`Hears with`,note:`Which ear hears the caller. A model beside it when the vendor's own default is not wanted.`},{field:`llm`,modality:`llm`,label:`Decides with`,note:`What reads the words and answers.`},{field:`tts`,modality:`tts`,label:`Speaks with`,note:`What says it out loud. The voice is then that vendor's own id, unless the vendor is the one this build curates voices for.`}],EK=`elevenlabs`;function DK(e){let t=e.turn??void 0,n=e.memory??void 0;return{voice:e.voice??``,tts:e.tts??``,tts_model:e.tts_model??``,stt:e.stt??``,llm:e.llm??``,say:e.greeting?.say??``,reply:e.greeting?.reply??``,hangup:e.hangup?.when??``,endpointing_ms:typeof t?.endpointing_ms==`number`?String(t.endpointing_ms):``,min_interruption_words:typeof t?.min_interruption_words==`number`?String(t.min_interruption_words):``,remember:(n?.remember??[]).join(`
100
+ `},HI}var GI;function KI(){if(GI)return FI;GI=1;var e=VI(),t=WI();return FI.grammar=zI(),FI.write=t,FI.parse=e.parse,FI.parseParams=e.parseParams,FI.parseFmtpConfig=e.parseFmtpConfig,FI.parsePayloads=e.parsePayloads,FI.parseRemoteCandidates=e.parseRemoteCandidates,FI.parseImageAttributes=e.parseImageAttributes,FI.parseSimulcastStreamList=e.parseSimulcastStreamList,FI}var qI=KI(),JI=.9,YI=1e3,XI=20;function ZI(e,t,n,r){let i=arguments.length>4&&arguments[4]!==void 0&&arguments[4];if(!e.msid?.includes(t))return;let a=e.rtp.find(e=>e.codec.toUpperCase()===n.toUpperCase())?.payload??0;if(a===0)return 0;let o=Math.round(r*JI),s=i?o:Math.min(o,YI),c=e.fmtp.find(e=>e.payload===a);return c?c.config.includes(`x-google-start-bitrate`)||(c.config+=`;x-google-start-bitrate=${s}`):e.fmtp.push({payload:a,config:`x-google-start-bitrate=${s}`}),a}var QI={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,OfferAnswered:`offerAnswered`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},$I=class extends pj.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=JA,this.iceLog=JA,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=SF(e=>J(this,void 0,void 0,function*(){this.emit(QI.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),XI),this.close=()=>{this._pc&&=(this.log.debug(`closing peer connection`),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.loggerOptions=t,this.log=YA(t.loggerName??qA.PCTransport,()=>this.logContext),this.iceLog=YA(qA.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new $T}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug(`local ICE candidate gathered`,{candidate:e.candidate.candidate}),(t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug(`ICE candidate error`,{event:e}),(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug(`ICE connection state: ${e.iceConnectionState}`),(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug(`signaling state: ${e.signalingState}`),(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug(`connection state: ${e.connectionState}`),(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug(`data channel opened by peer`,{label:e.channel.label,id:e.channel.id}),(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return J(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug(`queuing remote ICE candidate until remote description applied`,{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return J(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,{offerId:t,latestOfferId:this.latestOfferId}),!1;let n;if(e.type===`offer`){let t=lL(e),n=t.stereoMids,r=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=r}else if(e.type===`answer`){if(this.pendingInitialOffer&&this._pc){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=qI.parse(e.sdp??``);t.media.forEach(e=>{uL(e)}),this.log.debug(`setting pending initial offer before processing answer`),yield this.setMungedSDP(e,qI.write(t))}let t=qI.parse(e.sdp??``);t.media.forEach(e=>{let t=dL(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(r=e.payload,!0)),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})});let r=this.getPlaceholderMids();r.size>0&&cL(t.media,e=>r.has(dL(e.mid))),n=qI.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.length>0&&this.iceLog.debug(`flushing queued ICE candidates`,{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,e.type===`answer`&&(this.latestAcknowledgedOfferId=t,this.emit(QI.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(QI.NegotiationComplete),e.sdp&&qI.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(QI.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return J(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=qI.parse(t.sdp??``);return n.media.forEach(e=>{uL(e)}),t.sdp=qI.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return J(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug(`restarting ICE`),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else if(e?.iceRestart)throw new HM(`ICE restart requested without a remote description, peer connection must be recreated`);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`);return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`);return}this.log.debug(`starting to negotiate`);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,{sdp:n.sdp});let r=qI.parse(n.sdp??``);r.media.forEach(e=>{uL(e),e.type===`audio`?oL(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!t.cid)return!1;let n=ZI(e,t.cid,t.codec,t.maxbr,t.isScreenShare);return n!==void 0&&(n>0&&WN(t.codec)&&!tP()&&(this.ddExtID=eL(e,r,this.ddExtID)),!0)})});let i=this.getPlaceholderMids();if(i.size>0&&cL(r.media,e=>i.has(dL(e.mid))),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,{latestOfferId:this.latestOfferId,offerId:t});return}yield this.setMungedSDP(n,qI.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return J(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=qI.parse(e.sdp??``);return t.media.forEach(e=>{uL(e),e.type===`audio`&&oL(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,qI.write(t)),e})}getPlaceholderMids(){return sL(this._pc?.getTransceivers()??[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new VM(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new VM(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this._pc?.getStats()}getMaxMessageSize(){return this._pc?.sctp?.maxMessageSize}getConnectedAddress(){return J(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`)}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return J(this,void 0,void 0,function*(){let r=e.sdp;if(t){e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,{error:n,mungedSdp:t,originalSdp:r}),e.sdp=r}}try{n?yield this._pc?.setRemoteDescription(e):yield this._pc?.setLocalDescription(e)}catch(i){let a=`unknown error`;i instanceof Error?a=i.message:typeof i==`string`&&(a=i);let o={error:a,sdp:e.sdp};throw t&&t!==r&&(o.mungedSdp=t),!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,{fields:o}),new HM(a)}})}};function eL(e,t,n){let r=tL(t,n);return r===void 0?n:(e.ext?.some(e=>e.uri===LN)||(e.ext??=[],e.ext.push({value:r,uri:LN})),r)}function tL(e,t){let n=nL(e,LN);return n===void 0?t!==0&&!rL(e,t,LN)?t:iL(e):rL(e,n,LN)?void 0:n}function nL(e,t){for(let n of e.media){let e=n.ext?.find(e=>e.uri===t);if(e)return e.value}}function rL(e,t,n){return e.media.some(e=>e.ext?.some(e=>e.value===t&&e.uri!==n))}function iL(e){let t=0;return e.media.forEach(e=>{var n;(n=e.ext)==null||n.forEach(e=>{e.value>t&&(t=e.value)})}),t+1===15?16:t+1}function aL(e,t){return e.split(`;`).some(e=>e.trim()===t)}function oL(e,t,n){let r=dL(e.mid),i=0;e.rtp.some(e=>e.codec.toLowerCase()===`opus`&&(i=e.payload,!0)),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i&&(aL(e.config,`stereo=1`)||(e.config+=`;stereo=1`),!0)))}function sL(e){let t=new Set;for(let n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}function cL(e,t){let n=new Map,r=new Set;for(let i of e){let e=t(i);for(let t of i.fmtp??[])e?n.has(t.payload)||n.set(t.payload,t.config):(n.set(t.payload,t.config),r.add(t.payload))}if(n.size!==0){for(let r of e)if(t(r))for(let e of r.fmtp??[]){let t=n.get(e.payload);t!==void 0&&e.config!==t&&(e.config=t)}}}function lL(e){let t=[],n=[],r=qI.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=dL(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec.toLowerCase()===`opus`&&(i=e.payload,!0)),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i&&(aL(e.config,`sprop-stereo=1`)&&t.push(r),!0)))}),{stereoMids:t,nackMids:n}}function uL(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function dL(e){return typeof e==`number`?e.toFixed(0):e}var fL=`vp8`,pL={audioPreset:uN.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:pN.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:fL,backupCodec:!0,preConnectBuffer:!1},mL={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},hL={deviceId:{ideal:`default`},resolution:dN.h720.resolution},gL={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new rj,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},_L={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},vL;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(vL||={});var yL=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=_L.peerConnectionTimeout,this.log=JA,this.iceLog=JA,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=vL.CONNECTED:n.some(e=>e===`failed`)?this.state=vL.FAILED:n.some(e=>e===`connecting`)?this.state=vL.CONNECTING:n.every(e=>e===`closed`)?this.state=vL.CLOSED:n.some(e=>e===`closed`)?this.state=vL.CLOSING:n.every(e=>e===`new`)&&(this.state=vL.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${vL[t]} to ${vL[this.state]}`),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.loggerOptions=t,this.log=YA(t.loggerName??qA.PCManager,()=>this.logContext),this.iceLog=YA(qA.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new $I(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new $I(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,Dk.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,Dk.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=vL.NEW,this.connectionLock=new $T,this.remoteOfferLock=new $T}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return J(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,{error:e})}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return J(this,void 0,void 0,function*(){this.iceLog.warn(`triggering ICE restart`),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return J(this,void 0,void 0,function*(){this.iceLog.debug(`adding remote ICE candidate`,{target:t,candidate:e}),t===Dk.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return J(this,void 0,void 0,function*(){this.log.debug(`received server offer`,{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()});let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.log.debug(`updating rtc configuration`,{iceRestart:t}),this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return J(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return J(this,void 0,void 0,function*(){return new EM((t,n)=>{let r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug(`negotiation already handled in more recent acknowledged offer`,this.logContext),t();return}let i=!1,a=()=>{i||(i=!0,clearTimeout(c),this.publisher.off(QI.OfferAnswered,o),e.signal.removeEventListener(`abort`,s))},o=e=>{e>r&&(a(),t())},s=()=>{a(),n(new HM(`negotiation aborted`))},c=setTimeout(()=>{a(),n(new HM(`negotiation timed out`))},this.peerConnectionTimeout);e.signal.addEventListener(`abort`,s),this.publisher.on(QI.OfferAnswered,o),this.publisher.negotiate(e=>{a(),e instanceof Error?n(e):n(Error(String(e)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Dk.PUBLISHER||e===Dk.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>J(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`),XM.clearTimeout(a),i(LM.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=XM.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(LM.internal(`could not establish pc connection`))},r);for(;this.state!==vL.CONNECTED;)if(yield zN(50),t?.signal.aborted){i(LM.cancelled(`room connection has been cancelled`));return}XM.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},bL=class{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new $T,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters(`data channel replaced`),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`data channel torn down`;this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return J(this,void 0,void 0,function*(){let e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return J(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new VM(`engine closed`);let e=this.getChannel();if(!e)throw new VM(`DataChannel not found, kind: ${this.kind}`);if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new EM((n,r)=>{let i=()=>{s(),n()},a=()=>{s(),r(new VM(`DataChannel ${this.kind} closed while draining the buffer`))},o=()=>{s(),r(new VM(`DataChannel ${this.kind} was replaced or torn down while waiting for headroom`))},s=()=>{e.removeEventListener(`bufferedamountlow`,i),e.removeEventListener(`close`,a),t.removeEventListener(`abort`,o)};if(t.aborted){o();return}e.addEventListener(`bufferedamountlow`,i),e.addEventListener(`close`,a),t.addEventListener(`abort`,o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;let t=this.getChannel();if(!t)return;let n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,(e=this.onBufferStatusChanged)==null||e.call(this,n))}},xL=class extends bL{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return J(this,void 0,void 0,function*(){let t=this.getChannel();if(t){switch(this.bufferFullBehavior){case`wait`:this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case`drop`:if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100==0&&JA.warn(`dropping lossy data channel messages, total dropped: ${this.dropCount}`);return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(e){if(e instanceof TypeError)JA.error(e);else throw e}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=XM.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;let e=this.getChannel();if(e){let t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&=(XM.clearInterval(this.statInterval),void 0),this.dropCount=0}},SL=class{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(let e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},CL=class extends bL{constructor(e){super(e),this.messageBuffer=new SL,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){let e=this.sequence;return this.sequence+=1,e}send(e,t){return J(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}let n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(n){if(this.isEngineClosed())throw n;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus()}})}replay(e){return J(this,void 0,void 0,function*(){let t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);let n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let e=this.messageBuffer.getUnsent();e.length>0;e=this.messageBuffer.getUnsent())for(let n of e)yield this.waitForHeadroomWithoutLock(),t.send(n.data),this.messageBuffer.markSent(n)}finally{n()}this.refreshBufferStatus()})}refreshBufferStatus(){let e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new SL,this.sequence=1}},wL;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(wL||={});var TL=65536,EL=1048576,DL=8192,OL=262144;function kL(e){return e===wL.RELIABLE?TL:DL}function AL(e){return e===wL.RELIABLE?EL:OL}var jL=`_lossy`,ML=`_reliable`,NL=`_data_track`,PL=class{constructor(e){this.opts=e;let t=t=>({kind:t,lowWaterMark:kL(t),highWaterMark:AL(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new CL(Object.assign(Object.assign({},t(wL.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new xL(Object.assign(Object.assign({},t(wL.LOSSY)),{bufferFullBehavior:`drop`,shouldSkipSends:e.isReconnecting})),this.dataTrack=new xL(Object.assign(Object.assign({},t(wL.DATA_TRACK_LOSSY)),{bufferFullBehavior:`wait`,shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case wL.RELIABLE:return this.reliable;case wL.LOSSY:return this.lossy;case wL.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case wL.RELIABLE:return this.reliableSub;case wL.LOSSY:return this.lossySub;case wL.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(let e of[this.lossy,this.reliable,this.dataTrack]){let t=e.channelHandle;t&&(t.onmessage=null,t.onerror=null,t.onclose=null)}let t=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)};t(this.lossy,e.createPublisherDataChannel(jL,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(ML,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(NL,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===ML)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===jL)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===NL)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){let e=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};for(let t of[this.lossy,this.reliable,this.dataTrack]){let n=t.channelHandle;t.detach(`peer connections cleaned up`),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}},FL=typeof MediaRecorder<`u`,IL=FL?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},LL=class extends IL{constructor(e,t){if(!FL)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>J(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function RL(){return FL}var zL=1e3,BL=1e4,VL=class extends ${get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=SF(()=>J(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>J(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(Q.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new $T,this.pauseUpstreamLock=new $T,this.trackChangeLock=new $T,this.trackChangeLock.lock().then(t=>J(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==$.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return J(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{FN(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(PN(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{PN(r??e,t)}))})}waitForDimensions(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:zL;return function*(){if(e.kind===$.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);kM()?.os===`iOS`&&(yield zN(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield zN(50)}throw new zM(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return J(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===DP(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),DP(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===$.Source.ScreenShare)return;let n=e._mediaStreamTrack.getSettings(),r=n.deviceId,i=n.groupId,a=e.kind===$.Kind.Audio?`audioinput`:`videoinput`;return t?zF.getInstance().normalizeDeviceId(a,r,i):r}()})}mute(){return J(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return J(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return J(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new zM(`unable to replace an unpublished track`);let n,r;typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return J(this,void 0,void 0,function*(){})}restart(e,t){return J(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let n=e,r=n.deviceId,i=n.facingMode,a=ij(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let o={audio:!1,video:!1};this.kind===$.Kind.Video?o.video=r||i?{deviceId:r,facingMode:i}:!0:o.audio=!r||Object.assign({deviceId:r},a),this.attachedElements.forEach(e=>{FN(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===$.Kind.Video&&(yield s.applyConstraints(a)),s.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(s,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(Q.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),(this.isMuted!==e||this._mediaStreamTrack.enabled===e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Q.Muted:Q.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),aP()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return J(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(Q.UpstreamPaused,this);let e=kM();if(e?.name===`Safari`&&mP(e.version,`12.0`)<0)throw new RM(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return J(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(Q.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return J(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext,localTrack:t};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(PN(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(FN(t._mediaStreamTrack,e),PN(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(Q.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Q.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!RL()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new LL(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},BL)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},HL=class extends VL{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,$.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>J(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=wF(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,TO.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,TO.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===$.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===$.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return J(this,void 0,void 0,function*(){let t;if(e){let n=gN({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}applyConstraints(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{let t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return J(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){sP()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},CF))}setProcessor(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!cP()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(Q.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return J(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(n=>{if(n.type===`outbound-rtp`){t={type:`audio`,streamId:n.id,packetsSent:n.packetsSent,bytesSent:n.bytesSent,timestamp:n.timestamp};let r=e.get(n.remoteId);r&&(t.packetsLost=r.packetsLost,t.jitter=r.jitter,t.roundTripTime=r.roundTripTime)}}),t})}checkForSilence(){return J(this,void 0,void 0,function*(){let e=yield _N(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(Q.AudioSilenceDetected)),e})}};function UL(e,t,n){switch(e.kind){case`audio`:return new HL(e,t,!1,void 0,n);case`video`:return new cR(e,t,!1,n);default:throw new zM(`unsupported track type: ${e.kind}`)}}var WL=Object.values(dN),GL=Object.values(fN),KL=Object.values(pN),qL=[dN.h180,dN.h360],JL=[fN.h180,fN.h360],YL=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new iN(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),XL=[`q`,`h`,`f`];function ZL(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec,c=KN(s,r);if(!i&&!a&&!o||!t||!n)return[{}];i||(i=eR(e,t,n,s),JA.debug(`using video encoding`,i));let l=i.maxFramerate,u=new iN(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&WN(s)&&!c){let e=new aR(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=kM();if(qN()){let r=e.suffix==`h`?2:3,a=iP(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:XL[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:o});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),JA.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let d=e=>(c&&e.forEach(e=>{e.scalabilityMode=o}),e),f;f=e?iR(r?.screenShareSimulcastLayers)??nR(e,u):iR(r?.videoSimulcastLayers)??nR(e,u);let p;if(f.length>0){let e=f[0];f.length>1&&(p=K(f,2)[1]);let r=Math.max(t,n);if(r>=960&&p)return d(rR(t,n,[e,p,u],l));if(r>=480)return d(rR(t,n,[e,u],l))}return d(rR(t,n,[u]))}function QL(e,t,n){return WN(e)&&!KN(e,t)?n[0]?.maxBitrate??0:n.reduce((e,t)=>e+(t.maxBitrate??0),0)}function $L(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&JA.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===$.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),ZL(e.source===$.Source.ScreenShare,i,a,n)}function eR(e,t,n,r){let i=tR(e,t,n),a=i[0].encoding,o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85}return a}function tR(e,t,n){if(e)return KL;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?WL:GL}function nR(e,t){if(e)return YL(t);let n=t.width,r=t.height,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?qL:JL}function rR(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=XL.length)return;let o=Math.min(e,t),s={rid:XL[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=kM(),u=l?.name===`Firefox`&&l.os!==`iOS`||a===0;n.encoding.priority&&u&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),cP()&&fP()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,JA.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),JA.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function iR(e){if(e)return e.slice().sort((e,t)=>{let n=e.encoding,r=t.encoding;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var aR=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function oR(e){switch(e.source){case $.Source.Camera:return`maintain-framerate`;case $.Source.ScreenShare:return`maintain-resolution`;default:return`balanced`}}var sR=5e3,cR=class extends VL{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,$.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>J(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(Q.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=wF(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new $T}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!sP())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},CF))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return J(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=lj(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return J(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=lj(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===$.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===$.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return J(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}isSvcPublish(e){return WN(e)&&!KN(e,this.publishOptions)}setPublishingQuality(e){let t=[];for(let n=NN.LOW;n<=NN.HIGH;n+=1)t.push(new hA({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(this.isSvcPublish(this.codec),t)}restartTrack(e){return J(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=gN({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=lj(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return J(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return J(this,void 0,void 0,function*(){if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let e=yield this.senderLock.lock();try{let e;try{e=yield this.waitForDimensions()}catch(e){this.log.warn(`could not determine new track dimensions, skipping encoding recompute`,Object.assign(Object.assign({},this.logContext),{error:e}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===e.width&&this.lastEncodedDimensions.height===e.height)return;let n=ZL(this.source===$.Source.ScreenShare,e.width,e.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=e;for(let e of this.simulcastCodecs){var t=K(e,2);let n=t[0],r=t[1];if(!r.sender||r.sender.transport?.state===`closed`||!sN(n))continue;let i=Object.assign({},this.publishOptions),a=$L(this,n,i);a&&(yield this.applyEncodingsToSender(r.sender,a),r.encodings=a)}}catch(e){this.log.warn(`failed to apply recomputed encodings`,Object.assign(Object.assign({},this.logContext),{error:e}))}finally{e()}})}applyEncodingsToSender(e,t){return J(this,void 0,void 0,function*(){let n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach((e,n)=>{if(e.active===!1)return;let r=t[n];r.scaleResolutionDownBy!==void 0&&(e.scaleResolutionDownBy=r.scaleResolutionDownBy),r.maxBitrate!==void 0&&(e.maxBitrate=r.maxBitrate),r.maxFramerate!==void 0&&(e.maxFramerate=r.maxFramerate),r.priority!==void 0&&(e.priority=r.priority,e.networkPriority=r.priority)}),this.log.debug(`updating sender encodings after track restart`,Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return J(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=lj(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return J(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(let e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)})}applyDegradationPreference(e){return J(this,void 0,void 0,function*(){if(e)try{this.log.debug(`setting degradationPreference to ${this.degradationPreference}`,this.logContext);let t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){return J(this,void 0,void 0,function*(){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},sR))})}setPublishingCodecs(e){return J(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(this.isSvcPublish(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=lj(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(this.isSvcPublish(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield lR(t.sender,t.encodings,e.qualities,this.senderLock,this.isSvcPublish(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return J(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield lR(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return J(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&WN(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),aP()&&this.isInBackground&&this.source===$.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function lR(e,t,n,r,i,a,o){return J(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),s=r.encodings;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=uR(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),QN()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function uR(e){switch(e){case`f`:return NN.HIGH;case`h`:return NN.MEDIUM;case`q`:return NN.LOW;default:return NN.HIGH}}function dR(e,t,n,r){if(!n)return[new KO({quality:NN.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new aR(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new KO({quality:Math.min(NN.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new KO({quality:uR(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var fR=2e3,pR=`leave-reconnect`,mR=1e4,hR=3e4,gR=3,_R=3,vR;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(vR||={});var yR=64e3,bR=class extends pj.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get serverVersion(){return this.latestJoinResponse?.serverInfo?.version||this.latestJoinResponse?.serverVersion||void 0}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=_L.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=vR.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=JA,this.reliableReceivedState=new PI(hR),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>J(this,[e],void 0,function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug(`on data channel ${n.id}, ${n.label}`)}()}),this.handleDataMessage=e=>J(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t=yield this.decodeDataMessage(e);if(!t)return;let n=JO.fromBinary(t);if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(Z.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`);return}let e;try{e=yield this.e2eeManager.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex)}catch(e){this.log.debug(`failed to decrypt data packet`,{error:e,participantIdentity:n.participantIdentity});return}let t=new JO({value:ZO.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&xR(t,t.value.value),this.emit(Z.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&xR(n,n.value.value),this.emit(Z.DataPacketReceived,n,PO.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>J(this,void 0,void 0,function*(){let t=yield this.decodeDataMessage(e);t&&this.emit(`dataTrackPacketReceived`,t)}),this.handleDataError=e=>{if(this._isClosed)return;let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(typeof RTCErrorEvent<`u`&&e instanceof RTCErrorEvent&&e.error){let n=e.error;this.log.error(`DataChannel error on ${t}: ${n.message}`,{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error(`Unknown DataChannel error on ${t}`,{event:e})},this.handleDataChannelClose=e=>()=>{!this._isClosed&&this.pcManager?.publisher.getConnectionState()===`connected`&&this.log.error(`publisher data channel '${wL[e]}' closed unexpectedly`,this.logContext)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`),this.emit(Z.Disconnected),this.close(`gave up reconnecting after ${this.reconnectAttempts} attempts, ${e}ms`)},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===pR&&(i=0),this.log.debug(`reconnecting in ${i}ms`),this.clearReconnectTimeout(),this.token&&this.emit(Z.TokenRefreshed,this.token),this.reconnectTimeout=XM.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===vR.Connected&&e();let n=()=>{this.off(Z.Disconnected,r),e()},r=()=>{this.off(Z.Restarted,n),t()};this.once(Z.Restarted,n),this.once(Z.Disconnected,r)}),this.onRtpMapAvailable=e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();EP(n)&&t.set(e.payload,n)}),this.emit(Z.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>J(this,void 0,void 0,function*(){this.url&&(yield fetch(kP(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===TI.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===TI.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(CO.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>J(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(kP(this.url),{method:`HEAD`}),zN(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=YA(e.loggerName??qA.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new kI(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new $T,this.dataProcessLock=new $T,this.dataChannels=new PL({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(e,t)=>this.emit(Z.DCBufferStatusChanged,t,e)}),this.client.onParticipantUpdate=e=>this.emit(Z.ParticipantUpdate,e),this.client.onConnectionQuality=e=>{this.handleLocalConnectionQuality(e),this.emit(Z.ConnectionQualityUpdate,e)},this.client.onRoomUpdate=e=>this.emit(Z.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Z.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Z.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Z.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Z.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Z.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(Z.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(Z.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s=!a&&YP(),c;if(s){i.pcManager||(yield i.configure(),i.applyInitialPublisherLayout());let e=yield i.pcManager?.publisher.createInitialOffer();e&&(c=jI(e.offer,e.offerId))}if(r?.aborted)throw LM.cancelled(`Connection aborted`);if(!a&&i.shouldFailOnV1Path)throw i.shouldFailOnV1Path=!1,LM.serviceNotFound(`Simulated v1 path failure`,`v0-rtc`);let l=yield i.client.join(e,t,n,r,a,c);i._isClosed=!1,i.latestJoinResponse=l,i.participantSid=l.participant?.sid,i.subscriberPrimary=l.subscriberPrimary,s?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(l)):(i.pcManager||(yield i.configure(l,!a),a||i.applyInitialPublisherLayout()),(!i.subscriberPrimary||l.fastPublish)&&i.negotiate().catch(e=>{i.log.error(e)})),i.registerOnLineListener(),i.clientConfiguration=l.clientConfiguration,i.emit(Z.SignalConnected,l);let u=l.serverInfo;return u||={version:l.serverVersion,region:l.serverRegion},i.log.info(`connected to Livekit Server ${Object.entries(u).map(e=>{let t=K(e,2);return`${t[0]}: ${t[1]}`}).join(`, `)}`),{joinResponse:l,serverInfo:u}}catch(o){if(o instanceof LM){if(o.reason===IM.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===IM.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.pcManager&&(i.pcManager.onStateChange=void 0,yield i.cleanupPeerConnections()),i.join(e,t,n,r,!0)}throw o}}()})}close(e){return J(this,void 0,void 0,function*(){let t=yield this.closingLock.lock();if(this.isClosed){t();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(Z.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(e)}finally{t()}})}cleanupPeerConnections(){return J(this,void 0,void 0,function*(){this.dataChannels.teardown(),yield this.pcManager?.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return J(this,void 0,void 0,function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(let e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new zM(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=XM.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(LM.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{XM.clearTimeout(r),t(e)},reject:()=>{XM.clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,{error:e})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.dataChannelForKind(wL.RELIABLE,!0)?.readyState}getConnectedServerAddress(){return J(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return J(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==vL.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new yL(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new yL(`publisher-only`,this.loggerOptions,e)}this.emit(Z.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>J(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`),this.transportConnectingSince=e===vL.CONNECTING?Date.now():void 0,[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===vL.CONNECTED){let e=this.pcState===vR.New;this.pcState=vR.Connected,e&&this.emit(Z.Connected,this.latestJoinResponse)}else e===vL.FAILED&&(this.pcState===vR.Connected||this.pcState===vR.Reconnecting)&&(this.pcState=vR.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?CO.RR_SUBSCRIBER_FAILED:CO.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===TI.RECONNECTING,i=[vL.FAILED,vL.CLOSING,vL.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(Z.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(Z.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>J(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.pcManager.mode===`publisher-only`&&(this.midToTrackId=n),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>J(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,{cid:e.cid,track:e.track?.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,{cid:e.cid});return}let t=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Z.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Z.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(Z.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Z.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Z.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Z.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(Z.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(Z.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(Z.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,CO.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info(`client leave request received (action=${e?.action})`,{reason:e?.reason}),e.regions&&(this.log.debug(`updating regions`),this.emit(Z.ServerRegionsReported,e.regions)),e.action){case aA.DISCONNECT:this.emit(Z.Disconnected,e?.reason),this.close(`server leave: ${SO[e.reason]??e.reason}`);break;case aA.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(pR);break;case aA.RESUME:this.handleDisconnect(pR)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if((this.signalOpts?.e2eeEnabled||this.frameMetadataWorker&&!_F())&&pF()&&(this.log.debug(`E2EE - setting up transports with insertable streams`),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===xO.ENABLED&&(t.iceTransportPolicy=`relay`),t}applyInitialPublisherLayout(){this.createDataChannels(),cP()||this.addMediaSections(gR,_R)}addMediaSections(e,t){var n;let r={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,r);let i=this.pcManager?.mode===`publisher-only`;for(let e=0;e<t;e++){let e=this.pcManager?.addPublisherTransceiverOfKind(`video`,r);if(i&&e){let t=GN(e);this.log.debug(`dependency descriptor negotiated for received video`,{negotiated:t})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return J(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error(`unsupported data type`,{data:e.data})})}createSender(e,t,n){return J(this,void 0,void 0,function*(){let r;if(BN())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(VN())this.log.warn(`using add-track fallback`),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new VM(`Required webRTC APIs not supported on this device`);return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return J(this,void 0,void 0,function*(){let i;if(BN())i=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(VN())this.log.debug(`using add-track fallback`),i=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new VM(`Cannot stream on this device`);return i&&this.setupFrameMetadataSender(i,n),i})}get frameMetadataWorker(){return(this.options.frameMetadata??this.options.packetTrailer)?.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=this.frameMetadataWorker;if(!n||this.signalOpts?.e2eeEnabled)return;let r=t.frameMetadata??t.packetTrailer,i=yF(r);if(_F()){i&&(e.transform=new RTCRtpScriptTransform(n,{kind:`encode`,packetTrailer:r}));return}if(!vF(this.options.frameMetadata??this.options.packetTrailer)||!(`createEncodedStreams`in e)){i&&this.log.warn(`frame metadata transform not supported; skipping write`,this.logContext);return}let a=e.createEncodedStreams(),o=a.readable,s=a.writable;i?n.postMessage({kind:`encode`,data:{readableStream:o,writableStream:s,packetTrailer:r}},[o,s]):o.pipeTo(s)}createTransceiverRTCRtpSender(e,t,n){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new VM(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),LP(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new VM(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new VM(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;let t=e.updates.find(e=>e.participantSid===this.participantSid);t&&(t.quality===bO.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||=XM.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==vR.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn(`local connection quality lost while publishing, triggering full reconnect`,this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect(`connection quality lost`,CO.RR_PUBLISHER_FAILED))},mR)}clearLostQualityTimeout(){this.lostQualityTimeout&&=(XM.clearTimeout(this.lostQualityTimeout),void 0)}hasActivePublisherSenders(){return this.pcManager?.publisher.getSenders().some(e=>!!e.track&&e.track.readyState===`live`)??!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:CO.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect(`reconcile`,e)}attemptReconnect(e){return J(this,void 0,void 0,function*(){if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn(`already attempting reconnect, returning early`);return}this.clearLostQualityTimeout(),(this.clientConfiguration?.resumeConnection===xO.DISABLED||(this.pcManager?.currentState??vL.NEW)===vL.NEW)&&(this.fullReconnectOnNext=!0);let t=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let n=!1;try{this.attemptingReconnect=!0,t?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),n=!0}catch(e){this.reconnectAttempts+=1;let n=!0;e instanceof VM?(this.log.debug(`received unrecoverable error`,{error:e}),n=!1):(t||!(e instanceof JM))&&(this.fullReconnectOnNext=!0),n?this.handleDisconnect(`reconnect`,CO.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`),this.emit(Z.Disconnected),yield this.close(`gave up reconnecting after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms`))}finally{this.attemptingReconnect=!1,n&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug(`full reconnect requested during in-progress attempt, dispatching`),this.handleDisconnect(`reconnect`))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,{error:e})}return null}restartConnection(e){return J(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new VM(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`),this.emit(Z.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`),new JM;n=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){throw e instanceof LM&&e.reason===IM.NotAllowed?new VM(`could not reconnect, token might be expired`):new JM}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(Z.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==TI.CONNECTED)throw new JM(`Signal connection got severed during reconnect`);(t=this.regionStrategy)==null||t.resetAttempts(),this.emit(Z.Restarted)}catch(e){let t=yield this.regionStrategy?.getNextUrl();if(t){yield this.restartConnection(t);return}throw(n=this.regionStrategy)==null||n.resetAttempts(),e}})}resumeConnection(e){return J(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new VM(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new VM(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`),this.emit(Z.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,{error:e})),e instanceof LM&&e.reason===IM.NotAllowed?new VM(`could not reconnect, token might be expired`):e instanceof LM&&e.reason===IM.LeaveRequest?e:new JM(t)}if(this.emit(Z.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==TI.CONNECTED)throw new JM(`Signal connection got severed during reconnect`);this.client.setReconnected();let n=this.dataChannelForKind(wL.RELIABLE);n?.readyState===`open`&&n.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(e=>{this.log.warn(`failed to resend reliable messages after resume`,Object.assign(Object.assign({},this.logContext),{error:e}))}),this.emit(Z.Resumed)})}waitForPCInitialConnection(e,t){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new VM(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return J(this,void 0,void 0,function*(){this.pcState=vR.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`);try{if(yield zN(fR),!this.pcManager)throw new VM(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=vR.Connected}catch(e){throw this.pcState=vR.Disconnected,LM.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcAck(e,t){return J(this,void 0,void 0,function*(){let n=new JO({destinationIdentities:[e],kind:YO.RELIABLE,value:{case:`rpcAck`,value:new ok({requestId:t})}});yield this.sendDataPacket(n,wL.RELIABLE)})}sendDataPacket(e,t){return J(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=mF(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new XO({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===wL.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let n=e.toBinary(),r=Math.min(this.pcManager?.getMaxPublisherMessageSize()??yR,yR);if(r!==void 0&&r!==0&&n.byteLength>r)throw new UM(`cannot publish data packet larger than ${r} bytes (got ${n.byteLength})`);t===wL.RELIABLE?yield this.reliableChannel.send(n,e.sequence):yield this.lossyChannel.send(n)})}sendDataTrackFrame(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(wL.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(wL.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return J(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new VM(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw LM.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{t.log.error(e)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield zN(50)}throw LM.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return J(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;let e=this.pcManager.currentState;return![vL.CONNECTING,vL.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===vL.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn(`transport stuck in connecting state`,this.logContext),!1):!0}negotiate(){return J(this,void 0,void 0,function*(){return new EM((e,t)=>J(this,void 0,void 0,function*(){if(!this.pcManager){t(new HM(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`),e()};this.isClosed&&t(new HM(`cannot negotiate on closed engine`)),this.on(Z.Closing,r),this.on(Z.Restarting,r),this.pcManager.publisher.off(QI.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(QI.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof HM&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,CO.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(Z.Closing,r),this.off(Z.Restarting,r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new CA({answer:this.pcManager.mode===`publisher-only`?i?jI({sdp:i.sdp,type:i.type}):void 0:o?jI({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?jI({sdp:r.sdp,type:r.type}):void 0:a?jI({sdp:a.sdp,type:a.type}):void 0,subscription:new Jk({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:CN(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new wA({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new Fk({info:XF.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new TA({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(wL.LOSSY),Dk.PUBLISHER),t(this.dataChannelForKind(wL.RELIABLE),Dk.PUBLISHER),t(this.dataChannelForKind(wL.LOSSY,!0),Dk.SUBSCRIBER),t(this.dataChannelForKind(wL.RELIABLE,!0),Dk.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&XM.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){sP()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){sP()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>K(e,1)[0]===t);if(e)return e[1]}}};function xR(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var SR=YA(qA.Region),CR=5e3,wR=3e4,TR=class e{static fetchRegionSettings(t,n,r){return J(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${ER(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=qP(e.headers),n=t?t*1e3:CR;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}throw e.status===401?LM.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status):LM.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof LM?e:r?.aborted?LM.cancelled(`Region fetching was aborted`):LM.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return J(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>J(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof LM&&i.reason===IM.NotAllowed){SR.debug(`token is not valid, cancelling auto region refresh`);return}SR.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(SR.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},wR))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(t){this.token=t;let n=this.getServerUrl(),r=e.cache.get(n.hostname);e.scheduleRefetch(this.serverUrl,this.token,r?.maxAgeInMs??CR)}isCloud(){return lP(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return J(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return J(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),SR.info(`switching to region: ${e.region}`,{region:e.region}),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};TR.cache=new Map,TR.settingsTimeouts=new Map,TR.connectionTrackers=new Map,TR.fetchLock=new $T;function ER(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}function DR(){return new CompressionStream(`deflate-raw`)}function OR(){return new DecompressionStream(`deflate-raw`)}function kR(e,t){return J(this,void 0,void 0,function*(){let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();return r.write(e).catch(()=>{}),r.close().catch(()=>{}),AR(n.readable,t)})}function AR(e,t){return J(this,void 0,void 0,function*(){let n=e.getReader(),r=[],i=0;for(;;){let e=yield n.read(),a=e.done,o=e.value;if(a)break;if(r.push(o),i+=o.byteLength,typeof t==`number`&&i>t)throw yield n.cancel(),new qM(`Decompressed payload exceeds the maximum payload size of ${t} bytes`,KM.PayloadTooLarge)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a})}var jR=15e3,MR=5e9,NR=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(typeof this.totalByteSize==`number`&&this.totalByteSize!==0){if(e&&this.bytesReceived<this.totalByteSize)throw new qM(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,KM.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new qM(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,KM.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}},PR=class extends NR{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>J(this,void 0,void 0,function*(){var n;try{let t=this.signal;if(t?.aborted)throw t.reason;let r=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return r.done?(this.validateBytesReceived(!0),typeof this.totalByteSize==`number`&&((n=this.onProgress)==null||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(e){throw t(),e}}),return(){return J(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=lj(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},FR=class extends NR{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>J(this,void 0,void 0,function*(){var i;try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),typeof this.totalByteSize==`number`&&((i=this.onProgress)==null||i.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new qM(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,KM.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return J(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=lj(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},IR=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:MR;this.log=JA,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new qM(`A text stream handler for topic "${e}" has already been set.`,KM.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new qM(`A byte stream handler for topic "${e}" has already been set.`,KM.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let a=new qM(`Participant ${e} unexpectedly disconnected in the middle of sending data`,KM.AbnormalEnd);for(let e of n){var r=K(e,2);let t=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(t)}for(let e of t){var i=K(e,2);let t=i[0];i[1].controller.error(a),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}}handleStreamHeader(e,t,n){switch(e.contentHeader.case){case`byteHeader`:{let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:NP(e.timestamp),attributes:e.attributes,encryptionType:n},o;switch(e.compression){case bk.DEFLATE_RAW:if(!JP()){JA.warn(`Data stream ${e.streamId} received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping...`);return}o=!0;break;case bk.NONE:o=!1;break;default:JA.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){r(new PR(a,LR(e.streamId,o?kR(s,this.maxPayloadByteLength):s),NP(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.byteStreamControllers.has(e.streamId))throw new qM(`A data stream read is already in progress for a stream with id ${e.streamId}.`,KM.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new PR(a,o?HR(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(RR(e.streamId)),NP(e.totalLength)),{identity:t});return}case`textHeader`:{let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds},o;switch(e.compression){case bk.DEFLATE_RAW:if(!JP()){JA.warn(`Data stream ${e.streamId} received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping...`);return}o=!0;break;case bk.NONE:o=!1;break;default:JA.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){let n=o?kR(s,this.maxPayloadByteLength):s;r(new FR(a,LR(e.streamId,n),NP(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new qM(`A data stream read is already in progress for a stream with id ${e.streamId}.`,KM.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new FR(a,o?UR(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(RR(e.streamId)),NP(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?n.controller.enqueue(e):(n.controller.error(new qM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,KM.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?r.controller.enqueue(e):(r.controller.error(new qM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,KM.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new qM(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,KM.AbnormalEnd)):n.controller.close()):n.controller.error(new qM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,KM.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new qM(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,KM.AbnormalEnd)):r.controller.close()):r.controller.error(new qM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,KM.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}};function LR(e,t){return new ReadableStream({start:n=>J(this,void 0,void 0,function*(){let r=yield t;n.enqueue(new wk({streamId:e,chunkIndex:BigInt(0),content:r})),n.close()})})}function RR(e){let t=-1;return new TransformStream({transform:(n,r)=>{let i=NP(n.chunkIndex);if(i<=t){JA.warn(`ignoring duplicate chunk ${i} ${n.version>0?`(version ${n.version})`:``} for data stream ${e} (last processed: ${t})`);return}if(i>t+1)throw new qM(`Missing chunk(s) ${t+1}..${i-1} for data stream ${e} - cannot reassemble payload`,KM.Incomplete);t=i,n.content.length!==0&&r.enqueue(n)}})}function zR(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function BR(e){let t=0;return new TransformStream({transform:(n,r)=>{n.byteLength>0&&(r.enqueue(new wk({streamId:e,chunkIndex:PP(t),content:n})),t+=1)}})}function VR(e){let t=new TextDecoder(`utf-8`),n=new TextEncoder,r=0,i=n=>{try{return n?t.decode(n,{stream:!0}):t.decode()}catch(t){throw new qM(`Cannot decode compressed data stream ${e} as text: ${t}`,KM.DecodeFailed)}};return new TransformStream({transform:(t,a)=>{let o=i(t);o.length>0&&(a.enqueue(new wk({streamId:e,chunkIndex:PP(r),content:n.encode(o)})),r+=1)},flush:t=>{let a=i();a.length>0&&(t.enqueue(new wk({streamId:e,chunkIndex:PP(r),content:n.encode(a)})),r+=1)}})}function HR(e,t,n){return e.pipeThrough(RR(t)).pipeThrough(zR()).pipeThrough(OR()).pipeThrough(WR(t,n)).pipeThrough(BR(t))}function UR(e,t,n){return e.pipeThrough(RR(t)).pipeThrough(zR()).pipeThrough(OR()).pipeThrough(WR(t,n)).pipeThrough(VR(t))}function WR(e,t){let n=0;return new TransformStream({transform:(r,i)=>{if(n+=r.byteLength,n>t)throw new qM(`Data stream ${e} exceeds the maximum payload size of ${t} bytes`,KM.PayloadTooLarge);i.enqueue(r)}})}var GR=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return J(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},KR=class extends GR{},qR=class extends GR{};function JR(e,t,n){return new Ck({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:PP(e.timestamp),totalLength:PP(e.size),attributes:e.attributes,compression:n?.compression??bk.NONE,inlineContent:n?.inlineContent,contentHeader:{case:`textHeader`,value:new xk({version:t?.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:t?.replyToStreamId,operationType:t?.type===`update`?yk.UPDATE:yk.CREATE})}})}function YR(e,t){return new Ck({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:PP(e.timestamp),totalLength:PP(e.size),attributes:e.attributes,compression:t?.compression??bk.NONE,inlineContent:t?.inlineContent,contentHeader:{case:`byteHeader`,value:new Sk({name:e.name})}})}function XR(e,t){return new JO({destinationIdentities:t,value:{case:`streamHeader`,value:e}})}var ZR=new TextEncoder,QR=class{constructor(e,t,n,r,i){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=i}setupEngine(e){this.engine=e}sendText(e,t){return J(this,void 0,void 0,function*(){var n;let r=crypto.randomUUID(),i=ZR.encode(e),a=i.byteLength,o=t?.compress??!0,s={id:r,mimeType:`text/plain`,timestamp:Date.now(),topic:t?.topic??``,size:a,attributes:t?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?PO.GCM:PO.NONE},c=o&&JP()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?$R.fromStream(GP(i).pipeThrough(DR())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let e=i,r=bk.NONE;if(c){let t=yield c.collect();t.byteLength<i.byteLength&&(e=t,r=bk.DEFLATE_RAW)}let a=XR(JR(s,void 0,{compression:r,inlineContent:e}),t?.destinationIdentities);if(a.toBinary().byteLength<=jR)return yield this.engine.sendDataPacket(a,wL.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let l=(t?.attachments)?.map(()=>crypto.randomUUID()),u=l?l.length+1:1,d=Array(u).fill(0),f=(e,n)=>{var r;d[n]=e,(r=t?.onProgress)==null||r.call(t,d.reduce((e,t)=>e+t,0)/u)};if(c){s.attachedStreamIds=l;let e=XR(JR(s,void 0,{compression:bk.DEFLATE_RAW}),t?.destinationIdentities);yield this.sendChunkedByteStream(e,r,t?.destinationIdentities,c.stream().pipeThrough(ez(i.length,e=>f(e,0)))),i.length===0&&f(1,0)}else{let n=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:l,attributes:t?.attributes});yield n.write(e),f(1,0),yield n.close(),s=n.info}return t?.attachments&&l&&(yield Promise.all(t.attachments.map((e,n)=>J(this,void 0,void 0,function*(){return this._sendFile(l[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{f(e,n+1)}})})))),s})}sendBytes(e,t){return J(this,void 0,void 0,function*(){var n,r;let i=crypto.randomUUID(),a=t?.destinationIdentities,o=t?.compress??!0,s={id:i,name:t?.name??`unknown`,mimeType:t?.mimeType??`application/octet-stream`,timestamp:Date.now(),topic:t?.topic??``,size:e.byteLength,attributes:t?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?PO.GCM:PO.NONE},c=ez(e.length,t?.onProgress),l=o&&JP()&&this.allRecipientsSupportV2(a)&&this.allRecipientsSupportCompression(a)?$R.fromStream(GP(e).pipeThrough(c).pipeThrough(DR())):null;if(this.allRecipientsSupportV2(a)){let r=e,i=bk.NONE;if(l){let t=yield l.collect();t.byteLength<e.byteLength&&(r=t,i=bk.DEFLATE_RAW)}let o=XR(YR(s,{compression:i,inlineContent:r}),a);if(o.toBinary().byteLength<=jR)return yield this.engine.sendDataPacket(o,wL.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let u=XR(YR(s,{compression:l?bk.DEFLATE_RAW:bk.NONE}),a),d=l?l.stream():GP(e).pipeThrough(c);return yield this.sendChunkedByteStream(u,i,a,d),e.length===0&&((r=t?.onProgress)==null||r.call(t,1)),s})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantClientProtocol(e)>=2)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantCapabilities(e).includes(mk.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,n,r){return J(this,void 0,void 0,function*(){var i,a,o,s;let c=this.engine;yield tz(c,e);let l=0;try{for(var u=!0,d=lj(KP(r,jR)),f;f=yield d.next(),i=f.done,!i;u=!0){s=f.value,u=!1;let e=new JO({destinationIdentities:n,value:{case:`streamChunk`,value:new wk({content:s,streamId:t,chunkIndex:PP(l)})}});yield c.sendDataPacket(e,wL.RELIABLE),l+=1}}catch(e){a={error:e}}finally{try{!u&&!i&&(o=d.return)&&(yield o.call(d))}finally{if(a)throw a.error}}yield nz(t,n,c)})}streamText(e){return J(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?PO.GCM:PO.NONE,attachedStreamIds:e?.attachedStreamIds},i=XR(JR(r,e),n);yield tz(this.engine,i);let a=0,o=this.engine,s=new WritableStream({write(e){return J(this,void 0,void 0,function*(){for(let r of WP(e,jR)){let e=new wk({content:r,streamId:t,chunkIndex:PP(a)}),i=new JO({destinationIdentities:n,value:{case:`streamChunk`,value:e}});yield o.sendDataPacket(i,wL.RELIABLE),a+=1}})},close(){return J(this,void 0,void 0,function*(){yield nz(t,n,o)})},abort(e){console.log(`Sink error:`,e)}}),c=()=>J(this,void 0,void 0,function*(){yield l.close()});o.once(Z.Closing,c);let l=new KR(s,r,()=>this.engine.off(Z.Closing,c));return l})}sendFile(e,t){return J(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return J(this,void 0,void 0,function*(){var r;let i=n?.destinationIdentities,a=(n?.compress??!0)&&JP()&&this.allRecipientsSupportV2(i)&&this.allRecipientsSupportCompression(i),o={id:e,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic??``,timestamp:Date.now(),size:t.size,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?PO.GCM:PO.NONE},s=XR(YR(o,{compression:a?bk.DEFLATE_RAW:bk.NONE}),i),c=t.stream().pipeThrough(ez(t.size,n?.onProgress)),l=a?c.pipeThrough(DR()):c;return yield this.sendChunkedByteStream(s,e,i,l),t.size===0&&((r=n?.onProgress)==null||r.call(n,1)),o})}streamBytes(e){return J(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?PO.GCM:PO.NONE},i=XR(YR(r),n);yield tz(this.engine,i);let a=0,o=new $T,s=this.engine,c=this.log;return new qR(new WritableStream({write(e){return J(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+jR),o=new JO({destinationIdentities:n,value:{case:`streamChunk`,value:new wk({content:r,streamId:t,chunkIndex:PP(a)})}});yield s.sendDataPacket(o,wL.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return J(this,void 0,void 0,function*(){yield nz(t,n,s)})},abort(e){c.error(`Sink error:`,e)}}),r)})}},$R=class e{constructor(e){this.state=e}static fromStream(t){return new e({type:`stream`,stream:t})}collect(){return J(this,void 0,void 0,function*(){switch(this.state.type){case`stream`:let e=yield AR(this.state.stream);return this.state={type:`collected`,bytes:e},e;case`collected`:return this.state.bytes}})}stream(){switch(this.state.type){case`stream`:return this.state.stream;case`collected`:return GP(this.state.bytes)}}};function ez(e,t){let n=0;return new TransformStream({transform(r,i){n+=r.byteLength,t&&typeof e==`number`&&e>0&&t(Math.min(n/e,1)),i.enqueue(r)}})}function tz(e,t){return J(this,void 0,void 0,function*(){if(t.toBinary().byteLength>jR)throw new qM(`data stream header exceeds the ${jR}-byte limit; reduce attribute size`,KM.HeaderTooLarge);yield e.sendDataPacket(t,wL.RELIABLE)})}function nz(e,t,n){return J(this,void 0,void 0,function*(){let r=new JO({destinationIdentities:t,value:{case:`streamTrailer`,value:new Tk({streamId:e})}});yield n.sendDataPacket(r,wL.RELIABLE)})}function rz(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function iz(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var az=1,oz=2,sz=4,cz=8,lz=0,uz=12,dz=5,fz=7,pz=3,mz=3,hz=2,gz=1,_z=0,vz=3,yz=2,bz=2,xz=1,Sz=0,Cz;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(Cz||={});var wz=class e extends FM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=Cz[t]}static tooShort(){return new e(`Too short to contain a valid header`,Cz.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,Cz.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,Cz.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,Cz.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,Cz.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,Cz.MalformedExt)}},Tz;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(Tz||={});var Ez=class e extends FM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=Tz[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,Tz.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,Tz.TooSmallForPayload)}},Dz=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},Oz;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(Oz||={});var kz=class extends Dz{},Az=class e extends kz{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=az,t.setUint8(n,e.lengthBytes),n+=az,t.setBigUint64(n,this.timestamp),n+=cz;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};Az.tag=Oz.UserTimestamp,Az.lengthBytes=8;var jz=class e extends kz{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=az,t.setUint8(n,e.lengthBytes),n+=az,t.setUint8(n,this.keyIndex),n+=az;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=az;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};jz.tag=Oz.E2ee,jz.lengthBytes=13;var Mz=class e extends Dz{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=GF(t),r,i,a=0;for(;n.byteLength-a>=2;){let e=n.getUint8(a);a+=az;let t=n.getUint8(a);if(a+=az,e!==Sz)switch(e){case Oz.UserTimestamp:if(n.byteLength-a<Az.lengthBytes)throw wz.malformedExt(e);r=new Az(n.getBigUint64(a)),a+=t;break;case Oz.E2ee:if(n.byteLength-a<jz.lengthBytes)throw wz.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=az,t+=e*az,s[e]=n.getUint8(t)}i=new jz(o,s),a+=t;break;default:if(n.byteLength-a<t)throw wz.malformedExt(e);a+=t}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},Nz={from(e){return{payload:e.payload,extensions:new Mz({userTimestamp:e.userTimestamp?new Az(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},Pz=Symbol.for(`lk.track`),Fz=Symbol.for(`lk.data-track`),Iz=class{constructor(e,t,n){this.trackSymbol=Pz,this.isLocal=!1,this.typeSymbol=Fz,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let t=K(this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),2),n=t[0];return t[1].catch(()=>{}),n}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},Lz=class e extends Dz{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new Mz}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((yz+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-yz-e}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=uz;return t>0&&(r+=yz+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Ez.tooSmallForHeader();let t=0,n;switch(this.marker){case Rz.Inter:n=_z;break;case Rz.Final:n=gz;break;case Rz.Start:n=hz;break;case Rz.Single:n=vz}t|=n<<pz;let r=this.extensionsMetrics(),i=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;i>0&&(t|=4);let s=0;if(e.setUint8(s,t),s+=az,e.setUint8(s,0),s+=az,e.setUint16(s,this.trackHandle),s+=oz,e.setUint16(s,this.sequence.value),s+=oz,e.setUint16(s,this.frameNumber.value),s+=oz,e.setUint32(s,this.timestamp.asTicks()),s+=sz,i>0){let t=a-1;e.setUint16(s,t),s+=oz;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+s));s+=n;for(let t=0;t<o;t+=1)e.setUint8(s,0),s+=az}let c=this.toBinaryLengthBytes();if(s!==c)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${s} bytes but expected length was ${c} bytes`);return c}static fromBinary(t){let n=GF(t);if(n.byteLength<uz)throw wz.tooShort();let r=0,i=n.getUint8(r);r+=az;let a=i>>dz&fz;if(a>lz)throw wz.unsupportedVersion(a);let o;switch(i>>pz&mz){case hz:o=Rz.Start;break;case gz:o=Rz.Final;break;case vz:o=Rz.Single;break;case _z:default:o=Rz.Inter}let s=(i>>bz&xz)>0;r+=az;let c;try{c=JF.fromNumber(n.getUint16(r))}catch(e){throw e instanceof qF&&(e.isReason(KF.Reserved)||e.isReason(KF.TooLarge))?wz.invalidHandle(e):e}r+=oz;let l=HF.u16(n.getUint16(r));r+=oz;let u=HF.u16(n.getUint16(r));r+=oz;let d=UF.fromRtpTicks(n.getUint32(r));r+=sz;let f=new Mz;if(s){if(n.byteLength-r<oz)throw wz.missingExtWords();let e=n.getUint16(r);r+=oz;let t=4*(e+1)-yz;if(r+t>n.byteLength)throw wz.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),a=K(Mz.fromBinary(i),2),o=a[0],s=a[1];f=o,r+=s}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},Rz;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(Rz||={});var zz=class e extends Dz{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw Ez.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=az;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=GF(t),r=K(Lz.fromBinary(n),2),i=r[0],a=r[1],o=n.buffer.slice(n.byteOffset+a,n.byteOffset+n.byteLength);return[new e(i,new Uint8Array(o)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Bz=YA(qA.DataTracks),Vz=class e extends FM{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=Hz[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,Hz.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,Hz.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,Hz.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,Hz.Incomplete,t)}},Hz;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(Hz||={});var Uz=class e{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Rz.Single:return this.frameFromSingle(e,t);case Rz.Start:return this.beginPartial(e,t);case Rz.Inter:case Rz.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){if(e.header.marker!==Rz.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);let n=t?.maxPartialFrames??1;if(this.partials.size>=n){let n=this.peekOldestPartialFrameNumber();if(typeof n!=`number`)throw Error(`Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ${this.partials.size}.`);if(this.partials.delete(n),t?.throwOnInterruption)throw Vz.interrupted(n,e.header.frameNumber.value);Bz.warn(`Data track frame ${n} was interrupted by single-packet frame ${e.header.frameNumber.value}, dropping.`)}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==Rz.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);let n=e.header.sequence,r=e.header.frameNumber.value,i={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},a=t?.maxPartialFrames??1;for(;this.partials.size>=a;){let e=this.peekOldestPartialFrameNumber();if(typeof e!=`number`)break;if(this.partials.delete(e),t?.throwOnInterruption)throw Vz.interrupted(e,r);Bz.warn(`Data track partials full (max ${a}), evicted oldest frame ${e} to make room for new frame ${r}.`)}return this.partials.set(r,i),null}pushToPartial(t){if(t.header.marker!==Rz.Inter&&t.header.marker!==Rz.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);let n=t.header.frameNumber.value,r=this.partials.get(n);if(!r)throw this.partials.delete(n),Vz.unknownFrame(n);if(r.payloads.size>=e.MAX_BUFFER_PACKETS)throw this.partials.delete(n),Vz.bufferFull(n);return r.payloads.has(t.header.sequence.value)&&Bz.warn(`Data track frame ${n} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),r.payloads.set(t.header.sequence.value,t.payload),t.header.marker===Rz.Final?this.finalize(n,r,t.header.sequence.value):null}finalize(e,t,n){let r=t.payloads.size,i=0;for(let e of t.payloads.values())i+=e.length;let a=new Uint8Array(i),o=t.startSequence.clone(),s=0;for(;;){let r=t.payloads.get(o.value);if(!r)break;t.payloads.delete(o.value);let i=a.length-s;if(r.length>i)throw Error(`Depacketizer.finalize: Expected at least ${r.length} more bytes left in the payload buffer, only got ${i} bytes.`);if(a.set(r,s),s+=r.length,o.value!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),Vz.incomplete(e,r,n-t.startSequence.value+1)}};Uz.MAX_BUFFER_PACKETS=128;var Wz;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(Wz||={});var Gz=class e extends FM{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=Wz[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,Wz.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,Wz.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,Wz.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,Wz.Cancelled)}},Kz=YA(qA.DataTracks),qz=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new Uz;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n,this.options=e.pipelineOptions??{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return J(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return Kz.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return J(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return Kz.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return Kz.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},Jz=YA(qA.DataTracks),Yz=1e4,Xz=16,Zz=class extends pj.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let n=this.descriptors.get(e);if(!n){Jz.warn(`Unknown track ${e}, cannot set pipeline options.`);return}n.pipelineOptions=t,n.subscription.type===`active`&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Xz,r=null,i=new TP,a=this.descriptors.get(e),o=()=>{t?.removeEventListener(`abort`,c)},s=()=>{if(o(),!r){Jz.warn(`ReadableStream subscribed to ${e} was not started.`);return}if(!a||this.descriptors.get(a.info.sid)!==a){Jz.warn(`Unknown track ${e}, skipping cancel...`);return}if(a.subscription.type!==`active`){Jz.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},c=()=>{var e;r&&(a?.subscription.type===`active`&&a.subscription.streamControllers.delete(r),r.error(Gz.cancelled()),(e=i.reject)==null||e.call(i,Gz.cancelled()),s())};return[new ReadableStream({start:n=>{r=n,this.subscribeRequest(e,t).then(()=>J(this,void 0,void 0,function*(){var r,s,l;if(!a||this.descriptors.get(a.info.sid)!==a){Jz.error(`Unknown track ${e}`);let t=Gz.disconnected();n.error(t),(r=i.reject)==null||r.call(i,t);return}if(a.subscription.type!==`active`){Jz.error(`Subscription for track ${e} is not active`);let t=Gz.disconnected();n.error(t),(s=i.reject)==null||s.call(i,t);return}if(t?.aborted){c();return}t?.addEventListener(`abort`,c),a.subscription.streamControllers.set(n,o),(l=i.resolve)==null||l.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)})},cancel:()=>{s()}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return J(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>J(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=rz([n,r].filter(e=>e!==void 0)),a=new TP;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,Gz.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new TP,pendingRequestCount:1,cancel:()=>{var e,t;let r=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:n.info.sid,subscribe:!1}),r.type===`pending`&&((t=(e=r.completionFuture).reject)==null||t.call(e,i.aborted?Gz.timeout():Gz.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=iz(Yz);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return J(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){Jz.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}this.closeStreamControllers(t.subscription.streamControllers,e);let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var n=K(r,2);let e=n[0],i=n[1];i();try{e.close()}catch(e){Jz.warn(`Failed to close readable stream for track ${t}: ${e}`)}}}receiveSfuPublicationUpdates(e){return J(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let r of e.entries()){var n=K(r,2);let e=n[0],i=n[1],a=new Set;for(let t of i)a.add(t.sid),!this.descriptors.has(t.sid)&&(this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t)));t.set(e,a)}for(let e of t.entries()){var r=K(e,2);let t=r[0],n=r[1],i=Array.from(this.descriptors.entries()).filter(e=>{let n=K(e,2);return n[0],n[1].publisherIdentity===t}).map(e=>K(e,1)[0]).filter(e=>!n.has(e));for(let e of i)this.handleTrackUnpublished(e)}})}queryPublications(){return J(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return J(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){Jz.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);let r=new Iz(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleSidReassigned(e,t){let n=Array.from(this.descriptors.entries()).find(n=>{let r=K(n,2);r[0];let i=r[1];return i.publisherIdentity===e&&i.info.pubHandle===t.pubHandle});if(!n)return!1;let r=K(n,2),i=r[0],a=r[1],o=a.info,s=o.name,c=o.usesE2ee;if(s!==t.name||c!==t.usesE2ee)return Jz.warn(`Info mismatch for ${i}, treating as new publication`),!1;let l=t.sid;if(Jz.debug(`SID reassigned: ${i} -> ${l}`),!this.descriptors.delete(i))return!1;switch(a.info.sid=l,a.subscription.type){case`none`:break;case`pending`:case`active`:this.emit(`sfuUpdateSubscription`,{sid:l,subscribe:!0})}return a.subscription.type===`active`&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){Jz.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let n of e.entries()){var t=K(n,2);let e=t[0],r=t[1];this.registerSubscriberHandle(e,r)}}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){Jz.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:Jz.warn(`No subscription for ${t}`);return;case`active`:this.subscriptionHandles.delete(i.subscription.subcriptionHandle),i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{Jz.debug(`data track subscription activated`,{sid:t,handle:e});let a=new qz({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:i.pipelineOptions}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return J(this,void 0,void 0,function*(){let t;try{t=K(zz.fromBinary(e),1)[0]}catch(e){Jz.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){Jz.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){Jz.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){Jz.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers.keys()){if(e.desiredSize!==null&&e.desiredSize<=0){Jz.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=Nz.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=K(t,2);let n=e[0];e[1].subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,Gz.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid)}}reset(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,Gz.disconnected())),n.subscription.type===`active`&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},Qz=class e extends FM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=$z[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,$z.MtuTooShort)}},$z;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})($z||={});var eB=class e{constructor(e,t){this.sequence=HF.u16(0),this.frameNumber=HF.u16(0),this.clock=WF.rtpStartingNow(UF.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Rz.Single:e===0?Rz.Start:e===t-1?Rz.Final:Rz.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:Rz.Inter,trackHandle:this.handle,sequence:HF.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new Lz(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Qz.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;c=[n+1,r+o],n=c[0],r=c[1]){var c;let a=this.sequence.getThenIncrement(),l=new Lz(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),u=Math.min(o,t.payload.byteLength-r);yield new zz(l,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,u))}}},tB;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(tB||={});var nB=class e extends FM{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=tB[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,tB.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,tB.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,tB.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,tB.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,tB.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,tB.Unknown)}static disconnected(){return new e(`Room disconnected`,tB.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,tB.Cancelled)}},rB;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(rB||={});var iB=class e extends FM{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=rB[t]}static trackUnpublished(){return new e(`Track is no longer published`,rB.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,rB.Dropped,{cause:t})}},aB;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(aB||={});var oB=class e extends FM{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=aB[t]}static packetizer(t){return new e(`Error packetizing frame`,aB.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,aB.Encryption,{cause:t})}},sB=class e{constructor(e,t){this.trackSymbol=Pz,this.isLocal=!0,this.typeSymbol=Fz,this.handle=null,this.log=JA,this.flushedFuture=new TP,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;(t=(e=this.flushedFuture).resolve)==null||t.call(e),this.manager.off(`packetsFlushedChange`,this.handleManagerPacketsFlushedChange),this.manager.off(`reset`,this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&((n=(t=this.flushedFuture).resolve)==null||n.call(t),this.flushedFuture=new TP)},this.options=e,this.manager=t,this.log=YA(qA.DataTracks),this.manager.on(`packetsFlushedChange`,this.handleManagerPacketsFlushedChange),this.manager.on(`reset`,this.handleManagerReset)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return J(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw iB.trackUnpublished();let t=Nz.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return J(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return J(this,void 0,void 0,function*(){if(!this.handle){JA.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},cB=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new eB(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return sj(this,arguments,function*(){let t=yield oj(this.encryptIfNeeded(e));try{yield oj(yield*cj(lj(this.packetizer.packetize(t))))}catch(e){throw e instanceof Qz?oB.packetizer(e):e}})}encryptIfNeeded(e){return J(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw oB.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new jz(t.keyIndex,t.iv),e})}};cB.TRANSPORT_MTU_BYTES=16e3;var lB=YA(qA.DataTracks),uB={pending(){return{type:`pending`,completionFuture:new TP}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new cB({info:e,e2eeManager:t}),unpublishingFuture:new TP}}},dB=1e4,fB=class e extends pj.EventEmitter{constructor(e){super(),this.handleAllocator=new YF,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return J(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw iB.trackUnpublished();if(o.publishState===`republishing`)throw iB.dropped(`Data track republishing`);try{try{for(var s=!0,c=lj(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let t=a,n=this.inFlightPacketCounter.get(e)??0;this.inFlightPacketCounter.set(e,n+1),n===0&&this.emit(`packetsFlushedChange`,{handle:e,isFlushed:!1}),this.emit(`packetAvailable`,{handle:e,bytes:t.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw iB.dropped(e)}})}handlePacketSendComplete(e){let t=(this.inFlightPacketCounter.get(e)??0)-1;t<0&&(lB.warn(`OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ${this.inFlightPacketCounter} - resetting to 0. Were more packets send than were emitted?`),t=0),this.inFlightPacketCounter.set(e,t),t===0&&this.emit(`packetsFlushedChange`,{handle:e,isFlushed:!0})}publishRequest(e,t){return J(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw nB.limitReached();let r=iz(dB),i=t?rz([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=uB.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){lB.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?nB.timeout():nB.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:sB.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return J(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){lB.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){lB.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){lB.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let i=t.data;lB.debug(`SFU accepted publish request for handle ${e}`,{sid:i.sid});let a=i.usesE2ee?this.e2eeManager:null;this.descriptors.set(i.pubHandle,uB.active(i,a)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else lB.debug(`SFU rejected publish request for handle ${e}`,{error:t.error}),(a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){lB.warn(`Track ${e} already active`);return}if(t.type===`error`){lB.warn(`Republish failed for track ${e}`);return}lB.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){lB.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){lB.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var n=K(r,2);let i=n[0],a=n[1];switch(a.type){case`pending`:this.descriptors.delete(i),(t=(e=a.completionFuture).reject)==null||t.call(e,nB.disconnected());break;case`active`:a.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return J(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,nB.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit(`reset`)})}},pB=class e extends Error{constructor(t,n,r,i){super(n),this.code=t,this.message=xB(n,e.MAX_MESSAGE_BYTES),this.data=r?xB(r,e.MAX_DATA_BYTES):void 0,i?.cause!==void 0&&(this.cause=i?.cause)}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new ck({code:this.code,message:this.message,data:this.data})}static builtIn(t,n,r){return new e(e.ErrorCode[t],e.ErrorMessage[t],n,r)}};pB.MAX_MESSAGE_BYTES=256,pB.MAX_DATA_BYTES=15360,pB.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},pB.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var mB=15360,hB=`lk.rpc_request`,gB=`lk.rpc_response`,_B;(function(e){e.RPC_REQUEST_ID=`lk.rpc_request_id`,e.RPC_REQUEST_METHOD=`lk.rpc_request_method`,e.RPC_REQUEST_RESPONSE_TIMEOUT_MS=`lk.rpc_request_response_timeout_ms`,e.RPC_REQUEST_VERSION=`lk.rpc_request_version`})(_B||={});var vB=1,yB=2;function bB(e){return new TextEncoder().encode(e).length}function xB(e,t){if(bB(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var SB=class extends pj.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return J(this,arguments,void 0,function(e){var t=this;let n=e.destinationIdentity,r=e.method,i=e.payload,a=e.responseTimeout,o=a===void 0?15e3:a;return function*(){let e=t.getRemoteParticipantClientProtocol(n);if(bB(i)>mB&&e<1)throw pB.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`);let a=t.getServerVersion();if(a&&mP(a,`1.8.0`)<0)throw pB.builtIn(`UNSUPPORTED_SERVER`);let s=Math.max(o,8e3),c=crypto.randomUUID(),l=new TP,u=null,d=setTimeout(()=>{var e;t.pendingAcks.delete(c),(e=l.reject)==null||e.call(l,pB.builtIn(`CONNECTION_TIMEOUT`)),t.pendingResponses.delete(c),u!==null&&clearTimeout(u)},7e3);return t.pendingAcks.set(c,{resolve:()=>{clearTimeout(d)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:l,participantIdentity:n}),yield t.publishRpcRequest(n,c,r,i,s,e),u=setTimeout(()=>{var e;t.pendingResponses.delete(c),(e=l.reject)==null||e.call(l,pB.builtIn(`RESPONSE_TIMEOUT`))},o),[c,l.promise.finally(()=>{clearTimeout(u),t.pendingAcks.has(c)&&(t.log.warn(`RPC response received before ack`,c),t.pendingAcks.delete(c),clearTimeout(d))})]}()})}publishRpcRequest(e,t,n,r,i,a){return J(this,void 0,void 0,function*(){if(a>=1){yield this.outgoingDataStreamManager.sendText(r,{topic:hB,destinationIdentities:[e],attributes:{[_B.RPC_REQUEST_ID]:t,[_B.RPC_REQUEST_METHOD]:n,[_B.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:`${i}`,[_B.RPC_REQUEST_VERSION]:`${yB}`}});return}this.emit(`sendDataPacket`,{packet:new JO({destinationIdentities:[e],kind:YO.RELIABLE,value:{case:`rpcRequest`,value:new ak({id:t,method:n,payload:r,responseTimeoutMs:i,version:vB})}})})})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[_B.RPC_REQUEST_ID];if(!r){this.log.warn(`RPC data stream malformed: ${_B.RPC_REQUEST_ID} not set.`);return}let i=this.pendingResponses.get(r);if(i&&i.participantIdentity!==t){this.log.warn(`RPC response stream for ${r} arrived from unexpected sender ${t}, expected ${i.participantIdentity}. Ignoring.`);return}let a;try{a=yield e.readAll()}catch(e){this.log.warn(`Error reading RPC response payload: ${e}`),this.handleIncomingRpcResponseFailure(r,pB.builtIn(`APPLICATION_ERROR`,`Error reading RPC response payload`,{cause:e}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var n,r;let i=this.pendingResponses.get(e);i?((r=(n=i.completionFuture).resolve)==null||r.call(n,t),this.pendingResponses.delete(e)):this.log.error(`Response received for unexpected RPC request`,e)}handleIncomingRpcResponseFailure(e,t){var n,r;let i=this.pendingResponses.get(e);i?((r=(n=i.completionFuture).reject)==null||r.call(n,t),this.pendingResponses.delete(e)):this.log.error(`Response received for unexpected RPC request`,e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error(`Ack received for unexpected RPC request: ${e}`)}handleParticipantDisconnected(e){var t;for(let t of this.pendingAcks){var n=K(t,2);let r=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(r)}for(let n of this.pendingResponses){var r=K(n,2);let a=r[0];var i=r[1];let o=i.participantIdentity,s=i.completionFuture;o===e&&((t=s.reject)==null||t.call(s,pB.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(a))}}},CB=class extends pj.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return J(this,void 0,void 0,function*(){if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,pB.builtIn(`UNSUPPORTED_VERSION`));return}let n=this.rpcHandlers.get(t.method);if(!n){this.publishRpcResponsePacket(e,t.id,null,pB.builtIn(`UNSUPPORTED_METHOD`));return}let r;try{r=yield n({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(n){let r;n instanceof pB?r=n:(this.log.warn(`Uncaught error returned by RPC handler for ${t.method}. Returning APPLICATION_ERROR instead.`,n),r=pB.builtIn(`APPLICATION_ERROR`,`Uncaught error: ${n?.message??n}`,{cause:n})),this.publishRpcResponsePacket(e,t.id,null,r);return}yield this.publishRpcResponse(e,t.id,r??``)})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[_B.RPC_REQUEST_ID],i=n[_B.RPC_REQUEST_METHOD],a=parseInt(n[_B.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[_B.RPC_REQUEST_VERSION],10);if(!r||!i||Number.isNaN(a)||Number.isNaN(o)){this.log.warn(`RPC data stream malformed: ${_B.RPC_REQUEST_ID} / ${_B.RPC_REQUEST_METHOD} / ${_B.RPC_REQUEST_RESPONSE_TIMEOUT_MS} / ${_B.RPC_REQUEST_VERSION} not set.`),this.publishRpcResponsePacket(t,r,null,pB.builtIn(`APPLICATION_ERROR`,`RPC data stream malformed`));return}if(this.publishRpcAck(t,r),o!==yB){this.publishRpcResponsePacket(t,r,null,pB.builtIn(`UNSUPPORTED_VERSION`));return}let s;try{s=yield e.readAll()}catch(e){this.log.warn(`Error reading RPC request payload: ${e}`),this.publishRpcResponsePacket(t,r,null,pB.builtIn(`APPLICATION_ERROR`,`Error reading RPC request payload`,{cause:e}));return}let c=this.rpcHandlers.get(i);if(!c){this.publishRpcResponsePacket(t,r,null,pB.builtIn(`UNSUPPORTED_METHOD`));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:s,responseTimeout:a})}catch(e){let n;e instanceof pB?n=e:(this.log.warn(`Uncaught error returned by RPC handler for ${i}. Returning APPLICATION_ERROR instead.`,e),n=pB.builtIn(`APPLICATION_ERROR`)),this.publishRpcResponsePacket(t,r,null,n);return}yield this.publishRpcResponse(t,r,l??``)})}publishRpcAck(e,t){this.emit(`sendDataPacket`,{packet:new JO({destinationIdentities:[e],kind:YO.RELIABLE,value:{case:`rpcAck`,value:new ok({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit(`sendDataPacket`,{packet:new JO({destinationIdentities:[e],kind:YO.RELIABLE,value:{case:`rpcResponse`,value:new sk({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}})})}publishRpcResponse(e,t,n){return J(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){yield this.outgoingDataStreamManager.sendText(n,{topic:gB,destinationIdentities:[e],attributes:{[_B.RPC_REQUEST_ID]:t}});return}if(bB(n)>mB){this.log.warn(`RPC Response payload too large for request ${t}. To send larger responses, consider updating the sending client.`),this.publishRpcResponsePacket(e,t,null,pB.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`));return}this.publishRpcResponsePacket(e,t,n,null)})}},wB=class extends TF{constructor(e,t,n,r,i,a){super(e,t,$.Kind.Audio,n,a),this.monitorReceiver=()=>J(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=wF(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;cP()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(cP())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return J(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(XN(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&XN(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(Q.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(Q.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return J(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},TB=class extends pj.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=PO.NONE,this.log=JA,this.handleMuted=()=>{this.emit(Q.Muted)},this.handleUnmuted=()=>{this.emit(Q.Unmuted)},this.log=YA(r?.loggerName??qA.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=$.Source.Unknown}setTrack(e){this.track&&(this.track.off(Q.Muted,this.handleMuted),this.track.off(Q.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Q.Muted,this.handleMuted),e.on(Q.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),wN(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==PO.NONE}get audioTrack(){if(IP(this.track))return this.track}get videoTrack(){if(LP(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=$.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===$.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(TB||={});var EB=class extends TB{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Q.Ended)},this.handleCpuConstrained=()=>{this.track&&LP(this.track)&&this.emit(Q.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(Q.Ended,this.handleTrackEnded),this.track.off(Q.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Q.Ended,this.handleTrackEnded),e.on(Q.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return J(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return J(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return J(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return J(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(IP(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(TO.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(TO.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(TO.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(TO.TF_STEREO),this.options?.dtx||t.add(TO.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(TO.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}return[]}};function DB(e,t){return J(this,void 0,void 0,function*(){e??={};let n=!1,r=DN(e),i=r.audioProcessor,a=r.videoProcessor,o=r.optionsWithoutProcessor,s=o.audio,c=o.video;if(i&&typeof o.audio==`object`&&(o.audio.processor=i),a&&typeof o.video==`object`&&(o.video.processor=a),e.audio&&typeof o.audio==`object`&&typeof o.audio.deviceId==`string`){let e=o.audio.deviceId;o.audio.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&typeof o.video==`object`&&typeof o.video.deviceId==`string`){let e=o.video.deviceId;o.video.deviceId={exact:e},n=!0,c=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}o.audio===!0?o.audio={deviceId:`default`}:typeof o.audio==`object`&&o.audio!==null&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||`default`})),o.video===!0?o.video={deviceId:`default`}:typeof o.video==`object`&&!o.video.deviceId&&(o.video.deviceId=`default`);let l=gN(mN(o,mL,hL)),u=navigator.mediaDevices.getUserMedia(l);o.audio&&(zF.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>zF.userMediaPromiseMap.delete(`audioinput`))),o.video&&(zF.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>zF.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>J(this,void 0,void 0,function*(){let r=n.kind===`audio`,o,s=r?l.audio:l.video;typeof s!=`boolean`&&(o=s);let c=n.getSettings().deviceId;o?.deviceId&&DP(o.deviceId)!==c?o.deviceId=c:o||={deviceId:c};let u=UL(n,o,t);return u.kind===$.Kind.Video?u.source=$.Source.Camera:u.kind===$.Kind.Audio&&(u.source=$.Source.Microphone),u.mediaStream=e,IP(u)&&i?yield u.setProcessor(i):LP(u)&&a&&(yield u.setProcessor(a)),u})))}catch(r){if(!n)throw r;return DB(Object.assign(Object.assign({},e),{audio:s,video:c}),t)}})}var OB;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(OB||={});function kB(e){switch(e){case bO.EXCELLENT:return OB.Excellent;case bO.GOOD:return OB.Good;case bO.POOR:return OB.Poor;case bO.LOST:return OB.Lost;default:return OB.Unknown}}var AB=class extends pj.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===MO.AGENT}get isActive(){return this.participantInfo?.state===jO.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:MO.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=OB.Unknown,this.log=JA,this.loggerOptions=a,this.log=YA(a?.loggerName??qA.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let t of this.trackPublications){let n=K(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(let t of this.trackPublications){let n=K(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new TP,this.once(X.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication($.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication($.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication($.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===jO.ACTIVE&&this.participantInfo?.state!==jO.ACTIVE&&this.emit(X.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(X.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(X.ParticipantNameChanged,e)}_setAttributes(e){let t=EN(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(X.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(X.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(X.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=kB(e),t!==this._connectionQuality&&this.emit(X.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>IP(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug(`adding track publication`,{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(Q.Muted,()=>{this.emit(X.TrackMuted,e)}),e.on(Q.Unmuted,()=>{this.emit(X.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case $.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case $.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}};function jB(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new yA({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var MB=class extends AB{constructor(e,t,n,r,i,a,o,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=PO.NONE,this.e2eeStateMutex=new $T,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||=new TP},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new TP,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let t=e.requestId,n=e.reason,r=e.message,i=this.pendingSignalRequests.get(t);switch(i&&(n!==NA.OK&&i.reject(new GM(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case NA.NOT_ALLOWED:t=nB.notAllowed(e.message);break;case NA.DUPLICATE_NAME:t=nB.duplicateName(e.message);break;case NA.INVALID_NAME:t=nB.invalidName(e.message);break;case NA.LIMIT_EXCEEDED:t=nB.limitReached(e.message);break;default:t=nB.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>jB(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,wN(e));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,wN(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,wN(e)),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,wN(t)),this.emit(X.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>J(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,{trackSid:e.trackSid});return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=lj(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;cN(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,wN(a)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,{trackSid:e.trackSid});return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>J(this,void 0,void 0,function*(){if(e.source===$.Source.ScreenShare||e.source===$.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,wN(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(zP(e)||RP(e))try{if(sP())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===$.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,wN(e)),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,wN(e)),zP(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,wN(e)),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=i,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==PO.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Z.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(Z.Connected,this.handleReconnected).on(Z.SignalConnected,this.handleSignalConnected).on(Z.SignalRestarted,this.handleReconnected).on(Z.SignalResumed,this.handleReconnected).on(Z.Restarting,this.handleReconnecting).on(Z.Resuming,this.handleReconnecting).on(Z.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Z.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Z.Closing,this.handleClosing).on(Z.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return J(this,arguments,void 0,function(e){var t=this;let n=e.metadata,r=e.name,i=e.attributes;return function*(){return new EM((e,a)=>J(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let t=K(e,2),n=t[0],r=t[1];return this.attributes[n]===r||r===``&&!this.attributes[n]}))){this.pendingSignalRequests.delete(o),e();return}yield zN(50)}a(new GM(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled($.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled($.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled($.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return J(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?PO.GCM:PO.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(t=>t.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return J(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t){if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,{source:e}),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case $.Source.Camera:t=yield this.createTracks({video:n??!0});break;case $.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case $.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new zM(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(X.MediaDevicesError,n,bN(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===$.Source.Microphone&&IP(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,wN(n)),e.push(this.publishTrack(n,r));i=K(yield Promise.all(e),1)[0]}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,{source:e})),i&&i.track){if(e===$.Source.ScreenShare){let e=[this.unpublishTrack(i.track)],t=this.getTrackPublication($.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),i=K(yield Promise.all(e),1)[0]}else yield i.mute()}return i})}enableCameraAndMicrophone(){return J(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has($.Source.Camera)||this.pendingPublishing.has($.Source.Microphone))){this.pendingPublishing.add($.Source.Camera),this.pendingPublishing.add($.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete($.Source.Camera),this.pendingPublishing.delete($.Source.Microphone)}}})}createTracks(e){return J(this,void 0,void 0,function*(){e??={};let t=mN(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield DB(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(IP(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=$.Source.Microphone,this.emit(X.AudioStreamAcquired)),LP(e)&&(this.cameraError=void 0,e.source=$.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return J(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new RM(`getDisplayMedia not supported`);e.resolution===void 0&&!rP()&&(e.resolution=pN.h1080fps30.resolution);let t=xN(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new zM(`no video track found`);let i=new cR(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=$.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(X.AudioStreamAcquired);let e=new HL(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=$.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return J(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,n)=>{let r=()=>{clearTimeout(o),this.engine.off(Z.Restarted,i),this.engine.off(Z.Closing,a)},i=()=>{r(),t()},a=()=>{r(),n(Error(`engine closed before restart completed`))},o=setTimeout(()=>{r(),n(Error(`timed out waiting for engine restart`))},e);this.engine.once(Z.Restarted,i),this.engine.once(Z.Closing,a)})}publishOrRepublishTrack(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0&&arguments[2],i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return function*(){zP(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),FP(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let a;if(e instanceof MediaStreamTrack)a=e.getConstraints();else{a=e.constraints;let t;switch(e.source){case $.Source.Microphone:t=`audioinput`;break;case $.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(a=Object.assign(Object.assign({},a),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new HL(e,a,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new cR(e,a,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new zM(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let o;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return n.log.warn(`track has already been published, skipping`,wN(o)),o;let s=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),c=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,l=s.forceStereo??c;l&&(s.dtx===void 0&&n.log.debug(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,wN(e)),s.red===void 0&&n.log.debug(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),s.dtx??=!1,s.red??=!1),!oP()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`),s.simulcast=!1),s.source&&(e.source=s.source);let u=new Promise((t,r)=>J(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==TI.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,{track:wN(e)});let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new WM(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,s,l))}else try{t(yield this.publish(e,s,l))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,u);try{return yield u}catch(a){if(!i&&a instanceof HM)return n.log.warn(`negotiation due to track publish failed, retrying after reconnect`,{error:a}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,r,!0);throw a}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new TP,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,wN(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(e=>ON(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,wN(e)),!1)}publish(e,t,n){return J(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new WM(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>FP(e)&&t.source===e.source)&&e.source!==$.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,wN(e)),t.stopMicTrackOnMute&&IP(e)&&(e.stopOnMute=!0),e.source===$.Source.ScreenShare&&QN()&&(t.simulcast=!1),t.videoCodec===`av1`&&!HN()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!UN()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=fL),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===SN(e.mime))||(t.videoCodec=SN(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(Q.Muted,this.onTrackMuted),e.on(Q.Unmuted,this.onTrackUnmuted),e.on(Q.Ended,this.handleTrackEnded),e.on(Q.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Q.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Q.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(TO.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(TO.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(TO.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(TO.TF_STEREO),a&&i.push(TO.TF_NO_DTX),zP(e)&&e.hasPreConnectBuffer&&i.push(TO.TF_PRECONNECT_BUFFER);let s=this.normalizeRequestedFrameMetadataOptions(e,t),c=new Nk({cid:e.mediaStreamTrack.id,name:t.name,type:$.kindToProto(e.kind),muted:e.isMuted,source:$.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i,packetTrailerFeatures:s}),l;if(e.kind===$.Kind.Video){let n;try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??dN.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign({},wN(e)),{dims:n}))}if(c.width=n.width,c.height=n.height,RP(e)){KN(r,t)&&(qN()||!YN(this.engine?.serverVersion))&&(t.simulcast=!1,this.log.info(`SVC simulcast is not supported, disabling simulcast.`,wN(e)));let n=KN(r,t);WN(r)&&!n&&(e.source===$.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.debug(`forcing contentHint to motion for screenshare with SVC codecs`,wN(e)))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`);let i=new Mk({codec:r,cid:e.mediaStreamTrack.id});n&&(i.videoLayerMode=qO.ONE_SPATIAL_LAYER_PER_STREAM),c.simulcastCodecs=[i],t.backupCodec===!0&&(t.backupCodec={codec:fL}),t.backupCodec&&r!==t.backupCodec.codec&&c.encryption===PO.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),c.simulcastCodecs.push(new Mk({codec:t.backupCodec.codec,cid:``})))}l=ZL(e.source===$.Source.ScreenShare,c.width,c.height,t),c.layers=dR(c.width,c.height,l,WN(t.videoCodec)&&!KN(t.videoCodec,t))}else e.kind===$.Kind.Audio&&(l=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new VM(`cannot publish track when not connected`);let u=()=>J(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new VM(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,l),RP(e)&&(e.publishOptions=t),this.emit(X.LocalSenderCreated,e.sender,e),RP(e)&&(t.degradationPreference??=oR(e),e.setDegradationPreference(t.degradationPreference)),l){if(QN()&&e.kind===$.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:l[0]?.maxBitrate?l[0].maxBitrate/1e3:0})}else if(e.codec&&EP(e.codec)){let n=QL(e.codec,t,l);n>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:c.cid,codec:e.codec,maxbr:n/1e3,isScreenShare:e.source===$.Source.ScreenShare})}}yield this.engine.negotiate()}),d,f=new Promise((t,n)=>J(this,void 0,void 0,function*(){try{d=yield this.engine.addTrack(c),t(d)}catch(t){if(e.sender&&this.engine.pcManager?.publisher){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign({},wN(e)),{error:t}))})}n(t)}}));if(this.enabledPublishVideoCodecs.length>0&&s.length===0)d=(yield Promise.all([f,u()]))[0];else{d=yield f;let n;if(d.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===$.Kind.Video){let i=SN(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign({},wN(e)),{codec:i})),t.videoCodec=i,l=ZL(e.source===$.Source.ScreenShare,c.width,c.height,t))}yield u()}let p=new EB(e.kind,d,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(p.on(Q.CpuConstrained,e=>this.onTrackCpuConstrained(e,p)),p.options=t,e.sid=d.sid,RP(e)&&(e.publishOptions=t,c.width&&c.height&&(e.lastEncodedDimensions={width:c.width,height:c.height})),this.log.debug(`publishing ${e.kind} with encodings`,{encodings:l,trackInfo:d}),RP(e)?e.startMonitor(this.engine.client):zP(e)&&e.startMonitor(),this.addTrackPublication(p),this.emit(X.LocalTrackPublished,p),zP(e)&&d.audioFeatures.includes(TO.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(X.LocalTrackSubscribed,t=>{if(t.trackSid===d.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`);return}this.log.debug(`finished recording preconnect buffer`,wN(e)),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>J(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,wN(e));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,wN(e));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:p.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=lj(t),f;f=yield d.next(),a=f.done,!a;u=!0){l=f.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,wN(e))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign({},wN(e)),{error:t}))})}return p})}canPublishFrameMetadata(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||vF(this.roomOptions.frameMetadata??this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){let n=t.frameMetadata??t.packetTrailer;if(e.kind!==$.Kind.Video||!yF(n))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn(`frame metadata transform not supported; not advertising features`,Object.assign(Object.assign({},this.logContext),wN(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let r=bF(n),i=xF(r);return t.frameMetadata=i,t.packetTrailer=i,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return J(this,void 0,void 0,function*(){if(this.encryptionType!==PO.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new zM(`track is not published`);if(!RP(e))throw new zM(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=$L(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,wN(e));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=this.normalizeRequestedFrameMetadataOptions(e,i),c=new Nk({cid:o.mediaStreamTrack.id,type:$.kindToProto(e.kind),muted:e.isMuted,source:$.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:s,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=dR(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new VM(`cannot publish track when not connected`);let l=(yield Promise.all([this.engine.addTrack(c),J(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,{encodings:a,trackInfo:l})})}unpublishTrack(e,t){return J(this,void 0,void 0,function*(){if(FP(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.debug(`awaiting publish promise before attempting to unpublish`,wN(e)),yield t)}let n=this.getPublicationForTrack(e),r=n?wN(n):void 0;if(this.log.info(`unpublishing track`,r),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,r);return}e=n.track,e.off(Q.Muted,this.onTrackMuted),e.off(Q.Unmuted,this.onTrackUnmuted),e.off(Q.Ended,this.handleTrackEnded),e.off(Q.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Q.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Q.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<vL.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);try{i=this.engine.removeTrack(a)}catch(e){this.log.warn(e),i=!0}if(RP(e)){for(let t of e.simulcastCodecs){let e=K(t,2)[1];if(e.sender){try{i=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),i=!0}e.sender=void 0}}e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign({},r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case $.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case $.Kind.Video:this.videoTrackPublications.delete(n.trackSid)}return this.emit(X.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return J(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new EM((r,i)=>J(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>J(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==$.Source.ScreenShare&&t.source!==$.Source.ScreenShareAudio&&(zP(t)||RP(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?wL.RELIABLE:wL.LOSSY,i=n.reliable?YO.RELIABLE:YO.LOSSY,a=n.destinationIdentities,o=n.topic,s=new JO({kind:i,value:{case:`user`,value:new ek({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return J(this,void 0,void 0,function*(){let n=new JO({kind:YO.RELIABLE,value:{case:`sipDtmf`,value:new tk({code:e,digit:t})}});yield this.engine.sendDataPacket(n,wL.RELIABLE)})}sendChatMessage(e,t){return J(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new JO({value:{case:`chatMessage`,value:new ik(Object.assign(Object.assign({},n),{timestamp:AE.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,wL.RELIABLE),this.emit(X.ChatMessage,n),n})}editChatMessage(e,t){return J(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new JO({value:{case:`chatMessage`,value:new ik(Object.assign(Object.assign({},n),{timestamp:AE.parse(n.timestamp),editTimestamp:AE.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,wL.RELIABLE),this.emit(X.ChatMessage,n),n})}sendText(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(e=>{let t=K(e,2);return t[0],t[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign({},wN(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new TP,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(zP(r)||RP(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return J(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>K(t,1)[0].source===e);if(t)return t[1];yield zN(20)}})}publishDataTrack(e){return J(this,void 0,void 0,function*(){let t=new sB(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},NB=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},PB=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending?.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`DeferrableMap`}getDeferred(e,t){return J(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new NB(`The operation was aborted.`,t.reason);let r=new TP(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new NB(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},FB=class extends TB{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Q.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Jk({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new lk({participantSid:``,trackSids:[this.trackSid]})]});this.emit(Q.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?TB.SubscriptionStatus.Unsubscribed:super.isSubscribed?TB.SubscriptionStatus.Subscribed:TB.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?TB.PermissionStatus.Allowed:TB.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed!==!1&&super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?!this.isAdaptiveStream||this.visible:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width!==e.width||this.requestedVideoDimensions?.height!==e.height)&&(HP(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&HP(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??NN.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(Q.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(Q.VisibilityChanged,this.handleVisibilityChange),r.off(Q.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(Q.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Q.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Q.VisibilityChanged,this.handleVisibilityChange),e.on(Q.Ended,this.handleEnded),this.emit(Q.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Q.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Q.Muted:Q.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(Q.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Q.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return HP(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new tA({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===$.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0){if(t)kN(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=AN(this.trackInfo,this.requestedMaxQuality);e&&kN(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream}t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:NN.HIGH})),e.quality=NN.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(Q.UpdateSettings,e)}},IB=class e extends AB{static fromParticipantInfo(t,n,r,i){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind,n.dataTracks.map(e=>new Iz(XF.from(e),i,{publisherIdentity:n.identity})),n.clientProtocol,n.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:MO.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:0,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new PB(c.map(e=>[e.info.name,e])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(Q.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),wN(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Q.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Q.SubscriptionPermissionChanged,t=>{this.emit(X.TrackSubscriptionPermissionChanged,e,t)}),e.on(Q.SubscriptionStatusChanged,t=>{this.emit(X.TrackSubscriptionStatusChanged,e,t)}),e.on(Q.Subscribed,t=>{this.emit(X.TrackSubscribed,t,e)}),e.on(Q.Unsubscribed,t=>{this.emit(X.TrackUnsubscribed,t,e)}),e.on(Q.SubscriptionFailed,t=>{this.emit(X.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:$.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(X.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),wN(o))),this.emit(X.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new DF(e,t,r,i):new wB(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&BP(c)&&IP(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=$.kindFromProto(e.type);if(!t)return;r=new FB(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==$.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:wN(i),newTrack:wN(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),wN(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(X.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case $.Kind.Audio:this.audioTrackPublications.delete(e);break;case $.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(X.TrackUnpublished,n)}setAudioOutput(e){return J(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{IP(n.track)&&BP(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let n of this.dataTracks.entries()){var t=K(n,2);let r=t[0];e===t[1].info.sid&&this.dataTracks.delete(r)}}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},LB;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(LB||={});var RB=4e3,zB=3e4,BB=class e extends pj.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=LB.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new $T,this.isVideoPlaybackBlocked=!1,this.log=JA,this.statsLog=JA,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(e,t,n)=>J(this,void 0,void 0,function*(){if(!ZN())throw cP()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===LB.Connected)return this.log.info(`already connected to room ${this.name}`),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(LB.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==eF(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),lP(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new TR(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,{error:e})}));let i=(a,o,s)=>J(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield LF.getInstance().getBackOffPromise(e),c.signal.aborted)throw LM.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof LM&&t.reason!==IM.Cancelled&&t.reason!==IM.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof LM&&(e.status===401||e.reason===IM.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[IM.InternalError,IM.ServerUnreachable,IM.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),LF.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,MP(t)),o(t))}else{let e=SO.UNKNOWN_REASON;t instanceof LM&&(e=MP(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new TP((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>J(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`||i.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(i),maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.joinResponse,c=o.serverInfo;if(this.serverInfo=c,!c.version)throw new BM(`unknown server version`);return c.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`),i.dynacast=!1),s}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>J(this,void 0,void 0,function*(){this.state===LB.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},_L),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?LM.cancelled(`Signal connection aborted`):LM.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof LM&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),LM.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}sP()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),sP()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(LB.Connected),this.emit(Y.Connected),LF.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return J(n,[...arguments],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===LB.Disconnected){e.log.debug(`already disconnected`);return}if(e.log.info(`disconnect from room`),e.state===LB.Connecting||e.state===LB.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,LM.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,SO.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>J(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`),yield this.disconnect()}),this.startAudio=()=>J(this,void 0,void 0,function*(){let e=[],t=kM();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=wP();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`),this.startAudio()))}),document.body.append(n),this.once(Y.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(this.options.webAudioMix||(e.muted=!1),e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>J(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(LB.Reconnecting)&&this.emit(Y.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>J(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,{region:e.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,{region:e.serverRegion})}catch{return}this.setAndEmitConnectionState(LB.Connected),this.emit(Y.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===jO.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e,t.disconnectReason===SO.UNKNOWN_REASON?void 0:t.disconnectReason):this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>XF.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Y.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(Y.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=$.streamStateFromProto(e.state),i=n.track.streamState;n.track.setStreamState(r),r!==i&&(t.emit(X.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(Y.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{this.cancelPendingTrackAdded(e.trackSid);let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if(e.value.case===`rpcResponse`){let t=e.value.value;switch(t.value.case){case`payload`:this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case`error`:this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,pB.fromProto(t.value.value));break;default:this.log.warn(`Unknown rpcResponse.value.case: ${t.value.case}`,this.logContext)}}else e.value.case===`rpcAck`&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(e,t,n,r)=>{this.emit(Y.DataReceived,t.payload,e,n,t.topic,r),e?.emit(X.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(Y.SipDTMFReceived,t,e),e?.emit(X.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=AP(t,this.transcriptionReceivedTimes);r?.emit(Q.TranscriptionReceived,i),n?.emit(X.TranscriptionReceived,i,r),this.emit(Y.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=jP(t);this.emit(Y.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(Y.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Y.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Y.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Y.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Y.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>J(this,void 0,void 0,function*(){kM()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(Y.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Y.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(Y.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.getRemoteParticipantClientProtocol=e=>this.remoteParticipants.get(e)?.clientProtocol??0,this.getRemoteParticipantCapabilities=e=>this.remoteParticipants.get(e)?.capabilities??[],this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.logWebRTCStats=()=>J(this,void 0,void 0,function*(){let e=this.engine?.pcManager;if(e)try{let t=K(yield Promise.all([e.publisher.getStats(),e.subscriber?.getStats()]),2),n=t[0],r=t[1],i=n&&nN(n),a=r&&nN(r);this.statsLog.info(`webrtc stats`,{publisher:i?.connection,subscriber:a?.connection,inbound:[...i?.inbound??[],...a?.inbound??[]],outbound:i?.outbound})}catch(e){this.statsLog.debug(`could not collect webrtc stats`,{error:e})}}),this.onLocalParticipantMetadataChanged=e=>{this.emit(Y.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Y.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Y.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Y.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Y.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>J(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(Q.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(Q.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(Y.LocalTrackPublished,e,this.localParticipant),zP(e.track)&&(yield e.track.checkForSilence())&&this.emit(Y.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=bN(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(Y.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(Q.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(Q.Restarted,this.onLocalTrackRestarted),this.emit(Y.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>J(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=bN(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`),this.localParticipant.activeDeviceMap.set(n,t),this.emit(Y.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Y.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Y.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Y.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Y.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gL),t),this.log=YA(this.options.loggerName??qA.Room,()=>this.logContext),this.statsLog=YA(qA.Stats,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},mL),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},hL),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},pL),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new IR(this.options.dataStream?.maxPayloadByteLength),this.outgoingDataStreamManager=new QR(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new Zz({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(Y.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(Y.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new fB({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(Y.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(Y.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let t=e.handle,n=e.bytes;this.engine.sendDataTrackFrame(n).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(t))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new SB(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>this.engine?.serverVersion),this.rpcClientManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,wL.RELIABLE)}),this.rpcServerManager=new CB(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,wL.RELIABLE)}),this.disconnectLock=new $T,this.localParticipant=new MB(``,``,this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,DP(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,DP(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,DP(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),sP()){let t=new AbortController,n;if(e.cleanupRegistry){let r=new WeakRef(this);n=()=>{let e=r.deref();e&&e.handleDeviceChange()},e.cleanupRegistry.register(this,()=>{t.abort()})}else n=this.handleDeviceChange;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,n,{signal:t.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return J(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error(`e2ee not configured, please set e2ee settings within the room options`)}finally{t()}})}setupE2EE(){var e,t;let n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&(`e2eeManager`in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new jF(r,n),this.e2eeManager.on(lF.ParticipantEncryptionStatusChanged,(e,t)=>{UP(t)&&(this.isE2EEEnabled=e),this.emit(Y.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(lF.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(Y.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this),(t=this.e2eeManager)==null||t.setupEngine(this.engine))}setupFrameMetadata(){let e=this.options.frameMetadata??this.options.packetTrailer;this.frameMetadataManager=new PF(e),this.frameMetadataManager.setup(this)}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant?.identity,participantID:this.localParticipant?.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===LB.Disconnected?EM.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?EM.resolve(this.roomInfo.sid):new EM((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(Z.RoomUpdate,n),e(t.sid))};this.engine.on(Z.RoomUpdate,n),this.once(Y.Disconnected,()=>{this.engine.off(Z.RoomUpdate,n),t(new VM(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){(!this.engine||!this.engine.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new bR(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Z.ParticipantUpdate,this.handleParticipantUpdates).on(Z.RoomUpdate,this.handleRoomUpdate).on(Z.SpeakersChanged,this.handleSpeakersChanged).on(Z.StreamStateChanged,this.handleStreamStateUpdate).on(Z.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Z.SubscriptionError,this.handleSubscriptionError).on(Z.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Z.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(Z.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Z.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Z.DataPacketReceived,this.handleDataPacket).on(Z.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug(`Resuming signal connection`),this.setAndEmitConnectionState(LB.SignalReconnecting)&&this.emit(Y.SignalReconnecting)}).on(Z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug(`Resumed signal connection`),this.updateSubscriptions(),this.setAndEmitConnectionState(LB.Connected)&&this.emit(Y.Reconnected),this.emitBufferedEvents()}).on(Z.SignalResumed,()=>{(this.state===LB.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(Z.Restarting,this.handleRestarting).on(Z.Restarted,this.handleRestarted).on(Z.SignalRestarted,this.handleSignalRestarted).on(Z.Offline,()=>{this.setAndEmitConnectionState(LB.Reconnecting)&&this.emit(Y.Reconnecting)}).on(Z.DCBufferStatusChanged,(e,t)=>{this.emit(Y.DCBufferStatusChanged,e,t)}).on(Z.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(Z.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Y.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(Z.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==PO.NONE}})}).on(Z.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(Z.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let t=K(e,2),n=t[0],r=t[1];return[parseInt(n,10),r.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(Z.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(Z.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>XF.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(Z.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)==null||t.updateToken(e)}).on(Z.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:CR})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>J(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>this.regionUrlProvider?.resetAttempts()}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return zF.getInstance().getDevices(e,t)}prepareConnection(e,t){return J(this,void 0,void 0,function*(){if(this.state===LB.Disconnected){this.log.debug(`prepareConnection to ${e}`);try{if(lP(new URL(e))&&t){this.regionUrlProvider=new TR(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===LB.Disconnected&&(this.regionUrl=n,yield fetch(kP(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`))}else yield fetch(kP(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,{error:e})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return J(this,void 0,void 0,function*(){let n=()=>J(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`fail-on-v1-path`:this.engine.failNextV1Path();break;case`speaker`:r=new EA({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new EA({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new EA({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new EA({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>J(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new EA({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>J(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new EA({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new EA({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>J(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new iA({reason:SO.CLIENT_INITIATED,action:aA.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new EA({scenario:{case:`subscriberBandwidth`,value:PP(t)}});break;case`leave-full-reconnect`:r=new EA({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===$.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===$.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!XN()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield zF.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(Y.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(X.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(X.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(X.AttributesChanged,this.onLocalAttributesChanged).on(X.TrackMuted,this.onLocalTrackMuted).on(X.TrackUnmuted,this.onLocalTrackUnmuted).on(X.LocalTrackPublished,this.onLocalTrackPublished).on(X.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(X.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(X.MediaDevicesError,this.onMediaDevicesError).on(X.AudioStreamAcquired,this.startAudio).on(X.ChatMessage,this.onLocalChatMessageSent).on(X.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if([LB.Connecting,LB.Reconnecting].includes(this.state)){let r=XP(e,t);this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)});let i=()=>{a(),this.onTrackAdded(e,t,n)},a=()=>{if(this.off(Y.Reconnected,i),this.off(Y.Connected,i),this.off(Y.Disconnected,a),r){let e=this.pendingTrackAddedCallbacks.get(r);e?.delete(a),e?.size===0&&this.pendingTrackAddedCallbacks.delete(r)}};if(this.once(Y.Reconnected,i),this.once(Y.Connected,i),this.once(Y.Disconnected,a),r){let e=this.pendingTrackAddedCallbacks.get(r)??new Set;e.add(a),this.pendingTrackAddedCallbacks.set(r,e)}return}if(this.state===LB.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`);return}if(e.readyState===`ended`){this.log.debug(`skipping incoming track as it already ended`);return}let r=RN(t.id),i=r[0],a=r[1],o=XP(e,t)??e.id;if(i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,{remoteParticipantID:i,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(Y.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))==null||t.forEach(e=>e())}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(t=>t.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug(`deferring LocalTrackSubscribed, publication not yet available`,{subscribedSid:e});let r,i=t=>{t.trackSid===e&&(a(),this.emitLocalTrackSubscribed(t))},a=()=>{clearTimeout(r),this.localParticipant.off(X.LocalTrackPublished,i),this.off(Y.Disconnected,a)};this.localParticipant.on(X.LocalTrackPublished,i),this.once(Y.Disconnected,a),r=setTimeout(()=>{a();let n=t();n?this.emitLocalTrackSubscribed(n):this.log.warn(`could not find local track publication for LocalTrackSubscribed event after timeout`,{subscribedSid:e})},1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(X.LocalTrackSubscribed,e),this.emitWhenConnected(Y.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==LB.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(X.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(X.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(X.AttributesChanged,this.onLocalAttributesChanged).off(X.TrackMuted,this.onLocalTrackMuted).off(X.TrackUnmuted,this.onLocalTrackUnmuted).off(X.LocalTrackPublished,this.onLocalTrackPublished).off(X.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(X.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(X.MediaDevicesError,this.onMediaDevicesError).off(X.AudioStreamAcquired,this.startAudio).off(X.ChatMessage,this.onLocalChatMessageSent).off(X.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),sP()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(LB.Disconnected),this.emit(Y.Disconnected,t)}}}handleParticipantDisconnected(e,t,n){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Y.ParticipantDisconnected,t,n),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return J(this,void 0,void 0,function*(){let e=zF.getInstance().previousDevices,t=yield zF.getInstance().getDevices(void 0,!1),n=kM();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)==="default"&&this.emit(Y.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=yN(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!nP()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!nP())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return J(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=vN()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),zN(200)])}catch(e){this.log.warn(`Could not resume audio context`,{error:e})}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(Y.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?IB.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new IB(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Y.ParticipantConnected,n),n.on(X.TrackPublished,e=>{this.emitWhenConnected(Y.TrackPublished,e,n)}).on(X.TrackSubscribed,(e,t)=>{e.kind===$.Kind.Audio?(e.on(Q.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Q.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===$.Kind.Video&&(e.on(Q.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Q.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(Y.TrackSubscribed,e,t,n)}).on(X.TrackUnpublished,e=>{this.cancelPendingTrackAdded(e.trackSid),this.emit(Y.TrackUnpublished,e,n)}).on(X.TrackUnsubscribed,(e,t)=>{this.emit(Y.TrackUnsubscribed,e,t,n)}).on(X.TrackMuted,e=>{this.emitWhenConnected(Y.TrackMuted,e,n)}).on(X.TrackUnmuted,e=>{this.emitWhenConnected(Y.TrackUnmuted,e,n)}).on(X.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Y.ParticipantMetadataChanged,e,n)}).on(X.ParticipantNameChanged,e=>{this.emitWhenConnected(Y.ParticipantNameChanged,e,n)}).on(X.AttributesChanged,e=>{this.emitWhenConnected(Y.ParticipantAttributesChanged,e,n)}).on(X.ConnectionQualityChanged,e=>{this.emitWhenConnected(Y.ConnectionQualityChanged,e,n)}).on(X.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Y.ParticipantPermissionsChanged,e,n)}).on(X.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Y.TrackSubscriptionStatusChanged,e,t,n)}).on(X.TrackSubscriptionFailed,(e,t)=>{this.emit(Y.TrackSubscriptionFailed,e,n,t)}).on(X.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Y.TrackSubscriptionPermissionChanged,e,t,n)}).on(X.Active,()=>{this.emitWhenConnected(Y.ParticipantActive,n),n.kind===MO.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&VP(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){let t=[];return(vF(e.frameMetadata??e.packetTrailer)||this.e2eeManager)&&t.push(mk.CAP_PACKET_TRAILER),JP()&&t.push(mk.CAP_COMPRESSION_DEFLATE_RAW),t}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(hB,(e,t)=>J(this,[e,t],void 0,function(e,t){var n=this;let r=t.identity;return function*(){let t=e.info.attributes??{};yield n.rpcServerManager.handleIncomingDataStream(e,r,t)}()})),this.incomingDataStreamManager.registerTextStreamHandler(gB,(e,t)=>J(this,[e,t],void 0,function(e,t){var n=this;let r=t.identity;return function*(){let t=e.info.attributes??{};yield n.rpcClientManager.handleIncomingDataStream(e,r,t)}()}))}setStatsLogging(e){e?this.statsLogInterval||=XM.setInterval(()=>{this.logWebRTCStats()},zB):this.statsLogInterval&&=(XM.clearInterval(this.statsLogInterval),void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=XM.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn(`detected connection state mismatch, attempting full reconnect`),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,SO.STATE_MISMATCH)))):e=0},RB)}clearConnectionReconcile(){this.connectionReconcileInterval&&XM.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info(`connection state changed: ${this.state} -> ${e}`),this.state=e,this.incomingDataStreamManager.setConnected(e===LB.Connected),this.setStatsLogging(e===LB.Connected),this.emit(Y.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=K(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===LB.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===LB.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return J(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new DO({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:AE.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new AO({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected),this.emit(Y.Connected),this.setAndEmitConnectionState(LB.Connected),t.video){let e=new EB($.Kind.Video,new IO({source:vO.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:_O.AUDIO,name:`video-dummy`}),new cR(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:SP(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(X.LocalTrackPublished,e)}if(t.audio){let e=new EB($.Kind.Audio,new IO({source:vO.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:_O.AUDIO}),new HL(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:wP(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(X.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new AO({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:jO.ACTIVE,tracks:[],joinedAt:AE.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=SP(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new IO({source:vO.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:_O.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=wP(),n=new IO({source:vO.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:_O.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==Y.ActiveSpeakersChanged&&e!==Y.TranscriptionReceived){let n=VB(t).filter(e=>e!==void 0);(e===Y.TrackSubscribed||e===Y.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,{event:e,args:n}),this.log.debug(`room event ${e}`,{event:e,args:n})}return super.emit(e,...t)}};BB.cleanupRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});function VB(e){return e.map(e=>{if(e)return Array.isArray(e)?VB(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var HB;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(HB||={}),pj.EventEmitter,pj.EventEmitter,new TextEncoder,new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});var UB=class extends Error{constructor(e,t){var n;super(e,t),RE(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};RE(UB,`code`,`ERR_JOSE_GENERIC`),RE(class extends UB{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),RE(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),RE(this,`claim`,void 0),RE(this,`reason`,void 0),RE(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),RE(class extends UB{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),RE(this,`code`,`ERR_JWT_EXPIRED`),RE(this,`claim`,void 0),RE(this,`reason`,void 0),RE(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),RE(class extends UB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),RE(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),RE(class extends UB{constructor(){super(...arguments),RE(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),RE(class extends UB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),RE(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),RE(class extends UB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),RE(this,Symbol.asyncIterator,XE(function*(){})),RE(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),RE(class extends UB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),RE(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),RE(class extends UB{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),RE(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);var WB=new Set;function GB(e){WB.add(e)}function KB(e){return WB.has(e)}var qB=z({server_url:P(),participant_token:P(),call:P()});function JB(e){let t=j(),[n,r]=(0,D.useState)(`idle`),[i,a]=(0,D.useState)(`talk`),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(null),[f,p]=(0,D.useState)([]),[m,h]=(0,D.useState)(null),g=(0,D.useRef)(null),_=(0,D.useRef)(new Set),v=(0,D.useRef)(null),y=(0,D.useRef)([]),b=(0,D.useRef)(null),x=(0,D.useCallback)(()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null);let e=y.current;y.current=[],e.length>0&&p(t=>[...t,...e])},[]),S=(0,D.useCallback)(e=>{if(!_.current.has(e.id)){_.current.add(e.id),e.speaker===`user`&&x(),p(t=>BT(t,e)),v.current=e.speaker,e.speaker===`agent`&&x();return}p(t=>BT(t,e))},[x]),C=(0,D.useRef)(0),w=(0,D.useCallback)(async e=>{let t=g.current;if(t===null)return;C.current+=1;let n=`typed-${C.current}`;x(),p(t=>[...t,{kind:`said`,id:n,speaker:`user`,text:e,final:!0,pending:!0}]),v.current=`user`;try{await t.localParticipant.sendText(e,{topic:FT})}catch(e){p(e=>e.filter(e=>e.id!==n)),h(e instanceof Error?e.message:String(e))}},[x]),T=(0,D.useCallback)(e=>{if(e.type===`turn.user`){let t=String(e.data.text??``).trim();p(e=>{let n=e.findIndex(e=>e.kind===`said`&&e.pending===!0&&e.text.trim()===t);if(n===-1)return e;let r=e.slice();return r[n]={...e[n],pending:!1},r});return}let t=HT(e);if(t!==null){if(v.current===`agent`){p(e=>[...e,t]);return}y.current.push(t),b.current!==null&&window.clearTimeout(b.current),b.current=window.setTimeout(x,IT)}},[x]),ee=(0,D.useCallback)(async n=>{r(`connecting`),a(n),l(!1),s(null),h(null),p([]),_.current.clear(),v.current=null,y.current=[];try{let i=qB.parse(await sa(t,`/v1/tokens`,{agent:e,scope:n})),a=new BB;g.current=a,a.registerTextStreamHandler(NT,(e,t)=>{YB(a,e,t.identity,S)}),n===`talk`&&a.on(Y.TrackSubscribed,XB),a.on(Y.TrackUnsubscribed,e=>e.detach().forEach(e=>e.remove())),a.on(Y.Disconnected,()=>r(`ended`)),GB(i.call),d(i.call),await a.connect(i.server_url,i.participant_token),n===`talk`&&await a.localParticipant.setMicrophoneEnabled(!0),s(Date.now()/1e3),r(`live`)}catch(e){h(e instanceof Error?e.message:String(e)),r(`failed`)}},[e,t,S]),te=(0,D.useCallback)(async()=>{await g.current?.disconnect()},[]),ne=(0,D.useCallback)(async()=>{let e=g.current;e!==null&&(await e.localParticipant.setMicrophoneEnabled(c),l(!c))},[c]);return(0,D.useEffect)(()=>()=>{g.current?.disconnect()},[]),{phase:n,mode:i,call:u,lines:f,error:m,since:o,muted:c,open:ee,close:te,toggleMic:ne,write:w,heard:T}}async function YB(e,t,n,r){let i=t.info.attributes?.[`lk.segment_id`]??t.info.id,a=e.remoteParticipants.get(n)?.kind===MO.AGENT?`agent`:`user`,o=``;for await(let e of t)o+=e,r({kind:`said`,id:i,speaker:a,text:o,final:!1});r({kind:`said`,id:i,speaker:a,text:o,final:t.info.attributes?.[PT]===`true`})}function XB(e){if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.style.display=`none`,document.body.append(t)}function ZB(){let e=Sr().agent??``,t=JB(e),n=wh(),{world:r}=kh(),i=t.phase===`live`||t.phase===`connecting`,a=vh({name:`agent.inspector`,initial:330,min:260,max:620,side:`right`}),o=n?.name??n?.label??`this key`;return(0,A.jsxs)(`div`,{className:`talk-grid`,style:a.style,children:[a.handle,(0,A.jsxs)(sh,{width:760,children:[(0,A.jsx)(ch,{title:`Talk to ${e}`,lede:`This machine's microphone reaches the agent, and it answers out loud. You can write into the same call too — a number, an address, a name nobody spells out loud.`}),(0,A.jsxs)(`div`,{className:`talk-card`,children:[(0,A.jsx)(QB,{live:t}),(0,A.jsxs)(`div`,{className:`talk-standing`,children:[(0,A.jsx)(`div`,{className:`talk-phase`,children:eV(t)}),(0,A.jsx)(`div`,{className:`talk-hint`,children:tV(t)})]}),t.phase===`live`&&(0,A.jsxs)(`div`,{className:`talk-mic`,children:[(0,A.jsxs)(`span`,{className:t.muted?`talk-bars`:`talk-bars talk-bars-on`,"aria-hidden":!0,children:[(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{})]}),(0,A.jsx)(U,{size:`sm`,onClick:()=>void t.toggleMic(),children:t.muted?`Unmute`:`Mute`})]}),t.phase===`ended`&&t.call!==null&&(0,A.jsx)(zm,{size:`sm`,to:`/a/${e}/sessions/${t.call}`,children:`Open the session`}),i&&t.call!==null&&(0,A.jsx)(`div`,{className:`talk-call`,children:t.call})]}),(0,A.jsxs)(`div`,{className:`talk-facts`,children:[(0,A.jsxs)(`div`,{className:`talk-fact`,children:[(0,A.jsx)(`div`,{className:`talk-fact-label`,children:`Speaking as`}),(0,A.jsxs)(`div`,{className:`talk-fact-value`,children:[o,` · you`]})]}),(0,A.jsxs)(`div`,{className:`talk-fact`,children:[(0,A.jsx)(`div`,{className:`talk-fact-label`,children:`Lands in`}),(0,A.jsxs)(`div`,{className:`talk-fact-value`,children:[r,` · counts in usage`]})]})]}),(0,A.jsx)(Nm,{children:t.error}),(0,A.jsx)(GT,{lines:i?t.lines:[],mode:`talk`,children:(0,A.jsx)(JT,{open:t.phase===`live`,mode:`talk`,onWrite:t.write})}),t.call!==null&&(0,A.jsx)($B,{call:t.call,heard:t.heard})]}),(0,A.jsx)(aw,{agent:e,call:t.call})]})}function QB({live:e}){let t=nV(e.phase===`live`);return e.phase===`live`||e.phase===`connecting`?(0,A.jsxs)(`button`,{type:`button`,className:`talk-door talk-door-on`,disabled:e.phase===`connecting`,onClick:()=>void e.close(),children:[(0,A.jsx)(`span`,{children:`Hang up`}),e.phase===`live`&&(0,A.jsx)(`span`,{className:`talk-door-clock`,children:Jh(e.since,t)})]}):(0,A.jsx)(`button`,{type:`button`,className:`talk-door`,onClick:()=>void e.open(`talk`),children:`Call`})}function $B({call:e,heard:t}){return tw(e,{onEntry:t}),null}function eV(e){switch(e.phase){case`idle`:return`Ready — press Call`;case`connecting`:return`Joining the room…`;case`live`:return e.muted?`On the call — muted`:`On the call — speak or write`;case`ended`:return`The call ended`;case`failed`:return`The room did not open`}}function tV(e){switch(e.phase){case`idle`:return`The browser asks for the microphone, and the agent answers straight away.`;case`connecting`:return`The microphone opens as soon as the room does.`;case`live`:return`Everything said lands in the log beside you.`;case`ended`:return`Judged at hang-up. Press the button to call again.`;case`failed`:return`Nothing reached the agent. The reason is under the facts.`}}function nV(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}function rV(){let e=Sr().agent??``,t=JB(e),{world:n}=kh(),r=t.phase===`live`||t.phase===`connecting`,i=vh({name:`agent.inspector`,initial:330,min:260,max:620,side:`right`}),a=(0,D.useRef)(``);return(0,D.useEffect)(()=>{e!==``&&a.current!==e&&(a.current=e,t.open(`chat`))},[e,t]),(0,A.jsxs)(`div`,{className:`rchat-grid`,style:i.style,children:[i.handle,(0,A.jsx)(`div`,{className:`rchat-stage`,children:(0,A.jsxs)(`section`,{className:`rchat`,"aria-label":`Chat with ${e}`,children:[(0,A.jsx)(iV,{agent:e,live:t,world:n}),r||t.lines.length>0?(0,A.jsx)(GT,{lines:t.lines,mode:`chat`}):(0,A.jsx)(aV,{agent:e,live:t}),t.error!==null&&(0,A.jsx)(`p`,{className:`rchat-refused`,children:t.error}),(0,A.jsx)(JT,{open:t.phase===`live`,mode:`chat`,onWrite:t.write}),t.call!==null&&(0,A.jsx)(sV,{call:t.call,heard:t.heard})]})}),(0,A.jsx)(aw,{agent:e,call:t.call})]})}function iV({agent:e,live:t,world:n}){let r=cV(t.phase===`live`);return(0,A.jsxs)(`header`,{className:`rchat-bar`,children:[(0,A.jsx)(`span`,{className:t.phase===`live`?`rchat-light rchat-light-on`:`rchat-light`,"aria-hidden":!0}),(0,A.jsxs)(`div`,{className:`rchat-words`,children:[(0,A.jsxs)(`div`,{className:`rchat-title`,children:[`Chat with `,e]}),(0,A.jsx)(`div`,{className:`rchat-standing`,children:oV(t,r,n)})]}),(0,A.jsxs)(`div`,{className:`rchat-moves`,children:[t.phase===`ended`&&t.call!==null&&(0,A.jsx)(zm,{size:`sm`,to:`/a/${e}/sessions/${t.call}`,children:`Open the session`}),t.phase===`live`||t.phase===`connecting`?(0,A.jsx)(U,{kind:`danger`,size:`sm`,disabled:t.phase===`connecting`,onClick:()=>void t.close(),children:`End chat`}):(0,A.jsx)(U,{kind:`primary`,size:`sm`,onClick:()=>void t.open(`chat`),children:t.lines.length===0?`Start a chat`:`Start another`})]})]})}function aV({agent:e,live:t}){return(0,A.jsxs)(`div`,{className:`rchat-empty`,children:[(0,A.jsx)(`p`,{className:`rchat-empty-words`,children:t.phase===`connecting`?`Opening a written room with ${e}…`:`Write to ${e} as a visitor would. No microphone and no voice: the agent answers in writing, with the same tools, memory and knowledge, and the call is judged at hang-up like any other.`}),t.phase===`failed`&&(0,A.jsx)(`p`,{className:`rchat-empty-failed`,children:`The room did not open. The reason is below.`})]})}function oV(e,t,n){switch(e.phase){case`idle`:return`Not started — it lands in ${n} and counts in usage`;case`connecting`:return`Opening the room…`;case`live`:return`Chatting · ${Jh(e.since,t)}`;case`ended`:return`The chat ended — judged at hang-up, in Sessions`;case`failed`:return`The room did not open`}}function sV({call:e,heard:t}){return tw(e,{onEntry:t}),null}function cV(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}async function lV(e,t,n){if(n<=0)return null;let r=Bv.parse(await k(e,`/v1/calls/${encodeURIComponent(t)}/events`,{after:n-1,types:Fv,limit:1})).entries.find(e=>e.type===Fv);return r===void 0?null:Y_.parse(r.data)}var uV=20;function dV(e){let t=j(),n=(0,D.useRef)(new Map),[r,i]=(0,D.useState)(n.current),a=e.filter(e=>!VS(e)).slice(0,uV),o=a.map(e=>`${e.call}@${e.last_seq}`).join(` `);return(0,D.useEffect)(()=>{let e=!1,r=a.filter(e=>!n.current.has(e.call));return(async()=>{let a=await Promise.all(r.map(e=>fV(t,e)));if(!(e||a.length===0)){for(let e of a)n.current.set(e.line.call,e);i(new Map(n.current))}})(),()=>{e=!0}},[o,t]),a.map(e=>r.get(e.call)??pV(e))}async function fV(e,t){try{return{line:t,read:!0,score:await lV(e,t.call,t.last_seq),refused:null}}catch(e){return{line:t,read:!0,score:null,refused:String(e)}}}function pV(e){return{line:e,read:!1,score:null,refused:null}}function mV(e){let{lines:t,error:n}=BS(e);return{rows:dV(t),error:n}}function hV({call:e}){let t=j(),n=Sr().agent??``,[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),d=async r=>{i(r),u(null);try{r===`check`?o(await rT(t,e)):c(await aT(t,n,e))}catch(e){u(e instanceof na?e.message:String(e))}finally{i(``)}};return(0,A.jsxs)(`div`,{className:`ev-acts`,children:[(0,A.jsxs)(`div`,{className:`ev-acts-buttons`,children:[(0,A.jsx)(U,{size:`md`,disabled:r!==``,onClick:()=>void d(`check`),children:r===`check`?`Checking…`:`Re-check by code`}),(0,A.jsx)(U,{size:`md`,disabled:r!==``,onClick:()=>void d(`promote`),children:r===`promote`?`Writing…`:`Promote to a golden`})]}),a!==null&&(0,A.jsx)(`div`,{className:`ui-tags`,children:a.verdicts.map(e=>(0,A.jsx)(`span`,{title:e.detail,children:(0,A.jsxs)(Qm,{tone:e.status===`passed`?`green`:e.status===`failed`?`red`:`muted`,children:[e.check,` `,e.status]})},e.check))}),s!==null&&(0,A.jsxs)(`div`,{className:`ui-note`,children:[`Written to `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:s.path}),` · `,s.candidate.input.length,` caller turn(s)`,s.notes.map(e=>(0,A.jsx)(`div`,{children:e},e))]}),(0,A.jsx)(Nm,{children:l})]})}var gV=`minmax(0,1.2fr) 120px 104px minmax(0,1.7fr) 70px 84px`;function _V({agent:e,rows:t}){let[n,r]=(0,D.useState)(null);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:gV,labels:[`Call`,`Started`,`Verdict`,`Judges`,`Calls>`,`Cost>`]}),t.map(t=>(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:t.line.call===n?`ui-table-row ui-table-row-link ev-row-open`:`ui-table-row ui-table-row-link`,style:{gridTemplateColumns:gV},onClick:()=>r(t.line.call===n?null:t.line.call),children:[(0,A.jsx)(`span`,{className:`ui-cell-link ui-clip`,children:t.line.call}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:Qh(t.line.started_at)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(vV,{row:t})}),(0,A.jsx)(`span`,{className:`ui-tags`,children:t.score?.judges.map(e=>(0,A.jsx)(`span`,{className:e.verdict===`held`?`ev-judge`:`ev-judge ev-judge-bad`,children:e.name},e.name))}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:t.score?.judge_calls??`—`}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:Yh(t.score?.judge_cost_eur)})]}),t.line.call===n&&(0,A.jsx)(yV,{agent:e,row:t})]},t.line.call))]})}function vV({row:e}){return e.read?e.refused===null?e.score?.passed==null?(0,A.jsx)(Qm,{tone:`muted`,children:`not judged`}):e.score.passed?(0,A.jsx)(Qm,{tone:`green`,children:`passed`}):(0,A.jsx)(Qm,{tone:`red`,children:`did not pass`}):(0,A.jsx)(`span`,{title:e.refused,children:(0,A.jsx)(Qm,{tone:`red`,children:`unreadable`})}):(0,A.jsx)(Qm,{tone:`muted`,children:`reading…`})}function yV({agent:e,row:t}){let n=t.score;return(0,A.jsxs)(`div`,{className:`ev-evidence`,children:[(0,A.jsx)(`div`,{className:`ev-evidence-head`,children:(0,A.jsx)(Wi,{className:`ui-cell-link`,to:`/a/${e}/sessions/${t.line.call}`,children:`Open the session`})}),(0,A.jsx)(hV,{call:t.line.call}),n===null&&(0,A.jsx)(`div`,{className:`ui-note`,children:`This call's log carries no verdict.`}),n?.not_judged!=null&&(0,A.jsx)(`div`,{className:`ev-warn`,children:n.not_judged}),n!==null&&(0,A.jsx)(bV,{score:n}),n?.judges.filter(e=>e.verdict!==`held`).map(n=>(0,A.jsx)(xV,{agent:e,call:t.line.call,judgment:n},n.name)),n!==null&&n.judges.length>0&&n.judges.every(e=>e.verdict===`held`)&&(0,A.jsxs)(`div`,{className:`ui-note`,children:[`Every judge on the panel held: `,n.judges.map(e=>e.name).join(`, `),`.`]})]})}function bV({score:e}){let t=new Set(e.judges.map(e=>e.name)),n=(e.panel??[]).filter(e=>!t.has(e));return n.length===0?null:(0,A.jsxs)(`div`,{className:`ev-warn`,children:[n.join(`, `),` was run over this call and answered nothing; the panel was `,e.panel?.join(`, `),`.`]})}function xV({agent:e,call:t,judgment:n}){let r=n.evidence.seqs;return(0,A.jsxs)(`div`,{className:`ev-said`,children:[(0,A.jsxs)(Im,{children:[n.name,` · `,n.verdict]}),(0,A.jsxs)(`div`,{className:`ev-said-body`,children:[(0,A.jsx)(`div`,{className:`ev-reason`,children:n.reason}),(0,A.jsx)(`div`,{className:`ui-cell-faint`,children:n.criteria}),n.evidence.said!=null&&(0,A.jsxs)(`div`,{className:`ev-quote`,children:[`“`,n.evidence.said,`”`]}),r.length>0&&(0,A.jsx)(`div`,{className:`ui-tags`,children:r.map(n=>(0,A.jsxs)(Wi,{className:`ui-tag`,to:`/a/${e}/sessions/${t}#seq-${n}`,children:[`seq `,n]},n))})]})]})}var SV=86400,CV=7,wV=30,TV=`minmax(0,1fr) 150px 150px 90px`;function EV({agent:e}){let t=j(),[n,r]=(0,D.useState)(CV),[i,a]=(0,D.useState)(wV),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!0),[u,d]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let r=!1;return l(!0),eT(t,e,n*SV,i*SV).then(e=>{r||(s(e),l(!1))},e=>{r||(d(e instanceof na?e.message:String(e)),l(!1))}),()=>{r=!0}},[t,e,n,i]),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Drift`,meta:c?`reading…`:`held-rate per judge, over two windows`,children:(0,A.jsxs)(`span`,{className:`ev-drift-windows`,children:[(0,A.jsxs)(`label`,{className:`ev-drift-field`,children:[(0,A.jsx)(`span`,{children:`now, days`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:365,value:n,onChange:e=>r(Number(e.target.value))})]}),(0,A.jsxs)(`label`,{className:`ev-drift-field`,children:[(0,A.jsx)(`span`,{children:`against the last`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:365,value:i,onChange:e=>a(Number(e.target.value))})]})]})}),(0,A.jsx)(Nm,{children:u}),o!==null&&o.drift.judges.length===0&&(0,A.jsx)(Mm,{children:`No finished call of this agent carries a verdict in either window.`}),o!==null&&o.drift.judges.length>0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:TV,labels:[`Judge`,`Before>`,`Now>`,`Points>`]}),o.drift.judges.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:TV},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.judge}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:DV(e,`before`)}),(0,A.jsx)(`span`,{className:`ev-num`,children:DV(e,`now`)}),(0,A.jsx)(`span`,{className:OV(e,o.threshold)?`ev-num ev-num-bad`:`ev-num ev-num-faint`,children:e.delta===null?`—`:`${e.delta>0?`+`:``}${e.delta.toFixed(0)}`})]},e.judge)),(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[o.drift.notJudged.now,` call`,o.drift.notJudged.now===1?``:`s`,` in this window carried no verdict at all (`,o.drift.notJudged.before,` before it). A judge may fall `,o.threshold.toFixed(0)," points before `pinecall runs drift` fails the night."]}),o.drift.broke.map(t=>(0,A.jsxs)(`div`,{className:`ev-broke`,children:[(0,A.jsx)(Wi,{className:`ui-cell-link ui-clip`,to:`/a/${e}/sessions/${t.call}`,children:t.call}),(0,A.jsx)(`span`,{className:`ev-judge ev-judge-bad`,children:t.judge}),(0,A.jsx)(`span`,{className:`ev-reason`,children:t.reason})]},`${t.call}-${t.judge}`))]})]})}function DV(e,t){let n=e[t];return n===null?`—`:`${n.percent.toFixed(0)}% · ${n.held}/${n.settled}`}function OV(e,t){return e.delta!==null&&e.delta<-Math.abs(t)}var kV=` · `;function AV(e,t,n){return[t,e,n].join(kV)}function jV(e){if(e===null)return{held:0,judgments:0};let t=e.runs.flatMap(e=>e.scores);return{held:t.filter(e=>e.passed).length,judgments:t.length}}function MV(e,t){if(t?.matrix==null||e.matrix===null)return null;let n=NV(t.matrix),r=NV(e.matrix),i=[...r.keys()].filter(e=>n.has(e));return{broke:i.filter(e=>n.get(e)===!0&&r.get(e)===!1),recovered:i.filter(e=>n.get(e)===!1&&r.get(e)===!0)}}function NV(e){let t=new Map;for(let n of e.runs)for(let e of n.scores)t.set(AV(n.model,n.golden,e.metric),e.passed);return t}function PV({run:e}){let t=j(),n=Sr().agent??``,[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);if((0,D.useEffect)(()=>{let r=!1;return c(null),u(null),cT(t,n,e).then(e=>{r||(i(e.goldens),o(e.folder))},()=>{r||i([])}),()=>{r=!0}},[t,n,e]),r===null||r.length===0)return null;let d=async r=>{u(null);try{c(await lT(t,n,e,r))}catch(e){u(e instanceof na?e.message:String(e))}};return(0,A.jsxs)(`div`,{className:`ev-repro`,children:[(0,A.jsx)(Im,{ruled:!0,children:`Reproductions`}),(0,A.jsxs)(`div`,{className:`ev-repro-body`,children:[(0,A.jsxs)(`div`,{className:`ui-note`,children:[r.length,` in `,(0,A.jsxs)(`span`,{className:`ui-fixed`,children:[a,`/`]}),` — the golden as written, every verdict on it, and the requests the model answered.`]}),(0,A.jsx)(`div`,{className:`ui-chips`,children:r.map(e=>(0,A.jsx)(`button`,{type:`button`,className:s?.golden===e?`ui-chip ui-chip-on`:`ui-chip`,onClick:()=>void d(e),children:e},e))}),(0,A.jsx)(Nm,{children:l}),s!==null&&(0,A.jsxs)(`div`,{className:`ev-repro-open`,children:[(0,A.jsxs)(`div`,{className:`ev-repro-title`,children:[s.golden,` · `,s.model,` `,(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:s.call})]}),s.verdicts.filter(e=>!e.passed).map(e=>(0,A.jsxs)(`div`,{className:`ev-repro-verdict`,children:[(0,A.jsx)(Qm,{tone:`red`,small:!0,children:e.metric}),(0,A.jsx)(`span`,{className:`ev-reason`,children:e.reason})]},e.metric)),(0,A.jsx)(`pre`,{className:`ui-code ev-asked`,children:JSON.stringify(s.asked,null,2)})]})]})]})}var FV=`minmax(0,1.1fr) 120px 84px 70px 80px minmax(0,1.6fr)`,IV={done:`green`,running:`amber`,failed:`red`};function LV({runs:e,selected:t,onSelect:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:FV,labels:[`Run`,`Started`,`Status`,`Held>`,`Judge calls>`,`Since the run before`]}),e.map((r,i)=>{let a=jV(r.matrix),o=r.id===t;return(0,A.jsxs)(`div`,{className:o?`ui-table-row ui-table-row-link ev-row-open`:`ui-table-row ui-table-row-link`,style:{gridTemplateColumns:FV},onClick:()=>n(r.id),children:[(0,A.jsx)(`span`,{className:`ui-cell-link ui-clip`,children:r.id}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:Qh(r.started_at)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(Qm,{tone:IV[r.status],children:r.status})}),(0,A.jsx)(`span`,{className:a.judgments>0&&a.held<a.judgments?`ev-num ev-num-bad`:`ev-num`,children:a.judgments===0?`—`:`${a.held}/${a.judgments}`}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:r.matrix?.judge_calls??`—`}),(0,A.jsx)(RV,{delta:MV(r,e[i+1])})]},r.id)})]})}function RV({delta:e}){return e===null?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`first of its kind`}):e.broke.length===0&&e.recovered.length===0?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`±0`}):(0,A.jsxs)(`span`,{className:`ui-tags`,children:[e.broke.map(e=>(0,A.jsxs)(Qm,{tone:`red`,small:!0,children:[`broke · `,e]},`broke-${e}`)),e.recovered.map(e=>(0,A.jsxs)(Qm,{tone:`green`,small:!0,children:[`held again · `,e]},`held-${e}`))]})}var zV=`minmax(0,1.1fr) minmax(0,.8fr) 110px 120px 84px minmax(0,1.6fr)`,BV={done:`green`,running:`amber`,failed:`red`};function VV({run:e,before:t}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:e.id,meta:`${e.agent} · ${e.matrix?.judge_calls??0} judge calls`,children:(0,A.jsx)(`span`,{className:`ev-head-end`,children:(0,A.jsx)(Qm,{tone:BV[e.status],children:e.status})})}),(0,A.jsxs)(`div`,{className:`ev-facts`,children:[(0,A.jsx)(Lm,{label:`Started`,children:Qh(e.started_at)}),(0,A.jsx)(Lm,{label:`Finished`,children:Qh(e.finished_at)}),e.error!==null&&(0,A.jsx)(Lm,{label:`Error`,children:e.error}),(0,A.jsx)(Lm,{label:`Since before`,children:(0,A.jsx)(RV,{delta:MV(e,t)})})]}),e.matrix===null?(0,A.jsx)(Mm,{children:`No matrix yet — the run is still opening its calls, or it failed before a judge answered.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:zV,labels:[`Golden`,`Model`,`Metric`,`Score`,`Held`,`The judge's own sentence`]}),e.matrix.runs.flatMap(t=>t.scores.map(n=>(0,A.jsx)(HV,{run:e,cell:t,score:n},`${t.golden}/${t.model}/${n.metric}`))),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`A hard policy writes the seqs into its reason on purpose, so the sentence is the way into the log.`})]}),(0,A.jsx)(PV,{run:e.id})]})}function HV({run:e,cell:t,score:n}){let r=e.calls.find(e=>e.golden===t.golden&&e.model===t.model);return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:zV},children:[(0,A.jsxs)(`span`,{className:`ev-golden`,children:[(0,A.jsx)(`span`,{className:`ev-golden-says ui-clip`,children:t.golden}),r!==void 0&&(0,A.jsx)(Wi,{className:`ev-golden-call ui-clip`,to:`/a/${e.agent}/sessions/${r.call}`,children:r.call})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip`,children:t.model}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:n.metric}),(0,A.jsxs)(`span`,{className:`ev-score`,children:[(0,A.jsx)(`span`,{className:`ev-score-value`,children:n.score.toFixed(2)}),(0,A.jsx)(oh,{share:n.score,color:n.passed?`var(--green-dot)`:`var(--red)`,height:5})]}),(0,A.jsx)(`span`,{children:n.passed?(0,A.jsx)(Qm,{tone:`green`,children:`held`}):(0,A.jsx)(Qm,{tone:`red`,children:`did not hold`})}),(0,A.jsx)(`span`,{className:`ev-reason`,title:n.criteria,children:n.reason})]})}var UV=z({name:P(),input:R(P()),expect:fp(P(),Zf())}),WV=z({agent:P().nullable(),goldens:R(UV)}),GV=z({run:P()});async function KV(e,t){return WV.parse(await eC(e,t,`goldens.roster`))}async function qV(e,t){return GV.parse(await eC(e,t.agent,`goldens.run`,t)).run}var JV=15,YV=0;function XV({agent:e,roster:t,onOpened:n}){let r=j(),[i,a]=(0,D.useState)(()=>new Set(t.goldens.map(e=>e.name))),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(JV),[m,h]=(0,D.useState)(YV),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),b=(e,t)=>{let n=new Set(i);t?n.add(e):n.delete(e),a(n)},x=i.size===t.goldens.length,S=async a=>{a.preventDefault(),_(!0),y(null);try{let a=o.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(await qV(r,{agent:e,goldens:t.goldens.map(e=>e.name).filter(e=>i.has(e)),...a.length===0?{}:{models:a},voice:c,...c&&u?{background_noise:f,packet_loss:m/100}:{}}))}catch(e){y(e instanceof na?e.message:String(e))}finally{_(!1)}};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Run a suite`,meta:`through the class in the directory pinecall start runs in, scored by this gateway`}),(0,A.jsxs)(`form`,{onSubmit:e=>void S(e),children:[(0,A.jsxs)(`div`,{className:`ev-suite-controls`,children:[(0,A.jsxs)(`div`,{className:`ev-suite-models`,children:[(0,A.jsx)(Vm,{children:`Models`}),(0,A.jsx)(W,{size:`sm`,value:o,placeholder:`the one the settings name · vendor/model, comma separated`,onChange:e=>s(e.target.value)})]}),(0,A.jsx)(Ym,{checked:c,onChange:l,children:`Voice — ring 2, a real line`}),c&&(0,A.jsx)(Ym,{checked:u,onChange:d,children:`Noisy line`}),c&&u&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ev-suite-number`,children:[(0,A.jsx)(Vm,{children:`Noise, dB under`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:60,value:f,onChange:e=>p(Number(e.target.value))})]}),(0,A.jsxs)(`div`,{className:`ev-suite-number`,children:[(0,A.jsx)(Vm,{children:`Packets lost, %`}),(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:100,value:m,onChange:e=>h(Number(e.target.value))})]})]}),(0,A.jsx)(U,{kind:`primary`,size:`md`,type:`submit`,className:`ev-suite-go`,disabled:g||i.size===0,children:g?`Opening…`:`Run ${x?`the suite`:`${i.size} golden${i.size===1?``:`s`}`}`})]}),(0,A.jsx)(`div`,{className:`ev-suite-all`,children:(0,A.jsxs)(Ym,{checked:x,onChange:e=>a(new Set(e?t.goldens.map(e=>e.name):[])),children:[i.size,` of `,t.goldens.length]})}),t.goldens.map(e=>(0,A.jsxs)(`div`,{className:`ev-suite-golden`,children:[(0,A.jsx)(Ym,{checked:i.has(e.name),onChange:t=>b(e.name,t),children:(0,A.jsx)(`span`,{className:`ev-suite-name`,children:e.name})}),(0,A.jsx)(`span`,{className:`ev-suite-says ui-clip`,children:e.input[0]??``}),(0,A.jsx)(`span`,{className:`ev-suite-expects ui-clip`,children:ZV(e)})]},e.name))]}),(0,A.jsx)(Nm,{children:v})]})}function ZV(e){let t=Object.entries(e.expect).map(([e,t])=>`${e}: ${QV(t)}`);return t.length===0?`consent only`:t.join(` · `)}function QV(e){return Array.isArray(e)?e.map(String).join(`, `):String(e)}var $V=3e3;function eH(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(!0),[o,s]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=await Yw(t,e);n||(r(i),s(null))}catch(e){n||s(String(e))}finally{n||a(!1)}};i();let o=window.setInterval(()=>void i(),$V);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{runs:n,reading:i,error:o}}var tH=`minmax(0,1fr) 110px 90px`;function nH(e){let t=Object.keys(e.expect);return t.includes(`tools`)||t.includes(`not_tools`)?`tool call`:t.includes(`says`)||t.includes(`not`)?`exact phrase`:t.includes(`grounded`)||t.includes(`register`)?`judge`:t.includes(`replies`)?`a reply`:t.length===0?`consent`:t[0]??`—`}function rH(e){let t=new Map;for(let n of e?.matrix?.runs??[]){let e=n.scores.every(e=>e.passed);t.set(n.golden,(t.get(n.golden)??!0)&&e)}return t}function iH(){let e=Sr().agent??``,t=j(),[n,r]=Xi(),i=eH(e),a=mV(e),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(null),m=fm===`local`;(0,D.useEffect)(()=>{let n=!1;return KV(t,e).then(e=>{n||s(e)},e=>{n||l(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[t,e]);let h=n.get(`view`),g=h===`calls`||h===`drift`?h:h===`runs`&&m||m?`runs`:`calls`,_=n.get(`run`),v=i.runs.find(e=>e.id===_)??null,y=i.runs.find(e=>e.matrix!==null),b=rH(y),x=o!==null&&o.agent===e?o.goldens:[],S=x.length>0?x.map(e=>e.name):[...b.keys()],C=[...b.values()].filter(Boolean).length,w=b.size-C,T=e=>{let t=new URLSearchParams(n);for(let[n,r]of Object.entries(e))r===null?t.delete(n):t.set(n,r);r(t)},ee=async()=>{d(!0),p(null);try{let n=await qV(t,{agent:e,goldens:x.map(e=>e.name),voice:!1});T({view:null,run:n})}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}},te=[...m?[{value:`runs`,label:`Runs`}]:[],{value:`calls`,label:`Scored calls`},{value:`drift`,label:`Drift`}];return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Evals`,ledeWidth:620,lede:`Golden sessions replayed against the agent as it is now. A golden is fixed and the agent is the variable: never soften a golden so a change can pass.`}),(0,A.jsxs)(lh,{min:150,children:[(0,A.jsx)(uh,{size:`small`,label:`Goldens`,value:S.length===0?`—`:S.length}),(0,A.jsx)(uh,{size:`small`,label:`Passing`,value:y===void 0?`—`:C,tone:y===void 0?void 0:`green`}),(0,A.jsx)(uh,{size:`small`,label:`Failing`,value:y===void 0?`—`:w,tone:y===void 0||w===0?void 0:`red`}),(0,A.jsxs)(`div`,{className:`ui-stat ui-stat-small`,children:[(0,A.jsx)(`div`,{className:`ui-stat-label`,children:`Last run`}),(0,A.jsx)(`div`,{className:`ev-last`,children:i.runs[0]===void 0?`never`:Qh(i.runs[0].started_at)})]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Golden questions`,children:m&&x.length>0&&(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ev-run-all`,disabled:u,onClick:()=>void ee(),children:u?`Opening…`:`Run all`})}),S.length===0&&(0,A.jsx)(Mm,{children:o!==null&&o.agent!==e?o.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so no goldens to read.":`The process holding the agent runs in ${o.agent}'s directory; its goldens are that agent's.`:c!==null&&i.runs.length===0?`The goldens are files beside the class, read by the process holding the agent — and no run has been stored yet to list them from.`:`No goldens for this agent yet: write one in its goldens folder — test/goldens, or test/goldens/<name> in a project of several.`}),(0,A.jsx)(`div`,{className:`ev-goldens`,children:S.map(e=>{let t=x.find(t=>t.name===e),n=b.get(e);return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:tH},children:[(0,A.jsx)(`span`,{className:`ev-golden-says ui-clip`,title:e,children:t?.input[0]??e}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:t===void 0?`—`:nH(t)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:n===void 0?(0,A.jsx)(Qm,{tone:`muted`,children:`not run`}):n?(0,A.jsx)(Qm,{tone:`green`,children:`pass`}):(0,A.jsx)(Qm,{tone:`red`,children:`fail`})})]},e)})})]}),(0,A.jsx)(Nm,{children:f}),(0,A.jsx)(`div`,{className:`ev-views`,children:(0,A.jsx)(Gm,{options:te,value:g,onChange:e=>T({view:e===(m?`runs`:`calls`)?null:e,run:null})})}),g===`runs`&&(0,A.jsxs)(A.Fragment,{children:[o!==null&&o.agent===e&&x.length>0&&(0,A.jsx)(XV,{agent:e,roster:o,onOpened:e=>T({run:e})}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Runs`,meta:`${i.runs.length} · the same rows pinecall runs list prints`}),(0,A.jsx)(Nm,{children:i.error}),i.runs.length>0?(0,A.jsx)(LV,{runs:i.runs,selected:_,onSelect:e=>T({run:e})}):(0,A.jsx)(Mm,{children:i.reading?`Reading…`:`No run has been stored yet. A run appears here the moment one opens — from this page, a laptop or CI.`})]}),v!==null&&(0,A.jsx)(VV,{run:v,before:i.runs[i.runs.indexOf(v)+1]})]}),g===`drift`&&(0,A.jsx)(EV,{agent:e}),g===`calls`&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Scored calls`,meta:`the verdict is the call.score entry the log seals on`}),(0,A.jsx)(Nm,{children:a.error}),a.rows.length>0?(0,A.jsx)(_V,{agent:e,rows:a.rows}):(0,A.jsx)(Mm,{children:`No call of this agent has finished yet. The judges seal a call's log with its verdict when the caller hangs up; the first one lands here.`})]})]})}var aH=z({state_fields:fp(P(),mp([`public`,`tenant`,`pii`])).default({})});function oH(e){let t=j(),[n,r]=(0,D.useState)({});return(0,D.useEffect)(()=>{let n=!1;if(e!==``)return(async()=>{try{let i=aH.parse(await k(t,`/v1/agents/${e}/config`));n||r(i.state_fields)}catch{n||r({})}})(),()=>{n=!0}},[e,t]),n}function sH(e){let t=e?.recording;return typeof t==`string`&&t!==``?t:null}function cH({call:e,path:t}){let[n,r]=(0,D.useState)(!1),i=(0,D.useCallback)(()=>r(!0),[]);return t===null||n?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Listen to this call`}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(lH,{call:e,onNothing:i})})]})}function lH({call:e,onNothing:t}){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let r=null,a=!1;return(async()=>{try{let o=await fetch(la(n,`/v1/calls/${e}/recording`),{headers:ra(n)});if(o.status===404&&t!==void 0){a||t();return}if(!o.ok)throw Error(await uH(o));r=URL.createObjectURL(await o.blob()),a?URL.revokeObjectURL(r):i(r)}catch(e){a||o(e instanceof Error?e.message:String(e))}})(),()=>{a=!0,r!==null&&URL.revokeObjectURL(r)}},[e,n,t]),a===null?r===null?(0,A.jsx)(`p`,{className:`session-sentence`,children:`Reading the recording…`}):(0,A.jsx)(`audio`,{className:`session-player`,controls:!0,preload:`none`,src:r}):(0,A.jsx)(`p`,{className:`session-sentence`,children:a})}async function uH(e){try{let t=(await e.json()).detail;if(typeof t==`string`)return t}catch{}return`the recording answered ${e.status}`}var dH=z({server_url:P(),participant_token:P(),identity:P()});async function fH(e,t,n){return dH.parse(await sa(e,`/v1/calls/${t}/${n}`,{}))}function pH(e){let t=j(),[n,r]=(0,D.useState)(`off`),[i,a]=(0,D.useState)(null),o=(0,D.useRef)(null),s=(0,D.useRef)([]),c=(0,D.useCallback)(async()=>{r(`joining`),a(null);try{let n=await fH(t,e,`listen`),i=new BB;o.current=i,i.on(Y.TrackSubscribed,e=>{if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.muted=!0,t.style.display=`none`,document.body.append(t),s.current.push(t)}),i.on(Y.TrackUnsubscribed,e=>{for(let t of e.detach())t.remove(),s.current=s.current.filter(e=>e!==t)}),i.on(Y.Disconnected,()=>r(`off`)),await i.connect(n.server_url,n.participant_token),r(`muted`)}catch(e){a(e instanceof Error?e.message:String(e)),r(`failed`)}},[e,t]),l=(0,D.useCallback)(e=>{for(let t of s.current)t.muted=!e;r(e?`on`:`muted`)},[]),u=(0,D.useCallback)(async()=>{await o.current?.disconnect(),o.current=null},[]);return(0,D.useEffect)(()=>()=>{o.current?.disconnect()},[]),{listening:n,error:i,join:c,hear:l,leave:u}}var mH=`cold`,hH=class{#e;#t;#n=null;constructor(e,t){this.#e=e,this.#t=t}async send(e){await sa(this.#e,`/v1/calls/${this.#t}/verbs`,n_.parse(e))}async take(){await(await this.#r()).localParticipant.setMicrophoneEnabled(!0),await this.send({verb:`takeover`})}async give(){await this.send({verb:`release`}),await this.#i()}async leave(){await this.#i(),await this.#n?.disconnect(),this.#n=null}async#r(){if(this.#n!==null)return this.#n;let e=await fH(this.#e,this.#t,`supervise`),t=new BB;return await t.connect(e.server_url,e.participant_token,{autoSubscribe:!1}),this.#n=t,t}async#i(){let e=this.#n?.localParticipant,t=e?.getTrackPublication($.Source.Microphone);e!==void 0&&t?.track!==void 0&&await e.unpublishTrack(t.track,!0)}};function gH(e){let t=j(),[n,r]=(0,D.useState)(!1),[i,a]=(0,D.useState)(null),o=(0,D.useRef)(null),s=(0,D.useCallback)(()=>(o.current??=new hH(t,e),o.current),[e,t]),c=(0,D.useCallback)(async(e,t)=>{a(null);try{await e(s()),t!==null&&r(t)}catch(e){a(e instanceof Error?e.message:String(e))}},[s]),l=(0,D.useCallback)(e=>c(t=>t.send({verb:`whisper`,text:e}),null),[c]),u=(0,D.useCallback)(e=>c(t=>t.send({verb:`say`,text:e}),null),[c]),d=(0,D.useCallback)(()=>c(e=>e.take(),!0),[c]),f=(0,D.useCallback)(()=>c(e=>e.give(),!1),[c]),p=(0,D.useCallback)(e=>c(t=>t.send({verb:`transfer`,to:e,mode:mH}),null),[c]),m=(0,D.useCallback)(()=>c(e=>e.send({verb:`end`}),null),[c]);return(0,D.useEffect)(()=>()=>{o.current?.leave(),o.current=null},[]),{whisper:l,say:u,takeOver:d,release:f,transfer:p,end:m,holding:n,error:i}}var _H={whisper:`Whisper to the agent — the caller never hears it`,say:`Say it to the caller, in the agent's voice, verbatim`};function vH({call:e,live:t}){let n=pH(e),r=gH(e),i=(0,D.useRef)(!1);(0,D.useEffect)(()=>{t&&!i.current&&(i.current=!0,n.join())},[t,n]);let a=n.error??r.error;return(0,A.jsxs)(`div`,{className:`lv-desk`,role:`group`,"aria-label":`the supervisor's desk`,children:[(0,A.jsx)(yH,{ear:n,live:t}),t?(0,A.jsx)(bH,{desk:r}):(0,A.jsx)(`span`,{className:`lv-desk-note`,children:`The call is over: nothing is left to supervise. Read its log below, or play its recording.`}),a!==null&&(0,A.jsx)(`span`,{className:`lv-desk-refused`,children:a})]})}function yH({ear:e,live:t}){if(!t)return null;switch(e.listening){case`off`:case`failed`:return(0,A.jsxs)(U,{size:`sm`,pill:!0,onClick:()=>void e.join(),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot`}),`Listen`]});case`joining`:return(0,A.jsxs)(U,{size:`sm`,pill:!0,disabled:!0,children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-warm`}),`Joining…`]});case`muted`:return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(U,{size:`sm`,pill:!0,onClick:()=>e.hear(!0),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-warm`}),`Hear it`]}),(0,A.jsx)(U,{size:`sm`,pill:!0,onClick:()=>void e.leave(),children:`Stop`})]});case`on`:return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(U,{size:`sm`,pill:!0,onClick:()=>e.hear(!1),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-on`}),`Listening · mute`]}),(0,A.jsx)(U,{size:`sm`,pill:!0,onClick:()=>void e.leave(),children:`Stop`})]})}}function bH({desk:e}){let[t,n]=(0,D.useState)(`whisper`),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1),l=()=>{r.trim()!==``&&(t===`whisper`?e.whisper(r):e.say(r),i(``))},u=()=>{a!==null&&a.trim()!==``&&(e.transfer(a.trim()),o(null))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`lv-desk-say`,children:[(0,A.jsx)(Gm,{options:[{value:`whisper`,label:`Whisper`},{value:`say`,label:`Say`}],value:t,onChange:n}),(0,A.jsx)(W,{size:`sm`,className:`lv-desk-text`,value:r,placeholder:_H[t],onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&l()}}),(0,A.jsx)(U,{size:`sm`,kind:`primary`,disabled:r.trim()===``,onClick:l,children:`Send`})]}),(0,A.jsx)(U,{size:`sm`,className:e.holding?`lv-desk-holding`:void 0,title:e.holding?`the agent hears and speaks again, and your microphone stops`:`your microphone takes the line: the agent stops speaking`,onClick:()=>void(e.holding?e.release():e.takeOver()),children:e.holding?`Hand back`:`Take the line`}),a===null?(0,A.jsx)(U,{size:`sm`,onClick:()=>o(``),children:`Transfer`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(W,{size:`sm`,className:`lv-desk-number`,autoFocus:!0,value:a,placeholder:`+34… then Enter`,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Enter`&&u(),e.key===`Escape`&&o(null)}}),(0,A.jsx)(U,{size:`sm`,disabled:a.trim()===``,onClick:u,children:`Transfer`}),(0,A.jsx)(U,{size:`sm`,onClick:()=>o(null),children:`Cancel`})]}),(0,A.jsx)(U,{size:`sm`,kind:`danger`,className:s?`lv-desk-armed`:void 0,onClick:()=>{s&&e.end(),c(!s)},onBlur:()=>c(!1),children:s?`End · sure?`:`End call`})]})}var xH=new Set([`tag`,`name`,`id`,`flag`]);function SH({rows:e}){return(0,A.jsx)(`div`,{className:`lv-readings`,children:e.map(e=>(0,A.jsxs)(`div`,{className:`lv-reading`,children:[(0,A.jsx)(`span`,{className:`lv-reading-name`,children:e.field}),(0,A.jsxs)(`span`,{className:`lv-reading-value`,title:String(e.value),children:[CH(String(e.value)),e.unit!==null&&!xH.has(e.unit)&&(0,A.jsxs)(`span`,{className:`lv-seen`,children:[` `,e.unit]})]})]},e.field))})}function CH(e){return/^-?\d+\.\d{4,}$/.test(e)?Number(e).toFixed(3):e}function wH({metrics:e,entries:t}){let n=XC(t),r=Math.max(...n.map(e=>e.seconds),0),i=WC();return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{ruled:!0,children:`Metrics`}),(0,A.jsxs)(`div`,{className:`lv-pane-body`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`lv-sub`,children:`Nothing measured yet: the first turn fills this in.`}),n.map(e=>(0,A.jsxs)(`div`,{className:`lv-meter`,title:`median over ${String(e.turns)} turns`,children:[(0,A.jsx)(`span`,{className:`lv-meter-name`,children:e.name}),(0,A.jsx)(oh,{share:r===0?0:e.seconds/r}),(0,A.jsx)(`span`,{className:`lv-meter-value`,children:GC(e.seconds)})]},e.name)),Object.entries(e).map(([e,t])=>(0,A.jsx)(TH,{kind:e,blocks:t,shape:i.get(e)},e))]})]})}function TH({kind:e,blocks:t,shape:n}){return t.length===0?null:(0,A.jsxs)(`details`,{className:`lv-blocks`,children:[(0,A.jsxs)(`summary`,{children:[`metrics.`,e,` · `,t.length]}),t.map((t,r)=>(0,A.jsx)(SH,{rows:UC(t,n)},`${e}-${String(r)}`))]})}function EH({prompt:e,cost:t}){let n=Object.entries(e);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{ruled:!0,children:`Prompt`}),(0,A.jsxs)(`div`,{className:`lv-pane-body lv-pane-body-tight`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`lv-sub`,children:`The app has written no block yet.`}),n.map(([e,t])=>(0,A.jsxs)(`div`,{className:`lv-prompt-row`,children:[(0,A.jsx)(`span`,{className:`lv-prompt-name`,children:e}),(0,A.jsx)(`span`,{className:`lv-prompt-hash`,title:t.hash,children:t.hash.slice(0,8)}),(0,A.jsxs)(`span`,{className:`lv-prompt-chars`,children:[t.chars.toLocaleString(`en`).replace(/,/g,` `),` chars`]})]},e)),t!==null&&(0,A.jsx)(Lm,{label:`cost so far`,children:Yh(t.eur)})]})]})}function DH({room:e,from:t,over:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{ruled:!0,children:`Room`}),e===null?(0,A.jsx)(`div`,{className:`lv-pane-text`,children:`No room: this session carries no media.`}):(0,A.jsxs)(`div`,{className:`lv-pane-text`,children:[n?`Audio room closed`:`Audio room open`,` · `,e.participants.length,` `,e.participants.length===1?`participant`:`participants`,t!==null&&(0,A.jsxs)(A.Fragment,{children:[` · rang from `,t]}),(0,A.jsx)(`ul`,{className:`lv-people`,children:e.participants.map(e=>(0,A.jsx)(`li`,{className:`lv-person`,children:(0,A.jsxs)(`details`,{children:[(0,A.jsxs)(`summary`,{children:[(0,A.jsx)(eh,{tone:e.speaking?`green`:void 0,small:!0}),(0,A.jsx)(`span`,{children:e.name??e.identity}),(0,A.jsx)(`span`,{className:`lv-person-kind`,children:e.kind})]}),(0,A.jsx)(`pre`,{className:`lv-data`,children:JSON.stringify(e.attributes,null,2)})]})},e.identity))})]})]})}var OH=`***`,kH=`tenant`;function AH({fields:e,declared:t}){let n=Object.keys(e).sort();return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Im,{children:`State`}),n.length===0?(0,A.jsx)(`div`,{className:`lv-pane-text`,children:`The app has declared no state yet.`}):(0,A.jsx)(`div`,{className:`lv-pane-body`,children:n.map(n=>{let r=jH(e[n],t[n]);return(0,A.jsxs)(Lm,{label:n,children:[MH(e[n]),r!==kH&&(0,A.jsx)(`span`,{className:r===`pii`?`lv-seen lv-seen-pii`:`lv-seen`,children:r})]},n)})})]})}function jH(e,t){return e===OH?`pii`:t===`public`?`public`:kH}function MH(e){return typeof e==`string`?e:JSON.stringify(e)}function NH({seq:e,kind:t,tone:n,who:r,said:i,note:a=[],children:o}){let s=a.filter(e=>e!=null&&e!==``),c=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`lv-seq`,children:e}),(0,A.jsx)(`span`,{className:`lv-kind lv-kind-${n}`,children:t}),(0,A.jsxs)(`span`,{className:n===`turn`?`lv-text lv-text-turn`:n===`quiet`?`lv-text lv-text-quiet`:`lv-text`,children:[r!==void 0&&(0,A.jsx)(`span`,{className:r===`agent`?`lv-who lv-who-agent`:`lv-who`,children:r}),i,s.length>0&&(0,A.jsx)(`span`,{className:`lv-note`,children:s.map((e,t)=>(0,A.jsxs)(`span`,{children:[t>0&&` · `,e]},t))})]})]}),l=`lv-row lv-${n}`;return o==null||o===!1?(0,A.jsx)(`div`,{className:l,children:(0,A.jsx)(`div`,{className:`lv-line`,children:c})}):(0,A.jsxs)(`details`,{className:l,children:[(0,A.jsx)(`summary`,{className:`lv-line`,children:c}),(0,A.jsx)(`div`,{className:`lv-more`,children:o})]})}function PH(e){return e.ops.map(RH).join(`; `)}function FH(e){return e.ops.flatMap(e=>e.facts.map(e=>e.category?`${e.text} (${e.category})`:e.text))}function IH(e){return`${e.sources.length} sources · ${zH(e.took_ms)}`}function LH(e){return e.sources.map(e=>`${e.heading?`${e.path} › ${e.heading}`:e.path} · ${e.score.toFixed(3)}`)}function RH(e){return`${e.op} · ${e.facts.length} facts · ${zH(e.took_ms)}`}function zH(e){return`${Math.round(e)} ms`}function BH({ops:e,seq:t}){return(0,A.jsx)(HH,{kind:`memory`,said:PH(e),lines:FH(e),seq:t})}function VH({sources:e,seq:t}){return(0,A.jsx)(HH,{kind:`sources`,said:IH(e),lines:LH(e),seq:t})}function HH({kind:e,said:t,lines:n,seq:r}){return(0,A.jsx)(NH,{seq:r,kind:e,tone:`lookup`,said:t,children:(0,A.jsx)(`ul`,{className:`lv-list`,children:n.map(e=>(0,A.jsx)(`li`,{children:e},e))})})}function UH({changed:e,cause:t,seq:n}){return(0,A.jsx)(NH,{seq:n,kind:`state`,tone:`state`,said:`${e.join(`, `)} ← ${JH(t)}`})}function WH({mark:e,seq:t}){return(0,A.jsx)(NH,{seq:t,kind:`supervisor`,tone:`supervisor`,said:e.said,note:[e.by]})}function GH({confirm:e,seq:t}){let n=[{field:`tool`,value:e.tool,unit:null},{field:`audience`,value:e.audience,unit:null},...e.said==null?[]:[{field:`said`,value:e.said,unit:null}],...e.reason==null?[]:[{field:`reason`,value:e.reason,unit:null}]];return(0,A.jsx)(NH,{seq:t,kind:`confirm`,tone:`confirm`,said:e.phrase,note:[e.status],children:(0,A.jsx)(SH,{rows:n})})}function KH({name:e,source:t,data:n,seq:r}){return(0,A.jsx)(NH,{seq:r,kind:`event`,tone:`event`,said:e,note:[t],children:(0,A.jsx)(`pre`,{className:`lv-data`,children:JSON.stringify(n,null,2)})})}function qH({entries:e}){return(0,A.jsx)(NH,{seq:e[0]?.seq,kind:`quiet`,tone:`quiet`,said:e.length===1?`1 entry`:`${e.length} entries`,children:(0,A.jsx)(`ul`,{className:`lv-list`,children:e.map(e=>(0,A.jsxs)(`li`,{children:[e.seq,` `,e.type]},`${String(e.seq)}-${e.type}`))})})}function JH(e){return e===null?`the app`:e.kind===`tool`?e.tool:`${e.name} (seq ${String(e.seq)})`}function YH({run:e,seq:t}){let n=[{field:`arguments`,value:JSON.stringify(e.arguments,null,2),unit:null},...XH(e.output)?[{field:`output`,value:JSON.stringify(e.output,null,2),unit:null}]:[],...XH(e.error)?[{field:`error`,value:e.error,unit:null}]:[],...XH(e.duration_s)?[{field:`duration_s`,value:GC(e.duration_s),unit:null}]:[]];return(0,A.jsx)(NH,{seq:t,kind:`tool`,tone:`tool`,said:`${e.name}(${ZH(e)})`,note:[(0,A.jsx)(`span`,{className:e.status===`failed`?`lv-failed`:``,children:QH(e)})],children:(0,A.jsx)(SH,{rows:n})})}function XH(e){return e!=null}function ZH(e){return Object.entries(e.arguments).map(([e,t])=>`${e}=${$H(t)}`).join(`, `)}function QH(e){return e.status===`running`?`…`:e.error??e.summary??$H(e.output)}function $H(e){let t=typeof e==`string`?e:JSON.stringify(e);return t===void 0?``:t.slice(0,60)}var eU={transcription_delay:`stt`,end_of_turn_delay:`eot`,llm_node_ttft:`ttft`,tts_node_ttfb:`ttfb`,e2e_latency:`e2e`};function tU({turn:e,seq:t,metrics:n}){let r=JC(n,e.speech_id),i=HC(e).map(e=>`${eU[e.field]??e.field} ${e.value}`),a=[...e.role===`agent`&&e.interrupted?[`interrupted`]:[],...e.role===`user`&&e.language!==void 0&&e.language!==null?[e.language]:[]],o=e.role===`user`?[...i,e.speech_id,...a]:[...i,...a];return(0,A.jsx)(NH,{seq:t,kind:`turn`,tone:`turn`,who:e.role===`agent`?`agent`:`caller`,said:e.text,note:o,children:r.length===0?null:r.map((e,t)=>(0,A.jsxs)(`section`,{children:[(0,A.jsxs)(`h4`,{className:`lv-block-name`,children:[`metrics.`,e.kind]}),(0,A.jsx)(SH,{rows:e.readings})]},`${e.kind}-${String(t)}`))})}var nU=80;function rU({entries:e,state:t,after:n}){let r=t.live.agent,i=(0,D.useRef)(null),a=(0,D.useRef)(!0);return(0,D.useEffect)(()=>{let e=i.current;e!==null&&a.current&&(e.scrollTop=e.scrollHeight)},[e,t.live.user,r]),(0,A.jsxs)(`div`,{className:`lv-rows`,ref:i,onScroll:e=>{let t=e.currentTarget;a.current=t.scrollHeight-t.scrollTop-t.clientHeight<nU},children:[vw(e,t).map(e=>(0,A.jsx)(iU,{row:e,state:t},`${e.kind}-${String(e.seq)}`)),(0,A.jsx)(aU,{said:t.live.user,who:`caller`}),(0,A.jsx)(aU,{said:r,who:`agent`}),n]})}function iU({row:e,state:t}){switch(e.kind){case`turn`:return(0,A.jsx)(tU,{turn:e.turn,seq:e.seq,metrics:t.metrics});case`tool`:return(0,A.jsx)(YH,{run:e.run,seq:e.seq});case`state`:return(0,A.jsx)(UH,{changed:e.changed,cause:e.cause,seq:e.seq});case`confirm`:return(0,A.jsx)(GH,{confirm:e.confirm,seq:e.seq});case`event`:return(0,A.jsx)(KH,{name:e.name,source:e.source,data:e.data,seq:e.seq});case`supervisor`:return(0,A.jsx)(WH,{mark:e.mark,seq:e.seq});case`memory`:return(0,A.jsx)(BH,{ops:e.ops,seq:e.seq});case`sources`:return(0,A.jsx)(VH,{sources:e.sources,seq:e.seq});case`quiet`:return(0,A.jsx)(qH,{entries:e.entries})}}function aU({said:e,who:t}){if(e===null)return null;let n=e.split(/\s+/).filter(e=>e!==``);return(0,A.jsx)(`div`,{className:`lv-saying`,children:(0,A.jsx)(NH,{seq:void 0,kind:`turn`,tone:`turn`,who:t,said:(0,A.jsxs)(A.Fragment,{children:[n.map((e,t)=>(0,A.jsxs)(`span`,{className:t===n.length-1?`lv-word lv-word-now`:`lv-word`,children:[e,` `]},t)),(0,A.jsx)(`span`,{className:`lv-caret`,"aria-hidden":!0})]})})})}function oU({call:e,agent:t}){let n=iw(e),r=n.state,i=oH(r.agent),a=Eh(),[o,s]=(0,D.useState)(!1),c=r.status===`ended`,l=sH(uU(n.entries)),u=a===null||a.includes(`supervise`),d=vh({name:`live.call`,initial:360,min:280,max:640,side:`right`});return(0,D.useEffect)(()=>s(!1),[e]),(0,A.jsxs)(`div`,{className:`lv`,style:d.style,children:[d.handle,(0,A.jsxs)(`div`,{className:`lv-middle`,children:[(0,A.jsxs)(sU,{call:e,agent:t,state:r,connection:n.error??n.connection,failed:n.error!==null,children:[(0,A.jsx)(Wi,{to:`/sessions/${e}`,className:`lv-session`,children:`Open session`}),u&&(0,A.jsxs)(`button`,{type:`button`,className:o?`lv-listen lv-listen-open`:`lv-listen`,disabled:c&&!o,title:c?`the call is over`:void 0,onClick:()=>s(!o),"aria-expanded":o,children:[(0,A.jsx)(`span`,{className:c?`ui-dot ui-dot-small`:`ui-dot ui-dot-small ui-dot-green`}),o?`Close the desk`:`Listen in`]})]}),o&&(0,A.jsx)(vH,{call:e,live:!c}),(0,A.jsx)(rU,{entries:n.entries,state:r,after:l===null?void 0:(0,A.jsx)(dU,{call:e})})]}),(0,A.jsxs)(`aside`,{className:`lv-pane`,"aria-label":`what the call holds`,children:[(0,A.jsx)(AH,{fields:r.app_state,declared:i}),(0,A.jsx)(DH,{room:r.room,from:r.from,over:c}),(0,A.jsx)(EH,{prompt:r.prompt,cost:r.cost}),(0,A.jsx)(wH,{metrics:r.metrics,entries:n.entries})]})]})}function sU({call:e,agent:t,state:n,connection:r,failed:i,children:a}){let o=lU(n.status!==`ended`),s=n.status===`ended`,c=n.caller?.name??cU(n.direction===`outbound`?n.to:n.from);return(0,A.jsxs)(`div`,{className:`lv-head`,children:[(0,A.jsx)(`span`,{className:`lv-call`,children:e}),n.channel!==null&&(0,A.jsx)(`span`,{className:`lv-tag`,children:n.channel}),n.direction!==null&&(0,A.jsx)(`span`,{className:`lv-tag`,children:n.direction}),(0,A.jsx)(`span`,{className:s?`lv-status lv-status-over`:`lv-status`,children:s?(n.end_reason??`ended`).replace(/_/g,` `):n.status===`active`?`on a call · ${Jh(n.started_at,o)}`:n.status}),(0,A.jsxs)(`span`,{className:`lv-sub`,children:[c,` → `,n.agent||t||`—`,` · seq `,n.seq,n.agent_state!==null&&` · agent ${n.agent_state}`,n.user_state!==null&&` · caller ${n.user_state}`,` · `,(0,A.jsx)(`span`,{className:i?`lv-connection-bad`:void 0,children:r})]}),a]})}function cU(e){return e===null?`—`:e.startsWith(`+`)?og(e):e}function lU(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}function uU(e){return[...e].reverse().find(e=>e.type===`call.summary`)?.data}function dU({call:e}){let[t,n]=(0,D.useState)(!1),r=(0,D.useCallback)(()=>n(!0),[]);return t?null:(0,A.jsx)(`div`,{className:`lv-recording`,children:(0,A.jsx)(lH,{call:e,onNothing:r})})}var fU=Uv.loose(),pU=50,mU=250;function hU(e,t,n,r){let i=j(),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(s)return;let r=!1,a=window.setTimeout(()=>{(async()=>{let a=e===``?`/v1/sessions`:`/v1/agents/${encodeURIComponent(e)}/sessions`,s={limit:pU};t.query.trim()!==``&&(s.q=t.query.trim()),t.agent!==``&&(s.agent=t.agent),t.channel!==``&&(s.channel=t.channel);try{let e=[],t=0,l=null;for(let o=0;o<n&&!(o>0&&l===null);o+=1){let n=await k(i,a,l===null?s:{...s,before:l});if(r)return;if(typeof n.total!=`number`){c(!0);return}let o=Array.isArray(n.calls)?n.calls:[];e.push(...o.map(e=>fU.parse(e))),t=n.total,l=typeof n.next==`string`?n.next:null}o({rows:e,total:t,next:l})}catch{r||c(!0)}})()},mU);return()=>{r=!0,window.clearTimeout(a)}},[i,e,t.query,t.agent,t.channel,n,s,r]),s?null:a}function gU(e,t){let n=t.trim().toLowerCase();if(n===``)return!0;let r=n.replace(/[^\d]/g,``);if([e.call,e.agent,e.from,e.to,e.caller?.name,e.outcome,e.channel].filter(Boolean).join(` `).toLowerCase().includes(n))return!0;if(r.length>=3){let t=`${e.from??``} ${e.to??``} ${e.call}`.replace(/[^\d ]/g,``);return t.replace(/ /g,``).includes(r)||t.includes(r)}return!1}var _U=80;function vU(){let{lines:e,agents:t,floorError:n}=Zy(),r=Sr().call,[i,a]=Xi(),o=i.get(`agent`),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(``),d=vh({name:`live.calls`,initial:300,min:220,max:520,side:`left`}),f=bU(),p=e.filter(e=>(o===null||e.agent===o)&&gU(e,l)),m=p.filter(VS),h=p.filter(e=>!VS(e)).slice(0,_U),g=[...m,...h],_=r??m[0]?.call??g[0]?.call,v=o===null?``:`?agent=${encodeURIComponent(o)}`;return(0,A.jsxs)(`div`,{className:`fl`,style:d.style,children:[d.handle,(0,A.jsxs)(`nav`,{className:`fl-side`,"aria-label":`the floor's calls`,children:[(0,A.jsxs)(`div`,{className:`fl-side-head`,children:[(0,A.jsxs)(`div`,{className:`fl-standing`,children:[(0,A.jsx)(eh,{tone:m.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`fl-count`,children:m.length===1?`1 call up`:`${m.length} calls up`}),(0,A.jsxs)(`span`,{className:`fl-asked`,title:`re-asked every ${zS/1e3} s`,children:[p.length,` listed`]})]}),(0,A.jsx)(W,{size:`sm`,className:`fl-search`,placeholder:`Search a number, agent or outcome`,"aria-label":`Search the floor's calls`,value:l,onChange:e=>u(e.target.value)}),o!==null&&(0,A.jsxs)(`div`,{className:`fl-only`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:o}),(0,A.jsx)(`button`,{type:`button`,className:`fl-only-clear`,onClick:()=>{i.delete(`agent`),a(i)},children:`every agent`})]}),(0,A.jsx)(`button`,{type:`button`,className:`fl-simulate`,onClick:()=>c(!s),"aria-expanded":s,children:`Simulate a caller`}),s&&(0,A.jsx)(`div`,{className:`fl-sim`,children:(0,A.jsx)(lC,{agents:o===null?t.map(e=>e.slug):[o],onClose:()=>c(!1)})})]}),(0,A.jsxs)(`div`,{className:`fl-list`,children:[n!==null&&(0,A.jsx)(`p`,{className:`fl-empty fl-refused`,children:n}),g.length===0&&n===null&&(0,A.jsx)(`p`,{className:`fl-empty`,children:l===``?`No calls yet. Leave this open — a call that reaches any agent shows up here as it rings.`:`No call here matches.`}),m.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`On a call now`}),m.map(e=>(0,A.jsx)(yU,{line:e,on:e.call===_,now:f,to:`/live/${e.call}${v}`},e.call)),h.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`Recent`}),h.map(e=>(0,A.jsx)(yU,{line:e,on:e.call===_,now:f,to:`/live/${e.call}${v}`},e.call)),h.length>0&&(0,A.jsx)(Wi,{to:`/sessions`,className:`fl-all`,children:`Every session →`})]})]}),_===void 0?(0,A.jsx)(`div`,{className:`fl-nothing`,children:`Nothing to watch yet: the first call the org takes appears on the left, and opens here.`}):(0,A.jsx)(oU,{call:_,agent:g.find(e=>e.call===_)?.agent},_)]})}function yU({line:e,on:t,now:n,to:r}){let i=VS(e);return(0,A.jsxs)(Wi,{to:r,className:t?`fl-row fl-row-on`:`fl-row`,title:e.call,children:[(0,A.jsx)(`span`,{className:i?`fl-dot fl-dot-live`:`fl-dot`}),(0,A.jsxs)(`span`,{className:`fl-row-words`,children:[(0,A.jsxs)(`span`,{className:`fl-row-top`,children:[(0,A.jsx)(`span`,{className:`fl-id`,children:sg(e)}),(0,A.jsx)(`span`,{className:i?`fl-meta fl-meta-live`:`fl-meta`,children:i?e.status===`active`?Jh(e.started_at,n):e.status:eg(e.started_at,n)})]}),(0,A.jsxs)(`span`,{className:`fl-row-sub`,children:[(0,A.jsxs)(`span`,{className:`ui-clip`,children:[e.agent,e.channel!==null&&` · ${e.channel}`,e.direction===`outbound`&&` · outbound`,!i&&` · ${qh(e)}`]}),e.score!=null&&(0,A.jsx)(`span`,{className:`fl-score`,children:(0,A.jsxs)(Qm,{tone:e.score.passed?`green`:`red`,children:[e.score.held,`/`,e.score.judged]})}),e.score==null&&(e.flags??[]).includes(`escalated`)&&(0,A.jsx)(`span`,{className:`fl-score`,children:(0,A.jsx)(Qm,{tone:`amber`,children:`escalated`})})]}),!i&&e.outcome!==null&&(0,A.jsx)(`span`,{className:`fl-outcome`,children:e.outcome})]})]})}function bU(){let[e,t]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{let e=window.setInterval(()=>t(Date.now()/1e3),1e3);return()=>window.clearInterval(e)},[]),e}var xU=/^call[_-][\w+-]{6,}$/,SU=`minmax(0,1.3fr) 128px 84px 78px 74px minmax(0,1.5fr)`,CU=`minmax(0,1.3fr) 84px 78px 74px minmax(0,1.6fr)`,wU=[`web`,`phone`,`whatsapp`];function TU({lines:e,error:t,agent:n,agents:r}){let i=vr(),[a,o]=(0,D.useState)({query:``,agent:``,channel:``}),[s,c]=(0,D.useState)(1),l=hU(n,a,s,`${e.length}:${e[0]?.call??``}:${e.filter(VS).length}`),u=n===``,d=l===null?e.filter(e=>gU(e,a.query)&&(a.agent===``||e.agent===a.agent)&&(a.channel===``||e.channel===a.channel)):l.rows,f=[...d.filter(VS),...d.filter(e=>!VS(e))],p=e=>u?`/sessions/${e}`:`/a/${n}/sessions/${e}`,m=e=>{let t=a.query.trim();e.key===`Enter`&&xU.test(t)&&i(p(t))},h=u?SU:CU,g=a.query!==``||a.agent!==``||a.channel!==``;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`sessions-filters`,children:[(0,A.jsx)(W,{size:`sm`,className:`sessions-search`,placeholder:`Search a session id, number or outcome`,"aria-label":`Search a session id, number or outcome`,value:a.query,onChange:e=>o({...a,query:e.target.value}),onKeyDown:m}),u&&(0,A.jsxs)(Hm,{size:`sm`,className:`sessions-select`,value:a.agent,onChange:e=>o({...a,agent:e.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Every agent`}),r.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}),u&&(0,A.jsxs)(Hm,{size:`sm`,className:`sessions-select`,value:a.channel,onChange:e=>o({...a,channel:e.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Every channel`}),wU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]})]}),(0,A.jsx)(Nm,{children:t}),(0,A.jsxs)(V,{children:[f.length===0?(0,A.jsx)(Mm,{children:g?xU.test(a.query.trim())?(0,A.jsxs)(A.Fragment,{children:[`Not on this page — press Enter to open `,a.query.trim(),` by its id.`]}):(0,A.jsx)(A.Fragment,{children:`No session here matches. The search reads the sessions this page has listed.`}):(0,A.jsxs)(A.Fragment,{children:[`No session recorded yet. The log is written during the call, so one appears here the moment it starts — from the browser, from`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall chat`}),`, or from the telephone.`]})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:h,labels:u?[`Session`,`Agent`,`Channel`,`Started`,`Duration`,`Outcome`]:[`Session`,`Channel`,`Started`,`Duration`,`Outcome`]}),f.map(e=>(0,A.jsxs)(fh,{columns:h,to:p(e.call),children:[(0,A.jsxs)(`div`,{className:`sessions-id`,children:[(0,A.jsxs)(`div`,{className:`sessions-call`,children:[VS(e)&&(0,A.jsx)(eh,{tone:`green`,small:!0}),(0,A.jsx)(`span`,{className:`ui-clip`,children:e.call})]}),(0,A.jsx)(`div`,{className:`sessions-from ui-clip`,children:sg(e)})]}),u&&(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.channel??`—`}),(0,A.jsx)(`span`,{className:`ui-cell`,children:Zh(e.started_at)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:VS(e)?(0,A.jsx)(`span`,{className:`sessions-live`,children:`live`}):qh(e)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.outcome??EU(e)})]},e.call))]}),l!==null&&l.total>l.rows.length&&(0,A.jsxs)(jm,{children:[(0,A.jsxs)(`span`,{children:[l.rows.length,` of `,l.total]}),(0,A.jsx)(`span`,{className:`sessions-more`,children:(0,A.jsx)(U,{size:`sm`,onClick:()=>c(s+1),children:`Load more`})})]})]})]})}function EU(e){return VS(e)?`on a call`:e.end_reason===null?`—`:e.end_reason.replace(/_/g,` `)}function DU(){let{lines:e,floorError:t,agents:n}=Zy(),r=[...new Set([...n.map(e=>e.slug),...e.map(e=>e.agent)])].sort();return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Sessions`,lede:`Every conversation the org has had, newest first, whichever agent handled it.`}),(0,A.jsx)(TU,{lines:e,error:t,agent:``,agents:r})]})}var OU=[`qa`,`supervisor`,`manager`,`admin`,`developer`],kU=z({id:P(),email:P(),name:P(),role:mp(OU),agents:R(P()),status:mp([`invited`,`active`,`disabled`]),scopes:R(P()),production:L()}),AU=z({member:kU,token:P(),expires_at:P()});async function jU(e){return z({members:R(kU)}).parse(await k(e,`/v1/members`)).members}async function MU(e,t){return AU.parse(await sa(e,`/v1/members`,t))}async function NU(e,t){return AU.parse(await sa(e,`/v1/members/${encodeURIComponent(t)}/reset`,{}))}async function PU(e,t){await ca(e,`/v1/members/${encodeURIComponent(t)}`)}async function FU(e,t,n){let r=await fetch(new URL(`${e.base.replace(/\/$/,``)}/v1/members/${encodeURIComponent(t)}`,window.location.origin),{method:`PATCH`,headers:{...ra(e),"content-type":`application/json`},body:JSON.stringify(n)});return kU.parse(await fa(r))}var IU=z({configured:L(),issuer:P().nullish(),client_id:P().nullish(),domains:R(P()),role:P().nullish(),required:L(),redirect_uri:P()});async function LU(e){try{return IU.parse(await k(e,`/v1/org/sso`))}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}async function RU(e,t){return IU.parse(await oa(e,`/v1/org/sso`,t))}async function zU(e){await ca(e,`/v1/org/sso`)}var BU=z({on:L(),ceiling_eur:F().nullable()});function VU(){let e=j(),t=Eh(),[n,r]=(0,D.useState)(null),i=Sm(vm,`numbers`)&&t!==null&&$y(t,`numbers`),a=Sm(vm,`team`)&&t!==null&&$y(t,`team`),[o,s]=(0,D.useState)(0);return(0,D.useEffect)(()=>{if(t===null)return;let n=!1;return(async()=>{let o=[];if(i){let[t,n]=await Promise.all([gb(e).catch(()=>null),hb(e).catch(()=>[])]);o.push({done:t!==null,name:`Connect a phone carrier`,action:`Connect`,to:`/numbers`});let r=n.filter(e=>e.route.number!==null).length;o.push({done:r>0,name:r>1?`Point ${r} numbers at an agent`:`Point a number at an agent`,action:`Add`,to:`/numbers`})}let c=await k(e,`/v1/org/judging`).then(e=>BU.parse(e),()=>null);if(c!==null&&t!==null&&t.includes(`usage`)&&o.push({done:c.on,name:`Add a judge so calls get scored`,action:`Turn on`,run:async()=>{await oa(e,`/v1/org/judging`,{on:!0}),s(e=>e+1)}}),a){let t=await jU(e).catch(()=>[]);o.push({done:t.filter(e=>e.status!==`disabled`).length>1,name:`Invite your team`,action:`Invite`,to:`/team`})}n||r(o)})(),()=>{n=!0}},[e,i,a,t,o]),n===null||n.length===0||n.every(e=>e.done)?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Finish setting up`})}),(0,A.jsx)(`div`,{className:`home-steps`,children:n.map(e=>e.done?(0,A.jsxs)(`div`,{className:`home-step`,children:[(0,A.jsx)(`span`,{className:`home-step-done`,children:`✓`}),(0,A.jsx)(`span`,{className:`home-step-name home-step-name-done`,children:e.name})]},e.name):e.run===void 0?(0,A.jsxs)(Wi,{to:e.to??`/`,className:`home-step home-step-open`,children:[(0,A.jsx)(`span`,{className:`home-step-todo`}),(0,A.jsx)(`span`,{className:`home-step-name`,children:e.name}),(0,A.jsx)(`span`,{className:`home-step-action`,children:e.action})]},e.name):(0,A.jsxs)(`button`,{type:`button`,className:`home-step home-step-open home-step-button`,onClick:()=>void e.run?.(),children:[(0,A.jsx)(`span`,{className:`home-step-todo`}),(0,A.jsx)(`span`,{className:`home-step-name`,children:e.name}),(0,A.jsx)(`span`,{className:`home-step-action`,children:e.action})]},e.name))})]})}var HU=new Set([`transferred`,`supervisor_ended`]),UU={escalated:{pill:`red`,tint:`red`},"low score":{pill:`amber`,tint:`amber`},"promise made":{pill:`indigo`,tint:`indigo`}},WU={escalated:`escalated`,low_score:`low score`,promise:`promise made`};function GU(){let e=new Date().getHours();return e<12?`Good morning`:e<19?`Good afternoon`:`Good evening`}function KU(e){let t=[];for(let n of e){let{score:e}=n,r=n.line;if(r.flags!==void 0&&r.flags!==null){let e=r.flags.map(e=>WU[e]).find(e=>e!==void 0);e!==void 0&&t.push({row:n,flag:e,reason:r.score?.reason??r.outcome??``});continue}if(r.end_reason!==null&&HU.has(r.end_reason))t.push({row:n,flag:`escalated`,reason:r.outcome??(r.end_reason===`transferred`?`Handed to a person`:`A supervisor ended it`)});else if(e!==null&&e.passed===!1){let i=e.judges.find(e=>e.verdict===`broken`);t.push({row:n,flag:`low score`,reason:i?.reason??r.outcome??`A judge did not hold`})}}return t}function qU(e){let t=e.filter(e=>!e.live);return t.length===0?null:t.filter(e=>e.end_reason===null||!HU.has(e.end_reason)).length/t.length}function JU(){let e=wh(),{lines:t,live:n,insights:r}=Zy(),i=ng(),a=rg(t,i.today),o=rg(t,i.yesterday),s=KU(dV(a)),c=(e?.name??``).split(` `)[0]??``,l=ug(i.yesterday),u=r?.conversations.today??a.length,d=ig(u,r?.conversations.yesterday??o.length),f=r===null?qU(a):r.resolved_rate,p=r===null?qU(o):l?.resolved_rate??null,m=f===null||p===null?null:Math.round((f-p)*100),h=r?.spend_eur??a.reduce((e,t)=>e+(t.cost?.eur??0),0),g=r?.budget.limit_eur??null,_=n.length===0?`Nobody on a call right now`:n.length===1?`One call on the floor`:`${n.length} calls on the floor`,v=s.length===0?`nothing needs a look`:s.length===1?`one conversation needs a look`:`${s.length} conversations need a look`;return(0,A.jsxs)(sh,{children:[(0,A.jsx)(ch,{title:c===``?GU():`${GU()}, ${c}`,lede:`${_}, ${v}, everything else handled.`}),(0,A.jsxs)(lh,{min:190,children:[(0,A.jsx)(uh,{size:`big`,label:`Conversations`,value:a.length,delta:d?.text,tone:d?.tone}),(0,A.jsx)(uh,{size:`big`,label:`Resolved without a human`,value:f===null?`—`:ag(f),delta:m===null?void 0:m===0?`steady`:`${m>0?`+`:`−`}${Math.abs(m)} pts`,tone:m===null||m===0?`flat`:m>0?`up`:`down`}),r!==null&&(0,A.jsx)(XU,{insights:r,before:l}),(0,A.jsx)(uh,{size:`big`,label:`Spend today`,value:Xh(h),delta:g===null?`today`:`of €${g}`,tone:`flat`})]}),(0,A.jsxs)(`div`,{className:`home-split`,children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Needs a look`,meta:`${s.length} of ${u} today`,action:(0,A.jsx)(Am,{to:`/sessions`,children:`All sessions`})}),s.length===0&&(0,A.jsx)(Mm,{children:`Nothing today needs a look: no call went to a person, and no judge said no.`}),s.map(e=>(0,A.jsx)(Pm,{to:`/sessions/${e.row.line.call}`,lead:(0,A.jsx)(ah,{name:sg(e.row.line),tint:UU[e.flag].tint}),name:sg(e.row.line),tag:(0,A.jsx)(Qm,{tone:UU[e.flag].pill,small:!0,children:e.flag}),sub:e.reason,end:(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ui-row-end-1`,children:[e.row.line.channel??`—`,` · `,qh(e.row.line)]}),(0,A.jsx)(`div`,{className:`ui-row-end-2`,children:eg(e.row.line.started_at)})]})},e.row.line.call)),(0,A.jsxs)(jm,{children:[(0,A.jsxs)(`span`,{children:[Math.max(0,u-s.length),` more handled cleanly`]}),(0,A.jsx)(Am,{to:`/sessions`,children:`See all sessions`})]})]}),(0,A.jsxs)(`div`,{className:`home-side`,children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:(0,A.jsxs)(`span`,{className:`home-floor-title`,children:[(0,A.jsx)(eh,{tone:n.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`ui-card-title`,children:`On the floor now`})]})}),(0,A.jsxs)(`div`,{className:`home-floor`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`home-quiet`,children:`Nobody is on a call. A call that rings appears here the moment it does.`}),n.slice(0,4).map(e=>(0,A.jsxs)(`div`,{className:`home-live`,children:[(0,A.jsx)(ah,{name:sg(e),tint:`green`}),(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`home-live-name`,children:sg(e)}),(0,A.jsxs)(`div`,{className:`home-live-sub`,children:[e.agent,` · `,e.channel??`—`,` · `,Jh(e.started_at)]})]}),(0,A.jsx)(zm,{to:`/live/${e.call}`,size:`xs`,children:`Listen`})]},e.call))]})]}),(0,A.jsx)(ZU,{lines:a.length>0?a:t,counted:r!==null&&u>0?r.channels:null}),(0,A.jsx)(VU,{})]})]})]})}var YU=[{channel:`phone`,name:`Phone`,color:`var(--accent)`},{channel:`web`,name:`Web`,color:`var(--accent-2)`},{channel:`whatsapp`,name:`WhatsApp`,color:`var(--accent-3)`}];function XU({insights:e,before:t}){let n=e.median_e2e_s,r=t?.median_e2e_s??null,i=`today`,a=`flat`;if(n!==null&&r!==null){let e=Math.round((n-r)*10)/10;Math.abs(e)<.1?i=`steady`:(i=`${e>0?`+`:`−`}${Math.abs(e).toFixed(1)}s`,a=e>0?`down`:`up`)}return(0,A.jsx)(uh,{size:`big`,label:`Median answer`,value:n===null?`—`:`${n.toFixed(1)}s`,delta:i,tone:a})}function ZU({lines:e,counted:t}){let n=t===null?e.length:t.phone+t.web+t.whatsapp,r=n=>t===null?e.filter(e=>e.channel===n).length:t[n]??0;return(0,A.jsxs)(V,{children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Where calls arrive`})}),(0,A.jsx)(`div`,{className:`home-channels`,children:YU.map(({channel:e,name:t,color:i})=>{let a=n===0?0:r(e)/n;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`home-channel-line`,children:[(0,A.jsx)(`span`,{className:`home-channel-name`,children:t}),(0,A.jsx)(`span`,{className:`home-channel-share`,children:ag(a)})]}),(0,A.jsx)(oh,{share:a,color:i})]},e)})})]})}var QU=`minmax(0,1.2fr) 96px minmax(0,1fr) 150px 92px`;function $U(){let e=j(),t=wh(),n=Eh(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(`production`),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),_=n!==null&&n.includes(`app`),v=t?.production===!0,y=v?s:`sandbox`,b=async()=>i(await ib(e));(0,D.useEffect)(()=>{let t=!1;return ib(e).then(e=>{t||i(e)},e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let x=async t=>{if(t.preventDefault(),a.trim()===``){g(`Name what the token is for — the server or the job it will run on.`);return}u(!0),g(null);try{f(await ab(e,{label:a.trim(),env:y})),m(!1),o(``),await b()}catch(e){g(e instanceof na?e.message:String(e))}finally{u(!1)}},S=async t=>{g(null);try{await ob(e,t),await b()}catch(e){g(e instanceof na?e.message:String(e))}},C=async e=>{try{await navigator.clipboard.writeText(e),m(!0)}catch{m(!1)}};return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Tokens`,ledeWidth:640,lede:"Your own keys — one per device, what `pinecall link` writes into a project — and the tokens this org's servers run on. A server's token is the org's: it opens one world, and it stays when the person who made it leaves."}),_&&(0,A.jsx)(V,{pad:!0,children:(0,A.jsxs)(`form`,{className:`keys-form`,onSubmit:e=>void x(e),children:[(0,A.jsxs)(`div`,{className:`keys-label-field`,children:[(0,A.jsx)(`label`,{className:`ui-label`,htmlFor:`token-label`,children:`New server token`}),(0,A.jsx)(W,{id:`token-label`,value:a,placeholder:`maravilla web`,onChange:e=>o(e.target.value)})]}),(0,A.jsxs)(Hm,{className:`keys-env-select`,value:y,onChange:e=>c(e.target.value),"aria-label":`which world it opens`,children:[(0,A.jsx)(`option`,{value:`production`,disabled:!v,children:`production`}),(0,A.jsx)(`option`,{value:`sandbox`,children:`sandbox`})]}),(0,A.jsx)(U,{type:`submit`,kind:`primary`,size:`form`,disabled:l,children:l?`Making…`:`Create`}),(0,A.jsx)(`div`,{className:`keys-form-note`,children:v?`It holds the agent in that world and pushes its knowledge base in a release — nothing else.`:`Production's is made by somebody your org lets act in production.`})]})}),d!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`${d.label??`A new token`} · ${d.env}`,meta:`shown once`,action:(0,A.jsxs)(`span`,{className:`keys-minted-actions`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>void C(`PINECALL_KEY=${d.key}`),children:p?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>f(null),children:`Done`})]})}),(0,A.jsxs)(`pre`,{className:`ui-code`,children:[`PINECALL_KEY=`,d.key]}),(0,A.jsx)(`div`,{className:`keys-minted-warn`,children:`Copy it now and put it in your server's secrets: the gateway keeps its fingerprint, and this token is never shown again.`})]}),(0,A.jsx)(Nm,{children:h}),(0,A.jsx)(V,{children:r!==null&&r.length===0?(0,A.jsx)(Mm,{children:"No token yet. A server's is made above; yours is made by `pinecall link`."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:QU,labels:[`Name`,`World`,`Whose`,`Last used`,`Status>`]}),(r??[]).map(e=>(0,A.jsx)(eW,{row:e,stop:S},e.fingerprint))]})})]})}function eW({row:e,stop:t}){let[n,r]=(0,D.useState)(!1),i=e.revoked_at!==null,a=e.kind===`person`?`${e.name??`a person`} · their own`:`the org's${e.created_by===null?``:` · made by ${e.created_by}`}`;return(0,A.jsxs)(`div`,{className:`ui-table-row keys-row`,style:{gridTemplateColumns:QU},onMouseLeave:()=>r(!1),children:[(0,A.jsx)(`span`,{className:i?`keys-name keys-name-gone`:`keys-name`,title:e.fingerprint,children:e.label??e.fingerprint.slice(0,12)}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:e.env??`—`}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:a}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:e.last_used_at===null?`never`:Qh(Date.parse(e.last_used_at)/1e3)}),(0,A.jsxs)(`span`,{className:`ui-cell-end`,children:[!i&&(0,A.jsx)(`span`,{className:n?`keys-revoke keys-revoke-sure`:`keys-revoke`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>n?void t(e.fingerprint):r(!0),children:n?`Revoke it`:`Revoke`})}),i?(0,A.jsx)(Qm,{tone:`gray`,children:`revoked`}):(0,A.jsx)(Qm,{tone:`green`,children:`active`})]})]})}var tW=`/v1/lexicon`;async function nW(e){return xy.parse(await k(e,tW))}async function rW(e,t,n,r,i){return xy.parse(await oa(e,tW,{lexicon:t,if_version:n,note:r,team:i}))}function iW(e){return e instanceof Error?e.message:String(e)}function aW(e){return{said:[...e?.lexicon.said??[]],heard:[...e?.lexicon.heard??[]]}}function oW(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)({said:[],heard:[]}),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(``),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(null),[y,b]=(0,D.useState)(null),x=fm===`hosted`;(0,D.useEffect)(()=>{let t=!1;return nW(e).then(e=>{t||(n(e),i(aW(x?e.production:e.yours??e.team)))},e=>!t&&v(iW(e))),()=>{t=!0}},[e]);let S=t===null?null:x?t.production:a?t.team:t.yours,C=async o=>{if(o.preventDefault(),t===null)return;g(`Saving…`),v(null);let s={said:r.said,heard:r.heard};try{let t=await rW(e,s,S?.version??null,p.trim()===``?null:p.trim(),a);n(t),i(aW(x?t.production:a?t.team:t.yours??t.team)),m(``),b(`Kept as the next version. Every agent of the org says it from its next call in this corner.`)}catch(e){v(iW(e))}finally{g(null)}};return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Lexicon`,ledeWidth:640,lede:`The org's words, laid over every agent's own: how the voice says a brand, a surname, an acronym, and which words the ears must know. Whole and versioned; a word said wrong is fixed by whoever hears it.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Where every corner is`,meta:t?.world}),t===null?(0,A.jsx)(Mm,{children:_??`Asking the gateway…`}):(0,A.jsx)(`div`,{className:`lex-corners`,children:[`yours`,`team`,`production`].map(e=>(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:e}),` `,t[e]===null?`nothing set`:`v${t[e].version} · ${t[e].author} · ${Qh(t[e].set_at)}`]},e))})]}),t!==null&&(0,A.jsxs)(`form`,{className:`ui-card`,onSubmit:e=>void C(e),children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:x?`What production says`:`The words`}),!x&&(0,A.jsx)(Ym,{checked:a,onChange:e=>{o(e),i(aW(e?t.team:t.yours??t.team))},children:`the team's corner`})]}),(0,A.jsxs)(`div`,{className:`lex-body`,children:[(0,A.jsxs)(`div`,{className:`lex-said`,children:[(0,A.jsx)(`div`,{className:`ui-label`,children:`Said`}),r.said.length===0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:`No word is said any other way than written.`}),r.said.map(e=>(0,A.jsxs)(`div`,{className:`lex-pair`,children:[(0,A.jsx)(`span`,{className:`lex-word`,children:e.word}),(0,A.jsx)(`span`,{className:`lex-arrow`,children:`→`}),(0,A.jsxs)(`span`,{className:`lex-spoken`,children:[`“`,e.spoken,`”`]}),(0,A.jsx)(Bm,{danger:!0,onClick:()=>i({...r,said:r.said.filter(t=>t.word!==e.word)}),children:`Remove`})]},e.word)),(0,A.jsxs)(`div`,{className:`lex-add`,children:[(0,A.jsx)(W,{size:`sm`,value:s,placeholder:`the word, as written`,onChange:e=>c(e.target.value)}),(0,A.jsx)(W,{size:`sm`,value:l,placeholder:`how it is said`,onChange:e=>u(e.target.value)}),(0,A.jsx)(U,{size:`sm`,onClick:()=>{s.trim()!==``&&l.trim()!==``&&(i({...r,said:[...r.said.filter(e=>e.word!==s.trim()),{word:s.trim(),spoken:l.trim()}]}),c(``),u(``))},children:`Add`})]})]}),(0,A.jsxs)(`div`,{className:`lex-heard`,children:[(0,A.jsx)(`div`,{className:`ui-label`,children:`Heard`}),r.heard.length===0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:`The ears know only the names the state carries.`}),(0,A.jsx)(`div`,{className:`lex-chips`,children:r.heard.map(e=>(0,A.jsxs)(`span`,{className:`ui-pill-muted lex-chip`,children:[e,(0,A.jsx)(Bm,{onClick:()=>i({...r,heard:r.heard.filter(t=>t!==e)}),children:`×`})]},e))}),(0,A.jsxs)(`div`,{className:`lex-add`,children:[(0,A.jsx)(W,{size:`sm`,value:d,placeholder:`words the ears must know, comma-separated`,onChange:e=>f(e.target.value)}),(0,A.jsx)(U,{size:`sm`,onClick:()=>{let e=d.split(/[,\n]/).map(e=>e.trim()).filter(e=>e!==``&&!r.heard.includes(e));e.length>0&&i({...r,heard:[...r.heard,...e]}),f(``)},children:`Add`})]})]})]}),(0,A.jsxs)(`div`,{className:`pipe-save`,children:[(0,A.jsx)(W,{value:p,placeholder:`why, for the history`,onChange:e=>m(e.target.value)}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:h!==null,children:h??`Save as the next version`})]})]}),y!==null&&(0,A.jsx)(`div`,{className:`ui-empty`,children:y}),(0,A.jsx)(Nm,{children:_})]})}var sW=[`all`,...Fh],cW=`130px minmax(0,1.6fr) 110px 92px`,lW={[Ah]:0,[Mh]:1,[Nh]:2,[jh]:3};function uW(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(`all`),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(null),h=async()=>i(await jb(e));(0,D.useEffect)(()=>{let t=!1,r=e=>{t||m(e instanceof Error?e.message:String(e))};return Lh(e).then(e=>{t||n(e)},r),jb(e).then(e=>{t||i(e)},r),()=>{t=!0}},[e]);let g=async t=>{t.preventDefault(),f(!0),m(null);try{await Mb(e,a.trim(),s),c(``),o(``),await h()}catch(e){m(e instanceof na?e.message:String(e))}finally{f(!1)}},_=async t=>{m(null);try{await Nb(e,t),await h()}catch(e){m(e instanceof na?e.message:String(e))}},v=t?.providers??[],y=new Set(r??[]),b=(l===`all`?v:Rh(v,l)).slice().sort((e,t)=>Number(y.has(t.name))-Number(y.has(e.name))||lW[e.standing]-lW[t.standing]||e.name.localeCompare(t.name));return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Providers`,ledeWidth:660,lede:`Every vendor the runtime can reach, and what each one still wants on this box. Nothing reads a key back — not this page, not the CLI, not the log.`}),(0,A.jsxs)(V,{pad:!0,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void g(e),children:[(0,A.jsx)(Wm,{label:`Bring one`,minWidth:180,children:(0,A.jsxs)(Hm,{value:a,onChange:e=>o(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Choose a vendor…`}),v.filter(e=>e.env!==null).map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,` · `,e.does.join(` `)]},e.name))]})}),(0,A.jsx)(Wm,{label:`The key, sent once`,grow:!0,minWidth:220,children:(0,A.jsx)(W,{type:`password`,value:s,placeholder:`sk-…`,autoComplete:`off`,onChange:e=>c(e.target.value)})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:d||a.trim()===``||s===``,children:d?`Sending…`:`Bring it`})]}),(0,A.jsx)(`div`,{className:`prov-hint`,children:`A key brought here runs every call of this org from the next one; every vendor nobody brought runs on the box's own key.`})]}),(0,A.jsx)(Nm,{children:p}),(0,A.jsx)(Km,{options:sW.map(e=>({value:e,label:e===`all`?`All ${v.length}`:`${e.toUpperCase()} ${Rh(v,e).length}`})),value:l,onChange:u}),(0,A.jsx)(V,{children:b.map(e=>(0,A.jsxs)(`div`,{className:`prov-row`,style:{gridTemplateColumns:cW},title:e.aliases.length>0?`also ${e.aliases.join(` · `)}`:void 0,children:[(0,A.jsx)(`span`,{className:`prov-name`,children:e.name}),(0,A.jsxs)(`span`,{className:`prov-note`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:zh(e)}),y.has(e.name)&&(0,A.jsx)(Bm,{danger:!0,onClick:()=>void _(e.name),children:`Give back`})]}),(0,A.jsx)(`span`,{className:`prov-kinds`,children:e.does.join(` `)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(dW,{provider:e,brought:y.has(e.name)})})]},e.name))})]})}function dW({provider:e,brought:t}){return t?(0,A.jsx)(Qm,{tone:`green`,children:`your key`}):e.standing===`ready`?(0,A.jsx)(Qm,{tone:`green`,children:`ready`}):(0,A.jsx)(Qm,{tone:`gray`,children:e.standing})}function fW(e){return`/v1/agents/${encodeURIComponent(e)}/settings`}async function pW(e,t){return _y.parse(await k(e,fW(t)))}async function mW(e,t,n){return _y.parse(await oa(e,fW(t),n))}async function hW(e,t,n){return vy.parse(await k(e,`${fW(t)}/history`,{team:String(n)}))}async function gW(e,t,n,r){return _y.parse(await sa(e,`${fW(t)}/rollback`,{version:n,team:r}))}var _W=[`voice`,`tts`,`tts_model`,`stt`,`llm`,`greeting`,`hangup`,`turn`,`memory`,`knowledge`,`bases`],vW={voice:`voice`,tts:`speaks with`,tts_model:`tts model`,stt:`hears with`,llm:`decides with`,greeting:`greeting`,hangup:`hangup`,turn:`turn`,memory:`memory`,knowledge:`knowledge`,bases:`bases`};function yW(e,t){if(t===`greeting`){let t=e.greeting??void 0;if(t===void 0)return;let n=t.say??void 0;return n===void 0?`reply: ${t.reply??``}`:`"${n}"`}if(t===`hangup`){let t=e.hangup??void 0;return t===void 0?void 0:t.when?`when ${t.when}`:`may hang up`}if(t===`turn`){let t=e.turn??void 0;if(t===void 0)return;let n=[];return typeof t.endpointing_ms==`number`&&n.push(`endpointing ${t.endpointing_ms} ms`),typeof t.min_interruption_words==`number`&&n.push(`interrupt at ${t.min_interruption_words} words`),n.join(` · `)}if(t===`memory`){let t=e.memory??void 0;return t===void 0?void 0:`remember ${t.remember?.length??0} · forget ${t.forget?.length??0}`}if(t===`knowledge`){let t=e.knowledge??void 0;return t===void 0?void 0:`${t.length.toLocaleString(`en-US`)} chars`}if(t===`bases`){let t=e.bases??void 0;return t===void 0||t.length===0?void 0:t.map(e=>`${e.base}${typeof e.k==`number`?` (k ${e.k})`:``}`).join(` · `)}let n=e[t];return typeof n==`string`?n:void 0}function bW(e,t){let n=[];for(let r of _W){let i=yW(e,r),a=yW(t,r);i!==a&&n.push(`${vW[r]} ${i??`—`} → ${a??`—`}`)}return n}function xW(e,t){return t?e.team:e.yours}function SW(e){return e instanceof Error?e.message:String(e)}function CW(e){return(fm===`hosted`?e.production:e.yours??e.team)?.config.bases??[]}function wW({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return pW(t,e).then(e=>{n||r(CW(e))},e=>{n||a(SW(e))}),()=>{n=!0}},[t,e]),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Attached bases`,meta:`what this agent reads on every call — set in Settings, per corner and versioned`}),i===null?n===null?(0,A.jsx)(Mm,{children:`Asking the gateway…`}):n.length===0?(0,A.jsxs)(Mm,{children:[`No base attached: this agent searches nothing. Attach one in `,(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),", or `pinecall docs attach <base>`."]}):(0,A.jsxs)(`div`,{className:`kb-attached`,children:[n.map(e=>(0,A.jsxs)(`div`,{className:`kb-attached-row`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.base}),(0,A.jsxs)(`span`,{className:`ui-cell-faint`,children:[e.mode??`retrieved`,` · k `,e.k??8,e.min_score===void 0||e.min_score===null?``:` · min score ${e.min_score}`]})]},e.base)),(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[`Change them in `,(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),`.`]})]}):(0,A.jsx)(Mm,{children:i})]})}var TW=z({agent:P().nullable(),base:P().nullable(),directory:P().nullable(),files:I(),golden:P().nullable(),questions:I()}),EW=iy.extend({files:I()});async function DW(e){return ay.parse(await k(e,`/v1/knowledge`))}async function OW(e,t){return TW.parse(await eC(e,t,`knowledge.roster`,{agent:t}))}async function kW(e,t,n){return EW.parse(await eC(e,t,`knowledge.push`,{agent:t,...n===``?{}:{base:n}}))}async function AW(e,t,n){return ry.parse(await eC(e,t,`knowledge.eval`,{agent:t,...n===``?{}:{base:n}}))}async function jW(e,t){await ca(e,`/v1/knowledge/${encodeURIComponent(t)}`)}var MW=`minmax(0,1fr) 90px 140px 150px 80px`;function NW(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(null),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useCallback)(async()=>{s((await DW(e)).bases)},[e]);(0,D.useEffect)(()=>{let n=!1;return v().catch(e=>{n||_(FW(e))}),OW(e,t).then(e=>{n||(r(e),l(e.base??t))},e=>{n||a(FW(e))}),()=>{n=!0}},[e,t,v]);let y=async n=>{d(n),_(null);try{n===`push`?(p(await kW(e,t,c)),await v()):h(await AW(e,t,c))}catch(e){_(FW(e))}finally{d(``)}},b=async t=>{if(window.confirm(`Drop the base ${t}? Nothing brings it back but another push.`)){_(null);try{await jW(e,t),await v()}catch(e){_(FW(e))}}},x=n!==null&&n.agent===t;return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Docs`,ledeWidth:620,lede:`The documents this agent searches on a turn — the RAG. The folder is pushed whole and the base is replaced, never merged; which bases the agent reads is its Settings. What it knows by heart is Settings ▸ Knowledge, not a document.`}),(0,A.jsx)(wW,{agent:t}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`This directory`,children:x&&(0,A.jsxs)(`label`,{className:`kb-base`,children:[(0,A.jsx)(`span`,{className:`kb-base-label`,children:`base`}),(0,A.jsx)(`input`,{className:`kb-base-input`,value:c,size:Math.max(6,c.length),onChange:e=>l(e.target.value)})]})}),n===null&&i===null&&(0,A.jsxs)(Mm,{children:[`Asking the process that holds `,t,`…`]}),n===null&&i!==null&&(0,A.jsxs)(Mm,{children:[`The directory is read by the process holding `,t,`, and it did not answer: `,i,`. Bases already pushed are listed below.`]}),n!==null&&!x&&(0,A.jsx)(Mm,{children:n.agent===null?"No agent class in the project the agent's `pinecall start` runs in, so there is nothing here to push.":`The process holding the agent runs in ${n.agent}'s project: to push ${t}'s documents, run \`pinecall start\` there.`}),x&&(0,A.jsxs)(`div`,{className:`kb-here`,children:[(0,A.jsx)(`span`,{className:`kb-path`,children:n.directory??`—`}),(0,A.jsxs)(`span`,{className:`kb-count`,children:[n.files,` markdown file`,n.files===1?``:`s`]}),(0,A.jsx)(U,{size:`md`,disabled:u!==``||n.files===0,onClick:()=>void y(`push`),children:u===`push`?`Pushing…`:`Push the folder`}),(0,A.jsx)(`span`,{className:`kb-path`,children:n.golden===null?`no golden beside it`:`${n.questions} questions`}),(0,A.jsx)(U,{size:`md`,disabled:u!==``||n.golden===null,onClick:()=>void y(`eval`),children:u===`eval`?`Asking…`:`Run the golden`})]}),f!==null&&(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[`Pushed `,f.base,` · `,f.files,` files · `,f.chunks,` chunks · `,Math.round(f.took_ms),` ms`]})]}),(0,A.jsx)(Nm,{children:g}),m!==null&&(0,A.jsx)(PW,{score:m}),(0,A.jsx)(V,{children:o!==null&&o.length===0?(0,A.jsx)(Mm,{children:"No base pushed yet. Push the folder above, or `pinecall docs push` from the project."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:MW,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,`Action>`]}),(o??[]).map(e=>(0,A.jsxs)(fh,{columns:MW,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.base}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.model}),(0,A.jsx)(`span`,{className:`ui-cell`,children:Qh(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void b(e.base),children:`Drop`})})]},e.base))]})})]})}function PW({score:e}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The golden`,meta:`${e.base} · ${e.model} · ${e.questions} questions · ${Math.round(e.took_ms)} ms`}),(0,A.jsxs)(`div`,{className:`kb-figures`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`kb-figure-label`,children:[`recall@`,e.k]}),(0,A.jsx)(`div`,{className:`kb-figure`,children:e.recall_at_k.toFixed(2)})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`kb-figure-label`,children:`nDCG@10`}),(0,A.jsx)(`div`,{className:`kb-figure`,children:e.ndcg_at_10.toFixed(2)})]})]}),e.misses.length===0?(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`Every question found what it asked for.`}):e.misses.map(e=>(0,A.jsxs)(`div`,{className:`kb-miss`,children:[(0,A.jsx)(`div`,{className:`kb-miss-asks`,children:e.asks}),(0,A.jsxs)(`div`,{className:`kb-miss-why`,children:[`wanted `,e.expects,` · got `,e.found[0]??`nothing`]})]},e.asks))]})}function FW(e){return e instanceof na||e instanceof Error?e.message:String(e)}var IW=`150px minmax(0,1fr) 110px 76px`;function LW(e){return e.startsWith(`+`)?og(e):e}function RW(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(void 0),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(null),f=(0,D.useCallback)(async()=>{r(await xT(e,t))},[e,t]);(0,D.useEffect)(()=>{let n=!1;return xT(e,t).then(e=>{n||r(e)},e=>{n||(r(null),d(VW(e)))}),()=>{n=!0}},[e,t]);let p=async t=>{t.preventDefault();let n=i.trim();d(null),l(null);try{s({contact:n,facts:(await hT(e,n)).facts})}catch(e){d(VW(e))}},m=async t=>{if(window.confirm(`Erase everything memory kept about ${t}? There is no undo.`)){d(null);try{let r=(await gT(e,t)).forgotten;l(`${r} fact${r===1?``:`s`} about ${LW(t)} forgotten.`),s({contact:t,facts:[]}),n!=null&&await f()}catch(e){d(VW(e))}}},h=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${LW(t.contact)} stays.`)){d(null);try{await ST(e,t.id),await f()}catch(e){d(VW(e))}}},g=n!=null,_=g?n.filter(e=>i.trim()===``||e.contact.includes(i.trim())):[];return(0,A.jsxs)(sh,{width:900,tight:!0,children:[(0,A.jsx)(ch,{title:`Memory`,ledeWidth:620,lede:`What this agent carries between calls with the same caller — written by the agent, readable here, and droppable one row at a time.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Callers`,children:(0,A.jsxs)(`form`,{className:`mem-look`,onSubmit:e=>void p(e),children:[(0,A.jsx)(W,{size:`sm`,value:i,placeholder:`Look up a caller — a number or an id`,onChange:e=>a(e.target.value)}),!g&&(0,A.jsx)(U,{size:`sm`,type:`submit`,disabled:i.trim()===``,children:`Look up`}),o!==null&&o.facts.length>0&&(0,A.jsx)(U,{size:`sm`,kind:`danger`,onClick:()=>void m(o.contact),children:`Forget`})]})}),c!==null&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:c}),g?_.length===0?(0,A.jsx)(Mm,{children:n.length===0?`Memory keeps nothing about any caller of this agent yet.`:`No caller matches.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:IW,labels:[`Caller`,`Remembered`,`Written`,`Action>`]}),_.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:IW},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:LW(e.contact)}),(0,A.jsx)(`span`,{className:`mem-fact`,children:e.text}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:$h(e.written_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void h(e),children:`Drop`})})]},e.id))]}):o===null?(0,A.jsx)(Mm,{children:`Look up a caller by the number they called from, or by the id your app named them with, to read what memory keeps about them.`}):o.facts.length===0?(0,A.jsxs)(Mm,{children:[`Memory keeps nothing about `,LW(o.contact),`.`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:IW,labels:[`Caller`,`Remembered`,`Written`,`Category>`]}),o.facts.map((e,t)=>(0,A.jsxs)(`div`,{className:e.invalidated_at===null?`ui-table-row`:`ui-table-row mem-gone`,style:{gridTemplateColumns:IW},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,children:LW(o.contact)}),(0,A.jsxs)(`span`,{className:`mem-fact`,children:[e.text,e.invalidated_at!==null&&(0,A.jsxs)(`span`,{className:`mem-superseded`,children:[` · superseded `,$h(e.invalidated_at)]})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:$h(e.valid_from)}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip mem-category`,children:e.category??`—`})]},e.id??`${t}`))]})]}),(0,A.jsx)(Nm,{children:u}),(0,A.jsx)(zW,{agent:t})]})}function zW({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(null),[f,p]=(0,D.useState)(null);(0,D.useEffect)(()=>{let n=!1;return _T(t,e).then(e=>{n||r(e)},e=>{n||a(VW(e))}),()=>{n=!0}},[t,e]);let m=async n=>{s(n),p(null);try{n===`recall`?l(await vT(t,e)):d(await yT(t,e))}catch(e){p(VW(e))}finally{s(``)}};return n===null?i===null?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The goldens of this directory`}),(0,A.jsxs)(Mm,{children:[`They are read by the process holding `,e,`, and it did not answer: `,i,`.`]})]}):n.agent===e?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-goldens`,children:[(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Recall`,meta:`${n.questions} questions`}),(0,A.jsxs)(`div`,{className:`mem-run`,children:[(0,A.jsx)(`p`,{className:`mem-say`,children:`Every question asked of the ranking, scored by code with no model. No contact of yours is read: each question brings its own facts to a scratch contact.`}),(0,A.jsx)(U,{size:`md`,disabled:o!==``||n.questions===0,onClick:()=>void m(`recall`),children:o===`recall`?`Asking…`:`Run it`})]}),c!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-figures`,children:[(0,A.jsx)(BW,{label:`recall@${c.k}`,value:c.recall_at_k.toFixed(2)}),(0,A.jsx)(BW,{label:`nDCG@10`,value:c.ndcg_at_10.toFixed(2)}),(0,A.jsx)(BW,{label:`missed`,value:String(c.misses.length)})]}),c.misses.map(e=>(0,A.jsxs)(`div`,{className:`mem-miss`,children:[(0,A.jsx)(`div`,{className:`mem-miss-asks`,children:e.asks}),(0,A.jsxs)(`div`,{className:`mem-miss-why`,children:[`wanted `,e.missing.join(`, `),` · got `,e.found[0]??`nothing`]})]},e.asks))]})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Extraction`,meta:`${n.cases.length} cases`}),(0,A.jsxs)(`div`,{className:`mem-run`,children:[(0,A.jsx)(`p`,{className:`mem-say`,children:`One call written down per case, and one model call each — the very one a hang-up makes. Which categories got a fact, which never did, what must not survive.`}),(0,A.jsx)(U,{size:`md`,disabled:o!==``||n.cases.length===0,onClick:()=>void m(`extraction`),children:o===`extraction`?`Running…`:`Run them`})]}),u!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-figures`,children:[(0,A.jsx)(BW,{label:`held`,value:`${u.held}/${u.cases}`}),(0,A.jsx)(BW,{label:`model`,value:u.model})]}),u.results.filter(e=>!e.held).map(e=>(0,A.jsxs)(`div`,{className:`mem-miss`,children:[(0,A.jsx)(`div`,{className:`mem-miss-asks`,children:e.name}),(0,A.jsx)(`div`,{className:`mem-miss-why`,children:(e.broke??[]).map(e=>`${e.check}: ${e.detail}`).join(` · `)})]},e.name))]})]})]}),(0,A.jsx)(Nm,{children:f})]}):(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The goldens of this directory`}),(0,A.jsx)(Mm,{children:n.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so its goldens are not here.":`The process holding the agent runs in ${n.agent}'s directory: to run ${e}'s memory goldens, run \`pinecall start\` there.`})]})}function BW({label:e,value:t}){return(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`mem-figure-label`,children:e}),(0,A.jsx)(`div`,{className:`mem-figure ui-clip`,children:t})]})}function VW(e){return e instanceof na||e instanceof Error?e.message:String(e)}function HW({carrier:e,agents:t,available:n,busy:r,onImport:i,onBuy:a,onDone:o,onClose:s}){let[c,l]=(0,D.useState)(e===null?`buy`:`import`),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(`US`),[m,h]=(0,D.useState)(``),[g,_]=(0,D.useState)(t[0]?.slug??``),[v,y]=(0,D.useState)(null);(0,D.useEffect)(()=>{g===``&&t[0]!==void 0&&_(t[0].slug)},[t,g]);let b=()=>y(null),x=async e=>c===`import`?i({number:u.trim(),agent:g},e):a({country:f.trim().toUpperCase(),...m.trim()===``?{}:{area_code:m.trim()},agent:g},e),S=async e=>{e.preventDefault(),y(await x(!0).catch(()=>null))},C=async()=>{let e=await x(!1).catch(()=>null);e!==null&&(y(null),d(``),o(e))},w=n!==null&&n.kind===`twilio`?n.numbers.filter(e=>!e.imported):[],T=e=>{l(e),b()};return(0,A.jsxs)(`div`,{className:`num-add`,children:[(0,A.jsxs)(`div`,{className:`num-add-head`,children:[(0,A.jsxs)(`div`,{className:`ui-segmented`,role:`group`,children:[(0,A.jsx)(`button`,{type:`button`,className:c===`import`?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":c===`import`,onClick:()=>T(`import`),disabled:e===null,title:e===null?`connect your phone carrier first, in the Carrier tab`:void 0,children:w.length>0?`I already have one · ${w.length}`:`I already have one`}),(0,A.jsx)(`button`,{type:`button`,className:c===`buy`?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":c===`buy`,onClick:()=>T(`buy`),children:`Buy a new one`})]}),(0,A.jsx)(`button`,{type:`button`,className:`ui-text-action num-add-close`,onClick:s,children:`Close`})]}),(0,A.jsxs)(`form`,{onSubmit:e=>void S(e),children:[(0,A.jsxs)(`div`,{className:c===`buy`?`num-fields num-fields-3`:`num-fields`,children:[c===`import`?(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Number`}),w.length>0?(0,A.jsxs)(Hm,{value:u,onChange:e=>{d(e.target.value),b()},required:!0,children:[(0,A.jsx)(`option`,{value:``,children:`Choose a number…`}),w.map(e=>(0,A.jsxs)(`option`,{value:e.number,children:[og(e.number),` — `,e.name]},e.number))]}):(0,A.jsx)(W,{value:u,onChange:e=>{d(e.target.value),b()},placeholder:`+14176743169`,required:!0,autoComplete:`off`})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Country · two letters`}),(0,A.jsx)(W,{value:f,onChange:e=>{p(e.target.value),b()},maxLength:2,required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Area code · optional`}),(0,A.jsx)(W,{value:m,onChange:e=>{h(e.target.value),b()},placeholder:`417`,autoComplete:`off`})]})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Agent that answers`}),t.length>0?(0,A.jsx)(Hm,{value:g,onChange:e=>{_(e.target.value),b()},required:!0,children:t.map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.slug))}):(0,A.jsx)(W,{value:g,onChange:e=>{_(e.target.value),b()},placeholder:`the agent's slug`,required:!0,autoComplete:`off`})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(U,{kind:`primary`,type:`submit`,disabled:r||v!==null,children:r&&v===null?`Checking…`:`Review`}),(0,A.jsx)(`span`,{className:`num-note`,children:c===`import`?`Nothing changes yet — you will see exactly what is going to happen, and confirm.`:`Nothing is bought yet — you will see the number that was found, and confirm.`})]})]}),v!==null&&(0,A.jsxs)(`div`,{className:`num-plan`,children:[(0,A.jsxs)(`div`,{className:`num-plan-title`,children:[`This is what will happen`,c===`buy`&&v.route.number!==null?(0,A.jsxs)(A.Fragment,{children:[` with `,og(v.route.number)]}):null,`. Nothing is deleted.`]}),(0,A.jsx)(UW,{steps:v.steps}),(0,A.jsxs)(`div`,{className:`num-plan-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,onClick:()=>void C(),disabled:r,children:r?`Working…`:c===`buy`?`Buy it and connect it`:`Confirm`}),(0,A.jsx)(U,{size:`md`,onClick:b,disabled:r,children:`Cancel`})]})]})]})}function UW({steps:e}){return(0,A.jsx)(`ol`,{className:`num-steps`,children:e.map((e,t)=>{let[n,...r]=e.split(/\s+/);return(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`num-step-kind`,children:n}),(0,A.jsx)(`span`,{className:`num-step-text`,children:r.join(` `)})]},t)})})}function WW({carrier:e,busy:t,onBring:n,onDrop:r}){let[i,a]=(0,D.useState)(!1);return e!==null&&!i?(0,A.jsxs)(`div`,{className:`ui-card num-carrier`,children:[(0,A.jsx)(`span`,{className:`num-kind`,children:e.kind.toUpperCase()}),(0,A.jsx)(`span`,{className:`num-carrier-standing`,children:e.kind===`twilio`?`Account connected`:`SIP peer connected`}),(0,A.jsx)(`span`,{className:`num-carrier-account`,children:e.account}),(0,A.jsxs)(`span`,{className:`num-carrier-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>a(!0),disabled:t,children:`Change`}),(0,A.jsx)(U,{size:`xs`,kind:`danger`,onClick:()=>void r(),disabled:t,children:`Disconnect`})]})]}):(0,A.jsx)(GW,{busy:t,onBring:async e=>{await n(e),a(!1)},onCancel:e===null?null:()=>a(!1)})}function GW({busy:e,onBring:t,onCancel:n}){let[r,i]=(0,D.useState)(`twilio`),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(``),[h,g]=(0,D.useState)(``),[_,v]=(0,D.useState)(``),[y,b]=(0,D.useState)(`auto`),[x,S]=(0,D.useState)(``),[C,w]=(0,D.useState)(``);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Connect your phone carrier`,children:(0,A.jsxs)(`div`,{className:`ui-segmented num-ways`,role:`group`,children:[(0,A.jsx)(`button`,{type:`button`,className:r===`twilio`?`ui-segment ui-segment-on`:`ui-segment`,onClick:()=>i(`twilio`),children:`Twilio`}),(0,A.jsx)(`button`,{type:`button`,className:r===`sip`?`ui-segment ui-segment-on`:`ui-segment`,onClick:()=>i(`sip`),children:`SIP peer`})]})}),(0,A.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),t(r===`twilio`?{kind:r,account_sid:a.trim(),user:s.trim()||a.trim(),secret:l}:{kind:r,username:d.trim(),password:p,addresses:h.split(/[\s,]+/).filter(Boolean),..._.trim()===``?{}:{outbound_host:_.trim(),outbound_transport:y,...x.trim()===``?{}:{outbound_username:x.trim()},...C===``?{}:{outbound_password:C}}})},children:[(0,A.jsx)(`div`,{className:`num-fields num-fields-3`,children:r===`twilio`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Account SID`}),(0,A.jsx)(W,{value:a,onChange:e=>o(e.target.value),placeholder:`AC…`,required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`API key SID · or the account SID`}),(0,A.jsx)(W,{value:s,onChange:e=>c(e.target.value),placeholder:`SK…`,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Secret · the key's, or the auth token`}),(0,A.jsx)(W,{type:`password`,value:l,onChange:e=>u(e.target.value),required:!0,autoComplete:`off`})]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Username`}),(0,A.jsx)(W,{value:d,onChange:e=>f(e.target.value),required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Password`}),(0,A.jsx)(W,{type:`password`,value:p,onChange:e=>m(e.target.value),required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Networks its calls come from · CIDR`}),(0,A.jsx)(W,{value:h,onChange:e=>g(e.target.value),placeholder:`203.0.113.0/24`,required:!0,autoComplete:`off`})]})]})}),r===`sip`&&(0,A.jsxs)(`div`,{className:`num-outbound-group`,children:[(0,A.jsx)(`div`,{className:`num-outbound-title`,children:`Outbound`}),(0,A.jsx)(`div`,{className:`num-outbound-say`,children:`Where this box sends a call it places. Leave empty for a peer you only receive from.`}),(0,A.jsxs)(`div`,{className:`num-fields num-fields-4 num-fields-flush`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Host · and port`}),(0,A.jsx)(W,{value:_,onChange:e=>v(e.target.value),placeholder:`sip.carrier.example:5060`,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Transport`}),(0,A.jsxs)(Hm,{value:y,onChange:e=>b(e.target.value),children:[(0,A.jsx)(`option`,{value:`auto`,children:`auto`}),(0,A.jsx)(`option`,{value:`udp`,children:`udp`}),(0,A.jsx)(`option`,{value:`tcp`,children:`tcp`}),(0,A.jsx)(`option`,{value:`tls`,children:`tls`})]})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Username · else the one above`}),(0,A.jsx)(W,{value:x,onChange:e=>S(e.target.value),autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Password · else the one above`}),(0,A.jsx)(W,{type:`password`,value:C,onChange:e=>w(e.target.value),autoComplete:`off`})]})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(U,{kind:`primary`,type:`submit`,disabled:e,children:e?`Connecting…`:`Connect`}),n!==null&&(0,A.jsx)(U,{onClick:n,children:`Cancel`}),(0,A.jsx)(`span`,{className:`num-note`,children:r===`twilio`?`The account is checked once. The credentials are stored encrypted and never shown again.`:`Calls are accepted only from these networks, with this username and password.`})]})]})]})}var KW=/^\+[1-9]\d{6,14}$/;function qW(e){let t=e.toLowerCase();return t.includes(`no outbound trunk`)?`Outbound calls are not turned on yet.`:t.includes(`carrier`)?(0,A.jsxs)(A.Fragment,{children:[`Connect a carrier first — `,(0,A.jsx)(Wi,{to:`/numbers?tab=carrier`,children:`Carrier`}),`.`]}):t.includes(`number`)?(0,A.jsxs)(A.Fragment,{children:[`Add a number first — `,(0,A.jsx)(Wi,{to:`/numbers`,children:`Numbers`}),`.`]}):e.replace(/:?\s*(POST|PUT|GET|DELETE) \/v1\/\S+.*$/,``).trim()}function JW(e){return[e.dial_anywhere?`Agents can call any number`:`Agents can only call numbers that already contacted you`,`${e.per_minute} a minute`,`${e.per_day} a day`,`${Math.round(e.max_duration_s/60)} min per call`].join(` · `)}function YW({outbound:e,agents:t,busy:n,onProvision:r}){let[i,a]=(0,D.useState)(null);if(e===null)return(0,A.jsx)(V,{children:(0,A.jsxs)(`div`,{className:`num-hero`,children:[(0,A.jsx)(`div`,{className:`num-hero-title`,children:`Let your agents call people back`}),(0,A.jsxs)(`p`,{className:`num-hero-say`,children:[`Calls go out from your own numbers through your carrier account. Connect a carrier first — `,(0,A.jsx)(Wi,{to:`/numbers?tab=carrier`,children:`Carrier`}),`.`]})]})});let o=()=>void r(!0).then(a,()=>void 0),s=i!==null&&(0,A.jsxs)(`div`,{className:`num-plan`,children:[(0,A.jsx)(`div`,{className:`num-plan-title`,children:`What will happen — on your carrier account and on this gateway. Nothing is deleted.`}),(0,A.jsx)(UW,{steps:i.steps}),(0,A.jsxs)(`div`,{className:`num-plan-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`md`,onClick:()=>void r(!1).then(()=>a(null),()=>void 0),disabled:n,children:n?`Working…`:`Confirm`}),(0,A.jsx)(U,{size:`md`,onClick:()=>a(null),disabled:n,children:`Cancel`})]})]});if(!e.ready){let t=e.steps_missing.every(e=>e.toLowerCase().includes(`no outbound trunk`));return(0,A.jsxs)(V,{children:[(0,A.jsxs)(`div`,{className:`num-hero`,children:[(0,A.jsx)(`div`,{className:`num-hero-title`,children:`Let your agents call people back`}),(0,A.jsx)(`p`,{className:`num-hero-say`,children:`Calls go out from your own numbers through your carrier account.`}),e.steps_missing.filter(e=>!e.toLowerCase().includes(`no outbound trunk`)).map(e=>(0,A.jsx)(`p`,{className:`num-hero-missing`,children:qW(e)},e)),t&&(0,A.jsxs)(`div`,{className:`num-hero-move`,children:[(0,A.jsx)(U,{kind:`primary`,onClick:o,disabled:n||i!==null,children:n&&i===null?`Checking…`:`Turn on outbound calls`}),(0,A.jsx)(`span`,{className:`num-note`,children:`You will see what is going to happen, and confirm.`})]})]}),s]})}let[c,...l]=e.from_numbers;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`num-on`,children:[(0,A.jsx)(eh,{tone:`green`}),(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:`On`}),` — agents call from `,og(c),l.length>0&&` and ${l.length} more`]})]}),(0,A.jsx)(XW,{agents:t,from:e.from_numbers}),(0,A.jsxs)(`div`,{className:`num-limits`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`num-limits-say`,children:JW(e.guards)}),(0,A.jsx)(`div`,{className:`num-limits-who`,children:`Limits are set by whoever runs this gateway.`})]}),(0,A.jsx)(Bm,{onClick:o,disabled:n||i!==null,children:`Repair the setup`})]}),i!==null&&(0,A.jsx)(V,{children:s})]})}function XW({agents:e,from:t}){let n=j(),[r,i]=(0,D.useState)(e[0]?.slug??``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(t[0]??``),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(null);(0,D.useEffect)(()=>{r===``&&e[0]!==void 0&&i(e[0].slug)},[e,r]);let h=async e=>{e.preventDefault();let i=a.replace(/[\s()-]/g,``);if(f(null),!KW.test(i)){m(`Write the number with its country code, like +34600000000.`);return}u(!0),m(null);try{f(await Ob(n,r,i,t.length>1?s:void 0))}catch(e){m(e instanceof na?e.message:String(e))}finally{u(!1)}};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Make a test call`,meta:`the agent rings the number and talks when it is answered`}),(0,A.jsxs)(`form`,{onSubmit:e=>void h(e),children:[(0,A.jsxs)(`div`,{className:t.length>1?`num-fields num-fields-3`:`num-fields`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Agent`}),(0,A.jsx)(Hm,{value:r,onChange:e=>i(e.target.value),required:!0,children:e.map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.slug))})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`Number to call`}),(0,A.jsx)(W,{value:a,onChange:e=>o(e.target.value),placeholder:`+34 600 000 000`,required:!0,autoComplete:`off`})]}),t.length>1&&(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Vm,{children:`From`}),(0,A.jsx)(Hm,{value:s,onChange:e=>c(e.target.value),children:t.map(e=>(0,A.jsx)(`option`,{value:e,children:og(e)},e))})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(U,{kind:`primary`,type:`submit`,disabled:l||r===``,children:l?`Calling…`:`Call`}),d!==null&&(0,A.jsxs)(`span`,{className:`num-placed`,children:[`Ringing. `,(0,A.jsx)(Wi,{to:`/live/${d}`,children:`Watch it live`})]})]}),p!==null&&(0,A.jsx)(`div`,{className:`num-refused`,children:(0,A.jsx)(Nm,{children:p})})]})]})}var ZW=[{tab:`numbers`,name:`Numbers`},{tab:`outbound`,name:`Outbound calls`},{tab:`carrier`,name:`Carrier`}];function QW(){let e=j(),{agents:t}=Zy(),[n,r]=Xi(),i=ZW.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`numbers`,[a,o]=(0,D.useState)(void 0),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),{world:p}=kh(),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!1),[b,x]=(0,D.useState)(null),S=(0,D.useCallback)(async()=>{let[t,n]=await Promise.all([gb(e),hb(e)]);o(t),c(n),u(t===null?null:await yb(e)),f(t===null?null:await Tb(e).catch(()=>null))},[e]);(0,D.useEffect)(()=>{let e=!1;return S().catch(t=>{e||_($W(t))}),()=>{e=!0}},[S]);let C=async e=>{h(!0),_(null);try{let t=await e();return await S(),t}catch(e){throw _($W(e)),e}finally{h(!1)}},w=(s??[]).filter(e=>e.route.number!==null),T=(s??[]).filter(e=>e.route.number===null);return(0,A.jsxs)(sh,{width:900,children:[(0,A.jsx)(ch,{title:`Phone numbers`,lede:`The numbers people call, which agent picks up, and the calls your agents place.`}),(0,A.jsx)(yh,{label:`Phone numbers`,tabs:ZW.map(e=>e.tab===`outbound`&&a!==void 0?{...e,mark:(0,A.jsx)(eh,{tone:d?.ready?`green`:`amber`,small:!0})}:e),on:i,onPick:e=>r(e===`numbers`?{}:{tab:e})}),(0,A.jsx)(Nm,{children:g}),i===`numbers`&&s!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Numbers in ${p}`,action:!v&&a!==void 0?(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>{x(null),y(!0)},children:`Add a number`}):void 0}),w.length===0&&(0,A.jsxs)(Mm,{children:[`No phone number rings in `,p,` yet.`]}),w.map(t=>(0,A.jsxs)(`div`,{className:`num-row`,children:[(0,A.jsx)(`span`,{className:`num-number`,children:og(t.route.number)}),(0,A.jsx)(`span`,{className:`num-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(`span`,{className:`num-agent`,children:t.route.agent}),t.route.managed&&(0,A.jsx)(`span`,{title:`bought by the box for this org`,children:(0,A.jsx)(Qm,{tone:`violet`,children:`bought`})}),t.source===`operator`&&(0,A.jsx)(U,{kind:`danger`,size:`xs`,className:`num-remove`,disabled:m,title:`The number stops ringing this agent. It stays in your carrier account.`,onClick:()=>void C(()=>Sb(e,t.route.number??``)).catch(()=>void 0),children:`Remove`})]},t.route.number)),b!==null&&(0,A.jsxs)(`div`,{className:`num-added`,children:[`Done. `,og(b.route.number),` now rings `,b.route.agent,`.`]}),v&&a!==void 0&&(0,A.jsx)(HW,{carrier:a,agents:t,available:l,busy:m,onImport:(t,n)=>C(()=>bb(e,{...t,channel:`phone`},n)),onBuy:(t,n)=>C(()=>xb(e,{...t,channel:`phone`},n)),onDone:e=>{x(e),y(!1)},onClose:()=>y(!1)}),T.length>0&&(0,A.jsxs)(`div`,{className:`num-foot`,children:[`Also on the web, with no number needed: `,[...new Set(T.map(e=>e.route.agent))].join(`, `),`.`]})]}),i===`outbound`&&a!==void 0&&(0,A.jsx)(YW,{outbound:d,agents:t,busy:m,onProvision:t=>C(()=>Eb(e,t))}),i===`carrier`&&a!==void 0&&(0,A.jsx)(WW,{carrier:a,busy:m,onBring:async t=>{await C(()=>_b(e,t)).catch(()=>void 0)},onDrop:async()=>{await C(()=>vb(e)).catch(()=>void 0)}})]})}function $W(e){return e instanceof na?e.message:String(e)}function eG(){let e=j(),t=Gh(wh()),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)([]);(0,D.useEffect)(()=>{let t=!1;return k(e,`/v1/line/numbers`).then(e=>{if(t)return;let n=e;r(n.numbers),a(n.calling??[])},()=>void 0),()=>{t=!0}},[e]);let o=Zy().held.filter(e=>t!==null&&e.holder?.holder===t);return(0,A.jsxs)(sh,{width:900,children:[(0,A.jsx)(ch,{title:`Phone testing`,ledeWidth:660,lede:(0,A.jsxs)(A.Fragment,{children:[`Call the number your customers call, from your own mobile, and `,(0,A.jsx)(`b`,{children:`your copy answers`}),`. Everybody else who calls still reaches production. You do not need a sandbox number.`]})}),(0,A.jsxs)(V,{children:[(0,A.jsx)(Im,{children:`Once per machine`}),(0,A.jsx)(`pre`,{className:`ui-code`,children:`pinecall line from +1XXXXXXXXXX # this mobile is mine`}),(0,A.jsx)(Im,{ruled:!0,children:`While you work`}),(0,A.jsx)(`pre`,{className:`ui-code`,children:`pinecall start --serve # your copies up, and this console
101
+ pinecall line forget # give your calls back to production`}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:(0,A.jsxs)(`span`,{children:[`The call shows up here, in Sessions, marked `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`diverted_from: production`}),`.`]})})]}),n!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The numbers to call`}),n.length===0&&(0,A.jsx)(Mm,{children:`This org has no phone number in production yet. The gateway's console adds one, under Numbers.`}),n.map(e=>{let t=o.some(t=>t.slug===e.agent),n=t&&i.length>0;return(0,A.jsxs)(`div`,{className:`num-row`,children:[(0,A.jsx)(`span`,{className:`num-number`,children:og(e.number)}),(0,A.jsx)(`span`,{className:`num-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(`span`,{className:`num-agent`,children:e.agent}),(0,A.jsx)(`span`,{className:`num-end`,children:n?(0,A.jsxs)(Qm,{tone:`green`,children:[`your copy answers `,i.map(og).join(`, `)]}):t?(0,A.jsx)(Qm,{tone:`amber`,children:`production answers: say which phone is yours`}):(0,A.jsx)(Qm,{tone:`gray`,children:`production answers: you are not running it`})})]},e.number)})]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`What a call from your phone reaches right now`}),(0,A.jsx)(`div`,{className:`num-body`,children:o.length===0?(0,A.jsxs)(A.Fragment,{children:[`Nothing: no copy of yours is running, so your calls reach production. Start `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in the project.`]}):i.length===0?(0,A.jsxs)(A.Fragment,{children:[`Production, still: you are running `,o.map(e=>e.slug).join(`, `),`, and the gateway does not know which phone is yours.`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall line from +1…`}),`, once.`]}):(0,A.jsxs)(A.Fragment,{children:[`Your copy of `,o.map(e=>e.slug).join(`, `),`, from `,i.map(og).join(`, `),` — for as long as`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` stays up.`]})})]})]})}var tG=z({vendor:P(),model:P().nullable(),voice_id:P().nullable(),language:P().nullable()}),nG=z({name:mp(VC),seconds:F(),turns:I()}),rG=z({say:P().nullable(),reply:P().nullable(),allow_interruptions:L().nullable()}),iG=z({agent:P(),hears:tG,decides:tG,speaks:tG,greeting:rG.nullable(),voices:R(P()),providers:R(Ph),calls:I(),medians:R(nG),unavailable_reasons:fp(P(),P())});async function aG(e,t){return iG.parse(await k(e,oG(t)))}function oG(e){return`/v1/agents/${encodeURIComponent(e)}/pipeline`}var sG=z({played:mp([`default`,`off`,`custom`]),name:P().nullable(),seconds:F().nullable(),sha256:P().nullable()});async function cG(e,t){return sG.parse(await k(e,`${oG(t)}/hold-audio`))}async function lG(e,t,n){let r=await fetch(la(e,`${oG(t)}/hold-audio`,{name:n.name}),{method:`PUT`,headers:{...ra(e),"content-type":n.type||`application/octet-stream`},body:n});return sG.parse(await fa(r))}async function uG(e,t,n){return sG.parse(await oa(e,`${oG(t)}/hold-audio/played`,{played:n}))}async function dG(e,t){let n=await fetch(la(e,`${oG(t)}/hold-audio/audio`),{headers:ra(e)});return n.ok||await fa(n),URL.createObjectURL(await n.blob())}function fG({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),u=(0,D.useRef)(null);(0,D.useEffect)(()=>{let n=!1;return cG(t,e).then(e=>!n&&r(e),e=>!n&&s(e instanceof Error?e.message:String(e))),()=>{n=!0}},[t,e]),(0,D.useEffect)(()=>()=>{c!==null&&URL.revokeObjectURL(c)},[c]);let d=async(e,t)=>{a(e),s(null);try{r(await t()),l(null)}catch(e){s(e instanceof Error?e.message:String(e))}finally{a(null)}},f=async()=>{s(null);try{l(await dG(t,e))}catch(e){s(e instanceof Error?e.message:String(e))}},p=n=>{n!==void 0&&(d(`Converting…`,()=>lG(t,e,n)),u.current!==null&&(u.current.value=``))};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Hold melody`,meta:`what the caller hears while a tool runs — phone and web alike, from the next call`}),(0,A.jsxs)(`div`,{className:`pipe-hold`,children:[(0,A.jsxs)(`div`,{className:`pipe-hold-now`,children:[(0,A.jsx)(`b`,{children:n===null?`…`:n.played===`off`?`Off`:n.name??`Your file`}),(0,A.jsx)(`span`,{className:`pipe-note`,children:n===null?`Asking the gateway.`:n.played===`off`?`Silence while a tool runs.`:`${n.played==="default"?`The runtime's own`:`Uploaded`} · ${n.seconds??`?`} s, looped under the wait at 60 %, after 0.6 s.`})]}),(0,A.jsxs)(`div`,{className:`pipe-hold-actions`,children:[n!==null&&n.played!==`off`&&(0,A.jsx)(U,{size:`sm`,onClick:()=>void f(),disabled:i!==null,children:`Listen`}),(0,A.jsx)(U,{size:`sm`,onClick:()=>u.current?.click(),disabled:i!==null,children:i??`Upload a file…`}),n!==null&&n.played!=="default"&&(0,A.jsx)(U,{size:`sm`,onClick:()=>void d(`Saving…`,()=>uG(t,e,`default`)),disabled:i!==null,children:`Use the default`}),n!==null&&n.played!==`off`&&(0,A.jsx)(U,{size:`sm`,onClick:()=>void d(`Saving…`,()=>uG(t,e,`off`)),disabled:i!==null,children:`Turn off`}),(0,A.jsx)(`input`,{ref:u,type:`file`,accept:`audio/*,.mp3,.wav,.ogg,.m4a`,hidden:!0,onChange:e=>p(e.target.files?.[0])})]}),c!==null&&(0,A.jsx)(`audio`,{className:`pipe-hold-player`,controls:!0,autoPlay:!0,src:c}),o===null?(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`A wav, an mp3, an ogg or an m4a, up to 20 MB and five minutes: the gateway converts it.`}):(0,A.jsx)(`span`,{className:`pipe-save-error`,children:o})]})]})}function pG({stage:e,unavailable:t}){return(0,A.jsxs)(gG,{job:`hears`,stage:e,unavailable:t,children:[(0,A.jsx)(_G,{label:`Language`,value:e.language??`the vendor's default`,note:`What the ear is told to expect; the runtime adds the names the state carries.`}),e.model!==null&&e.model!==``&&(0,A.jsx)(_G,{label:`Model`,value:e.model}),(0,A.jsx)(_G,{label:`Switchable to`,value:`Any STT provider on file`,note:`Effective on the next session.`})]})}function mG({stage:e,unavailable:t}){return(0,A.jsxs)(gG,{job:`decides`,stage:e,unavailable:t,children:[(0,A.jsx)(_G,{label:`Model`,value:e.model??`the vendor's default`}),(0,A.jsx)(_G,{label:`Prompt`,value:`identity · knowledge · tools · history · view`,note:`Named blocks in two regions, never reordered: the static ones are cached, the dynamic ones rewritten every turn.`}),(0,A.jsx)(_G,{label:`Tools`,value:`The class's @tool methods`})]})}function hG({stage:e,unavailable:t}){return(0,A.jsxs)(gG,{job:`speaks`,stage:e,unavailable:t,children:[(0,A.jsx)(_G,{label:`Voice`,value:e.voice_id??`the vendor's default`,note:`One of the voices this build curates, by name; the id is the vendor's.`}),e.model!==null&&e.model!==``&&(0,A.jsx)(_G,{label:`Model`,value:e.model}),(0,A.jsx)(_G,{label:`Aligned transcript`,value:`On`,note:`Timed words, so the log knows when each word was spoken.`})]})}function gG({job:e,stage:t,unavailable:n,children:r}){return(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`pipe-leg-head`,children:[(0,A.jsx)(`span`,{className:`pipe-leg-vendor`,children:t.vendor}),(0,A.jsx)(`span`,{className:`pipe-leg-job`,children:e})]}),(0,A.jsxs)(`div`,{className:`pipe-leg-body`,children:[r,n!==null&&(0,A.jsxs)(`div`,{className:`pipe-field`,children:[(0,A.jsx)(`div`,{className:`pipe-label`,children:`Not right now`}),(0,A.jsx)(`div`,{className:`pipe-refused`,children:n})]})]})]})}function _G({label:e,value:t,note:n}){return(0,A.jsxs)(`div`,{className:`pipe-field`,children:[(0,A.jsx)(`div`,{className:`pipe-label`,children:e}),(0,A.jsx)(`div`,{className:`pipe-value`,children:t}),n!==void 0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:n})]})}function vG(e){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return r(null),aG(t,e).then(e=>{n||r(e)},e=>{n||a(String(e))}),()=>{n=!0}},[e,t]),{report:n,error:i}}var yG={transcription_delay:{label:`Transcription`,note:`from the end of speech to the ear's final transcript`,color:`var(--accent-3)`},end_of_turn_delay:{label:`End of turn`,note:`silence the turn detector waits through before it believes the caller stopped`,color:`var(--accent-3)`},llm_node_ttft:{label:`LLM first token`,note:`to the model's first token`,color:`var(--accent)`},tts_node_ttfb:{label:`Speech starts`,note:`to the voice's first audio byte`,color:`var(--accent-2)`},e2e_latency:{label:`End to end`,note:`what the caller actually waits: their last word to the agent's first audio`,color:`var(--accent-hover)`}};function bG({medians:e,calls:t,agent:n}){let r=new Map(e.map(e=>[e.name,e])),i=Math.max(0,...e.map(e=>e.seconds)),a=Math.max(0,...e.map(e=>e.turns));return(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Anatomy of a turn`}),i>0&&(0,A.jsxs)(`span`,{className:`ui-card-meta`,children:[`medians over the last `,t,` call`,t===1?``:`s`,` · `,a,` turns`]})]}),(0,A.jsx)(`div`,{className:`pipe-anatomy`,children:VC.map((e,t)=>{let n=yG[e],a=r.get(e)?.seconds??null;return(0,A.jsxs)(`div`,{className:t===VC.length-1?`pipe-turn-row pipe-turn-row-last`:`pipe-turn-row`,title:n.note,children:[(0,A.jsx)(`span`,{className:`pipe-turn-label`,children:n.label}),(0,A.jsx)(`span`,{className:`pipe-track`,children:a!==null&&i>0&&(0,A.jsx)(`span`,{className:`pipe-bar`,style:{width:`${Math.max(a/i*100,.8)}%`,background:n.color}})}),(0,A.jsx)(`span`,{className:a===null?`pipe-ms pipe-ms-none`:`pipe-ms`,children:a===null?`—`:`${Math.round(a*1e3)} ms`})]},e)})}),i===0&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:xG(t,n)})]})}function xG(e,t){return e===0?`No call stored for ${t} yet — place one and the bars fill.`:`${e} stored call${e===1?``:`s`} for ${t}, and not one turn carries a latency — a text session measures none.`}function SG(){let e=Sr().agent??``,{report:t,error:n}=vG(e);return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Pipeline`,ledeWidth:660,lede:`The three legs of a voice turn as data, not prose: what hears, what decides, what speaks — every value read from the gateway with this agent's settings already laid over the class.`}),t===null?(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:n??`Asking the gateway what ${e} runs on…`})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`pipe-legs`,children:[(0,A.jsx)(pG,{stage:t.hears,unavailable:t.unavailable_reasons.hears??null}),(0,A.jsx)(mG,{stage:t.decides,unavailable:t.unavailable_reasons.decides??null}),(0,A.jsx)(hG,{stage:t.speaks,unavailable:t.unavailable_reasons.speaks??null})]}),(0,A.jsx)(bG,{medians:t.medians,calls:t.calls,agent:e}),(0,A.jsx)(V,{children:(0,A.jsxs)(Mm,{children:[`Changing any of it is the `,(0,A.jsx)(Wi,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),` tab: the vendors and models with the opening, the cut of a turn and what is remembered, per corner and versioned.`]})}),(0,A.jsx)(fG,{agent:e},`hold-${e}`)]})]})}function CG(){let e=Sr().agent??``,{lines:t,error:n}=BS(e);return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Sessions`,lede:`Only what ${e} handled, newest first.`}),(0,A.jsx)(TU,{lines:t,error:n,agent:e,agents:[]})]})}var wG={passed:`green`,failed:`red`,deferred:`amber`,skipped:`muted`};function TG({agent:e,call:t}){let n=j(),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),d=async r=>{i(r),u(null);try{r===`check`?o(await rT(n,t)):c(await aT(n,e,t))}catch(e){u(e instanceof na?e.message:String(e))}finally{i(``)}};return(0,A.jsxs)(`div`,{className:`session-acts`,children:[(0,A.jsxs)(`div`,{className:`session-buttons`,children:[(0,A.jsx)(U,{size:`md`,disabled:r!==``,onClick:()=>void d(`check`),children:r===`check`?`Checking…`:`Re-check by code`}),(0,A.jsx)(U,{size:`md`,disabled:r!==``||e===``,onClick:()=>void d(`promote`),children:r===`promote`?`Writing…`:`Promote to a golden`})]}),a!==null&&(0,A.jsxs)(`div`,{className:`session-result`,children:[(0,A.jsx)(`span`,{className:`session-result-lead`,children:a.passed?`Holds by code`:`Does not hold by code`}),a.verdicts.map(e=>(0,A.jsxs)(Qm,{tone:wG[e.status]??`muted`,children:[e.check,` `,e.status]},e.check))]}),s!==null&&(0,A.jsxs)(`div`,{className:`session-result`,children:[(0,A.jsx)(`span`,{className:`session-result-lead`,children:`Written down`}),(0,A.jsx)(`span`,{className:`ui-fixed session-path`,children:s.path}),(0,A.jsxs)(`span`,{className:`session-result-note`,children:[s.candidate.input.length,` caller `,s.candidate.input.length===1?`turn`:`turns`]}),s.notes.map(e=>(0,A.jsx)(`span`,{className:`session-result-note session-result-line`,children:e},e))]}),l!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:l})]})}var EG=`confirm.`,DG=`tool.call`;function OG(e){let t=new Map;for(let n of e){if(!n.type.startsWith(EG))continue;let e=LG(n,`call_id`),r=t.get(e)??FG(e,LG(n,`tool`));t.set(e,{...r,...PG(n)})}for(let n of e){let e=n.type===DG?t.get(LG(n,`call_id`)):void 0;e!==void 0&&(e.ran=n)}return[...t.values()]}function kG({rows:e}){return e.length===0?null:(0,A.jsx)(`div`,{className:`session-consents`,children:e.map(e=>(0,A.jsx)(AG,{consent:e},e.callId))})}function AG({consent:e}){let t=MG(e);return(0,A.jsxs)(`div`,{className:`session-consent`,children:[(0,A.jsxs)(`div`,{className:`session-consent-join`,children:[(0,A.jsx)(`span`,{className:`session-consent-tool`,children:e.tool}),(0,A.jsx)(`span`,{className:`session-consent-seqs`,children:jG(e)}),(0,A.jsx)(`span`,{className:`session-consent-id ui-fixed`,children:e.callId})]}),e.requested!==null&&(0,A.jsx)(`div`,{className:`session-consent-said`,children:LG(e.requested,`phrase`)}),e.granted!==null&&(0,A.jsxs)(`div`,{className:`session-consent-said`,children:[`“`,LG(e.granted,`said`),`”`]}),(0,A.jsxs)(`div`,{className:`session-consent-audience`,children:[`audience `,NG(e)]}),t!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:t})]})}function jG(e){return e.granted===null?e.declined===null?`seq ${IG(e.requested)} asked and nothing answered`:`seq ${IG(e.declined)} declined seq ${IG(e.ran)}`:`seq ${e.granted.seq} authorised seq ${IG(e.ran)}`}function MG(e){let{granted:t,ran:n,requested:r}=e;if(t===null||n===null)return null;if(t.seq>n.seq)return`${e.tool} ran at seq ${n.seq}, before its confirm.granted at seq ${t.seq}`;let i=r===null?null:LG(r,`audience`);return i!==null&&i!==LG(t,`audience`)?`${e.tool} was confirmed by another audience than the one asked at seq ${r?.seq??0}`:null}function NG(e){let t=e.granted??e.declined??e.requested;return t===null?`—`:LG(t,`audience`)}function PG(e){return e.type===`confirm.granted`?{granted:e}:e.type===`confirm.declined`?{declined:e}:{requested:e}}function FG(e,t){return{callId:e,tool:t,requested:null,granted:null,declined:null,ran:null}}function IG(e){return e===null?`—`:String(e.seq)}function LG(e,t){let n=e.data[t];return typeof n==`string`?n:``}var RG={held:`green`,broken:`red`,deferred:`amber`,skipped:`muted`};function zG({call:e,back:t,score:n,turns:r,ended:i}){let[a,o]=(0,D.useState)(null),s=a??n;return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Score`,meta:s!==null&&s.passed!=null?`${HG(s)} of ${s.judges.length} held`:void 0}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:s===null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`session-standing session-standing-amber`,children:`Not scored yet`}),(0,A.jsxs)(`p`,{className:`session-sentence`,children:[`The call is still running, or its log was sealed before the judges existed. Ask for one with`,` `,(0,A.jsxs)(`span`,{className:`ui-fixed`,children:[`pinecall eval `,e]}),`.`]}),i&&(0,A.jsx)(WG,{call:e,onJudged:o})]}):s.passed==null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`session-standing session-standing-amber`,children:`No judge was given to this session`}),VG(s.not_judged)&&(0,A.jsx)(`p`,{className:`session-sentence`,children:s.not_judged}),(0,A.jsx)(`p`,{className:`session-sentence`,children:UG(s,r)}),i&&(0,A.jsx)(WG,{call:e,onJudged:o})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:s.passed?`session-standing session-standing-green`:`session-standing session-standing-red`,children:s.passed?`Passed`:`Did not pass`}),(0,A.jsxs)(`div`,{className:`session-judges`,children:[s.judges.map(n=>(0,A.jsx)(BG,{back:t,call:e,judgment:n},n.name)),(s.panel??[]).filter(e=>!s.judges.some(t=>t.name===e)).map(e=>(0,A.jsxs)(`div`,{className:`session-judge`,children:[(0,A.jsxs)(`div`,{className:`session-judge-line`,children:[(0,A.jsx)(`span`,{className:`session-judge-name`,children:e}),(0,A.jsx)(Qm,{tone:`muted`,children:`on the panel`})]}),(0,A.jsx)(`div`,{className:`session-judge-reason`,children:`Was run over this call and answered nothing.`})]},e))]}),(0,A.jsx)(`p`,{className:`session-sentence`,children:UG(s,r)})]})})]})}function BG({back:e,call:t,judgment:n}){return(0,A.jsxs)(`div`,{className:`session-judge`,children:[(0,A.jsxs)(`div`,{className:`session-judge-line`,children:[(0,A.jsx)(`span`,{className:`session-judge-name`,children:n.name}),(0,A.jsx)(Qm,{tone:RG[n.verdict]??`muted`,children:n.verdict}),n.evidence.seqs.map(n=>(0,A.jsxs)(Wi,{className:`session-seq`,to:`${e}/${t}#seq-${n}`,children:[`seq `,n]},n))]}),(0,A.jsxs)(`div`,{className:`session-judge-reason`,children:[n.reason,n.evidence.said!=null&&(0,A.jsxs)(`span`,{className:`session-judge-said`,children:[` “`,n.evidence.said,`”`]})]})]})}function VG(e){return e!=null&&e.trim().toLowerCase()!==`no judge was given to this session`}function HG(e){return e.judges.filter(e=>e.verdict===`held`).length}function UG(e,t){let n=`${t===1?`One turn`:`${t} turns`} replayed from the log`;return e.judge_calls===0?`${n}; the hard policies alone, and they cost nothing.`:`${n}; ${e.judge_calls} judge call${e.judge_calls===1?``:`s`} for ${Yh(e.judge_cost_eur)}.`}function WG({call:e,onJudged:t}){let n=j(),r=Eh(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null);if(r!==null&&!r.includes(`evals`))return null;let c=async()=>{a(!0),s(null);try{t(Y_.parse(await sa(n,`/v1/evals/judge/${encodeURIComponent(e)}`,{})))}catch(e){s(e instanceof na?e.message:String(e))}finally{a(!1)}};return(0,A.jsxs)(`div`,{className:`session-attach`,children:[(0,A.jsx)(U,{size:`md`,disabled:i,onClick:()=>void c(),children:i?`Judging…`:`Attach a judge`}),o!==null&&(0,A.jsx)(`p`,{className:`session-sentence session-refused-line`,children:o})]})}var GG={llm_node_ttft:`LLM first token`,e2e_latency:`End to end`,tts_node_ttfb:`Speech starts`,transcription_delay:`Transcription`,end_of_turn_delay:`End of turn`},KG=[`llm_node_ttft`,`e2e_latency`];function qG({rows:e}){let t=[...e.filter(e=>KG.includes(e.name)).sort((e,t)=>KG.indexOf(e.name)-KG.indexOf(t.name)),...e.filter(e=>!KG.includes(e.name))];return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Latency across this call`}),t.length===0?(0,A.jsx)(`p`,{className:`session-sentence session-latency-none`,children:`No turn in this session carried a metric — a chat session times nothing, and a voice call that dropped before its first answer has nothing to time.`}):(0,A.jsx)(`div`,{className:`session-latency`,children:t.map(e=>(0,A.jsxs)(`div`,{title:`${e.name} · median over ${e.turns} ${e.turns===1?`turn`:`turns`}`,children:[(0,A.jsx)(`div`,{className:`session-latency-label`,children:GG[e.name]??e.name}),(0,A.jsx)(`div`,{className:`session-latency-value`,children:GC(e.seconds)}),(0,A.jsxs)(`div`,{className:`session-latency-max`,children:[`max `,GC(e.max)]})]},e.name))})]})}var JG={"turn.user":`user`,"turn.agent":`agent`},YG=/^#seq-(\d+)$/;function XG({lines:e,turns:t}){let[n,r]=(0,D.useState)(new Set),[i,a]=(0,D.useState)(!1),o=nK(t),s=ZG(gr().hash),c=e.length;(0,D.useEffect)(()=>{s!==null&&c>0&&document.getElementById(QG(s))?.scrollIntoView({block:`center`})},[s,c]);let l=e=>r(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n});return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The log`,meta:`${e.length} entries, append-only, numbered by seq`,action:(0,A.jsx)(`span`,{className:`session-log-action`,children:(0,A.jsx)(U,{size:`sm`,onClick:()=>a(!i),children:i?`Hide the fields`:`Show every field`})})}),(0,A.jsx)(`div`,{className:`session-log`,children:e.map(e=>(0,A.jsx)($G,{line:e,turn:o.get(rK(e.entry.type,e.entry.data)),open:i||n.has(e.entry.seq),cited:e.entry.seq===s,onToggle:()=>l(e.entry.seq)},e.entry.seq))})]})}function ZG(e){let t=YG.exec(e)?.[1];return t===void 0?null:Number(t)}function QG(e){return`seq-${e}`}function $G({line:e,turn:t,open:n,cited:r,onToggle:i}){let a=e.fields.length>0,o=[`session-entry`,`session-entry-${eK(e.entry.type)}`];return a&&o.push(`session-entry-opens`),r&&o.push(`session-entry-cited`),(0,A.jsxs)(`div`,{id:QG(e.entry.seq),className:o.join(` `),onClick:a?i:void 0,children:[(0,A.jsx)(`span`,{className:`session-entry-seq`,children:e.entry.seq}),(0,A.jsx)(`span`,{className:`session-entry-since`,children:e.since}),(0,A.jsxs)(`span`,{className:`session-entry-type`,children:[e.mark!==``&&(0,A.jsxs)(`span`,{className:`session-entry-mark`,children:[e.mark,` `]}),e.entry.type]}),(0,A.jsxs)(`span`,{className:`session-entry-payload`,children:[e.payload,a&&(0,A.jsxs)(`span`,{className:`session-entry-caret`,children:[` `,n?`▾`:`▸`]}),t!==void 0&&(0,A.jsx)(tK,{turn:t}),n&&(0,A.jsx)(`span`,{className:`session-fields`,children:e.fields.map(e=>(0,A.jsxs)(`span`,{className:`session-field`,children:[(0,A.jsx)(`span`,{className:`session-field-name`,children:e.name}),(0,A.jsx)(`span`,{className:`session-field-value`,children:e.value})]},e.name))})]})]})}function eK(e){return e.startsWith(`turn.`)?`turn`:e.startsWith(`state.`)?`state`:e.startsWith(`tool.`)||e.startsWith(`confirm.`)?`tool`:e.startsWith(`call.`)?`call`:`quiet`}function tK({turn:e}){return(0,A.jsx)(`span`,{className:`session-chips`,children:HC(e).map(e=>(0,A.jsxs)(`span`,{className:`session-chip`,children:[e.field,` `,(0,A.jsx)(`b`,{children:e.value})]},e.field))})}function nK(e){return new Map(e.map(e=>[`${e.role}:${e.speech_id}`,e]))}function rK(e,t){let n=t.speech_id;return`${JG[e]??``}:${typeof n==`string`?n:``}`}var iK=[`turn.user`,`turn.agent`],aK=`metrics.`,oK=`memory.ops`,sK=`docs.sources`,cK={"tool.call":`→`,"tool.result":`←`},lK=`!`;function uK(e){let t=MC(e.map(e=>e.type)),n=e[0]?.ts??0;return e.map(e=>fK(e,n,t.get(e.type)))}function dK(e,t){return`+${(e-t).toFixed(3)}`}function fK(e,t,n){return{entry:e,mark:pK(e.type),since:dK(e.ts,t),payload:mK(e,n),fields:hK(e,n)}}function pK(e){return e.startsWith(`confirm.`)?lK:cK[e]??``}function mK(e,t){return iK.includes(e.type)?NC(Object.fromEntries(Object.entries(e.data).filter(([e])=>e!==`metrics`)),t):e.type.startsWith(aK)?``:e.type===oK?PH(e.data):e.type===sK?IH(e.data):NC(e.data,t)}function hK(e,t){if(iK.includes(e.type)){let n=e.data.metrics,r=t?.properties?.metrics;return yK(n)?gK(n,aK,r):[]}return e.type.startsWith(aK)?gK(e.data,``,t):e.type===oK?FH(e.data).map(e=>({name:`fact`,value:e})):e.type===sK?LH(e.data).map(e=>({name:`source`,value:e})):[]}function gK(e,t,n){return _K(e,t,n,vK(e,n))}function _K(e,t,n,r){let i=[];for(let a of r){let r=e[a],o=n?.properties?.[a];yK(r)?i.push(..._K(r,`${t}${a}.`,o,Object.keys(r))):i.push({name:`${t}${a}`,value:PC(r,o)})}return i}function vK(e,t){let n=Object.keys(t?.properties??{}).filter(t=>t in e);return[...n,...Object.keys(e).filter(e=>!n.includes(e))]}function yK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bK(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(!0),[o,s]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return r([]),a(!0),s(null),(async()=>{try{let i=await xC(t,e);n||r(i)}catch(e){n||s(String(e))}finally{n||a(!1)}})(),()=>{n=!0}},[e,t]),{entries:n,reading:i,error:o}}var xK=`call.summary`;function SK(){let{agent:e=``,call:t=``}=Sr(),{entries:n,reading:r,error:i}=bK(t),a=(0,D.useMemo)(()=>({state:wy(n),lines:uK(n),latencies:XC(n),consented:OG(n),recording:sH(AK(n)?.data),score:jK(n)}),[n]),o=e===``?`/sessions`:`/a/${e}/sessions`,s=e===``?a.state.agent:e;return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(Wi,{to:o,className:`ui-back`,children:`← Sessions`}),(0,A.jsx)(`h1`,{className:`session-title`,children:t}),(0,A.jsx)(TG,{agent:s,call:t})]}),i!==null&&(0,A.jsx)(V,{children:(0,A.jsxs)(Mm,{children:[`That session did not load. `,(0,A.jsx)(Nm,{children:i})]})}),i===null&&n.length===0&&(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:r?`Reading ${t}…`:`No call ${t} in the log.`})}),n.length>0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(TK,{state:a.state,events:n.length}),(0,A.jsxs)(V,{pad:!0,children:[(0,A.jsx)(`div`,{className:`session-outcome-label`,children:`Outcome`}),(0,A.jsx)(`div`,{className:`session-outcome`,children:a.state.outcome??(a.state.end_reason===null?`The call is still going.`:`The call left no outcome sentence.`)})]}),(0,A.jsx)(cH,{call:t,path:a.recording}),(0,A.jsxs)(`div`,{className:`session-split`,children:[(0,A.jsx)(EK,{state:a.state}),(0,A.jsxs)(`div`,{className:`session-side`,children:[(0,A.jsx)(qG,{rows:a.latencies}),(0,A.jsx)(zG,{call:t,back:o,score:a.score,turns:a.state.turns.length,ended:a.state.status===`ended`})]})]}),a.state.cost!==null&&a.state.cost.rows.length>0&&(0,A.jsx)(DK,{cost:a.state.cost}),(0,A.jsxs)(wK,{children:[a.consented.length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Consent proof`,meta:`each grant joined to the tool call it authorised`}),(0,A.jsx)(kG,{rows:a.consented})]}),Object.keys(a.state.prompt).length>0&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The prompt, block by block`,meta:`by name, hash and length — the text never enters the log`}),(0,A.jsx)(`div`,{className:`session-prompt`,children:Object.entries(a.state.prompt).map(([e,t])=>(0,A.jsxs)(Lm,{label:e,children:[(0,A.jsx)(`span`,{className:`ui-fixed session-hash`,children:t.hash}),` · `,t.chars,` chars · seq `,t.seq]},e))}),(0,A.jsxs)(`div`,{className:`session-note`,children:[(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall prompt --state`}),` prints the text offline.`]})]}),(0,A.jsx)(XG,{lines:a.lines,turns:a.state.turns})]})]})]})}var CK=/^#seq-\d+$/;function wK({children:e}){let{hash:t}=gr(),[n,r]=(0,D.useState)(()=>CK.test(t));return(0,D.useEffect)(()=>{CK.test(t)&&r(!0)},[t]),(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(V,{children:(0,A.jsxs)(`button`,{type:`button`,className:`session-details`,"aria-expanded":n,onClick:()=>r(!n),children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Details`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`consent, prompt blocks, the full log`}),(0,A.jsx)(`span`,{className:`session-details-caret`,children:n?`Hide ▴`:`Show ▾`})]})}),n&&e]})}function TK({state:e,events:t}){return(0,A.jsx)(`div`,{className:`session-facts`,children:(0,A.jsxs)(lh,{min:150,children:[(0,A.jsx)(uh,{size:`fact`,label:`Agent`,value:e.agent}),(0,A.jsx)(uh,{size:`fact`,label:`Channel`,value:e.direction===`outbound`?`${e.channel??`—`} · outbound`:e.channel??`—`}),(0,A.jsx)(uh,{size:`fact`,label:`Started`,value:Qh(e.started_at)}),(0,A.jsx)(uh,{size:`fact`,label:`Duration`,value:e.ended_at===null?`still going`:qh(e)}),(0,A.jsx)(uh,{size:`fact`,label:`Ended`,value:e.end_reason===null?`not yet`:e.end_reason.replace(/_/g,` `)}),(0,A.jsx)(uh,{size:`fact`,label:`Cost`,value:Yh(e.cost?.eur)}),(0,A.jsx)(uh,{size:`fact`,label:`Turns · events`,value:`${e.turns.length} · ${t}`})]})})}function EK({state:e}){let t=kK(e);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Transcript · ${e.turns.length} ${e.turns.length===1?`turn`:`turns`}`,meta:t===null?void 0:`with ${t}`}),e.turns.length===0?(0,A.jsx)(Mm,{children:`Nobody said anything a turn was written for.`}):(0,A.jsx)(`div`,{className:`session-turns`,children:e.turns.map((e,t)=>(0,A.jsxs)(`div`,{className:`session-turn`,children:[(0,A.jsx)(`span`,{className:e.role===`agent`?`session-who session-who-agent`:`session-who`,children:e.role===`agent`?`agent`:`caller`}),(0,A.jsxs)(`span`,{className:e.role===`agent`?`session-said session-said-agent`:`session-said`,children:[e.text,e.role===`agent`&&e.interrupted&&(0,A.jsx)(`span`,{className:`session-interrupted`,children:` · interrupted`})]})]},`${t}:${e.role}:${e.speech_id}`))})]})}function DK({cost:e}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Cost by model`,children:(0,A.jsx)(`span`,{className:`session-total`,children:Yh(e.eur)})}),(0,A.jsx)(`div`,{children:e.rows.map(e=>(0,A.jsxs)(`div`,{className:`session-cost`,children:[(0,A.jsxs)(`span`,{className:`session-cost-model`,children:[e.model,` `,(0,A.jsxs)(`span`,{className:`session-cost-kind`,children:[`· `,e.unit.replace(/_/g,` `)]})]}),(0,A.jsx)(`span`,{className:`session-cost-units`,children:OK(e.quantity)}),(0,A.jsx)(`span`,{className:`session-cost-eur`,children:Yh(e.eur)})]},`${e.provider}/${e.model}/${e.unit}`))}),(0,A.jsxs)(`div`,{className:`session-note`,children:[`EUR at `,e.rate.usd_to_eur,` per USD, as of `,e.rate.as_of,e.unpriced.length>0&&` · unpriced: ${e.unpriced.map(e=>`${e.provider}/${e.model}`).join(`, `)}`]})]})}function OK(e){let[t,n]=String(Math.round(e*100)/100).split(`.`),r=(t??``).replace(/\B(?=(\d{3})+(?!\d))/g,` `);return n===void 0?r:`${r}.${n}`}function kK(e){let t=e.caller?.name;if(t!=null&&t!==``)return t;let n=e.direction===`outbound`?e.to:e.from;return n===null?null:n.startsWith(`+`)?og(n):n}function AK(e){return[...e].reverse().find(e=>e.type===xK)}function jK(e){let t=[...e].reverse().find(e=>e.type===Fv);return t===void 0?null:Y_.parse(t.data)}var MK=[{field:`stt`,modality:`stt`,label:`Hears with`,note:`Which ear hears the caller. A model beside it when the vendor's own default is not wanted.`},{field:`llm`,modality:`llm`,label:`Decides with`,note:`What reads the words and answers.`},{field:`tts`,modality:`tts`,label:`Speaks with`,note:`What says it out loud. The voice is then that vendor's own id, unless the vendor is the one this build curates voices for.`}],NK=`elevenlabs`;function PK(e){let t=e.turn??void 0,n=e.memory??void 0;return{voice:e.voice??``,tts:e.tts??``,tts_model:e.tts_model??``,stt:e.stt??``,llm:e.llm??``,say:e.greeting?.say??``,reply:e.greeting?.reply??``,hangup:e.hangup?.when??``,endpointing_ms:typeof t?.endpointing_ms==`number`?String(t.endpointing_ms):``,min_interruption_words:typeof t?.min_interruption_words==`number`?String(t.min_interruption_words):``,remember:(n?.remember??[]).join(`
102
102
  `),forget:(n?.forget??[]).join(`
103
- `),knowledge:(e.knowledge??[]).map(e=>typeof e.k==`number`?`${e.base} ${e.k}`:e.base).join(`
104
- `),note:``}}function OK(e,t,n){let r=t?{...n}:{},i=n=>{if(t)return;let i=e[n].trim();i!==``&&(r[n]=i)};i(`voice`),i(`tts`),i(`tts_model`),i(`stt`),i(`llm`);let a=e.say.trim(),o=e.reply.trim();a===``?o!==``&&!t?r.greeting={reply:o}:delete r.greeting:r.greeting={say:a};let s=kK(e.remember),c=kK(e.forget);if(s.length>0||c.length>0?r.memory={remember:s,forget:c}:delete r.memory,!t){let t=e.hangup.trim();t!==``&&(r.hangup={when:t});let n={};e.endpointing_ms.trim()!==``&&(n.endpointing_ms=Number(e.endpointing_ms)),e.min_interruption_words.trim()!==``&&(n.min_interruption_words=Number(e.min_interruption_words)),Object.keys(n).length>0&&(r.turn=n);let i=kK(e.knowledge).map(e=>{let[t,n]=e.split(/\s+/);return n===void 0?{base:t??``}:{base:t??``,k:Number(n)}});i.length>0&&(r.knowledge=i)}return r}function kK(e){return e.split(`
105
- `).map(e=>e.trim()).filter(e=>e!==``)}function AK({standing:e,version:t,wordsOnly:n,voices:r,providers:i,saving:a,error:o,onSave:s}){let[c,l]=(0,D.useState)(()=>DK(e)),[u,d]=(0,D.useState)(!1),f=(e,t)=>{d(!1),l({...c,[e]:t})},p=new Set(Rh(i,`tts`).map(e=>e.name)),m=jK(c.tts,p)||EK,h=async r=>{r.preventDefault(),await s(OK(c,n,e),t,c.note.trim()===``?null:c.note.trim()),d(!0)};return(0,A.jsxs)(`form`,{className:`ui-card`,onSubmit:e=>void h(e),children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Set`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:t===null?`the first version of this corner`:`over v${t} — a corner that moved since is told so, never written over`})]}),(0,A.jsxs)(`div`,{className:`set-grid`,children:[!n&&TK.map(e=>(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:e.label}),(0,A.jsx)(PK,{value:c[e.field],offered:Rh(i,e.modality),onChange:t=>f(e.field,t)}),(0,A.jsx)(`p`,{className:`pipe-note`,children:e.note})]},e.field)),!n&&(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Voice`}),m===EK?(0,A.jsxs)(Hm,{value:c.voice,onChange:e=>f(`voice`,e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`as the class declares`}),(r.includes(c.voice)||c.voice===``?r:[c.voice,...r]).map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}):(0,A.jsx)(W,{value:c.voice,spellCheck:!1,placeholder:`${m}'s own voice id`,onChange:e=>f(`voice`,e.target.value)}),(0,A.jsx)(W,{value:c.tts_model,spellCheck:!1,placeholder:`tts model, when the vendor's default is not wanted`,onChange:e=>f(`tts_model`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Greeting`}),(0,A.jsx)(Um,{value:c.say,rows:2,placeholder:`the words said as the call opens, verbatim`,onChange:e=>f(`say`,e.target.value)}),!n&&(0,A.jsx)(Um,{value:c.reply,rows:2,placeholder:`or: what the model reads before it finds its own opening`,onChange:e=>f(`reply`,e.target.value)}),(0,A.jsx)(`p`,{className:`pipe-note`,children:`One of the two: the words themselves, or an instruction. Words also stop a class that improvises its opening.`})]}),!n&&(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Hangup`}),(0,A.jsx)(W,{value:c.hangup,placeholder:`when the model may end the call, in your words`,onChange:e=>f(`hangup`,e.target.value)})]}),!n&&(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Turn`}),(0,A.jsx)(W,{value:c.endpointing_ms,inputMode:`numeric`,placeholder:`endpointing, ms`,onChange:e=>f(`endpointing_ms`,e.target.value)}),(0,A.jsx)(W,{value:c.min_interruption_words,inputMode:`numeric`,placeholder:`words before an interruption counts`,onChange:e=>f(`min_interruption_words`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Remember`}),(0,A.jsx)(Um,{value:c.remember,rows:3,placeholder:`what to keep about a caller, one line each`,onChange:e=>f(`remember`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Never keep`}),(0,A.jsx)(Um,{value:c.forget,rows:3,placeholder:`what is never written down, one line each`,onChange:e=>f(`forget`,e.target.value)})]}),!n&&(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Knowledge`}),(0,A.jsx)(Um,{value:c.knowledge,rows:2,placeholder:`bases the agent reads, one per line: name, and k after a space`,onChange:e=>f(`knowledge`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Note`}),(0,A.jsx)(W,{value:c.note,placeholder:`why, for the history`,onChange:e=>f(`note`,e.target.value)})]})]}),(0,A.jsxs)(`div`,{className:`pipe-save`,children:[(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:a,children:a?`Saving…`:`Save as the next version`}),o===null?u?(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`Kept. The corners above are the gateway's answer.`}):(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`An empty field gives it back to what the class declares.`}):(0,A.jsx)(`span`,{className:`pipe-save-error`,children:o})]})]})}function jK(e,t){let n=e.lastIndexOf(`/`);return n>=0?e.slice(0,n):t.has(e)?e:``}function MK(e,t){let n=e.lastIndexOf(`/`);return n>=0?e.slice(n+1):t.has(e)?``:e}function NK(e,t){return e===``?t:t===``?e:`${e}/${t}`}function PK({value:e,offered:t,onChange:n}){let r=new Set(t.map(e=>e.name)),i=jK(e,r),a=MK(e,r);return(0,A.jsxs)(`div`,{className:`set-stage`,children:[(0,A.jsxs)(Hm,{value:i,onChange:e=>n(NK(e.target.value,a)),children:[(0,A.jsx)(`option`,{value:``,children:`as the class declares`}),t.map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,e.ready?``:` — ${e.standing}`]},e.name))]}),(0,A.jsx)(W,{value:a,spellCheck:!1,placeholder:`the vendor's own default model`,onChange:e=>n(NK(i,e.target.value))})]})}function FK({kept:e,canRollBack:t,onRollBack:n}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`History`,meta:e===null?void 0:e.holder===``?`the org's own corner`:`corner ${e.holder}`}),e===null?(0,A.jsx)(Mm,{children:`Asking the gateway…`}):e.rows.length===0?(0,A.jsx)(Mm,{children:`Nothing set in this corner yet: the class declares what the next call runs on.`}):e.rows.map((r,i)=>{let a=e.rows[i+1],o=CK(a?.config??{},r.config);return(0,A.jsxs)(`div`,{className:`set-version`,children:[(0,A.jsxs)(`div`,{className:`set-version-head`,children:[(0,A.jsxs)(`b`,{children:[`v`,r.version]}),(0,A.jsxs)(`span`,{className:`ui-cell-faint`,children:[r.author,` · `,Qh(r.set_at)]}),r.note!==null&&(0,A.jsxs)(`span`,{className:`set-version-note`,children:[`“`,r.note,`”`]}),t&&i>0&&(0,A.jsx)(U,{size:`xs`,onClick:()=>void n(r.version),children:`Roll back to this`})]}),o.length>0&&(0,A.jsx)(`div`,{className:`set-version-changes`,children:o.join(` · `)})]},r.version)})]})}var IK=`140px minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)`;function LK(e){return e instanceof Error?e.message:String(e)}function RK(){let e=j(),t=Sr().agent??``,n=Eh(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(null),[h,g]=(0,D.useState)(null),_=n!==null&&!n.includes(`pipeline`),v=fm===`hosted`,y=(0,D.useCallback)(async()=>{i(await gK(e,t)),o(await vK(e,t,v||l))},[e,t,l,v]);(0,D.useEffect)(()=>{let n=!1;return m(null),y().catch(e=>{n||m(LK(e))}),HW(e,t).then(e=>!n&&c(e),e=>{!n&&!(e instanceof na&&(e.status===403||e.status===404))&&m(LK(e))}),()=>{n=!0}},[e,t,y]);let b=async(n,r,a)=>{f(!0),m(null);try{i(await _K(e,t,{config:n,if_version:r,note:a,team:l})),o(await vK(e,t,v||l))}catch(e){m(LK(e))}finally{f(!1)}},x=async n=>{m(null);try{i(await yK(e,t,n,v||l)),o(await vK(e,t,v||l)),g(`v${n} is the newest again, as a new version.`)}catch(e){m(LK(e))}},S=r===null?null:wK(r,v||l);return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Settings`,ledeWidth:680,lede:`What the org set over the class, per world and per corner, a version a row: which vendors and models, how the call opens and ends, how a turn is cut, what is remembered, which bases are read. Set here, in the world this console looks at, and kept forever: every version, who set it, and a roll back.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The three corners`,meta:r===null?void 0:r.world}),r===null?(0,A.jsx)(Mm,{children:p??`Asking the gateway…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:IK,labels:[``,`yours`,`team`,`production`]}),bK.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:IK},children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:xK[e]}),[r.yours,r.team,r.production].map((t,n)=>(0,A.jsx)(`span`,{className:`ui-clip`,children:zK(t,e,n===0)},n))]},e)),(0,A.jsx)(`div`,{className:`ui-card-foot set-corners-foot`,children:[`yours`,`team`,`production`].map(e=>(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:e}),` `,r[e]===null?`nothing set`:BK(r[e])]},e))})]})]}),r!==null&&(0,A.jsxs)(A.Fragment,{children:[!_&&!v&&(0,A.jsx)(`div`,{className:`set-corner-pick`,children:(0,A.jsx)(Ym,{checked:l,onChange:u,children:`Write the team's corner, which every corner falls back to — not only yours`})}),(0,A.jsx)(AK,{standing:S?.config??{},version:S?.version??null,wordsOnly:_,voices:s?.voices??[],providers:s?.providers??[],saving:d,error:p,onSave:b},`${t}-${l}-${S?.version??0}`)]}),(0,A.jsx)(FK,{kept:a,canRollBack:!_,onRollBack:x}),h!==null&&(0,A.jsx)(`div`,{className:`ui-empty`,children:h}),(0,A.jsx)(Nm,{children:p})]})}function zK(e,t,n){return e===null?n?`(team's)`:`—`:SK(e.config,t)??`—`}function BK(e){return`v${e.version} · ${e.author} · ${Qh(e.set_at)}${e.note===null?``:` · “${e.note}”`}`}var VK=z({device:P().nullable(),expires_at:F(),answered:L()}),HK=z({device:P().nullable(),org:P()});function UK(e){return`/v1/login/pairings/${encodeURIComponent(e)}`}async function WK(e,t){return VK.parse(await k(e,UK(t)))}async function GK(e,t){return HK.parse(await sa(e,UK(t),{})).org}var KK=`c`,qK=`a terminal`;function JK(){let e=j(),[t]=Xi(),n=t.get(KK),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);(0,D.useEffect)(()=>{if(n===null)return;let t=!1;return WK(e,n).then(e=>{t||i(e)},e=>{t||u(e instanceof na?e.message:String(e))}),()=>{t=!0}},[e,n]);let d=async()=>{if(n!==null){o(!0),u(null);try{c(await GK(e,n))}catch(e){u(e instanceof na?e.message:String(e))}finally{o(!1)}}};return n===null?(0,A.jsx)(XK,{title:`No terminal is asking`,lede:YK}):s===null?l!==null&&r===null?(0,A.jsx)(XK,{title:`That link is no good`,lede:l}):(0,A.jsxs)(XK,{title:`Sign this terminal in?`,lede:`A terminal calling itself ${r?.device??qK} asked to be signed in as you. Approve it only if you just ran "pinecall login" on that machine yourself.`,children:[(0,A.jsx)(U,{kind:`primary`,size:`lg`,onClick:()=>void d(),disabled:a||r===null,children:a?`Signing in…`:`Yes, that is my terminal`}),l!==null&&(0,A.jsx)(`p`,{className:`terminal-refused`,children:l})]}):(0,A.jsx)(XK,{title:`Your terminal is signed in`,lede:`Go back to it. You are in ${s}.`})}var YK="Run `pinecall login` in your terminal — it prints a link, and that link comes back here.";function XK({title:e,lede:t,children:n}){return(0,A.jsx)(`div`,{className:`terminal`,children:(0,A.jsxs)(`div`,{className:`terminal-card`,children:[(0,A.jsx)(`img`,{className:`terminal-mark`,src:`/pinecall-mark.png`,alt:``}),(0,A.jsx)(`h1`,{className:`terminal-title`,children:e}),(0,A.jsx)(`p`,{className:`terminal-lede`,children:t}),n]})})}var ZK=`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,QK={active:`green`,invited:`amber`,disabled:`gray`};function $K({member:e,onChange:t,onResend:n,onReset:r,onRemove:i,yourself:a=!1}){let[o,s]=(0,D.useState)(!1),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(e.agents.join(` `)),[f,p]=(0,D.useState)(!1),m=async e=>{p(!0);try{await e()}finally{p(!1)}},h=()=>{l(null);let n=u.split(/[\s,]+/).filter(e=>e!==``);n.join(` `)!==e.agents.join(` `)&&m(()=>t({agents:n}))};return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:ZK},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.email}),c===`role`?(0,A.jsx)(Hm,{size:`sm`,autoFocus:!0,value:e.role,onBlur:()=>l(null),onChange:e=>{l(null),m(()=>t({role:e.target.value}))},"aria-label":`${e.name}'s role`,children:CU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))}):(0,A.jsx)(`button`,{type:`button`,className:`team-editable team-role`,onClick:()=>l(`role`),title:`Change the role`,children:e.role}),c===`agents`?(0,A.jsx)(W,{size:`sm`,autoFocus:!0,value:u,placeholder:`every agent`,onChange:e=>d(e.target.value),onBlur:h,onKeyDown:t=>{t.key===`Enter`&&h(),t.key===`Escape`&&(d(e.agents.join(` `)),l(null))},"aria-label":`${e.name}'s agents`}):(0,A.jsx)(`button`,{type:`button`,className:`team-editable team-agents ui-clip`,onClick:()=>l(`agents`),title:`Change the agents`,children:e.agents.length===0?`every agent`:e.agents.join(`, `)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.role===`admin`?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`always`}):(0,A.jsx)(Jm,{on:e.production,label:`${e.name} acts in production`,onChange:e=>void m(()=>t({production:e}))})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Qm,{tone:QK[e.status],children:e.status})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:o?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`team-sure`,children:`Remove for good?`}),(0,A.jsx)(Bm,{danger:!0,disabled:f,onClick:()=>void m(i),children:`Remove`}),(0,A.jsx)(Bm,{disabled:f,onClick:()=>s(!1),children:`Keep`})]}):(0,A.jsxs)(A.Fragment,{children:[e.status===`active`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(r),title:`A one-use link to choose a new password`,children:`Reset password`}),!a&&(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(()=>t({status:`disabled`})),children:`Disable`})]}),e.status===`disabled`&&(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(()=>t({status:`active`})),children:`Bring back`}),e.status===`invited`&&(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(n),children:`Resend invite`}),!a&&(0,A.jsx)(Bm,{danger:!0,disabled:f,onClick:()=>s(!0),title:`Out of the org for good: every key revoked, the seat freed`,children:`Remove`})]})})]})}var eq={qa:{who:`Reads finished calls and the suites`,opens:`calls · evals`},supervisor:{who:`Sits beside a live call: listens, whispers, takes it over`,opens:`calls · evals · supervise · talk · memory`},manager:{who:`Runs the floor and the org's accounts, never the agent's declaration`,opens:`calls · evals · supervise · talk · memory · numbers · keys · providers · usage · team`},developer:{who:`Writes and runs the agent`,opens:`app · calls · talk · supervise · pipeline · knowledge · memory · evals`},admin:{who:`The org's owner`,opens:`every door`}},tq=[`qa`,`supervisor`,`manager`,`developer`,`admin`],nq=`110px minmax(0,1fr) minmax(0,1.4fr)`;function rq(){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Roles`,meta:`a preset of what a person's keys open — and where: the sandbox always, production when their switch is on (an admin's always is)`}),(0,A.jsx)(dh,{columns:nq,labels:[`Role`,`Who`,`Opens`]}),tq.map(e=>(0,A.jsxs)(fh,{columns:nq,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:eq[e].who}),(0,A.jsx)(`span`,{className:`ui-cell-faint team-role-opens`,children:eq[e].opens})]},e))]})}var iq=``;function aq(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{let t=!1;return MU(e).then(e=>{t||n(e)},e=>{t||i(cq(e))}),()=>{t=!0}},[e]),t===null)return r===null?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Single sign-on`}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(Nm,{children:r})})]});let l=async()=>{if(!s){c(!0);return}i(null);try{await PU(e),n(await MU(e)),c(!1)}catch(e){i(cq(e))}};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Single sign-on`,meta:t.configured?`this org's people sign in with its identity provider`:`sign in with Google Workspace, Okta or Entra instead of a password`,children:t.configured&&!a&&(0,A.jsxs)(`span`,{className:`team-link-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>o(!0),children:`Change`}),(0,A.jsx)(U,{size:`xs`,kind:`danger`,onClick:()=>void l(),onBlur:()=>c(!1),children:s?`Remove · sure?`:`Remove`})]})}),t.configured&&!a?(0,A.jsxs)(`div`,{className:`team-sso-values`,children:[(0,A.jsx)(Lm,{label:`Issuer`,children:t.issuer}),(0,A.jsx)(Lm,{label:`Client ID`,children:t.client_id}),(0,A.jsx)(Lm,{label:`Client secret`,children:`kept, and never shown`}),(0,A.jsx)(Lm,{label:`Allowed domains`,children:t.domains.join(`, `)||`—`}),(0,A.jsx)(Lm,{label:`Arriving new`,children:t.role??`nobody: invite first`}),(0,A.jsx)(Lm,{label:`Passwords`,children:t.required?`stopped for this org`:`still work beside it`})]}):(0,A.jsx)(oq,{sso:t,onSaved:e=>{n(e),o(!1)},onCancel:t.configured?()=>o(!1):void 0}),(0,A.jsx)(sq,{uri:t.redirect_uri}),r!==null&&(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(Nm,{children:r})})]})}function oq({sso:e,onSaved:t,onCancel:n}){let r=j(),[i,a]=(0,D.useState)(e.issuer??``),[o,s]=(0,D.useState)(e.client_id??``),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(e.domains.join(` `)),[f,p]=(0,D.useState)(e.role??iq),[m,h]=(0,D.useState)(e.required),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),b=async e=>{e.preventDefault(),_(!0),y(null);try{t(await NU(r,{issuer:i.trim(),client_id:o.trim(),client_secret:c,domains:u.split(/[\s,]+/).filter(e=>e!==``),role:f===iq?null:f,required:m}))}catch(e){y(cq(e))}finally{_(!1)}};return(0,A.jsxs)(`form`,{className:`team-sso-form`,onSubmit:e=>void b(e),children:[(0,A.jsxs)(`div`,{className:`team-sso-grid`,children:[(0,A.jsx)(Wm,{label:`Issuer URL`,children:(0,A.jsx)(W,{type:`url`,placeholder:`https://accounts.google.com`,value:i,onChange:e=>a(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Client ID`,children:(0,A.jsx)(W,{value:o,onChange:e=>s(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Client secret, sent once`,children:(0,A.jsx)(W,{type:`password`,autoComplete:`off`,placeholder:`never shown again`,value:c,onChange:e=>l(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Allowed domains`,children:(0,A.jsx)(W,{placeholder:`company.com other.com`,value:u,onChange:e=>d(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Role for people who arrive new`,children:(0,A.jsxs)(Hm,{value:f,onChange:e=>p(e.target.value),children:[(0,A.jsx)(`option`,{value:iq,children:`nobody: invite first`}),CU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]})}),(0,A.jsxs)(`div`,{className:`team-sso-required`,children:[(0,A.jsx)(`span`,{className:`team-sso-required-words`,children:`Passwords stop working for this org`}),(0,A.jsx)(Jm,{on:m,onChange:h,label:`Passwords stop working for this org`})]})]}),(0,A.jsxs)(`div`,{className:`team-sso-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:g,children:g?`Asking the issuer…`:`Save`}),n!==void 0&&(0,A.jsx)(U,{size:`form`,onClick:n,children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`The gateway asks the issuer for its discovery document before it keeps anything.`})]}),(0,A.jsx)(Nm,{children:v})]})}function sq({uri:e}){let[t,n]=(0,D.useState)(!1);return(0,A.jsxs)(`div`,{className:`team-sso-redirect`,children:[(0,A.jsxs)(`div`,{className:`team-sso-redirect-head`,children:[(0,A.jsx)(`span`,{className:`ui-note`,children:`Register this at your identity provider as the redirect URI`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>n(!0))},children:t?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:e})]})}function cq(e){return e instanceof na?e.message:String(e)}var lq=[{tab:`people`,name:`People`},{tab:`roles`,name:`Roles`},{tab:`sso`,name:`Single sign-on`}];function uq(){let e=j(),t=Gh(wh()),[n,r]=Xi(),i=lq.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`people`,[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),p=async()=>o(await EU(e)),m=e=>r(e===`people`?{}:{tab:e});(0,D.useEffect)(()=>{let t=!1;return EU(e).then(e=>{t||o(e)},e=>{t||f(pq(e))}),()=>{t=!0}},[e]);let h=async(t,n)=>{f(null);try{await AU(e,t,n),await p()}catch(e){f(pq(e))}},g=async t=>{f(null);try{return u({link:await DU(e,t),kind:`invitation`}),await p(),!0}catch(e){return f(pq(e)),!1}},_=async t=>{f(null);try{await kU(e,t),await p()}catch(e){f(pq(e))}},v=async t=>{f(null);try{u({link:await OU(e,t),kind:`reset`})}catch(e){f(pq(e))}},y=e=>(a??[]).filter(t=>t.status===e).length;return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Team`,lede:`The org's people: who they are, what their keys may do, and how they sign in.`}),(0,A.jsx)(yh,{label:`Team`,tabs:lq,on:i,onPick:m}),i===`people`&&(0,A.jsxs)(A.Fragment,{children:[l!==null&&(0,A.jsx)(dq,{invited:l.link,kind:l.kind,onClose:()=>u(null)}),(0,A.jsx)(Nm,{children:d}),a!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`People`,meta:[`${y(`active`)} active`,y(`invited`)>0&&`${y(`invited`)} invited`,y(`disabled`)>0&&`${y(`disabled`)} disabled`].filter(Boolean).join(` · `),action:s?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>c(!0),children:`Invite someone`})}),s&&(0,A.jsx)(fq,{onInvite:async e=>{await g(e)&&c(!1)},onClose:()=>c(!1),onRoles:()=>m(`roles`)}),a.length===0?(0,A.jsx)(Mm,{children:`Nobody is a member yet: the org's machine key alone opens its doors. Invite the first person.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,labels:[`Name`,`Email`,`Role`,`Agents`,`Production`,`Status>`,``]}),a.map(e=>(0,A.jsx)($K,{member:e,onChange:t=>h(e.id,t),onResend:async()=>{await g({email:e.email,name:e.name,role:e.role,agents:e.agents,production:e.production})},onReset:()=>v(e.id),onRemove:()=>_(e.id),yourself:e.id===t},e.id))]})]})]}),i===`roles`&&(0,A.jsx)(rq,{}),i===`sso`&&(0,A.jsx)(aq,{})]})}function dq({invited:e,kind:t,onClose:n}){let r=mq(e.token),[i,a]=(0,D.useState)(!1);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:t===`reset`?`A new password for ${e.member.name}`:`${e.member.name} is invited`,meta:`copy it now: the table keeps the fingerprint, and it is never shown again`,children:(0,A.jsxs)(`span`,{className:`team-link-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>a(!0))},children:i?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:n,children:`Done`})]})}),(0,A.jsx)(`pre`,{className:`ui-code`,children:r}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:t===`reset`?`One use · dies ${e.expires_at} · hand it to them: it opens the card where they choose a new password. Any older link of theirs no longer opens.`:`One use · dies ${e.expires_at} · it opens a card where they choose their password and take their first key.`})]})}function fq({onInvite:e,onClose:t,onRoles:n}){let[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(`qa`),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(!1),h=async t=>{t.preventDefault(),m(!0);try{await e({email:r.trim(),name:a.trim(),role:s,agents:l.split(/[\s,]+/).filter(e=>e!==``),production:d})}finally{m(!1)}};return(0,A.jsxs)(`div`,{className:`team-invite`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void h(e),children:[(0,A.jsx)(Wm,{label:`Email`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{placeholder:`name@company.com`,type:`email`,value:r,onChange:e=>i(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Name`,grow:!0,minWidth:150,children:(0,A.jsx)(W,{placeholder:`Full name`,value:a,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Role`,minWidth:130,children:(0,A.jsx)(Hm,{value:s,onChange:e=>c(e.target.value),children:CU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(Wm,{label:`Agents`,minWidth:150,children:(0,A.jsx)(W,{placeholder:`every agent`,value:l,onChange:e=>u(e.target.value)})}),(0,A.jsx)(Wm,{label:`Production`,minWidth:90,children:s===`admin`?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`always`}):(0,A.jsx)(Jm,{on:d,label:`acts in production`,onChange:f})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:p,children:p?`Inviting…`:`Invite`})]}),(0,A.jsxs)(`div`,{className:`team-roles`,children:[`A role is a preset of what their keys open — `,(0,A.jsx)(Bm,{onClick:n,children:`see what each one does`}),(0,A.jsx)(`span`,{className:`team-invite-close`,children:(0,A.jsx)(Bm,{onClick:t,children:`Close`})})]})]})}function pq(e){return e instanceof na?e.message:String(e)}function mq(e){return`${window.location.origin}/invitations/${encodeURIComponent(e)}`}var hq=z({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F()}),gq=z({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F(),calls:F()}),_q=z({rows:R(hq),totals:gq.nullable(),next:F().nullable()});async function vq(e,t=0){return _q.parse(await k(e,`/v1/usage`,{after:t}))}function yq(e){let t=new Map;for(let n of e){let e=t.get(n.call)??{call:n.call,agent:n.agent,at:n.at,calls:1,minutes:0,messages:0,judge_calls:0,cost_eur:0};e.minutes+=n.minutes,e.messages+=n.messages,e.judge_calls+=n.judge_calls,e.cost_eur+=n.cost_eur,e.at=Math.min(e.at,n.at),t.set(n.call,e)}return[...t.values()].sort((e,t)=>t.at-e.at)}function bq(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e)??{name:e,calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0};i.calls+=1,i.minutes+=r.minutes,i.messages+=r.messages,i.judge_calls+=r.judge_calls,i.cost_eur+=r.cost_eur,n.set(e,i)}return[...n.values()]}function xq(e){return bq(e,e=>tg(e.at)).sort((e,t)=>t.name.localeCompare(e.name))}function Sq(e){return bq(e,e=>e.agent).sort((e,t)=>t.cost_eur-e.cost_eur)}function Cq(e){return bq(e,()=>``)[0]??{calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0}}var wq=[{tab:`days`,name:`By day`},{tab:`agents`,name:`By agent`},{tab:`calls`,name:`Call by call`}],Tq=`minmax(0,1.2fr) 70px 80px 90px minmax(0,1fr) 90px`,Eq=`130px 140px minmax(0,1fr) 70px 80px 90px`,Dq=40;function Oq(){let e=j(),t=ug(),[n,r]=Xi(),i=wq.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`days`,[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return(async()=>{try{let n=[],r=0;for(let i=0;i<Dq;i+=1){let i=await vq(e,r);if(t)return;if(n.push(...i.rows),o([...n]),i.next===null)break;r=i.next}}catch(e){t||c(e instanceof na?e.message:String(e))}})(),()=>{t=!0}},[e]);let l=yq(a??[]),u=Cq(l),d=xq(l),f=d.find(e=>e.name===ng().today)?.cost_eur??0,p=t?.budget??null;return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Usage`,lede:`What this org spent: the providers' bill as the call log knows it, never a price of ours.`}),(0,A.jsx)(Nm,{children:s}),a!==null&&(0,A.jsxs)(lh,{min:150,children:[(0,A.jsx)(uh,{size:`small`,label:p===null?`Spent in all`:`Spent this month`,value:Yh(p===null?u.cost_eur:p.spent_eur_month),of:p!==null&&p.limit_eur!==null?`of ${Yh(p.limit_eur)}`:void 0,accent:!0}),(0,A.jsx)(uh,{size:`small`,label:`Today`,value:Yh(f)}),(0,A.jsx)(uh,{size:`small`,label:`Calls`,value:u.calls}),(0,A.jsx)(uh,{size:`small`,label:`Minutes`,value:u.minutes.toFixed(1)}),(0,A.jsx)(uh,{size:`small`,label:`Per call`,value:u.calls===0?`—`:Yh(u.cost_eur/u.calls)}),(0,A.jsx)(uh,{size:`small`,label:`Per minute`,value:u.minutes===0?`—`:Yh(u.cost_eur/u.minutes)})]}),(0,A.jsx)(yh,{label:`Usage`,tabs:wq,on:i,onPick:e=>r(e===`days`?{}:{tab:e})}),a!==null&&l.length===0&&(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`Nothing metered yet: the first call to end writes the first row.`})}),l.length>0&&i!==`calls`&&(0,A.jsx)(kq,{label:i===`days`?`Day`:`Agent`,groups:i===`days`?d:Sq(l)}),l.length>0&&i===`calls`&&(0,A.jsxs)(V,{children:[(0,A.jsx)(dh,{columns:Eq,labels:[`Started`,`Agent`,`Call`,`Min>`,`Messages>`,`Cost>`]}),l.map(e=>(0,A.jsxs)(fh,{columns:Eq,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:Qh(e.at)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(Wi,{to:`/sessions/${e.call}`,className:`usage-call ui-clip`,children:e.call}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.messages}),(0,A.jsx)(`span`,{className:`usage-cost`,children:Yh(e.cost_eur)})]},e.call)),(0,A.jsx)(jm,{children:(0,A.jsxs)(`span`,{children:[l.length,` calls`,u.judge_calls>0&&` · ${u.judge_calls} judge calls`,` · a call's judging is folded into its line`]})})]})]})}function kq({label:e,groups:t}){let n=Math.max(...t.map(e=>e.cost_eur),0);return(0,A.jsxs)(V,{children:[(0,A.jsx)(dh,{columns:Tq,labels:[e,`Calls>`,`Min>`,`Per call>`,``,`Cost>`]}),t.map(e=>(0,A.jsxs)(fh,{columns:Tq,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.calls}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-faint usage-right`,children:Yh(e.cost_eur/e.calls)}),(0,A.jsx)(`span`,{className:`usage-bar`,children:(0,A.jsx)(oh,{share:n===0?0:e.cost_eur/n})}),(0,A.jsx)(`span`,{className:`usage-cost`,children:Yh(e.cost_eur)})]},e.name))]})}var Aq=z({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()});async function jq(e,t){try{return Aq.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/widget`))}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}async function Mq(e,t,n){return Aq.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/widget`,n))}function Nq(){return`${pm()}/widget/pinecall-widget.js`}var Pq=null;function Fq(){return Pq??=yi(()=>import(Nq()).then(()=>void 0,e=>{throw Pq=null,Error(`the widget did not load from ${Nq()}: ${e instanceof Error?e.message:String(e)}`)}),[]),Pq}function Iq(e,t,n,r){let i=document.createElement(`pinecall-widget`);i.setAttribute(`agent`,n);for(let[e,t]of Object.entries(r))i.setAttribute(e,t);return i.tokenProvider=e=>sa(t,`/v1/tokens`,{agent:n,scope:e,ttl_s:60,metadata:{page:`console preview`,scope:e}}),e.replaceChildren(i),i}var Lq=[`#5b3df5`,`#101014`,`#0f766e`,`#be185d`];function Rq(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(`Assistant`),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(Lq[0]),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!1),[b,x]=(0,D.useState)(null),[S,C]=(0,D.useState)(!1),[w,T]=(0,D.useState)(!1),ee={greeting:b!==null,autostart:b!==null},te=Eh(),ne=b!==null&&(te===null||te.includes(`pipeline`)),re=(0,D.useRef)(null);(0,D.useEffect)(()=>{let n=!1;return jq(e,t).then(e=>{n||e===null||(x(e),e.title!==null&&r(e.title),e.tagline!==null&&s(e.tagline),e.greeting!==null&&d(e.greeting),e.accent!==null&&h(e.accent),p(e.autostart))},()=>void 0),()=>{n=!0}},[e,t]),(0,D.useEffect)(()=>{let n=!1;return mb(e).then(e=>{let r=e.find(e=>e.route.agent===t&&e.route.number!==null)?.route.number;!n&&r!=null&&l(e=>e===``?og(r):e)},()=>void 0),()=>{n=!0}},[e,t]);let E={title:n.trim()===``?null:n.trim(),tagline:o.trim()===``?null:o.trim(),greeting:u.trim()===``?null:u.trim(),accent:m,autostart:f},ie=b!==null&&((b.title??`Assistant`)!==n.trim()||(b.tagline??``)!==o.trim()||(b.greeting??``)!==u.trim()||(b.accent??Lq[0])!==m||b.autostart!==f),ae=async()=>{C(!0),_(null);try{x(await Mq(e,t,E)),T(!0),window.setTimeout(()=>T(!1),1500)}catch(e){_(e instanceof na?e.message:String(e))}finally{C(!1)}};(0,D.useEffect)(()=>{let r=!1;return Fq().then(()=>{if(r||re.current===null)return;let a={name:n,position:`inline`};i&&(a.company=i),o&&(a.tagline=o),c&&(a.phone=c),u&&(a.greeting=u),Iq(re.current,e,t,a).style.setProperty(`--pc-accent`,m),_(null)},e=>{r||_(e instanceof Error?e.message:String(e))}),()=>{r=!0}},[e,t,n,i,o,c,u,m]);let oe=[`agent="${t}"`,`name="${n}"`,i&&`company="${i}"`,o&&`tagline="${o}"`,c&&`phone="${c}"`,ee.greeting&&u&&`greeting="${u}"`,ee.autostart&&f&&`autostart`,`token-url="/pinecall/token"`,`log-url="/pinecall/log"`].filter(Boolean),se=m===Lq[0]?``:`\n<style>pinecall-widget { --pc-accent: ${m}; }</style>`,O=`<script type="module" src="${Nq()}"><\/script>\n<pinecall-widget ${oe.join(`
106
- `)}></pinecall-widget>${se}`,ce=new URLSearchParams({name:n,company:i,tagline:o,phone:c,accent:m,...ee.greeting&&u?{greeting:u}:{}});return(0,A.jsxs)(sh,{width:900,tight:!0,children:[(0,A.jsx)(ch,{title:`Widget`,ledeWidth:620,lede:`The web door for ${t} — one script tag on your site, and the call lands in the same log as the phone.`}),(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Embed`}),(0,A.jsx)(U,{size:`xs`,className:`widget-copy`,onClick:()=>{navigator.clipboard.writeText(O).then(()=>{y(!0),window.setTimeout(()=>y(!1),1500)})},children:v?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:O}),(0,A.jsxs)(`div`,{className:`widget-endpoints`,children:[(0,A.jsx)(`span`,{className:`ui-fixed`,children:`token-url`}),` and `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`log-url`}),` are your site's: the first mints a visit token at `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`/v1/tokens`}),` with a key holding `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`talk`}),`, the second relays the call's log with a key holding `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`calls`}),`. Ready-made PHP and Laravel endpoints:`,` `,(0,A.jsx)(`a`,{href:`https://github.com/pinecall/widget`,target:`_blank`,rel:`noreferrer`,children:`github.com/pinecall/widget`}),`.`]})]}),(0,A.jsxs)(`div`,{className:`widget-split`,children:[(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Appearance`}),ne&&(0,A.jsx)(U,{kind:ie?`primary`:`secondary`,size:`xs`,className:`widget-copy`,disabled:S||!ie,onClick:()=>void ae(),children:S?`Saving…`:w?`Saved`:`Save`})]}),(0,A.jsxs)(`div`,{className:`widget-fields`,children:[(0,A.jsx)(Wm,{label:`Name`,children:(0,A.jsx)(W,{value:n,onChange:e=>r(e.target.value)})}),(0,A.jsx)(Wm,{label:`Tagline`,children:(0,A.jsx)(W,{value:o,placeholder:`the line under the name`,onChange:e=>s(e.target.value)})}),ee.greeting&&(0,A.jsx)(Wm,{label:`Greeting`,children:(0,A.jsx)(W,{value:u,placeholder:`what the widget says before the call starts`,onChange:e=>d(e.target.value)})}),(0,A.jsxs)(`div`,{className:`widget-pair`,children:[(0,A.jsx)(Wm,{label:`Company`,children:(0,A.jsx)(W,{value:i,placeholder:`whose agent it is`,onChange:e=>a(e.target.value)})}),(0,A.jsx)(Wm,{label:`Phone`,children:(0,A.jsx)(W,{value:c,placeholder:`the number it answers, if it has one`,onChange:e=>l(e.target.value)})})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`widget-accent-label`,children:`Accent`}),(0,A.jsx)(`div`,{className:`widget-accents`,role:`group`,"aria-label":`accent`,children:(Lq.includes(m)?Lq:[...Lq,m]).map(e=>(0,A.jsx)(`button`,{type:`button`,className:`widget-accent`,style:{background:e,boxShadow:e===m?`0 0 0 2px var(--on-accent),0 0 0 4px ${e}`:void 0},onClick:()=>h(e),"aria-label":e,"aria-pressed":e===m},e))})]}),ee.autostart&&(0,A.jsxs)(`div`,{className:`widget-toggle`,children:[(0,A.jsx)(`span`,{className:`widget-toggle-label`,children:`Open with the microphone ready`}),(0,A.jsx)(Jm,{on:f,onChange:p,label:`Open with the microphone ready`})]})]})]}),(0,A.jsxs)(`div`,{className:`widget-preview`,children:[(0,A.jsx)(`div`,{className:`widget-preview-label`,children:`Preview`}),(0,A.jsx)(`div`,{className:`widget-stage`,ref:re}),(0,A.jsx)(Nm,{children:g}),(0,A.jsx)(Wi,{className:`widget-open`,to:`/a/${t}/widget/preview?${ce.toString()}`,target:`_blank`,children:`Open on a blank page ↗`})]})]})]})}function zq(){let e=j(),t=Sr().agent??``,[n]=Xi(),[r,i]=(0,D.useState)(null),a=(0,D.useRef)(null);return(0,D.useEffect)(()=>{let r=!1;return Fq().then(()=>{if(r||a.current===null)return;let i={};for(let e of[`name`,`company`,`tagline`,`phone`,`greeting`]){let t=n.get(e);t&&(i[e]=t)}let o=Iq(a.current,e,t,i),s=n.get(`accent`);s&&o.style.setProperty(`--pc-accent`,s)},e=>{r||i(e instanceof Error?e.message:String(e))}),()=>{r=!0}},[e,t,n]),(0,A.jsxs)(`div`,{className:`widget-blank`,children:[(0,A.jsx)(`div`,{ref:a}),(0,A.jsxs)(`span`,{className:`widget-blank-mark`,children:[`pinecall · `,t,` · preview`]}),r!==null&&(0,A.jsx)(`p`,{className:`widget-blank-refused`,children:r})]})}function Bq({agent:e}){let{agents:t,live:n}=Xy(),r=Eh(),i=t.find(t=>t.slug===e),a=n.filter(t=>t.agent===e).length,o=xm(bm).filter(e=>r===null||Qy(r,e.key));return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`agenthead`,children:[(0,A.jsxs)(`div`,{className:`agenthead-name`,children:[(0,A.jsx)(eh,{tone:i===void 0?void 0:`green`}),(0,A.jsx)(`span`,{className:`agenthead-slug`,children:e}),a>0?(0,A.jsx)(`span`,{className:`agenthead-status ui-pill-green`,children:a===1?`on a call`:`on ${a} calls`}):i!==void 0&&(0,A.jsx)(`span`,{className:`agenthead-status ui-pill-muted`,children:`idle`})]}),(0,A.jsx)(`span`,{className:`agenthead-doors`,children:i?.channels.join(` · `)||`no doors`})]}),(0,A.jsx)(`nav`,{className:`agenttabs`,"aria-label":`${e}'s screens`,children:o.map(t=>(0,A.jsx)(Gi,{to:`/a/${e}/${t.path}`,className:({isActive:e})=>e?`agenttab agenttab-on`:`agenttab`,children:t.name},t.key))})]})}var Vq=/^call_[\w+-]{6,}$/,Hq=40;function Uq({agent:e,onClose:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(0),{agents:o,lines:s,operator:c}=Xy(),l=Eh(),u=vr(),d=(0,D.useRef)(null);(0,D.useEffect)(()=>d.current?.focus(),[]);let f=(0,D.useMemo)(()=>{let t=e=>l===null||Qy(l,e),r=n.trim().toLowerCase(),i=[];if(Vq.test(n.trim())){let e=s.find(e=>e.call===n.trim());i.push({group:`Open`,label:n.trim(),sub:e?.agent??`by its id`,to:`/sessions/${n.trim()}`})}for(let e of xm(vm).filter(e=>t(e.key)))i.push({group:`Screens`,label:e.name,sub:``,to:`/${e.path}`});for(let e of xm(ym,fm,c===!0))i.push({group:`Box`,label:e.name,sub:``,to:`/${e.path}`});for(let e of o)i.push({group:`Agents`,label:e.slug,sub:e.channels.join(` · `),to:`/a/${e.slug}/talk`});let a=e===``?o[0]?.slug:e;if(a!==void 0)for(let e of xm(bm).filter(e=>t(e.key)))i.push({group:`${a}`,label:e.name,sub:a,to:`/a/${a}/${e.path}`});for(let e of s){let t=e.caller?.name??e.from??``;i.push({group:`Sessions`,label:e.call,sub:[e.agent,e.channel,t,e.outcome].filter(Boolean).join(` · `),to:`/sessions/${e.call}`})}return r===``?i.filter(e=>e.group!==`Sessions`).slice(0,Hq):i.filter(e=>`${e.label} ${e.sub}`.toLowerCase().includes(r)).slice(0,Hq)},[n,o,s,e,l,c]);(0,D.useEffect)(()=>a(0),[n]);let p=e=>{e!==void 0&&(t(),u(e.to))},m=e=>{e.key===`Escape`&&t(),e.key===`ArrowDown`&&(e.preventDefault(),a(e=>Math.min(f.length-1,e+1))),e.key===`ArrowUp`&&(e.preventDefault(),a(e=>Math.max(0,e-1))),e.key===`Enter`&&p(f[i])},h=``;return(0,A.jsx)(`div`,{className:`palette-veil`,onMouseDown:t,children:(0,A.jsxs)(`div`,{className:`palette`,role:`dialog`,"aria-label":`Search`,onMouseDown:e=>e.stopPropagation(),children:[(0,A.jsxs)(`div`,{className:`palette-input-row`,children:[(0,A.jsx)(Zm,{name:`search`,size:16}),(0,A.jsx)(`input`,{ref:d,className:`palette-input`,placeholder:`Search a screen, an agent, a session id, a number or an outcome`,value:n,onChange:e=>r(e.target.value),onKeyDown:m})]}),(0,A.jsxs)(`div`,{className:`palette-list`,children:[f.length===0&&(0,A.jsx)(`div`,{className:`palette-none`,children:`Nothing here matches — the sessions searched are the ones the floor has listed.`}),f.map((e,t)=>{let n=e.group===h?null:e.group;return h=e.group,(0,A.jsxs)(`div`,{children:[n!==null&&(0,A.jsx)(`div`,{className:`palette-group`,children:n}),(0,A.jsxs)(`button`,{type:`button`,className:t===i?`palette-item palette-item-on`:`palette-item`,onMouseEnter:()=>a(t),onClick:()=>p(e),children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:e.label}),e.sub!==``&&(0,A.jsx)(`span`,{className:`palette-item-sub`,children:e.sub})]})]},`${e.group}:${e.to}`)})]})]})})}var Wq=3,Gq=5e3;function Kq(){let{live:e,lines:t}=Xy(),n=vr(),r=gr().pathname,i=(0,D.useRef)(null),[a,o]=(0,D.useState)([]),s=Yq(a.length>0);(0,D.useEffect)(()=>{if(i.current===null){if(t.length===0&&e.length===0)return;i.current=new Set(e.map(e=>e.call));return}let n=i.current,r=e.filter(e=>!n.has(e.call)&&!VB(e.call));e.forEach(e=>n.add(e.call)),r.forEach(e=>n.add(e.call)),o(e=>{let n=e.map(e=>{let n=t.find(t=>t.call===e.call);return n===void 0?e:{...e,line:n,ended:!n.live}});return[...r.map(e=>({call:e.call,line:e,ended:!1})),...n].slice(0,Wq)})},[e,t]),(0,D.useEffect)(()=>{if(!a.some(e=>e.ended))return;let e=window.setTimeout(()=>o(e=>e.filter(e=>!e.ended)),Gq);return()=>window.clearTimeout(e)},[a]);let c=e=>o(t=>t.filter(t=>t.call!==e)),l=a.filter(e=>r!==`/live/${e.call}`);return l.length===0?null:(0,A.jsx)(`div`,{className:`ring-stack`,role:`region`,"aria-label":`Calls coming in`,"aria-live":`polite`,children:l.map(e=>(0,A.jsxs)(`div`,{className:e.ended?`ring ring-ended`:`ring`,children:[(0,A.jsxs)(`button`,{type:`button`,className:`ring-body`,onClick:()=>{c(e.call),n(`/live/${e.call}`)},children:[(0,A.jsx)(`span`,{className:e.ended?`ring-icon ring-icon-ended`:`ring-icon`,"aria-hidden":!0,children:(0,A.jsx)(Jq,{})}),(0,A.jsxs)(`span`,{className:`ring-words`,children:[(0,A.jsxs)(`span`,{className:`ring-top`,children:[(0,A.jsx)(`span`,{className:`ring-kicker`,children:qq(e)}),!e.ended&&(0,A.jsx)(`span`,{className:`ring-watch`,children:`Watch live →`})]}),(0,A.jsx)(`span`,{className:`ring-who`,children:sg(e.line)}),(0,A.jsxs)(`span`,{className:`ring-sub`,children:[e.line.agent,e.line.channel!==null&&` · ${e.line.channel}`,e.line.direction===`outbound`&&` · outbound`,!e.ended&&e.line.started_at!==null&&` · ${Jh(e.line.started_at,s)}`]})]})]}),(0,A.jsx)(`button`,{type:`button`,className:`ring-close`,"aria-label":`Dismiss`,onClick:()=>c(e.call),children:`×`})]},e.call))})}function qq(e){return e.ended?`Call ended`:e.line.direction===`outbound`?`Calling out`:e.line.channel===`web`?`New conversation`:e.line.channel===`whatsapp`?`New WhatsApp chat`:e.line.status===`active`?`New call · answered`:`New call ringing`}function Jq(){return(0,A.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z`})})}function Yq(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}var Xq=[{group:`gateway`,label:fm===`local`?`Sandbox`:`Gateway`},{group:`settings`,label:`Settings`},{group:`box`,label:`Box`}];function Zq({agent:e,onSearch:t}){let[n,r]=(0,D.useState)(!1),i=Eh(),a=wh(),{agents:o,live:s,lines:c,here:l,insights:u,operator:d}=Xy(),f=e=>i===null||Qy(i,e.key),p=a?.name??a?.label??``,m=l?.role??(a===null?``:a.subject===null||a.subject===void 0?`a machine's key`:``),h=e=>e.key===`agents`&&o.length>0?{text:String(o.length),live:!1}:e.key===`live`&&s.length>0?{text:`${s.length} live`,live:!0}:e.key===`sessions`&&u!==null?{text:String(u.sessions_total),live:!1}:e.key===`sessions`&&c.length>0?{text:c.length>=200?`200+`:String(c.length),live:!1}:null;return(0,A.jsxs)(`aside`,{className:n?`side side-folded`:`side`,"aria-label":`Screens`,children:[(0,A.jsx)($q,{}),(0,A.jsx)(`div`,{className:`side-search-wrap`,children:(0,A.jsxs)(`button`,{type:`button`,className:`side-search`,onClick:t,title:`Search`,children:[(0,A.jsx)(Zm,{name:`search`,size:15}),(0,A.jsx)(`span`,{className:`side-label`,children:`Search`}),(0,A.jsx)(`span`,{className:`side-kbd`,children:`⌘K`})]})}),(0,A.jsxs)(`nav`,{className:`side-nav`,children:[(0,A.jsx)(`div`,{className:`side-group side-group-first`,children:`Agents`}),o.length===0&&(0,A.jsx)(`div`,{className:`side-none side-name`,children:`none held here`}),o.map(t=>{let n=s.some(e=>e.agent===t.slug),r=t.slug===e;return(0,A.jsxs)(Gi,{to:`/a/${t.slug}/talk`,title:t.slug,className:r?`side-link side-link-on`:`side-link`,children:[(0,A.jsx)(`span`,{className:n&&!r?`side-icon side-icon-live`:`side-icon`,children:(0,A.jsx)(Zm,{name:`bot`})}),(0,A.jsx)(`span`,{className:`side-name side-name-agent`,children:t.slug}),n&&(0,A.jsx)(`span`,{className:`side-badge side-badge-live`,children:`live`})]},t.slug)}),Xq.map(({group:t,label:n})=>{let r=xm([...vm,...ym],fm,d===!0).filter(e=>e.group===t&&f(e));return r.length===0?null:(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`side-group`,children:n}),r.map(t=>{let n=h(t);return(0,A.jsxs)(Gi,{to:`/${t.path}`,end:t.path===``,title:t.name,className:({isActive:t})=>t&&e===``?`side-link side-link-on`:`side-link`,children:[(0,A.jsx)(`span`,{className:`side-icon`,children:t.icon!==void 0&&(0,A.jsx)(Zm,{name:t.icon})}),(0,A.jsx)(`span`,{className:`side-name`,children:t.name}),n!==null&&(0,A.jsx)(`span`,{className:n.live?`side-badge side-badge-live`:`side-badge`,children:n.text})]},t.key)})]},t)})]}),(0,A.jsxs)(`div`,{className:`side-foot`,children:[(0,A.jsxs)(`div`,{className:`side-user`,title:p,children:[(0,A.jsx)(`span`,{className:`side-user-avatar`,children:ih(p||(a===null?`?`:Th(a)))}),(0,A.jsxs)(`span`,{className:`side-label`,children:[(0,A.jsx)(`span`,{className:`side-user-name`,children:p||`—`}),(0,A.jsx)(`span`,{className:`side-user-role`,children:Qq(m)})]})]}),(0,A.jsx)(`button`,{type:`button`,className:`side-fold`,onClick:()=>r(!n),title:n?`Open the sidebar`:`Collapse the sidebar`,children:(0,A.jsx)(Zm,{name:`panel`,size:15})})]})]})}function Qq(e){return e===``?``:e.charAt(0).toUpperCase()+e.slice(1)}function $q(){let e=wh(),{agents:t,orgs:n}=Xy(),{moveTo:r}=kh(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!1),u=(0,D.useRef)(null),d=gr().pathname;(0,D.useEffect)(()=>a(!1),[d]),(0,D.useEffect)(()=>{if(!i)return;let e=e=>{u.current!==null&&!u.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let f=e===null?``:Th(e),p=fm===`hosted`&&n!==null&&n.length>1,m=async e=>{l(!0),s(null);try{await r(e)}catch(e){s(e instanceof na?e.message:String(e)),l(!1)}};return(0,A.jsxs)(`div`,{ref:u,className:`side-workspace-wrap`,children:[(0,A.jsxs)(`button`,{type:`button`,className:`side-workspace`,onClick:()=>p&&a(!i),title:f,"aria-expanded":i,children:[(0,A.jsx)(`span`,{className:`side-tile`,children:ih(f||`?`).slice(0,1)}),(0,A.jsxs)(`span`,{className:`side-label`,children:[(0,A.jsx)(`span`,{className:`side-org`,children:f||`…`}),(0,A.jsxs)(`span`,{className:`side-org-sub`,children:[e?.visiting===!0?`visiting as operator · `:``,t.length,` `,t.length===1?`agent`:`agents`]})]}),(0,A.jsx)(`span`,{className:`side-caret`,children:`▾`})]}),i&&n!==null&&(0,A.jsxs)(`div`,{className:`side-orgs`,role:`menu`,children:[[{label:`Your organizations`,rows:n.filter(e=>e.member!==!1)},{label:`Every other org on this box · as operator`,rows:n.filter(e=>e.member===!1)}].filter(e=>e.rows.length>0).map(e=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`side-orgs-label`,children:e.label}),e.rows.map(e=>(0,A.jsxs)(`button`,{type:`button`,className:`side-org-row`,disabled:c||e.here,onClick:()=>void m(e.org),children:[(0,A.jsx)(`span`,{className:`side-tile`,children:ih(e.slug??e.name??e.org).slice(0,1)}),(0,A.jsx)(`span`,{className:`ui-clip`,children:e.slug??e.name??e.org}),(0,A.jsx)(`span`,{className:`side-org-role`,children:e.here?`here`:e.role})]},e.org))]},e.label)),o!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,style:{padding:`6px 8px`},children:o})]})]})}var eJ=new Set([`talk`,`chat`,`dev-chat`,`calls`,`sessions`,`pipeline`,`knowledge`,`memory`,`evals`,`widget`]),tJ=`http://localhost:4100`;function nJ({agent:e}){let t=wh(),n=Gh(t),{world:r,corner:i,lookInto:a}=kh(),{held:o,agentsLoaded:s}=Xy(),[c,l]=(0,D.useState)(!1),u=vr(),{pathname:d}=gr(),f=(0,D.useRef)(null),p=d.split(`/`).filter(Boolean),m=e!==``&&eJ.has(p[2]??``)?p[2]:`talk`;(0,D.useEffect)(()=>l(!1),[d]),(0,D.useEffect)(()=>{if(!c)return;let e=e=>{f.current!==null&&!f.current.contains(e.target)&&l(!1)},t=e=>{e.key===`Escape`&&l(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let h=t?.name??t?.label??``,g=t===null?`this org`:Th(t),_=r===`production`,v=!_&&t?.scopes.includes(`team`)===!0,y=e=>e.holder?.holder??null,b=e=>_?y(e)===null:y(e)!==null&&(y(e)===n||v),x=t=>t.slug===e&&(_?y(t)===null:y(t)===(i??n)),S=e=>{let t=y(e);return t===null?_?`${g} · deployed on the box`:`${g} · shared`:t===n?`${h||`you`} · you`:`${e.holder?.name??t} · theirs`},C=[...o].sort((e,t)=>e.slug.localeCompare(t.slug)||Number(Vh(e,n))-Number(Vh(t,n))),w=i===null?void 0:o.find(e=>y(e)===i),T=()=>{let e=fm===`hosted`?tJ:pm();window.open(`${e}${d}`,`_blank`,`noopener`)};return(0,A.jsxs)(`div`,{ref:f,style:{position:`relative`},children:[(0,A.jsxs)(`button`,{type:`button`,className:c?`switch-trigger switch-trigger-open`:`switch-trigger`,onClick:()=>l(!c),"aria-expanded":c,"aria-haspopup":`dialog`,children:[(0,A.jsx)(eh,{tone:_?`green`:`amber`}),(0,A.jsx)(`span`,{className:`switch-agent`,children:e===``?`choose an agent`:e}),(0,A.jsx)(Qm,{tone:_?`green`:`amber`,children:r}),t!==null&&(0,A.jsx)(ah,{name:h||g,tint:`violet`,size:20}),(0,A.jsx)(`span`,{className:`switch-caret`,"aria-hidden":!0,children:`▾`})]}),c&&(0,A.jsxs)(`div`,{className:`switch-panel`,role:`dialog`,"aria-label":`what this console is looking at`,children:[t!==null&&(0,A.jsxs)(`div`,{className:`switch-who`,children:[(0,A.jsx)(ah,{name:h||g,tint:`violet`,size:36}),(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`switch-who-name`,children:h||`an org's key`}),(0,A.jsxs)(`div`,{className:`switch-who-sub`,children:[g,` · key `,t.key_id]})]})]}),i!==null&&(0,A.jsxs)(`div`,{className:`switch-looking`,children:[(0,A.jsxs)(`span`,{style:{flex:1},children:[`Looking at `,(0,A.jsx)(`b`,{children:w?.holder?.name??i}),`'s copy`]}),(0,A.jsx)(`button`,{type:`button`,className:`ui-text-action`,onClick:()=>a(null),children:`Back to yours`})]}),(0,A.jsxs)(`div`,{className:`switch-where`,children:[(0,A.jsx)(rJ,{}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`switch-label`,children:`Environment`}),(0,A.jsxs)(`div`,{className:`switch-choices`,children:[(0,A.jsx)(qm,{on:_,onClick:_?void 0:T,children:`production`}),(0,A.jsx)(qm,{on:!_,onClick:_?T:void 0,children:`sandbox`})]}),(0,A.jsx)(`div`,{className:`switch-note`,children:_?(0,A.jsxs)(A.Fragment,{children:[`Your sandbox copies are watched on your machine: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall serve`}),`, then sandbox.`]}):(0,A.jsx)(A.Fragment,{children:`Production is watched on the gateway's console, signed in to.`})})]})]}),(0,A.jsxs)(`div`,{className:`switch-agents`,children:[(0,A.jsxs)(`div`,{className:`switch-label`,children:[`agents in `,g,` · `,r]}),s&&C.length===0&&(0,A.jsx)(`div`,{className:`switch-empty`,children:fm===`local`?(0,A.jsxs)(A.Fragment,{children:[`Nothing is running here. `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in a project puts its agents on this list.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing is running in production: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start --prod`}),` on your server holds it, on a server token.`]})}),(0,A.jsx)(`div`,{className:`switch-list`,children:C.map(t=>{let r=y(t),i=b(t),o=x(t);return(0,A.jsxs)(`button`,{type:`button`,className:o?`switch-card switch-card-here`:`switch-card`,disabled:!i,title:i?void 0:`their copy: it answers them, and they open it from their own console`,onClick:()=>{l(!1),_||a(r===n?null:r),t.slug!==e&&u(`/a/${t.slug}/${m}`)},children:[(0,A.jsx)(eh,{tone:`green`}),(0,A.jsxs)(`span`,{style:{minWidth:0,flex:1},children:[(0,A.jsx)(`span`,{className:`switch-card-name`,children:t.slug}),(0,A.jsxs)(`span`,{className:`switch-card-sub`,children:[S(t),` · `,t.channels.join(` · `)||`no doors`]})]}),(0,A.jsx)(`span`,{className:`switch-card-open`,children:o?`Viewing`:i?`Open`:`Theirs`})]},`${t.slug}:${r??`org`}`)})})]})]})]})}function rJ(){let{orgs:e}=Xy(),{moveTo:t}=kh(),[n,r]=(0,D.useState)(!1),[i,a]=(0,D.useState)(null);if(fm!==`hosted`||e===null||e.length<2)return null;let o=async e=>{r(!0),a(null);try{await t(e)}catch(e){a(e instanceof na?e.message:String(e)),r(!1)}};return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`switch-label`,children:`Organization`}),(0,A.jsx)(`div`,{className:`switch-choices`,children:e.map(e=>(0,A.jsx)(qm,{on:e.here,disabled:n,title:e.member===!1?`as the box's operator`:e.role,onClick:()=>!e.here&&void o(e.org),children:e.slug??e.name??e.org},e.org))}),i!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,style:{marginTop:6},children:i})]})}function iJ(e,t){let n=e.split(`/`).filter(Boolean);if(t!==``){let e=bm.find(e=>e.path===n[2]);return e===void 0?`Talk`:e.key===`sessions`&&n[3]!==void 0?`Session`:e.name}if(n[0]===`cli`)return`Sign in a terminal`;if(n[0]===`box`){let e=ym.find(e=>e.path===`box/${n[1]??``}`);return e===void 0?`Box`:e.key===`box-orgs`&&n[2]!==void 0?`Organization`:e.name}let r=vm.find(e=>e.path===(n[0]??``));return r===void 0?`Home`:r.key===`sessions`&&n[1]!==void 0?`Session`:r.key===`numbers`?`Phone numbers`:r.name}function aJ({agent:e}){let t=wh(),n=dm(),{pathname:r}=gr(),i=e===``?r.startsWith(`/box/`)?`box`:t===null?``:Th(t):e;return(0,A.jsxs)(`header`,{className:`top`,children:[i!==``&&(0,A.jsxs)(`span`,{className:`top-crumb`,children:[i,` /`]}),(0,A.jsx)(`span`,{className:`top-title`,children:iJ(r,e)}),(0,A.jsxs)(`div`,{className:`top-right`,children:[(0,A.jsx)(nJ,{agent:e}),fm===`hosted`&&(0,A.jsx)(`button`,{type:`button`,className:`top-leave`,onClick:n,children:`Sign out`})]})]})}var oJ=`No agent called {agent} is held here`;function sJ(){return(0,A.jsx)(Yy,{children:(0,A.jsx)(cJ,{})})}function cJ(){let e=Sr().agent??``,{agents:t,agentsLoaded:n}=Xy(),[r,i]=(0,D.useState)(!1),a=e!==``&&n&&!t.some(t=>t.slug===e);return(0,D.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),i(e=>!e))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[]),(0,A.jsxs)(`div`,{className:`frame`,children:[(0,A.jsx)(Zq,{agent:a?``:e,onSearch:()=>i(!0)}),(0,A.jsxs)(`div`,{className:`frame-main`,children:[(0,A.jsx)(aJ,{agent:e}),e!==``&&!a&&(0,A.jsx)(Bq,{agent:e}),(0,A.jsx)(`div`,{className:`frame-screen`,children:a?(0,A.jsx)(lJ,{agent:e}):(0,A.jsx)(Zr,{})})]}),(0,A.jsx)(Kq,{}),r&&(0,A.jsx)(Uq,{agent:a?``:e,onClose:()=>i(!1)})]})}function lJ({agent:e}){return(0,A.jsxs)(`p`,{className:`missing`,children:[oJ.replace(`{agent}`,e),fm===`local`?" — no copy of yours is running. Start `pinecall start` in the project, and it appears.":" — nothing by that name is deployed in this org. Check the org you signed in with; a copy you are running yourself is on your own machine, at `pinecall serve`."]})}var uJ={home:(0,A.jsx)(UU,{}),agents:(0,A.jsx)(Fb,{}),live:(0,A.jsx)(pU,{}),sessions:(0,A.jsx)(SU,{}),"org-evals":(0,A.jsx)(dT,{}),"org-memory":(0,A.jsx)(DT,{}),numbers:(0,A.jsx)(PW,{}),phone:(0,A.jsx)(IW,{}),tokens:(0,A.jsx)(JU,{}),providers:(0,A.jsx)(aW,{}),team:(0,A.jsx)(uq,{}),usage:(0,A.jsx)(Oq,{}),lexicon:(0,A.jsx)(tW,{})},dJ={"box-orgs":(0,A.jsx)(LS,{children:(0,A.jsx)(tS,{})}),"box-fleet":(0,A.jsx)(LS,{children:(0,A.jsx)(ax,{})}),"box-routes":(0,A.jsx)(LS,{children:(0,A.jsx)(aS,{})}),"box-usage":(0,A.jsx)(LS,{children:(0,A.jsx)(PS,{})}),"box-settings":(0,A.jsx)(LS,{children:(0,A.jsx)(kS,{})})},fJ={talk:(0,A.jsx)(KB,{}),chat:(0,A.jsx)(QB,{}),devchat:(0,A.jsx)(Iw,{}),calls:(0,A.jsx)(CC,{}),sessions:(0,A.jsx)(oG,{}),settings:(0,A.jsx)(RK,{}),pipeline:(0,A.jsx)(aG,{}),knowledge:(0,A.jsx)(hW,{}),memory:(0,A.jsx)(bW,{}),evals:(0,A.jsx)($V,{}),widget:(0,A.jsx)(Rq,{})},pJ={devchat:(0,A.jsx)(Iw,{}),calls:(0,A.jsx)(CC,{}),sessions:(0,A.jsx)(aK,{})},mJ={live:(0,A.jsx)(pU,{}),sessions:(0,A.jsx)(aK,{})};function hJ(e,t){return xm(e,fm,!0).flatMap(e=>{let n=t[e.key];if(e.path===``)return[{index:!0,element:n}];let r=(t===fJ?pJ:mJ)[e.key];return r===void 0?[{path:e.path,element:n}]:[{path:e.path,element:n},{path:`${e.path}/:call`,element:r}]})}var gJ=Vi([{path:`/`,element:(0,A.jsx)(sJ,{}),children:[...hJ(vm,uJ),...hJ(ym,dJ),...fm===`hosted`?[{path:`box/orgs/:org`,element:(0,A.jsx)(LS,{children:(0,A.jsx)($x,{})})}]:[],...fm===`hosted`?[{path:`cli`,element:(0,A.jsx)(JK,{})}]:[]]},{path:`/a/:agent`,element:(0,A.jsx)(sJ,{}),children:[{index:!0,element:(0,A.jsx)(Xr,{to:`talk`,replace:!0})},...hJ(bm,fJ)]},{path:`/a/:agent/widget/preview`,element:(0,A.jsx)(zq,{})},{path:`*`,element:(0,A.jsx)(Xr,{to:`/`,replace:!0})}],{basename:`/`}),_J=np({version:P(),cloud:L(),signup:L(),min_password:F(),mail:L().optional(),google:L().optional()});async function vJ(e){try{let t=await fetch(new URL(`${e.replace(/\/$/,``)}/.well-known/pinecall`,window.location.origin));return _J.parse(await fa(t))}catch{return{version:``,cloud:!1,signup:!1,min_password:0}}}function yJ({base:e,onSigned:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(()=>new URLSearchParams(window.location.search).get(`refused`)),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!0),b=(0,D.useRef)(``),[x,S]=(0,D.useState)(!1),[C,w]=(0,D.useState)(null),[T,ee]=(0,D.useState)(null),[te,ne]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let t=!1;return Qp(e).then(e=>{t||S(e)}),vJ(e).then(e=>{t||h(e.google===!0)}),()=>{t=!0}},[e]);let re=async()=>{if(ee(null),w(null),i.trim()===``){ee(`Type your work email first: it says which workspace signs you in.`);return}ne(!0);try{let t=await $p(e,i.trim()),n=t[0];t.length===1&&n!==void 0?window.location.assign(em(e,n.slug??n.org)):t.length===0?ee(`No workspace signs in with a provider for that address.`):w(t)}catch(e){ee(e instanceof na?e.message:String(e))}finally{ne(!1)}},E=async()=>{let t=`${i.trim()}\n${o}`;if(i.trim()!==``&&o!==``&&t!==b.current){b.current=t;try{let t=await Yp(e,i.trim(),o);if(t===null){y(!1);return}_(t);let a=t[0];t.length>0&&!t.some(e=>(e.slug??e.org)===n)&&a!==void 0&&r(a.slug??a.org)}catch{_(null)}}},ie=async r=>{r.preventDefault(),l(!0),d(null);try{t(await Up(e,{org:n.trim(),email:i.trim(),password:o}))}catch(e){d(e instanceof na?e.message:String(e))}finally{l(!1)}};return(0,A.jsx)(am,{children:(0,A.jsxs)(`form`,{onSubmit:e=>void ie(e),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`Sign in`}),(0,A.jsx)(`p`,{className:`login-lede`,children:`Use the email and password you were invited with.`}),(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-email`,children:`Email`}),(0,A.jsx)(`input`,{id:`login-email`,className:`login-input`,type:`email`,value:i,onChange:e=>a(e.target.value),autoComplete:`username`,autoFocus:!0,required:!0}),(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-password`,children:`Password`}),(0,A.jsx)(`button`,{type:`button`,className:`login-link`,onClick:()=>p(!f),children:`Forgot password`})]}),(0,A.jsx)(`input`,{id:`login-password`,className:`login-input login-input-secret`,type:`password`,value:o,onChange:e=>s(e.target.value),onBlur:()=>void E(),autoComplete:`current-password`,required:!0}),f&&(0,A.jsx)(`p`,{className:`login-forgot`,children:`Ask an admin of your workspace: from Team they hand you a one-use link where you choose a new password.`}),g!==null&&g.length>0?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-org`,children:`Workspace`}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:(n[0]??`·`).toUpperCase()}),(0,A.jsx)(`select`,{id:`login-org`,className:`login-workspace-input`,value:n,onChange:e=>r(e.target.value),disabled:g.length===1,children:g.map(e=>(0,A.jsx)(`option`,{value:e.slug??e.org,children:e.name??e.slug??e.org},e.org))})]})]}):!v&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-org`,children:`Workspace`}),(0,A.jsx)(`span`,{className:`login-hint`,children:`only if you belong to several`})]}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:(n.trim()[0]??`·`).toUpperCase()}),(0,A.jsx)(`input`,{id:`login-org`,className:`login-workspace-input`,value:n,onChange:e=>r(e.target.value),autoComplete:`organization`,placeholder:`the oldest of yours`})]})]}),(0,A.jsx)(`button`,{className:`login-go`,type:`submit`,disabled:c,children:c?`Signing in…`:`Sign in`}),u!==null&&(0,A.jsx)(`p`,{className:`login-refused`,children:u}),(x||m)&&(0,A.jsxs)(`div`,{className:`login-or`,children:[(0,A.jsx)(`span`,{className:`login-or-line`}),(0,A.jsx)(`span`,{className:`login-or-word`,children:`or`}),(0,A.jsx)(`span`,{className:`login-or-line`})]}),m&&(0,A.jsxs)(`button`,{type:`button`,className:`login-sso login-google`,onClick:()=>window.location.assign(tm(e)),children:[(0,A.jsx)(bJ,{}),`Continue with Google`]}),x&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`button`,{type:`button`,className:`login-sso`,disabled:te,onClick:()=>void re(),children:[(0,A.jsx)(`span`,{className:`login-sso-glyph`}),te?`Looking for your workspace…`:`Continue with SSO`]}),C!==null&&(0,A.jsxs)(`div`,{className:`login-sso-pick`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-sso-org`,children:`Which workspace`}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:`·`}),(0,A.jsxs)(`select`,{id:`login-sso-org`,className:`login-workspace-input`,defaultValue:``,onChange:t=>t.target.value!==``&&window.location.assign(em(e,t.target.value)),children:[(0,A.jsx)(`option`,{value:``,disabled:!0,children:`Choose one…`}),C.map(e=>(0,A.jsx)(`option`,{value:e.slug??e.org,children:e.name??e.slug??e.org},e.org))]})]})]}),T!==null&&(0,A.jsx)(`p`,{className:`login-sso-note`,children:T})]}),(0,A.jsx)(`p`,{className:`login-note`,children:`Invited and no password yet? Open the link in your invitation — that is where you choose one.`})]})})}function bJ(){return(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 48 48`,"aria-hidden":!0,children:[(0,A.jsx)(`path`,{fill:`#EA4335`,d:`M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z`}),(0,A.jsx)(`path`,{fill:`#4285F4`,d:`M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z`}),(0,A.jsx)(`path`,{fill:`#FBBC05`,d:`M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z`}),(0,A.jsx)(`path`,{fill:`#34A853`,d:`M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z`})]})}function xJ({base:e,token:t,onSigned:n}){let[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return vJ(e).then(e=>{t||c(e.min_password)}),()=>{t=!0}},[e]);let p=async i=>{if(i.preventDefault(),r!==a){f(`The two passwords differ.`);return}u(!0),f(null);try{n(await qp(e,t,r))}catch(e){f(e instanceof na?e.message:String(e))}finally{u(!1)}};return(0,A.jsx)(am,{children:(0,A.jsxs)(`form`,{onSubmit:e=>void p(e),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`Choose your password`}),(0,A.jsx)(`p`,{className:`login-lede`,children:`This link came from an invitation, or from an admin resetting your password. It opens once; the password you pick here is the one you sign in with from now on.`}),(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`accept-password`,children:`Password`}),s!==null&&s>0&&(0,A.jsxs)(`span`,{className:`login-hint`,children:[s,` characters at least`]})]}),(0,A.jsx)(`input`,{id:`accept-password`,className:`login-input login-input-secret`,type:`password`,value:r,minLength:s??void 0,onChange:e=>i(e.target.value),autoComplete:`new-password`,autoFocus:!0,required:!0}),(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`accept-again`,children:`Again`}),(0,A.jsx)(`input`,{id:`accept-again`,className:`login-input login-input-secret`,type:`password`,value:a,onChange:e=>o(e.target.value),autoComplete:`new-password`,required:!0}),(0,A.jsx)(`button`,{className:`login-go`,type:`submit`,disabled:l,style:{marginTop:8},children:l?`Joining…`:`Join`}),d!==null&&(0,A.jsx)(`p`,{className:`login-refused`,children:d})]})})}var SJ=document.getElementById(`root`);if(SJ===null)throw Error(`index.html has no #root for the console to mount in`);var CJ=`login`,wJ=/^\/invitations\/([^/]+)\/?$/;function TJ(){let e=wJ.exec(window.location.pathname);return e===null?null:decodeURIComponent(e[1]??``)}var EJ=mm[fm],DJ=``;async function OJ(){if(fm===`local`)return DJ;let e=new URL(window.location.href),t=e.searchParams.get(CJ);if(t!==null){e.searchParams.delete(CJ),window.history.replaceState(null,``,e.toString());try{let e=await Hp(`/`,t);return Tm(e.key),e.key}catch{}}return wm()}function kJ({startingWith:e}){let[t,n]=(0,D.useState)(e),[r,i]=(0,D.useState)(()=>EJ===`sandbox`?Om():null),a=(0,D.useCallback)(e=>{km(e),i(e)},[]);aa(()=>{Em(),n(null)});let o=(0,D.useCallback)(async e=>{if(t===null)return;let n=await Kp({base:`/`,key:t},e);km(null),Tm(n.key),window.location.assign(`/`)},[t]),s=(0,D.useMemo)(()=>({world:EJ,moveTo:o,corner:r,lookInto:a}),[o,r,a]),c=(0,D.useMemo)(()=>({base:`/`,key:t??``,corner:r,...fm===`hosted`?{world:EJ}:{}}),[t,r]),l=(0,D.useCallback)(()=>{Em(),km(null),i(null),n(null)},[]),u=e=>{Tm(e.key),n(e.key)};if(t===null){if(fm===`local`)return(0,A.jsx)(cm,{});let e=TJ();return e===null?(0,A.jsx)(yJ,{base:`/`,onSigned:u}):(0,A.jsx)(xJ,{base:`/`,token:e,onSigned:e=>{window.history.replaceState(null,``,`/`),u(e)}})}return(0,A.jsx)(_a,{value:c,children:(0,A.jsx)(Ch,{children:(0,A.jsx)(Oh,{value:s,children:(0,A.jsx)(um,{value:l,children:(0,A.jsx)(Kr,{router:gJ})})})})})}OJ().then(e=>{(0,hi.createRoot)(SJ).render((0,A.jsx)(D.StrictMode,{children:(0,A.jsx)(kJ,{startingWith:e})}))});
103
+ `),knowledge:e.knowledge??``,bases:(e.bases??[]).map(e=>typeof e.k==`number`?`${e.base} ${e.k}`:e.base).join(`
104
+ `),note:``}}function FK(e,t,n){let r=t?{...n}:{},i=n=>{if(t)return;let i=e[n].trim();i!==``&&(r[n]=i)};i(`voice`),i(`tts`),i(`tts_model`),i(`stt`),i(`llm`);let a=e.say.trim(),o=e.reply.trim();a===``?o!==``&&!t?r.greeting={reply:o}:delete r.greeting:r.greeting={say:a};let s=IK(e.remember),c=IK(e.forget);if(s.length>0||c.length>0?r.memory={remember:s,forget:c}:delete r.memory,e.knowledge.trim()===``?delete r.knowledge:r.knowledge=e.knowledge,!t){let t=e.hangup.trim();t!==``&&(r.hangup={when:t});let n={};e.endpointing_ms.trim()!==``&&(n.endpointing_ms=Number(e.endpointing_ms)),e.min_interruption_words.trim()!==``&&(n.min_interruption_words=Number(e.min_interruption_words)),Object.keys(n).length>0&&(r.turn=n);let i=IK(e.bases).map(e=>{let[t,n]=e.split(/\s+/);return n===void 0?{base:t??``}:{base:t??``,k:Number(n)}});i.length>0&&(r.bases=i)}return r}function IK(e){return e.split(`
105
+ `).map(e=>e.trim()).filter(e=>e!==``)}function LK({standing:e,version:t,wordsOnly:n,voices:r,providers:i,saving:a,error:o,onSave:s}){let[c,l]=(0,D.useState)(()=>PK(e)),[u,d]=(0,D.useState)(!1),f=(e,t)=>{d(!1),l({...c,[e]:t})},p=new Set(Rh(i,`tts`).map(e=>e.name)),m=RK(c.tts,p)||NK,h=async r=>{r.preventDefault(),await s(FK(c,n,e),t,c.note.trim()===``?null:c.note.trim()),d(!0)};return(0,A.jsxs)(`form`,{className:`ui-card`,onSubmit:e=>void h(e),children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Set`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:t===null?`the first version of this corner`:`over v${t} — a corner that moved since is told so, never written over`})]}),(0,A.jsxs)(`div`,{className:`set-grid`,children:[!n&&MK.map(e=>(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:e.label}),(0,A.jsx)(VK,{value:c[e.field],offered:Rh(i,e.modality),onChange:t=>f(e.field,t)}),(0,A.jsx)(`p`,{className:`pipe-note`,children:e.note})]},e.field)),!n&&(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Voice`}),m===NK?(0,A.jsxs)(Hm,{value:c.voice,onChange:e=>f(`voice`,e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the runtime's default`}),(r.includes(c.voice)||c.voice===``?r:[c.voice,...r]).map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}):(0,A.jsx)(W,{value:c.voice,spellCheck:!1,placeholder:`${m}'s own voice id`,onChange:e=>f(`voice`,e.target.value)}),(0,A.jsx)(W,{value:c.tts_model,spellCheck:!1,placeholder:`tts model, when the vendor's default is not wanted`,onChange:e=>f(`tts_model`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Greeting`}),(0,A.jsx)(Um,{value:c.say,rows:2,placeholder:`the words said as the call opens, verbatim`,onChange:e=>f(`say`,e.target.value)}),!n&&(0,A.jsx)(Um,{value:c.reply,rows:2,placeholder:`or: what the model reads before it finds its own opening`,onChange:e=>f(`reply`,e.target.value)}),(0,A.jsx)(`p`,{className:`pipe-note`,children:`One of the two: the words themselves, or an instruction. Words also stop a class that improvises its opening.`})]}),!n&&(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Hangup`}),(0,A.jsx)(W,{value:c.hangup,placeholder:`when the model may end the call, in your words`,onChange:e=>f(`hangup`,e.target.value)})]}),!n&&(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Turn`}),(0,A.jsx)(W,{value:c.endpointing_ms,inputMode:`numeric`,placeholder:`endpointing, ms`,onChange:e=>f(`endpointing_ms`,e.target.value)}),(0,A.jsx)(W,{value:c.min_interruption_words,inputMode:`numeric`,placeholder:`words before an interruption counts`,onChange:e=>f(`min_interruption_words`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Remember`}),(0,A.jsx)(Um,{value:c.remember,rows:3,placeholder:`what to keep about a caller, one line each`,onChange:e=>f(`remember`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Never keep`}),(0,A.jsx)(Um,{value:c.forget,rows:3,placeholder:`what is never written down, one line each`,onChange:e=>f(`forget`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Knowledge`}),(0,A.jsx)(Um,{value:c.knowledge,rows:14,spellCheck:!1,placeholder:`what the agent knows by heart, in Markdown: the business as you describe it — hours, prices, what needs an authorisation. Read whole on every call.`,onChange:e=>f(`knowledge`,e.target.value)}),(0,A.jsxs)(`p`,{className:`pipe-note`,children:[c.knowledge.length.toLocaleString(`en-US`),` characters. This is not the documents it searches: those are the Docs tab, attached below as bases.`]})]}),!n&&(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Bases`}),(0,A.jsx)(Um,{value:c.bases,rows:2,placeholder:`bases the agent searches, one per line: name, and k after a space`,onChange:e=>f(`bases`,e.target.value)})]}),(0,A.jsxs)(`div`,{className:`set-field set-field-wide`,children:[(0,A.jsx)(Vm,{children:`Note`}),(0,A.jsx)(W,{value:c.note,placeholder:`why, for the history`,onChange:e=>f(`note`,e.target.value)})]})]}),(0,A.jsxs)(`div`,{className:`pipe-save`,children:[(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:a,children:a?`Saving…`:`Save as the next version`}),o===null?u?(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`Kept. The corners above are the gateway's answer.`}):(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`An empty field gives it back to the runtime's default.`}):(0,A.jsx)(`span`,{className:`pipe-save-error`,children:o})]})]})}function RK(e,t){let n=e.lastIndexOf(`/`);return n>=0?e.slice(0,n):t.has(e)?e:``}function zK(e,t){let n=e.lastIndexOf(`/`);return n>=0?e.slice(n+1):t.has(e)?``:e}function BK(e,t){return e===``?t:t===``?e:`${e}/${t}`}function VK({value:e,offered:t,onChange:n}){let r=new Set(t.map(e=>e.name)),i=RK(e,r),a=zK(e,r);return(0,A.jsxs)(`div`,{className:`set-stage`,children:[(0,A.jsxs)(Hm,{value:i,onChange:e=>n(BK(e.target.value,a)),children:[(0,A.jsx)(`option`,{value:``,children:`the runtime's default`}),t.map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,e.ready?``:` — ${e.standing}`]},e.name))]}),(0,A.jsx)(W,{value:a,spellCheck:!1,placeholder:`the vendor's own default model`,onChange:e=>n(BK(i,e.target.value))})]})}function HK({kept:e,canRollBack:t,onRollBack:n}){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`History`,meta:e===null?void 0:e.holder===``?`the org's own corner`:`corner ${e.holder}`}),e===null?(0,A.jsx)(Mm,{children:`Asking the gateway…`}):e.rows.length===0?(0,A.jsx)(Mm,{children:`Nothing set in this corner yet: the next call runs on what the corner falls back to.`}):e.rows.map((r,i)=>{let a=e.rows[i+1],o=bW(a?.config??{},r.config);return(0,A.jsxs)(`div`,{className:`set-version`,children:[(0,A.jsxs)(`div`,{className:`set-version-head`,children:[(0,A.jsxs)(`b`,{children:[`v`,r.version]}),(0,A.jsxs)(`span`,{className:`ui-cell-faint`,children:[r.author,` · `,Qh(r.set_at)]}),r.note!==null&&(0,A.jsxs)(`span`,{className:`set-version-note`,children:[`“`,r.note,`”`]}),t&&i>0&&(0,A.jsx)(U,{size:`xs`,onClick:()=>void n(r.version),children:`Roll back to this`})]}),o.length>0&&(0,A.jsx)(`div`,{className:`set-version-changes`,children:o.join(` · `)})]},r.version)})]})}var UK=`140px minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)`;function WK(e){return e instanceof Error?e.message:String(e)}function GK(){let e=j(),t=Sr().agent??``,n=Eh(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(null),[h,g]=(0,D.useState)(null),_=n!==null&&!n.includes(`pipeline`),v=fm===`hosted`,y=(0,D.useCallback)(async()=>{i(await pW(e,t)),o(await hW(e,t,v||l))},[e,t,l,v]);(0,D.useEffect)(()=>{let n=!1;return m(null),y().catch(e=>{n||m(WK(e))}),aG(e,t).then(e=>!n&&c(e),e=>{!n&&!(e instanceof na&&(e.status===403||e.status===404))&&m(WK(e))}),()=>{n=!0}},[e,t,y]);let b=async(n,r,a)=>{f(!0),m(null);try{i(await mW(e,t,{config:n,if_version:r,note:a,team:l})),o(await hW(e,t,v||l))}catch(e){m(WK(e))}finally{f(!1)}},x=async n=>{m(null);try{i(await gW(e,t,n,v||l)),o(await hW(e,t,v||l)),g(`v${n} is the newest again, as a new version.`)}catch(e){m(WK(e))}},S=r===null?null:xW(r,v||l);return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Settings`,ledeWidth:680,lede:`What the agent runs on, per world and per corner, a version a row: which vendors and models, how the call opens and ends, how a turn is cut, what is remembered, what it knows by heart, which bases it searches. Set here, in the world this console looks at, and kept forever: every version, who set it, and a roll back.`}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`The three corners`,meta:r===null?void 0:r.world}),r===null?(0,A.jsx)(Mm,{children:p??`Asking the gateway…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:UK,labels:[``,`yours`,`team`,`production`]}),_W.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:UK},children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:vW[e]}),[r.yours,r.team,r.production].map((t,n)=>(0,A.jsx)(`span`,{className:`ui-clip`,children:KK(t,e,n===0)},n))]},e)),(0,A.jsx)(`div`,{className:`ui-card-foot set-corners-foot`,children:[`yours`,`team`,`production`].map(e=>(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:e}),` `,r[e]===null?`nothing set`:qK(r[e])]},e))})]})]}),r!==null&&(0,A.jsxs)(A.Fragment,{children:[!_&&!v&&(0,A.jsx)(`div`,{className:`set-corner-pick`,children:(0,A.jsx)(Ym,{checked:l,onChange:u,children:`Write the team's corner, which every corner falls back to — not only yours`})}),(0,A.jsx)(LK,{standing:S?.config??{},version:S?.version??null,wordsOnly:_,voices:s?.voices??[],providers:s?.providers??[],saving:d,error:p,onSave:b},`${t}-${l}-${S?.version??0}`)]}),(0,A.jsx)(HK,{kept:a,canRollBack:!_,onRollBack:x}),h!==null&&(0,A.jsx)(`div`,{className:`ui-empty`,children:h}),(0,A.jsx)(Nm,{children:p})]})}function KK(e,t,n){return e===null?n?`(team's)`:`—`:yW(e.config,t)??`—`}function qK(e){return`v${e.version} · ${e.author} · ${Qh(e.set_at)}${e.note===null?``:` · “${e.note}”`}`}var JK=z({device:P().nullable(),expires_at:F(),answered:L()}),YK=z({device:P().nullable(),org:P()});function XK(e){return`/v1/login/pairings/${encodeURIComponent(e)}`}async function ZK(e,t){return JK.parse(await k(e,XK(t)))}async function QK(e,t){return YK.parse(await sa(e,XK(t),{})).org}var $K=`c`,eq=`a terminal`;function tq(){let e=j(),[t]=Xi(),n=t.get($K),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);(0,D.useEffect)(()=>{if(n===null)return;let t=!1;return ZK(e,n).then(e=>{t||i(e)},e=>{t||u(e instanceof na?e.message:String(e))}),()=>{t=!0}},[e,n]);let d=async()=>{if(n!==null){o(!0),u(null);try{c(await QK(e,n))}catch(e){u(e instanceof na?e.message:String(e))}finally{o(!1)}}};return n===null?(0,A.jsx)(rq,{title:`No terminal is asking`,lede:nq}):s===null?l!==null&&r===null?(0,A.jsx)(rq,{title:`That link is no good`,lede:l}):(0,A.jsxs)(rq,{title:`Sign this terminal in?`,lede:`A terminal calling itself ${r?.device??eq} asked to be signed in as you. Approve it only if you just ran "pinecall login" on that machine yourself.`,children:[(0,A.jsx)(U,{kind:`primary`,size:`lg`,onClick:()=>void d(),disabled:a||r===null,children:a?`Signing in…`:`Yes, that is my terminal`}),l!==null&&(0,A.jsx)(`p`,{className:`terminal-refused`,children:l})]}):(0,A.jsx)(rq,{title:`Your terminal is signed in`,lede:`Go back to it. You are in ${s}.`})}var nq="Run `pinecall login` in your terminal — it prints a link, and that link comes back here.";function rq({title:e,lede:t,children:n}){return(0,A.jsx)(`div`,{className:`terminal`,children:(0,A.jsxs)(`div`,{className:`terminal-card`,children:[(0,A.jsx)(`img`,{className:`terminal-mark`,src:`/pinecall-mark.png`,alt:``}),(0,A.jsx)(`h1`,{className:`terminal-title`,children:e}),(0,A.jsx)(`p`,{className:`terminal-lede`,children:t}),n]})})}var iq=`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,aq={active:`green`,invited:`amber`,disabled:`gray`};function oq({member:e,onChange:t,onResend:n,onReset:r,onRemove:i,yourself:a=!1}){let[o,s]=(0,D.useState)(!1),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(e.agents.join(` `)),[f,p]=(0,D.useState)(!1),m=async e=>{p(!0);try{await e()}finally{p(!1)}},h=()=>{l(null);let n=u.split(/[\s,]+/).filter(e=>e!==``);n.join(` `)!==e.agents.join(` `)&&m(()=>t({agents:n}))};return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:iq},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.email}),c===`role`?(0,A.jsx)(Hm,{size:`sm`,autoFocus:!0,value:e.role,onBlur:()=>l(null),onChange:e=>{l(null),m(()=>t({role:e.target.value}))},"aria-label":`${e.name}'s role`,children:OU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))}):(0,A.jsx)(`button`,{type:`button`,className:`team-editable team-role`,onClick:()=>l(`role`),title:`Change the role`,children:e.role}),c===`agents`?(0,A.jsx)(W,{size:`sm`,autoFocus:!0,value:u,placeholder:`every agent`,onChange:e=>d(e.target.value),onBlur:h,onKeyDown:t=>{t.key===`Enter`&&h(),t.key===`Escape`&&(d(e.agents.join(` `)),l(null))},"aria-label":`${e.name}'s agents`}):(0,A.jsx)(`button`,{type:`button`,className:`team-editable team-agents ui-clip`,onClick:()=>l(`agents`),title:`Change the agents`,children:e.agents.length===0?`every agent`:e.agents.join(`, `)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.role===`admin`?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`always`}):(0,A.jsx)(Jm,{on:e.production,label:`${e.name} acts in production`,onChange:e=>void m(()=>t({production:e}))})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(Qm,{tone:aq[e.status],children:e.status})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:o?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`team-sure`,children:`Remove for good?`}),(0,A.jsx)(Bm,{danger:!0,disabled:f,onClick:()=>void m(i),children:`Remove`}),(0,A.jsx)(Bm,{disabled:f,onClick:()=>s(!1),children:`Keep`})]}):(0,A.jsxs)(A.Fragment,{children:[e.status===`active`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(r),title:`A one-use link to choose a new password`,children:`Reset password`}),!a&&(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(()=>t({status:`disabled`})),children:`Disable`})]}),e.status===`disabled`&&(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(()=>t({status:`active`})),children:`Bring back`}),e.status===`invited`&&(0,A.jsx)(Bm,{disabled:f,onClick:()=>void m(n),children:`Resend invite`}),!a&&(0,A.jsx)(Bm,{danger:!0,disabled:f,onClick:()=>s(!0),title:`Out of the org for good: every key revoked, the seat freed`,children:`Remove`})]})})]})}var sq={qa:{who:`Reads finished calls and the suites`,opens:`calls · evals`},supervisor:{who:`Sits beside a live call: listens, whispers, takes it over`,opens:`calls · evals · supervise · talk · memory`},manager:{who:`Runs the floor and the org's accounts, never the agent's declaration`,opens:`calls · evals · supervise · talk · memory · numbers · keys · providers · usage · team`},developer:{who:`Writes and runs the agent`,opens:`app · calls · talk · supervise · pipeline · knowledge · memory · evals`},admin:{who:`The org's owner`,opens:`every door`}},cq=[`qa`,`supervisor`,`manager`,`developer`,`admin`],lq=`110px minmax(0,1fr) minmax(0,1.4fr)`;function uq(){return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Roles`,meta:`a preset of what a person's keys open — and where: the sandbox always, production when their switch is on (an admin's always is)`}),(0,A.jsx)(dh,{columns:lq,labels:[`Role`,`Who`,`Opens`]}),cq.map(e=>(0,A.jsxs)(fh,{columns:lq,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:sq[e].who}),(0,A.jsx)(`span`,{className:`ui-cell-faint team-role-opens`,children:sq[e].opens})]},e))]})}var dq=``;function fq(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{let t=!1;return LU(e).then(e=>{t||n(e)},e=>{t||i(hq(e))}),()=>{t=!0}},[e]),t===null)return r===null?null:(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Single sign-on`}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(Nm,{children:r})})]});let l=async()=>{if(!s){c(!0);return}i(null);try{await zU(e),n(await LU(e)),c(!1)}catch(e){i(hq(e))}};return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Single sign-on`,meta:t.configured?`this org's people sign in with its identity provider`:`sign in with Google Workspace, Okta or Entra instead of a password`,children:t.configured&&!a&&(0,A.jsxs)(`span`,{className:`team-link-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>o(!0),children:`Change`}),(0,A.jsx)(U,{size:`xs`,kind:`danger`,onClick:()=>void l(),onBlur:()=>c(!1),children:s?`Remove · sure?`:`Remove`})]})}),t.configured&&!a?(0,A.jsxs)(`div`,{className:`team-sso-values`,children:[(0,A.jsx)(Lm,{label:`Issuer`,children:t.issuer}),(0,A.jsx)(Lm,{label:`Client ID`,children:t.client_id}),(0,A.jsx)(Lm,{label:`Client secret`,children:`kept, and never shown`}),(0,A.jsx)(Lm,{label:`Allowed domains`,children:t.domains.join(`, `)||`—`}),(0,A.jsx)(Lm,{label:`Arriving new`,children:t.role??`nobody: invite first`}),(0,A.jsx)(Lm,{label:`Passwords`,children:t.required?`stopped for this org`:`still work beside it`})]}):(0,A.jsx)(pq,{sso:t,onSaved:e=>{n(e),o(!1)},onCancel:t.configured?()=>o(!1):void 0}),(0,A.jsx)(mq,{uri:t.redirect_uri}),r!==null&&(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(Nm,{children:r})})]})}function pq({sso:e,onSaved:t,onCancel:n}){let r=j(),[i,a]=(0,D.useState)(e.issuer??``),[o,s]=(0,D.useState)(e.client_id??``),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(e.domains.join(` `)),[f,p]=(0,D.useState)(e.role??dq),[m,h]=(0,D.useState)(e.required),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),b=async e=>{e.preventDefault(),_(!0),y(null);try{t(await RU(r,{issuer:i.trim(),client_id:o.trim(),client_secret:c,domains:u.split(/[\s,]+/).filter(e=>e!==``),role:f===dq?null:f,required:m}))}catch(e){y(hq(e))}finally{_(!1)}};return(0,A.jsxs)(`form`,{className:`team-sso-form`,onSubmit:e=>void b(e),children:[(0,A.jsxs)(`div`,{className:`team-sso-grid`,children:[(0,A.jsx)(Wm,{label:`Issuer URL`,children:(0,A.jsx)(W,{type:`url`,placeholder:`https://accounts.google.com`,value:i,onChange:e=>a(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Client ID`,children:(0,A.jsx)(W,{value:o,onChange:e=>s(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Client secret, sent once`,children:(0,A.jsx)(W,{type:`password`,autoComplete:`off`,placeholder:`never shown again`,value:c,onChange:e=>l(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Allowed domains`,children:(0,A.jsx)(W,{placeholder:`company.com other.com`,value:u,onChange:e=>d(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Role for people who arrive new`,children:(0,A.jsxs)(Hm,{value:f,onChange:e=>p(e.target.value),children:[(0,A.jsx)(`option`,{value:dq,children:`nobody: invite first`}),OU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]})}),(0,A.jsxs)(`div`,{className:`team-sso-required`,children:[(0,A.jsx)(`span`,{className:`team-sso-required-words`,children:`Passwords stop working for this org`}),(0,A.jsx)(Jm,{on:m,onChange:h,label:`Passwords stop working for this org`})]})]}),(0,A.jsxs)(`div`,{className:`team-sso-moves`,children:[(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:g,children:g?`Asking the issuer…`:`Save`}),n!==void 0&&(0,A.jsx)(U,{size:`form`,onClick:n,children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`The gateway asks the issuer for its discovery document before it keeps anything.`})]}),(0,A.jsx)(Nm,{children:v})]})}function mq({uri:e}){let[t,n]=(0,D.useState)(!1);return(0,A.jsxs)(`div`,{className:`team-sso-redirect`,children:[(0,A.jsxs)(`div`,{className:`team-sso-redirect-head`,children:[(0,A.jsx)(`span`,{className:`ui-note`,children:`Register this at your identity provider as the redirect URI`}),(0,A.jsx)(U,{size:`xs`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>n(!0))},children:t?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:e})]})}function hq(e){return e instanceof na?e.message:String(e)}var gq=[{tab:`people`,name:`People`},{tab:`roles`,name:`Roles`},{tab:`sso`,name:`Single sign-on`}];function _q(){let e=j(),t=Gh(wh()),[n,r]=Xi(),i=gq.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`people`,[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),p=async()=>o(await jU(e)),m=e=>r(e===`people`?{}:{tab:e});(0,D.useEffect)(()=>{let t=!1;return jU(e).then(e=>{t||o(e)},e=>{t||f(bq(e))}),()=>{t=!0}},[e]);let h=async(t,n)=>{f(null);try{await FU(e,t,n),await p()}catch(e){f(bq(e))}},g=async t=>{f(null);try{return u({link:await MU(e,t),kind:`invitation`}),await p(),!0}catch(e){return f(bq(e)),!1}},_=async t=>{f(null);try{await PU(e,t),await p()}catch(e){f(bq(e))}},v=async t=>{f(null);try{u({link:await NU(e,t),kind:`reset`})}catch(e){f(bq(e))}},y=e=>(a??[]).filter(t=>t.status===e).length;return(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Team`,lede:`The org's people: who they are, what their keys may do, and how they sign in.`}),(0,A.jsx)(yh,{label:`Team`,tabs:gq,on:i,onPick:m}),i===`people`&&(0,A.jsxs)(A.Fragment,{children:[l!==null&&(0,A.jsx)(vq,{invited:l.link,kind:l.kind,onClose:()=>u(null)}),(0,A.jsx)(Nm,{children:d}),a!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`People`,meta:[`${y(`active`)} active`,y(`invited`)>0&&`${y(`invited`)} invited`,y(`disabled`)>0&&`${y(`disabled`)} disabled`].filter(Boolean).join(` · `),action:s?void 0:(0,A.jsx)(U,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>c(!0),children:`Invite someone`})}),s&&(0,A.jsx)(yq,{onInvite:async e=>{await g(e)&&c(!1)},onClose:()=>c(!1),onRoles:()=>m(`roles`)}),a.length===0?(0,A.jsx)(Mm,{children:`Nobody is a member yet: the org's machine key alone opens its doors. Invite the first person.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,labels:[`Name`,`Email`,`Role`,`Agents`,`Production`,`Status>`,``]}),a.map(e=>(0,A.jsx)(oq,{member:e,onChange:t=>h(e.id,t),onResend:async()=>{await g({email:e.email,name:e.name,role:e.role,agents:e.agents,production:e.production})},onReset:()=>v(e.id),onRemove:()=>_(e.id),yourself:e.id===t},e.id))]})]})]}),i===`roles`&&(0,A.jsx)(uq,{}),i===`sso`&&(0,A.jsx)(fq,{})]})}function vq({invited:e,kind:t,onClose:n}){let r=xq(e.token),[i,a]=(0,D.useState)(!1);return(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:t===`reset`?`A new password for ${e.member.name}`:`${e.member.name} is invited`,meta:`copy it now: the table keeps the fingerprint, and it is never shown again`,children:(0,A.jsxs)(`span`,{className:`team-link-moves`,children:[(0,A.jsx)(U,{size:`xs`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>a(!0))},children:i?`Copied`:`Copy`}),(0,A.jsx)(U,{size:`xs`,onClick:n,children:`Done`})]})}),(0,A.jsx)(`pre`,{className:`ui-code`,children:r}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:t===`reset`?`One use · dies ${e.expires_at} · hand it to them: it opens the card where they choose a new password. Any older link of theirs no longer opens.`:`One use · dies ${e.expires_at} · it opens a card where they choose their password and take their first key.`})]})}function yq({onInvite:e,onClose:t,onRoles:n}){let[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(`qa`),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(!1),h=async t=>{t.preventDefault(),m(!0);try{await e({email:r.trim(),name:a.trim(),role:s,agents:l.split(/[\s,]+/).filter(e=>e!==``),production:d})}finally{m(!1)}};return(0,A.jsxs)(`div`,{className:`team-invite`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void h(e),children:[(0,A.jsx)(Wm,{label:`Email`,grow:!0,minWidth:180,children:(0,A.jsx)(W,{placeholder:`name@company.com`,type:`email`,value:r,onChange:e=>i(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(Wm,{label:`Name`,grow:!0,minWidth:150,children:(0,A.jsx)(W,{placeholder:`Full name`,value:a,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(Wm,{label:`Role`,minWidth:130,children:(0,A.jsx)(Hm,{value:s,onChange:e=>c(e.target.value),children:OU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(Wm,{label:`Agents`,minWidth:150,children:(0,A.jsx)(W,{placeholder:`every agent`,value:l,onChange:e=>u(e.target.value)})}),(0,A.jsx)(Wm,{label:`Production`,minWidth:90,children:s===`admin`?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`always`}):(0,A.jsx)(Jm,{on:d,label:`acts in production`,onChange:f})}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:p,children:p?`Inviting…`:`Invite`})]}),(0,A.jsxs)(`div`,{className:`team-roles`,children:[`A role is a preset of what their keys open — `,(0,A.jsx)(Bm,{onClick:n,children:`see what each one does`}),(0,A.jsx)(`span`,{className:`team-invite-close`,children:(0,A.jsx)(Bm,{onClick:t,children:`Close`})})]})]})}function bq(e){return e instanceof na?e.message:String(e)}function xq(e){return`${window.location.origin}/invitations/${encodeURIComponent(e)}`}var Sq=z({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F()}),Cq=z({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F(),calls:F()}),wq=z({rows:R(Sq),totals:Cq.nullable(),next:F().nullable()});async function Tq(e,t=0){return wq.parse(await k(e,`/v1/usage`,{after:t}))}function Eq(e){let t=new Map;for(let n of e){let e=t.get(n.call)??{call:n.call,agent:n.agent,at:n.at,calls:1,minutes:0,messages:0,judge_calls:0,cost_eur:0};e.minutes+=n.minutes,e.messages+=n.messages,e.judge_calls+=n.judge_calls,e.cost_eur+=n.cost_eur,e.at=Math.min(e.at,n.at),t.set(n.call,e)}return[...t.values()].sort((e,t)=>t.at-e.at)}function Dq(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e)??{name:e,calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0};i.calls+=1,i.minutes+=r.minutes,i.messages+=r.messages,i.judge_calls+=r.judge_calls,i.cost_eur+=r.cost_eur,n.set(e,i)}return[...n.values()]}function Oq(e){return Dq(e,e=>tg(e.at)).sort((e,t)=>t.name.localeCompare(e.name))}function kq(e){return Dq(e,e=>e.agent).sort((e,t)=>t.cost_eur-e.cost_eur)}function Aq(e){return Dq(e,()=>``)[0]??{calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0}}var jq=[{tab:`days`,name:`By day`},{tab:`agents`,name:`By agent`},{tab:`calls`,name:`Call by call`}],Mq=`minmax(0,1.2fr) 70px 80px 90px minmax(0,1fr) 90px`,Nq=`130px 140px minmax(0,1fr) 70px 80px 90px`,Pq=40;function Fq(){let e=j(),t=ug(),[n,r]=Xi(),i=jq.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`days`,[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return(async()=>{try{let n=[],r=0;for(let i=0;i<Pq;i+=1){let i=await Tq(e,r);if(t)return;if(n.push(...i.rows),o([...n]),i.next===null)break;r=i.next}}catch(e){t||c(e instanceof na?e.message:String(e))}})(),()=>{t=!0}},[e]);let l=Eq(a??[]),u=Aq(l),d=Oq(l),f=d.find(e=>e.name===ng().today)?.cost_eur??0,p=t?.budget??null;return(0,A.jsxs)(sh,{tight:!0,children:[(0,A.jsx)(ch,{title:`Usage`,lede:`What this org spent: the providers' bill as the call log knows it, never a price of ours.`}),(0,A.jsx)(Nm,{children:s}),a!==null&&(0,A.jsxs)(lh,{min:150,children:[(0,A.jsx)(uh,{size:`small`,label:p===null?`Spent in all`:`Spent this month`,value:Yh(p===null?u.cost_eur:p.spent_eur_month),of:p!==null&&p.limit_eur!==null?`of ${Yh(p.limit_eur)}`:void 0,accent:!0}),(0,A.jsx)(uh,{size:`small`,label:`Today`,value:Yh(f)}),(0,A.jsx)(uh,{size:`small`,label:`Calls`,value:u.calls}),(0,A.jsx)(uh,{size:`small`,label:`Minutes`,value:u.minutes.toFixed(1)}),(0,A.jsx)(uh,{size:`small`,label:`Per call`,value:u.calls===0?`—`:Yh(u.cost_eur/u.calls)}),(0,A.jsx)(uh,{size:`small`,label:`Per minute`,value:u.minutes===0?`—`:Yh(u.cost_eur/u.minutes)})]}),(0,A.jsx)(yh,{label:`Usage`,tabs:jq,on:i,onPick:e=>r(e===`days`?{}:{tab:e})}),a!==null&&l.length===0&&(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`Nothing metered yet: the first call to end writes the first row.`})}),l.length>0&&i!==`calls`&&(0,A.jsx)(Iq,{label:i===`days`?`Day`:`Agent`,groups:i===`days`?d:kq(l)}),l.length>0&&i===`calls`&&(0,A.jsxs)(V,{children:[(0,A.jsx)(dh,{columns:Nq,labels:[`Started`,`Agent`,`Call`,`Min>`,`Messages>`,`Cost>`]}),l.map(e=>(0,A.jsxs)(fh,{columns:Nq,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:Qh(e.at)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(Wi,{to:`/sessions/${e.call}`,className:`usage-call ui-clip`,children:e.call}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.messages}),(0,A.jsx)(`span`,{className:`usage-cost`,children:Yh(e.cost_eur)})]},e.call)),(0,A.jsx)(jm,{children:(0,A.jsxs)(`span`,{children:[l.length,` calls`,u.judge_calls>0&&` · ${u.judge_calls} judge calls`,` · a call's judging is folded into its line`]})})]})]})}function Iq({label:e,groups:t}){let n=Math.max(...t.map(e=>e.cost_eur),0);return(0,A.jsxs)(V,{children:[(0,A.jsx)(dh,{columns:Mq,labels:[e,`Calls>`,`Min>`,`Per call>`,``,`Cost>`]}),t.map(e=>(0,A.jsxs)(fh,{columns:Mq,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.calls}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-faint usage-right`,children:Yh(e.cost_eur/e.calls)}),(0,A.jsx)(`span`,{className:`usage-bar`,children:(0,A.jsx)(oh,{share:n===0?0:e.cost_eur/n})}),(0,A.jsx)(`span`,{className:`usage-cost`,children:Yh(e.cost_eur)})]},e.name))]})}var Lq=z({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()});async function Rq(e,t){try{return Lq.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/widget`))}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}async function zq(e,t,n){return Lq.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/widget`,n))}function Bq(){return`${pm()}/widget/pinecall-widget.js`}var Vq=null;function Hq(){return Vq??=yi(()=>import(Bq()).then(()=>void 0,e=>{throw Vq=null,Error(`the widget did not load from ${Bq()}: ${e instanceof Error?e.message:String(e)}`)}),[]),Vq}function Uq(e,t,n,r){let i=document.createElement(`pinecall-widget`);i.setAttribute(`agent`,n);for(let[e,t]of Object.entries(r))i.setAttribute(e,t);return i.tokenProvider=e=>sa(t,`/v1/tokens`,{agent:n,scope:e,ttl_s:60,metadata:{page:`console preview`,scope:e}}),e.replaceChildren(i),i}var Wq=[`#5b3df5`,`#101014`,`#0f766e`,`#be185d`];function Gq(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(`Assistant`),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(Wq[0]),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!1),[b,x]=(0,D.useState)(null),[S,C]=(0,D.useState)(!1),[w,T]=(0,D.useState)(!1),ee={greeting:b!==null,autostart:b!==null},te=Eh(),ne=b!==null&&(te===null||te.includes(`pipeline`)),re=(0,D.useRef)(null);(0,D.useEffect)(()=>{let n=!1;return Rq(e,t).then(e=>{n||e===null||(x(e),e.title!==null&&r(e.title),e.tagline!==null&&s(e.tagline),e.greeting!==null&&d(e.greeting),e.accent!==null&&h(e.accent),p(e.autostart))},()=>void 0),()=>{n=!0}},[e,t]),(0,D.useEffect)(()=>{let n=!1;return hb(e).then(e=>{let r=e.find(e=>e.route.agent===t&&e.route.number!==null)?.route.number;!n&&r!=null&&l(e=>e===``?og(r):e)},()=>void 0),()=>{n=!0}},[e,t]);let E={title:n.trim()===``?null:n.trim(),tagline:o.trim()===``?null:o.trim(),greeting:u.trim()===``?null:u.trim(),accent:m,autostart:f},ie=b!==null&&((b.title??`Assistant`)!==n.trim()||(b.tagline??``)!==o.trim()||(b.greeting??``)!==u.trim()||(b.accent??Wq[0])!==m||b.autostart!==f),ae=async()=>{C(!0),_(null);try{x(await zq(e,t,E)),T(!0),window.setTimeout(()=>T(!1),1500)}catch(e){_(e instanceof na?e.message:String(e))}finally{C(!1)}};(0,D.useEffect)(()=>{let r=!1;return Hq().then(()=>{if(r||re.current===null)return;let a={name:n,position:`inline`};i&&(a.company=i),o&&(a.tagline=o),c&&(a.phone=c),u&&(a.greeting=u),Uq(re.current,e,t,a).style.setProperty(`--pc-accent`,m),_(null)},e=>{r||_(e instanceof Error?e.message:String(e))}),()=>{r=!0}},[e,t,n,i,o,c,u,m]);let oe=[`agent="${t}"`,`name="${n}"`,i&&`company="${i}"`,o&&`tagline="${o}"`,c&&`phone="${c}"`,ee.greeting&&u&&`greeting="${u}"`,ee.autostart&&f&&`autostart`,`token-url="/pinecall/token"`,`log-url="/pinecall/log"`].filter(Boolean),se=m===Wq[0]?``:`\n<style>pinecall-widget { --pc-accent: ${m}; }</style>`,O=`<script type="module" src="${Bq()}"><\/script>\n<pinecall-widget ${oe.join(`
106
+ `)}></pinecall-widget>${se}`,ce=new URLSearchParams({name:n,company:i,tagline:o,phone:c,accent:m,...ee.greeting&&u?{greeting:u}:{}});return(0,A.jsxs)(sh,{width:900,tight:!0,children:[(0,A.jsx)(ch,{title:`Widget`,ledeWidth:620,lede:`The web door for ${t} — one script tag on your site, and the call lands in the same log as the phone.`}),(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Embed`}),(0,A.jsx)(U,{size:`xs`,className:`widget-copy`,onClick:()=>{navigator.clipboard.writeText(O).then(()=>{y(!0),window.setTimeout(()=>y(!1),1500)})},children:v?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:O}),(0,A.jsxs)(`div`,{className:`widget-endpoints`,children:[(0,A.jsx)(`span`,{className:`ui-fixed`,children:`token-url`}),` and `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`log-url`}),` are your site's: the first mints a visit token at `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`/v1/tokens`}),` with a key holding `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`talk`}),`, the second relays the call's log with a key holding `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`calls`}),`. Ready-made PHP and Laravel endpoints:`,` `,(0,A.jsx)(`a`,{href:`https://github.com/pinecall/widget`,target:`_blank`,rel:`noreferrer`,children:`github.com/pinecall/widget`}),`.`]})]}),(0,A.jsxs)(`div`,{className:`widget-split`,children:[(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Appearance`}),ne&&(0,A.jsx)(U,{kind:ie?`primary`:`secondary`,size:`xs`,className:`widget-copy`,disabled:S||!ie,onClick:()=>void ae(),children:S?`Saving…`:w?`Saved`:`Save`})]}),(0,A.jsxs)(`div`,{className:`widget-fields`,children:[(0,A.jsx)(Wm,{label:`Name`,children:(0,A.jsx)(W,{value:n,onChange:e=>r(e.target.value)})}),(0,A.jsx)(Wm,{label:`Tagline`,children:(0,A.jsx)(W,{value:o,placeholder:`the line under the name`,onChange:e=>s(e.target.value)})}),ee.greeting&&(0,A.jsx)(Wm,{label:`Greeting`,children:(0,A.jsx)(W,{value:u,placeholder:`what the widget says before the call starts`,onChange:e=>d(e.target.value)})}),(0,A.jsxs)(`div`,{className:`widget-pair`,children:[(0,A.jsx)(Wm,{label:`Company`,children:(0,A.jsx)(W,{value:i,placeholder:`whose agent it is`,onChange:e=>a(e.target.value)})}),(0,A.jsx)(Wm,{label:`Phone`,children:(0,A.jsx)(W,{value:c,placeholder:`the number it answers, if it has one`,onChange:e=>l(e.target.value)})})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`widget-accent-label`,children:`Accent`}),(0,A.jsx)(`div`,{className:`widget-accents`,role:`group`,"aria-label":`accent`,children:(Wq.includes(m)?Wq:[...Wq,m]).map(e=>(0,A.jsx)(`button`,{type:`button`,className:`widget-accent`,style:{background:e,boxShadow:e===m?`0 0 0 2px var(--on-accent),0 0 0 4px ${e}`:void 0},onClick:()=>h(e),"aria-label":e,"aria-pressed":e===m},e))})]}),ee.autostart&&(0,A.jsxs)(`div`,{className:`widget-toggle`,children:[(0,A.jsx)(`span`,{className:`widget-toggle-label`,children:`Open with the microphone ready`}),(0,A.jsx)(Jm,{on:f,onChange:p,label:`Open with the microphone ready`})]})]})]}),(0,A.jsxs)(`div`,{className:`widget-preview`,children:[(0,A.jsx)(`div`,{className:`widget-preview-label`,children:`Preview`}),(0,A.jsx)(`div`,{className:`widget-stage`,ref:re}),(0,A.jsx)(Nm,{children:g}),(0,A.jsx)(Wi,{className:`widget-open`,to:`/a/${t}/widget/preview?${ce.toString()}`,target:`_blank`,children:`Open on a blank page ↗`})]})]})]})}function Kq(){let e=j(),t=Sr().agent??``,[n]=Xi(),[r,i]=(0,D.useState)(null),a=(0,D.useRef)(null);return(0,D.useEffect)(()=>{let r=!1;return Hq().then(()=>{if(r||a.current===null)return;let i={};for(let e of[`name`,`company`,`tagline`,`phone`,`greeting`]){let t=n.get(e);t&&(i[e]=t)}let o=Uq(a.current,e,t,i),s=n.get(`accent`);s&&o.style.setProperty(`--pc-accent`,s)},e=>{r||i(e instanceof Error?e.message:String(e))}),()=>{r=!0}},[e,t,n]),(0,A.jsxs)(`div`,{className:`widget-blank`,children:[(0,A.jsx)(`div`,{ref:a}),(0,A.jsxs)(`span`,{className:`widget-blank-mark`,children:[`pinecall · `,t,` · preview`]}),r!==null&&(0,A.jsx)(`p`,{className:`widget-blank-refused`,children:r})]})}function qq({agent:e}){let{agents:t,live:n}=Zy(),r=Eh(),i=t.find(t=>t.slug===e),a=n.filter(t=>t.agent===e).length,o=xm(bm).filter(e=>r===null||$y(r,e.key));return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`agenthead`,children:[(0,A.jsxs)(`div`,{className:`agenthead-name`,children:[(0,A.jsx)(eh,{tone:i===void 0?void 0:`green`}),(0,A.jsx)(`span`,{className:`agenthead-slug`,children:e}),a>0?(0,A.jsx)(`span`,{className:`agenthead-status ui-pill-green`,children:a===1?`on a call`:`on ${a} calls`}):i!==void 0&&(0,A.jsx)(`span`,{className:`agenthead-status ui-pill-muted`,children:`idle`})]}),(0,A.jsx)(`span`,{className:`agenthead-doors`,children:i?.channels.join(` · `)||`no doors`})]}),(0,A.jsx)(`nav`,{className:`agenttabs`,"aria-label":`${e}'s screens`,children:o.map(t=>(0,A.jsx)(Gi,{to:`/a/${e}/${t.path}`,className:({isActive:e})=>e?`agenttab agenttab-on`:`agenttab`,children:t.name},t.key))})]})}var Jq=/^call_[\w+-]{6,}$/,Yq=40;function Xq({agent:e,onClose:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(0),{agents:o,lines:s,operator:c}=Zy(),l=Eh(),u=vr(),d=(0,D.useRef)(null);(0,D.useEffect)(()=>d.current?.focus(),[]);let f=(0,D.useMemo)(()=>{let t=e=>l===null||$y(l,e),r=n.trim().toLowerCase(),i=[];if(Jq.test(n.trim())){let e=s.find(e=>e.call===n.trim());i.push({group:`Open`,label:n.trim(),sub:e?.agent??`by its id`,to:`/sessions/${n.trim()}`})}for(let e of xm(vm).filter(e=>t(e.key)))i.push({group:`Screens`,label:e.name,sub:``,to:`/${e.path}`});for(let e of xm(ym,fm,c===!0))i.push({group:`Box`,label:e.name,sub:``,to:`/${e.path}`});for(let e of o)i.push({group:`Agents`,label:e.slug,sub:e.channels.join(` · `),to:`/a/${e.slug}/talk`});let a=e===``?o[0]?.slug:e;if(a!==void 0)for(let e of xm(bm).filter(e=>t(e.key)))i.push({group:`${a}`,label:e.name,sub:a,to:`/a/${a}/${e.path}`});for(let e of s){let t=e.caller?.name??e.from??``;i.push({group:`Sessions`,label:e.call,sub:[e.agent,e.channel,t,e.outcome].filter(Boolean).join(` · `),to:`/sessions/${e.call}`})}return r===``?i.filter(e=>e.group!==`Sessions`).slice(0,Yq):i.filter(e=>`${e.label} ${e.sub}`.toLowerCase().includes(r)).slice(0,Yq)},[n,o,s,e,l,c]);(0,D.useEffect)(()=>a(0),[n]);let p=e=>{e!==void 0&&(t(),u(e.to))},m=e=>{e.key===`Escape`&&t(),e.key===`ArrowDown`&&(e.preventDefault(),a(e=>Math.min(f.length-1,e+1))),e.key===`ArrowUp`&&(e.preventDefault(),a(e=>Math.max(0,e-1))),e.key===`Enter`&&p(f[i])},h=``;return(0,A.jsx)(`div`,{className:`palette-veil`,onMouseDown:t,children:(0,A.jsxs)(`div`,{className:`palette`,role:`dialog`,"aria-label":`Search`,onMouseDown:e=>e.stopPropagation(),children:[(0,A.jsxs)(`div`,{className:`palette-input-row`,children:[(0,A.jsx)(Zm,{name:`search`,size:16}),(0,A.jsx)(`input`,{ref:d,className:`palette-input`,placeholder:`Search a screen, an agent, a session id, a number or an outcome`,value:n,onChange:e=>r(e.target.value),onKeyDown:m})]}),(0,A.jsxs)(`div`,{className:`palette-list`,children:[f.length===0&&(0,A.jsx)(`div`,{className:`palette-none`,children:`Nothing here matches — the sessions searched are the ones the floor has listed.`}),f.map((e,t)=>{let n=e.group===h?null:e.group;return h=e.group,(0,A.jsxs)(`div`,{children:[n!==null&&(0,A.jsx)(`div`,{className:`palette-group`,children:n}),(0,A.jsxs)(`button`,{type:`button`,className:t===i?`palette-item palette-item-on`:`palette-item`,onMouseEnter:()=>a(t),onClick:()=>p(e),children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:e.label}),e.sub!==``&&(0,A.jsx)(`span`,{className:`palette-item-sub`,children:e.sub})]})]},`${e.group}:${e.to}`)})]})]})})}var Zq=3,Qq=5e3;function $q(){let{live:e,lines:t}=Zy(),n=vr(),r=gr().pathname,i=(0,D.useRef)(null),[a,o]=(0,D.useState)([]),s=nJ(a.length>0);(0,D.useEffect)(()=>{if(i.current===null){if(t.length===0&&e.length===0)return;i.current=new Set(e.map(e=>e.call));return}let n=i.current,r=e.filter(e=>!n.has(e.call)&&!KB(e.call));e.forEach(e=>n.add(e.call)),r.forEach(e=>n.add(e.call)),o(e=>{let n=e.map(e=>{let n=t.find(t=>t.call===e.call);return n===void 0?e:{...e,line:n,ended:!n.live}});return[...r.map(e=>({call:e.call,line:e,ended:!1})),...n].slice(0,Zq)})},[e,t]),(0,D.useEffect)(()=>{if(!a.some(e=>e.ended))return;let e=window.setTimeout(()=>o(e=>e.filter(e=>!e.ended)),Qq);return()=>window.clearTimeout(e)},[a]);let c=e=>o(t=>t.filter(t=>t.call!==e)),l=a.filter(e=>r!==`/live/${e.call}`);return l.length===0?null:(0,A.jsx)(`div`,{className:`ring-stack`,role:`region`,"aria-label":`Calls coming in`,"aria-live":`polite`,children:l.map(e=>(0,A.jsxs)(`div`,{className:e.ended?`ring ring-ended`:`ring`,children:[(0,A.jsxs)(`button`,{type:`button`,className:`ring-body`,onClick:()=>{c(e.call),n(`/live/${e.call}`)},children:[(0,A.jsx)(`span`,{className:e.ended?`ring-icon ring-icon-ended`:`ring-icon`,"aria-hidden":!0,children:(0,A.jsx)(tJ,{})}),(0,A.jsxs)(`span`,{className:`ring-words`,children:[(0,A.jsxs)(`span`,{className:`ring-top`,children:[(0,A.jsx)(`span`,{className:`ring-kicker`,children:eJ(e)}),!e.ended&&(0,A.jsx)(`span`,{className:`ring-watch`,children:`Watch live →`})]}),(0,A.jsx)(`span`,{className:`ring-who`,children:sg(e.line)}),(0,A.jsxs)(`span`,{className:`ring-sub`,children:[e.line.agent,e.line.channel!==null&&` · ${e.line.channel}`,e.line.direction===`outbound`&&` · outbound`,!e.ended&&e.line.started_at!==null&&` · ${Jh(e.line.started_at,s)}`]})]})]}),(0,A.jsx)(`button`,{type:`button`,className:`ring-close`,"aria-label":`Dismiss`,onClick:()=>c(e.call),children:`×`})]},e.call))})}function eJ(e){return e.ended?`Call ended`:e.line.direction===`outbound`?`Calling out`:e.line.channel===`web`?`New conversation`:e.line.channel===`whatsapp`?`New WhatsApp chat`:e.line.status===`active`?`New call · answered`:`New call ringing`}function tJ(){return(0,A.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z`})})}function nJ(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}var rJ=[{group:`gateway`,label:fm===`local`?`Sandbox`:`Gateway`},{group:`settings`,label:`Settings`},{group:`box`,label:`Box`}];function iJ({agent:e,onSearch:t}){let[n,r]=(0,D.useState)(!1),i=Eh(),a=wh(),{agents:o,live:s,lines:c,here:l,insights:u,operator:d}=Zy(),f=e=>i===null||$y(i,e.key),p=a?.name??a?.label??``,m=l?.role??(a===null?``:a.subject===null||a.subject===void 0?`a machine's key`:``),h=e=>e.key===`agents`&&o.length>0?{text:String(o.length),live:!1}:e.key===`live`&&s.length>0?{text:`${s.length} live`,live:!0}:e.key===`sessions`&&u!==null?{text:String(u.sessions_total),live:!1}:e.key===`sessions`&&c.length>0?{text:c.length>=200?`200+`:String(c.length),live:!1}:null;return(0,A.jsxs)(`aside`,{className:n?`side side-folded`:`side`,"aria-label":`Screens`,children:[(0,A.jsx)(oJ,{}),(0,A.jsx)(`div`,{className:`side-search-wrap`,children:(0,A.jsxs)(`button`,{type:`button`,className:`side-search`,onClick:t,title:`Search`,children:[(0,A.jsx)(Zm,{name:`search`,size:15}),(0,A.jsx)(`span`,{className:`side-label`,children:`Search`}),(0,A.jsx)(`span`,{className:`side-kbd`,children:`⌘K`})]})}),(0,A.jsxs)(`nav`,{className:`side-nav`,children:[(0,A.jsx)(`div`,{className:`side-group side-group-first`,children:`Agents`}),o.length===0&&(0,A.jsx)(`div`,{className:`side-none side-name`,children:`none held here`}),o.map(t=>{let n=s.some(e=>e.agent===t.slug),r=t.slug===e;return(0,A.jsxs)(Gi,{to:`/a/${t.slug}/talk`,title:t.slug,className:r?`side-link side-link-on`:`side-link`,children:[(0,A.jsx)(`span`,{className:n&&!r?`side-icon side-icon-live`:`side-icon`,children:(0,A.jsx)(Zm,{name:`bot`})}),(0,A.jsx)(`span`,{className:`side-name side-name-agent`,children:t.slug}),n&&(0,A.jsx)(`span`,{className:`side-badge side-badge-live`,children:`live`})]},t.slug)}),rJ.map(({group:t,label:n})=>{let r=xm([...vm,...ym],fm,d===!0).filter(e=>e.group===t&&f(e));return r.length===0?null:(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`side-group`,children:n}),r.map(t=>{let n=h(t);return(0,A.jsxs)(Gi,{to:`/${t.path}`,end:t.path===``,title:t.name,className:({isActive:t})=>t&&e===``?`side-link side-link-on`:`side-link`,children:[(0,A.jsx)(`span`,{className:`side-icon`,children:t.icon!==void 0&&(0,A.jsx)(Zm,{name:t.icon})}),(0,A.jsx)(`span`,{className:`side-name`,children:t.name}),n!==null&&(0,A.jsx)(`span`,{className:n.live?`side-badge side-badge-live`:`side-badge`,children:n.text})]},t.key)})]},t)})]}),(0,A.jsxs)(`div`,{className:`side-foot`,children:[(0,A.jsxs)(`div`,{className:`side-user`,title:p,children:[(0,A.jsx)(`span`,{className:`side-user-avatar`,children:ih(p||(a===null?`?`:Th(a)))}),(0,A.jsxs)(`span`,{className:`side-label`,children:[(0,A.jsx)(`span`,{className:`side-user-name`,children:p||`—`}),(0,A.jsx)(`span`,{className:`side-user-role`,children:aJ(m)})]})]}),(0,A.jsx)(`button`,{type:`button`,className:`side-fold`,onClick:()=>r(!n),title:n?`Open the sidebar`:`Collapse the sidebar`,children:(0,A.jsx)(Zm,{name:`panel`,size:15})})]})]})}function aJ(e){return e===``?``:e.charAt(0).toUpperCase()+e.slice(1)}function oJ(){let e=wh(),{agents:t,orgs:n}=Zy(),{moveTo:r}=kh(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!1),u=(0,D.useRef)(null),d=gr().pathname;(0,D.useEffect)(()=>a(!1),[d]),(0,D.useEffect)(()=>{if(!i)return;let e=e=>{u.current!==null&&!u.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let f=e===null?``:Th(e),p=fm===`hosted`&&n!==null&&n.length>1,m=async e=>{l(!0),s(null);try{await r(e)}catch(e){s(e instanceof na?e.message:String(e)),l(!1)}};return(0,A.jsxs)(`div`,{ref:u,className:`side-workspace-wrap`,children:[(0,A.jsxs)(`button`,{type:`button`,className:`side-workspace`,onClick:()=>p&&a(!i),title:f,"aria-expanded":i,children:[(0,A.jsx)(`span`,{className:`side-tile`,children:ih(f||`?`).slice(0,1)}),(0,A.jsxs)(`span`,{className:`side-label`,children:[(0,A.jsx)(`span`,{className:`side-org`,children:f||`…`}),(0,A.jsxs)(`span`,{className:`side-org-sub`,children:[e?.visiting===!0?`visiting as operator · `:``,t.length,` `,t.length===1?`agent`:`agents`]})]}),(0,A.jsx)(`span`,{className:`side-caret`,children:`▾`})]}),i&&n!==null&&(0,A.jsxs)(`div`,{className:`side-orgs`,role:`menu`,children:[[{label:`Your organizations`,rows:n.filter(e=>e.member!==!1)},{label:`Every other org on this box · as operator`,rows:n.filter(e=>e.member===!1)}].filter(e=>e.rows.length>0).map(e=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`side-orgs-label`,children:e.label}),e.rows.map(e=>(0,A.jsxs)(`button`,{type:`button`,className:`side-org-row`,disabled:c||e.here,onClick:()=>void m(e.org),children:[(0,A.jsx)(`span`,{className:`side-tile`,children:ih(e.slug??e.name??e.org).slice(0,1)}),(0,A.jsx)(`span`,{className:`ui-clip`,children:e.slug??e.name??e.org}),(0,A.jsx)(`span`,{className:`side-org-role`,children:e.here?`here`:e.role})]},e.org))]},e.label)),o!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,style:{padding:`6px 8px`},children:o})]})]})}var sJ=new Set([`talk`,`chat`,`dev-chat`,`calls`,`sessions`,`pipeline`,`knowledge`,`memory`,`evals`,`widget`]),cJ=`http://localhost:4100`;function lJ({agent:e}){let t=wh(),n=Gh(t),{world:r,corner:i,lookInto:a}=kh(),{held:o,agentsLoaded:s}=Zy(),[c,l]=(0,D.useState)(!1),u=vr(),{pathname:d}=gr(),f=(0,D.useRef)(null),p=d.split(`/`).filter(Boolean),m=e!==``&&sJ.has(p[2]??``)?p[2]:`talk`;(0,D.useEffect)(()=>l(!1),[d]),(0,D.useEffect)(()=>{if(!c)return;let e=e=>{f.current!==null&&!f.current.contains(e.target)&&l(!1)},t=e=>{e.key===`Escape`&&l(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let h=t?.name??t?.label??``,g=t===null?`this org`:Th(t),_=r===`production`,v=!_&&t?.scopes.includes(`team`)===!0,y=e=>e.holder?.holder??null,b=e=>_?y(e)===null:y(e)!==null&&(y(e)===n||v),x=t=>t.slug===e&&(_?y(t)===null:y(t)===(i??n)),S=e=>{let t=y(e);return t===null?_?`${g} · deployed on the box`:`${g} · shared`:t===n?`${h||`you`} · you`:`${e.holder?.name??t} · theirs`},C=[...o].sort((e,t)=>e.slug.localeCompare(t.slug)||Number(Vh(e,n))-Number(Vh(t,n))),w=i===null?void 0:o.find(e=>y(e)===i),T=()=>{let e=fm===`hosted`?cJ:pm();window.open(`${e}${d}`,`_blank`,`noopener`)};return(0,A.jsxs)(`div`,{ref:f,style:{position:`relative`},children:[(0,A.jsxs)(`button`,{type:`button`,className:c?`switch-trigger switch-trigger-open`:`switch-trigger`,onClick:()=>l(!c),"aria-expanded":c,"aria-haspopup":`dialog`,children:[(0,A.jsx)(eh,{tone:_?`green`:`amber`}),(0,A.jsx)(`span`,{className:`switch-agent`,children:e===``?`choose an agent`:e}),(0,A.jsx)(Qm,{tone:_?`green`:`amber`,children:r}),t!==null&&(0,A.jsx)(ah,{name:h||g,tint:`violet`,size:20}),(0,A.jsx)(`span`,{className:`switch-caret`,"aria-hidden":!0,children:`▾`})]}),c&&(0,A.jsxs)(`div`,{className:`switch-panel`,role:`dialog`,"aria-label":`what this console is looking at`,children:[t!==null&&(0,A.jsxs)(`div`,{className:`switch-who`,children:[(0,A.jsx)(ah,{name:h||g,tint:`violet`,size:36}),(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`switch-who-name`,children:h||`an org's key`}),(0,A.jsxs)(`div`,{className:`switch-who-sub`,children:[g,` · key `,t.key_id]})]})]}),i!==null&&(0,A.jsxs)(`div`,{className:`switch-looking`,children:[(0,A.jsxs)(`span`,{style:{flex:1},children:[`Looking at `,(0,A.jsx)(`b`,{children:w?.holder?.name??i}),`'s copy`]}),(0,A.jsx)(`button`,{type:`button`,className:`ui-text-action`,onClick:()=>a(null),children:`Back to yours`})]}),(0,A.jsxs)(`div`,{className:`switch-where`,children:[(0,A.jsx)(uJ,{}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`switch-label`,children:`Environment`}),(0,A.jsxs)(`div`,{className:`switch-choices`,children:[(0,A.jsx)(qm,{on:_,onClick:_?void 0:T,children:`production`}),(0,A.jsx)(qm,{on:!_,onClick:_?T:void 0,children:`sandbox`})]}),(0,A.jsx)(`div`,{className:`switch-note`,children:_?(0,A.jsxs)(A.Fragment,{children:[`Your sandbox copies are watched on your machine: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall serve`}),`, then sandbox.`]}):(0,A.jsx)(A.Fragment,{children:`Production is watched on the gateway's console, signed in to.`})})]})]}),(0,A.jsxs)(`div`,{className:`switch-agents`,children:[(0,A.jsxs)(`div`,{className:`switch-label`,children:[`agents in `,g,` · `,r]}),s&&C.length===0&&(0,A.jsx)(`div`,{className:`switch-empty`,children:fm===`local`?(0,A.jsxs)(A.Fragment,{children:[`Nothing is running here. `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in a project puts its agents on this list.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing is running in production: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start --prod`}),` on your server holds it, on a server token.`]})}),(0,A.jsx)(`div`,{className:`switch-list`,children:C.map(t=>{let r=y(t),i=b(t),o=x(t);return(0,A.jsxs)(`button`,{type:`button`,className:o?`switch-card switch-card-here`:`switch-card`,disabled:!i,title:i?void 0:`their copy: it answers them, and they open it from their own console`,onClick:()=>{l(!1),_||a(r===n?null:r),t.slug!==e&&u(`/a/${t.slug}/${m}`)},children:[(0,A.jsx)(eh,{tone:`green`}),(0,A.jsxs)(`span`,{style:{minWidth:0,flex:1},children:[(0,A.jsx)(`span`,{className:`switch-card-name`,children:t.slug}),(0,A.jsxs)(`span`,{className:`switch-card-sub`,children:[S(t),` · `,t.channels.join(` · `)||`no doors`]})]}),(0,A.jsx)(`span`,{className:`switch-card-open`,children:o?`Viewing`:i?`Open`:`Theirs`})]},`${t.slug}:${r??`org`}`)})})]})]})]})}function uJ(){let{orgs:e}=Zy(),{moveTo:t}=kh(),[n,r]=(0,D.useState)(!1),[i,a]=(0,D.useState)(null);if(fm!==`hosted`||e===null||e.length<2)return null;let o=async e=>{r(!0),a(null);try{await t(e)}catch(e){a(e instanceof na?e.message:String(e)),r(!1)}};return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`switch-label`,children:`Organization`}),(0,A.jsx)(`div`,{className:`switch-choices`,children:e.map(e=>(0,A.jsx)(qm,{on:e.here,disabled:n,title:e.member===!1?`as the box's operator`:e.role,onClick:()=>!e.here&&void o(e.org),children:e.slug??e.name??e.org},e.org))}),i!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,style:{marginTop:6},children:i})]})}function dJ(e,t){let n=e.split(`/`).filter(Boolean);if(t!==``){let e=bm.find(e=>e.path===n[2]);return e===void 0?`Talk`:e.key===`sessions`&&n[3]!==void 0?`Session`:e.name}if(n[0]===`cli`)return`Sign in a terminal`;if(n[0]===`box`){let e=ym.find(e=>e.path===`box/${n[1]??``}`);return e===void 0?`Box`:e.key===`box-orgs`&&n[2]!==void 0?`Organization`:e.name}let r=vm.find(e=>e.path===(n[0]??``));return r===void 0?`Home`:r.key===`sessions`&&n[1]!==void 0?`Session`:r.key===`numbers`?`Phone numbers`:r.name}function fJ({agent:e}){let t=wh(),n=dm(),{pathname:r}=gr(),i=e===``?r.startsWith(`/box/`)?`box`:t===null?``:Th(t):e;return(0,A.jsxs)(`header`,{className:`top`,children:[i!==``&&(0,A.jsxs)(`span`,{className:`top-crumb`,children:[i,` /`]}),(0,A.jsx)(`span`,{className:`top-title`,children:dJ(r,e)}),(0,A.jsxs)(`div`,{className:`top-right`,children:[(0,A.jsx)(lJ,{agent:e}),fm===`hosted`&&(0,A.jsx)(`button`,{type:`button`,className:`top-leave`,onClick:n,children:`Sign out`})]})]})}var pJ=`No agent called {agent} is held here`;function mJ(){return(0,A.jsx)(Xy,{children:(0,A.jsx)(hJ,{})})}function hJ(){let e=Sr().agent??``,{agents:t,agentsLoaded:n}=Zy(),[r,i]=(0,D.useState)(!1),a=e!==``&&n&&!t.some(t=>t.slug===e);return(0,D.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),i(e=>!e))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[]),(0,A.jsxs)(`div`,{className:`frame`,children:[(0,A.jsx)(iJ,{agent:a?``:e,onSearch:()=>i(!0)}),(0,A.jsxs)(`div`,{className:`frame-main`,children:[(0,A.jsx)(fJ,{agent:e}),e!==``&&!a&&(0,A.jsx)(qq,{agent:e}),(0,A.jsx)(`div`,{className:`frame-screen`,children:a?(0,A.jsx)(gJ,{agent:e}):(0,A.jsx)(Zr,{})})]}),(0,A.jsx)($q,{}),r&&(0,A.jsx)(Xq,{agent:a?``:e,onClose:()=>i(!1)})]})}function gJ({agent:e}){return(0,A.jsxs)(`p`,{className:`missing`,children:[pJ.replace(`{agent}`,e),fm===`local`?" — no copy of yours is running. Start `pinecall start` in the project, and it appears.":" — nothing by that name is deployed in this org. Check the org you signed in with; a copy you are running yourself is on your own machine, at `pinecall serve`."]})}var _J={home:(0,A.jsx)(JU,{}),agents:(0,A.jsx)(Ib,{}),live:(0,A.jsx)(vU,{}),sessions:(0,A.jsx)(DU,{}),"org-evals":(0,A.jsx)(fT,{}),"org-memory":(0,A.jsx)(OT,{}),"org-docs":(0,A.jsx)(MT,{}),numbers:(0,A.jsx)(QW,{}),phone:(0,A.jsx)(eG,{}),tokens:(0,A.jsx)($U,{}),providers:(0,A.jsx)(uW,{}),team:(0,A.jsx)(_q,{}),usage:(0,A.jsx)(Fq,{}),lexicon:(0,A.jsx)(oW,{})},vJ={"box-orgs":(0,A.jsx)(RS,{children:(0,A.jsx)(nS,{})}),"box-fleet":(0,A.jsx)(RS,{children:(0,A.jsx)(ox,{})}),"box-routes":(0,A.jsx)(RS,{children:(0,A.jsx)(oS,{})}),"box-usage":(0,A.jsx)(RS,{children:(0,A.jsx)(FS,{})}),"box-settings":(0,A.jsx)(RS,{children:(0,A.jsx)(AS,{})})},yJ={talk:(0,A.jsx)(ZB,{}),chat:(0,A.jsx)(rV,{}),devchat:(0,A.jsx)(Lw,{}),calls:(0,A.jsx)(wC,{}),sessions:(0,A.jsx)(CG,{}),settings:(0,A.jsx)(GK,{}),pipeline:(0,A.jsx)(SG,{}),docs:(0,A.jsx)(NW,{}),memory:(0,A.jsx)(RW,{}),evals:(0,A.jsx)(iH,{}),widget:(0,A.jsx)(Gq,{})},bJ={devchat:(0,A.jsx)(Lw,{}),calls:(0,A.jsx)(wC,{}),sessions:(0,A.jsx)(SK,{})},xJ={live:(0,A.jsx)(vU,{}),sessions:(0,A.jsx)(SK,{})};function SJ(e,t){return xm(e,fm,!0).flatMap(e=>{let n=t[e.key];if(e.path===``)return[{index:!0,element:n}];let r=(t===yJ?bJ:xJ)[e.key];return r===void 0?[{path:e.path,element:n}]:[{path:e.path,element:n},{path:`${e.path}/:call`,element:r}]})}var CJ=Vi([{path:`/`,element:(0,A.jsx)(mJ,{}),children:[...SJ(vm,_J),...SJ(ym,vJ),...fm===`hosted`?[{path:`box/orgs/:org`,element:(0,A.jsx)(RS,{children:(0,A.jsx)(eS,{})})}]:[],...fm===`hosted`?[{path:`cli`,element:(0,A.jsx)(tq,{})}]:[]]},{path:`/a/:agent`,element:(0,A.jsx)(mJ,{}),children:[{index:!0,element:(0,A.jsx)(Xr,{to:`talk`,replace:!0})},...SJ(bm,yJ)]},{path:`/a/:agent/widget/preview`,element:(0,A.jsx)(Kq,{})},{path:`*`,element:(0,A.jsx)(Xr,{to:`/`,replace:!0})}],{basename:`/`}),wJ=np({version:P(),cloud:L(),signup:L(),min_password:F(),mail:L().optional(),google:L().optional()});async function TJ(e){try{let t=await fetch(new URL(`${e.replace(/\/$/,``)}/.well-known/pinecall`,window.location.origin));return wJ.parse(await fa(t))}catch{return{version:``,cloud:!1,signup:!1,min_password:0}}}function EJ({base:e,onSigned:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(()=>new URLSearchParams(window.location.search).get(`refused`)),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!0),b=(0,D.useRef)(``),[x,S]=(0,D.useState)(!1),[C,w]=(0,D.useState)(null),[T,ee]=(0,D.useState)(null),[te,ne]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let t=!1;return Qp(e).then(e=>{t||S(e)}),TJ(e).then(e=>{t||h(e.google===!0)}),()=>{t=!0}},[e]);let re=async()=>{if(ee(null),w(null),i.trim()===``){ee(`Type your work email first: it says which workspace signs you in.`);return}ne(!0);try{let t=await $p(e,i.trim()),n=t[0];t.length===1&&n!==void 0?window.location.assign(em(e,n.slug??n.org)):t.length===0?ee(`No workspace signs in with a provider for that address.`):w(t)}catch(e){ee(e instanceof na?e.message:String(e))}finally{ne(!1)}},E=async()=>{let t=`${i.trim()}\n${o}`;if(i.trim()!==``&&o!==``&&t!==b.current){b.current=t;try{let t=await Yp(e,i.trim(),o);if(t===null){y(!1);return}_(t);let a=t[0];t.length>0&&!t.some(e=>(e.slug??e.org)===n)&&a!==void 0&&r(a.slug??a.org)}catch{_(null)}}},ie=async r=>{r.preventDefault(),l(!0),d(null);try{t(await Up(e,{org:n.trim(),email:i.trim(),password:o}))}catch(e){d(e instanceof na?e.message:String(e))}finally{l(!1)}};return(0,A.jsx)(am,{children:(0,A.jsxs)(`form`,{onSubmit:e=>void ie(e),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`Sign in`}),(0,A.jsx)(`p`,{className:`login-lede`,children:`Use the email and password you were invited with.`}),(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-email`,children:`Email`}),(0,A.jsx)(`input`,{id:`login-email`,className:`login-input`,type:`email`,value:i,onChange:e=>a(e.target.value),autoComplete:`username`,autoFocus:!0,required:!0}),(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-password`,children:`Password`}),(0,A.jsx)(`button`,{type:`button`,className:`login-link`,onClick:()=>p(!f),children:`Forgot password`})]}),(0,A.jsx)(`input`,{id:`login-password`,className:`login-input login-input-secret`,type:`password`,value:o,onChange:e=>s(e.target.value),onBlur:()=>void E(),autoComplete:`current-password`,required:!0}),f&&(0,A.jsx)(`p`,{className:`login-forgot`,children:`Ask an admin of your workspace: from Team they hand you a one-use link where you choose a new password.`}),g!==null&&g.length>0?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-org`,children:`Workspace`}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:(n[0]??`·`).toUpperCase()}),(0,A.jsx)(`select`,{id:`login-org`,className:`login-workspace-input`,value:n,onChange:e=>r(e.target.value),disabled:g.length===1,children:g.map(e=>(0,A.jsx)(`option`,{value:e.slug??e.org,children:e.name??e.slug??e.org},e.org))})]})]}):!v&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-org`,children:`Workspace`}),(0,A.jsx)(`span`,{className:`login-hint`,children:`only if you belong to several`})]}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:(n.trim()[0]??`·`).toUpperCase()}),(0,A.jsx)(`input`,{id:`login-org`,className:`login-workspace-input`,value:n,onChange:e=>r(e.target.value),autoComplete:`organization`,placeholder:`the oldest of yours`})]})]}),(0,A.jsx)(`button`,{className:`login-go`,type:`submit`,disabled:c,children:c?`Signing in…`:`Sign in`}),u!==null&&(0,A.jsx)(`p`,{className:`login-refused`,children:u}),(x||m)&&(0,A.jsxs)(`div`,{className:`login-or`,children:[(0,A.jsx)(`span`,{className:`login-or-line`}),(0,A.jsx)(`span`,{className:`login-or-word`,children:`or`}),(0,A.jsx)(`span`,{className:`login-or-line`})]}),m&&(0,A.jsxs)(`button`,{type:`button`,className:`login-sso login-google`,onClick:()=>window.location.assign(tm(e)),children:[(0,A.jsx)(DJ,{}),`Continue with Google`]}),x&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`button`,{type:`button`,className:`login-sso`,disabled:te,onClick:()=>void re(),children:[(0,A.jsx)(`span`,{className:`login-sso-glyph`}),te?`Looking for your workspace…`:`Continue with SSO`]}),C!==null&&(0,A.jsxs)(`div`,{className:`login-sso-pick`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-sso-org`,children:`Which workspace`}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:`·`}),(0,A.jsxs)(`select`,{id:`login-sso-org`,className:`login-workspace-input`,defaultValue:``,onChange:t=>t.target.value!==``&&window.location.assign(em(e,t.target.value)),children:[(0,A.jsx)(`option`,{value:``,disabled:!0,children:`Choose one…`}),C.map(e=>(0,A.jsx)(`option`,{value:e.slug??e.org,children:e.name??e.slug??e.org},e.org))]})]})]}),T!==null&&(0,A.jsx)(`p`,{className:`login-sso-note`,children:T})]}),(0,A.jsx)(`p`,{className:`login-note`,children:`Invited and no password yet? Open the link in your invitation — that is where you choose one.`})]})})}function DJ(){return(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 48 48`,"aria-hidden":!0,children:[(0,A.jsx)(`path`,{fill:`#EA4335`,d:`M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z`}),(0,A.jsx)(`path`,{fill:`#4285F4`,d:`M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z`}),(0,A.jsx)(`path`,{fill:`#FBBC05`,d:`M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z`}),(0,A.jsx)(`path`,{fill:`#34A853`,d:`M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z`})]})}function OJ({base:e,token:t,onSigned:n}){let[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return TJ(e).then(e=>{t||c(e.min_password)}),()=>{t=!0}},[e]);let p=async i=>{if(i.preventDefault(),r!==a){f(`The two passwords differ.`);return}u(!0),f(null);try{n(await qp(e,t,r))}catch(e){f(e instanceof na?e.message:String(e))}finally{u(!1)}};return(0,A.jsx)(am,{children:(0,A.jsxs)(`form`,{onSubmit:e=>void p(e),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`Choose your password`}),(0,A.jsx)(`p`,{className:`login-lede`,children:`This link came from an invitation, or from an admin resetting your password. It opens once; the password you pick here is the one you sign in with from now on.`}),(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`accept-password`,children:`Password`}),s!==null&&s>0&&(0,A.jsxs)(`span`,{className:`login-hint`,children:[s,` characters at least`]})]}),(0,A.jsx)(`input`,{id:`accept-password`,className:`login-input login-input-secret`,type:`password`,value:r,minLength:s??void 0,onChange:e=>i(e.target.value),autoComplete:`new-password`,autoFocus:!0,required:!0}),(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`accept-again`,children:`Again`}),(0,A.jsx)(`input`,{id:`accept-again`,className:`login-input login-input-secret`,type:`password`,value:a,onChange:e=>o(e.target.value),autoComplete:`new-password`,required:!0}),(0,A.jsx)(`button`,{className:`login-go`,type:`submit`,disabled:l,style:{marginTop:8},children:l?`Joining…`:`Join`}),d!==null&&(0,A.jsx)(`p`,{className:`login-refused`,children:d})]})})}var kJ=document.getElementById(`root`);if(kJ===null)throw Error(`index.html has no #root for the console to mount in`);var AJ=`login`,jJ=/^\/invitations\/([^/]+)\/?$/;function MJ(){let e=jJ.exec(window.location.pathname);return e===null?null:decodeURIComponent(e[1]??``)}var NJ=mm[fm],PJ=``;async function FJ(){if(fm===`local`)return PJ;let e=new URL(window.location.href),t=e.searchParams.get(AJ);if(t!==null){e.searchParams.delete(AJ),window.history.replaceState(null,``,e.toString());try{let e=await Hp(`/`,t);return Tm(e.key),e.key}catch{}}return wm()}function IJ({startingWith:e}){let[t,n]=(0,D.useState)(e),[r,i]=(0,D.useState)(()=>NJ===`sandbox`?Om():null),a=(0,D.useCallback)(e=>{km(e),i(e)},[]);aa(()=>{Em(),n(null)});let o=(0,D.useCallback)(async e=>{if(t===null)return;let n=await Kp({base:`/`,key:t},e);km(null),Tm(n.key),window.location.assign(`/`)},[t]),s=(0,D.useMemo)(()=>({world:NJ,moveTo:o,corner:r,lookInto:a}),[o,r,a]),c=(0,D.useMemo)(()=>({base:`/`,key:t??``,corner:r,...fm===`hosted`?{world:NJ}:{}}),[t,r]),l=(0,D.useCallback)(()=>{Em(),km(null),i(null),n(null)},[]),u=e=>{Tm(e.key),n(e.key)};if(t===null){if(fm===`local`)return(0,A.jsx)(cm,{});let e=MJ();return e===null?(0,A.jsx)(EJ,{base:`/`,onSigned:u}):(0,A.jsx)(OJ,{base:`/`,token:e,onSigned:e=>{window.history.replaceState(null,``,`/`),u(e)}})}return(0,A.jsx)(_a,{value:c,children:(0,A.jsx)(Ch,{children:(0,A.jsx)(Oh,{value:s,children:(0,A.jsx)(um,{value:l,children:(0,A.jsx)(Kr,{router:CJ})})})})})}FJ().then(e=>{(0,hi.createRoot)(kJ).render((0,A.jsx)(D.StrictMode,{children:(0,A.jsx)(IJ,{startingWith:e})}))});