pinecall 0.7.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/agent-knowledge.d.ts.map +1 -1
- package/dist/cli/agent-knowledge.js +4 -9
- package/dist/cli/agent-knowledge.js.map +1 -1
- package/dist/cli/agent-lines.d.ts +4 -0
- package/dist/cli/agent-lines.d.ts.map +1 -1
- package/dist/cli/agent-lines.js +16 -0
- package/dist/cli/agent-lines.js.map +1 -1
- package/dist/cli/agent.js +3 -3
- package/dist/cli/agent.js.map +1 -1
- package/dist/cli/docs-attach.js +8 -5
- package/dist/cli/docs-attach.js.map +1 -1
- package/dist/cli/simulate.js +15 -6
- package/dist/cli/simulate.js.map +1 -1
- package/dist/cli/ui/console/assets/{index-CZCFF8Yh.js → index-C3cnwAoj.js} +27 -14
- package/dist/cli/ui/console/assets/index-CItDJPWi.css +1 -0
- package/dist/cli/ui/console/index.html +2 -2
- package/package.json +1 -1
- package/dist/cli/ui/console/assets/index-gPwW4dvS.css +0 -1
|
@@ -56,12 +56,14 @@ 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:`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
|
|
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:`simulations`,path:`simulations`,name:`Simulations`,in:hm,group:`gateway`,icon:`headphones`},{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`],headphones:[`M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3`],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()),models:fp(P(),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({path:P(),chars:I(),chunks:I(),pushed_at:F()}),Cy=B({base:P(),kept:L(),files:R(Sy)}),wy=B({path:P(),text:P(),chunks:I(),pushed_at:F()});B({text:P()});var Ty=B({base:P(),path:P(),chunks:I(),took_ms:F()}),Ey=B({bases:R(B({base:P(),agents:R(P())}))}),Dy={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 Oy(e){let t=ky();for(let n of e)t=My(t,n);return t}function ky(){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 Ay=`unreadable`;function jy(e,t,n){let r=n instanceof Error?n.message:String(n);return e.errors.push({seq:t.seq,code:Ay,message:`${t.type} at seq ${t.seq} is not the shape this reader knows: ${r.split(`
|
|
60
|
+
`)[0]?.trim()??r}`}),e}function My(e,t){let n;try{n=Rv(t)}catch(n){let r=jy(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=By(e,n):Ny(e,t,n),r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}function Ny(e,t,n){switch(n.type){case`call.ringing`:e.status=`ringing`,e.direction=`inbound`,Py(e,n.data);return;case`call.dialing`:e.status=`dialing`,e.direction=`outbound`,Py(e,n.data);return;case`call.started`:e.status=`active`,e.direction=n.data.direction,e.started_at=n.data.started_at,Py(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:Hy(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`:Fy(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`:Iy(e,n.data.call_id,{status:`granted`,said:n.data.said});return;case`confirm.declined`:Iy(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`:Ly(e,t,n.data);return;case`participant.left`:Ry(e,n.data.identity);return;case`participant.speaking`:{let t=zy(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 Py(e,t){e.channel=t.channel,e.from=t.from,e.to=t.to,e.caller=t.caller}function Fy(e,t){let n=Vy(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 Iy(e,t,n){let r=Vy(e.confirms,e=>e.call_id===t);if(r===-1)return;let i=e.confirms[r];e.confirms[r]={...i,...n}}function Ly(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 Ry(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 zy(e,t){return e.room?.participants.find(e=>e.identity===t)}function By(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 Vy(e,t){for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1}function Hy(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 Uy=500,Wy=8e3,Gy=204,Ky=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 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
|
-
|
|
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(`
|
|
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 qy(e,t,n){let r=new AbortController,i=null,a=null,o=Uy,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 Jy(o,r.signal),o=Math.min(o*2,Wy);continue}if(i.status===Gy){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=Uy;let c=new Ky,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 Jy(o,r.signal),o=Math.min(o*2,Wy)}})(),()=>{s=!1,i!==null&&window.clearTimeout(i),r.abort()}}function Jy(e,t){return new Promise(n=>{let r=window.setTimeout(n,e);t.addEventListener(`abort`,()=>{window.clearTimeout(r),n()},{once:!0})})}var Yy=3e3;function Xy(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(),Yy),c=qy(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 Zy(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,$y=(0,D.createContext)(null);function eb({children:e}){let t=j(),n=wh(),r=Xy(Qy),i=ug(),a=dg(),o=Zy(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)($y,{value:u,children:e})}function tb(){let e=(0,D.useContext)($y);if(e===null)throw Error(`a screen was mounted outside the shell's org`);return e}var nb={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`,simulations:`evals`,"org-memory":`memory`,"org-docs":`knowledge`,numbers:`numbers`,providers:`providers`,team:`team`,usage:`usage`};function rb(e,t){let n=nb[t];return n===void 0||e.includes(n)}var ib=[`app`,`calls`,`evals`,`keys`,`knowledge`,`memory`,`numbers`,`pipeline`,`providers`,`supervise`,`talk`,`team`,`usage`,`words`];function ab(e){let t=ib.filter(t=>!e.includes(t));return t.length===0||t.length===1&&t[0]===`app`?`everything`:e.join(`, `)}var ob=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())}),sb=z({key:P(),key_id:P(),label:P().nullable(),env:P(),scopes:R(P())});async function cb(e){return R(ob).parse(await k(e,`/v1/keys`))}async function lb(e,t){return sb.parse(await sa(e,`/v1/keys`,t))}async function ub(e,t){await sa(e,`/v1/keys/${encodeURIComponent(t)}/revoke`,{})}async function db(e){return ey.parse(await k(e,`/v1/apps`)).apps}async function fb(e,t){ty.parse(await sa(e,`/v1/apps/${encodeURIComponent(t)}/stop`,{}))}function pb({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 db(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 fb(n,e),i(await db(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)(mb,{app:e,stop:t?s:void 0},e.app))]})]})}function mb({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 hb=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`])}),gb=z({kind:mp([`twilio`,`sip`]),account:P()}),_b=z({kind:mp([`twilio`,`sip`]),numbers:R(z({number:P(),name:P(),imported:L()}))}),vb=z({route:hb.shape.route,steps:R(P()),dry_run:L()});async function yb(e){return R(hb).parse(await k(e,`/v1/numbers`))}async function bb(e){try{return gb.parse(await k(e,`/v1/carrier`))}catch(e){if(Nb(e,404))return null;throw e}}async function xb(e,t){await oa(e,`/v1/carrier`,t)}async function Sb(e){await ca(e,`/v1/carrier`)}async function Cb(e){return _b.parse(await k(e,`/v1/numbers/available`))}async function wb(e,t,n){return vb.parse(await sa(e,`/v1/numbers${n?`?dry_run=true`:``}`,t))}async function Tb(e,t,n){return vb.parse(await sa(e,`/v1/numbers/buy${n?`?dry_run=true`:``}`,t))}async function Eb(e,t){await ca(e,`/v1/numbers/${encodeURIComponent(t)}`)}var Db=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()})}),Ob=np({steps:R(P()),dry_run:L(),ready:L()});async function kb(e){try{return Db.parse(await k(e,`/v1/carrier/outbound`))}catch(e){if(Nb(e,404)||Nb(e,405)||Nb(e,403))return null;throw e}}async function Ab(e,t){return Ob.parse(await sa(e,`/v1/carrier/outbound${t?`?dry_run=true`:``}`,{}))}var jb=np({call:P()});async function Mb(e,t,n,r){let i=r===void 0||r===``?{to:n}:{to:n,from:r};return jb.parse(await sa(e,`/v1/agents/${encodeURIComponent(t)}/dial`,i)).call}function Nb(e,t){return typeof e==`object`&&!!e&&e.status===t}var Pb=z({vendors:R(P())});async function Fb(e){return Pb.parse(await k(e,`/v1/provider-keys`)).vendors}async function Ib(e,t,n){await oa(e,`/v1/provider-keys/${encodeURIComponent(t)}`,{key:n})}async function Lb(e,t){await ca(e,`/v1/provider-keys/${encodeURIComponent(t)}`)}var Rb=`minmax(0,1.5fr) minmax(0,1.3fr) minmax(0,1.1fr) 90px 90px`;function zb(){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&&rb(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?yb(e).catch(()=>null):Promise.resolve(null),a?Cb(e).catch(()=>null):Promise.resolve(null),o?cb(e).catch(()=>null):Promise.resolve(null),s?Lh(e).catch(()=>null):Promise.resolve(null),s?Fb(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 Bb(){let{held:e,agents:t,live:n,lines:r,connection:i,agentsError:a,agentsLoaded:o,insights:s}=tb(),c=Gh(wh()),l=Eh(),u=zb(),[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:Rb,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:Rb,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)(Ub,{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)(pb,{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)(Vb,{tokens:u.keys}),u.catalogue!==null&&(0,A.jsx)(Hb,{catalogue:u.catalogue,brought:u.brought})]})]})}function Vb({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 Hb({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:Gb(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 Ub({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 Wb={llm:`decides`,stt:`hears`,tts:`speaks`};function Gb(e,t){let n=e.does.filter(n=>(t.defaults[n]??``).split(`/`)[0]===e.name);return n.length>0?`${n.map(e=>Wb[e]).join(`, `)} · the default`:`${e.does.map(e=>Wb[e]).join(`, `)} · ${e.note}`}var Kb=`/v1/ops`,qb=np({worker:P(),active:F(),max_jobs:F().nullish(),load:F(),draining:L(),cordoned:L(),seen_at:F()}),Jb=np({now:F(),stale_after_s:F(),workers:R(qb)}),Yb=np({route:np({agent:P(),channel:P(),number:P().nullish(),env:P(),managed:L().nullish()}),source:P()}),Xb=np({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),cost_eur:F()}),Zb=np({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F()}),Qb=np({rows:R(Xb),totals:fp(P(),Zb),next:F().nullish()});async function $b(e){return Jb.parse(await k(e,`${Kb}/fleet`))}async function ex(e,t,n){let r=`${Kb}/fleet/${encodeURIComponent(t)}/cordon`;await(n?sa(e,r,{}):ca(e,r))}async function tx(e,t,n){return R(Yb).parse(await k(e,`${Kb}/routes`,{org:t,env:n}))}async function nx(e,t){return np({overrides:P().nullish()}).parse(await sa(e,`${Kb}/routes`,t)).overrides??null}async function rx(e,t,n){await ca(e,`${Kb}/routes/${encodeURIComponent(n)}?org=${encodeURIComponent(t)}`)}async function ix(e,t,n){return Qb.parse(await k(e,`${Kb}/usage`,{after:t,limit:n}))}function ax(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(ox(e))}},[e]);return(0,D.useEffect)(()=>{let t=!1;return e().then(e=>{t||n(e)},e=>{t||i(ox(e))}),()=>{t=!0}},[e]),{value:t,refused:r,reread:a}}function ox(e){return e instanceof na||e instanceof Error?e.message:String(e)}function sx(){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(ox(e)),!1}finally{t(!1)}},[])}}var cx=5e3,lx=`minmax(0,1.4fr) 150px 130px 120px 90px`;function ux(){let e=j(),t=ax((0,D.useCallback)(()=>$b(e),[e])),n=sx(),{reread:r}=t;(0,D.useEffect)(()=>{let e=window.setInterval(()=>void r(),cx);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 ${cx/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:lx,labels:[`Worker`,`Calls`,`Load`,`Standing`,``]}),i.workers.map(t=>{let[i,o]=dx(t,a(t));return(0,A.jsxs)(fh,{columns:lx,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 ex(e,t.worker,!t.cordoned),await r()}),children:t.cordoned?`Uncordon`:`Cordon`})})]},t.worker)})]})]})]})]})}function dx(e,t){return t?[`not heard from`,`gray`]:e.draining?[`draining`,`amber`]:e.cordoned?[`cordoned`,`amber`]:[`taking calls`,`green`]}var fx=`/v1/ops`,px=e=>`${fx}/orgs/${encodeURIComponent(e)}`,mx=[`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`,`budget_eur`],hx=F().nullish(),gx=np({id:P(),slug:P(),name:P()}),_x=np({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()}),vx=gx.extend({quotas:np({minutes:hx,messages:hx,agents:hx,concurrent_calls:hx,memory_facts:hx,knowledge_chunks:hx,numbers:hx,seats:hx,budget_eur:hx}),dialling:_x.nullish(),holding:np({memory_facts:F(),knowledge_chunks:F(),numbers:F(),seats:F()})}),yx=np({fingerprint:P(),label:P().nullish(),created_at:P(),revoked_at:P().nullish(),env:P(),scopes:R(P()),subject:P().nullish(),name:P().nullish()}),bx=np({key:P(),key_id:P(),label:P().nullish(),env:P(),scopes:R(P())}),xx=np({id:P(),email:P(),name:P(),role:P(),agents:R(P()),status:P(),operator:L().nullish()}),Sx=np({member:xx,token:P().nullish(),expires_at:P().nullish(),mailed:L().nullish()}),Cx=np({configured:L(),issuer:P().nullish(),domains:R(P()).nullish(),required:L()});async function wx(e){return R(gx).parse(await k(e,`${fx}/orgs`))}async function Tx(e,t){return vx.parse(await k(e,px(t)))}async function Ex(e,t,n){return gx.parse(await sa(e,`${fx}/orgs`,{slug:t,name:n||null}))}async function Dx(e,t){await ca(e,px(t))}async function Ox(e,t,n){await oa(e,`${px(t)}/quotas`,n)}async function kx(e,t,n){await oa(e,`${px(t)}/dialling`,n)}async function Ax(e,t,n){return np({logs:F(),numbers:R(P())}).parse(await oa(e,`${px(t)}/agents`,{agent:n}))}async function jx(e,t){return R(yx).parse(await k(e,`${px(t)}/keys`))}async function Mx(e,t,n){return bx.parse(await sa(e,`${px(t)}/keys`,n))}async function Nx(e,t){await sa(e,`${fx}/keys/${encodeURIComponent(t)}/revoke`,{})}async function Px(e,t){return np({members:R(xx),seated:F()}).parse(await k(e,`${px(t)}/members`))}async function Fx(e,t,n){return Sx.parse(await sa(e,`${px(t)}/members`,n))}async function Ix(e,t,n,r){await oa(e,`${px(t)}/members/${encodeURIComponent(n)}/operator`,{operator:r})}async function Lx(e,t,n){await ca(e,`${px(t)}/members/${encodeURIComponent(n)}`)}async function Rx(e,t){return np({vendors:R(P())}).parse(await k(e,`${px(t)}/provider-keys`)).vendors}async function zx(e,t,n,r){await oa(e,`${px(t)}/provider-keys/${encodeURIComponent(n)}`,{key:r})}async function Bx(e,t,n){await ca(e,`${px(t)}/provider-keys/${encodeURIComponent(n)}`)}async function Vx(e,t){try{return Cx.parse(await k(e,`${px(t)}/sso`))}catch{return null}}async function Hx(e,t,n){await oa(e,`${px(t)}/sso/required`,{required:n})}var Ux=`minmax(0,1fr) 96px 140px minmax(0,1.3fr) 92px`,Wx=[{name:`app — what a deployed agent runs on`,scopes:[`app`]},{name:`everything — the org's own machine key`,scopes:null}];function Gx({named:e}){let t=j(),n=ax((0,D.useCallback)(()=>jx(t,e),[t,e])),r=sx(),[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 Mx(t,e,{label:o.trim(),env:c,scopes:Wx[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:Wx.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:Ux,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:Ux,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:ab(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 Nx(t,e.fingerprint),await n.reread()}),children:`Revoke`})})]},e.fingerprint)})]})]})]})}var Kx={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`}},qx={memory_facts:`memory_facts`,knowledge_chunks:`knowledge_chunks`,numbers:`numbers`,seats:`seats`},Jx=e=>e.replace(/[^0-9]/g,``);function Yx({org:e,onSaved:t}){let n=j(),r=sx(),i=sx(),[a,o]=(0,D.useState)(()=>Object.fromEntries(mx.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 Ox(n,e.slug,Object.fromEntries(mx.map(e=>[e,a[e]===``?null:Number(a[e])]))),await t()})&&c(`quotas`)},y=async()=>{c(null),await i.move(async()=>{await kx(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:mx.map(t=>(0,A.jsxs)(Wm,{label:Kx[t].name,children:[(0,A.jsx)(W,{inputMode:`numeric`,value:a[t]??``,placeholder:`no limit`,onChange:e=>o({...a,[t]:Jx(e.target.value)})}),(0,A.jsxs)(`div`,{className:`box-limit-about`,children:[Kx[t].about,qx[t]!==void 0&&` · holding ${e.holding[qx[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(Jx(e.target.value))})}),(0,A.jsx)(Wm,{label:`Calls a day`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:m,onChange:e=>h(Jx(e.target.value))})}),(0,A.jsx)(Wm,{label:`Longest call, seconds`,children:(0,A.jsx)(W,{inputMode:`numeric`,value:g,onChange:e=>_(Jx(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 Xx=[`admin`,`manager`,`developer`,`supervisor`,`qa`],Zx=`minmax(0,1fr) minmax(0,1.3fr) 100px 90px 220px`,Qx={active:`green`,invited:`amber`,disabled:`gray`};function $x({named:e,seats:t}){let n=j(),r=ax((0,D.useCallback)(()=>Px(n,e),[n,e])),i=sx(),[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 Fx(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)(eS,{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:Xx.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:Zx,labels:[`Name`,`Email`,`Role`,`Status`,``]}),r.value.members.map(t=>(0,A.jsxs)(fh,{columns:Zx,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(()=>Lx(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(()=>Ix(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 eS({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 tS({org:e}){let t=j(),n=vr(),r=ax((0,D.useCallback)(()=>Vx(t,e.slug),[t,e.slug])),i=sx(),[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 Ax(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 Hx(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 Dx(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 nS({named:e}){let t=j(),n=ax((0,D.useCallback)(()=>Rx(t,e),[t,e])),r=sx(),[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 zx(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 Bx(t,e,i),await n.reread()}),children:`Give it back to the box`})},i))]})]})}var rS=[{tab:`overview`,name:`Overview`},{tab:`members`,name:`Members`},{tab:`keys`,name:`Keys`},{tab:`limits`,name:`Limits`},{tab:`providers`,name:`Providers`}];function iS(){let e=j(),t=Sr().org??``,[n,r]=Xi(),i=rS.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`overview`,a=ax((0,D.useCallback)(()=>Tx(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(ox(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:rS,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)(tS,{org:a.value}),i===`members`&&(0,A.jsx)($x,{named:t,seats:a.value?.quotas.seats??null}),i===`keys`&&(0,A.jsx)(Gx,{named:t}),a.value!==void 0&&i===`limits`&&(0,A.jsx)(Yx,{org:a.value,onSaved:a.reread}),i===`providers`&&(0,A.jsx)(nS,{named:t})]})}var aS=`minmax(0,1.2fr) minmax(0,1fr) minmax(0,1fr) 60px`;function oS(){let e=j(),t=ax((0,D.useCallback)(()=>wx(e),[e])),n=sx(),[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 Ex(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:aS,labels:[`Organization`,`Slug`,`Id`,``]}),t.value.map(e=>(0,A.jsxs)(fh,{columns:aS,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 sS=[`production`,`sandbox`],cS=[`phone`,`whatsapp`],lS=`minmax(0,1.1fr) 110px minmax(0,1fr) 150px 80px`;function uS(){let e=j(),t=ax((0,D.useCallback)(()=>wx(e),[e])),[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(sS[0]),o=ax((0,D.useCallback)(()=>n===``?Promise.resolve(void 0):tx(e,n,i),[e,n,i])),s=sx(),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(cS[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 nx(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:sS.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:cS.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:lS,labels:[`Number`,`Channel`,`Agent`,`Said by`,``]}),o.value.map(t=>(0,A.jsxs)(fh,{columns:lS,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 rx(e,n,t.route.number??``),await o.reread()}),children:`Forget`})})]},`${t.route.channel}-${t.route.number??t.route.agent}`))]})]})]})}var dS=`/v1/ops`;async function fS(e){try{return await e}catch(e){if(e instanceof na&&(e.status===404||e.status===405))return null;throw e}}var pS=np({google:np({configured:L(),client_id:P().nullish(),redirect_uri:P().nullish()})});async function mS(e){return fS(k(e,`${dS}/signin`).then(e=>pS.parse(e)))}async function hS(e,t){await oa(e,`${dS}/signin/google`,t)}async function gS(e){await ca(e,`${dS}/signin/google`)}var _S=[`starttls`,`tls`,`none`],vS=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 yS(e){return fS(k(e,`${dS}/mail`).then(e=>vS.parse(e)))}async function bS(e,t){await oa(e,`${dS}/mail`,t)}async function xS(e){await ca(e,`${dS}/mail`)}async function SS(e,t){let n=np({sent:L(),error:P().nullish()}).parse(await sa(e,`${dS}/mail/test`,{to:t}));return{sent:n.sent,error:n.error??null}}var CS=np({name:P().nullish(),logo_url:P().nullish(),accent:P().nullish()});async function wS(e){return fS(k(e,`${dS}/brand`).then(e=>CS.parse(e)))}async function TS(e,t){await oa(e,`${dS}/brand`,t)}var ES=`Pinecall`,DS=`#5b3df5`,OS=/^#[0-9a-fA-F]{6}$/;function kS(){let e=j(),t=ax((0,D.useCallback)(()=>wS(e),[e])),n=sx(),[r,i]=(0,D.useState)(ES),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(DS),[l,u]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{t.value!==void 0&&t.value!==null&&(i(t.value.name??ES),o(t.value.logo_url??``),c(t.value.accent??DS))},[t.value]),t.value===void 0)return(0,A.jsx)(Nm,{children:t.refused});if(t.value===null)return(0,A.jsx)(FS,{});let d=async i=>{i.preventDefault(),u(!1),u(await n.move(async()=>{await TS(e,{name:r.trim(),logo_url:a.trim(),accent:s}),await t.reread()}))},f=OS.test(s)?s:DS;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 AS(){let e=j(),t=ax((0,D.useCallback)(()=>yS(e),[e])),n=sx(),[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)(FS,{});let l=t.value,u=async r=>{r.preventDefault(),c(null),await n.move(async()=>{c(await SS(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)(jS,{kept:l,busy:n.busy,onCancel:l.configured?()=>i(!1):void 0,onSave:async r=>{await n.move(async()=>{await bS(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 xS(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 jS({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)(_S.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:_S.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 MS(){let e=j(),t=ax((0,D.useCallback)(()=>mS(e),[e])),n=sx(),[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)(FS,{});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 hS(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 gS(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 NS=[{tab:`signin`,name:`Sign-in`},{tab:`email`,name:`Email`},{tab:`brand`,name:`Brand`}];function PS(){let[e,t]=Xi(),n=NS.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:NS,on:n,onPick:e=>t(e===`signin`?{}:{tab:e})}),n===`signin`&&(0,A.jsx)(MS,{}),n===`email`&&(0,A.jsx)(AS,{}),n===`brand`&&(0,A.jsx)(kS,{})]})}function FS(){return(0,A.jsx)(V,{children:(0,A.jsx)(Mm,{children:`This gateway does not have this door yet.`})})}var IS=100,LS=`minmax(0,1.2fr) 110px 110px 140px 140px`,RS=`130px minmax(0,1fr) minmax(0,1.4fr) 110px 80px 80px 90px`;function zS(){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 ix(e,t,IS);n(e=>r?a.rows:[...e,...a.rows]),i(e=>r?a.totals:VS(e,a.totals)),o(a.next??null),c(!0)}catch(e){f(ox(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:LS,labels:[`Organization`,`Minutes>`,`Messages>`,`Tokens>`,`Cost>`]}),Object.entries(r).map(([e,t])=>(0,A.jsxs)(fh,{columns:LS,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:RS,labels:[`When`,`Organization`,`Agent · call`,`What`,`Min>`,`Msgs>`,`Cost>`]}),t.map(e=>(0,A.jsxs)(fh,{columns:RS,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:BS(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 BS(e){return new Date(e*1e3).toISOString().slice(0,16).replace(`T`,` `)}function VS(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 HS({children:e}){let{operator:t}=tb();return t===null?null:t?e:(0,A.jsx)(Xr,{to:`/`,replace:!0})}var US=3e3;function WS(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(),US);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{lines:n,error:i}}function GS(e){return e.status!==`ended`}var KS=/^\+[1-9]\d{4,14}$/;function qS(){let e=j(),[t,n]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return kb(e).then(e=>{t||n(e!==null&&e.ready?e:null)},()=>void 0),()=>{t=!0}},[e]),t}function JS({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 YS({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 Mb(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)(JS,{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 XS({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(),!KS.test(p)){f(`A number is written whole, with its country: +14176743169.`);return}u(!0),f(null);try{let t=await Mb(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)(JS,{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 ZS=np({threads:R(np({contact:P(),name:P().nullish(),unread:F().nullish()}))});async function QS(e,t){try{let n=ZS.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 $S(e,t,n){await sa(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/read`,{})}async function eC(e,t,n,r){await sa(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/messages`,{text:r})}async function tC(e,t,n){await sa(e,`/v1/calls/${encodeURIComponent(t)}/verbs`,n_.parse({verb:`say`,text:n}))}function nC(e){return e.direction===`outbound`?e.to:e.from}function rC(e){let t=new Map;for(let n of e){let e=n.caller?.id??n.caller?.phone??nC(n)??n.call,r=t.get(e);if(r===void 0){t.set(e,{contact:e,name:n.caller?.name??null,handle:iC(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 iC(e){let t=nC(e);return t===null?e.channel===`web`?`web visitor`:`—`:t.startsWith(`+`)?og(t):e.channel===`web`?`web visitor`:t}function aC(e){return e.name!==null&&e.name!==``?e.name:e.contact.startsWith(`+`)?og(e.contact):e.contact}function oC(e){if(e.name===null||e.name===``)return e.handle===`web visitor`?`W`:e.contact.startsWith(`+`)?e.contact.slice(-2):void 0}function sC(e,t){if(e.channel===`phone`)return!0;let n=ky();for(let e of t)n=My(n,e);return n.room!==null}function cC(e,t,n){let r=[],i=t[0]?.ts??e.started_at??0;n&&r.push({kind:`call`,text:lC(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 lC(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 uC(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 dC=500;async function fC(e,t){let n=[],r=0;for(;;){let i=Bv.parse(await k(e,`/v1/calls/${t}/events`,{after:r,limit:dC}));if(n.push(...i.entries),i.next===null||i.entries.length<dC)return n;r=i.next}}var pC=12;function mC(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,pC)??[],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 fC(t,e.call),i=sC(e,r);n.current.set(e.call,{seq:e.last_seq,voice:i,messages:cC(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 hC(){let e=Sr(),t=e.agent??``,n=e.call,r=vr(),i=j(),a=WS(t),o=(0,D.useMemo)(()=>rC(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=qS(),p=_C(t,a.lines.length),m=o.find(e=>n!==void 0&&e.lines.some(e=>e.call===n))??o[0],h=s.trim().toLowerCase(),g=o.filter(e=>h===``||`${gC(e,p)} ${e.handle} ${uC(e)}`.toLowerCase().includes(h));return(0,D.useEffect)(()=>{m!==void 0&&p!==null&&(p.get(m.contact)?.unread??0)!==0&&$S(i,t,m.contact).catch(()=>void 0)},[m?.contact,p,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)}),f!==null&&(0,A.jsx)(`button`,{type:`button`,className:`ib-new`,title:`Call a number`,"aria-expanded":u,onClick:()=>d(!u),children:`+`}),u&&f!==null&&(0,A.jsx)(`div`,{className:`ib-dial`,children:(0,A.jsxs)(`div`,{className:`dial-panel`,children:[(0,A.jsxs)(`div`,{className:`dial-panel-head`,children:[(0,A.jsx)(`span`,{className:`dial-panel-title`,children:`Call a number`}),(0,A.jsx)(`button`,{type:`button`,className:`dial-panel-close`,onClick:()=>d(!1),"aria-label":`close`,children:`×`})]}),(0,A.jsx)(XS,{agent:t,outbound:f,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&&g.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`Nobody here matches “`,s,`”.`]}),g.map(e=>(0,A.jsx)(vC,{thread:e,name:gC(e,p),unread:p?.get(e.contact)?.unread??0,on:e===m,onOpen:()=>void r(`/a/${t}/calls/${e.latest.call}`)},e.contact))]})]}),m===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)(bC,{agent:t,thread:m,name:gC(m,p),door:p!==null,outbound:f},m.contact)]})}function gC(e,t){return t?.get(e.contact)?.name??aC(e)}function _C(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 vC({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:oC(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:yC(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:uC(e)}),n>0&&(0,A.jsx)(`span`,{className:`ib-unread`,children:n})]})]})]})}function yC(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 bC({agent:e,thread:t,name:n,door:r,outbound:i}){let a=vr(),o=j(),{messages:s,voice:c,loading:l,error:u}=mC(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 tC(o,x.call,d.trim()):await eC(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:oC(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)(YS,{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)(xC,{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 xC({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 SC(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 CC(e,t){return e==null?`null`:typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?JSON.stringify(e):typeof e==`number`?DC(e,t):Array.isArray(e)?`[${e.map(e=>CC(e,t?.items)).join(`,`)}]`:TC(e,t)}function wC(e,t){return typeof e==`string`?e:CC(e,t)}function TC(e,t){let n=EC(e,t)?.properties;return`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${CC(t,n?.[e])}`).join(`,`)}}`}function EC(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 DC(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)?OC(e):Number.isInteger(e)?`${e}.0`:String(e)}function OC(e){let[t=``,n=``]=e.toExponential().split(`e`);return`${t}e${n.startsWith(`-`)?`-`:`+`}${n.replace(/^[+-]/,``).padStart(2,`0`)}`}var kC=[`transcription_delay`,`end_of_turn_delay`],AC=[`llm_node_ttft`,`tts_node_ttfb`,`e2e_latency`],jC=[...kC,...AC];function MC(e){return HC(e).map(([e,t])=>({field:e,value:FC(t),unit:null}))}function NC(e,t){return IC(e,``,t)}function PC(){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 FC(e){return e<0?`—`:e<1?`${Math.round(e*1e3)} ms`:`${e.toFixed(2)} s`}function IC(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(...IC(a,`${e}.`,o)):r.push({field:e,value:wC(a,o),unit:LC(i)}))}return r}function LC(e){return Dy[e]??null}function RC(e,t){let n=PC(),r=[];for(let[i,a]of Object.entries(e))for(let e of a)VC(e,t)&&r.push({kind:i,readings:NC(e,n.get(i))});return r}var zC=[`turn.user`,`turn.agent`];function BC(e){let t=UC(e);return jC.filter(e=>(t.get(e)??[]).length>0).map(e=>{let n=t.get(e)??[];return{name:e,seconds:WC(n),max:Math.max(...n),turns:n.length}})}function VC(e,t){return`speech_id`in e&&e.speech_id===t}function HC(e){let t=e.role===`user`?kC:AC,n=e.metrics,r=[];for(let e of t){let t=n[e];typeof t==`number`&&r.push([e,t])}return r}function UC(e){let t=new Map(jC.map(e=>[e,[]]));for(let n of e){if(!zC.includes(n.type))continue;let e=n.data.metrics;for(let n of jC){let r=e?.[n];typeof r==`number`&&t.get(n)?.push(r)}}return t}function WC(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 GC(e,t={}){let n=j(),[r,i]=(0,D.useState)(ky),[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:ky()},r=!1,a=null,s=()=>i({...t.current}),u=()=>{r=!0,a?.()};return(async()=>{let i=0;try{i=await KC(n,e,t,l)}catch(e){c(String(e)),o(`ended`);return}if(!r){if(s(),t.current.status===`ended`){o(`ended`);return}a=qy(la(n,`/v1/calls/${e}/events`,{after:i}),n,{onEntry(e){t.current=My(t.current,e),l.current.onEntry?.(e),qC(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 KC(e,t,n,r){let i;try{i=await fC(e,t)}catch(e){if(e instanceof na&&e.status===404)return 0;throw e}for(let e of i)n.current=My(n.current,e),r.current.onEntry?.(e),qC(e,n.current,r.current);return i.at(-1)?.seq??0}function qC(e,t,n){if(e.type!==`custom`)return;let r=t.custom.at(-1);r!==void 0&&n.onCustom?.(r)}function JC(e){let t=(0,D.useRef)([]),n=GC(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 YC({agent:e,call:t}){let{lines:n}=tb(),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)(XC,{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)(QC,{call:i,yours:t!==null},i)})}function XC({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:ZC(e)})]})}function ZC(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 QC({call:e,yours:t}){let[n,r]=(0,D.useState)(`call`),i=JC(e),{state:a}=i,o=new Set,s=BC(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?`—`:FC(t.seconds)},l=ew(a),u=[[`Turns`,String(a.turns.length)],[`ttft`,c(`llm_node_ttft`)],[`e2e`,c(`e2e_latency`)],[`Cost`,Yh(a.cost?.eur)],[`Tokens in`,tw(l.in)],[`Tokens out`,tw(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)(XC,{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:$C(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:nw(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:rw(a.app_state[e])})]},e))]}),i.error!==null&&(0,A.jsx)(`p`,{className:`inspector-refused`,children:i.error})]})}function $C(e){if(e.role===`agent`){let t=[];return typeof e.metrics.llm_node_ttft==`number`&&t.push(`ttft ${FC(e.metrics.llm_node_ttft)}`),typeof e.metrics.e2e_latency==`number`&&t.push(`e2e ${FC(e.metrics.e2e_latency)}`),e.interrupted&&t.push(`interrupted`),t.join(` · `)}let t=[];return typeof e.metrics.transcription_delay==`number`&&t.push(`stt ${FC(e.metrics.transcription_delay)}`),t.push(e.speech_id),t.join(` · `)}function ew(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 tw(e){return e.toLocaleString(`en-US`).replace(/,/g,` `)}function nw(e){let t=Object.entries(e).map(([e,t])=>`${e}=${rw(t)}`);return t.length===0?`no arguments`:t.join(` · `)}function rw(e){return typeof e==`string`?e:JSON.stringify(e)}var iw=`supervisor.`;function aw(e){if(!e.type.startsWith(iw))return null;let t=Rv(e);switch(t.type){case`supervisor.whispered`:return{said:`supervisor whispered: ${t.data.text}`,by:ow(t.data.by)};case`supervisor.said`:return{said:`supervisor made the agent say: ${t.data.text}`,by:ow(t.data.by)};case`supervisor.took_over`:return{said:`supervisor took the line`,by:ow(t.data.by)};case`supervisor.released`:return{said:`supervisor handed the line back`,by:ow(t.data.by)};case`supervisor.transferred`:return{said:`supervisor transferred the call to ${t.data.to}`,by:ow(t.data.by)};case`supervisor.ended`:return{said:`supervisor ended the call${sw(t.data.reason)}`,by:ow(t.data.by)};default:return null}}function ow(e){return e.name??e.id}function sw(e){return e==null?``:`: ${e}`}function cw(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=lw(a,t);if(e===null){r.push(a);continue}i(),n.push(e)}return i(),n}function lw(e,t){let n=e.seq,r=aw(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=uw(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=dw(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=dw(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 uw(e,t,n){return dw(e.turns,e=>e.role===t&&e.speech_id===n)}function dw(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(t(r))return r}}function fw(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 pw=new Map,mw=1,hw=.18;function gw(e,t,n){let[r,i]=(0,D.useState)(()=>n?t.length:pw.get(e)??0),a=(0,D.useRef)(t.length);return a.current=t.length,(0,D.useEffect)(()=>{if(n){pw.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(mw,Math.ceil(n*hw)));return pw.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 _w=80;function vw({watched:e,pending:t,onConfirmed:n}){let r=bw(e.entries),i=cw(r,e.state),{streaming:a,settled:o}=fw(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<_w},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)(yw,{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)(yw,{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 yw({speech:e,text:t,instant:n,done:r}){let i=gw(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 bw(e){let t=new Set;return e.filter(e=>!t.has(e.seq)&&(t.add(e.seq),!0))}var xw={"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 Sw(e,t){return`/v1/agents/${encodeURIComponent(e)}/dev/${xw[t]}/${t}`}async function Cw(e,t,n,r={}){return sa(e,Sw(t,n),r)}var ww=z({agent:P().nullable(),states:R(P())}),Tw=z({call:P()});async function Ew(e,t){return ww.parse(await Cw(e,t,`chat.roster`))}async function Dw(e,t,n,r){let i={agent:t,...n===``?{}:{as:n},...r===``?{}:{golden:r}};return Tw.parse(await Cw(e,t,`chat.start`,i)).call}async function Ow(e,t,n,r){Tw.parse(await Cw(e,t,`chat.say`,{call:n,text:r}))}async function kw(e,t,n){Tw.parse(await Cw(e,t,`chat.end`,{call:n}))}function Aw(){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)(Mw,{agent:t}):(0,A.jsx)(Nw,{agent:t,call:n})}),(0,A.jsx)(YC,{agent:t,call:n??null})]})}function jw({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 Mw({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 Ew(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 Dw(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)(jw,{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 Nw({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=JC(t),u=l.state.status===`ended`||l.connection===`ended`,d=async()=>{try{await kw(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)(jw,{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)(vw,{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)(Pw,{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 Pw({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 Ow(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 Fw=z({golden:P(),model:P(),call:P()}),Iw=z({metric:P(),score:F(),passed:L(),reason:P(),criteria:P(),judge_calls:I()}),Lw=z({model:P(),golden:P(),scores:R(Iw),summary:fp(P(),Zf()).nullable()}),Rw=z({models:R(P()),goldens:R(P()),metrics:R(P()),judge_calls:I(),runs:R(Lw),failures:R(z({model:P(),golden:P(),metric:P()}))}),zw=z({runs:R(z({id:P(),agent:P(),started_at:F(),finished_at:F().nullable(),status:mp([`running`,`done`,`failed`]),calls:R(Fw),matrix:Rw.nullable(),error:P().nullable()}))}),Bw=200;async function Vw(e){return zw.parse(await k(e,`/v1/evals/runs`,{limit:Bw})).runs}async function Hw(e,t){return zw.parse(await k(e,`/v1/evals/runs`,{agent:t,limit:Bw})).runs}var Uw=z({held:I(),settled:I(),percent:F()}),Ww=z({judge:P(),before:Uw.nullable(),now:Uw.nullable(),delta:F().nullable()}),Gw=z({call:P(),judge:P(),seqs:R(I()),reason:P()}),Kw=z({agent:P(),window:F(),baseline:F(),threshold:F(),drift:z({judges:R(Ww),notJudged:z({now:I(),before:I()}),broke:R(Gw),worst:F().nullable()})});async function qw(e,t,n,r){return Kw.parse(await Cw(e,t,`drift.read`,{agent:t,window:n,baseline:r}))}var Jw=z({check:P(),status:P(),detail:P()}),Yw=z({call:P(),agent:P(),passed:L(),verdicts:R(Jw)});async function Xw(e,t){return Yw.parse(await sa(e,`/v1/evals/replay/${encodeURIComponent(t)}`,{}))}var Zw=z({path:P(),candidate:z({name:P(),input:R(P())}),notes:R(P())});async function Qw(e,t,n){return Zw.parse(await Cw(e,t,`promote.write`,{call:n}))}var $w=z({run:P(),folder:P(),goldens:R(P())}),eT=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 tT(e,t,n){return $w.parse(await Cw(e,t,`reproductions.roster`,{run:n}))}async function nT(e,t,n,r){return eT.parse(await Cw(e,t,`reproductions.read`,{run:n,golden:r}))}var rT=`minmax(0,1.2fr) minmax(0,1.3fr) 90px minmax(0,1fr) 80px`,iT=`minmax(0,1fr) 150px 70px minmax(0,2fr) 90px`;function aT(){let e=j(),{agents:t,lines:n}=tb(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return Vw(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=>oT(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:rT,labels:[`Agent`,`Last suite`,`Judged`,`Held on real calls`,``]}),l.map(e=>(0,A.jsxs)(fh,{columns:rT,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:iT,labels:[`Caller`,`Agent`,`Score`,`Why`,`When>`]}),c.slice(0,40).map(e=>(0,A.jsxs)(fh,{columns:iT,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 oT(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 sT=z({agent:P().nullable(),golden:P().nullable(),questions:I(),cases:R(P())});async function cT(e,t){return oy.parse(await k(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function lT(e,t){return sy.parse(await ca(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function uT(e,t){return sT.parse(await Cw(e,t,`memory.roster`,{agent:t}))}async function dT(e,t){return ly.parse(await Cw(e,t,`memory.eval`,{agent:t}))}async function fT(e,t){return py.parse(await Cw(e,t,`memory.extraction`,{agent:t}))}var pT=z({facts:R(z({id:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:ip([P(),F()]).nullish()});async function mT(e,t){try{return pT.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 hT(e,t){await ca(e,`/v1/memory/facts/${encodeURIComponent(t)}`)}var gT=z({facts:R(z({id:P(),agent:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:P().nullish()});async function _T(e,t,n){let r={};t!==``&&(r.q=t),n!==null&&(r.after=n);try{return gT.parse(await k(e,`/v1/memory`,r))}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}var vT=`150px 140px minmax(0,1fr) 100px 64px`;function yT(e){return e.startsWith(`+`)?og(e):e}function bT(e){return e instanceof Error?e.message:String(e)}function xT(){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),_T(e,r,null).then(e=>{t||(o(e===null?null:e.facts),c(e?.next??null))},e=>{t||u(bT(e))}),()=>{t=!0}},[e,r]);let d=async()=>{if(s!==null)try{let t=await _T(e,r,s);if(t===null)return;o(e=>[...e??[],...t.facts]),c(t.next??null)}catch(e){u(bT(e))}},f=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${yT(t.contact)} stays.`)){u(null);try{await hT(e,t.id),o(e=>(e??[]).filter(e=>e.id!==t.id))}catch(e){u(bT(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:vT,labels:[`Caller`,`Agent`,`Remembered`,`Written`,`Action>`]}),a.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:vT},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:yT(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 ST(e){let[t,n]=await Promise.all([ay.parse(await k(e,`/v1/knowledge`)),Ey.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)??[]}))}function CT(e,t){return`/v1/knowledge/${encodeURIComponent(e)}/files/${t.split(`/`).map(encodeURIComponent).join(`/`)}`}async function wT(e,t){return Cy.parse(await k(e,`/v1/knowledge/${encodeURIComponent(t)}`))}async function TT(e,t,n){return wy.parse(await k(e,CT(t,n)))}async function ET(e,t,n,r){return Ty.parse(await oa(e,CT(t,n),{text:r}))}async function DT(e,t,n){await ca(e,CT(t,n))}var OT=`minmax(0,1fr) 110px 90px 150px 70px`,kT=`new`;function AT(e){return e instanceof Error?e.message:String(e)}function jT(){let e=j(),t=Sr().base??``,[n,r]=Xi(),i=n.get(`file`),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(null),y=(0,D.useCallback)(async()=>{o(await wT(e,t))},[e,t]);(0,D.useEffect)(()=>{let e=!1;return y().catch(t=>{e||v(AT(t))}),()=>{e=!0}},[y]),(0,D.useEffect)(()=>{let n=!1;if(g(null),i!==null){if(i===kT){c(``),u(``),f(``);return}return TT(e,t,i).then(e=>{n||(c(e.path),u(e.text),f(e.text))},e=>{n||v(AT(e))}),()=>{n=!0}}},[e,t,i]);let b=e=>r(e===null?{}:{file:e}),x=async()=>{let n=s.trim();if(n===``){v(`name the file first: a path like faq/horarios.md`);return}m(!0),v(null);try{let r=await ET(e,t,n,l);f(l),g(`${r.path} kept · ${r.chunks} chunk${r.chunks===1?``:`s`} · ${Math.round(r.took_ms)} ms`),await y(),i!==n&&b(n)}catch(e){v(AT(e))}finally{m(!1)}},S=async n=>{if(window.confirm(`Take ${n} out of ${t}? The agent stops searching it on the next call.`)){v(null);try{await DT(e,t,n),i===n&&b(null),await y()}catch(e){v(AT(e))}}},C=async n=>{let r=Array.from(n.target.files??[]);if(n.target.value=``,r.length!==0){m(!0),v(null);try{for(let n of r)await ET(e,t,n.name,await n.text());await y(),b(r[r.length-1].name),g(`${r.length} file${r.length===1?``:`s`} added`)}catch(e){v(AT(e))}finally{m(!1)}}},w=l!==d||i===kT&&s.trim()!==``;return(0,A.jsxs)(sh,{width:1060,children:[(0,A.jsx)(ch,{title:t,back:(0,A.jsx)(Wi,{to:`/docs`,children:`← Docs`}),ledeWidth:640,lede:`The documents the agent searches, one file each. Open one to read or change it, add one from your disk or write it here, take one out. Every change is searchable on the next call.`,actions:(0,A.jsxs)(`div`,{className:`od-actions`,children:[(0,A.jsxs)(`label`,{className:p?`ui-button ui-button-form od-upload od-busy`:`ui-button ui-button-form od-upload`,children:[`Add files…`,(0,A.jsx)(`input`,{type:`file`,accept:`.md,.markdown,.txt,text/markdown,text/plain`,multiple:!0,disabled:p,onChange:e=>void C(e)})]}),(0,A.jsx)(U,{kind:`primary`,size:`form`,disabled:p,onClick:()=>b(kT),children:`Write one`})]})}),(0,A.jsx)(Nm,{children:_}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:`Files`,meta:a===null?void 0:`${a.files.length} file${a.files.length===1?``:`s`}`}),a===null?(0,A.jsx)(Mm,{children:_===null?`Asking the gateway…`:`The files could not be read.`}):a.kept?a.files.length===0?(0,A.jsx)(Mm,{children:`No file in this base. Add one above.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:OT,labels:[`File`,`Characters`,`Chunks`,`Arrived`,``]}),a.files.map(e=>(0,A.jsxs)(fh,{columns:OT,onClick:()=>b(e.path),children:[(0,A.jsx)(`span`,{className:i===e.path?`ui-cell-strong ui-clip od-open`:`ui-cell-strong ui-clip`,children:e.path}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.chars.toLocaleString(`en-US`)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell`,children:Qh(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell od-row-end`,children:(0,A.jsx)(Bm,{danger:!0,onClick:()=>void S(e.path),children:`Take out`})})]},e.path))]}):(0,A.jsx)(Mm,{children:"This base was pushed before its files were kept, so there is nothing to open here yet. Push it again from its project (`pinecall docs push`), or add a file: from then on the files are kept."})]}),i!==null&&(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:i===kT?`A new file`:i,meta:i===kT?void 0:`${l.length.toLocaleString(`en-US`)} characters`,children:(0,A.jsx)(Bm,{onClick:()=>b(null),children:`Close`})}),(0,A.jsxs)(`div`,{className:`od-editor`,children:[i===kT&&(0,A.jsx)(`input`,{className:`ui-input od-path`,value:s,placeholder:`its path in the base: faq/horarios.md`,spellCheck:!1,onChange:e=>c(e.target.value)}),(0,A.jsx)(`textarea`,{className:`ui-textarea od-text`,value:l,spellCheck:!1,placeholder:`# Horarios
|
|
63
|
+
|
|
64
|
+
De lunes a viernes, de 9:00 a 20:00.`,onChange:e=>u(e.target.value)}),(0,A.jsxs)(`div`,{className:`od-editor-foot`,children:[(0,A.jsx)(U,{kind:`primary`,size:`form`,disabled:p||!w,onClick:()=>void x(),children:p?`Keeping…`:i===kT?`Add to the base`:`Save`}),(0,A.jsx)(`span`,{className:`od-said`,children:h??(w?`Not kept yet.`:`Markdown. Headings are what a search finds a passage by.`)})]})]})]})]})}var MT=`minmax(0,1fr) 90px 140px 150px minmax(0,1fr)`;function NT(e){return e instanceof Error?e.message:String(e)}function PT(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return ST(e).then(e=>{t||n(e)},e=>{t||i(NT(e))}),()=>{t=!0}},[e]),(0,A.jsxs)(sh,{width:1060,tight:!0,children:[(0,A.jsx)(ch,{title:`Docs`,ledeWidth:640,lede:"Every base of documents in this world, and which agents search it. Open a base to read, add, edit or take out its files; attach one to an agent in its Settings. A project pushes a whole folder with `pinecall docs push`."}),(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:MT,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,`Read by`]}),t.map(e=>(0,A.jsxs)(fh,{columns:MT,to:`/docs/${encodeURIComponent(e.base)}`,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 FT=`lk.transcription`,IT=`lk.transcription_final`,LT=`lk.chat`,RT=1500,zT=`→`,BT=`←`,VT=`✗`;function HT(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 UT(e){return e.split(/(\s+)/).filter(e=>e.length>0)}function WT(e){let t=aw(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:`${zT} ${String(n.name)}(${KT(n.arguments)})`};case`tool.result`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${BT} ${String(n.name)} ${GT(n)}`};case`error`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`error`,text:`${VT} ${String(n.message)}`};default:return null}}function GT(e){return e.error!==void 0&&e.error!==null?`error: ${KT(e.error)}`:typeof e.summary==`string`?e.summary:e.output===void 0?`nothing`:KT(e.output)}function KT(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 qT({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)(JT,{line:e},e.id):(0,A.jsx)(YT,{mark:e},e.id))]}),n]})}function JT({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:[UT(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 YT({mark:e}){return(0,A.jsx)(`p`,{className:`talk-mark talk-mark-${e.tone}`,children:e.text})}function XT({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 ZT(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 QT=Object.defineProperty,$T=(e,t,n)=>t in e?QT(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,eE=(e,t,n)=>$T(e,typeof t==`symbol`?t:t+``,n),tE=class{constructor(){eE(this,`_locking`),eE(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 nE(e,t){if(!e)throw Error(t)}var rE=34028234663852886e22,iE=-34028234663852886e22,aE=4294967295,oE=2147483647,sE=-2147483648;function cE(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>oE||e<sE)throw Error(`invalid int 32: `+e)}function lE(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>aE||e<0)throw Error(`invalid uint 32: `+e)}function uE(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>rE||e<iE))throw Error(`invalid float 32: `+e)}var dE=Symbol(`@bufbuild/protobuf/enum-type`);function fE(e){let t=e[dE];return nE(t,`missing enum type on enum object`),t}function pE(e,t,n,r){e[dE]=mE(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function mE(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=gE(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 hE(e,t,n){let r={};for(let e of t){let t=gE(e);r[t.localName]=t.no,r[t.no]=t.localName}return pE(r,e,t),r}function gE(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var _E=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 vE(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 _E),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 yE(){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 bE(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 xE=4294967296;function SE(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>=xE&&(i+=r/xE|0,r%=xE)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?DE(r,i):EE(r,i)}function CE(e,t){let n=EE(e,t),r=n.hi&2147483648;r&&(n=DE(n.lo,n.hi));let i=wE(n.lo,n.hi);return r?`-`+i:i}function wE(e,t){var n=TE(e,t);if(e=n.lo,t=n.hi,t<=2097151)return String(xE*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()+OE(s)+OE(o)}function TE(e,t){return{lo:e>>>0,hi:t>>>0}}function EE(e,t){return{lo:e|0,hi:t|0}}function DE(e,t){return t=~t,e?e=~e+1:t+=1,EE(e,t)}var OE=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function kE(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 AE(){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 jE(){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=>nE(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>nE(/^[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),SE(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),SE(e)},dec(e,t){return CE(e,t)},uDec(e,t){return wE(e,t)}}}var ME=jE(),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 NE;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(NE||={});function PE(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 FE(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?ME.zero:`0`;case G.DOUBLE:case G.FLOAT:return 0;case G.BYTES:return new Uint8Array;case G.STRING:return``;default:return 0}}function IE(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 LE(e,t){this.v=e,this.k=t}function RE(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 zE(e){if(Array.isArray(e))return e}function BE(e,t,n){return(t=XE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function VE(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function HE(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 UE(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
65
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function WE(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 GE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?WE(Object(n),!0).forEach(function(t){BE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):WE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function KE(e,t){if(e==null)return{};var n,r,i=qE(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 qE(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 zE(e)||HE(e,t)||ZE(e,t)||UE()}function JE(e){return zE(e)||VE(e)||ZE(e)||UE()}function YE(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 XE(e){var t=YE(e,`string`);return typeof t==`symbol`?t:t+``}function ZE(e,t){if(e){if(typeof e==`string`)return RE(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)?RE(e,t):void 0}}function QE(e){return function(){return new $E(e.apply(this,arguments))}}function $E(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof LE;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)}$E.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},$E.prototype.next=function(e){return this._invoke(`next`,e)},$E.prototype.throw=function(e){return this._invoke(`throw`,e)},$E.prototype.return=function(e){return this._invoke(`return`,e)};var eD;(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`})(eD||={});var tD=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(lE(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return cE(e),kE(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){uE(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){lE(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){cE(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return cE(e),e=(e<<1^e>>31)>>>0,kE(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=ME.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=ME.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=ME.enc(e);return bE(t.lo,t.hi,this.buf),this}sint64(e){let t=ME.enc(e),n=t.hi>>31;return bE(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=ME.uEnc(e);return bE(t.lo,t.hi,this.buf),this}},nD=class{constructor(e,t){this.varint64=yE,this.uint32=AE,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 eD.Varint:for(;this.buf[this.pos++]&128;);break;case eD.Bit64:this.pos+=4;case eD.Bit32:this.pos+=4;break;case eD.LengthDelimited:let n=this.uint32();this.pos+=n;break;case eD.StartGroup:for(;;){let e=K(this.tag(),2),n=e[0],r=e[1];if(r===eD.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 ME.dec(...this.varint64())}uint64(){return ME.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,ME.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 ME.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ME.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 rD(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 iD(e){let t=e.field.localName,n=Object.create(null);return n[t]=aD(e),[n,()=>n[t]]}function aD(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 FE(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 oD(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 sD=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),cD=[];for(let e=0;e<sD.length;e++)cD[sD[e].charCodeAt(0)]=e;cD[45]=sD.indexOf(`+`),cD[95]=sD.indexOf(`/`);var lD={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=cD[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
|
|
66
|
+
`: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+=sD[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=sD[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=sD[i|r>>6],t+=sD[r&63],n=0}return n&&(t+=sD[i],t+=`=`,n==1&&(t+=`=`)),t}};function uD(e,t,n){pD(t,e);let r=t.runtime.bin.makeReadOptions(n),i=oD(e.getType().runtime.bin.listUnknownFields(e),t.field),a=K(iD(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 dD(e,t,n,r){pD(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(fD(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 fD(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 pD(e,t){nE(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function mD(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:!IE(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function hD(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?FE(e.T,e.L):void 0;break;case`message`:t[n]=void 0}}function gD(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(_E.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 _D(e,t){return gD(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 vD={ignoreUnknownFields:!1},yD={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function bD(e){return e?Object.assign(Object.assign({},vD),e):vD}function xD(e){return e?Object.assign(Object.assign({},yD),e):yD}var SD=Symbol(),CD=Symbol();function wD(){return{makeReadOptions:bD,makeWriteOptions:xD,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${TD(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)}ED(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(iD(o),2),t=e[0],a=e[1];ED(t,c,o.field,n,o),dD(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(!mD(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!AD(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=jD(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&&fD(e,o)){let n=uD(e,o,t),i=jD(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 OD(e,t,n??NE.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||IE(e,t)))return ND(e,t)},debug:TD}}function TD(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 ED(e,t,n,r,i){let a=n.localName;if(n.repeated){if(nE(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${TD(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${TD(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=kD(n.T,e,r.ignoreUnknownFields,!0);t!==CD&&o.push(t);break;case`scalar`:try{o.push(OD(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${TD(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: ${TD(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=DD(n.K,a)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${TD(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=kD(n.V.T,c,r.ignoreUnknownFields,!0);e!==CD&&(s[l]=e);break;case`scalar`:try{s[l]=OD(n.V.T,c,NE.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${TD(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];gD(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=kD(n.T,t,r.ignoreUnknownFields,!1);switch(c){case SD:hD(n,e);break;case CD:break;default:e[a]=c}break;case`scalar`:try{let r=OD(n.T,t,n.L,!1);switch(r){case SD:hD(n,e);break;default:e[a]=r}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${TD(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}function DD(e,t){if(e===G.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1}return OD(e,t,NE.BIGINT,!0).toString()}function OD(e,t,n,r){if(t===null)return r?FE(e,n):SD;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&&uE(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?lE(i):cE(i),i;case G.INT64:case G.SFIXED64:case G.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=ME.parse(t);return n?a.toString():a;case G.FIXED64:case G.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=ME.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 lD.dec(t)}throw Error()}function kD(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:SD;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 CD}throw Error(`cannot decode enum ${e.typeName} from JSON: ${TD(t)}`)}function AD(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function jD(e,t,n){if(e.kind==`map`){nE(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()]=ND(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()]=MD(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){nE(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(ND(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(MD(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 ND(e.T,t);case`enum`:return MD(e.T,t,n.enumAsInteger);case`message`:return _D(e.T,t).toJson(n)}}function MD(e,t,n){return nE(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function ND(e,t){switch(e){case G.INT32:case G.SFIXED32:case G.SINT32:case G.FIXED32:case G.UINT32:return nE(typeof t==`number`),t;case G.FLOAT:case G.DOUBLE:return nE(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case G.STRING:return nE(typeof t==`string`),t;case G.BOOL:return nE(typeof t==`boolean`),t;case G.UINT64:case G.FIXED64:case G.INT64:case G.SFIXED64:case G.SINT64:return nE(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case G.BYTES:return nE(t instanceof Uint8Array),lD.enc(t)}}var PD=Symbol(`@bufbuild/protobuf/unknown-fields`),FD={readUnknownFields:!0,readerFactory:e=>new nD(e)},ID={writeUnknownFields:!0,writerFactory:()=>new tD};function LD(e){return e?Object.assign(Object.assign({},FD),e):FD}function RD(e){return e?Object.assign(Object.assign({},ID),e):ID}function zD(){return{makeReadOptions:LD,makeWriteOptions:RD,listUnknownFields(e){return e[PD]??[]},discardUnknownFields(e){delete e[PD]},writeUnknownFields(e,t){let n=e[PD];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[PD])||(i[PD]=[]),i[PD].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==eD.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}BD(e,t,n,c,r)}if(i&&(c!=eD.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:BD,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!mD(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}GD(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&&GD(e,t,n,r)}}}function BD(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=WD;if(n.kind==`scalar`&&n.L>0&&(c=UD),a){let n=e[o];if(r==eD.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(VD(t,new l,i,n)):gD(e[o])?VD(t,e[o],i,n):(e[o]=VD(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let u=K(HD(n,t,i),2),d=u[0],f=u[1];e[o][d]=f}}function VD(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 HD(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=WD(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=WD(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=VD(t,new e.V.T,n,void 0)}}if(a===void 0&&(a=FE(e.K,NE.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=FE(e.V.T,NE.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T}return[a,o]}function UD(e,t){let n=WD(e,t);return typeof n==`bigint`?n.toString():n}function WD(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 GD(e,t,n,r){nE(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(nE(Array.isArray(t)),e.packed)YD(n,o,e.no,t);else for(let r of t)JD(n,o,e.no,r)}else JD(n,o,e.no,t);break;case`message`:if(i){nE(Array.isArray(t));for(let i of t)qD(n,r,e,i)}else qD(n,r,e,t);break;case`map`:nE(typeof t==`object`&&!!t);for(let i of Object.entries(t)){var a=K(i,2);let t=a[0],o=a[1];KD(n,r,e,t,o)}}}function KD(e,t,n,r,i){e.tag(n.no,eD.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:nE(r==`true`||r==`false`),a=r==`true`}switch(JD(e,n.K,1,a),n.V.kind){case`scalar`:JD(e,n.V.T,2,i);break;case`enum`:JD(e,G.INT32,2,i);break;case`message`:nE(i!==void 0),e.tag(2,eD.LengthDelimited).bytes(i.toBinary(t))}e.join()}function qD(e,t,n,r){let i=_D(n.T,r);n.delimited?e.tag(n.no,eD.StartGroup).raw(i.toBinary(t)).tag(n.no,eD.EndGroup):e.tag(n.no,eD.LengthDelimited).bytes(i.toBinary(t))}function JD(e,t,n,r){nE(r!==void 0);let i=K(XD(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function YD(e,t,n,r){if(!r.length)return;e.tag(n,eD.LengthDelimited).fork();let i=K(XD(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function XD(e){let t=eD.Varint;switch(e){case G.BYTES:case G.STRING:t=eD.LengthDelimited;break;case G.DOUBLE:case G.FIXED64:case G.SFIXED64:t=eD.Bit64;break;case G.FIXED32:case G.SFIXED32:case G.FLOAT:t=eD.Bit32}let n=G[e].toLowerCase();return[t,n]}function ZD(){return{setEnumType:pE,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`&&!gD(s,t.T)?s=new t.T(s):t&&t.kind===`scalar`&&t.T===G.BYTES&&(s=$D(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($D):$D(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]=$D(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=>gD(e,l)?e:new l(e));else{let e=o[n];a[n]=l.fieldWrapper?l.typeName===`google.protobuf.BytesValue`?$D(e):e:gD(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)=>PE(e.T,t,i[n]));case`enum`:return r.every((e,t)=>PE(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&&!gD(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!gD(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return PE(G.INT32,r,i);case`scalar`:return PE(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 PE(G.INT32,r.value,i.value);case`scalar`:return PE(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=>PE(G.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>PE(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(QD);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]=QD(n)}}else a=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:QD(t.value)}:{case:void 0}:QD(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 QD(e){if(e===void 0)return e;if(gD(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function $D(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function eO(e,t,n){return{syntax:e,json:wD(),bin:zD(),util:Object.assign(Object.assign({},ZD()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return vE(this,e,t,n)},makeEnum:hE,makeEnumType:mE,getEnumType:fE,makeExtension(e,t,n){return rD(this,e,t,n)}}}var tO=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 nO(e,t){let n=aO(e);return t?n:uO(lO(n))}function rO(e){return nO(e,!1)}var iO=aO;function aO(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 oO=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),sO=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),cO=e=>`${e}\$`,lO=e=>sO.has(e)?cO(e):e,uO=e=>oO.has(e)?cO(e):e,dO=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=rO(e)}addField(e){nE(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 fO(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=nO(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??iO(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??NE.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 dO(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var q=eO(`proto3`,e=>new tO(e,e=>fO(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]=FE(t.T,t.L)}}}),pO=class e extends _E{constructor(e){super(),this.seconds=ME.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=ME.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:ME.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)}};pO.runtime=q,pO.typeName=`google.protobuf.Timestamp`,pO.fields=q.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var mO=q.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:pO},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:hO,repeated:!0},{no:5,name:`events`,kind:`message`,T:_O,repeated:!0}]),hO=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:gO,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),gO=q.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:pO},{no:3,name:`value`,kind:`scalar`,T:2}]),_O=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:pO},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:pO,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),vO=q.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),yO=q.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),bO=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`}]),xO=q.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),SO=q.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),CO=q.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),wO=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`}]),TO=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`}]),EO=q.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),DO=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`}]),OO=q.makeEnum(`livekit.PacketTrailerFeature`,[{no:0,name:`PTF_USER_TIMESTAMP`},{no:1,name:`PTF_FRAME_ID`},{no:2,name:`PTF_USER_DATA`}]),kO=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:AO,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:bk}]),AO=q.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),jO=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(bO),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}]),MO=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(NO)},{no:4,name:`tracks`,kind:`message`,T:RO,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:jO},{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(PO)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:q.getEnumType(wO)},{no:18,name:`kind_details`,kind:`enum`,T:q.getEnumType(FO),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:zO,repeated:!0},{no:20,name:`client_protocol`,kind:`scalar`,T:5},{no:21,name:`capabilities`,kind:`enum`,T:q.getEnumType(gk),repeated:!0}]),NO=q.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),PO=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`}]),FO=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`}]),IO=q.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),LO=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:JO,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(YO)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),RO=q.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:q.getEnumType(yO)},{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(bO)},{no:10,name:`layers`,kind:`message`,T:JO,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:LO,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(IO)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:bk},{no:19,name:`audio_features`,kind:`enum`,T:q.getEnumType(DO),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(vO)},{no:21,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(OO),repeated:!0}]),zO=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(IO)},{no:5,name:`frame_encoding`,kind:`message`,T:BO,opt:!0},{no:6,name:`schema`,kind:`message`,T:WO,opt:!0}]),BO=q.makeMessageType(`livekit.DataTrackFrameEncoding`,()=>[{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.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`}]),HO=q.makeMessageType(`livekit.DataTrackSchemaEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(UO),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),UO=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`}]),WO=q.makeMessageType(`livekit.DataTrackSchemaId`,()=>[{no:1,name:`name`,kind:`scalar`,T:9},{no:2,name:`encoding`,kind:`message`,T:HO}]),GO=q.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),KO=q.makeMessageType(`livekit.DataBlobKey`,()=>[{no:1,name:`generic`,kind:`scalar`,T:9,oneof:`key`},{no:2,name:`schema_id`,kind:`message`,T:WO,oneof:`key`}]),qO=q.makeMessageType(`livekit.DataBlob`,()=>[{no:1,name:`key`,kind:`message`,T:KO},{no:2,name:`contents`,kind:`scalar`,T:12}]),JO=q.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(xO)},{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}]),YO=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`}]),XO=q.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:q.getEnumType(ZO)},{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:nk,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:ek,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:rk,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:ik,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:mO,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:ok,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:sk,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:ck,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:lk,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:Tk,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:Ek,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:Dk,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:QO,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),ZO=q.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),QO=q.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:q.getEnumType(IO)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),$O=q.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:nk,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:ok,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:sk,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:ck,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:lk,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:Tk,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:Ek,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:Dk,oneof:`value`}]),ek=q.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:tk,repeated:!0}]),tk=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}]),nk=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}]),rk=q.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),ik=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:ak,repeated:!0}]),ak=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}]),ok=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}]),sk=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}]),ck=q.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),lk=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:uk,oneof:`value`},{no:4,name:`compressed_payload`,kind:`scalar`,T:12,oneof:`value`}]),uk=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}]),dk=q.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),fk=q.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,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:`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}]),pk=q.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),mk=q.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:q.getEnumType(hk)},{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(gk),repeated:!0}]),hk=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`}]),gk=q.makeEnum(`livekit.ClientInfo.Capability`,[{no:0,name:`CAP_UNUSED`},{no:1,name:`CAP_PACKET_TRAILER`},{no:2,name:`CAP_COMPRESSION_DEFLATE_RAW`}]),_k=q.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:vk},{no:2,name:`screen`,kind:`message`,T:vk},{no:3,name:`resume_connection`,kind:`enum`,T:q.getEnumType(CO)},{no:4,name:`disabled_codecs`,kind:`message`,T:yk},{no:5,name:`force_relay`,kind:`enum`,T:q.getEnumType(CO)}]),vk=q.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:q.getEnumType(CO)}]),yk=q.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:AO,repeated:!0},{no:2,name:`publish`,kind:`message`,T:AO,repeated:!0}]),bk=q.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),xk=q.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),Sk=q.makeEnum(`livekit.DataStream.CompressionType`,[{no:0,name:`NONE`},{no:1,name:`DEFLATE_RAW`}]),Ck=q.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:q.getEnumType(xk)},{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`}),wk=q.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),Tk=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(IO)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:Ck,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:wk,oneof:`content_header`},{no:11,name:`inline_content`,kind:`scalar`,T:12,opt:!0},{no:12,name:`compression`,kind:`enum`,T:q.getEnumType(Sk)}],{localName:`DataStream_Header`}),Ek=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`}),Dk=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`}),Ok=q.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),kk=q.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),Ak=q.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),jk=q.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),Mk=q.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Jk,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Jk,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:Hk,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:Fk,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:Uk,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Xk,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:rA,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:oA,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:cA,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:SA,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:TA,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:OA,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:lA,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:kA,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:iA,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:aA,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:Ik,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:Rk,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Zk,oneof:`message`},{no:22,name:`store_data_blob_request`,kind:`message`,T:$k,oneof:`message`},{no:23,name:`get_data_blob_request`,kind:`message`,T:tA,oneof:`message`}]),Nk=q.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:Wk,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Jk,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Jk,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:Hk,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Yk,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Kk,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:oA,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:Uk,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:dA,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:fA,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:mA,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:gA,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:yA,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:CA,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:qk,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:Gk,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:AA,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:NA,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:PA,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:IA,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:wA,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:VA,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:bA,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:Lk,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:zk,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:Bk,oneof:`message`},{no:30,name:`store_data_blob_response`,kind:`message`,T:eA,oneof:`message`},{no:31,name:`get_data_blob_response`,kind:`message`,T:nA,oneof:`message`}]),Pk=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:JO,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(YO)}]),Fk=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(yO)},{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(bO)},{no:9,name:`layers`,kind:`message`,T:JO,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:Pk,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(IO)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(vO)},{no:17,name:`audio_features`,kind:`enum`,T:q.getEnumType(DO),repeated:!0},{no:18,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(OO),repeated:!0}]),Ik=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(IO)},{no:4,name:`frame_encoding`,kind:`message`,T:BO,opt:!0},{no:5,name:`schema`,kind:`message`,T:WO,opt:!0}]),Lk=q.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:zO}]),Rk=q.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),zk=q.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:zO}]),Bk=q.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:Vk}}]),Vk=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`}),Hk=q.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:q.getEnumType(kk)},{no:3,name:`final`,kind:`scalar`,T:8}]),Uk=q.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),Wk=q.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:kO},{no:2,name:`participant`,kind:`message`,T:MO},{no:3,name:`other_participants`,kind:`message`,T:MO,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:uA,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:_k},{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:fk},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:AO,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),Gk=q.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:uA,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:_k},{no:3,name:`server_info`,kind:`message`,T:fk},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Kk=q.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:RO}]),qk=q.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Jk=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}}]),Yk=q.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:MO,repeated:!0}]),Xk=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:dk,repeated:!0}]),Zk=q.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:Qk,repeated:!0}]),Qk=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:GO}],{localName:`UpdateDataSubscription_Update`}),$k=q.makeMessageType(`livekit.StoreDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:qO}]),eA=q.makeMessageType(`livekit.StoreDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`key`,kind:`message`,T:KO}]),tA=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:KO}]),nA=q.makeMessageType(`livekit.GetDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:qO}]),rA=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(xO)},{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}]),iA=q.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:q.getEnumType(DO),repeated:!0}]),aA=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}]),oA=q.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(wO)},{no:3,name:`action`,kind:`enum`,T:q.getEnumType(sA)},{no:4,name:`regions`,kind:`message`,T:jA}]),sA=q.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),cA=q.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:JO,repeated:!0}]),lA=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}]),uA=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}]),dA=q.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:tk,repeated:!0}]),fA=q.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:kO}]),pA=q.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:q.getEnumType(SO)},{no:3,name:`score`,kind:`scalar`,T:2}]),mA=q.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:pA,repeated:!0}]),hA=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(Ak)}]),gA=q.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:hA,repeated:!0}]),_A=q.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(xO)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),vA=q.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:_A,repeated:!0}]),yA=q.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:_A,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:vA,repeated:!0}]),bA=q.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:Ok,repeated:!0}]),xA=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}]),SA=q.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:xA,repeated:!0}]),CA=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}]),wA=q.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:kO},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:MO},{no:4,name:`other_participants`,kind:`message`,T:MO,repeated:!0}]),TA=q.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Jk},{no:2,name:`subscription`,kind:`message`,T:Xk},{no:3,name:`publish_tracks`,kind:`message`,T:Kk,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:DA,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Jk},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:EA,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:Lk,repeated:!0}]),EA=q.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),DA=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(kk)}]),OA=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(jk),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`}]),kA=q.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),AA=q.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),jA=q.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:MA,repeated:!0}]),MA=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}]),NA=q.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:q.getEnumType(EO)}]),PA=q.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(FA)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:Hk,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:Fk,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:Uk,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:lA,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:iA,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:aA,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:Ik,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:Rk,oneof:`request`}]),FA=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`}]),IA=q.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),LA=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}]),RA=q.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:mk},{no:2,name:`connection_settings`,kind:`message`,T:LA},{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:Fk,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Jk},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:q.getEnumType(TO)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:TA}]),zA=q.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:q.getEnumType(BA)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),BA=q.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),VA=q.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function HA(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var UA={exports:{}},WA=UA.exports,GA;function KA(){return GA?UA.exports:(GA=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(WA,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})})(UA),UA.exports)}var qA=KA(),JA;(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`})(JA||={});var YA;(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`})(YA||={});var XA=qA.getLogger(YA.Default);Object.values(YA).map(e=>qA.getLogger(e)),XA.setDefaultLevel(JA.info);function ZA(e,t){let n=qA.getLogger(e);return n.setDefaultLevel(XA.getLevel()),t?QA(n,t):n}function QA(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 $A=qA.getLogger(YA.E2EE),ej=new Set,tj=$A.setLevel.bind($A);$A.setLevel=(e,t)=>{tj(e,t);let n=$A.getLevel();ej.forEach(e=>e(n))};function nj(e){return ej.add(e),()=>{ej.delete(e)}}var rj=7e3,ij=[0,300,1200,2700,4800,rj,rj,rj,rj,rj],aj=class{constructor(e){this._retryDelays=e===void 0?ij:[...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 oj(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 sj(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 cj(e){return this instanceof cj?(this.v=e,this):new cj(e)}function lj(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 cj?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 uj(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:cj(e[r](t)),done:!1}:i?i(t):t}:i}}function dj(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof sj==`function`?sj(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 fj={exports:{}},pj;function mj(){if(pj)return fj.exports;pj=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)}fj.exports=a,fj.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 fj.exports}var hj=mj(),gj=!0,_j=!0;function vj(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function yj(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,`addEventListener`).writable){Sj(`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 bj(e){return typeof e==`boolean`?(gj=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function xj(e){return typeof e==`boolean`?(_j=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function Sj(){if(typeof window==`object`){if(gj)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function Cj(e,t){_j&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function wj(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(vj(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(vj(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(vj(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=vj(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function Tj(e){return Object.prototype.toString.call(e)===`[object Object]`}function Ej(e){return Tj(e)?Object.keys(e).reduce(function(t,n){let r=Tj(e[n]),i=r?Ej(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function Dj(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?Dj(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{Dj(e,e.get(t),n)})}))}function Oj(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&&Dj(e,n,i)})}),i}var kj=Sj;function Aj(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),kj(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return kj(`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 jj(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function Mj(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 yj(e,`track`,e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}}function Nj(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 Pj(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=>Oj(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}),yj(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>Oj(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 Fj(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 Ij(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return Fj(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 Lj(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 Rj(e,t){t.version>102||yj(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var zj=Object.freeze({__proto__:null,fixNegotiationNeeded:Rj,shimAddTrackRemoveTrack:Ij,shimAddTrackRemoveTrackWithNative:Fj,shimGetSendersWithDtmf:Nj,shimGetUserMedia:Aj,shimMediaStream:jj,shimOnTrack:Mj,shimPeerConnection:Lj,shimSenderReceiverGetStats:Pj});function Bj(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){Cj(`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 Vj(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 Hj(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 Uj(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 Wj(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 Gj(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 Kj(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}),yj(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function qj(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){Cj(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Jj(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function Yj(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 Xj(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 Zj(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 Qj(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 $j=Object.freeze({__proto__:null,shimAddTransceiver:Yj,shimCreateAnswer:Qj,shimCreateOffer:Zj,shimGetDisplayMedia:Vj,shimGetParameters:Xj,shimGetStats:Wj,shimGetUserMedia:Bj,shimOnTrack:Hj,shimPeerConnection:Uj,shimRTCDataChannel:Jj,shimReceiverGetStats:Kj,shimRemoveStream:qj,shimSenderGetStats:Gj});function eM(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 tM(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 nM(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 rM(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(iM(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function iM(e){return e&&e.video!==void 0?Object.assign({},e,{video:Ej(e.video)}):e}function aM(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?(Cj(`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 oM(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 sM(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 cM(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var lM=Object.freeze({__proto__:null,shimAudioContext:cM,shimCallbacksAPI:nM,shimConstraints:iM,shimCreateOfferLegacy:sM,shimGetUserMedia:rM,shimLocalStreamsAPI:eM,shimRTCIceServerUrls:aM,shimRemoteStreamsAPI:tM,shimTrackEventTransceiver:oM}),uM={exports:{}},dM;function fM(){return dM?uM.exports:(dM=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
67
|
`).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
|
|
66
68
|
m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
|
|
67
69
|
`)},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 +94,26 @@ a=ice-pwd:`+e.password+`\r
|
|
|
92
94
|
o=`+(r||`thisisadapterortc`)+` `+i+` `+a+` IN IP4 127.0.0.1\r
|
|
93
95
|
s=-\r
|
|
94
96
|
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})(
|
|
97
|
+
`},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})(uM),uM.exports)}var pM=fM(),mM=HA(pM),hM=ZT({__proto__:null,default:mM},[pM]);function gM(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=mM.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,yj(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function _M(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||yj(e,`icecandidate`,e=>{if(e.candidate){let t=mM.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function vM(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=mM.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=mM.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=mM.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 yM(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},yj(e,`datachannel`,e=>(n(e.channel,e.target),e))}function bM(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 xM(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
98
|
a=extmap-allow-mixed`)!==-1){let n=t.sdp.split(`
|
|
97
99
|
`).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 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
|
|
100
|
+
`);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 SM(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 CM(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 wM=Object.freeze({__proto__:null,removeExtmapAllowMixed:xM,shimAddIceCandidateNullOrEmpty:SM,shimConnectionState:bM,shimMaxMessageSize:vM,shimParameterlessSetLocalDescription:CM,shimRTCIceCandidate:gM,shimRTCIceCandidateRelayProtocol:_M,shimSendThrowTypeError:yM});function TM(){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=Sj,r=wj(e),i={browserDetails:r,commonShim:wM,extractVersion:vj,disableLog:bj,disableWarnings:xj,sdp:hM};switch(r.browser){case`chrome`:if(!zj||!Lj||!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=zj,SM(e,r),CM(e),Aj(e,r),jj(e),Lj(e,r),Mj(e,r),Ij(e,r),Nj(e),Pj(e,r),Rj(e,r),gM(e),_M(e),bM(e),vM(e,r),yM(e,r),xM(e,r);break;case`firefox`:if(!$j||!Uj||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=$j,SM(e,r),CM(e),Bj(e,r),Uj(e,r),Wj(e,r),Hj(e),qj(e),Gj(e),Kj(e),Jj(e),Yj(e,r),Xj(e,r),Zj(e,r),Qj(e,r),gM(e),bM(e),vM(e,r),yM(e,r);break;case`safari`:if(!lM||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=lM,SM(e,r),CM(e),aM(e),sM(e),nM(e),eM(e),tM(e),oM(e),rM(e),cM(e),gM(e),_M(e),vM(e,r),yM(e,r),xM(e,r);break;default:n(`Unsupported browser!`)}return i}TM({window:typeof window>`u`?void 0:window});var EM,DM,OM=class extends (DM=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)}};EM=OM,OM.resolve=e=>Reflect.get(DM,`resolve`,EM).call(EM,e);var kM=/version\/(\d+(\.?_?\d+)+)/i,AM;function jM(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(AM===void 0||t)&&(AM=MM.find(e=>e.test.test(n))?.describe(n)),AM}var MM=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:NM(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:PM(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:NM(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:PM(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:NM(kM,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:PM(e)}}}];function NM(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 PM(e){return e.includes(`mac os`)?NM(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var FM=`2.22.3`,IM=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)}},LM=class extends IM{},RM;(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`})(RM||={});var zM=class e extends LM{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=RM[t]}static notAllowed(t,n,r){return new e(t,RM.NotAllowed,n,r)}static timeout(t){return new e(t,RM.Timeout)}static leaveRequest(t,n){return new e(t,RM.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,RM.InternalError,void 0,n)}static cancelled(t){return new e(t,RM.Cancelled)}static serverUnreachable(t,n){return new e(t,RM.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,RM.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,RM.ServiceNotFound,void 0,n)}},BM=class extends IM{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},VM=class extends IM{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},HM=class extends IM{constructor(e){super(10,e||`unsupported server`),this.name=`UnsupportedServer`}},UM=class extends IM{constructor(e){super(12,e||`unexpected connection state`),this.name=`UnexpectedConnectionState`}},WM=class extends IM{constructor(e){super(13,e||`unable to negotiate`),this.name=`NegotiationError`}},GM=class extends IM{constructor(e){super(14,e||`unable to publish data`),this.name=`PublishDataError`}},KM=class extends IM{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},qM=class extends LM{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:FA[t]}},JM;(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`})(JM||={});var YM=class extends LM{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=JM[t]}},XM=class extends IM{constructor(e){super(18,e),this.name=`SignalReconnectError`}},ZM;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(ZM||={}),(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})(ZM||={});var QM=class{};QM.setTimeout=function(){return setTimeout(...arguments)},QM.setInterval=function(){return setInterval(...arguments)},QM.clearTimeout=function(){return clearTimeout(...arguments)},QM.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 $M(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 eN(e,t){return e&&t?`${e}x${t}`:void 0}function tN(e){return Math.round(e*1e4)/1e4}function nN(e){let t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return t!==void 0&&n?tN(t/n):void 0}function rN(e,t){if(e.playoutDelay!==void 0)return tN(e.playoutDelay);let n=t?.totalPlayoutDelay,r=t?.totalSamplesCount;return n!==void 0&&r?tN(n/r):void 0}function iN(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($M({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:o(e),decoder:e.decoderImplementation,resolution:eN(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:nN(e),playoutDelay:rN(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($M({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:eN(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:eN(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=$M({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 aN(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 oN=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}}},sN=[`vp8`,`h264`],cN=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function lN(e){return!!sN.find(t=>t===e)}var uN=lN,dN;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(dN||={});var fN;(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}})(fN||={});var pN={h90:new oN(160,90,9e4,20),h180:new oN(320,180,16e4,20),h216:new oN(384,216,18e4,20),h360:new oN(640,360,45e4,20),h540:new oN(960,540,8e5,25),h720:new oN(1280,720,17e5,30),h1080:new oN(1920,1080,3e6,30),h1440:new oN(2560,1440,5e6,30),h2160:new oN(3840,2160,8e6,30)},mN={h120:new oN(160,120,7e4,20),h180:new oN(240,180,125e3,20),h240:new oN(320,240,14e4,20),h360:new oN(480,360,33e4,20),h480:new oN(640,480,5e5,20),h540:new oN(720,540,6e5,25),h720:new oN(960,720,13e5,30),h1080:new oN(1440,1080,23e5,30),h1440:new oN(1920,1440,38e5,30)},hN={h360fps3:new oN(640,360,2e5,3,`medium`),h360fps15:new oN(640,360,4e5,15,`medium`),h720fps5:new oN(1280,720,8e5,5,`medium`),h720fps15:new oN(1280,720,15e5,15,`medium`),h720fps30:new oN(1280,720,2e6,30,`medium`),h1080fps15:new oN(1920,1080,25e5,15,`medium`),h1080fps30:new oN(1920,1080,5e6,30,`medium`),original:new oN(0,0,7e6,30,`medium`)};function gN(e,t,n){var r,i;let a=kN(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&&(_N(d.audio,t),(r=d.audio).deviceId??(r.deviceId={ideal:`default`}),(s||l)&&(d.audio.processor=s??l)),d.video&&(_N(d.video,n),(i=d.video).deviceId??(i.deviceId={ideal:`default`}),(c||u)&&(d.video.processor=c??u)),d}function _N(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function vN(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`:_N(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 yN(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=bN();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 VN(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function bN(){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 xN(e){return e===`audioinput`?$.Source.Microphone:e===`videoinput`?$.Source.Camera:$.Source.Unknown}function SN(e){if(e===$.Source.Microphone)return`audioinput`;if(e===$.Source.Camera)return`videoinput`}function CN(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=rP()?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 wN(e){return e.split(`/`)[1].toLowerCase()}function TN(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Kk({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function EN(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?EN(e.track):{})}}function DN(){return typeof RTCRtpReceiver<`u`&&typeof RTCRtpReceiver.prototype.getSynchronizationSources==`function`}function ON(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 kN(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:aN(t)}}function AN(e){switch(e){case bO.CAMERA:return $.Source.Camera;case bO.MICROPHONE:return $.Source.Microphone;case bO.SCREEN_SHARE:return $.Source.ScreenShare;case bO.SCREEN_SHARE_AUDIO:return $.Source.ScreenShareAudio;default:return $.Source.Unknown}}function jN(e,t){return e.width*e.height<t.width*t.height}function MN(e,t){return e.layers?.find(e=>e.quality===t)}var NN=5e3,PN=[],FN;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(FN||={});var $=class e extends hj.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=XA,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),NN):this.handleAppVisibilityChanged()},this.loggerContextCb=r.loggerContextCb,this.log=ZA(r.loggerName??YA.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)),EN(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`&&(PN.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&PN.splice(PN.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),IN(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){LN(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=>{LN(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`,iN(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=ZA(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),PN.forEach(e=>{e.parentElement||(t=!1)}),t&&PN.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(){lP()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){lP()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function IN(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)),(!rP()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(rP()||eP())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function LN(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 yO.AUDIO;case t.Video:return yO.VIDEO;default:return yO.DATA}}e.kindToProto=i;function a(e){switch(e){case yO.AUDIO:return t.Audio;case yO.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return bO.CAMERA;case n.Microphone:return bO.MICROPHONE;case n.ScreenShare:return bO.SCREEN_SHARE;case n.ScreenShareAudio:return bO.SCREEN_SHARE_AUDIO;default:return bO.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case bO.CAMERA:return n.Camera;case bO.MICROPHONE:return n.Microphone;case bO.SCREEN_SHARE:return n.ScreenShare;case bO.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case Ak.ACTIVE:return r.Active;case Ak.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})($||={});var RN=`|`,zN=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function BN(e){let t=e.split(RN);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function VN(e){return new OM(t=>QM.setTimeout(t,e))}function HN(){return`addTransceiver`in RTCPeerConnection.prototype}function UN(){return`addTrack`in RTCPeerConnection.prototype}function WN(){if(!(`getCapabilities`in RTCRtpSender)||rP()||eP())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 GN(){if(!(`getCapabilities`in RTCRtpSender)||eP())return!1;if(rP()){let e=jM();if(e?.version&&gP(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&gP(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 KN(e){return e===`av1`||e===`vp9`}function qN(e){let t=e.getHeaderExtensionsToNegotiate?.call(e);if(!t||!e.setHeaderExtensionsToNegotiate)return!1;let n=t.find(e=>e.uri===zN);if(!n)return!1;if(n.direction!==`stopped`)return!0;n.direction=`sendrecv`;try{return e.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function JN(e,t){return KN(e)&&!!t?.simulcast&&!!t.scalabilityMode?.startsWith(`L1T`)}function YN(){let e=jM();return iP()||uP()||e?.name===`Chrome`&&gP(e.version,`113`)<0}var XN=`1.13.6`;function ZN(e){return e?gP(e,XN)>0:!1}function QN(e){return!document||iP()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function $N(){return typeof RTCPeerConnection>`u`?!1:HN()||UN()}function eP(){return jM()?.name===`Firefox`}function tP(){let e=jM();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function nP(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0&&!tP()}function rP(){return jM()?.name===`Safari`}function iP(){let e=jM();return e?.name===`Safari`||e?.os===`iOS`}function aP(){let e=jM();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&gP(e.osVersion,`17`)>=0}function oP(e){return e||=jM(),e?.name===`Safari`&&gP(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&gP(e.osVersion,`18.3`)>0}function sP(){return lP()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function cP(){let e=jM(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&gP(e.osVersion,t)>=0?!0:e.name===`Safari`&&gP(e.version,t)>=0}function lP(){return typeof document<`u`}function uP(){return navigator.product==`ReactNative`}function dP(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function fP(e){return dP(e)?e.hostname.split(`.`)[0]:null}function pP(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function mP(){if(!uP())return;let e=pP();if(e)return e.platform}function hP(){if(lP())return window.devicePixelRatio;if(uP()){let e=pP();if(e)return e.devicePixelRatio}return 1}function gP(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 _P(e){for(let t of e)t.target.handleResize(t)}function vP(e){for(let t of e)t.target.handleVisibilityChanged(t)}var yP=null,bP=()=>(yP||=new ResizeObserver(_P),yP),xP=null,SP=()=>(xP||=new IntersectionObserver(vP,{root:null,rootMargin:`0px`}),xP);function CP(e){let t=new mk({capabilities:e,sdk:hk.JS,protocol:17,clientProtocol:2,version:FM});return uP()&&(t.os=mP()??``),t}function wP(){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 TP;function EP(){if(!TP){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(),TP=K(r.stream.getAudioTracks(),1)[0],!TP)throw Error(`Could not get empty media stream audio track`);TP.enabled=!1}return TP.clone()}var DP=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 OP(e){return cN.includes(e)}function kP(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 AP(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function jP(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function MP(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 NP(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 PP(e){switch(e.reason){case RM.LeaveRequest:return e.context;case RM.Cancelled:return wO.CLIENT_INITIATED;case RM.NotAllowed:return wO.USER_REJECTED;case RM.ServerUnreachable:return wO.JOIN_FAILURE;default:return wO.UNKNOWN_REASON}}function FP(e){return e===void 0?void 0:Number(e)}function IP(e){return e===void 0?void 0:BigInt(e)}function LP(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function RP(e){return!!e&&e.kind==$.Kind.Audio}function zP(e){return!!e&&e.kind==$.Kind.Video}function BP(e){return LP(e)&&zP(e)}function VP(e){return LP(e)&&RP(e)}function HP(e){return!!e&&!e.isLocal}function UP(e){return!!e&&!e.isLocal}function WP(e){return HP(e)&&zP(e)}function GP(e){return e.isLocal}function KP(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 qP(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function JP(e,t){return lj(this,arguments,function*(){let n=e.getReader(),r=new Uint8Array;try{for(;;){let e=yield cj(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 cj(r.slice(0,t)),r=r.slice(t)}r.byteLength>0&&(yield yield cj(r))}finally{n.releaseLock()}})}function YP(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 XP(){return typeof CompressionStream<`u`}function ZP(){return XP()&&!eP()}function QP(e,t){let n=K(BN(t.id),2)[1];if(n?.startsWith(`TR`))return n;if(e.id.startsWith(`TR`))return e.id}function $P(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=eF(e,t);return n?r:rF(r,`v1`)}function eF(e,t){let n=new URL(AP(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),rF(n,`rtc`)}function tF(e){return rF(new URL(jP(e)),`validate`)}function nF(e){return e.endsWith(`/`)?e:`${e}/`}function rF(e,t){return e.pathname=`${nF(e.pathname)}${t}`,e}function iF(e){if(typeof e==`string`)return Nk.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return Nk.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function aF(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 oF(e,t){return e instanceof Error?e.name&&e.message?`${e.name}: ${e.message}`:e.name:`Encountered unknown ${t} error: ${String(e)}`}var sF=`lk_e2ee`,cF=`lk_e2ee_track_id`,lF;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(lF||={});var uF;(function(e){e.KeyRatcheted=`keyRatcheted`})(uF||={});var dF;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(dF||={});var fF;(function(e){e.Error=`cryptorError`})(fF||={});function pF(){return hF()||mF()}function mF(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0}function hF(){return typeof window<`u`&&window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function gF(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new $O({value:e.value})}hj.EventEmitter;var _F;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(_F||={});var vF=class extends IM{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_F.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}};function yF(){return nP()}function bF(e){return!!e?.worker&&(hF()||yF())}function xF(e){return!!(e?.timestamp||e?.frameId)}function SF(e){let t=[];return e?.timestamp&&t.push(OO.PTF_USER_TIMESTAMP),e?.frameId&&t.push(OO.PTF_FRAME_ID),t}function CF(e){if(!e||e.length===0)return;let t={};return e.includes(OO.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(OO.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}function wF(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&&QM.clearTimeout(r),r=QM.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&&QM.clearTimeout(r),c.forEach(t=>{let n=t.reject;return n(e)}),c=[]},u}var TF=2e3;function EF(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 DF=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(),TF),DN()&&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()}},OF=100,kF=class extends DF{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=EF(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=wF(()=>{this.updateDimensions()},OF),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?LN(this._mediaStreamTrack,t):IN(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 AF(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<OF){QM.setTimeout(()=>{this.updateVisibility()},OF);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`?hP():e||(hP()>2?2:1)}},AF=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=jF(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=jF(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)})})},this.onLeavePiP=()=>{var e;this.isPiP=jF(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??MF(e),this.isPiP=lP()&&jF(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=MF(this.element),this.isPiP=jF(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,SP().observe(this.element),bP().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=SP())==null||e.unobserve(this.element),(t=bP())==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 jF(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?MF(e,window.documentPictureInPicture?.window):!1}function MF(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 NF=class e extends hj.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=ZA(YA.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(dF.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(dF.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(dF.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(lF.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`:$A[r.level](r.msg,r.context)}},this.onWorkerError=e=>{this.log.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(dF.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(!pF())throw new BM(`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:$A.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=nj(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=nj(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 vF(`E2EEManager disposed`,_F.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 kF&&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===zB.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(!zP(e.track)||!iP())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:wN(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)}),t.on(lF.SetKey,(e,t)=>this.postKey(e,t??!0)).on(lF.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 DP;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 DP;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!==IO.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`?wN(n.mimeType):void 0,r)}setupE2EESender(e,t){if(!LP(e)||!t){t||this.log.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0,zP(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(nP()){let a={kind:`decode`,participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(sF in e&&cF in e){let a={kind:`updateCodec`,data:{trackId:t,previousTrackId:e[cF],codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(a),e[cF]=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[sF]=!0,e[cF]=t}})}handleSender(e,t,n,r){if(!(sF 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(nP()){this.log.info(`initialize script transform`);let i={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:xF(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:xF(r),packetTrailer:r}};this.worker.postMessage(a,[i.readable,i.writable])}e[sF]=!0}}};NF.disposeRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});var PF=300,FF=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>=PF;){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}},IF=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=>{XA.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(!bF(this.worker?{worker:this.worker}:void 0)&&!this.room?.hasE2EESetup){XA.warn(`frame metadata transform not supported; skipping extraction`);return}let r=new FF,i=e.mediaStreamID;this.extractors.set(i,r),e.frameMetadataExtractor=r,!this.room?.hasE2EESetup&&this.setupWorkerReceiver(n,i,!0)}setupPassthroughReceiver(e,t){if(yF()){`transform`in e&&(e.transform=null);return}if(this.worker&&bF({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(yF()){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)){XA.warn(`createEncodedStreams not supported`);return}let a;try{a=e.createEncodedStreams()}catch(e){XA.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 kF&&(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()}},LF=500,RF=15e3,zF=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=fP(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,VN(Math.min(LF*2**n,RF)))}getBackOffPromise(e){let t=new URL(e),n=t&&fP(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&fP(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};zF._instance=null;var BF=`default`,VF=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){XA.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{XA.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(rP()&&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!==BF)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===BF);if(!i){XA.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==BF&&e.groupId===(n??i.groupId));if(!a){XA.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};VF.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],VF.userMediaPromiseMap=new Map;var HF=65535,UF=4294967295,WF=class e{static u16(t){return new e(t,HF)}static u32(t){return new e(t,UF)}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}},GF=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*UF);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=WF.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)}},KF=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 qF(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 JF;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(JF||={});var YF=class e extends LM{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=JF[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,JF.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,JF.Reserved)}},XF={fromNumber(e){if(e===0)throw YF.reserved(e);if(e>HF)throw YF.tooLarge();return e}},ZF=class{constructor(){this.value=0}get(){return this.value+=1,this.value>HF?null:this.value}reset(){this.value=0}},QF={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==IO.NONE}},toProtobuf(e){return new zO({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?IO.GCM:IO.NONE})}},$F;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})($F||={});var eI=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new tE,this.nextTaskIndex=0}run(e){return J(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:$F.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=$F.RUNNING,yield e()}finally{t.status=$F.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())}},tI=[`client`],nI=class{constructor(){BE(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()}},rI=class extends Error{constructor(e,t){super(`non-serializable value at ${e} (${t})`),this.path=e,this.label=t}},iI=(e,t)=>aI(e,t,new Set),aI=(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 rI(t,sI(e));return e;case`object`:return oI(e,t,n);default:throw new rI(t,typeof e)}},oI=(e,t,n)=>{if(n.has(e))throw new rI(t,`circular reference`);if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new rI(t,`sparse array or array with non-index properties`);n.add(e);let r=e.map((e,r)=>aI(e,`${t}[${r}]`,n));return n.delete(e),r}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new rI(t,e.constructor?.name??`object`);n.add(e);let i={};for(let r of Object.keys(e)){let a=aI(e[r],`${t}.${r}`,n);Object.defineProperty(i,r,{value:a,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),i},sI=e=>Number.isNaN(e)?`NaN`:e>0?`Infinity`:`-Infinity`,cI=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=>cI(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=cI(e[n],t);Object.defineProperty(r,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),r},lI=Symbol(`machina.type`),uI=20,dI=class{constructor(e){BE(this,`id`,void 0),BE(this,`initialState`,void 0),BE(this,lI,`BehavioralFsm`),BE(this,`states`,void 0),BE(this,`emitter`,new nI),BE(this,`clients`,new WeakMap),BE(this,`knownClients`,new Set),BE(this,`childSubscriptions`,[]),BE(this,`disposed`,!1),BE(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>uI)throw this.transitionDepth=0,Error(`Max transition depth (${uI}) 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=>GE({inputName:e.inputName,args:cI(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=JE(t.split(`.`)),r=n[0],i=RE(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[lI]===`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=iI(e.args,`args`)}catch(t){if(!(t instanceof rI))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(!(lI in n))throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got a plain object`);t._child=fI(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 fI(e){if(!e||typeof e!=`object`)throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got ${String(e)}`);let t=e[lI];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 pI=class{constructor(e){BE(this,`id`,void 0),BE(this,`initialState`,void 0),BE(this,lI,`Fsm`),BE(this,`states`,void 0),BE(this,`bfsm`,void 0),BE(this,`context`,void 0),BE(this,`emitter`,new nI),BE(this,`disposed`,!1),this.id=e.id,this.initialState=e.initialState,this.context=e.context??{},this.bfsm=new dI(e),this.states=e.states,this.bfsm.on(`*`,(e,t)=>{if(t&&typeof t==`object`&&`client`in t){t.client;let n=KE(t,tI);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 mI(e){return new pI(e)}function hI(e){return e}function gI(e,t){return t.attemptId===e.attemptId}var _I=hI((e,t)=>{let n=e.ctx;if(gI(n,t))return`connected`}),vI=hI(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`connecting`}),yI=hI(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`reconnecting`}),bI=hI((e,t)=>{let n=e.ctx;return n.closeReason=t.reason,`disconnecting`}),xI={new:{connect:vI,close:bI},connecting:{connectComplete:_I,connectFailed:hI((e,t)=>{let n=e.ctx;return n.lastError=t.error,`closed`}),close:bI},connected:{reconnect:yI,transportFailed:hI((e,t)=>{let n=e.ctx;if(gI(n,t))return n.lastError=t.reason,`offline`}),close:bI},offline:{connect:vI,reconnect:yI,close:bI},reconnecting:{reconnectComplete:_I,reconnectFailed:hI((e,t)=>{let n=e.ctx;return n.lastError=t.error,t.recoverable?`offline`:`closed`}),close:bI},disconnecting:{closeComplete:`closed`},closed:{connect:vI,reconnect:yI}};function SI(){return mI({id:`signal`,initialState:arguments.length>0&&arguments[0]!==void 0?arguments[0]:`new`,context:{attemptId:0},states:xI})}var CI=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 OM((e,t)=>{let i=()=>{t(zM.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(zM.websocket(oF(t,`websocket`))),n.onclose=t=>{t.wasClean||t.code===1e3?e.close():e.error(zM.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 OM((e,t)=>{let r=()=>J(this,void 0,void 0,function*(){let r=new OM(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield OM.race([VN(250),r]);i?e(i):t(zM.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}},wI=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function TI(e){return e instanceof zM?e.reason!==RM.LeaveRequest&&e.reason!==RM.NotAllowed:!0}function EI(e){let t=wI.indexOf(e.case)>=0;return XA.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var DI;(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`})(DI||={});function OI(e){switch(e){case`connected`:return DI.CONNECTED;case`connecting`:return DI.CONNECTING;case`reconnecting`:return DI.RECONNECTING;case`disconnecting`:return DI.DISCONNECTING;default:return DI.DISCONNECTED}}var kI=250,AI=5e3,jI=class{get currentState(){return OI(this.lifecycleState)}get isDisconnected(){let e=this.currentState;return e===DI.DISCONNECTING||e===DI.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=XA,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=ZA(t.loggerName??YA.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new eI,this.queuedRequests=[],this.closingLock=new tE,this.connectionLock=new tE,this.machine=SI(),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 zM.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 zM.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:TI(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=CP(n.clientInfoCapabilities),l=$P(e,a?PI(t,c,n):yield FI(t,c,n,o),a).toString(),u=tF(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=aF(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 zM?e:zM.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(zM.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 CI(l);let f=!1;this.ws.opened.catch(()=>{f=!0});try{this.ws.closed.then(e=>{this.isEstablishingConnection&&!f&&t(zM.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(zM.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(zM.timeout(`signal connection timed out while waiting for the first message`))},AI)})])}catch(e){i.releaseLock(),t(e),this.close();return}finally{clearTimeout(o)}if(i.releaseLock(),!a.value)throw zM.internal(`no message received as first message`);let c=iF(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 VN(this.signalLatency));try{let t=yield e.read(),n=t.done,r=t.value;if(n)break;let i=iF(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,VN(kI)])}}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:NI(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,{answerSdp:e.sdp}),this.sendRequest({case:`answer`,value:NI(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,{candidate:e}),this.sendRequest({case:`trickle`,value:new Hk({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new Uk({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 lA({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 cA({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new SA({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:ME.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new kA({timestamp:ME.parse(Date.now()),rtt:ME.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new iA({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new oA({reason:wO.CLIENT_INITIATED,action:sA.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new Ik({pubHandle:e,name:t,encryption:n?IO.GCM:IO.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new Rk({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Zk({updates:[new Qk({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&&!EI(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 VN(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 Mk({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=MI(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=MI(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=QM.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&&QM.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=QM.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`),this.clearPingTimeout(),this.pingInterval&&QM.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:zM.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:zM.internal(`Unexpected first message`)}:{isValid:!1,error:zM.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`)?zM.notAllowed(e,n.status):zM.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let t=yield n.text();return zM.notAllowed(t,n.status)}return e instanceof zM?e:zM.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof zM?e:zM.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function MI(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 NI(e,t){return new Jk({sdp:e.sdp,type:e.type,id:t})}function PI(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`,uP()?`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 FI(e,t,n,r){return J(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new RA({clientInfo:t,connectionSettings:new LA({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(XP()){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=BA.GZIP}else s=o,c=BA.NONE;let l=new zA({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 II=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}},LI={},RI={},zI={exports:{}},BI;function VI(){if(BI)return zI.exports;BI=1;var e=zI.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`})}),zI.exports}var HI;function UI(){return HI?RI:(HI=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=VI(),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}})})}})(RI),RI)}var WI,GI;function KI(){if(GI)return WI;GI=1;var e=VI(),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 WI=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
101
|
`)+`\r
|
|
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
|
-
`),forget:(
|
|
103
|
-
`),knowledge:e.knowledge??``,bases:(e.bases??[]).map(e=>typeof e.k==`number
|
|
104
|
-
`)
|
|
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})}))});
|
|
102
|
+
`},WI}var qI;function JI(){if(qI)return LI;qI=1;var e=UI(),t=KI();return LI.grammar=VI(),LI.write=t,LI.parse=e.parse,LI.parseParams=e.parseParams,LI.parseFmtpConfig=e.parseFmtpConfig,LI.parsePayloads=e.parsePayloads,LI.parseRemoteCandidates=e.parseRemoteCandidates,LI.parseImageAttributes=e.parseImageAttributes,LI.parseSimulcastStreamList=e.parseSimulcastStreamList,LI}var YI=JI(),XI=.9,ZI=1e3,QI=20;function $I(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*XI),s=i?o:Math.min(o,ZI),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 eL={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,OfferAnswered:`offerAnswered`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},tL=class extends hj.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=XA,this.iceLog=XA,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=wF(e=>J(this,void 0,void 0,function*(){this.emit(eL.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),QI),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=ZA(t.loggerName??YA.PCTransport,()=>this.logContext),this.iceLog=ZA(YA.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new tE}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=dL(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=YI.parse(e.sdp??``);t.media.forEach(e=>{fL(e)}),this.log.debug(`setting pending initial offer before processing answer`),yield this.setMungedSDP(e,YI.write(t))}let t=YI.parse(e.sdp??``);t.media.forEach(e=>{let t=pL(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&&uL(t.media,e=>r.has(pL(e.mid))),n=YI.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(eL.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(eL.NegotiationComplete),e.sdp&&YI.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(eL.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=YI.parse(t.sdp??``);return n.media.forEach(e=>{fL(e)}),t.sdp=YI.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 WM(`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=YI.parse(n.sdp??``);r.media.forEach(e=>{fL(e),e.type===`audio`?cL(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!t.cid)return!1;let n=$I(e,t.cid,t.codec,t.maxbr,t.isScreenShare);return n!==void 0&&(n>0&&KN(t.codec)&&!rP()&&(this.ddExtID=nL(e,r,this.ddExtID)),!0)})});let i=this.getPlaceholderMids();if(i.size>0&&uL(r.media,e=>i.has(pL(e.mid))),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,{latestOfferId:this.latestOfferId,offerId:t});return}yield this.setMungedSDP(n,YI.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=YI.parse(e.sdp??``);return t.media.forEach(e=>{fL(e),e.type===`audio`&&cL(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,YI.write(t)),e})}getPlaceholderMids(){return lL(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 UM(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new UM(`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 WM(a)}})}};function nL(e,t,n){let r=rL(t,n);return r===void 0?n:(e.ext?.some(e=>e.uri===zN)||(e.ext??=[],e.ext.push({value:r,uri:zN})),r)}function rL(e,t){let n=iL(e,zN);return n===void 0?t!==0&&!aL(e,t,zN)?t:oL(e):aL(e,n,zN)?void 0:n}function iL(e,t){for(let n of e.media){let e=n.ext?.find(e=>e.uri===t);if(e)return e.value}}function aL(e,t,n){return e.media.some(e=>e.ext?.some(e=>e.value===t&&e.uri!==n))}function oL(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 sL(e,t){return e.split(`;`).some(e=>e.trim()===t)}function cL(e,t,n){let r=pL(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&&(sL(e.config,`stereo=1`)||(e.config+=`;stereo=1`),!0)))}function lL(e){let t=new Set;for(let n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}function uL(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 dL(e){let t=[],n=[],r=YI.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=pL(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&&(sL(e.config,`sprop-stereo=1`)&&t.push(r),!0)))}),{stereoMids:t,nackMids:n}}function fL(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 pL(e){return typeof e==`number`?e.toFixed(0):e}var mL=`vp8`,hL={audioPreset:fN.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:hN.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:mL,backupCodec:!0,preConnectBuffer:!1},gL={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},_L={deviceId:{ideal:`default`},resolution:pN.h720.resolution},vL={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new aj,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},yL={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},bL;(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`})(bL||={});var xL=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=yL.peerConnectionTimeout,this.log=XA,this.iceLog=XA,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=bL.CONNECTED:n.some(e=>e===`failed`)?this.state=bL.FAILED:n.some(e=>e===`connecting`)?this.state=bL.CONNECTING:n.every(e=>e===`closed`)?this.state=bL.CLOSED:n.some(e=>e===`closed`)?this.state=bL.CLOSING:n.every(e=>e===`new`)&&(this.state=bL.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${bL[t]} to ${bL[this.state]}`),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.loggerOptions=t,this.log=ZA(t.loggerName??YA.PCManager,()=>this.logContext),this.iceLog=ZA(YA.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new tL(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new tL(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,kk.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,kk.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=bL.NEW,this.connectionLock=new tE,this.remoteOfferLock=new tE}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===kk.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 OM((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(eL.OfferAnswered,o),e.signal.removeEventListener(`abort`,s))},o=e=>{e>r&&(a(),t())},s=()=>{a(),n(new WM(`negotiation aborted`))},c=setTimeout(()=>{a(),n(new WM(`negotiation timed out`))},this.peerConnectionTimeout);e.signal.addEventListener(`abort`,s),this.publisher.on(eL.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===kk.PUBLISHER||e===kk.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`),QM.clearTimeout(a),i(zM.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=QM.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(zM.internal(`could not establish pc connection`))},r);for(;this.state!==bL.CONNECTED;)if(yield VN(50),t?.signal.aborted){i(zM.cancelled(`room connection has been cancelled`));return}QM.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},SL=class{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new tE,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 UM(`engine closed`);let e=this.getChannel();if(!e)throw new UM(`DataChannel not found, kind: ${this.kind}`);if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new OM((n,r)=>{let i=()=>{s(),n()},a=()=>{s(),r(new UM(`DataChannel ${this.kind} closed while draining the buffer`))},o=()=>{s(),r(new UM(`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))}},CL=class extends SL{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&&XA.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)XA.error(e);else throw e}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=QM.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&&=(QM.clearInterval(this.statInterval),void 0),this.dropCount=0}},wL=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}},TL=class extends SL{constructor(e){super(e),this.messageBuffer=new wL,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 wL,this.sequence=1}},EL;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(EL||={});var DL=65536,OL=1048576,kL=8192,AL=262144;function jL(e){return e===EL.RELIABLE?DL:kL}function ML(e){return e===EL.RELIABLE?OL:AL}var NL=`_lossy`,PL=`_reliable`,FL=`_data_track`,IL=class{constructor(e){this.opts=e;let t=t=>({kind:t,lowWaterMark:jL(t),highWaterMark:ML(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new TL(Object.assign(Object.assign({},t(EL.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new CL(Object.assign(Object.assign({},t(EL.LOSSY)),{bufferFullBehavior:`drop`,shouldSkipSends:e.isReconnecting})),this.dataTrack=new CL(Object.assign(Object.assign({},t(EL.DATA_TRACK_LOSSY)),{bufferFullBehavior:`wait`,shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case EL.RELIABLE:return this.reliable;case EL.LOSSY:return this.lossy;case EL.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 EL.RELIABLE:return this.reliableSub;case EL.LOSSY:return this.lossySub;case EL.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(NL,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(PL,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(FL,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===PL)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===NL)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===FL)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()}},LL=typeof MediaRecorder<`u`,RL=LL?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},zL=class extends RL{constructor(e,t){if(!LL)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 BL(){return LL}var VL=1e3,HL=1e4,UL=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=wF(()=>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 tE,this.pauseUpstreamLock=new tE,this.trackChangeLock=new tE,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=>{LN(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&&(IN(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=>{IN(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]:VL;return function*(){if(e.kind===$.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);jM()?.os===`iOS`&&(yield VN(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield VN(50)}throw new VM(`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===kP(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),kP(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?VF.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 VM(`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=oj(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=>{LN(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),sP()&&(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=jM();if(e?.name===`Safari`&&gP(e.version,`12.0`)<0)throw new BM(`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(IN(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&&(LN(t._mediaStreamTrack,e),IN(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(!BL()){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 zL(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},HL)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},WL=class extends UL{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=EF(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,DO.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,DO.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=vN({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(){lP()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},TF))}setProcessor(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!uP()&&!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 yN(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(Q.AudioSilenceDetected)),e})}};function GL(e,t,n){switch(e.kind){case`audio`:return new WL(e,t,!1,void 0,n);case`video`:return new uR(e,t,!1,n);default:throw new VM(`unsupported track type: ${e.kind}`)}}var KL=Object.values(pN),qL=Object.values(mN),JL=Object.values(hN),YL=[pN.h180,pN.h360],XL=[mN.h180,mN.h360],ZL=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new oN(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)),QL=[`q`,`h`,`f`];function $L(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec,c=JN(s,r);if(!i&&!a&&!o||!t||!n)return[{}];i||(i=nR(e,t,n,s),XA.debug(`using video encoding`,i));let l=i.maxFramerate,u=new oN(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&KN(s)&&!c){let e=new sR(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=jM();if(YN()){let r=e.suffix==`h`?2:3,a=oP(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:QL[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),XA.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?oR(r?.screenShareSimulcastLayers)??iR(e,u):oR(r?.videoSimulcastLayers)??iR(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(aR(t,n,[e,p,u],l));if(r>=480)return d(aR(t,n,[e,u],l))}return d(aR(t,n,[u]))}function eR(e,t,n){return KN(e)&&!JN(e,t)?n[0]?.maxBitrate??0:n.reduce((e,t)=>e+(t.maxBitrate??0),0)}function tR(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&XA.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),$L(e.source===$.Source.ScreenShare,i,a,n)}function nR(e,t,n,r){let i=rR(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 rR(e,t,n){if(e)return JL;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?KL:qL}function iR(e,t){if(e)return ZL(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)?YL:XL}function aR(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=QL.length)return;let o=Math.min(e,t),s={rid:QL[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=jM(),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)}),uP()&&mP()===`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,XA.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),XA.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function oR(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 sR=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 cR(e){switch(e.source){case $.Source.Camera:return`maintain-framerate`;case $.Source.ScreenShare:return`maintain-resolution`;default:return`balanced`}}var lR=5e3,uR=class extends UL{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+=EF(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new tE}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!lP())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},TF))}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=dj(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=dj(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 KN(e)&&!JN(e,this.publishOptions)}setPublishingQuality(e){let t=[];for(let n=FN.LOW;n<=FN.HIGH;n+=1)t.push(new _A({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=vN({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=dj(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=$L(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`||!lN(n))continue;let i=Object.assign({},this.publishOptions),a=tR(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=dj(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)},lR))})}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=dj(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 dR(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 dR(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&&KN(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),sP()&&this.isInBackground&&this.source===$.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function dR(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=fR(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),eP()&&(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 fR(e){switch(e){case`f`:return FN.HIGH;case`h`:return FN.MEDIUM;case`q`:return FN.LOW;default:return FN.HIGH}}function pR(e,t,n,r){if(!n)return[new JO({quality:FN.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new sR(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 JO({quality:Math.min(FN.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 JO({quality:fR(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var mR=2e3,hR=`leave-reconnect`,gR=1e4,_R=3e4,vR=3,yR=3,bR;(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`})(bR||={});var xR=64e3,SR=class extends hj.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=yL.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=bR.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=XA,this.reliableReceivedState=new II(_R),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=XO.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 XO({value:$O.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&CR(t,t.value.value),this.emit(Z.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&CR(n,n.value.value),this.emit(Z.DataPacketReceived,n,IO.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 '${EL[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===hR&&(i=0),this.log.debug(`reconnecting in ${i}ms`),this.clearReconnectTimeout(),this.token&&this.emit(Z.TokenRefreshed,this.token),this.reconnectTimeout=QM.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===bR.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();OP(n)&&t.set(e.payload,n)}),this.emit(Z.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>J(this,void 0,void 0,function*(){this.url&&(yield fetch(jP(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===DI.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===DI.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(TO.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>J(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(jP(this.url),{method:`HEAD`}),VN(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=ZA(e.loggerName??YA.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jI(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new tE,this.dataProcessLock=new tE,this.dataChannels=new IL({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&&ZP(),c;if(s){i.pcManager||(yield i.configure(),i.applyInitialPublisherLayout());let e=yield i.pcManager?.publisher.createInitialOffer();e&&(c=NI(e.offer,e.offerId))}if(r?.aborted)throw zM.cancelled(`Connection aborted`);if(!a&&i.shouldFailOnV1Path)throw i.shouldFailOnV1Path=!1,zM.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 zM){if(o.reason===RM.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===RM.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 VM(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=QM.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(zM.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{QM.clearTimeout(r),t(e)},reject:()=>{QM.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(EL.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!==bL.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new xL(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new xL(`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===bL.CONNECTING?Date.now():void 0,[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===bL.CONNECTED){let e=this.pcState===bR.New;this.pcState=bR.Connected,e&&this.emit(Z.Connected,this.latestJoinResponse)}else e===bL.FAILED&&(this.pcState===bR.Connected||this.pcState===bR.Reconnecting)&&(this.pcState=bR.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?TO.RR_SUBSCRIBER_FAILED:TO.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===DI.RECONNECTING,i=[bL.FAILED,bL.CLOSING,bL.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`,TO.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 sA.DISCONNECT:this.emit(Z.Disconnected,e?.reason),this.close(`server leave: ${wO[e.reason]??e.reason}`);break;case sA.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(hR);break;case sA.RESUME:this.handleDisconnect(hR)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if((this.signalOpts?.e2eeEnabled||this.frameMetadataWorker&&!yF())&&hF()&&(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===CO.ENABLED&&(t.iceTransportPolicy=`relay`),t}applyInitialPublisherLayout(){this.createDataChannels(),uP()||this.addMediaSections(vR,yR)}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=qN(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(HN())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(UN())this.log.warn(`using add-track fallback`),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new UM(`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(HN())i=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(UN())this.log.debug(`using add-track fallback`),i=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new UM(`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=xF(r);if(yF()){i&&(e.transform=new RTCRtpScriptTransform(n,{kind:`encode`,packetTrailer:r}));return}if(!bF(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 UM(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),zP(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 UM(`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 UM(`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===SO.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||=QM.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==bR.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`,TO.RR_PUBLISHER_FAILED))},gR)}clearLostQualityTimeout(){this.lostQualityTimeout&&=(QM.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]:TO.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===CO.DISABLED||(this.pcManager?.currentState??bL.NEW)===bL.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 UM?(this.log.debug(`received unrecoverable error`,{error:e}),n=!1):(t||!(e instanceof XM))&&(this.fullReconnectOnNext=!0),n?this.handleDisconnect(`reconnect`,TO.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 UM(`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 XM;n=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){throw e instanceof zM&&e.reason===RM.NotAllowed?new UM(`could not reconnect, token might be expired`):new XM}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!==DI.CONNECTED)throw new XM(`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 UM(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new UM(`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 zM&&e.reason===RM.NotAllowed?new UM(`could not reconnect, token might be expired`):e instanceof zM&&e.reason===RM.LeaveRequest?e:new XM(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!==DI.CONNECTED)throw new XM(`Signal connection got severed during reconnect`);this.client.setReconnected();let n=this.dataChannelForKind(EL.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 UM(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return J(this,void 0,void 0,function*(){this.pcState=bR.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`);try{if(yield VN(mR),!this.pcManager)throw new UM(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=bR.Connected}catch(e){throw this.pcState=bR.Disconnected,zM.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcAck(e,t){return J(this,void 0,void 0,function*(){let n=new XO({destinationIdentities:[e],kind:ZO.RELIABLE,value:{case:`rpcAck`,value:new ck({requestId:t})}});yield this.sendDataPacket(n,EL.RELIABLE)})}sendDataPacket(e,t){return J(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=gF(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new QO({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===EL.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let n=e.toBinary(),r=Math.min(this.pcManager?.getMaxPublisherMessageSize()??xR,xR);if(r!==void 0&&r!==0&&n.byteLength>r)throw new GM(`cannot publish data packet larger than ${r} bytes (got ${n.byteLength})`);t===EL.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(EL.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(EL.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 UM(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw zM.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 VN(50)}throw zM.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![bL.CONNECTING,bL.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===bL.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 OM((e,t)=>J(this,void 0,void 0,function*(){if(!this.pcManager){t(new WM(`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 WM(`cannot negotiate on closed engine`)),this.on(Z.Closing,r),this.on(Z.Restarting,r),this.pcManager.publisher.off(eL.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(eL.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof WM&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,TO.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 TA({answer:this.pcManager.mode===`publisher-only`?i?NI({sdp:i.sdp,type:i.type}):void 0:o?NI({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?NI({sdp:r.sdp,type:r.type}):void 0:a?NI({sdp:a.sdp,type:a.type}):void 0,subscription:new Xk({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:TN(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new EA({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new Lk({info:QF.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 DA({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(EL.LOSSY),kk.PUBLISHER),t(this.dataChannelForKind(EL.RELIABLE),kk.PUBLISHER),t(this.dataChannelForKind(EL.LOSSY,!0),kk.SUBSCRIBER),t(this.dataChannelForKind(EL.RELIABLE,!0),kk.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&QM.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){lP()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){lP()&&(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 CR(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 wR=ZA(YA.Region),TR=5e3,ER=3e4,DR=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(`${OR(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=YP(e.headers),n=t?t*1e3:TR;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}throw e.status===401?zM.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status):zM.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof zM?e:r?.aborted?zM.cancelled(`Region fetching was aborted`):zM.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 zM&&i.reason===RM.NotAllowed){wR.debug(`token is not valid, cancelling auto region refresh`);return}wR.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&&(wR.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},ER))}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??TR)}isCloud(){return dP(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),wR.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)}};DR.cache=new Map,DR.settingsTimeouts=new Map,DR.connectionTrackers=new Map,DR.fetchLock=new tE;function OR(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}function kR(){return new CompressionStream(`deflate-raw`)}function AR(){return new DecompressionStream(`deflate-raw`)}function jR(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(()=>{}),MR(n.readable,t)})}function MR(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 YM(`Decompressed payload exceeds the maximum payload size of ${t} bytes`,JM.PayloadTooLarge)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a})}var NR=15e3,PR=5e9,FR=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 YM(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,JM.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new YM(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,JM.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)}},IR=class extends FR{[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=dj(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)}()})}},LR=class extends FR{[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 YM(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,JM.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=dj(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}()})}},RR=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:PR;this.log=XA,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 YM(`A text stream handler for topic "${e}" has already been set.`,JM.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new YM(`A byte stream handler for topic "${e}" has already been set.`,JM.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 YM(`Participant ${e} unexpectedly disconnected in the middle of sending data`,JM.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:FP(e.timestamp),attributes:e.attributes,encryptionType:n},o;switch(e.compression){case Sk.DEFLATE_RAW:if(!XP()){XA.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 Sk.NONE:o=!1;break;default:XA.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){r(new IR(a,zR(e.streamId,o?jR(s,this.maxPayloadByteLength):s),FP(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.byteStreamControllers.has(e.streamId))throw new YM(`A data stream read is already in progress for a stream with id ${e.streamId}.`,JM.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new IR(a,o?WR(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(BR(e.streamId)),FP(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 Sk.DEFLATE_RAW:if(!XP()){XA.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 Sk.NONE:o=!1;break;default:XA.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?jR(s,this.maxPayloadByteLength):s;r(new LR(a,zR(e.streamId,n),FP(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new YM(`A data stream read is already in progress for a stream with id ${e.streamId}.`,JM.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new LR(a,o?GR(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(BR(e.streamId)),FP(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 YM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,JM.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 YM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,JM.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 YM(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,JM.AbnormalEnd)):n.controller.close()):n.controller.error(new YM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,JM.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 YM(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,JM.AbnormalEnd)):r.controller.close()):r.controller.error(new YM(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,JM.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}};function zR(e,t){return new ReadableStream({start:n=>J(this,void 0,void 0,function*(){let r=yield t;n.enqueue(new Ek({streamId:e,chunkIndex:BigInt(0),content:r})),n.close()})})}function BR(e){let t=-1;return new TransformStream({transform:(n,r)=>{let i=FP(n.chunkIndex);if(i<=t){XA.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 YM(`Missing chunk(s) ${t+1}..${i-1} for data stream ${e} - cannot reassemble payload`,JM.Incomplete);t=i,n.content.length!==0&&r.enqueue(n)}})}function VR(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function HR(e){let t=0;return new TransformStream({transform:(n,r)=>{n.byteLength>0&&(r.enqueue(new Ek({streamId:e,chunkIndex:IP(t),content:n})),t+=1)}})}function UR(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 YM(`Cannot decode compressed data stream ${e} as text: ${t}`,JM.DecodeFailed)}};return new TransformStream({transform:(t,a)=>{let o=i(t);o.length>0&&(a.enqueue(new Ek({streamId:e,chunkIndex:IP(r),content:n.encode(o)})),r+=1)},flush:t=>{let a=i();a.length>0&&(t.enqueue(new Ek({streamId:e,chunkIndex:IP(r),content:n.encode(a)})),r+=1)}})}function WR(e,t,n){return e.pipeThrough(BR(t)).pipeThrough(VR()).pipeThrough(AR()).pipeThrough(KR(t,n)).pipeThrough(HR(t))}function GR(e,t,n){return e.pipeThrough(BR(t)).pipeThrough(VR()).pipeThrough(AR()).pipeThrough(KR(t,n)).pipeThrough(UR(t))}function KR(e,t){let n=0;return new TransformStream({transform:(r,i)=>{if(n+=r.byteLength,n>t)throw new YM(`Data stream ${e} exceeds the maximum payload size of ${t} bytes`,JM.PayloadTooLarge);i.enqueue(r)}})}var qR=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)})}},JR=class extends qR{},YR=class extends qR{};function XR(e,t,n){return new Tk({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:IP(e.timestamp),totalLength:IP(e.size),attributes:e.attributes,compression:n?.compression??Sk.NONE,inlineContent:n?.inlineContent,contentHeader:{case:`textHeader`,value:new Ck({version:t?.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:t?.replyToStreamId,operationType:t?.type===`update`?xk.UPDATE:xk.CREATE})}})}function ZR(e,t){return new Tk({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:IP(e.timestamp),totalLength:IP(e.size),attributes:e.attributes,compression:t?.compression??Sk.NONE,inlineContent:t?.inlineContent,contentHeader:{case:`byteHeader`,value:new wk({name:e.name})}})}function QR(e,t){return new XO({destinationIdentities:t,value:{case:`streamHeader`,value:e}})}var $R=new TextEncoder,ez=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=$R.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?IO.GCM:IO.NONE},c=o&&XP()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?tz.fromStream(qP(i).pipeThrough(kR())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let e=i,r=Sk.NONE;if(c){let t=yield c.collect();t.byteLength<i.byteLength&&(e=t,r=Sk.DEFLATE_RAW)}let a=QR(XR(s,void 0,{compression:r,inlineContent:e}),t?.destinationIdentities);if(a.toBinary().byteLength<=NR)return yield this.engine.sendDataPacket(a,EL.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=QR(XR(s,void 0,{compression:Sk.DEFLATE_RAW}),t?.destinationIdentities);yield this.sendChunkedByteStream(e,r,t?.destinationIdentities,c.stream().pipeThrough(nz(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?IO.GCM:IO.NONE},c=nz(e.length,t?.onProgress),l=o&&XP()&&this.allRecipientsSupportV2(a)&&this.allRecipientsSupportCompression(a)?tz.fromStream(qP(e).pipeThrough(c).pipeThrough(kR())):null;if(this.allRecipientsSupportV2(a)){let r=e,i=Sk.NONE;if(l){let t=yield l.collect();t.byteLength<e.byteLength&&(r=t,i=Sk.DEFLATE_RAW)}let o=QR(ZR(s,{compression:i,inlineContent:r}),a);if(o.toBinary().byteLength<=NR)return yield this.engine.sendDataPacket(o,EL.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let u=QR(ZR(s,{compression:l?Sk.DEFLATE_RAW:Sk.NONE}),a),d=l?l.stream():qP(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(gk.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 rz(c,e);let l=0;try{for(var u=!0,d=dj(JP(r,NR)),f;f=yield d.next(),i=f.done,!i;u=!0){s=f.value,u=!1;let e=new XO({destinationIdentities:n,value:{case:`streamChunk`,value:new Ek({content:s,streamId:t,chunkIndex:IP(l)})}});yield c.sendDataPacket(e,EL.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 iz(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?IO.GCM:IO.NONE,attachedStreamIds:e?.attachedStreamIds},i=QR(XR(r,e),n);yield rz(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 KP(e,NR)){let e=new Ek({content:r,streamId:t,chunkIndex:IP(a)}),i=new XO({destinationIdentities:n,value:{case:`streamChunk`,value:e}});yield o.sendDataPacket(i,EL.RELIABLE),a+=1}})},close(){return J(this,void 0,void 0,function*(){yield iz(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 JR(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)&&XP()&&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?IO.GCM:IO.NONE},s=QR(ZR(o,{compression:a?Sk.DEFLATE_RAW:Sk.NONE}),i),c=t.stream().pipeThrough(nz(t.size,n?.onProgress)),l=a?c.pipeThrough(kR()):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?IO.GCM:IO.NONE},i=QR(ZR(r),n);yield rz(this.engine,i);let a=0,o=new tE,s=this.engine,c=this.log;return new YR(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+NR),o=new XO({destinationIdentities:n,value:{case:`streamChunk`,value:new Ek({content:r,streamId:t,chunkIndex:IP(a)})}});yield s.sendDataPacket(o,EL.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return J(this,void 0,void 0,function*(){yield iz(t,n,s)})},abort(e){c.error(`Sink error:`,e)}}),r)})}},tz=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 MR(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 qP(this.state.bytes)}}};function nz(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 rz(e,t){return J(this,void 0,void 0,function*(){if(t.toBinary().byteLength>NR)throw new YM(`data stream header exceeds the ${NR}-byte limit; reduce attribute size`,JM.HeaderTooLarge);yield e.sendDataPacket(t,EL.RELIABLE)})}function iz(e,t,n){return J(this,void 0,void 0,function*(){let r=new XO({destinationIdentities:t,value:{case:`streamTrailer`,value:new Dk({streamId:e})}});yield n.sendDataPacket(r,EL.RELIABLE)})}function az(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 oz(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var sz=1,cz=2,lz=4,uz=8,dz=0,fz=12,pz=5,mz=7,hz=3,gz=3,_z=2,vz=1,yz=0,bz=3,xz=2,Sz=2,Cz=1,wz=0,Tz;(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`})(Tz||={});var Ez=class e extends LM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=Tz[t]}static tooShort(){return new e(`Too short to contain a valid header`,Tz.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,Tz.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,Tz.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,Tz.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,Tz.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,Tz.MalformedExt)}},Dz;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(Dz||={});var Oz=class e extends LM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=Dz[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,Dz.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,Dz.TooSmallForPayload)}},kz=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)}},Az;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(Az||={});var jz=class extends kz{},Mz=class e extends jz{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=sz,t.setUint8(n,e.lengthBytes),n+=sz,t.setBigUint64(n,this.timestamp),n+=uz;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}}};Mz.tag=Az.UserTimestamp,Mz.lengthBytes=8;var Nz=class e extends jz{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+=sz,t.setUint8(n,e.lengthBytes),n+=sz,t.setUint8(n,this.keyIndex),n+=sz;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=sz;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}}};Nz.tag=Az.E2ee,Nz.lengthBytes=13;var Pz=class e extends kz{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=qF(t),r,i,a=0;for(;n.byteLength-a>=2;){let e=n.getUint8(a);a+=sz;let t=n.getUint8(a);if(a+=sz,e!==wz)switch(e){case Az.UserTimestamp:if(n.byteLength-a<Mz.lengthBytes)throw Ez.malformedExt(e);r=new Mz(n.getBigUint64(a)),a+=t;break;case Az.E2ee:if(n.byteLength-a<Nz.lengthBytes)throw Ez.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=sz,t+=e*sz,s[e]=n.getUint8(t)}i=new Nz(o,s),a+=t;break;default:if(n.byteLength-a<t)throw Ez.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}}},Fz={from(e){return{payload:e.payload,extensions:new Pz({userTimestamp:e.userTimestamp?new Mz(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},Iz=Symbol.for(`lk.track`),Lz=Symbol.for(`lk.data-track`),Rz=class{constructor(e,t,n){this.trackSymbol=Iz,this.isLocal=!1,this.typeSymbol=Lz,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)}},zz=class e extends kz{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 Pz}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((xz+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-xz-e}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=fz;return t>0&&(r+=xz+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Oz.tooSmallForHeader();let t=0,n;switch(this.marker){case Bz.Inter:n=yz;break;case Bz.Final:n=vz;break;case Bz.Start:n=_z;break;case Bz.Single:n=bz}t|=n<<hz;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+=sz,e.setUint8(s,0),s+=sz,e.setUint16(s,this.trackHandle),s+=cz,e.setUint16(s,this.sequence.value),s+=cz,e.setUint16(s,this.frameNumber.value),s+=cz,e.setUint32(s,this.timestamp.asTicks()),s+=lz,i>0){let t=a-1;e.setUint16(s,t),s+=cz;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+=sz}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=qF(t);if(n.byteLength<fz)throw Ez.tooShort();let r=0,i=n.getUint8(r);r+=sz;let a=i>>pz&mz;if(a>dz)throw Ez.unsupportedVersion(a);let o;switch(i>>hz&gz){case _z:o=Bz.Start;break;case vz:o=Bz.Final;break;case bz:o=Bz.Single;break;case yz:default:o=Bz.Inter}let s=(i>>Sz&Cz)>0;r+=sz;let c;try{c=XF.fromNumber(n.getUint16(r))}catch(e){throw e instanceof YF&&(e.isReason(JF.Reserved)||e.isReason(JF.TooLarge))?Ez.invalidHandle(e):e}r+=cz;let l=WF.u16(n.getUint16(r));r+=cz;let u=WF.u16(n.getUint16(r));r+=cz;let d=GF.fromRtpTicks(n.getUint32(r));r+=lz;let f=new Pz;if(s){if(n.byteLength-r<cz)throw Ez.missingExtWords();let e=n.getUint16(r);r+=cz;let t=4*(e+1)-xz;if(r+t>n.byteLength)throw Ez.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),a=K(Pz.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()}}},Bz;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(Bz||={});var Vz=class e extends kz{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 Oz.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=sz;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=qF(t),r=K(zz.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}}},Hz=ZA(YA.DataTracks),Uz=class e extends LM{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=Wz[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,Wz.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,Wz.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,Wz.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,Wz.Incomplete,t)}},Wz;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(Wz||={});var Gz=class e{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Bz.Single:return this.frameFromSingle(e,t);case Bz.Start:return this.beginPartial(e,t);case Bz.Inter:case Bz.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!==Bz.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 Uz.interrupted(n,e.header.frameNumber.value);Hz.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!==Bz.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 Uz.interrupted(e,r);Hz.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!==Bz.Inter&&t.header.marker!==Bz.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),Uz.unknownFrame(n);if(r.payloads.size>=e.MAX_BUFFER_PACKETS)throw this.partials.delete(n),Uz.bufferFull(n);return r.payloads.has(t.header.sequence.value)&&Hz.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===Bz.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),Uz.incomplete(e,r,n-t.startSequence.value+1)}};Gz.MAX_BUFFER_PACKETS=128;var Kz;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(Kz||={});var qz=class e extends LM{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=Kz[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,Kz.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,Kz.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,Kz.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,Kz.Cancelled)}},Jz=ZA(YA.DataTracks),Yz=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 Gz;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 Jz.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 Jz.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return Jz.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},Xz=ZA(YA.DataTracks),Zz=1e4,Qz=16,$z=class extends hj.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){Xz.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]:Qz,r=null,i=new DP,a=this.descriptors.get(e),o=()=>{t?.removeEventListener(`abort`,c)},s=()=>{if(o(),!r){Xz.warn(`ReadableStream subscribed to ${e} was not started.`);return}if(!a||this.descriptors.get(a.info.sid)!==a){Xz.warn(`Unknown track ${e}, skipping cancel...`);return}if(a.subscription.type!==`active`){Xz.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(qz.cancelled()),(e=i.reject)==null||e.call(i,qz.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){Xz.error(`Unknown track ${e}`);let t=qz.disconnected();n.error(t),(r=i.reject)==null||r.call(i,t);return}if(a.subscription.type!==`active`){Xz.error(`Subscription for track ${e} is not active`);let t=qz.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=az([n,r].filter(e=>e!==void 0)),a=new DP;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,qz.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 DP,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?qz.timeout():qz.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=oz(Zz);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`){Xz.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){Xz.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)){Xz.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 Rz(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 Xz.warn(`Info mismatch for ${i}, treating as new publication`),!1;let l=t.sid;if(Xz.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){Xz.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){Xz.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:Xz.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`:{Xz.debug(`data track subscription activated`,{sid:t,handle:e});let a=new Yz({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(Vz.fromBinary(e),1)[0]}catch(e){Xz.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){Xz.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){Xz.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){Xz.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){Xz.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=Fz.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,qz.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,qz.disconnected())),n.subscription.type===`active`&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},eB=class e extends LM{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=tB[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,tB.MtuTooShort)}},tB;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(tB||={});var nB=class e{constructor(e,t){this.sequence=WF.u16(0),this.frameNumber=WF.u16(0),this.clock=KF.rtpStartingNow(GF.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Bz.Single:e===0?Bz.Start:e===t-1?Bz.Final:Bz.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:Bz.Inter,trackHandle:this.handle,sequence:WF.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new zz(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw eB.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 zz(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),u=Math.min(o,t.payload.byteLength-r);yield new Vz(l,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,u))}}},rB;(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`})(rB||={});var iB=class e extends LM{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=rB[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,rB.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,rB.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,rB.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,rB.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,rB.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,rB.Unknown)}static disconnected(){return new e(`Room disconnected`,rB.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,rB.Cancelled)}},aB;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(aB||={});var oB=class e extends LM{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=aB[t]}static trackUnpublished(){return new e(`Track is no longer published`,aB.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,aB.Dropped,{cause:t})}},sB;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(sB||={});var cB=class e extends LM{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=sB[t]}static packetizer(t){return new e(`Error packetizing frame`,sB.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,sB.Encryption,{cause:t})}},lB=class e{constructor(e,t){this.trackSymbol=Iz,this.isLocal=!0,this.typeSymbol=Lz,this.handle=null,this.log=XA,this.flushedFuture=new DP,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 DP)},this.options=e,this.manager=t,this.log=ZA(YA.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 oB.trackUnpublished();let t=Fz.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){XA.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}})}},uB=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new nB(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return lj(this,arguments,function*(){let t=yield cj(this.encryptIfNeeded(e));try{yield cj(yield*uj(dj(this.packetizer.packetize(t))))}catch(e){throw e instanceof eB?cB.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 cB.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new Nz(t.keyIndex,t.iv),e})}};uB.TRANSPORT_MTU_BYTES=16e3;var dB=ZA(YA.DataTracks),fB={pending(){return{type:`pending`,completionFuture:new DP}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new uB({info:e,e2eeManager:t}),unpublishingFuture:new DP}}},pB=1e4,mB=class e extends hj.EventEmitter{constructor(e){super(),this.handleAllocator=new ZF,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 oB.trackUnpublished();if(o.publishState===`republishing`)throw oB.dropped(`Data track republishing`);try{try{for(var s=!0,c=dj(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 oB.dropped(e)}})}handlePacketSendComplete(e){let t=(this.inFlightPacketCounter.get(e)??0)-1;t<0&&(dB.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 iB.limitReached();let r=oz(pB),i=t?az([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=fB.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){dB.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?iB.timeout():iB.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:lB.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){dB.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){dB.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){dB.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let i=t.data;dB.debug(`SFU accepted publish request for handle ${e}`,{sid:i.sid});let a=i.usesE2ee?this.e2eeManager:null;this.descriptors.set(i.pubHandle,fB.active(i,a)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else dB.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`){dB.warn(`Track ${e} already active`);return}if(t.type===`error`){dB.warn(`Republish failed for track ${e}`);return}dB.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){dB.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){dB.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,iB.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,iB.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`)})}},hB=class e extends Error{constructor(t,n,r,i){super(n),this.code=t,this.message=CB(n,e.MAX_MESSAGE_BYTES),this.data=r?CB(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 uk({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)}};hB.MAX_MESSAGE_BYTES=256,hB.MAX_DATA_BYTES=15360,hB.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},hB.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 gB=15360,_B=`lk.rpc_request`,vB=`lk.rpc_response`,yB;(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`})(yB||={});var bB=1,xB=2;function SB(e){return new TextEncoder().encode(e).length}function CB(e,t){if(SB(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 wB=class extends hj.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(SB(i)>gB&&e<1)throw hB.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`);let a=t.getServerVersion();if(a&&gP(a,`1.8.0`)<0)throw hB.builtIn(`UNSUPPORTED_SERVER`);let s=Math.max(o,8e3),c=crypto.randomUUID(),l=new DP,u=null,d=setTimeout(()=>{var e;t.pendingAcks.delete(c),(e=l.reject)==null||e.call(l,hB.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,hB.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:_B,destinationIdentities:[e],attributes:{[yB.RPC_REQUEST_ID]:t,[yB.RPC_REQUEST_METHOD]:n,[yB.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:`${i}`,[yB.RPC_REQUEST_VERSION]:`${xB}`}});return}this.emit(`sendDataPacket`,{packet:new XO({destinationIdentities:[e],kind:ZO.RELIABLE,value:{case:`rpcRequest`,value:new sk({id:t,method:n,payload:r,responseTimeoutMs:i,version:bB})}})})})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[yB.RPC_REQUEST_ID];if(!r){this.log.warn(`RPC data stream malformed: ${yB.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,hB.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,hB.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(a))}}},TB=class extends hj.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,hB.builtIn(`UNSUPPORTED_VERSION`));return}let n=this.rpcHandlers.get(t.method);if(!n){this.publishRpcResponsePacket(e,t.id,null,hB.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 hB?r=n:(this.log.warn(`Uncaught error returned by RPC handler for ${t.method}. Returning APPLICATION_ERROR instead.`,n),r=hB.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[yB.RPC_REQUEST_ID],i=n[yB.RPC_REQUEST_METHOD],a=parseInt(n[yB.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[yB.RPC_REQUEST_VERSION],10);if(!r||!i||Number.isNaN(a)||Number.isNaN(o)){this.log.warn(`RPC data stream malformed: ${yB.RPC_REQUEST_ID} / ${yB.RPC_REQUEST_METHOD} / ${yB.RPC_REQUEST_RESPONSE_TIMEOUT_MS} / ${yB.RPC_REQUEST_VERSION} not set.`),this.publishRpcResponsePacket(t,r,null,hB.builtIn(`APPLICATION_ERROR`,`RPC data stream malformed`));return}if(this.publishRpcAck(t,r),o!==xB){this.publishRpcResponsePacket(t,r,null,hB.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,hB.builtIn(`APPLICATION_ERROR`,`Error reading RPC request payload`,{cause:e}));return}let c=this.rpcHandlers.get(i);if(!c){this.publishRpcResponsePacket(t,r,null,hB.builtIn(`UNSUPPORTED_METHOD`));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:s,responseTimeout:a})}catch(e){let n;e instanceof hB?n=e:(this.log.warn(`Uncaught error returned by RPC handler for ${i}. Returning APPLICATION_ERROR instead.`,e),n=hB.builtIn(`APPLICATION_ERROR`)),this.publishRpcResponsePacket(t,r,null,n);return}yield this.publishRpcResponse(t,r,l??``)})}publishRpcAck(e,t){this.emit(`sendDataPacket`,{packet:new XO({destinationIdentities:[e],kind:ZO.RELIABLE,value:{case:`rpcAck`,value:new ck({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit(`sendDataPacket`,{packet:new XO({destinationIdentities:[e],kind:ZO.RELIABLE,value:{case:`rpcResponse`,value:new lk({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:vB,destinationIdentities:[e],attributes:{[yB.RPC_REQUEST_ID]:t}});return}if(SB(n)>gB){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,hB.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`));return}this.publishRpcResponsePacket(e,t,n,null)})}},EB=class extends DF{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=EF(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;uP()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(uP())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(QN(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&QN(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})}},DB=class extends hj.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=IO.NONE,this.log=XA,this.handleMuted=()=>{this.emit(Q.Muted)},this.handleUnmuted=()=>{this.emit(Q.Unmuted)},this.log=ZA(r?.loggerName??YA.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)),EN(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==IO.NONE}get audioTrack(){if(RP(this.track))return this.track}get videoTrack(){if(zP(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||={})})(DB||={});var OB=class extends DB{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&&zP(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(RP(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(DO.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(DO.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(DO.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(DO.TF_STEREO),this.options?.dtx||t.add(DO.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(DO.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}return[]}};function kB(e,t){return J(this,void 0,void 0,function*(){e??={};let n=!1,r=kN(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=vN(gN(o,gL,_L)),u=navigator.mediaDevices.getUserMedia(l);o.audio&&(VF.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>VF.userMediaPromiseMap.delete(`audioinput`))),o.video&&(VF.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>VF.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&&kP(o.deviceId)!==c?o.deviceId=c:o||={deviceId:c};let u=GL(n,o,t);return u.kind===$.Kind.Video?u.source=$.Source.Camera:u.kind===$.Kind.Audio&&(u.source=$.Source.Microphone),u.mediaStream=e,RP(u)&&i?yield u.setProcessor(i):zP(u)&&a&&(yield u.setProcessor(a)),u})))}catch(r){if(!n)throw r;return kB(Object.assign(Object.assign({},e),{audio:s,video:c}),t)}})}var AB;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(AB||={});function jB(e){switch(e){case SO.EXCELLENT:return AB.Excellent;case SO.GOOD:return AB.Good;case SO.POOR:return AB.Poor;case SO.LOST:return AB.Lost;default:return AB.Unknown}}var MB=class extends hj.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===PO.AGENT}get isActive(){return this.participantInfo?.state===NO.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]:PO.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=AB.Unknown,this.log=XA,this.loggerOptions=a,this.log=ZA(a?.loggerName??YA.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 DP,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===NO.ACTIVE&&this.participantInfo?.state!==NO.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=ON(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=jB(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=>RP(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 NB(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new xA({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var PB=class extends MB{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=IO.NONE,this.e2eeStateMutex=new tE,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||=new DP},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 DP,(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!==FA.OK&&i.reject(new qM(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case FA.NOT_ALLOWED:t=iB.notAllowed(e.message);break;case FA.DUPLICATE_NAME:t=iB.duplicateName(e.message);break;case FA.INVALID_NAME:t=iB.invalidName(e.message);break;case FA.LIMIT_EXCEEDED:t=iB.limitReached(e.message);break;default:t=iB.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=>NB(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`,EN(e));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,EN(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,EN(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`,EN(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=dj(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;uN(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,EN(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`,EN(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(VP(e)||BP(e))try{if(lP())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}`,EN(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`,EN(e)),VP(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,EN(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!==IO.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 OM((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 VN(50)}a(new qM(`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?IO.GCM:IO.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 VM(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(X.MediaDevicesError,n,SN(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===$.Source.Microphone&&RP(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`,EN(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=gN(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield kB(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(RP(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=$.Source.Microphone,this.emit(X.AudioStreamAcquired)),zP(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 BM(`getDisplayMedia not supported`);e.resolution===void 0&&!aP()&&(e.resolution=hN.h1080fps30.resolution);let t=CN(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new VM(`no video track found`);let i=new uR(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 WL(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*(){VP(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),LP(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 WL(e,a,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new uR(e,a,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new VM(`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`,EN(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.`,EN(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),!cP()&&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!==DI.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,{track:EN(e)});let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new KM(`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 WM)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 DP,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,EN(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(e=>AN(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,EN(e)),!1)}publish(e,t,n){return J(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new KM(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>LP(e)&&t.source===e.source)&&e.source!==$.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,EN(e)),t.stopMicTrackOnMute&&RP(e)&&(e.stopOnMute=!0),e.source===$.Source.ScreenShare&&eP()&&(t.simulcast=!1),t.videoCodec===`av1`&&!WN()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!GN()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=mL),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===wN(e.mime))||(t.videoCodec=wN(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(DO.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(DO.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(DO.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(DO.TF_STEREO),a&&i.push(DO.TF_NO_DTX),VP(e)&&e.hasPreConnectBuffer&&i.push(DO.TF_PRECONNECT_BUFFER);let s=this.normalizeRequestedFrameMetadataOptions(e,t),c=new Fk({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??pN.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign({},EN(e)),{dims:n}))}if(c.width=n.width,c.height=n.height,BP(e)){JN(r,t)&&(YN()||!ZN(this.engine?.serverVersion))&&(t.simulcast=!1,this.log.info(`SVC simulcast is not supported, disabling simulcast.`,EN(e)));let n=JN(r,t);KN(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`,EN(e)))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`);let i=new Pk({codec:r,cid:e.mediaStreamTrack.id});n&&(i.videoLayerMode=YO.ONE_SPATIAL_LAYER_PER_STREAM),c.simulcastCodecs=[i],t.backupCodec===!0&&(t.backupCodec={codec:mL}),t.backupCodec&&r!==t.backupCodec.codec&&c.encryption===IO.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),c.simulcastCodecs.push(new Pk({codec:t.backupCodec.codec,cid:``})))}l=$L(e.source===$.Source.ScreenShare,c.width,c.height,t),c.layers=pR(c.width,c.height,l,KN(t.videoCodec)&&!JN(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 UM(`cannot publish track when not connected`);let u=()=>J(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new UM(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,l),BP(e)&&(e.publishOptions=t),this.emit(X.LocalSenderCreated,e.sender,e),BP(e)&&(t.degradationPreference??=cR(e),e.setDegradationPreference(t.degradationPreference)),l){if(eP()&&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&&OP(e.codec)){let n=eR(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({},EN(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=wN(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign({},EN(e)),{codec:i})),t.videoCodec=i,l=$L(e.source===$.Source.ScreenShare,c.width,c.height,t))}yield u()}let p=new OB(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,BP(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}),BP(e)?e.startMonitor(this.engine.client):VP(e)&&e.startMonitor(),this.addTrackPublication(p),this.emit(X.LocalTrackPublished,p),VP(e)&&d.audioFeatures.includes(DO.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`,EN(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`,EN(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`,EN(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=dj(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`,EN(e))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign({},EN(e)),{error:t}))})}return p})}canPublishFrameMetadata(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||bF(this.roomOptions.frameMetadata??this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){let n=t.frameMetadata??t.packetTrailer;if(e.kind!==$.Kind.Video||!xF(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),EN(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let r=SF(n),i=CF(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!==IO.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new VM(`track is not published`);if(!BP(e))throw new VM(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=tR(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,EN(e));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=this.normalizeRequestedFrameMetadataOptions(e,i),c=new Fk({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=pR(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new UM(`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(LP(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.debug(`awaiting publish promise before attempting to unpublish`,EN(e)),yield t)}let n=this.getPublicationForTrack(e),r=n?EN(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<bL.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(BP(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 OM((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&&(VP(t)||BP(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?EL.RELIABLE:EL.LOSSY,i=n.reliable?ZO.RELIABLE:ZO.LOSSY,a=n.destinationIdentities,o=n.topic,s=new XO({kind:i,value:{case:`user`,value:new nk({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 XO({kind:ZO.RELIABLE,value:{case:`sipDtmf`,value:new rk({code:e,digit:t})}});yield this.engine.sendDataPacket(n,EL.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 XO({value:{case:`chatMessage`,value:new ok(Object.assign(Object.assign({},n),{timestamp:ME.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,EL.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 XO({value:{case:`chatMessage`,value:new ok(Object.assign(Object.assign({},n),{timestamp:ME.parse(n.timestamp),editTimestamp:ME.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,EL.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({},EN(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 DP,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(VP(r)||BP(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 VN(20)}})}publishDataTrack(e){return J(this,void 0,void 0,function*(){let t=new lB(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},FB=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},IB=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 FB(`The operation was aborted.`,t.reason);let r=new DP(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 FB(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},LB=class extends DB{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 Xk({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new dk({participantSid:``,trackSids:[this.trackSid]})]});this.emit(Q.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?DB.SubscriptionStatus.Unsubscribed:super.isSubscribed?DB.SubscriptionStatus.Subscribed:DB.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?DB.PermissionStatus.Allowed:DB.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)&&(WP(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&WP(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??FN.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 WP(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new rA({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)jN(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=MN(this.trackInfo,this.requestedMaxQuality);e&&jN(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:FN.HIGH})),e.quality=FN.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)}},RB=class e extends MB{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 Rz(QF.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]:PO.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 IB(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),EN(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),EN(o))),this.emit(X.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new kF(e,t,r,i):new EB(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)&&HP(c)&&RP(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 LB(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:EN(i),newTrack:EN(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),EN(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=>{RP(n.track)&&HP(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)}},zB;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(zB||={});var BB=4e3,VB=3e4,HB=class e extends hj.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=zB.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new tE,this.isVideoPlaybackBlocked=!1,this.log=XA,this.statsLog=XA,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(e,t,n)=>J(this,void 0,void 0,function*(){if(!$N())throw uP()?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===zB.Connected)return this.log.info(`already connected to room ${this.name}`),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(zB.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==nF(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),dP(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new DR(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 zF.getInstance().getBackOffPromise(e),c.signal.aborted)throw zM.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof zM&&t.reason!==RM.Cancelled&&t.reason!==RM.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof zM&&(e.status===401||e.reason===RM.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[RM.InternalError,RM.ServerUnreachable,RM.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),zF.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,PP(t)),o(t))}else{let e=wO.UNKNOWN_REASON;t instanceof zM&&(e=PP(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new DP((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 HM(`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===zB.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({},yL),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?zM.cancelled(`Signal connection aborted`):zM.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof zM&&(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(),zM.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}lP()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),lP()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(zB.Connected),this.emit(Y.Connected),zF.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===zB.Disconnected){e.log.debug(`already disconnected`);return}if(e.log.info(`disconnect from room`),e.state===zB.Connecting||e.state===zB.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,zM.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,wO.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=jM();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=EP();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(zB.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(zB.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===NO.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e,t.disconnectReason===wO.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=>QF.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,hB.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=MP(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=NP(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*(){jM()?.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&&iN(n),a=r&&iN(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),VP(e.track)&&(yield e.track.checkForSilence())&&this.emit(Y.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=SN(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=SN(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({},vL),t),this.log=ZA(this.options.loggerName??YA.Room,()=>this.logContext),this.statsLog=ZA(YA.Stats,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},gL),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},_L),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},hL),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new RR(this.options.dataStream?.maxPayloadByteLength),this.outgoingDataStreamManager=new ez(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new $z({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 mB({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 wB(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,EL.RELIABLE)}),this.rpcServerManager=new TB(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,EL.RELIABLE)}),this.disconnectLock=new tE,this.localParticipant=new PB(``,``,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`,kP(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,kP(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,kP(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),lP()){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 NF(r,n),this.e2eeManager.on(dF.ParticipantEncryptionStatusChanged,(e,t)=>{GP(t)&&(this.isE2EEEnabled=e),this.emit(Y.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(dF.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 IF(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===zB.Disconnected?OM.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?OM.resolve(this.roomInfo.sid):new OM((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 UM(`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 SR(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(zB.SignalReconnecting)&&this.emit(Y.SignalReconnecting)}).on(Z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug(`Resumed signal connection`),this.updateSubscriptions(),this.setAndEmitConnectionState(zB.Connected)&&this.emit(Y.Reconnected),this.emitBufferedEvents()}).on(Z.SignalResumed,()=>{(this.state===zB.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(zB.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!==IO.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=>QF.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:TR})}),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 VF.getInstance().getDevices(e,t)}prepareConnection(e,t){return J(this,void 0,void 0,function*(){if(this.state===zB.Disconnected){this.log.debug(`prepareConnection to ${e}`);try{if(dP(new URL(e))&&t){this.regionUrlProvider=new DR(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===zB.Disconnected&&(this.regionUrl=n,yield fetch(jP(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`))}else yield fetch(jP(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 OA({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new OA({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new OA({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new OA({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 OA({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 OA({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 OA({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 oA({reason:wO.CLIENT_INITIATED,action:sA.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new OA({scenario:{case:`subscriberBandwidth`,value:IP(t)}});break;case`leave-full-reconnect`:r=new OA({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,!QN()&&!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 VF.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([zB.Connecting,zB.Reconnecting].includes(this.state)){let r=QP(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===zB.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=BN(t.id),i=r[0],a=r[1],o=QP(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!==zB.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),lP()&&(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(zB.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=VF.getInstance().previousDevices,t=yield VF.getInstance().getDevices(void 0,!1),n=jM();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=xN(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`&&!iP()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!iP())&&(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=bN()??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(),VN(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?RB.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new RB(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===PO.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&&UP(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){let t=[];return(bF(e.frameMetadata??e.packetTrailer)||this.e2eeManager)&&t.push(gk.CAP_PACKET_TRAILER),XP()&&t.push(gk.CAP_COMPRESSION_DEFLATE_RAW),t}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(_B,(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(vB,(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||=QM.setInterval(()=>{this.logWebRTCStats()},VB):this.statsLogInterval&&=(QM.clearInterval(this.statsLogInterval),void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=QM.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,wO.STATE_MISMATCH)))):e=0},BB)}clearConnectionReconcile(){this.connectionReconcileInterval&&QM.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===zB.Connected),this.setStatsLogging(e===zB.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===zB.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===zB.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 kO({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:ME.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new MO({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected),this.emit(Y.Connected),this.setAndEmitConnectionState(zB.Connected),t.video){let e=new OB($.Kind.Video,new RO({source:bO.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:yO.AUDIO,name:`video-dummy`}),new uR(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:wP(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 OB($.Kind.Audio,new RO({source:bO.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:yO.AUDIO}),new WL(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:EP(),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 MO({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:NO.ACTIVE,tracks:[],joinedAt:ME.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=wP(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new RO({source:bO.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:yO.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=EP(),n=new RO({source:bO.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:yO.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=UB(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)}};HB.cleanupRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});function UB(e){return e.map(e=>{if(e)return Array.isArray(e)?UB(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var WB;(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`})(WB||={}),hj.EventEmitter,hj.EventEmitter,new TextEncoder,new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});var GB=class extends Error{constructor(e,t){var n;super(e,t),BE(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};BE(GB,`code`,`ERR_JOSE_GENERIC`),BE(class extends GB{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}}),BE(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),BE(this,`claim`,void 0),BE(this,`reason`,void 0),BE(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),BE(class extends GB{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}}),BE(this,`code`,`ERR_JWT_EXPIRED`),BE(this,`claim`,void 0),BE(this,`reason`,void 0),BE(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),BE(class extends GB{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),BE(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),BE(class extends GB{constructor(){super(...arguments),BE(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),BE(class extends GB{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),BE(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),BE(class extends GB{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),BE(this,Symbol.asyncIterator,QE(function*(){})),BE(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),BE(class extends GB{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),BE(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),BE(class extends GB{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),BE(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);var KB=new Set;function qB(e){KB.add(e)}function JB(e){return KB.has(e)}var YB=z({server_url:P(),participant_token:P(),call:P()});function XB(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=>HT(t,e)),v.current=e.speaker,e.speaker===`agent`&&x();return}p(t=>HT(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:LT})}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=WT(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,RT)}},[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=YB.parse(await sa(t,`/v1/tokens`,{agent:e,scope:n})),a=new HB;g.current=a,a.registerTextStreamHandler(FT,(e,t)=>{ZB(a,e,t.identity,S)}),n===`talk`&&a.on(Y.TrackSubscribed,QB),a.on(Y.TrackUnsubscribed,e=>e.detach().forEach(e=>e.remove())),a.on(Y.Disconnected,()=>r(`ended`)),qB(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 ZB(e,t,n,r){let i=t.info.attributes?.[`lk.segment_id`]??t.info.id,a=e.remoteParticipants.get(n)?.kind===PO.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?.[IT]===`true`})}function QB(e){if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.style.display=`none`,document.body.append(t)}function $B(){let e=Sr().agent??``,t=XB(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)(eV,{live:t}),(0,A.jsxs)(`div`,{className:`talk-standing`,children:[(0,A.jsx)(`div`,{className:`talk-phase`,children:nV(t)}),(0,A.jsx)(`div`,{className:`talk-hint`,children:rV(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)(qT,{lines:i?t.lines:[],mode:`talk`,children:(0,A.jsx)(XT,{open:t.phase===`live`,mode:`talk`,onWrite:t.write})}),t.call!==null&&(0,A.jsx)(tV,{call:t.call,heard:t.heard})]}),(0,A.jsx)(YC,{agent:e,call:t.call})]})}function eV({live:e}){let t=iV(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 tV({call:e,heard:t}){return GC(e,{onEntry:t}),null}function nV(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 rV(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 iV(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 aV(){let e=Sr().agent??``,t=XB(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)(oV,{agent:e,live:t,world:n}),r||t.lines.length>0?(0,A.jsx)(qT,{lines:t.lines,mode:`chat`}):(0,A.jsx)(sV,{agent:e,live:t}),t.error!==null&&(0,A.jsx)(`p`,{className:`rchat-refused`,children:t.error}),(0,A.jsx)(XT,{open:t.phase===`live`,mode:`chat`,onWrite:t.write}),t.call!==null&&(0,A.jsx)(lV,{call:t.call,heard:t.heard})]})}),(0,A.jsx)(YC,{agent:e,call:t.call})]})}function oV({agent:e,live:t,world:n}){let r=uV(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:cV(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 sV({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 cV(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 lV({call:e,heard:t}){return GC(e,{onEntry:t}),null}function uV(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 dV(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 fV=20;function pV(e){let t=j(),n=(0,D.useRef)(new Map),[r,i]=(0,D.useState)(n.current),a=e.filter(e=>!GS(e)).slice(0,fV),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=>mV(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)??hV(e))}async function mV(e,t){try{return{line:t,read:!0,score:await dV(e,t.call,t.last_seq),refused:null}}catch(e){return{line:t,read:!0,score:null,refused:String(e)}}}function hV(e){return{line:e,read:!1,score:null,refused:null}}function gV(e){let{lines:t,error:n}=WS(e);return{rows:pV(t),error:n}}function _V({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 Xw(t,e)):c(await Qw(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 vV=`minmax(0,1.2fr) 120px 104px minmax(0,1.7fr) 70px 84px`;function yV({agent:e,rows:t}){let[n,r]=(0,D.useState)(null);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:vV,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:vV},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)(bV,{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)(xV,{agent:e,row:t})]},t.line.call))]})}function bV({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 xV({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)(_V,{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)(SV,{score:n}),n?.judges.filter(e=>e.verdict!==`held`).map(n=>(0,A.jsx)(CV,{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 SV({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 CV({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 wV=86400,TV=7,EV=30,DV=`minmax(0,1fr) 150px 150px 90px`;function OV({agent:e}){let t=j(),[n,r]=(0,D.useState)(TV),[i,a]=(0,D.useState)(EV),[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),qw(t,e,n*wV,i*wV).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:DV,labels:[`Judge`,`Before>`,`Now>`,`Points>`]}),o.drift.judges.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:DV},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.judge}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:kV(e,`before`)}),(0,A.jsx)(`span`,{className:`ev-num`,children:kV(e,`now`)}),(0,A.jsx)(`span`,{className:AV(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 kV(e,t){let n=e[t];return n===null?`—`:`${n.percent.toFixed(0)}% · ${n.held}/${n.settled}`}function AV(e,t){return e.delta!==null&&e.delta<-Math.abs(t)}var jV=` · `;function MV(e,t,n){return[t,e,n].join(jV)}function NV(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 PV(e,t){if(t?.matrix==null||e.matrix===null)return null;let n=FV(t.matrix),r=FV(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 FV(e){let t=new Map;for(let n of e.runs)for(let e of n.scores)t.set(MV(n.model,n.golden,e.metric),e.passed);return t}function IV({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),tT(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 nT(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 LV=`minmax(0,1.1fr) 120px 84px 70px 80px minmax(0,1.6fr)`,RV={done:`green`,running:`amber`,failed:`red`};function zV({runs:e,selected:t,onSelect:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:LV,labels:[`Run`,`Started`,`Status`,`Held>`,`Judge calls>`,`Since the run before`]}),e.map((r,i)=>{let a=NV(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:LV},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:RV[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)(BV,{delta:PV(r,e[i+1])})]},r.id)})]})}function BV({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 VV=`minmax(0,1.1fr) minmax(0,.8fr) 110px 120px 84px minmax(0,1.6fr)`,HV={done:`green`,running:`amber`,failed:`red`};function UV({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:HV[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)(BV,{delta:PV(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:VV,labels:[`Golden`,`Model`,`Metric`,`Score`,`Held`,`The judge's own sentence`]}),e.matrix.runs.flatMap(t=>t.scores.map(n=>(0,A.jsx)(WV,{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)(IV,{run:e.id})]})}function WV({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:VV},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 GV=z({name:P(),input:R(P()),expect:fp(P(),Zf())}),KV=z({agent:P().nullable(),goldens:R(GV)}),qV=z({run:P()});async function JV(e,t){return KV.parse(await Cw(e,t,`goldens.roster`))}async function YV(e,t){return qV.parse(await Cw(e,t.agent,`goldens.run`,t)).run}var XV=15,ZV=0;function QV({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)(XV),[m,h]=(0,D.useState)(ZV),[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 YV(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:$V(e)})]},e.name))]}),(0,A.jsx)(Nm,{children:v})]})}function $V(e){let t=Object.entries(e.expect).map(([e,t])=>`${e}: ${eH(t)}`);return t.length===0?`consent only`:t.join(` · `)}function eH(e){return Array.isArray(e)?e.map(String).join(`, `):String(e)}var tH=3e3;function nH(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 Hw(t,e);n||(r(i),s(null))}catch(e){n||s(String(e))}finally{n||a(!1)}};i();let o=window.setInterval(()=>void i(),tH);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{runs:n,reading:i,error:o}}var rH=`minmax(0,1fr) 110px 90px`;function iH(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 aH(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 oH(){let e=Sr().agent??``,t=j(),[n,r]=Xi(),i=nH(e),a=gV(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 JV(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=aH(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 YV(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:rH},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?`—`:iH(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)(QV,{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)(zV,{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)(UV,{run:v,before:i.runs[i.runs.indexOf(v)+1]})]}),g===`drift`&&(0,A.jsx)(OV,{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)(yV,{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 sH=z({state_fields:fp(P(),mp([`public`,`tenant`,`pii`])).default({})});function cH(e){let t=j(),[n,r]=(0,D.useState)({});return(0,D.useEffect)(()=>{let n=!1;if(e!==``)return(async()=>{try{let i=sH.parse(await k(t,`/v1/agents/${e}/config`));n||r(i.state_fields)}catch{n||r({})}})(),()=>{n=!0}},[e,t]),n}function lH(e){let t=e?.recording;return typeof t==`string`&&t!==``?t:null}function uH({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)(dH,{call:e,onNothing:i})})]})}function dH({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 fH(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 fH(e){try{let t=(await e.json()).detail;if(typeof t==`string`)return t}catch{}return`the recording answered ${e.status}`}var pH=z({server_url:P(),participant_token:P(),identity:P()});async function mH(e,t,n){return pH.parse(await sa(e,`/v1/calls/${t}/${n}`,{}))}function hH(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 mH(t,e,`listen`),i=new HB;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 gH=`cold`,_H=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 mH(this.#e,this.#t,`supervise`),t=new HB;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 vH(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 _H(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:gH}),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 yH={whisper:`Whisper to the agent — the caller never hears it`,say:`Say it to the caller, in the agent's voice, verbatim`};function bH({call:e,live:t}){let n=hH(e),r=vH(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)(xH,{ear:n,live:t}),t?(0,A.jsx)(SH,{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 xH({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 SH({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:yH[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 CH=new Set([`tag`,`name`,`id`,`flag`]);function wH({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:[TH(String(e.value)),e.unit!==null&&!CH.has(e.unit)&&(0,A.jsxs)(`span`,{className:`lv-seen`,children:[` `,e.unit]})]})]},e.field))})}function TH(e){return/^-?\d+\.\d{4,}$/.test(e)?Number(e).toFixed(3):e}function EH({metrics:e,entries:t}){let n=BC(t),r=Math.max(...n.map(e=>e.seconds),0),i=PC();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:FC(e.seconds)})]},e.name)),Object.entries(e).map(([e,t])=>(0,A.jsx)(DH,{kind:e,blocks:t,shape:i.get(e)},e))]})]})}function DH({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)(wH,{rows:NC(t,n)},`${e}-${String(r)}`))]})}function OH({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 kH({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 AH=`***`,jH=`tenant`;function MH({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=NH(e[n],t[n]);return(0,A.jsxs)(Lm,{label:n,children:[PH(e[n]),r!==jH&&(0,A.jsx)(`span`,{className:r===`pii`?`lv-seen lv-seen-pii`:`lv-seen`,children:r})]},n)})})]})}function NH(e,t){return e===AH?`pii`:t===`public`?`public`:jH}function PH(e){return typeof e==`string`?e:JSON.stringify(e)}function FH({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 IH(e){return e.ops.map(BH).join(`; `)}function LH(e){return e.ops.flatMap(e=>e.facts.map(e=>e.category?`${e.text} (${e.category})`:e.text))}function RH(e){return`${e.sources.length} sources · ${VH(e.took_ms)}`}function zH(e){return e.sources.map(e=>`${e.heading?`${e.path} › ${e.heading}`:e.path} · ${e.score.toFixed(3)}`)}function BH(e){return`${e.op} · ${e.facts.length} facts · ${VH(e.took_ms)}`}function VH(e){return`${Math.round(e)} ms`}function HH({ops:e,seq:t}){return(0,A.jsx)(WH,{kind:`memory`,said:IH(e),lines:LH(e),seq:t})}function UH({sources:e,seq:t}){return(0,A.jsx)(WH,{kind:`sources`,said:RH(e),lines:zH(e),seq:t})}function WH({kind:e,said:t,lines:n,seq:r}){return(0,A.jsx)(FH,{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 GH({changed:e,cause:t,seq:n}){return(0,A.jsx)(FH,{seq:n,kind:`state`,tone:`state`,said:`${e.join(`, `)} ← ${XH(t)}`})}function KH({mark:e,seq:t}){return(0,A.jsx)(FH,{seq:t,kind:`supervisor`,tone:`supervisor`,said:e.said,note:[e.by]})}function qH({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)(FH,{seq:t,kind:`confirm`,tone:`confirm`,said:e.phrase,note:[e.status],children:(0,A.jsx)(wH,{rows:n})})}function JH({name:e,source:t,data:n,seq:r}){return(0,A.jsx)(FH,{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 YH({entries:e}){return(0,A.jsx)(FH,{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 XH(e){return e===null?`the app`:e.kind===`tool`?e.tool:`${e.name} (seq ${String(e.seq)})`}function ZH({run:e,seq:t}){let n=[{field:`arguments`,value:JSON.stringify(e.arguments,null,2),unit:null},...QH(e.output)?[{field:`output`,value:JSON.stringify(e.output,null,2),unit:null}]:[],...QH(e.error)?[{field:`error`,value:e.error,unit:null}]:[],...QH(e.duration_s)?[{field:`duration_s`,value:FC(e.duration_s),unit:null}]:[]];return(0,A.jsx)(FH,{seq:t,kind:`tool`,tone:`tool`,said:`${e.name}(${$H(e)})`,note:[(0,A.jsx)(`span`,{className:e.status===`failed`?`lv-failed`:``,children:eU(e)})],children:(0,A.jsx)(wH,{rows:n})})}function QH(e){return e!=null}function $H(e){return Object.entries(e.arguments).map(([e,t])=>`${e}=${tU(t)}`).join(`, `)}function eU(e){return e.status===`running`?`…`:e.error??e.summary??tU(e.output)}function tU(e){let t=typeof e==`string`?e:JSON.stringify(e);return t===void 0?``:t.slice(0,60)}var nU={transcription_delay:`stt`,end_of_turn_delay:`eot`,llm_node_ttft:`ttft`,tts_node_ttfb:`ttfb`,e2e_latency:`e2e`};function rU({turn:e,seq:t,metrics:n}){let r=RC(n,e.speech_id),i=MC(e).map(e=>`${nU[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)(FH,{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)(wH,{rows:e.readings})]},`${e.kind}-${String(t)}`))})}var iU=80;function aU({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<iU},children:[cw(e,t).map(e=>(0,A.jsx)(oU,{row:e,state:t},`${e.kind}-${String(e.seq)}`)),(0,A.jsx)(sU,{said:t.live.user,who:`caller`}),(0,A.jsx)(sU,{said:r,who:`agent`}),n]})}function oU({row:e,state:t}){switch(e.kind){case`turn`:return(0,A.jsx)(rU,{turn:e.turn,seq:e.seq,metrics:t.metrics});case`tool`:return(0,A.jsx)(ZH,{run:e.run,seq:e.seq});case`state`:return(0,A.jsx)(GH,{changed:e.changed,cause:e.cause,seq:e.seq});case`confirm`:return(0,A.jsx)(qH,{confirm:e.confirm,seq:e.seq});case`event`:return(0,A.jsx)(JH,{name:e.name,source:e.source,data:e.data,seq:e.seq});case`supervisor`:return(0,A.jsx)(KH,{mark:e.mark,seq:e.seq});case`memory`:return(0,A.jsx)(HH,{ops:e.ops,seq:e.seq});case`sources`:return(0,A.jsx)(UH,{sources:e.sources,seq:e.seq});case`quiet`:return(0,A.jsx)(YH,{entries:e.entries})}}function sU({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)(FH,{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 cU({call:e,agent:t}){let n=JC(e),r=n.state,i=cH(r.agent),a=Eh(),[o,s]=(0,D.useState)(!1),c=r.status===`ended`,l=lH(fU(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)(lU,{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)(bH,{call:e,live:!c}),(0,A.jsx)(aU,{entries:n.entries,state:r,after:l===null?void 0:(0,A.jsx)(pU,{call:e})})]}),(0,A.jsxs)(`aside`,{className:`lv-pane`,"aria-label":`what the call holds`,children:[(0,A.jsx)(MH,{fields:r.app_state,declared:i}),(0,A.jsx)(kH,{room:r.room,from:r.from,over:c}),(0,A.jsx)(OH,{prompt:r.prompt,cost:r.cost}),(0,A.jsx)(EH,{metrics:r.metrics,entries:n.entries})]})]})}function lU({call:e,agent:t,state:n,connection:r,failed:i,children:a}){let o=dU(n.status!==`ended`),s=n.status===`ended`,c=n.caller?.name??uU(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 uU(e){return e===null?`—`:e.startsWith(`+`)?og(e):e}function dU(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 fU(e){return[...e].reverse().find(e=>e.type===`call.summary`)?.data}function pU({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)(dH,{call:e,onNothing:r})})}var mU=Uv.loose(),hU=50,gU=250;function _U(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:hU};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=>mU.parse(e))),t=n.total,l=typeof n.next==`string`?n.next:null}o({rows:e,total:t,next:l})}catch{r||c(!0)}})()},gU);return()=>{r=!0,window.clearTimeout(a)}},[i,e,t.query,t.agent,t.channel,n,s,r]),s?null:a}function vU(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 yU=80;function bU(){let{lines:e,floorError:t}=tb(),n=Sr().call,[r,i]=Xi(),a=r.get(`agent`),[o,s]=(0,D.useState)(``),c=vh({name:`live.calls`,initial:300,min:220,max:520,side:`left`}),l=SU(),u=e.filter(e=>(a===null||e.agent===a)&&vU(e,o)),d=u.filter(GS),f=u.filter(e=>!GS(e)).slice(0,yU),p=[...d,...f],m=n??d[0]?.call??p[0]?.call,h=a===null?``:`?agent=${encodeURIComponent(a)}`;return(0,A.jsxs)(`div`,{className:`fl`,style:c.style,children:[c.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:d.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`fl-count`,children:d.length===1?`1 call up`:`${d.length} calls up`}),(0,A.jsxs)(`span`,{className:`fl-asked`,title:`re-asked every ${US/1e3} s`,children:[u.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:o,onChange:e=>s(e.target.value)}),a!==null&&(0,A.jsxs)(`div`,{className:`fl-only`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:a}),(0,A.jsx)(`button`,{type:`button`,className:`fl-only-clear`,onClick:()=>{r.delete(`agent`),i(r)},children:`every agent`})]})]}),(0,A.jsxs)(`div`,{className:`fl-list`,children:[t!==null&&(0,A.jsx)(`p`,{className:`fl-empty fl-refused`,children:t}),p.length===0&&t===null&&(0,A.jsx)(`p`,{className:`fl-empty`,children:o===``?`No calls yet. Leave this open — a call that reaches any agent shows up here as it rings.`:`No call here matches.`}),d.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`On a call now`}),d.map(e=>(0,A.jsx)(xU,{line:e,on:e.call===m,now:l,to:`/live/${e.call}${h}`},e.call)),f.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`Recent`}),f.map(e=>(0,A.jsx)(xU,{line:e,on:e.call===m,now:l,to:`/live/${e.call}${h}`},e.call)),f.length>0&&(0,A.jsx)(Wi,{to:`/sessions`,className:`fl-all`,children:`Every session →`})]})]}),m===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)(cU,{call:m,agent:p.find(e=>e.call===m)?.agent},m)]})}function xU({line:e,on:t,now:n,to:r}){let i=GS(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 SU(){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 CU=/^call[_-][\w+-]{6,}$/,wU=`minmax(0,1.3fr) 128px 84px 78px 74px minmax(0,1.5fr)`,TU=`minmax(0,1.3fr) 84px 78px 74px minmax(0,1.6fr)`,EU=[`web`,`phone`,`whatsapp`];function DU({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=_U(n,a,s,`${e.length}:${e[0]?.call??``}:${e.filter(GS).length}`),u=n===``,d=l===null?e.filter(e=>vU(e,a.query)&&(a.agent===``||e.agent===a.agent)&&(a.channel===``||e.channel===a.channel)):l.rows,f=[...d.filter(GS),...d.filter(e=>!GS(e))],p=e=>u?`/sessions/${e}`:`/a/${n}/sessions/${e}`,m=e=>{let t=a.query.trim();e.key===`Enter`&&CU.test(t)&&i(p(t))},h=u?wU:TU,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`}),EU.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?CU.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:[GS(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:GS(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??OU(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 OU(e){return GS(e)?`on a call`:e.end_reason===null?`—`:e.end_reason.replace(/_/g,` `)}function kU(){let{lines:e,floorError:t,agents:n}=tb(),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)(DU,{lines:e,error:t,agent:``,agents:r})]})}var AU=[`qa`,`supervisor`,`manager`,`admin`,`developer`],jU=z({id:P(),email:P(),name:P(),role:mp(AU),agents:R(P()),status:mp([`invited`,`active`,`disabled`]),scopes:R(P()),production:L()}),MU=z({member:jU,token:P(),expires_at:P()});async function NU(e){return z({members:R(jU)}).parse(await k(e,`/v1/members`)).members}async function PU(e,t){return MU.parse(await sa(e,`/v1/members`,t))}async function FU(e,t){return MU.parse(await sa(e,`/v1/members/${encodeURIComponent(t)}/reset`,{}))}async function IU(e,t){await ca(e,`/v1/members/${encodeURIComponent(t)}`)}async function LU(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 jU.parse(await fa(r))}var RU=z({configured:L(),issuer:P().nullish(),client_id:P().nullish(),domains:R(P()),role:P().nullish(),required:L(),redirect_uri:P()});async function zU(e){try{return RU.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 BU(e,t){return RU.parse(await oa(e,`/v1/org/sso`,t))}async function VU(e){await ca(e,`/v1/org/sso`)}var HU=z({on:L(),ceiling_eur:F().nullable()});function UU(){let e=j(),t=Eh(),[n,r]=(0,D.useState)(null),i=Sm(vm,`numbers`)&&t!==null&&rb(t,`numbers`),a=Sm(vm,`team`)&&t!==null&&rb(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([bb(e).catch(()=>null),yb(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=>HU.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 NU(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 WU=new Set([`transferred`,`supervisor_ended`]),GU={escalated:{pill:`red`,tint:`red`},"low score":{pill:`amber`,tint:`amber`},"promise made":{pill:`indigo`,tint:`indigo`}},KU={escalated:`escalated`,low_score:`low score`,promise:`promise made`};function qU(){let e=new Date().getHours();return e<12?`Good morning`:e<19?`Good afternoon`:`Good evening`}function JU(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=>KU[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&&WU.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 YU(e){let t=e.filter(e=>!e.live);return t.length===0?null:t.filter(e=>e.end_reason===null||!WU.has(e.end_reason)).length/t.length}function XU(){let e=wh(),{lines:t,live:n,insights:r}=tb(),i=ng(),a=rg(t,i.today),o=rg(t,i.yesterday),s=JU(pV(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?YU(a):r.resolved_rate,p=r===null?YU(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===``?qU():`${qU()}, ${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)(QU,{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:GU[e.flag].tint}),name:sg(e.row.line),tag:(0,A.jsx)(Qm,{tone:GU[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)($U,{lines:a.length>0?a:t,counted:r!==null&&u>0?r.channels:null}),(0,A.jsx)(UU,{})]})]})]})}var ZU=[{channel:`phone`,name:`Phone`,color:`var(--accent)`},{channel:`web`,name:`Web`,color:`var(--accent-2)`},{channel:`whatsapp`,name:`WhatsApp`,color:`var(--accent-3)`}];function QU({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 $U({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:ZU.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 eW=`minmax(0,1.2fr) 96px minmax(0,1fr) 150px 92px`;function tW(){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 cb(e));(0,D.useEffect)(()=>{let t=!1;return cb(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 lb(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 ub(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:eW,labels:[`Name`,`World`,`Whose`,`Last used`,`Status>`]}),(r??[]).map(e=>(0,A.jsx)(nW,{row:e,stop:S},e.fingerprint))]})})]})}function nW({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:eW},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 rW=`/v1/lexicon`;async function iW(e){return xy.parse(await k(e,rW))}async function aW(e,t,n,r,i){return xy.parse(await oa(e,rW,{lexicon:t,if_version:n,note:r,team:i}))}function oW(e){return e instanceof Error?e.message:String(e)}function sW(e){return{said:[...e?.lexicon.said??[]],heard:[...e?.lexicon.heard??[]]}}function cW(){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 iW(e).then(e=>{t||(n(e),i(sW(x?e.production:e.yours??e.team)))},e=>!t&&v(oW(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 aW(e,s,S?.version??null,p.trim()===``?null:p.trim(),a);n(t),i(sW(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(oW(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(sW(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 lW=[`all`,...Fh],uW=`130px minmax(0,1.6fr) 110px 92px`,dW={[Ah]:0,[Mh]:1,[Nh]:2,[jh]:3};function fW(){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 Fb(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),Fb(e).then(e=>{t||i(e)},r),()=>{t=!0}},[e]);let g=async t=>{t.preventDefault(),f(!0),m(null);try{await Ib(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 Lb(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))||dW[e.standing]-dW[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:lW.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:uW},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)(pW,{provider:e,brought:y.has(e.name)})})]},e.name))})]})}function pW({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 mW(e){return`/v1/agents/${encodeURIComponent(e)}/settings`}async function hW(e,t){return _y.parse(await k(e,mW(t)))}async function gW(e,t,n){return _y.parse(await oa(e,mW(t),n))}async function _W(e,t,n){return vy.parse(await k(e,`${mW(t)}/history`,{team:String(n)}))}async function vW(e,t,n,r){return _y.parse(await sa(e,`${mW(t)}/rollback`,{version:n,team:r}))}var yW=[`voice`,`tts`,`tts_model`,`stt`,`llm`,`greeting`,`hangup`,`turn`,`memory`,`knowledge`,`bases`],bW={voice:`Voice`,tts:`Voice vendor`,tts_model:`Voice model`,stt:`STT`,llm:`LLM`,greeting:`Opening`,hangup:`Hang up when`,turn:`Turn`,memory:`Memory`,knowledge:`Knowledge`,bases:`Bases`};function xW(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 SW(e,t){let n=[];for(let r of yW){let i=xW(e,r),a=xW(t,r);i!==a&&n.push(`${bW[r]} ${i??`—`} → ${a??`—`}`)}return n}function CW(e,t){return t?e.team:e.yours}function wW(e){return e instanceof Error?e.message:String(e)}function TW(e){return(fm===`hosted`?e.production:e.yours??e.team)?.config.bases??[]}function EW({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 hW(t,e).then(e=>{n||r(TW(e))},e=>{n||a(wW(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 DW=z({agent:P().nullable(),base:P().nullable(),directory:P().nullable(),files:I(),golden:P().nullable(),questions:I()}),OW=iy.extend({files:I()});async function kW(e){return ay.parse(await k(e,`/v1/knowledge`))}async function AW(e,t){return DW.parse(await Cw(e,t,`knowledge.roster`,{agent:t}))}async function jW(e,t,n){return OW.parse(await Cw(e,t,`knowledge.push`,{agent:t,...n===``?{}:{base:n}}))}async function MW(e,t,n){return ry.parse(await Cw(e,t,`knowledge.eval`,{agent:t,...n===``?{}:{base:n}}))}async function NW(e,t){await ca(e,`/v1/knowledge/${encodeURIComponent(t)}`)}var PW=`minmax(0,1fr) 90px 140px 150px 80px`;function FW(){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 kW(e)).bases)},[e]);(0,D.useEffect)(()=>{let n=!1;return v().catch(e=>{n||_(LW(e))}),AW(e,t).then(e=>{n||(r(e),l(e.base??t))},e=>{n||a(LW(e))}),()=>{n=!0}},[e,t,v]);let y=async n=>{d(n),_(null);try{n===`push`?(p(await jW(e,t,c)),await v()):h(await MW(e,t,c))}catch(e){_(LW(e))}finally{d(``)}},b=async t=>{if(window.confirm(`Drop the base ${t}? Nothing brings it back but another push.`)){_(null);try{await NW(e,t),await v()}catch(e){_(LW(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. A base opens onto its files, read and edited one at a time; a project pushes its folder whole from here. Which bases the agent reads is its Settings; what it knows by heart is Settings ▸ Knowledge, not a document.`}),(0,A.jsx)(EW,{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)(IW,{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:PW,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,``]}),(o??[]).map(e=>(0,A.jsxs)(fh,{columns:PW,to:`/docs/${encodeURIComponent(e.base)}`,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 IW({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 LW(e){return e instanceof na||e instanceof Error?e.message:String(e)}var RW=`150px minmax(0,1fr) 110px 76px`;function zW(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 mT(e,t))},[e,t]);(0,D.useEffect)(()=>{let n=!1;return mT(e,t).then(e=>{n||r(e)},e=>{n||(r(null),d(UW(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 cT(e,n)).facts})}catch(e){d(UW(e))}},m=async t=>{if(window.confirm(`Erase everything memory kept about ${t}? There is no undo.`)){d(null);try{let r=(await lT(e,t)).forgotten;l(`${r} fact${r===1?``:`s`} about ${zW(t)} forgotten.`),s({contact:t,facts:[]}),n!=null&&await f()}catch(e){d(UW(e))}}},h=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${zW(t.contact)} stays.`)){d(null);try{await hT(e,t.id),await f()}catch(e){d(UW(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:RW,labels:[`Caller`,`Remembered`,`Written`,`Action>`]}),_.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:RW},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:zW(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 `,zW(o.contact),`.`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:RW,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:RW},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,children:zW(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)(VW,{agent:t})]})}function VW({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 uT(t,e).then(e=>{n||r(e)},e=>{n||a(UW(e))}),()=>{n=!0}},[t,e]);let m=async n=>{s(n),p(null);try{n===`recall`?l(await dT(t,e)):d(await fT(t,e))}catch(e){p(UW(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)(HW,{label:`recall@${c.k}`,value:c.recall_at_k.toFixed(2)}),(0,A.jsx)(HW,{label:`nDCG@10`,value:c.ndcg_at_10.toFixed(2)}),(0,A.jsx)(HW,{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)(HW,{label:`held`,value:`${u.held}/${u.cases}`}),(0,A.jsx)(HW,{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 HW({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 UW(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)(GW,{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 GW({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 KW({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)(qW,{busy:t,onBring:async e=>{await n(e),a(!1)},onCancel:e===null?null:()=>a(!1)})}function qW({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 JW=/^\+[1-9]\d{6,14}$/;function YW(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 XW(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 ZW({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)(GW,{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:YW(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)(QW,{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:XW(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 QW({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),!JW.test(i)){m(`Write the number with its country code, like +34600000000.`);return}u(!0),m(null);try{f(await Mb(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 $W=[{tab:`numbers`,name:`Numbers`},{tab:`outbound`,name:`Outbound calls`},{tab:`carrier`,name:`Carrier`}];function eG(){let e=j(),{agents:t}=tb(),[n,r]=Xi(),i=$W.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([bb(e),yb(e)]);o(t),c(n),u(t===null?null:await Cb(e)),f(t===null?null:await kb(e).catch(()=>null))},[e]);(0,D.useEffect)(()=>{let e=!1;return S().catch(t=>{e||_(tG(t))}),()=>{e=!0}},[S]);let C=async e=>{h(!0),_(null);try{let t=await e();return await S(),t}catch(e){throw _(tG(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:$W.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(()=>Eb(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(()=>wb(e,{...t,channel:`phone`},n)),onBuy:(t,n)=>C(()=>Tb(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)(ZW,{outbound:d,agents:t,busy:m,onProvision:t=>C(()=>Ab(e,t))}),i===`carrier`&&a!==void 0&&(0,A.jsx)(KW,{carrier:a,busy:m,onBring:async t=>{await C(()=>xb(e,t)).catch(()=>void 0)},onDrop:async()=>{await C(()=>Sb(e)).catch(()=>void 0)}})]})}function tG(e){return e instanceof na?e.message:String(e)}function nG(){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=tb().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
|
|
103
|
+
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 rG=z({vendor:P(),model:P().nullable(),voice_id:P().nullable(),language:P().nullable()}),iG=z({name:mp(jC),seconds:F(),turns:I()}),aG=z({say:P().nullable(),reply:P().nullable(),allow_interruptions:L().nullable()}),oG=z({agent:P(),hears:rG,decides:rG,speaks:rG,greeting:aG.nullable(),voices:R(P()),providers:R(Ph),defaults:fp(P(),P()),models:fp(P(),R(P())),calls:I(),medians:R(iG),unavailable_reasons:fp(P(),P())});async function sG(e,t){return oG.parse(await k(e,cG(t)))}function cG(e){return`/v1/agents/${encodeURIComponent(e)}/pipeline`}var lG=z({played:mp([`default`,`off`,`custom`]),name:P().nullable(),seconds:F().nullable(),sha256:P().nullable()});async function uG(e,t){return lG.parse(await k(e,`${cG(t)}/hold-audio`))}async function dG(e,t,n){let r=await fetch(la(e,`${cG(t)}/hold-audio`,{name:n.name}),{method:`PUT`,headers:{...ra(e),"content-type":n.type||`application/octet-stream`},body:n});return lG.parse(await fa(r))}async function fG(e,t,n){return lG.parse(await oa(e,`${cG(t)}/hold-audio/played`,{played:n}))}async function pG(e,t){let n=await fetch(la(e,`${cG(t)}/hold-audio/audio`),{headers:ra(e)});return n.ok||await fa(n),URL.createObjectURL(await n.blob())}function mG({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 uG(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 pG(t,e))}catch(e){s(e instanceof Error?e.message:String(e))}},p=n=>{n!==void 0&&(d(`Converting…`,()=>dG(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…`,()=>fG(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…`,()=>fG(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 hG({stage:e,unavailable:t}){return(0,A.jsxs)(vG,{job:`hears`,stage:e,unavailable:t,children:[(0,A.jsx)(yG,{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)(yG,{label:`Model`,value:e.model}),(0,A.jsx)(yG,{label:`Switchable to`,value:`Any STT provider on file`,note:`Effective on the next session.`})]})}function gG({stage:e,unavailable:t}){return(0,A.jsxs)(vG,{job:`decides`,stage:e,unavailable:t,children:[(0,A.jsx)(yG,{label:`Model`,value:e.model??`the vendor's default`}),(0,A.jsx)(yG,{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)(yG,{label:`Tools`,value:`The class's @tool methods`})]})}function _G({stage:e,unavailable:t}){return(0,A.jsxs)(vG,{job:`speaks`,stage:e,unavailable:t,children:[(0,A.jsx)(yG,{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)(yG,{label:`Model`,value:e.model}),(0,A.jsx)(yG,{label:`Aligned transcript`,value:`On`,note:`Timed words, so the log knows when each word was spoken.`})]})}function vG({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 yG({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 bG(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),sG(t,e).then(e=>{n||r(e)},e=>{n||a(String(e))}),()=>{n=!0}},[e,t]),{report:n,error:i}}var xG={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 SG({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:jC.map((e,t)=>{let n=xG[e],a=r.get(e)?.seconds??null;return(0,A.jsxs)(`div`,{className:t===jC.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:CG(t,n)})]})}function CG(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 wG(){let e=Sr().agent??``,{report:t,error:n}=bG(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)(hG,{stage:t.hears,unavailable:t.unavailable_reasons.hears??null}),(0,A.jsx)(gG,{stage:t.decides,unavailable:t.unavailable_reasons.decides??null}),(0,A.jsx)(_G,{stage:t.speaks,unavailable:t.unavailable_reasons.speaks??null})]}),(0,A.jsx)(SG,{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)(mG,{agent:e},`hold-${e}`)]})]})}function TG(){let e=Sr().agent??``,{lines:t,error:n}=WS(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)(DU,{lines:t,error:n,agent:e,agents:[]})]})}var EG={passed:`green`,failed:`red`,deferred:`amber`,skipped:`muted`};function DG({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 Xw(n,t)):c(await Qw(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:EG[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 OG=`confirm.`,kG=`tool.call`;function AG(e){let t=new Map;for(let n of e){if(!n.type.startsWith(OG))continue;let e=zG(n,`call_id`),r=t.get(e)??LG(e,zG(n,`tool`));t.set(e,{...r,...IG(n)})}for(let n of e){let e=n.type===kG?t.get(zG(n,`call_id`)):void 0;e!==void 0&&(e.ran=n)}return[...t.values()]}function jG({rows:e}){return e.length===0?null:(0,A.jsx)(`div`,{className:`session-consents`,children:e.map(e=>(0,A.jsx)(MG,{consent:e},e.callId))})}function MG({consent:e}){let t=PG(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:NG(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:zG(e.requested,`phrase`)}),e.granted!==null&&(0,A.jsxs)(`div`,{className:`session-consent-said`,children:[`“`,zG(e.granted,`said`),`”`]}),(0,A.jsxs)(`div`,{className:`session-consent-audience`,children:[`audience `,FG(e)]}),t!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:t})]})}function NG(e){return e.granted===null?e.declined===null?`seq ${RG(e.requested)} asked and nothing answered`:`seq ${RG(e.declined)} declined seq ${RG(e.ran)}`:`seq ${e.granted.seq} authorised seq ${RG(e.ran)}`}function PG(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:zG(r,`audience`);return i!==null&&i!==zG(t,`audience`)?`${e.tool} was confirmed by another audience than the one asked at seq ${r?.seq??0}`:null}function FG(e){let t=e.granted??e.declined??e.requested;return t===null?`—`:zG(t,`audience`)}function IG(e){return e.type===`confirm.granted`?{granted:e}:e.type===`confirm.declined`?{declined:e}:{requested:e}}function LG(e,t){return{callId:e,tool:t,requested:null,granted:null,declined:null,ran:null}}function RG(e){return e===null?`—`:String(e.seq)}function zG(e,t){let n=e.data[t];return typeof n==`string`?n:``}var BG={held:`green`,broken:`red`,deferred:`amber`,skipped:`muted`};function VG({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?`${WG(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)(KG,{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`}),UG(s.not_judged)&&(0,A.jsx)(`p`,{className:`session-sentence`,children:s.not_judged}),(0,A.jsx)(`p`,{className:`session-sentence`,children:GG(s,r)}),i&&(0,A.jsx)(KG,{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)(HG,{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:GG(s,r)})]})})]})}function HG({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:BG[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 UG(e){return e!=null&&e.trim().toLowerCase()!==`no judge was given to this session`}function WG(e){return e.judges.filter(e=>e.verdict===`held`).length}function GG(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 KG({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 qG={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`},JG=[`llm_node_ttft`,`e2e_latency`];function YG({rows:e}){let t=[...e.filter(e=>JG.includes(e.name)).sort((e,t)=>JG.indexOf(e.name)-JG.indexOf(t.name)),...e.filter(e=>!JG.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:qG[e.name]??e.name}),(0,A.jsx)(`div`,{className:`session-latency-value`,children:FC(e.seconds)}),(0,A.jsxs)(`div`,{className:`session-latency-max`,children:[`max `,FC(e.max)]})]},e.name))})]})}var XG={"turn.user":`user`,"turn.agent":`agent`},ZG=/^#seq-(\d+)$/;function QG({lines:e,turns:t}){let[n,r]=(0,D.useState)(new Set),[i,a]=(0,D.useState)(!1),o=iK(t),s=$G(gr().hash),c=e.length;(0,D.useEffect)(()=>{s!==null&&c>0&&document.getElementById(eK(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)(tK,{line:e,turn:o.get(aK(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 $G(e){let t=ZG.exec(e)?.[1];return t===void 0?null:Number(t)}function eK(e){return`seq-${e}`}function tK({line:e,turn:t,open:n,cited:r,onToggle:i}){let a=e.fields.length>0,o=[`session-entry`,`session-entry-${nK(e.entry.type)}`];return a&&o.push(`session-entry-opens`),r&&o.push(`session-entry-cited`),(0,A.jsxs)(`div`,{id:eK(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)(rK,{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 nK(e){return e.startsWith(`turn.`)?`turn`:e.startsWith(`state.`)?`state`:e.startsWith(`tool.`)||e.startsWith(`confirm.`)?`tool`:e.startsWith(`call.`)?`call`:`quiet`}function rK({turn:e}){return(0,A.jsx)(`span`,{className:`session-chips`,children:MC(e).map(e=>(0,A.jsxs)(`span`,{className:`session-chip`,children:[e.field,` `,(0,A.jsx)(`b`,{children:e.value})]},e.field))})}function iK(e){return new Map(e.map(e=>[`${e.role}:${e.speech_id}`,e]))}function aK(e,t){let n=t.speech_id;return`${XG[e]??``}:${typeof n==`string`?n:``}`}var oK=[`turn.user`,`turn.agent`],sK=`metrics.`,cK=`memory.ops`,lK=`docs.sources`,uK={"tool.call":`→`,"tool.result":`←`},dK=`!`;function fK(e){let t=SC(e.map(e=>e.type)),n=e[0]?.ts??0;return e.map(e=>mK(e,n,t.get(e.type)))}function pK(e,t){return`+${(e-t).toFixed(3)}`}function mK(e,t,n){return{entry:e,mark:hK(e.type),since:pK(e.ts,t),payload:gK(e,n),fields:_K(e,n)}}function hK(e){return e.startsWith(`confirm.`)?dK:uK[e]??``}function gK(e,t){return oK.includes(e.type)?CC(Object.fromEntries(Object.entries(e.data).filter(([e])=>e!==`metrics`)),t):e.type.startsWith(sK)?``:e.type===cK?IH(e.data):e.type===lK?RH(e.data):CC(e.data,t)}function _K(e,t){if(oK.includes(e.type)){let n=e.data.metrics,r=t?.properties?.metrics;return xK(n)?vK(n,sK,r):[]}return e.type.startsWith(sK)?vK(e.data,``,t):e.type===cK?LH(e.data).map(e=>({name:`fact`,value:e})):e.type===lK?zH(e.data).map(e=>({name:`source`,value:e})):[]}function vK(e,t,n){return yK(e,t,n,bK(e,n))}function yK(e,t,n,r){let i=[];for(let a of r){let r=e[a],o=n?.properties?.[a];xK(r)?i.push(...yK(r,`${t}${a}.`,o,Object.keys(r))):i.push({name:`${t}${a}`,value:wC(r,o)})}return i}function bK(e,t){let n=Object.keys(t?.properties??{}).filter(t=>t in e);return[...n,...Object.keys(e).filter(e=>!n.includes(e))]}function xK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function SK(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 fC(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 CK=`call.summary`;function wK(){let{agent:e=``,call:t=``}=Sr(),{entries:n,reading:r,error:i}=SK(t),a=(0,D.useMemo)(()=>({state:Oy(n),lines:fK(n),latencies:BC(n),consented:AG(n),recording:lH(MK(n)?.data),score:NK(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)(DG,{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)(DK,{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)(uH,{call:t,path:a.recording}),(0,A.jsxs)(`div`,{className:`session-split`,children:[(0,A.jsx)(OK,{state:a.state}),(0,A.jsxs)(`div`,{className:`session-side`,children:[(0,A.jsx)(YG,{rows:a.latencies}),(0,A.jsx)(VG,{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)(kK,{cost:a.state.cost}),(0,A.jsxs)(EK,{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)(jG,{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)(QG,{lines:a.lines,turns:a.state.turns})]})]})]})}var TK=/^#seq-\d+$/;function EK({children:e}){let{hash:t}=gr(),[n,r]=(0,D.useState)(()=>TK.test(t));return(0,D.useEffect)(()=>{TK.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 DK({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 OK({state:e}){let t=jK(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 kK({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:AK(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 AK(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 jK(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 MK(e){return[...e].reverse().find(e=>e.type===CK)}function NK(e){let t=[...e].reverse().find(e=>e.type===Fv);return t===void 0?null:Y_.parse(t.data)}var PK=z({name:P(),goal:P(),style:P()}),FK=z({agent:P().nullable(),personas:R(PK)}),IK=z({call:P()});async function LK(e,t){return FK.parse(await Cw(e,t,`simulate.roster`))}async function RK(e,t){return IK.parse(await Cw(e,t.agent,`simulate.start`,t)).call}var zK=6,BK=15,VK=0;function HK({agents:e,onStarted:t}){let n=j(),[r,i]=(0,D.useState)(e[0]??``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!0),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(zK),[h,g]=(0,D.useState)(BK),[_,v]=(0,D.useState)(VK),[y,b]=(0,D.useState)(!1),[x,S]=(0,D.useState)(!1),[C,w]=(0,D.useState)(null),T=e[0]??``;(0,D.useEffect)(()=>{r===``&&T!==``&&i(T)},[r,T]),(0,D.useEffect)(()=>{if(r===``)return;let e=!1;return o(null),w(null),LK(n,r).then(t=>{e||(o(t),c(t.personas[0]?.name??``))},t=>{e||w(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[n,r]);let ee=a?.personas.find(e=>e.name===s),te=UK(a,r),ne=async e=>{e.preventDefault(),S(!0),w(null);try{t(await RK(n,{agent:r,persona:s,voice:l,judge:d,turns:p,...l&&y?{background_noise:h,packet_loss:_}:{}}),r,l)}catch(e){w(e instanceof na?e.message:String(e))}finally{S(!1)}};return(0,A.jsxs)(`form`,{className:`sim`,onSubmit:e=>void ne(e),children:[(0,A.jsx)(`div`,{className:`sim-head`,children:(0,A.jsx)(`span`,{className:`sim-title`,children:`Simulate a caller`})}),e.length>0&&(0,A.jsx)(Wm,{label:`Agent`,children:(0,A.jsx)(Hm,{size:`sm`,value:r,onChange:e=>i(e.target.value),children:e.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),a===null&&C===null&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Asking the process that holds `,r||`the agent`,` for its personas…`]}),te!==null&&(0,A.jsx)(`p`,{className:`sim-note`,children:te}),a!==null&&te===null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Wm,{label:`Persona`,children:(0,A.jsx)(Hm,{size:`sm`,value:s,onChange:e=>c(e.target.value),children:a.personas.map(e=>(0,A.jsx)(`option`,{value:e.name,children:e.name},e.name))})}),ee!==void 0&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Goal: `,ee.goal]}),(0,A.jsxs)(`div`,{className:`sim-pair`,children:[(0,A.jsx)(Wm,{label:`Max turns`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:1,max:30,value:p,onChange:e=>m(Number(e.target.value))})}),l&&y&&(0,A.jsx)(Wm,{label:`Noise, dB under`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:60,value:h,onChange:e=>g(Number(e.target.value))})}),l&&y&&(0,A.jsx)(Wm,{label:`Packets lost, %`,children:(0,A.jsx)(W,{size:`sm`,type:`number`,min:0,max:100,value:_,onChange:e=>v(Number(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`sim-checks`,children:[(0,A.jsxs)(Ym,{checked:l,onChange:u,children:[`Voice `,(0,A.jsx)(`span`,{className:`sim-aside`,children:`a real line, and you can listen`})]}),(0,A.jsx)(Ym,{checked:d,onChange:f,children:`Judge at hang-up`}),l&&(0,A.jsxs)(Ym,{checked:y,onChange:b,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:x||s===``,children:x?`Calling…`:`Call the agent`})]}),C!==null&&(0,A.jsx)(`p`,{className:`sim-refused`,children:C})]})}function UK(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 WK(){let{agents:e}=tb(),t=Sr().call,[n]=Xi(),r=vr(),i=vh({name:`simulations.form`,initial:340,min:280,max:520,side:`left`}),a=n.get(`agent`)??void 0,o=n.get(`spoken`)===`1`;return(0,A.jsxs)(`div`,{className:`sims`,style:i.style,children:[i.handle,(0,A.jsxs)(`aside`,{className:`sims-side`,"aria-label":`start a simulation`,children:[e.length===0?(0,A.jsx)(`p`,{className:`sims-note`,children:"No agent is held here yet: run `pinecall start` in the agent's directory, and it shows up to simulate against."}):(0,A.jsx)(HK,{agents:e.map(e=>e.slug),onStarted:(e,t,n)=>{let i=new URLSearchParams({agent:t,...n?{spoken:`1`}:{}});r(`/simulations/${e}?${i.toString()}`)}}),(0,A.jsx)(`p`,{className:`sims-note`,children:`A model plays the persona against the agent. With Voice on, the call is a real line and you hear both of them here as it happens. Max turns is where the caller stops, if it has not hung up before.`})]}),t===void 0?(0,A.jsx)(`div`,{className:`sims-nothing`,children:`Pick an agent and a persona, then call. The simulation opens here, and you hear it live.`}):(0,A.jsxs)(`div`,{className:`sims-watch`,children:[o&&(0,A.jsx)(qK,{call:t}),(0,A.jsx)(cU,{call:t,agent:a})]},t)]})}var GK=1e3,KK=30;function qK({call:e}){let t=hH(e),n=(0,D.useRef)(0),r=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(t.listening===`off`&&!r.current&&n.current===0&&(n.current=1,t.join()),t.listening===`failed`&&!r.current&&n.current<KK){let e=window.setTimeout(()=>{n.current+=1,t.join()},GK);return()=>window.clearTimeout(e)}t.listening===`muted`&&!r.current&&(r.current=!0,t.hear(!0))},[t]);let i=(()=>{switch(t.listening){case`on`:return`Listening live · the caller and the agent`;case`muted`:return`Muted`;case`joining`:return`Joining the call…`;case`failed`:return n.current<KK?`Waiting for the call's room to open…`:`Could not join the call: ${t.error??`no room`}`;case`off`:return r.current?`The call is over`:`Joining the call…`}})();return(0,A.jsxs)(`div`,{className:`sims-ear`,role:`status`,children:[(0,A.jsx)(`span`,{className:t.listening===`on`?`sims-ear-dot sims-ear-dot-on`:`sims-ear-dot`}),(0,A.jsx)(`span`,{className:`sims-ear-said`,children:i}),t.listening===`on`&&(0,A.jsx)(U,{size:`sm`,pill:!0,onClick:()=>t.hear(!1),children:`Mute`}),t.listening===`muted`&&(0,A.jsx)(U,{size:`sm`,pill:!0,onClick:()=>t.hear(!0),children:`Unmute`})]})}var JK=``,YK=[`2`,`4`,`6`,`8`,`12`,`16`];function XK({rows:e,offered:t,onChange:n}){let r=new Set(e.map(e=>e.base)),i=(t??[]).filter(e=>!r.has(e.base)),a=(t,r)=>n(e.map((e,n)=>n===t?r:e)),o=t=>n(e.filter((e,n)=>n!==t));return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Bases`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:"The documents the agent searches on every turn, by the name each folder was pushed under. A base is pushed from a project with `pinecall docs push`; the Docs tab lists them."})]}),e.length===0?(0,A.jsx)(`p`,{className:`set-help`,children:`Nothing attached: the agent answers from what it knows by heart and from its tools alone.`}):(0,A.jsxs)(`div`,{className:`set-bases`,children:[(0,A.jsxs)(`div`,{className:`set-bases-head`,children:[(0,A.jsx)(`span`,{children:`Base`}),(0,A.jsx)(`span`,{children:`Chunks a turn reads`}),(0,A.jsx)(`span`,{})]}),e.map((e,n)=>(0,A.jsxs)(`div`,{className:`set-bases-row`,children:[(0,A.jsxs)(Hm,{value:e.base,onChange:t=>a(n,{...e,base:t.target.value}),children:[(t??[]).some(t=>t.base===e.base)?null:(0,A.jsxs)(`option`,{value:e.base,children:[e.base,` · not pushed in this world`]}),(t??[]).map(t=>(0,A.jsxs)(`option`,{value:t.base,disabled:t.base!==e.base&&r.has(t.base),children:[t.base,` · `,t.chunks,` chunks`]},t.base))]}),(0,A.jsxs)(Hm,{value:e.k,onChange:t=>a(n,{...e,k:t.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default · 8`}),(e.k===``||YK.includes(e.k)?YK:[e.k,...YK]).map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}),(0,A.jsx)(U,{size:`xs`,onClick:()=>o(n),children:`Detach`})]},`${e.base}-${n}`))]}),(0,A.jsx)(`div`,{className:`set-row`,children:(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Attach a base`}),(0,A.jsxs)(Hm,{value:JK,disabled:i.length===0,onChange:t=>t.target.value!==JK&&n([...e,{base:t.target.value,k:``}]),children:[(0,A.jsx)(`option`,{value:JK,children:t===null?`Asking the gateway…`:i.length===0?`Every pushed base is attached`:`Pick one…`}),i.map(e=>(0,A.jsxs)(`option`,{value:e.base,children:[e.base,` · `,e.chunks,` chunks`]},e.base))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`Only bases pushed in this world appear. A base a colleague pushed to their own corner is theirs until they push it for the team.`})]})})]})}var ZK=[{value:`say`,label:`Say these words`},{value:`reply`,label:`Let the model open`}],QK=[`500`,`700`,`1000`,`1500`,`2000`,`3000`],$K=[`1`,`2`,`3`,`4`,`5`];function eq({typed:e,wordsOnly:t,change:n}){return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Conversation`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:`The first thing a caller hears, when the agent may hang up, and how quickly a turn is cut.`})]}),(0,A.jsxs)(`div`,{className:`set-field set-wide`,children:[(0,A.jsx)(Vm,{children:`Opening`}),!t&&(0,A.jsx)(Gm,{options:ZK,value:e.opening,onChange:e=>n(`opening`,e)}),e.opening===`say`||t?(0,A.jsx)(Um,{value:e.say,rows:2,placeholder:`The exact words the caller hears first`,onChange:e=>n(`say`,e.target.value)}):(0,A.jsx)(Um,{value:e.reply,rows:2,placeholder:`What the model is told about how to open the call`,onChange:e=>n(`reply`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:e.opening===`say`||t?`Said exactly as written, before the model runs: the caller hears it at once.`:`An instruction the model reads to find its own opening. It costs a model round trip before the caller hears anything.`})]}),!t&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`set-field set-wide`,children:[(0,A.jsx)(Vm,{children:`May hang up when`}),(0,A.jsx)(W,{value:e.hangup,placeholder:`the person has what they came for, or asks you to end the call`,onChange:e=>n(`hangup`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:`In your words. Empty: the agent never ends the call itself.`})]}),(0,A.jsxs)(`div`,{className:`set-row`,children:[(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Silence that ends a turn`}),(0,A.jsxs)(Hm,{value:e.endpointing_ms,onChange:e=>n(`endpointing_ms`,e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default · 1 second`}),tq(QK,e.endpointing_ms).map(e=>(0,A.jsxs)(`option`,{value:e,children:[Number(e)/1e3,` s`]},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`How long the caller stays quiet before the agent answers. Shorter answers faster, and cuts off a slow speaker.`})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Words before an interruption counts`}),(0,A.jsxs)(Hm,{value:e.min_interruption_words,onChange:e=>n(`min_interruption_words`,e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default · 2 words`}),tq($K,e.min_interruption_words).map(e=>(0,A.jsx)(`option`,{value:e,children:e===`1`?`1 word`:`${e} words`},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`How many words a caller says over the agent before it stops talking. A cough is not an interruption.`})]})]})]})]})}function tq(e,t){return t===``||e.includes(t)?e:[t,...e]}var nq=`elevenlabs`,rq=`not on this box`;function iq({modality:e,title:t,blurb:n,knob:r,providers:i,defaults:a,models:o,onChange:s,children:c}){let l=Rh(i,e).filter(t=>t.ready&&(o[`${e}/${t.name}`]??[]).length>0),u=a[e]??``,d=r.vendor===``?u:r.vendor,f=l.some(e=>e.name===r.vendor)||r.vendor===``?l:[{name:r.vendor,ready:!1},...l],p=o[`${e}/${d}`]??[],m=p.includes(r.model)||r.model===``?p:[r.model,...p];return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:t}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:n})]}),(0,A.jsxs)(`div`,{className:`set-row`,children:[(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Vendor`}),(0,A.jsxs)(Hm,{value:r.vendor,onChange:e=>s({vendor:e.target.value,model:``}),children:[(0,A.jsxs)(`option`,{value:``,children:[`Runtime default · `,u]}),f.map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,e.ready?``:` · ${rq}`]},e.name))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`The vendors this box has a key for. Another one appears here once its key is added in Providers.`})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Model`}),(0,A.jsxs)(Hm,{value:r.model,onChange:e=>s({...r,model:e.target.value}),children:[(0,A.jsxs)(`option`,{value:``,children:[d,`'s default`,p[0]===void 0?``:` · ${p[0]}`]}),m.map(e=>(0,A.jsxs)(`option`,{value:e,children:[e,p.includes(e)?``:` · as set`]},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:p.length===0?`${d} runs its own default; there is no model to pick.`:`The models that run on this box. The default is the one tuned for phone calls.`})]})]}),c]})}function aq({vendor:e,voice:t,voices:n,onChange:r}){if(e!==`elevenlabs`)return(0,A.jsx)(`div`,{className:`set-row`,children:(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Voice`}),(0,A.jsxs)(`p`,{className:`set-help`,children:[t===``?`${e} speaks in its model's own voice: there is no voice to pick here.`:`${e} speaks as ${t}, set from the terminal.`,` The voices to pick from are `,nq,`'s.`]})]})});let i=n.includes(t)||t===``?n:[t,...n];return(0,A.jsx)(`div`,{className:`set-row`,children:(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Voice`}),(0,A.jsxs)(Hm,{value:t,onChange:e=>r(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default`}),i.map(e=>(0,A.jsxs)(`option`,{value:e,children:[e,n.includes(e)?``:` · as set`]},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`Hear each one in the Talk tab before a caller does.`})]})})}function oq(e,t){if(e==null||e===``)return{vendor:``,model:``};let n=e.lastIndexOf(`/`);return n>=0?{vendor:e.slice(0,n),model:e.slice(n+1)}:t.has(e)?{vendor:e,model:``}:{vendor:``,model:e}}function sq(e){return e.vendor===``?e.model:e.model===``?e.vendor:`${e.vendor}/${e.model}`}function cq(e,t){let n=e.turn??void 0,r=e.memory??void 0,i=oq(e.tts,t),a=e.tts_model??void 0,o=e.greeting?.reply??``;return{stt:oq(e.stt,t),llm:oq(e.llm,t),tts:a===void 0||a===``?i:{...i,model:a},voice:e.voice??``,opening:o===``?`say`:`reply`,say:e.greeting?.say??``,reply:o,hangup:e.hangup?.when??``,endpointing_ms:typeof n?.endpointing_ms==`number`?String(n.endpointing_ms):``,min_interruption_words:typeof n?.min_interruption_words==`number`?String(n.min_interruption_words):``,remember:(r?.remember??[]).join(`
|
|
104
|
+
`),forget:(r?.forget??[]).join(`
|
|
105
|
+
`),knowledge:e.knowledge??``,bases:(e.bases??[]).map(e=>({base:e.base,k:typeof e.k==`number`?String(e.k):``})),note:``}}function lq(e,t,n){let r=t?{...n}:{};if(!t){for(let t of[`stt`,`llm`,`tts`]){let n=sq(e[t]);n!==``&&(r[t]=n)}let t=e.voice.trim();t!==``&&(r.voice=t);let n=e.hangup.trim();n!==``&&(r.hangup={when:n});let i={};e.endpointing_ms.trim()!==``&&(i.endpointing_ms=Number(e.endpointing_ms)),e.min_interruption_words.trim()!==``&&(i.min_interruption_words=Number(e.min_interruption_words)),Object.keys(i).length>0&&(r.turn=i);let a=e.bases.filter(e=>e.base.trim()!==``).map(e=>e.k.trim()===``?{base:e.base.trim()}:{base:e.base.trim(),k:Number(e.k)});a.length>0&&(r.bases=a)}let i=e.say.trim(),a=e.reply.trim();e.opening===`say`&&i!==``?r.greeting={say:i}:e.opening===`reply`&&a!==``&&!t?r.greeting={reply:a}:delete r.greeting;let o=uq(e.remember),s=uq(e.forget);return o.length>0||s.length>0?r.memory={remember:o,forget:s}:delete r.memory,e.knowledge.trim()===``?delete r.knowledge:r.knowledge=e.knowledge,r}function uq(e){return e.split(`
|
|
106
|
+
`).map(e=>e.trim()).filter(e=>e!==``)}function dq({typed:e,change:t}){return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Memory`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:`What the agent writes down about a caller when the call ends, and hands back the next time that number calls.`})]}),(0,A.jsxs)(`div`,{className:`set-row`,children:[(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Remember`}),(0,A.jsx)(Um,{value:e.remember,rows:5,placeholder:`their name and phone
|
|
107
|
+
allergies
|
|
108
|
+
the morning or the afternoon they prefer`,onChange:e=>t(`remember`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:`One kind of fact per line, in your words. The extraction keeps only these.`})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(Vm,{children:`Never keep`}),(0,A.jsx)(Um,{value:e.forget,rows:5,placeholder:`card numbers
|
|
109
|
+
anything about payment`,onChange:e=>t(`forget`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:`One per line. What is named here is never written down, whatever a caller says.`})]})]})]})}function fq({typed:e,change:t}){return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Knowledge`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:`What the agent knows by heart: the business as you would tell a new receptionist. Read whole on every call, so keep it to what every call may need.`})]}),(0,A.jsxs)(`div`,{className:`set-field set-wide`,children:[(0,A.jsx)(Vm,{children:`By heart, in Markdown`}),(0,A.jsx)(Um,{value:e.knowledge,rows:16,spellCheck:!1,placeholder:`# Clínica Norte
|
|
110
|
+
|
|
111
|
+
## Hours
|
|
112
|
+
Monday to Friday, 9:00 to 20:00.
|
|
113
|
+
|
|
114
|
+
## Prices
|
|
115
|
+
A first visit is 60 euros.
|
|
116
|
+
|
|
117
|
+
## Needs an authorisation
|
|
118
|
+
An X-ray, an extraction, anything over 300 euros.`,onChange:e=>t(`knowledge`,e.target.value)}),(0,A.jsxs)(`p`,{className:`set-help`,children:[e.knowledge.length.toLocaleString(`en-US`),` characters. The documents it searches are not this: those are the Docs tab, attached under Bases.`]})]})]})}var pq=[{tab:`hears`,name:`STT`},{tab:`decides`,name:`LLM`},{tab:`speaks`,name:`Voice`},{tab:`conversation`,name:`Conversation`},{tab:`memory`,name:`Memory`},{tab:`knowledge`,name:`Knowledge`},{tab:`bases`,name:`Bases`}],mq=[`conversation`,`memory`,`knowledge`];function hq(e){return e?pq.filter(e=>mq.includes(e.tab)):pq}function gq({standing:e,version:t,wordsOnly:n,voices:r,providers:i,defaults:a,models:o,bases:s,section:c,onPickSection:l,saving:u,error:d,onSave:f}){let p=new Set(i.map(e=>e.name)),[m,h]=(0,D.useState)(()=>cq(e,p)),[g,_]=(0,D.useState)(!1),v=(e,t)=>{_(!1),h({...m,[e]:t})},y=e=>t=>{_(!1),h(e===`tts`&&t.vendor!==m.tts.vendor?{...m,tts:t,voice:``}:{...m,[e]:t})},b=m.tts.vendor===``?a.tts??`elevenlabs`:m.tts.vendor,x=async r=>{r.preventDefault(),await f(lq(m,n,e),t,m.note.trim()===``?null:m.note.trim()),_(!0)};return(0,A.jsxs)(`form`,{className:`ui-card set-form`,onSubmit:e=>void x(e),children:[(0,A.jsx)(`div`,{className:`set-tabs`,children:(0,A.jsx)(yh,{label:`Settings`,tabs:hq(n),on:c,onPick:l})}),c===`hears`&&(0,A.jsx)(iq,{modality:`stt`,title:`Speech to text`,blurb:`What turns the caller's voice into words.`,knob:m.stt,providers:i,defaults:a,models:o,onChange:y(`stt`)}),c===`decides`&&(0,A.jsx)(iq,{modality:`llm`,title:`Language model`,blurb:`The model that reads what the caller said and writes the answer.`,knob:m.llm,providers:i,defaults:a,models:o,onChange:y(`llm`)}),c===`speaks`&&(0,A.jsx)(iq,{modality:`tts`,title:`Voice`,blurb:`What says the answer out loud, and in which voice.`,knob:m.tts,providers:i,defaults:a,models:o,onChange:y(`tts`),children:(0,A.jsx)(aq,{vendor:b,voice:m.voice,voices:r,onChange:e=>v(`voice`,e)})}),c===`conversation`&&(0,A.jsx)(eq,{typed:m,wordsOnly:n,change:v}),c===`memory`&&(0,A.jsx)(dq,{typed:m,change:v}),c===`knowledge`&&(0,A.jsx)(fq,{typed:m,change:v}),c===`bases`&&(0,A.jsx)(XK,{rows:m.bases,offered:s,onChange:e=>{_(!1),h({...m,bases:e})}}),(0,A.jsxs)(`div`,{className:`set-save`,children:[(0,A.jsx)(W,{className:`set-save-note`,value:m.note,placeholder:`Why, for the history (optional)`,onChange:e=>v(`note`,e.target.value)}),(0,A.jsx)(U,{kind:`primary`,size:`form`,type:`submit`,disabled:u,children:u?`Saving…`:t===null?`Save as the first version`:`Save as v${t+1}`}),(0,A.jsx)(`span`,{className:d===null?`set-save-said`:`set-save-said set-save-error`,children:d===null?g?`Kept. The next call runs on it.`:`Every section is saved together, as one version. An empty field is the runtime's default.`:d})]})]})}function _q({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=SW(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)})]})}function vq(e){return e instanceof Error?e.message:String(e)}function yq(){let e=j(),t=Sr().agent??``,n=Eh(),[r,i]=Xi(),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(!1),[_,v]=(0,D.useState)(null),[y,b]=(0,D.useState)(null),x=n!==null&&!n.includes(`pipeline`),S=fm===`hosted`,C=hq(x),w=r.get(`section`),T=C.some(e=>e.tab===w)?w:C[0].tab,ee=(0,D.useCallback)(async()=>{o(await hW(e,t)),c(await _W(e,t,S||p))},[e,t,p,S]);(0,D.useEffect)(()=>{let n=!1;return v(null),ee().catch(e=>{n||v(vq(e))}),sG(e,t).then(e=>!n&&u(e),e=>{!n&&!(e instanceof na&&(e.status===403||e.status===404))&&v(vq(e))}),kW(e).then(e=>!n&&f(e.bases),()=>!n&&f([])),()=>{n=!0}},[e,t,ee]),(0,D.useEffect)(()=>{let e=()=>void ee().catch(()=>void 0);return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[ee]);let te=async(n,r,i)=>{g(!0),v(null);try{o(await gW(e,t,{config:n,if_version:r,note:i,team:p})),c(await _W(e,t,S||p))}catch(e){v(vq(e))}finally{g(!1)}},ne=async n=>{v(null);try{o(await vW(e,t,n,S||p)),c(await _W(e,t,S||p)),b(`v${n} is the newest again, as a new version.`)}catch(e){v(vq(e))}},re=a===null?null:CW(a,S||p),E=re??(a===null||S||p?null:a.team),ie=S?[`production`]:[`yours`,`team`,`production`],ae=`150px ${ie.map(()=>`minmax(0,1fr)`).join(` `)}`;return(0,A.jsxs)(sh,{width:1060,children:[(0,A.jsx)(ch,{title:`Settings`,ledeWidth:660,lede:S?`What this agent runs on in production. Every save is a new version with your name on it, and any version can be rolled back.`:`What this agent runs on in the sandbox: yours to try in your own corner, or the team's, which every corner falls back to. Every save is a version; production has its own page.`}),a===null&&(0,A.jsx)(Mm,{children:_??`Asking the gateway…`}),a!==null&&(0,A.jsxs)(A.Fragment,{children:[!x&&!S&&(0,A.jsx)(`div`,{className:`set-corner-pick`,children:(0,A.jsx)(Ym,{checked:p,onChange:m,children:`Write the team's corner, which every corner falls back to — not only yours`})}),(0,A.jsx)(gq,{standing:E?.config??{},version:re?.version??null,wordsOnly:x,voices:l?.voices??[],providers:l?.providers??[],defaults:l?.defaults??{},models:l?.models??{},bases:d,section:T,onPickSection:e=>i(e===C[0].tab?{}:{section:e}),saving:h,error:_,onSave:te},`${t}-${p}-${re?.version??0}-${E?.version??0}-${l===null?`asking`:`read`}`)]}),(0,A.jsxs)(V,{children:[(0,A.jsx)(H,{title:S?`What is set now`:`Compared, corner by corner`,meta:a===null?void 0:a.world}),a===null?(0,A.jsx)(Mm,{children:_??`Asking the gateway…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(dh,{columns:ae,labels:[``,...ie]}),yW.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:ae},children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:bW[e]}),ie.map(t=>(0,A.jsx)(`span`,{className:`ui-clip`,children:bq(a[t],e,t===`yours`)},t))]},e)),(0,A.jsx)(`div`,{className:`ui-card-foot set-corners-foot`,children:ie.map(e=>(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:e}),` `,a[e]===null?`nothing set`:xq(a[e])]},e))})]})]}),(0,A.jsx)(_q,{kept:s,canRollBack:!x,onRollBack:ne}),y!==null&&(0,A.jsx)(`div`,{className:`ui-empty`,children:y}),(0,A.jsx)(Nm,{children:_})]})}function bq(e,t,n){return e===null?n?`(team's)`:`—`:xW(e.config,t)??`—`}function xq(e){return`v${e.version} · ${e.author} · ${Qh(e.set_at)}${e.note===null?``:` · “${e.note}”`}`}var Sq=z({device:P().nullable(),expires_at:F(),answered:L()}),Cq=z({device:P().nullable(),org:P()});function wq(e){return`/v1/login/pairings/${encodeURIComponent(e)}`}async function Tq(e,t){return Sq.parse(await k(e,wq(t)))}async function Eq(e,t){return Cq.parse(await sa(e,wq(t),{})).org}var Dq=`c`,Oq=`a terminal`;function kq(){let e=j(),[t]=Xi(),n=t.get(Dq),[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 Tq(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 Eq(e,n))}catch(e){u(e instanceof na?e.message:String(e))}finally{o(!1)}}};return n===null?(0,A.jsx)(jq,{title:`No terminal is asking`,lede:Aq}):s===null?l!==null&&r===null?(0,A.jsx)(jq,{title:`That link is no good`,lede:l}):(0,A.jsxs)(jq,{title:`Sign this terminal in?`,lede:`A terminal calling itself ${r?.device??Oq} 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)(jq,{title:`Your terminal is signed in`,lede:`Go back to it. You are in ${s}.`})}var Aq="Run `pinecall login` in your terminal — it prints a link, and that link comes back here.";function jq({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 Mq=`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,Nq={active:`green`,invited:`amber`,disabled:`gray`};function Pq({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:Mq},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:AU.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:Nq[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 Fq={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`}},Iq=[`qa`,`supervisor`,`manager`,`developer`,`admin`],Lq=`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:Lq,labels:[`Role`,`Who`,`Opens`]}),Iq.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:Fq[e].who}),(0,A.jsx)(`span`,{className:`ui-cell-faint team-role-opens`,children:Fq[e].opens})]},e))]})}var zq=``;function Bq(){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 zU(e).then(e=>{t||n(e)},e=>{t||i(Uq(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 VU(e),n(await zU(e)),c(!1)}catch(e){i(Uq(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)(Vq,{sso:t,onSaved:e=>{n(e),o(!1)},onCancel:t.configured?()=>o(!1):void 0}),(0,A.jsx)(Hq,{uri:t.redirect_uri}),r!==null&&(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(Nm,{children:r})})]})}function Vq({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??zq),[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 BU(r,{issuer:i.trim(),client_id:o.trim(),client_secret:c,domains:u.split(/[\s,]+/).filter(e=>e!==``),role:f===zq?null:f,required:m}))}catch(e){y(Uq(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:zq,children:`nobody: invite first`}),AU.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 Hq({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 Uq(e){return e instanceof na?e.message:String(e)}var Wq=[{tab:`people`,name:`People`},{tab:`roles`,name:`Roles`},{tab:`sso`,name:`Single sign-on`}];function Gq(){let e=j(),t=Gh(wh()),[n,r]=Xi(),i=Wq.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 NU(e)),m=e=>r(e===`people`?{}:{tab:e});(0,D.useEffect)(()=>{let t=!1;return NU(e).then(e=>{t||o(e)},e=>{t||f(Jq(e))}),()=>{t=!0}},[e]);let h=async(t,n)=>{f(null);try{await LU(e,t,n),await p()}catch(e){f(Jq(e))}},g=async t=>{f(null);try{return u({link:await PU(e,t),kind:`invitation`}),await p(),!0}catch(e){return f(Jq(e)),!1}},_=async t=>{f(null);try{await IU(e,t),await p()}catch(e){f(Jq(e))}},v=async t=>{f(null);try{u({link:await FU(e,t),kind:`reset`})}catch(e){f(Jq(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:Wq,on:i,onPick:m}),i===`people`&&(0,A.jsxs)(A.Fragment,{children:[l!==null&&(0,A.jsx)(Kq,{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)(qq,{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)(Pq,{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)(Bq,{})]})}function Kq({invited:e,kind:t,onClose:n}){let r=Yq(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 qq({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:AU.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 Jq(e){return e instanceof na?e.message:String(e)}function Yq(e){return`${window.location.origin}/invitations/${encodeURIComponent(e)}`}var Xq=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()}),Zq=z({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F(),calls:F()}),Qq=z({rows:R(Xq),totals:Zq.nullable(),next:F().nullable()});async function $q(e,t=0){return Qq.parse(await k(e,`/v1/usage`,{after:t}))}function eJ(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 tJ(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 nJ(e){return tJ(e,e=>tg(e.at)).sort((e,t)=>t.name.localeCompare(e.name))}function rJ(e){return tJ(e,e=>e.agent).sort((e,t)=>t.cost_eur-e.cost_eur)}function iJ(e){return tJ(e,()=>``)[0]??{calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0}}var aJ=[{tab:`days`,name:`By day`},{tab:`agents`,name:`By agent`},{tab:`calls`,name:`Call by call`}],oJ=`minmax(0,1.2fr) 70px 80px 90px minmax(0,1fr) 90px`,sJ=`130px 140px minmax(0,1fr) 70px 80px 90px`,cJ=40;function lJ(){let e=j(),t=ug(),[n,r]=Xi(),i=aJ.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<cJ;i+=1){let i=await $q(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=eJ(a??[]),u=iJ(l),d=nJ(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:aJ,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)(uJ,{label:i===`days`?`Day`:`Agent`,groups:i===`days`?d:rJ(l)}),l.length>0&&i===`calls`&&(0,A.jsxs)(V,{children:[(0,A.jsx)(dh,{columns:sJ,labels:[`Started`,`Agent`,`Call`,`Min>`,`Messages>`,`Cost>`]}),l.map(e=>(0,A.jsxs)(fh,{columns:sJ,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 uJ({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:oJ,labels:[e,`Calls>`,`Min>`,`Per call>`,``,`Cost>`]}),t.map(e=>(0,A.jsxs)(fh,{columns:oJ,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 dJ=z({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()});async function fJ(e,t){try{return dJ.parse(await k(e,`/v1/agents/${encodeURIComponent(t)}/widget`))}catch(e){if(e instanceof na&&e.status===404)return null;throw e}}async function pJ(e,t,n){return dJ.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/widget`,n))}function mJ(){return`${pm()}/widget/pinecall-widget.js`}var hJ=null;function gJ(){return hJ??=yi(()=>import(mJ()).then(()=>void 0,e=>{throw hJ=null,Error(`the widget did not load from ${mJ()}: ${e instanceof Error?e.message:String(e)}`)}),[]),hJ}function _J(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 vJ=[`#5b3df5`,`#101014`,`#0f766e`,`#be185d`];function yJ(){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)(vJ[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 fJ(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 yb(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??vJ[0])!==m||b.autostart!==f),ae=async()=>{C(!0),_(null);try{x(await pJ(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 gJ().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),_J(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===vJ[0]?``:`\n<style>pinecall-widget { --pc-accent: ${m}; }</style>`,O=`<script type="module" src="${mJ()}"><\/script>\n<pinecall-widget ${oe.join(`
|
|
119
|
+
`)}></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:(vJ.includes(m)?vJ:[...vJ,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 bJ(){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 gJ().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=_J(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 xJ({agent:e}){let{agents:t,live:n}=tb(),r=Eh(),i=t.find(t=>t.slug===e),a=n.filter(t=>t.agent===e).length,o=xm(bm).filter(e=>r===null||rb(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 SJ=/^call_[\w+-]{6,}$/,CJ=40;function wJ({agent:e,onClose:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(0),{agents:o,lines:s,operator:c}=tb(),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||rb(l,e),r=n.trim().toLowerCase(),i=[];if(SJ.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,CJ):i.filter(e=>`${e.label} ${e.sub}`.toLowerCase().includes(r)).slice(0,CJ)},[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 TJ=3,EJ=5e3;function DJ(){let{live:e,lines:t}=tb(),n=vr(),r=gr().pathname,i=(0,D.useRef)(null),[a,o]=(0,D.useState)([]),s=AJ(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)&&!JB(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,TJ)})},[e,t]),(0,D.useEffect)(()=>{if(!a.some(e=>e.ended))return;let e=window.setTimeout(()=>o(e=>e.filter(e=>!e.ended)),EJ);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)(kJ,{})}),(0,A.jsxs)(`span`,{className:`ring-words`,children:[(0,A.jsxs)(`span`,{className:`ring-top`,children:[(0,A.jsx)(`span`,{className:`ring-kicker`,children:OJ(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 OJ(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 kJ(){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 AJ(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 jJ=[{group:`gateway`,label:fm===`local`?`Sandbox`:`Gateway`},{group:`settings`,label:`Settings`},{group:`box`,label:`Box`}];function MJ({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}=tb(),f=e=>i===null||rb(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)(PJ,{}),(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)}),jJ.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:NJ(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 NJ(e){return e===``?``:e.charAt(0).toUpperCase()+e.slice(1)}function PJ(){let e=wh(),{agents:t,orgs:n}=tb(),{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 FJ=new Set([`talk`,`chat`,`dev-chat`,`calls`,`sessions`,`pipeline`,`knowledge`,`memory`,`evals`,`widget`]),IJ=`http://localhost:4100`;function LJ({agent:e}){let t=wh(),n=Gh(t),{world:r,corner:i,lookInto:a}=kh(),{held:o,agentsLoaded:s}=tb(),[c,l]=(0,D.useState)(!1),u=vr(),{pathname:d}=gr(),f=(0,D.useRef)(null),p=d.split(`/`).filter(Boolean),m=e!==``&&FJ.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`?IJ: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}=tb(),{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 zJ(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 BJ({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:zJ(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 VJ=`No agent called {agent} is held here`;function HJ(){return(0,A.jsx)(eb,{children:(0,A.jsx)(UJ,{})})}function UJ(){let e=Sr().agent??``,{agents:t,agentsLoaded:n}=tb(),[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)(MJ,{agent:a?``:e,onSearch:()=>i(!0)}),(0,A.jsxs)(`div`,{className:`frame-main`,children:[(0,A.jsx)(BJ,{agent:e}),e!==``&&!a&&(0,A.jsx)(xJ,{agent:e}),(0,A.jsx)(`div`,{className:`frame-screen`,children:a?(0,A.jsx)(WJ,{agent:e}):(0,A.jsx)(Zr,{})})]}),(0,A.jsx)(DJ,{}),r&&(0,A.jsx)(wJ,{agent:a?``:e,onClose:()=>i(!1)})]})}function WJ({agent:e}){return(0,A.jsxs)(`p`,{className:`missing`,children:[VJ.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 GJ={home:(0,A.jsx)(XU,{}),agents:(0,A.jsx)(Bb,{}),live:(0,A.jsx)(bU,{}),sessions:(0,A.jsx)(kU,{}),simulations:(0,A.jsx)(WK,{}),"org-evals":(0,A.jsx)(aT,{}),"org-memory":(0,A.jsx)(xT,{}),"org-docs":(0,A.jsx)(PT,{}),numbers:(0,A.jsx)(eG,{}),phone:(0,A.jsx)(nG,{}),tokens:(0,A.jsx)(tW,{}),providers:(0,A.jsx)(fW,{}),team:(0,A.jsx)(Gq,{}),usage:(0,A.jsx)(lJ,{}),lexicon:(0,A.jsx)(cW,{})},KJ={"box-orgs":(0,A.jsx)(HS,{children:(0,A.jsx)(oS,{})}),"box-fleet":(0,A.jsx)(HS,{children:(0,A.jsx)(ux,{})}),"box-routes":(0,A.jsx)(HS,{children:(0,A.jsx)(uS,{})}),"box-usage":(0,A.jsx)(HS,{children:(0,A.jsx)(zS,{})}),"box-settings":(0,A.jsx)(HS,{children:(0,A.jsx)(PS,{})})},qJ={talk:(0,A.jsx)($B,{}),chat:(0,A.jsx)(aV,{}),devchat:(0,A.jsx)(Aw,{}),calls:(0,A.jsx)(hC,{}),sessions:(0,A.jsx)(TG,{}),settings:(0,A.jsx)(yq,{}),pipeline:(0,A.jsx)(wG,{}),docs:(0,A.jsx)(FW,{}),memory:(0,A.jsx)(BW,{}),evals:(0,A.jsx)(oH,{}),widget:(0,A.jsx)(yJ,{})},JJ={devchat:(0,A.jsx)(Aw,{}),calls:(0,A.jsx)(hC,{}),sessions:(0,A.jsx)(wK,{})},YJ={live:(0,A.jsx)(bU,{}),sessions:(0,A.jsx)(wK,{}),simulations:(0,A.jsx)(WK,{})};function XJ(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===qJ?JJ:YJ)[e.key];return r===void 0?[{path:e.path,element:n}]:[{path:e.path,element:n},{path:`${e.path}/:call`,element:r}]})}var ZJ=Vi([{path:`/`,element:(0,A.jsx)(HJ,{}),children:[...XJ(vm,GJ),...XJ(ym,KJ),...fm===`hosted`?[{path:`box/orgs/:org`,element:(0,A.jsx)(HS,{children:(0,A.jsx)(iS,{})})}]:[],...fm===`hosted`?[{path:`cli`,element:(0,A.jsx)(kq,{})}]:[],{path:`docs/:base`,element:(0,A.jsx)(jT,{})}]},{path:`/a/:agent`,element:(0,A.jsx)(HJ,{}),children:[{index:!0,element:(0,A.jsx)(Xr,{to:`talk`,replace:!0})},...XJ(bm,qJ)]},{path:`/a/:agent/widget/preview`,element:(0,A.jsx)(bJ,{})},{path:`*`,element:(0,A.jsx)(Xr,{to:`/`,replace:!0})}],{basename:`/`}),QJ=np({version:P(),cloud:L(),signup:L(),min_password:F(),mail:L().optional(),google:L().optional()});async function $J(e){try{let t=await fetch(new URL(`${e.replace(/\/$/,``)}/.well-known/pinecall`,window.location.origin));return QJ.parse(await fa(t))}catch{return{version:``,cloud:!1,signup:!1,min_password:0}}}function eY({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)}),$J(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)(tY,{}),`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 tY(){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 nY({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 $J(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 rY=document.getElementById(`root`);if(rY===null)throw Error(`index.html has no #root for the console to mount in`);var iY=`login`,aY=/^\/invitations\/([^/]+)\/?$/;function oY(){let e=aY.exec(window.location.pathname);return e===null?null:decodeURIComponent(e[1]??``)}var sY=mm[fm],cY=``;async function lY(){if(fm===`local`)return cY;let e=new URL(window.location.href),t=e.searchParams.get(iY);if(t!==null){e.searchParams.delete(iY),window.history.replaceState(null,``,e.toString());try{let e=await Hp(`/`,t);return Tm(e.key),e.key}catch{}}return wm()}function uY({startingWith:e}){let[t,n]=(0,D.useState)(e),[r,i]=(0,D.useState)(()=>sY===`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:sY,moveTo:o,corner:r,lookInto:a}),[o,r,a]),c=(0,D.useMemo)(()=>({base:`/`,key:t??``,corner:r,...fm===`hosted`?{world:sY}:{}}),[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=oY();return e===null?(0,A.jsx)(eY,{base:`/`,onSigned:u}):(0,A.jsx)(nY,{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:ZJ})})})})})}lY().then(e=>{(0,hi.createRoot)(rY).render((0,A.jsx)(D.StrictMode,{children:(0,A.jsx)(uY,{startingWith:e})}))});
|