@voidly/agent-sdk 3.4.4 → 3.4.6

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/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import {createRequire}from'module';const require$1 = createRequire(import.meta.url);
2
- var hn=Object.create;var gr=Object.defineProperty;var yn=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var Yt=(a=>typeof require$1<"u"?require$1:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require$1<"u"?require$1:e)[t]}):a)(function(a){if(typeof require$1<"u")return require$1.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var mr=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var mn=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of un(e))!gn.call(a,i)&&i!==t&&gr(a,i,{get:()=>e[i],enumerable:!(n=yn(e,i))||n.enumerable});return a};var br=(a,e,t)=>(t=a!=null?hn(pn(a)):{},mn(!a||!a.__esModule?gr(t,"default",{value:a,enumerable:true}):t,a));var xr=mr((es,Kt)=>{(function(a){var e=function(s){var c,o=new Float64Array(16);if(s)for(c=0;c<s.length;c++)o[c]=s[c];return o},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var f=e(),d=e([1]),y=e([56129,1]),_=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),K=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),m=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),O=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),J=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function M(s,c,o,r){s[c]=o>>24&255,s[c+1]=o>>16&255,s[c+2]=o>>8&255,s[c+3]=o&255,s[c+4]=r>>24&255,s[c+5]=r>>16&255,s[c+6]=r>>8&255,s[c+7]=r&255;}function V(s,c,o,r,l){var u,p=0;for(u=0;u<l;u++)p|=s[c+u]^o[r+u];return (1&p-1>>>8)-1}function H(s,c,o,r){return V(s,c,o,r,16)}function be(s,c,o,r){return V(s,c,o,r,32)}function qe(s,c,o,r){for(var l=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,u=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,p=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,v=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,T=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,L=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,R=c[0]&255|(c[1]&255)<<8|(c[2]&255)<<16|(c[3]&255)<<24,fe=c[4]&255|(c[5]&255)<<8|(c[6]&255)<<16|(c[7]&255)<<24,$=c[8]&255|(c[9]&255)<<8|(c[10]&255)<<16|(c[11]&255)<<24,Y=c[12]&255|(c[13]&255)<<8|(c[14]&255)<<16|(c[15]&255)<<24,Q=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,te=o[16]&255|(o[17]&255)<<8|(o[18]&255)<<16|(o[19]&255)<<24,ee=o[20]&255|(o[21]&255)<<8|(o[22]&255)<<16|(o[23]&255)<<24,G=o[24]&255|(o[25]&255)<<8|(o[26]&255)<<16|(o[27]&255)<<24,W=o[28]&255|(o[29]&255)<<8|(o[30]&255)<<16|(o[31]&255)<<24,Z=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,I=l,N=u,C=p,F=v,B=T,E=L,b=R,x=fe,k=$,w=Y,S=Q,A=te,q=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+q|0,B^=h<<7|h>>>25,h=B+I|0,k^=h<<9|h>>>23,h=k+B|0,q^=h<<13|h>>>19,h=q+k|0,I^=h<<18|h>>>14,h=E+N|0,w^=h<<7|h>>>25,h=w+E|0,re^=h<<9|h>>>23,h=re+w|0,N^=h<<13|h>>>19,h=N+re|0,E^=h<<18|h>>>14,h=S+b|0,se^=h<<7|h>>>25,h=se+S|0,C^=h<<9|h>>>23,h=C+se|0,b^=h<<13|h>>>19,h=b+C|0,S^=h<<18|h>>>14,h=ne+A|0,F^=h<<7|h>>>25,h=F+ne|0,x^=h<<9|h>>>23,h=x+F|0,A^=h<<13|h>>>19,h=A+x|0,ne^=h<<18|h>>>14,h=I+F|0,N^=h<<7|h>>>25,h=N+I|0,C^=h<<9|h>>>23,h=C+N|0,F^=h<<13|h>>>19,h=F+C|0,I^=h<<18|h>>>14,h=E+B|0,b^=h<<7|h>>>25,h=b+E|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,E^=h<<18|h>>>14,h=S+w|0,A^=h<<7|h>>>25,h=A+S|0,k^=h<<9|h>>>23,h=k+A|0,w^=h<<13|h>>>19,h=w+k|0,S^=h<<18|h>>>14,h=ne+se|0,q^=h<<7|h>>>25,h=q+ne|0,re^=h<<9|h>>>23,h=re+q|0,se^=h<<13|h>>>19,h=se+re|0,ne^=h<<18|h>>>14;I=I+l|0,N=N+u|0,C=C+p|0,F=F+v|0,B=B+T|0,E=E+L|0,b=b+R|0,x=x+fe|0,k=k+$|0,w=w+Y|0,S=S+Q|0,A=A+te|0,q=q+ee|0,re=re+G|0,se=se+W|0,ne=ne+Z|0,s[0]=I>>>0&255,s[1]=I>>>8&255,s[2]=I>>>16&255,s[3]=I>>>24&255,s[4]=N>>>0&255,s[5]=N>>>8&255,s[6]=N>>>16&255,s[7]=N>>>24&255,s[8]=C>>>0&255,s[9]=C>>>8&255,s[10]=C>>>16&255,s[11]=C>>>24&255,s[12]=F>>>0&255,s[13]=F>>>8&255,s[14]=F>>>16&255,s[15]=F>>>24&255,s[16]=B>>>0&255,s[17]=B>>>8&255,s[18]=B>>>16&255,s[19]=B>>>24&255,s[20]=E>>>0&255,s[21]=E>>>8&255,s[22]=E>>>16&255,s[23]=E>>>24&255,s[24]=b>>>0&255,s[25]=b>>>8&255,s[26]=b>>>16&255,s[27]=b>>>24&255,s[28]=x>>>0&255,s[29]=x>>>8&255,s[30]=x>>>16&255,s[31]=x>>>24&255,s[32]=k>>>0&255,s[33]=k>>>8&255,s[34]=k>>>16&255,s[35]=k>>>24&255,s[36]=w>>>0&255,s[37]=w>>>8&255,s[38]=w>>>16&255,s[39]=w>>>24&255,s[40]=S>>>0&255,s[41]=S>>>8&255,s[42]=S>>>16&255,s[43]=S>>>24&255,s[44]=A>>>0&255,s[45]=A>>>8&255,s[46]=A>>>16&255,s[47]=A>>>24&255,s[48]=q>>>0&255,s[49]=q>>>8&255,s[50]=q>>>16&255,s[51]=q>>>24&255,s[52]=re>>>0&255,s[53]=re>>>8&255,s[54]=re>>>16&255,s[55]=re>>>24&255,s[56]=se>>>0&255,s[57]=se>>>8&255,s[58]=se>>>16&255,s[59]=se>>>24&255,s[60]=ne>>>0&255,s[61]=ne>>>8&255,s[62]=ne>>>16&255,s[63]=ne>>>24&255;}function Ee(s,c,o,r){for(var l=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,u=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,p=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,v=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,T=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,L=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,R=c[0]&255|(c[1]&255)<<8|(c[2]&255)<<16|(c[3]&255)<<24,fe=c[4]&255|(c[5]&255)<<8|(c[6]&255)<<16|(c[7]&255)<<24,$=c[8]&255|(c[9]&255)<<8|(c[10]&255)<<16|(c[11]&255)<<24,Y=c[12]&255|(c[13]&255)<<8|(c[14]&255)<<16|(c[15]&255)<<24,Q=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,te=o[16]&255|(o[17]&255)<<8|(o[18]&255)<<16|(o[19]&255)<<24,ee=o[20]&255|(o[21]&255)<<8|(o[22]&255)<<16|(o[23]&255)<<24,G=o[24]&255|(o[25]&255)<<8|(o[26]&255)<<16|(o[27]&255)<<24,W=o[28]&255|(o[29]&255)<<8|(o[30]&255)<<16|(o[31]&255)<<24,Z=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,I=l,N=u,C=p,F=v,B=T,E=L,b=R,x=fe,k=$,w=Y,S=Q,A=te,q=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+q|0,B^=h<<7|h>>>25,h=B+I|0,k^=h<<9|h>>>23,h=k+B|0,q^=h<<13|h>>>19,h=q+k|0,I^=h<<18|h>>>14,h=E+N|0,w^=h<<7|h>>>25,h=w+E|0,re^=h<<9|h>>>23,h=re+w|0,N^=h<<13|h>>>19,h=N+re|0,E^=h<<18|h>>>14,h=S+b|0,se^=h<<7|h>>>25,h=se+S|0,C^=h<<9|h>>>23,h=C+se|0,b^=h<<13|h>>>19,h=b+C|0,S^=h<<18|h>>>14,h=ne+A|0,F^=h<<7|h>>>25,h=F+ne|0,x^=h<<9|h>>>23,h=x+F|0,A^=h<<13|h>>>19,h=A+x|0,ne^=h<<18|h>>>14,h=I+F|0,N^=h<<7|h>>>25,h=N+I|0,C^=h<<9|h>>>23,h=C+N|0,F^=h<<13|h>>>19,h=F+C|0,I^=h<<18|h>>>14,h=E+B|0,b^=h<<7|h>>>25,h=b+E|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,E^=h<<18|h>>>14,h=S+w|0,A^=h<<7|h>>>25,h=A+S|0,k^=h<<9|h>>>23,h=k+A|0,w^=h<<13|h>>>19,h=w+k|0,S^=h<<18|h>>>14,h=ne+se|0,q^=h<<7|h>>>25,h=q+ne|0,re^=h<<9|h>>>23,h=re+q|0,se^=h<<13|h>>>19,h=se+re|0,ne^=h<<18|h>>>14;s[0]=I>>>0&255,s[1]=I>>>8&255,s[2]=I>>>16&255,s[3]=I>>>24&255,s[4]=E>>>0&255,s[5]=E>>>8&255,s[6]=E>>>16&255,s[7]=E>>>24&255,s[8]=S>>>0&255,s[9]=S>>>8&255,s[10]=S>>>16&255,s[11]=S>>>24&255,s[12]=ne>>>0&255,s[13]=ne>>>8&255,s[14]=ne>>>16&255,s[15]=ne>>>24&255,s[16]=b>>>0&255,s[17]=b>>>8&255,s[18]=b>>>16&255,s[19]=b>>>24&255,s[20]=x>>>0&255,s[21]=x>>>8&255,s[22]=x>>>16&255,s[23]=x>>>24&255,s[24]=k>>>0&255,s[25]=k>>>8&255,s[26]=k>>>16&255,s[27]=k>>>24&255,s[28]=w>>>0&255,s[29]=w>>>8&255,s[30]=w>>>16&255,s[31]=w>>>24&255;}function $e(s,c,o,r){qe(s,c,o,r);}function Le(s,c,o,r){Ee(s,c,o,r);}var Ie=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function Je(s,c,o,r,l,u,p){var v=new Uint8Array(16),T=new Uint8Array(64),L,R;for(R=0;R<16;R++)v[R]=0;for(R=0;R<8;R++)v[R]=u[R];for(;l>=64;){for($e(T,v,p,Ie),R=0;R<64;R++)s[c+R]=o[r+R]^T[R];for(L=1,R=8;R<16;R++)L=L+(v[R]&255)|0,v[R]=L&255,L>>>=8;l-=64,c+=64,r+=64;}if(l>0)for($e(T,v,p,Ie),R=0;R<l;R++)s[c+R]=o[r+R]^T[R];return 0}function De(s,c,o,r,l){var u=new Uint8Array(16),p=new Uint8Array(64),v,T;for(T=0;T<16;T++)u[T]=0;for(T=0;T<8;T++)u[T]=r[T];for(;o>=64;){for($e(p,u,l,Ie),T=0;T<64;T++)s[c+T]=p[T];for(v=1,T=8;T<16;T++)v=v+(u[T]&255)|0,u[T]=v&255,v>>>=8;o-=64,c+=64;}if(o>0)for($e(p,u,l,Ie),T=0;T<o;T++)s[c+T]=p[T];return 0}function Ve(s,c,o,r,l){var u=new Uint8Array(32);Le(u,r,l,Ie);for(var p=new Uint8Array(8),v=0;v<8;v++)p[v]=r[v+16];return De(s,c,o,p,u)}function he(s,c,o,r,l,u,p){var v=new Uint8Array(32);Le(v,u,p,Ie);for(var T=new Uint8Array(8),L=0;L<8;L++)T[L]=u[L+16];return Je(s,c,o,r,l,T,v)}var j=function(s){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var c,o,r,l,u,p,v,T;c=s[0]&255|(s[1]&255)<<8,this.r[0]=c&8191,o=s[2]&255|(s[3]&255)<<8,this.r[1]=(c>>>13|o<<3)&8191,r=s[4]&255|(s[5]&255)<<8,this.r[2]=(o>>>10|r<<6)&7939,l=s[6]&255|(s[7]&255)<<8,this.r[3]=(r>>>7|l<<9)&8191,u=s[8]&255|(s[9]&255)<<8,this.r[4]=(l>>>4|u<<12)&255,this.r[5]=u>>>1&8190,p=s[10]&255|(s[11]&255)<<8,this.r[6]=(u>>>14|p<<2)&8191,v=s[12]&255|(s[13]&255)<<8,this.r[7]=(p>>>11|v<<5)&8065,T=s[14]&255|(s[15]&255)<<8,this.r[8]=(v>>>8|T<<8)&8191,this.r[9]=T>>>5&127,this.pad[0]=s[16]&255|(s[17]&255)<<8,this.pad[1]=s[18]&255|(s[19]&255)<<8,this.pad[2]=s[20]&255|(s[21]&255)<<8,this.pad[3]=s[22]&255|(s[23]&255)<<8,this.pad[4]=s[24]&255|(s[25]&255)<<8,this.pad[5]=s[26]&255|(s[27]&255)<<8,this.pad[6]=s[28]&255|(s[29]&255)<<8,this.pad[7]=s[30]&255|(s[31]&255)<<8;};j.prototype.blocks=function(s,c,o){for(var r=this.fin?0:2048,l,u,p,v,T,L,R,fe,$,Y,Q,te,ee,G,W,Z,I,N,C,F=this.h[0],B=this.h[1],E=this.h[2],b=this.h[3],x=this.h[4],k=this.h[5],w=this.h[6],S=this.h[7],A=this.h[8],q=this.h[9],re=this.r[0],se=this.r[1],ne=this.r[2],h=this.r[3],ae=this.r[4],le=this.r[5],de=this.r[6],ie=this.r[7],oe=this.r[8],ce=this.r[9];o>=16;)l=s[c+0]&255|(s[c+1]&255)<<8,F+=l&8191,u=s[c+2]&255|(s[c+3]&255)<<8,B+=(l>>>13|u<<3)&8191,p=s[c+4]&255|(s[c+5]&255)<<8,E+=(u>>>10|p<<6)&8191,v=s[c+6]&255|(s[c+7]&255)<<8,b+=(p>>>7|v<<9)&8191,T=s[c+8]&255|(s[c+9]&255)<<8,x+=(v>>>4|T<<12)&8191,k+=T>>>1&8191,L=s[c+10]&255|(s[c+11]&255)<<8,w+=(T>>>14|L<<2)&8191,R=s[c+12]&255|(s[c+13]&255)<<8,S+=(L>>>11|R<<5)&8191,fe=s[c+14]&255|(s[c+15]&255)<<8,A+=(R>>>8|fe<<8)&8191,q+=fe>>>5|r,$=0,Y=$,Y+=F*re,Y+=B*(5*ce),Y+=E*(5*oe),Y+=b*(5*ie),Y+=x*(5*de),$=Y>>>13,Y&=8191,Y+=k*(5*le),Y+=w*(5*ae),Y+=S*(5*h),Y+=A*(5*ne),Y+=q*(5*se),$+=Y>>>13,Y&=8191,Q=$,Q+=F*se,Q+=B*re,Q+=E*(5*ce),Q+=b*(5*oe),Q+=x*(5*ie),$=Q>>>13,Q&=8191,Q+=k*(5*de),Q+=w*(5*le),Q+=S*(5*ae),Q+=A*(5*h),Q+=q*(5*ne),$+=Q>>>13,Q&=8191,te=$,te+=F*ne,te+=B*se,te+=E*re,te+=b*(5*ce),te+=x*(5*oe),$=te>>>13,te&=8191,te+=k*(5*ie),te+=w*(5*de),te+=S*(5*le),te+=A*(5*ae),te+=q*(5*h),$+=te>>>13,te&=8191,ee=$,ee+=F*h,ee+=B*ne,ee+=E*se,ee+=b*re,ee+=x*(5*ce),$=ee>>>13,ee&=8191,ee+=k*(5*oe),ee+=w*(5*ie),ee+=S*(5*de),ee+=A*(5*le),ee+=q*(5*ae),$+=ee>>>13,ee&=8191,G=$,G+=F*ae,G+=B*h,G+=E*ne,G+=b*se,G+=x*re,$=G>>>13,G&=8191,G+=k*(5*ce),G+=w*(5*oe),G+=S*(5*ie),G+=A*(5*de),G+=q*(5*le),$+=G>>>13,G&=8191,W=$,W+=F*le,W+=B*ae,W+=E*h,W+=b*ne,W+=x*se,$=W>>>13,W&=8191,W+=k*re,W+=w*(5*ce),W+=S*(5*oe),W+=A*(5*ie),W+=q*(5*de),$+=W>>>13,W&=8191,Z=$,Z+=F*de,Z+=B*le,Z+=E*ae,Z+=b*h,Z+=x*ne,$=Z>>>13,Z&=8191,Z+=k*se,Z+=w*re,Z+=S*(5*ce),Z+=A*(5*oe),Z+=q*(5*ie),$+=Z>>>13,Z&=8191,I=$,I+=F*ie,I+=B*de,I+=E*le,I+=b*ae,I+=x*h,$=I>>>13,I&=8191,I+=k*ne,I+=w*se,I+=S*re,I+=A*(5*ce),I+=q*(5*oe),$+=I>>>13,I&=8191,N=$,N+=F*oe,N+=B*ie,N+=E*de,N+=b*le,N+=x*ae,$=N>>>13,N&=8191,N+=k*h,N+=w*ne,N+=S*se,N+=A*re,N+=q*(5*ce),$+=N>>>13,N&=8191,C=$,C+=F*ce,C+=B*oe,C+=E*ie,C+=b*de,C+=x*le,$=C>>>13,C&=8191,C+=k*ae,C+=w*h,C+=S*ne,C+=A*se,C+=q*re,$+=C>>>13,C&=8191,$=($<<2)+$|0,$=$+Y|0,Y=$&8191,$=$>>>13,Q+=$,F=Y,B=Q,E=te,b=ee,x=G,k=W,w=Z,S=I,A=N,q=C,c+=16,o-=16;this.h[0]=F,this.h[1]=B,this.h[2]=E,this.h[3]=b,this.h[4]=x,this.h[5]=k,this.h[6]=w,this.h[7]=S,this.h[8]=A,this.h[9]=q;},j.prototype.finish=function(s,c){var o=new Uint16Array(10),r,l,u,p;if(this.leftover){for(p=this.leftover,this.buffer[p++]=1;p<16;p++)this.buffer[p]=0;this.fin=1,this.blocks(this.buffer,0,16);}for(r=this.h[1]>>>13,this.h[1]&=8191,p=2;p<10;p++)this.h[p]+=r,r=this.h[p]>>>13,this.h[p]&=8191;for(this.h[0]+=r*5,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,o[0]=this.h[0]+5,r=o[0]>>>13,o[0]&=8191,p=1;p<10;p++)o[p]=this.h[p]+r,r=o[p]>>>13,o[p]&=8191;for(o[9]-=8192,l=(r^1)-1,p=0;p<10;p++)o[p]&=l;for(l=~l,p=0;p<10;p++)this.h[p]=this.h[p]&l|o[p];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,u=this.h[0]+this.pad[0],this.h[0]=u&65535,p=1;p<8;p++)u=(this.h[p]+this.pad[p]|0)+(u>>>16)|0,this.h[p]=u&65535;s[c+0]=this.h[0]>>>0&255,s[c+1]=this.h[0]>>>8&255,s[c+2]=this.h[1]>>>0&255,s[c+3]=this.h[1]>>>8&255,s[c+4]=this.h[2]>>>0&255,s[c+5]=this.h[2]>>>8&255,s[c+6]=this.h[3]>>>0&255,s[c+7]=this.h[3]>>>8&255,s[c+8]=this.h[4]>>>0&255,s[c+9]=this.h[4]>>>8&255,s[c+10]=this.h[5]>>>0&255,s[c+11]=this.h[5]>>>8&255,s[c+12]=this.h[6]>>>0&255,s[c+13]=this.h[6]>>>8&255,s[c+14]=this.h[7]>>>0&255,s[c+15]=this.h[7]>>>8&255;},j.prototype.update=function(s,c,o){var r,l;if(this.leftover){for(l=16-this.leftover,l>o&&(l=o),r=0;r<l;r++)this.buffer[this.leftover+r]=s[c+r];if(o-=l,c+=l,this.leftover+=l,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0;}if(o>=16&&(l=o-o%16,this.blocks(s,c,l),c+=l,o-=l),o){for(r=0;r<o;r++)this.buffer[this.leftover+r]=s[c+r];this.leftover+=o;}};function P(s,c,o,r,l,u){var p=new j(u);return p.update(o,r,l),p.finish(s,c),0}function xe(s,c,o,r,l,u){var p=new Uint8Array(16);return P(p,0,o,r,l,u),H(s,c,p,0)}function ue(s,c,o,r,l){var u;if(o<32)return -1;for(he(s,0,c,0,o,r,l),P(s,16,s,32,o-32,s),u=0;u<16;u++)s[u]=0;return 0}function D(s,c,o,r,l){var u,p=new Uint8Array(32);if(o<32||(Ve(p,0,32,r,l),xe(c,16,c,32,o-32,p)!==0))return -1;for(he(s,0,c,0,o,r,l),u=0;u<32;u++)s[u]=0;return 0}function z(s,c){var o;for(o=0;o<16;o++)s[o]=c[o]|0;}function ve(s){var c,o,r=1;for(c=0;c<16;c++)o=s[c]+r+65535,r=Math.floor(o/65536),s[c]=o-r*65536;s[0]+=r-1+37*(r-1);}function _e(s,c,o){for(var r,l=~(o-1),u=0;u<16;u++)r=l&(s[u]^c[u]),s[u]^=r,c[u]^=r;}function pe(s,c){var o,r,l,u=e(),p=e();for(o=0;o<16;o++)p[o]=c[o];for(ve(p),ve(p),ve(p),r=0;r<2;r++){for(u[0]=p[0]-65517,o=1;o<15;o++)u[o]=p[o]-65535-(u[o-1]>>16&1),u[o-1]&=65535;u[15]=p[15]-32767-(u[14]>>16&1),l=u[15]>>16&1,u[14]&=65535,_e(p,u,1-l);}for(o=0;o<16;o++)s[2*o]=p[o]&255,s[2*o+1]=p[o]>>8;}function Re(s,c){var o=new Uint8Array(32),r=new Uint8Array(32);return pe(o,s),pe(r,c),be(o,0,r,0)}function Ue(s){var c=new Uint8Array(32);return pe(c,s),c[0]&1}function Me(s,c){var o;for(o=0;o<16;o++)s[o]=c[2*o]+(c[2*o+1]<<8);s[15]&=32767;}function we(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]+o[r];}function Ae(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]-o[r];}function X(s,c,o){var r,l,u=0,p=0,v=0,T=0,L=0,R=0,fe=0,$=0,Y=0,Q=0,te=0,ee=0,G=0,W=0,Z=0,I=0,N=0,C=0,F=0,B=0,E=0,b=0,x=0,k=0,w=0,S=0,A=0,q=0,re=0,se=0,ne=0,h=o[0],ae=o[1],le=o[2],de=o[3],ie=o[4],oe=o[5],ce=o[6],Te=o[7],ye=o[8],ke=o[9],Ke=o[10],Pe=o[11],je=o[12],Fe=o[13],Oe=o[14],Be=o[15];r=c[0],u+=r*h,p+=r*ae,v+=r*le,T+=r*de,L+=r*ie,R+=r*oe,fe+=r*ce,$+=r*Te,Y+=r*ye,Q+=r*ke,te+=r*Ke,ee+=r*Pe,G+=r*je,W+=r*Fe,Z+=r*Oe,I+=r*Be,r=c[1],p+=r*h,v+=r*ae,T+=r*le,L+=r*de,R+=r*ie,fe+=r*oe,$+=r*ce,Y+=r*Te,Q+=r*ye,te+=r*ke,ee+=r*Ke,G+=r*Pe,W+=r*je,Z+=r*Fe,I+=r*Oe,N+=r*Be,r=c[2],v+=r*h,T+=r*ae,L+=r*le,R+=r*de,fe+=r*ie,$+=r*oe,Y+=r*ce,Q+=r*Te,te+=r*ye,ee+=r*ke,G+=r*Ke,W+=r*Pe,Z+=r*je,I+=r*Fe,N+=r*Oe,C+=r*Be,r=c[3],T+=r*h,L+=r*ae,R+=r*le,fe+=r*de,$+=r*ie,Y+=r*oe,Q+=r*ce,te+=r*Te,ee+=r*ye,G+=r*ke,W+=r*Ke,Z+=r*Pe,I+=r*je,N+=r*Fe,C+=r*Oe,F+=r*Be,r=c[4],L+=r*h,R+=r*ae,fe+=r*le,$+=r*de,Y+=r*ie,Q+=r*oe,te+=r*ce,ee+=r*Te,G+=r*ye,W+=r*ke,Z+=r*Ke,I+=r*Pe,N+=r*je,C+=r*Fe,F+=r*Oe,B+=r*Be,r=c[5],R+=r*h,fe+=r*ae,$+=r*le,Y+=r*de,Q+=r*ie,te+=r*oe,ee+=r*ce,G+=r*Te,W+=r*ye,Z+=r*ke,I+=r*Ke,N+=r*Pe,C+=r*je,F+=r*Fe,B+=r*Oe,E+=r*Be,r=c[6],fe+=r*h,$+=r*ae,Y+=r*le,Q+=r*de,te+=r*ie,ee+=r*oe,G+=r*ce,W+=r*Te,Z+=r*ye,I+=r*ke,N+=r*Ke,C+=r*Pe,F+=r*je,B+=r*Fe,E+=r*Oe,b+=r*Be,r=c[7],$+=r*h,Y+=r*ae,Q+=r*le,te+=r*de,ee+=r*ie,G+=r*oe,W+=r*ce,Z+=r*Te,I+=r*ye,N+=r*ke,C+=r*Ke,F+=r*Pe,B+=r*je,E+=r*Fe,b+=r*Oe,x+=r*Be,r=c[8],Y+=r*h,Q+=r*ae,te+=r*le,ee+=r*de,G+=r*ie,W+=r*oe,Z+=r*ce,I+=r*Te,N+=r*ye,C+=r*ke,F+=r*Ke,B+=r*Pe,E+=r*je,b+=r*Fe,x+=r*Oe,k+=r*Be,r=c[9],Q+=r*h,te+=r*ae,ee+=r*le,G+=r*de,W+=r*ie,Z+=r*oe,I+=r*ce,N+=r*Te,C+=r*ye,F+=r*ke,B+=r*Ke,E+=r*Pe,b+=r*je,x+=r*Fe,k+=r*Oe,w+=r*Be,r=c[10],te+=r*h,ee+=r*ae,G+=r*le,W+=r*de,Z+=r*ie,I+=r*oe,N+=r*ce,C+=r*Te,F+=r*ye,B+=r*ke,E+=r*Ke,b+=r*Pe,x+=r*je,k+=r*Fe,w+=r*Oe,S+=r*Be,r=c[11],ee+=r*h,G+=r*ae,W+=r*le,Z+=r*de,I+=r*ie,N+=r*oe,C+=r*ce,F+=r*Te,B+=r*ye,E+=r*ke,b+=r*Ke,x+=r*Pe,k+=r*je,w+=r*Fe,S+=r*Oe,A+=r*Be,r=c[12],G+=r*h,W+=r*ae,Z+=r*le,I+=r*de,N+=r*ie,C+=r*oe,F+=r*ce,B+=r*Te,E+=r*ye,b+=r*ke,x+=r*Ke,k+=r*Pe,w+=r*je,S+=r*Fe,A+=r*Oe,q+=r*Be,r=c[13],W+=r*h,Z+=r*ae,I+=r*le,N+=r*de,C+=r*ie,F+=r*oe,B+=r*ce,E+=r*Te,b+=r*ye,x+=r*ke,k+=r*Ke,w+=r*Pe,S+=r*je,A+=r*Fe,q+=r*Oe,re+=r*Be,r=c[14],Z+=r*h,I+=r*ae,N+=r*le,C+=r*de,F+=r*ie,B+=r*oe,E+=r*ce,b+=r*Te,x+=r*ye,k+=r*ke,w+=r*Ke,S+=r*Pe,A+=r*je,q+=r*Fe,re+=r*Oe,se+=r*Be,r=c[15],I+=r*h,N+=r*ae,C+=r*le,F+=r*de,B+=r*ie,E+=r*oe,b+=r*ce,x+=r*Te,k+=r*ye,w+=r*ke,S+=r*Ke,A+=r*Pe,q+=r*je,re+=r*Fe,se+=r*Oe,ne+=r*Be,u+=38*N,p+=38*C,v+=38*F,T+=38*B,L+=38*E,R+=38*b,fe+=38*x,$+=38*k,Y+=38*w,Q+=38*S,te+=38*A,ee+=38*q,G+=38*re,W+=38*se,Z+=38*ne,l=1,r=u+l+65535,l=Math.floor(r/65536),u=r-l*65536,r=p+l+65535,l=Math.floor(r/65536),p=r-l*65536,r=v+l+65535,l=Math.floor(r/65536),v=r-l*65536,r=T+l+65535,l=Math.floor(r/65536),T=r-l*65536,r=L+l+65535,l=Math.floor(r/65536),L=r-l*65536,r=R+l+65535,l=Math.floor(r/65536),R=r-l*65536,r=fe+l+65535,l=Math.floor(r/65536),fe=r-l*65536,r=$+l+65535,l=Math.floor(r/65536),$=r-l*65536,r=Y+l+65535,l=Math.floor(r/65536),Y=r-l*65536,r=Q+l+65535,l=Math.floor(r/65536),Q=r-l*65536,r=te+l+65535,l=Math.floor(r/65536),te=r-l*65536,r=ee+l+65535,l=Math.floor(r/65536),ee=r-l*65536,r=G+l+65535,l=Math.floor(r/65536),G=r-l*65536,r=W+l+65535,l=Math.floor(r/65536),W=r-l*65536,r=Z+l+65535,l=Math.floor(r/65536),Z=r-l*65536,r=I+l+65535,l=Math.floor(r/65536),I=r-l*65536,u+=l-1+37*(l-1),l=1,r=u+l+65535,l=Math.floor(r/65536),u=r-l*65536,r=p+l+65535,l=Math.floor(r/65536),p=r-l*65536,r=v+l+65535,l=Math.floor(r/65536),v=r-l*65536,r=T+l+65535,l=Math.floor(r/65536),T=r-l*65536,r=L+l+65535,l=Math.floor(r/65536),L=r-l*65536,r=R+l+65535,l=Math.floor(r/65536),R=r-l*65536,r=fe+l+65535,l=Math.floor(r/65536),fe=r-l*65536,r=$+l+65535,l=Math.floor(r/65536),$=r-l*65536,r=Y+l+65535,l=Math.floor(r/65536),Y=r-l*65536,r=Q+l+65535,l=Math.floor(r/65536),Q=r-l*65536,r=te+l+65535,l=Math.floor(r/65536),te=r-l*65536,r=ee+l+65535,l=Math.floor(r/65536),ee=r-l*65536,r=G+l+65535,l=Math.floor(r/65536),G=r-l*65536,r=W+l+65535,l=Math.floor(r/65536),W=r-l*65536,r=Z+l+65535,l=Math.floor(r/65536),Z=r-l*65536,r=I+l+65535,l=Math.floor(r/65536),I=r-l*65536,u+=l-1+37*(l-1),s[0]=u,s[1]=p,s[2]=v,s[3]=T,s[4]=L,s[5]=R,s[6]=fe,s[7]=$,s[8]=Y,s[9]=Q,s[10]=te,s[11]=ee,s[12]=G,s[13]=W,s[14]=Z,s[15]=I;}function Se(s,c){X(s,c,c);}function He(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=253;r>=0;r--)Se(o,o),r!==2&&r!==4&&X(o,o,c);for(r=0;r<16;r++)s[r]=o[r];}function Ge(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=250;r>=0;r--)Se(o,o),r!==1&&X(o,o,c);for(r=0;r<16;r++)s[r]=o[r];}function st(s,c,o){var r=new Uint8Array(32),l=new Float64Array(80),u,p,v=e(),T=e(),L=e(),R=e(),fe=e(),$=e();for(p=0;p<31;p++)r[p]=c[p];for(r[31]=c[31]&127|64,r[0]&=248,Me(l,o),p=0;p<16;p++)T[p]=l[p],R[p]=v[p]=L[p]=0;for(v[0]=R[0]=1,p=254;p>=0;--p)u=r[p>>>3]>>>(p&7)&1,_e(v,T,u),_e(L,R,u),we(fe,v,L),Ae(v,v,L),we(L,T,R),Ae(T,T,R),Se(R,fe),Se($,v),X(v,L,v),X(L,T,fe),we(fe,v,L),Ae(v,v,L),Se(T,v),Ae(L,R,$),X(v,L,y),we(v,v,R),X(L,L,v),X(v,R,$),X(R,T,l),Se(T,fe),_e(v,T,u),_e(L,R,u);for(p=0;p<16;p++)l[p+16]=v[p],l[p+32]=L[p],l[p+48]=T[p],l[p+64]=R[p];var Y=l.subarray(32),Q=l.subarray(16);return He(Y,Y),X(Q,Q,Y),pe(s,Q),0}function bt(s,c){return st(s,c,i)}function or(s,c){return t(c,32),bt(s,c)}function xt(s,c,o){var r=new Uint8Array(32);return st(r,o,c),Le(s,n,r,Ie)}var cr=ue,sn=D;function an(s,c,o,r,l,u){var p=new Uint8Array(32);return xt(p,l,u),cr(s,c,o,r,p)}function on(s,c,o,r,l,u){var p=new Uint8Array(32);return xt(p,l,u),sn(s,c,o,r,p)}var fr=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function lr(s,c,o,r){for(var l=new Int32Array(16),u=new Int32Array(16),p,v,T,L,R,fe,$,Y,Q,te,ee,G,W,Z,I,N,C,F,B,E,b,x,k,w,S,A,q=s[0],re=s[1],se=s[2],ne=s[3],h=s[4],ae=s[5],le=s[6],de=s[7],ie=c[0],oe=c[1],ce=c[2],Te=c[3],ye=c[4],ke=c[5],Ke=c[6],Pe=c[7],je=0;r>=128;){for(B=0;B<16;B++)E=8*B+je,l[B]=o[E+0]<<24|o[E+1]<<16|o[E+2]<<8|o[E+3],u[B]=o[E+4]<<24|o[E+5]<<16|o[E+6]<<8|o[E+7];for(B=0;B<80;B++)if(p=q,v=re,T=se,L=ne,R=h,fe=ae,$=le,Y=de,Q=ie,te=oe,ee=ce,G=Te,W=ye,Z=ke,I=Ke,N=Pe,b=de,x=Pe,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=(h>>>14|ye<<18)^(h>>>18|ye<<14)^(ye>>>9|h<<23),x=(ye>>>14|h<<18)^(ye>>>18|h<<14)^(h>>>9|ye<<23),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=h&ae^~h&le,x=ye&ke^~ye&Ke,k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=fr[B*2],x=fr[B*2+1],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=l[B%16],x=u[B%16],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,C=S&65535|A<<16,F=k&65535|w<<16,b=C,x=F,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=(q>>>28|ie<<4)^(ie>>>2|q<<30)^(ie>>>7|q<<25),x=(ie>>>28|q<<4)^(q>>>2|ie<<30)^(q>>>7|ie<<25),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=q&re^q&se^re&se,x=ie&oe^ie&ce^oe&ce,k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,Y=S&65535|A<<16,N=k&65535|w<<16,b=L,x=G,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=C,x=F,k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,L=S&65535|A<<16,G=k&65535|w<<16,re=p,se=v,ne=T,h=L,ae=R,le=fe,de=$,q=Y,oe=Q,ce=te,Te=ee,ye=G,ke=W,Ke=Z,Pe=I,ie=N,B%16===15)for(E=0;E<16;E++)b=l[E],x=u[E],k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=l[(E+9)%16],x=u[(E+9)%16],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,C=l[(E+1)%16],F=u[(E+1)%16],b=(C>>>1|F<<31)^(C>>>8|F<<24)^C>>>7,x=(F>>>1|C<<31)^(F>>>8|C<<24)^(F>>>7|C<<25),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,C=l[(E+14)%16],F=u[(E+14)%16],b=(C>>>19|F<<13)^(F>>>29|C<<3)^C>>>6,x=(F>>>19|C<<13)^(C>>>29|F<<3)^(F>>>6|C<<26),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,l[E]=S&65535|A<<16,u[E]=k&65535|w<<16;b=q,x=ie,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[0],x=c[0],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[0]=q=S&65535|A<<16,c[0]=ie=k&65535|w<<16,b=re,x=oe,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[1],x=c[1],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[1]=re=S&65535|A<<16,c[1]=oe=k&65535|w<<16,b=se,x=ce,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[2],x=c[2],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[2]=se=S&65535|A<<16,c[2]=ce=k&65535|w<<16,b=ne,x=Te,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[3],x=c[3],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[3]=ne=S&65535|A<<16,c[3]=Te=k&65535|w<<16,b=h,x=ye,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[4],x=c[4],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[4]=h=S&65535|A<<16,c[4]=ye=k&65535|w<<16,b=ae,x=ke,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[5],x=c[5],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[5]=ae=S&65535|A<<16,c[5]=ke=k&65535|w<<16,b=le,x=Ke,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[6],x=c[6],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[6]=le=S&65535|A<<16,c[6]=Ke=k&65535|w<<16,b=de,x=Pe,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[7],x=c[7],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[7]=de=S&65535|A<<16,c[7]=Pe=k&65535|w<<16,je+=128,r-=128;}return r}function tt(s,c,o){var r=new Int32Array(8),l=new Int32Array(8),u=new Uint8Array(256),p,v=o;for(r[0]=1779033703,r[1]=3144134277,r[2]=1013904242,r[3]=2773480762,r[4]=1359893119,r[5]=2600822924,r[6]=528734635,r[7]=1541459225,l[0]=4089235720,l[1]=2227873595,l[2]=4271175723,l[3]=1595750129,l[4]=2917565137,l[5]=725511199,l[6]=4215389547,l[7]=327033209,lr(r,l,c,o),o%=128,p=0;p<o;p++)u[p]=c[v-o+p];for(u[o]=128,o=256-128*(o<112?1:0),u[o-9]=0,M(u,o-8,v/536870912|0,v<<3),lr(r,l,u,o),p=0;p<8;p++)M(s,8*p,r[p],l[p]);return 0}function _t(s,c){var o=e(),r=e(),l=e(),u=e(),p=e(),v=e(),T=e(),L=e(),R=e();Ae(o,s[1],s[0]),Ae(R,c[1],c[0]),X(o,o,R),we(r,s[0],s[1]),we(R,c[0],c[1]),X(r,r,R),X(l,s[3],c[3]),X(l,l,K),X(u,s[2],c[2]),we(u,u,u),Ae(p,r,o),Ae(v,u,l),we(T,u,l),we(L,r,o),X(s[0],p,v),X(s[1],L,T),X(s[2],T,v),X(s[3],p,L);}function dr(s,c,o){var r;for(r=0;r<4;r++)_e(s[r],c[r],o);}function Bt(s,c){var o=e(),r=e(),l=e();He(l,c[2]),X(o,c[0],l),X(r,c[1],l),pe(s,r),s[31]^=Ue(o)<<7;}function Lt(s,c,o){var r,l;for(z(s[0],f),z(s[1],d),z(s[2],d),z(s[3],f),l=255;l>=0;--l)r=o[l/8|0]>>(l&7)&1,dr(s,c,r),_t(c,s),_t(s,s),dr(s,c,r);}function wt(s,c){var o=[e(),e(),e(),e()];z(o[0],m),z(o[1],O),z(o[2],d),X(o[3],m,O),Lt(s,o,c);}function Dt(s,c,o){var r=new Uint8Array(64),l=[e(),e(),e(),e()],u;for(o||t(c,32),tt(r,c,32),r[0]&=248,r[31]&=127,r[31]|=64,wt(l,r),Bt(s,l),u=0;u<32;u++)c[u+32]=s[u];return 0}var vt=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Nt(s,c){var o,r,l,u;for(r=63;r>=32;--r){for(o=0,l=r-32,u=r-12;l<u;++l)c[l]+=o-16*c[r]*vt[l-(r-32)],o=Math.floor((c[l]+128)/256),c[l]-=o*256;c[l]+=o,c[r]=0;}for(o=0,l=0;l<32;l++)c[l]+=o-(c[31]>>4)*vt[l],o=c[l]>>8,c[l]&=255;for(l=0;l<32;l++)c[l]-=o*vt[l];for(r=0;r<32;r++)c[r+1]+=c[r]>>8,s[r]=c[r]&255;}function Ht(s){var c=new Float64Array(64),o;for(o=0;o<64;o++)c[o]=s[o];for(o=0;o<64;o++)s[o]=0;Nt(s,c);}function hr(s,c,o,r){var l=new Uint8Array(64),u=new Uint8Array(64),p=new Uint8Array(64),v,T,L=new Float64Array(64),R=[e(),e(),e(),e()];tt(l,r,32),l[0]&=248,l[31]&=127,l[31]|=64;var fe=o+64;for(v=0;v<o;v++)s[64+v]=c[v];for(v=0;v<32;v++)s[32+v]=l[32+v];for(tt(p,s.subarray(32),o+32),Ht(p),wt(R,p),Bt(s,R),v=32;v<64;v++)s[v]=r[v];for(tt(u,s,o+64),Ht(u),v=0;v<64;v++)L[v]=0;for(v=0;v<32;v++)L[v]=p[v];for(v=0;v<32;v++)for(T=0;T<32;T++)L[v+T]+=u[v]*l[T];return Nt(s.subarray(32),L),fe}function cn(s,c){var o=e(),r=e(),l=e(),u=e(),p=e(),v=e(),T=e();return z(s[2],d),Me(s[1],c),Se(l,s[1]),X(u,l,_),Ae(l,l,s[2]),we(u,s[2],u),Se(p,u),Se(v,p),X(T,v,p),X(o,T,l),X(o,o,u),Ge(o,o),X(o,o,l),X(o,o,u),X(o,o,u),X(s[0],o,u),Se(r,s[0]),X(r,r,u),Re(r,l)&&X(s[0],s[0],J),Se(r,s[0]),X(r,r,u),Re(r,l)?-1:(Ue(s[0])===c[31]>>7&&Ae(s[0],f,s[0]),X(s[3],s[0],s[1]),0)}function zt(s,c,o,r){var l,u=new Uint8Array(32),p=new Uint8Array(64),v=[e(),e(),e(),e()],T=[e(),e(),e(),e()];if(o<64||cn(T,r))return -1;for(l=0;l<o;l++)s[l]=c[l];for(l=0;l<32;l++)s[l+32]=r[l];if(tt(p,s,o),Ht(p),Lt(v,T,p),wt(T,c.subarray(32)),_t(v,T),Bt(u,v),o-=64,be(c,0,u,0)){for(l=0;l<o;l++)s[l]=0;return -1}for(l=0;l<o;l++)s[l]=c[l+64];return o}var Xt=32,St=24,dt=32,it=16,ht=32,kt=32,yt=32,ut=32,qt=32,yr=St,fn=dt,ln=it,Ye=64,rt=32,at=64,Jt=32,Vt=64;a.lowlevel={crypto_core_hsalsa20:Le,crypto_stream_xor:he,crypto_stream:Ve,crypto_stream_salsa20_xor:Je,crypto_stream_salsa20:De,crypto_onetimeauth:P,crypto_onetimeauth_verify:xe,crypto_verify_16:H,crypto_verify_32:be,crypto_secretbox:ue,crypto_secretbox_open:D,crypto_scalarmult:st,crypto_scalarmult_base:bt,crypto_box_beforenm:xt,crypto_box_afternm:cr,crypto_box:an,crypto_box_open:on,crypto_box_keypair:or,crypto_hash:tt,crypto_sign:hr,crypto_sign_keypair:Dt,crypto_sign_open:zt,crypto_secretbox_KEYBYTES:Xt,crypto_secretbox_NONCEBYTES:St,crypto_secretbox_ZEROBYTES:dt,crypto_secretbox_BOXZEROBYTES:it,crypto_scalarmult_BYTES:ht,crypto_scalarmult_SCALARBYTES:kt,crypto_box_PUBLICKEYBYTES:yt,crypto_box_SECRETKEYBYTES:ut,crypto_box_BEFORENMBYTES:qt,crypto_box_NONCEBYTES:yr,crypto_box_ZEROBYTES:fn,crypto_box_BOXZEROBYTES:ln,crypto_sign_BYTES:Ye,crypto_sign_PUBLICKEYBYTES:rt,crypto_sign_SECRETKEYBYTES:at,crypto_sign_SEEDBYTES:Jt,crypto_hash_BYTES:Vt,gf:e,D:_,L:vt,pack25519:pe,unpack25519:Me,M:X,A:we,S:Se,Z:Ae,pow2523:Ge,add:_t,set25519:z,modL:Nt,scalarmult:Lt,scalarbase:wt};function ur(s,c){if(s.length!==Xt)throw new Error("bad key size");if(c.length!==St)throw new Error("bad nonce size")}function dn(s,c){if(s.length!==yt)throw new Error("bad public key size");if(c.length!==ut)throw new Error("bad secret key size")}function ze(){for(var s=0;s<arguments.length;s++)if(!(arguments[s]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function pr(s){for(var c=0;c<s.length;c++)s[c]=0;}a.randomBytes=function(s){var c=new Uint8Array(s);return t(c,s),c},a.secretbox=function(s,c,o){ze(s,c,o),ur(o,c);for(var r=new Uint8Array(dt+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+dt]=s[u];return ue(l,r,r.length,c,o),l.subarray(it)},a.secretbox.open=function(s,c,o){ze(s,c,o),ur(o,c);for(var r=new Uint8Array(it+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+it]=s[u];return r.length<32||D(l,r,r.length,c,o)!==0?null:l.subarray(dt)},a.secretbox.keyLength=Xt,a.secretbox.nonceLength=St,a.secretbox.overheadLength=it,a.scalarMult=function(s,c){if(ze(s,c),s.length!==kt)throw new Error("bad n size");if(c.length!==ht)throw new Error("bad p size");var o=new Uint8Array(ht);return st(o,s,c),o},a.scalarMult.base=function(s){if(ze(s),s.length!==kt)throw new Error("bad n size");var c=new Uint8Array(ht);return bt(c,s),c},a.scalarMult.scalarLength=kt,a.scalarMult.groupElementLength=ht,a.box=function(s,c,o,r){var l=a.box.before(o,r);return a.secretbox(s,c,l)},a.box.before=function(s,c){ze(s,c),dn(s,c);var o=new Uint8Array(qt);return xt(o,s,c),o},a.box.after=a.secretbox,a.box.open=function(s,c,o,r){var l=a.box.before(o,r);return a.secretbox.open(s,c,l)},a.box.open.after=a.secretbox.open,a.box.keyPair=function(){var s=new Uint8Array(yt),c=new Uint8Array(ut);return or(s,c),{publicKey:s,secretKey:c}},a.box.keyPair.fromSecretKey=function(s){if(ze(s),s.length!==ut)throw new Error("bad secret key size");var c=new Uint8Array(yt);return bt(c,s),{publicKey:c,secretKey:new Uint8Array(s)}},a.box.publicKeyLength=yt,a.box.secretKeyLength=ut,a.box.sharedKeyLength=qt,a.box.nonceLength=yr,a.box.overheadLength=a.secretbox.overheadLength,a.sign=function(s,c){if(ze(s,c),c.length!==at)throw new Error("bad secret key size");var o=new Uint8Array(Ye+s.length);return hr(o,s,s.length,c),o},a.sign.open=function(s,c){if(ze(s,c),c.length!==rt)throw new Error("bad public key size");var o=new Uint8Array(s.length),r=zt(o,s,s.length,c);if(r<0)return null;for(var l=new Uint8Array(r),u=0;u<l.length;u++)l[u]=o[u];return l},a.sign.detached=function(s,c){for(var o=a.sign(s,c),r=new Uint8Array(Ye),l=0;l<r.length;l++)r[l]=o[l];return r},a.sign.detached.verify=function(s,c,o){if(ze(s,c,o),c.length!==Ye)throw new Error("bad signature size");if(o.length!==rt)throw new Error("bad public key size");var r=new Uint8Array(Ye+s.length),l=new Uint8Array(Ye+s.length),u;for(u=0;u<Ye;u++)r[u]=c[u];for(u=0;u<s.length;u++)r[u+Ye]=s[u];return zt(l,r,r.length,o)>=0},a.sign.keyPair=function(){var s=new Uint8Array(rt),c=new Uint8Array(at);return Dt(s,c),{publicKey:s,secretKey:c}},a.sign.keyPair.fromSecretKey=function(s){if(ze(s),s.length!==at)throw new Error("bad secret key size");for(var c=new Uint8Array(rt),o=0;o<c.length;o++)c[o]=s[32+o];return {publicKey:c,secretKey:new Uint8Array(s)}},a.sign.keyPair.fromSeed=function(s){if(ze(s),s.length!==Jt)throw new Error("bad seed size");for(var c=new Uint8Array(rt),o=new Uint8Array(at),r=0;r<32;r++)o[r]=s[r];return Dt(c,o,true),{publicKey:c,secretKey:o}},a.sign.publicKeyLength=rt,a.sign.secretKeyLength=at,a.sign.seedLength=Jt,a.sign.signatureLength=Ye,a.hash=function(s){ze(s);var c=new Uint8Array(Vt);return tt(c,s,s.length),c},a.hash.hashLength=Vt,a.verify=function(s,c){return ze(s,c),s.length===0||c.length===0||s.length!==c.length?false:V(s,0,c,0,s.length)===0},a.setPRNG=function(s){t=s;},(function(){var s=typeof self<"u"?self.crypto||self.msCrypto:null;if(s&&s.getRandomValues){var c=65536;a.setPRNG(function(o,r){var l,u=new Uint8Array(r);for(l=0;l<r;l+=c)s.getRandomValues(u.subarray(l,l+Math.min(r-l,c)));for(l=0;l<r;l++)o[l]=u[l];pr(u);});}else typeof Yt<"u"&&(s=Yt("crypto"),s&&s.randomBytes&&a.setPRNG(function(o,r){var l,u=s.randomBytes(r);for(l=0;l<r;l++)o[l]=u[l];pr(u);}));})();})(typeof Kt<"u"&&Kt.exports?Kt.exports:self.nacl=self.nacl||{});});var wr=mr((_r,Pt)=>{(function(a,e){typeof Pt<"u"&&Pt.exports?Pt.exports=e():(a.nacl||(a.nacl={}),a.nacl.util=e());})(_r,function(){var a={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return a.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,i=unescape(encodeURIComponent(t)),f=new Uint8Array(i.length);for(n=0;n<i.length;n++)f[n]=i.charCodeAt(n);return f},a.encodeUTF8=function(t){var n,i=[];for(n=0;n<t.length;n++)i.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(i.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(a.encodeBase64=function(t){return Buffer.from(t).toString("base64")},a.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(a.encodeBase64=function(t){return new Buffer(t).toString("base64")},a.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(a.encodeBase64=function(t){var n,i=[],f=t.length;for(n=0;n<f;n++)i.push(String.fromCharCode(t[n]));return btoa(i.join(""))},a.decodeBase64=function(t){e(t);var n,i=atob(t),f=new Uint8Array(i.length);for(n=0;n<i.length;n++)f[n]=i.charCodeAt(n);return f}),a});});var U=br(xr()),g=br(wr());var Ze=class extends Error{constructor(e){let t;e instanceof Error?t=e.message:typeof e=="string"?t=e:t="",super(t),this.name=this.constructor.name;}};var At=[2285,2571,2970,1812,1493,1422,287,202,3158,622,1577,182,962,2127,1855,1468,573,2004,264,383,2500,1458,1727,3199,2648,1017,732,608,1787,411,3124,1758,1223,652,2777,1015,2036,1491,3047,1785,516,3321,3009,2663,1711,2167,126,1469,2476,3239,3058,830,107,1908,3082,2378,2931,961,1821,2604,448,2264,677,2054,2226,430,555,843,2078,871,1550,105,422,587,177,3094,3038,2869,1574,1653,3083,778,1159,3182,2552,1483,2727,1119,1739,644,2457,349,418,329,3173,3254,817,1097,603,610,1322,2044,1864,384,2114,3193,1218,1994,2455,220,2142,1670,2144,1799,2051,794,1819,2475,2459,478,3221,3021,996,991,958,1869,1522,1628],Qt=[1701,1807,1460,2371,2338,2333,308,108,2851,870,854,1510,2535,1278,1530,1185,1659,1187,3109,874,1335,2111,136,1215,2945,1465,1285,2007,2719,2726,2232,2512,75,156,3e3,2911,2980,872,2685,1590,2210,602,1846,777,147,2170,2551,246,1676,1755,460,291,235,3152,2742,2907,3224,1779,2458,1251,2486,2774,2899,1103,1275,2652,1065,2881,725,1508,2368,398,951,247,1421,3222,2499,271,90,853,1860,3203,1162,1618,666,320,8,2813,1544,282,1838,1293,2314,552,2677,2106,1571,205,2918,1542,2721,2597,2312,681,130,1602,1871,829,2946,3065,1325,2756,1861,1474,1202,2367,3147,1752,2707,171,3127,3042,1907,1836,1517,359,758,1441];var Tt=BigInt(4294967295),vr=BigInt(32);function bn(a,e=false){return e?{h:Number(a&Tt),l:Number(a>>vr&Tt)}:{h:Number(a>>vr&Tt)|0,l:Number(a&Tt)|0}}function Sr(a,e=false){let t=a.length,n=new Uint32Array(t),i=new Uint32Array(t);for(let f=0;f<t;f++){let{h:d,l:y}=bn(a[f],e);[n[f],i[f]]=[d,y];}return [n,i]}var kr=(a,e,t)=>a<<t|e>>>32-t,Kr=(a,e,t)=>e<<t|a>>>32-t,Pr=(a,e,t)=>e<<t-32|a>>>64-t,Ar=(a,e,t)=>a<<t-32|e>>>64-t;function xn(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function Gt(a,e=""){if(!Number.isSafeInteger(a)||a<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >0, got ${a}`)}}function Ut(a,e,t=""){let n=xn(a),i=a?.length,f=e!==void 0;if(!n||f){let d=t&&`"${t}" `,y="",_=n?`length=${i}`:`type=${typeof a}`;throw new Error(d+"expected Uint8Array"+y+", got "+_)}return a}function Zt(a,e=true){if(a.destroyed)throw new Error("Hash instance has been destroyed");if(e&&a.finished)throw new Error("Hash#digest() has already been called")}function Tr(a,e){Ut(a,void 0,"digestInto() output");let t=e.outputLen;if(a.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Ur(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function Wt(...a){for(let e=0;e<a.length;e++)a[e].fill(0);}var _n=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function wn(a){return a<<24&4278190080|a<<8&16711680|a>>>8&65280|a>>>24&255}function vn(a){for(let e=0;e<a.length;e++)a[e]=wn(a[e]);return a}var er=_n?a=>a:vn;function tr(a,e={}){let t=(i,f)=>a(f).update(i).digest(),n=a(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=i=>a(i),Object.assign(t,e),Object.freeze(t)}var pt=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])});var Sn=BigInt(0),gt=BigInt(1),kn=BigInt(2),Kn=BigInt(7),Pn=BigInt(256),An=BigInt(113),jr=[],Cr=[],$r=[];for(let a=0,e=gt,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],jr.push(2*(5*n+t)),Cr.push((a+1)*(a+2)/2%64);let i=Sn;for(let f=0;f<7;f++)e=(e<<gt^(e>>Kn)*An)%Pn,e&kn&&(i^=gt<<(gt<<BigInt(f))-gt);$r.push(i);}var Mr=Sr($r,true),Tn=Mr[0],Un=Mr[1],Er=(a,e,t)=>t>32?Pr(a,e,t):kr(a,e,t),Rr=(a,e,t)=>t>32?Ar(a,e,t):Kr(a,e,t);function En(a,e=24){let t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let d=0;d<10;d++)t[d]=a[d]^a[d+10]^a[d+20]^a[d+30]^a[d+40];for(let d=0;d<10;d+=2){let y=(d+8)%10,_=(d+2)%10,K=t[_],m=t[_+1],O=Er(K,m,1)^t[y],J=Rr(K,m,1)^t[y+1];for(let M=0;M<50;M+=10)a[d+M]^=O,a[d+M+1]^=J;}let i=a[2],f=a[3];for(let d=0;d<24;d++){let y=Cr[d],_=Er(i,f,y),K=Rr(i,f,y),m=jr[d];i=a[m],f=a[m+1],a[m]=_,a[m+1]=K;}for(let d=0;d<50;d+=10){for(let y=0;y<10;y++)t[y]=a[d+y];for(let y=0;y<10;y++)a[d+y]^=~t[(y+2)%10]&t[(y+4)%10];}a[0]^=Tn[n],a[1]^=Un[n];}Wt(t);}var Et=class a{constructor(e,t,n,i=false,f=24){if(Object.defineProperty(this,"state",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"pos",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"posOut",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"finished",{enumerable:true,configurable:true,writable:true,value:false}),Object.defineProperty(this,"state32",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"destroyed",{enumerable:true,configurable:true,writable:true,value:false}),Object.defineProperty(this,"blockLen",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"enableXOF",{enumerable:true,configurable:true,writable:true,value:false}),Object.defineProperty(this,"rounds",{enumerable:true,configurable:true,writable:true,value:void 0}),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=f,Gt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ur(this.state);}clone(){return this._cloneInto()}keccak(){er(this.state32),En(this.state32,this.rounds),er(this.state32),this.posOut=0,this.pos=0;}update(e){Zt(this),Ut(e);let{blockLen:t,state:n}=this,i=e.length;for(let f=0;f<i;){let d=Math.min(t-this.pos,i-f);for(let y=0;y<d;y++)n[this.pos++]^=e[f++];this.pos===t&&this.keccak();}return this}finish(){if(this.finished)return;this.finished=true;let{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,(t&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak();}writeInto(e){Zt(this,false),Ut(e),this.finish();let t=this.state,{blockLen:n}=this;for(let i=0,f=e.length;i<f;){this.posOut>=n&&this.keccak();let d=Math.min(n-this.posOut,f-i);e.set(t.subarray(this.posOut,this.posOut+d),i),this.posOut+=d,i+=d;}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Gt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Tr(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true,Wt(this.state);}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:i,rounds:f,enableXOF:d}=this;return e||(e=new a(t,n,i,d,f)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=f,e.suffix=n,e.outputLen=i,e.enableXOF=d,e.destroyed=this.destroyed,e}},Ir=(a,e,t,n={})=>tr(()=>new Et(e,a,t),n),Rt=Ir(6,136,32,pt(8)),jt=Ir(6,72,64,pt(10));var Fr=(a,e,t,n={})=>tr((i={})=>new Et(e,a,i.dkLen===void 0?t:i.dkLen,true),n),Ct=Fr(31,168,16,pt(11)),ot=Fr(31,136,32,pt(12));var Rn={},Or=jn(globalThis,Rn);function jn(a,e){return new Proxy(a,{get(t,n,i){return n in e?e[n]:a[n]},set(t,n,i){return n in e&&delete e[n],a[n]=i,true},deleteProperty(t,n){let i=false;return n in e&&(delete e[n],i=true),n in a&&(delete a[n],i=true),i},ownKeys(t){let n=Reflect.ownKeys(a),i=Reflect.ownKeys(e),f=new Set(i);return [...n.filter(d=>!f.has(d)),...i]},defineProperty(t,n,i){return n in e&&delete e[n],Reflect.defineProperty(a,n,i),true},getOwnPropertyDescriptor(t,n){return n in e?Reflect.getOwnPropertyDescriptor(e,n):Reflect.getOwnPropertyDescriptor(a,n)},has(t,n){return n in e||n in a}})}function Xe(a){return a%256}function Ne(a){return a>=-32768&&a<=32767?a:a<-32768?(a=a+32769,a=a%65536,32767+a):(a=a-32768,a=a%65536,-32768+a)}function ge(a){return a%65536}function $t(a){return a>=-2147483648&&a<=2147483647?a:a<-2147483648?(a=a+2147483649,a=a%4294967296,2147483647+a):(a=a-2147483648,a=a%4294967296,-2147483648+a)}function Qe(a){return a%4294967296}function Br(a,e){if(a.length!=e.length)return 0;let t=new Uint8Array([0]);for(let i=0;i<a.length;i++)t[0]|=a[i]^e[i];let n=new Uint8Array([0]);return n[0]=~(t[0]^n[0]),n[0]&=n[0]>>4,n[0]&=n[0]>>2,n[0]&=n[0]>>1,n[0]}function Lr(a,e){if(a.length!=e.length)return false;for(let t=0;t<a.length;t++)if(a[t]!==e[t])return false;return true}async function Dr(){if(typeof Or<"u"&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:a}=await import('crypto');return a}catch{throw new Error("failed to load Crypto")}}function Mt(a,e,t){return ot.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}function Nr(a){let e=Qe(a[0]);return e|=Qe(a[1])<<8,e|=Qe(a[2])<<16,e|=Qe(a[3])<<24,Qe(e)}var ct=class{constructor(){Object.defineProperty(this,"_api",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"_k",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_du",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_dv",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_eta1",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_eta2",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_skSize",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_pkSize",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_compressedUSize",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_compressedVSize",{enumerable:true,configurable:true,writable:true,value:0});}async generateKeyPair(){await this._setup();try{let e=new Uint8Array(64);return this._api.getRandomValues(e),this._deriveKeyPair(e)}catch(e){throw new Ze(e)}}async deriveKeyPair(e){await this._setup();try{if(e.byteLength!==64)throw new Error("seed must be 64 bytes in length");return this._deriveKeyPair(e)}catch(t){throw new Ze(t)}}async encap(e,t){await this._setup();try{if(e.length!==384*this._k+32)throw new Error("invalid encapsulation key");let n=this._getSeed(t),[i,f]=rr(n,Hr(e));return [this._encap(e,n,f),i]}catch(n){throw new Ze(n)}}async decap(e,t){await this._setup();try{if(e.byteLength!==this._compressedUSize+this._compressedVSize)throw new Error("Invalid ct size");if(t.length!==768*this._k+96)throw new Error("Invalid decapsulation key");let n=t.subarray(0,this._skSize),i=t.subarray(this._skSize,this._skSize+this._pkSize),f=t.subarray(this._skSize+this._pkSize,this._skSize+this._pkSize+32),d=t.subarray(this._skSize+this._pkSize+32,this._skSize+this._pkSize+64),y=this._decap(e,n),[_,K]=rr(y,f),m=Mn(d,e),O=this._encap(i,y,K);return Br(e,O)===1?_:m}catch(n){throw new Ze(n)}}async _setup(){this._api===void 0&&(this._api=await Dr());}_getSeed(e){if(e==null){let t=new Uint8Array(32);return this._api.getRandomValues(t),t}if(e.byteLength!==32)throw new Error("seed must be 32 bytes in length");return e}_deriveKeyPair(e){let t=e.subarray(0,32),n=e.subarray(32,64),[i,f]=this._deriveCpaKeyPair(t),d=Hr(i),y=new Uint8Array(this._skSize+this._pkSize+64);return y.set(f,0),y.set(i,this._skSize),y.set(d,this._skSize+this._pkSize),y.set(n,this._skSize+this._pkSize+32),[i,y]}_deriveCpaKeyPair(e){let[t,n]=rr(e,new Uint8Array([this._k])),i=this._sampleMatrix(t,false),f=this._sampleNoise1(n,0,this._k),d=this._sampleNoise1(n,this._k,this._k);for(let m=0;m<this._k;m++)f[m]=It(f[m]),f[m]=nt(f[m]),d[m]=It(d[m]);let y=new Array(this._k);for(let m=0;m<this._k;m++)y[m]=Bn(Ft(i[m],f)),y[m]=mt(y[m],d[m]),y[m]=nt(y[m]);let _=new Uint8Array(this._pkSize);for(let m=0;m<this._k;m++)_.set(nr(y[m]),m*384);_.set(t,this._skSize);let K=new Uint8Array(this._skSize);for(let m=0;m<this._k;m++)K.set(nr(f[m]),m*384);return [_,K]}_encap(e,t,n){let i=new Array(this._k),f=new Uint8Array(384*this._k);for(let H=0;H<this._k;H++)i[H]=zr(e.subarray(H*384,(H+1)*384)),f.set(nr(i[H]),H*384);if(!Lr(e.subarray(0,f.length),f))throw new Error("invalid encapsulation key");let d=e.subarray(this._skSize),y=this._sampleMatrix(d,true),_=this._sampleNoise1(n,0,this._k),K=this._sampleNoise2(n,this._k,this._k),m=this._sampleNoise2(n,this._k*2,1)[0];for(let H=0;H<this._k;H++)_[H]=It(_[H]),_[H]=nt(_[H]);let O=new Array(this._k);for(let H=0;H<this._k;H++)O[H]=Ft(y[H],_),O[H]=sr(O[H]),O[H]=mt(O[H],K[H]),O[H]=nt(O[H]);let J=On(t),M=Ft(i,_);M=sr(M),M=mt(M,m),M=mt(M,J),M=nt(M);let V=new Uint8Array(this._compressedUSize+this._compressedVSize);return this._compressU(V.subarray(0,this._compressedUSize),O),this._compressV(V.subarray(this._compressedUSize),M),V}_decap(e,t){let n=this._decompressU(e.subarray(0,this._compressedUSize)),i=this._decompressV(e.subarray(this._compressedUSize)),f=this._polyvecFromBytes(t);for(let y=0;y<this._k;y++)n[y]=It(n[y]);let d=Ft(f,n);return d=sr(d),d=Ln(i,d),d=nt(d),Fn(d)}_sampleMatrix(e,t){let n=new Array(this._k),i=new Uint8Array(2);for(let f=0,d=0;d<this._k;d++){n[d]=new Array(this._k);for(let y=0;y<this._k;y++){t?(i[0]=d,i[1]=y):(i[0]=y,i[1]=d);let _=In(e,i),K=Xr(_.subarray(0,504),504,256);for(n[d][y]=K[0],f=K[1];f<256;){let m=_.subarray(504,672),O=Xr(m,168,256-f),J=O[0],M=O[1];for(let V=f;V<256;V++)n[d][y][V]=J[V-f];f=f+M;}}}return n}_sampleNoise1(e,t,n){let i=new Array(n);for(let f=0;f<n;f++)i[f]=qr(Mt(this._eta1*256/4,e,t),this._eta1),t++;return i}_sampleNoise2(e,t,n){let i=new Array(n);for(let f=0;f<n;f++)i[f]=qr(Mt(this._eta2*256/4,e,t),this._eta2),t++;return i}_polyvecFromBytes(e){let t=new Array(this._k);for(let n=0;n<this._k;n++)t[n]=zr(e.subarray(n*384,(n+1)*384));return t}_compressU(e,t){let n=new Array(4);for(let i=0,f=0;f<this._k;f++)for(let d=0;d<256/4;d++){for(let y=0;y<4;y++)n[y]=((t[f][4*d+y]<<10)+3329/2)/3329&1023;e[i++]=Xe(n[0]>>0),e[i++]=Xe(n[0]>>8|n[1]<<2),e[i++]=Xe(n[1]>>6|n[2]<<4),e[i++]=Xe(n[2]>>4|n[3]<<6),e[i++]=Xe(n[3]>>2);}return e}_compressV(e,t){let n=new Uint8Array(8);for(let i=0,f=0;f<256/8;f++){for(let d=0;d<8;d++)n[d]=Xe(((t[8*f+d]<<4)+3329/2)/3329)&15;e[i++]=n[0]|n[1]<<4,e[i++]=n[2]|n[3]<<4,e[i++]=n[4]|n[5]<<4,e[i++]=n[6]|n[7]<<4;}return e}_decompressU(e){let t=new Array(this._k);for(let i=0;i<this._k;i++)t[i]=new Array(384);let n=new Array(4);for(let i=0,f=0;f<this._k;f++)for(let d=0;d<256/4;d++){n[0]=ge(e[i+0])>>0|ge(e[i+1])<<8,n[1]=ge(e[i+1])>>2|ge(e[i+2])<<6,n[2]=ge(e[i+2])>>4|ge(e[i+3])<<4,n[3]=ge(e[i+3])>>6|ge(e[i+4])<<2,i=i+5;for(let y=0;y<4;y++)t[f][4*d+y]=Ne(Qe(n[y]&1023)*Qe(3329)+512>>10);}return t}_decompressV(e){let t=new Array(384);for(let n=0,i=0;i<256/2;i++,n++)t[2*i+0]=Ne(ge(e[n]&15)*ge(3329)+8>>4),t[2*i+1]=Ne(ge(e[n]>>4)*ge(3329)+8>>4);return t}};function rr(a,e){let t=jt.create().update(a);e!==void 0&&t.update(e);let n=t.digest();return [n.subarray(0,32),n.subarray(32,64)]}function Hr(a){return Rt.create().update(a).digest()}function Mn(a,e){let t=ot.create({dkLen:32}).update(a);return e!==void 0&&t.update(e),t.digest()}function In(a,e){return Ct.create({dkLen:672}).update(a).update(e).digest()}function nr(a){let e=0,t=0,n=new Uint8Array(384),i=Gr(a);for(let f=0;f<256/2;f++)e=ge(i[2*f]),t=ge(i[2*f+1]),n[3*f+0]=Xe(e>>0),n[3*f+1]=Xe(e>>8)|Xe(t<<4),n[3*f+2]=Xe(t>>4);return n}function zr(a){let e=new Array(384).fill(0);for(let t=0;t<256/2;t++)e[2*t]=Ne((ge(a[3*t+0])>>0|ge(a[3*t+1])<<8)&4095),e[2*t+1]=Ne((ge(a[3*t+1])>>4|ge(a[3*t+2])<<4)&4095);return e}function Fn(a){let e=new Uint8Array(32),t,n=Gr(a);for(let i=0;i<256/8;i++){e[i]=0;for(let f=0;f<8;f++)t=((ge(n[8*i+f])<<1)+ge(3329/2))/ge(3329)&1,e[i]|=Xe(t<<f);}return e}function On(a){let e=new Array(384).fill(0),t;for(let n=0;n<256/8;n++)for(let i=0;i<8;i++)t=-1*Ne(a[n]>>i&1),e[8*n+i]=t&Ne(3330/2);return e}function Xr(a,e,t){let n=new Array(384).fill(0),i=0,f,d;for(let y=0;i<t&&y+3<=e;)f=(ge(a[y]>>0)|ge(a[y+1])<<8)&4095,d=(ge(a[y+1]>>4)|ge(a[y+2])<<4)&4095,y=y+3,f<3329&&(n[i]=f,i=i+1),i<t&&d<3329&&(n[i]=d,i=i+1);return [n,i]}function qr(a,e){let t,n,i,f,d=new Array(384).fill(0);for(let y=0;y<256/8;y++){t=Nr(a.subarray(4*y,a.length)),n=t&1431655765,n=n+(t>>1&1431655765);for(let _=0;_<8;_++)i=Ne(n>>4*_+0&3),f=Ne(n>>4*_+e&3),d[8*y+_]=i-f;}return d}function It(a){for(let e=0,t=1,n=128;n>=2;n>>=1)for(let i=0;i<256;i=e+n){let f=At[t];for(t=t+1,e=i;e<i+n;e++){let d=We(f,a[e+n]);a[e+n]=a[e]-d,a[e]=a[e]+d;}}return a}function We(a,e){return Qr(a*e)}function nt(a){for(let e=0;e<256;e++)a[e]=Yr(a[e]);return a}function Yr(a){let t=(16777216+3329/2)/3329*a>>24;return t=t*3329,a-t}function Qr(a){let t=Ne($t(a)*62209)*3329;return t=a-t,t>>=16,Ne(t)}function Bn(a){for(let t=0;t<256;t++)a[t]=Qr($t(a[t])*$t(1353));return a}function Ft(a,e){let t=Jr(a[0],e[0]),n;for(let i=1;i<a.length;i++)n=Jr(a[i],e[i]),t=mt(t,n);return nt(t)}function Jr(a,e){let t,n;for(let i=0;i<256/4;i++)t=Vr(a[4*i+0],a[4*i+1],e[4*i+0],e[4*i+1],At[64+i]),n=Vr(a[4*i+2],a[4*i+3],e[4*i+2],e[4*i+3],-At[64+i]),a[4*i+0]=t[0],a[4*i+1]=t[1],a[4*i+2]=n[0],a[4*i+3]=n[1];return a}function Vr(a,e,t,n,i){let f=new Array(2);return f[0]=We(e,n),f[0]=We(f[0],i),f[0]+=We(a,t),f[1]=We(a,n),f[1]+=We(e,t),f}function mt(a,e){let t=new Array(384);for(let n=0;n<256;n++)t[n]=a[n]+e[n];return t}function Ln(a,e){for(let t=0;t<256;t++)a[t]-=e[t];return a}function sr(a){let e=0;for(let t=0,n=2;n<=128;n<<=1)for(let i=0;i<256;i=e+n){let f=Qt[t];for(t=t+1,e=i;e<i+n;e++){let d=a[e];a[e]=Yr(d+a[e+n]),a[e+n]=d-a[e+n],a[e+n]=We(f,a[e+n]);}}for(e=0;e<256;e++)a[e]=We(a[e],Qt[127]);return a}function Gr(a){for(let e=0;e<256;e++)a[e]-=3329,a[e]+=a[e]>>31&3329;return a}var et=class extends ct{constructor(){super(),Object.defineProperty(this,"_k",{enumerable:true,configurable:true,writable:true,value:3}),Object.defineProperty(this,"_du",{enumerable:true,configurable:true,writable:true,value:10}),Object.defineProperty(this,"_dv",{enumerable:true,configurable:true,writable:true,value:4}),Object.defineProperty(this,"_eta1",{enumerable:true,configurable:true,writable:true,value:2}),Object.defineProperty(this,"_eta2",{enumerable:true,configurable:true,writable:true,value:2}),this._skSize=12*this._k*256/8,this._pkSize=this._skSize+32,this._compressedUSize=this._k*this._du*256/8,this._compressedVSize=this._dv*256/8;}};async function ir(a){if(typeof globalThis.crypto?.subtle<"u"){let t=new TextEncoder,n=await globalThis.crypto.subtle.digest("SHA-256",t.encode(a));return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}let{createHash:e}=await import('crypto');return e("sha256").update(a).digest("hex")}function Dn(a){let e=a.length,t=Math.max(256,Nn(e+2)),n=new Uint8Array(t);n[0]=e>>8&255,n[1]=e&255,n.set(a,2);let i=U.default.randomBytes(t-e-2);return n.set(i,e+2),n}function Zr(a){if(a.length<2)return a;let e=a[0]<<8|a[1];return e+2>a.length?a:a.slice(2,2+e)}function Nn(a){let e=1;for(;e<a;)e<<=1;return e}async function ft(a){new TextEncoder;if(typeof globalThis.crypto?.subtle<"u"){let f=new Uint8Array([...a,1]),d=new Uint8Array([...a,2]),y=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",f)),_=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",d));return {nextChainKey:y,messageKey:_}}let{createHash:t}=await import('crypto'),n=new Uint8Array(t("sha256").update(Buffer.from([...a,1])).digest()),i=new Uint8Array(t("sha256").update(Buffer.from([...a,2])).digest());return {nextChainKey:n,messageKey:i}}function Hn(a,e,t){let n={v:3,from:a,msg:e,ts:new Date().toISOString()};return t?.contentType&&t.contentType!=="text/plain"&&(n.ct=t.contentType),t?.messageType&&t.messageType!=="text"&&(n.mt=t.messageType),t?.threadId&&(n.tid=t.threadId),t?.replyTo&&(n.rto=t.replyTo),JSON.stringify(n)}function zn(a){try{let e=JSON.parse(a);if((e.v===2||e.v===3)&&e.from&&e.msg!==void 0){let t={from:e.from,msg:e.msg,ts:e.ts};return e.ct&&(t.contentType=e.ct),e.mt&&(t.messageType=e.mt),e.tid&&(t.threadId=e.tid),e.rto&&(t.replyTo=e.rto),t}return null}catch{return null}}var nn=86,Wr=1,en=2,Xn=4,qn=8,Jn=16,Vn=32;function Yn(a,e){return new Uint8Array([nn,a,e>>8&255,e&255])}function Qn(a){return a.length<4||a[0]!==nn?null:{flags:a[1],ratchetStep:a[2]<<8|a[3],content:a.slice(4)}}async function lt(a,e){let t=new Uint8Array(a.length+e.length);if(t.set(a,0),t.set(e,a.length),typeof globalThis.crypto?.subtle<"u"){let y=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",t.buffer)),_=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new Uint8Array([...y,1]).buffer)),K=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new Uint8Array([...y,2]).buffer));return {newRootKey:_,newChainKey:K}}let{createHash:n}=await import('crypto'),i=new Uint8Array(n("sha256").update(Buffer.from(t)).digest()),f=new Uint8Array(n("sha256").update(Buffer.from([...i,1])).digest()),d=new Uint8Array(n("sha256").update(Buffer.from([...i,2])).digest());return {newRootKey:f,newChainKey:d}}async function tn(a,e){if(typeof globalThis.crypto?.subtle<"u"){let n=await globalThis.crypto.subtle.importKey("raw",a.buffer,{name:"HMAC",hash:"SHA-256"},false,["sign"]);return new Uint8Array(await globalThis.crypto.subtle.sign("HMAC",n,e.buffer))}let{createHmac:t}=await import('crypto');return new Uint8Array(t("sha256",Buffer.from(a)).update(Buffer.from(e)).digest())}var Ot=1e3,Gn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Zn(a){if(a.length===0)return "1";let e="",t=BigInt("0x"+Array.from(a).map(n=>n.toString(16).padStart(2,"0")).join(""));for(;t>0n;){let n=t%58n;t=t/58n,e=Gn[Number(n)]+e;}for(let n of a)if(n===0)e="1"+e;else break;return e||"1"}var rn=class a{constructor(e,t){this._signedPrekey=null;this._signedPrekeyId=0;this._pinnedDids=new Set;this._listeners=new Set;this._conversations=new Map;this._offlineQueue=[];this._ratchetStates=new Map;this._identityCache=new Map;this._seenMessageIds=new Set;this._decryptFailCount=0;this._peerDecryptFails=new Map;this._autoResetThreshold=10;this._rpcHandlers=new Map;this._rpcPending=new Map;this._coverTrafficTimer=null;this._rpcListener=null;this._persistMode="memory";this._persistKey=null;this.did=e.did,this.apiKey=e.apiKey,this.signingKeyPair=e.signingKeyPair,this.encryptionKeyPair=e.encryptionKeyPair,this.baseUrl=t?.baseUrl||"https://api.voidly.ai",this.autoPin=t?.autoPin!==false,this.defaultRetries=t?.retries??3,this.fallbackRelays=t?.fallbackRelays||[],this.paddingEnabled=t?.padding!==false,this.sealedSender=t?.sealedSender||false,this.requireSignatures=t?.requireSignatures||false,this.timeout=t?.timeout??3e4,this.postQuantum=t?.postQuantum!==false,this.deniable=t?.deniable||false,this.doubleRatchet=t?.doubleRatchet!==false,this.jitterMs=t?.jitterMs||0,this.longPoll=t?.longPoll!==false,this.mlkemPublicKey=e.mlkemPublicKey||null,this.mlkemSecretKey=e.mlkemSecretKey||null,this._persistMode=t?.persist||"memory",this._onPersist=t?.onPersist,this._onLoad=t?.onLoad,this._persistPath=t?.persistPath,this._transportPrefs=t?.transport||["sse","long-poll"],this._autoResetThreshold=t?.autoResetThreshold??10,this._onRatchetReset=t?.onRatchetReset;}static async register(e={},t){let n=t?.baseUrl||"https://api.voidly.ai",i=U.default.sign.keyPair(),f=U.default.box.keyPair(),d=t?.postQuantum!==false,y,_;d&&([y,_]=await new et().generateKeyPair());let K=U.default.box.keyPair(),m=1,O=U.default.sign.detached(K.publicKey,i.secretKey),J={name:e.name,capabilities:e.capabilities,signing_public_key:(0, g.encodeBase64)(i.publicKey),encryption_public_key:(0, g.encodeBase64)(f.publicKey),signed_prekey_public:(0, g.encodeBase64)(K.publicKey),signed_prekey_signature:(0, g.encodeBase64)(O),signed_prekey_id:m};y&&(J.mlkem_public_key=(0, g.encodeBase64)(y));let M=await fetch(`${n}/v1/agent/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)});if(!M.ok){let be=await M.json().catch(()=>({})),qe=be.error?.message||be.error||M.statusText;throw new Error(`Registration failed: ${qe}`)}let V=await M.json(),H=new a({did:V.did,apiKey:V.api_key,signingKeyPair:i,encryptionKeyPair:f,mlkemPublicKey:y,mlkemSecretKey:_},t);return H._signedPrekey=K,H._signedPrekeyId=m,H}static fromCredentials(e,t){if(!e.did||!e.did.startsWith("did:"))throw new Error('Invalid credentials: did must start with "did:"');if(!e.apiKey||e.apiKey.length<8)throw new Error("Invalid credentials: apiKey is missing or too short");if(!e.signingSecretKey||!e.encryptionSecretKey)throw new Error("Invalid credentials: secret keys are required");let n,i;try{n=(0,g.decodeBase64)(e.signingSecretKey),i=(0,g.decodeBase64)(e.encryptionSecretKey);}catch{throw new Error("Invalid credentials: secret keys must be valid base64")}if(n.length!==64)throw new Error(`Invalid credentials: signing key must be 64 bytes, got ${n.length}`);if(i.length!==32)throw new Error(`Invalid credentials: encryption key must be 32 bytes, got ${i.length}`);let f,d;if(e.mlkemPublicKey&&e.mlkemSecretKey)try{f=(0,g.decodeBase64)(e.mlkemPublicKey),d=(0,g.decodeBase64)(e.mlkemSecretKey),(f.length!==1184||d.length!==2400)&&(f=void 0,d=void 0);}catch{}let y=!d&&t?.postQuantum!==false?{...t,postQuantum:false}:t,_=new a({did:e.did,apiKey:e.apiKey,signingKeyPair:U.default.sign.keyPair.fromSecretKey(n),encryptionKeyPair:{publicKey:U.default.box.keyPair.fromSecretKey(i).publicKey,secretKey:i},mlkemPublicKey:f,mlkemSecretKey:d},y);if(e.ratchetStates)for(let[K,m]of Object.entries(e.ratchetStates))try{let O=(0,g.decodeBase64)(m.sendChainKey),J=(0,g.decodeBase64)(m.recvChainKey);if(O.length!==32||J.length!==32)continue;let M={sendChainKey:O,sendStep:m.sendStep||0,recvChainKey:J,recvStep:m.recvStep||0,skippedKeys:new Map};if(m.rootKey)try{M.rootKey=(0,g.decodeBase64)(m.rootKey),M.rootKey.length!==32&&(M.rootKey=void 0);}catch{}if(m.dhSendSecretKey&&m.dhSendPublicKey)try{let V=(0,g.decodeBase64)(m.dhSendSecretKey),H=(0,g.decodeBase64)(m.dhSendPublicKey);V.length===32&&H.length===32&&(M.dhSendKeyPair={publicKey:H,secretKey:V});}catch{}if(m.dhRecvPubKey)try{let V=(0,g.decodeBase64)(m.dhRecvPubKey);V.length===32&&(M.dhRecvPubKey=V);}catch{}if(m.prevSendStep!==void 0&&(M.prevSendStep=m.prevSendStep),M.dhSkippedKeys=new Map,m.skippedKeys&&typeof m.skippedKeys=="object")for(let[V,H]of Object.entries(m.skippedKeys))try{let be=(0,g.decodeBase64)(H);be.length===32&&M.skippedKeys.set(Number(V),be);}catch{}if(m.dhSkippedKeys&&typeof m.dhSkippedKeys=="object")for(let[V,H]of Object.entries(m.dhSkippedKeys))try{let be=(0,g.decodeBase64)(H);be.length===32&&M.dhSkippedKeys.set(V,be);}catch{}_._ratchetStates.set(K,M);}catch{}if(e.peerDecryptFails&&typeof e.peerDecryptFails=="object")for(let[K,m]of Object.entries(e.peerDecryptFails))typeof m=="number"&&m>0&&_._peerDecryptFails.set(K,m);if(e.signedPrekeySecret&&e.signedPrekeyPublic)try{let K=(0,g.decodeBase64)(e.signedPrekeySecret),m=(0,g.decodeBase64)(e.signedPrekeyPublic);K.length===32&&m.length===32&&(_._signedPrekey={publicKey:m,secretKey:K},_._signedPrekeyId=e.signedPrekeyId||0);}catch{}return _}exportCredentials(){let e={};for(let[t,n]of this._ratchetStates){let i={sendChainKey:(0, g.encodeBase64)(n.sendChainKey),sendStep:n.sendStep,recvChainKey:(0, g.encodeBase64)(n.recvChainKey),recvStep:n.recvStep};n.rootKey&&(i.rootKey=(0, g.encodeBase64)(n.rootKey)),n.dhSendKeyPair&&(i.dhSendSecretKey=(0, g.encodeBase64)(n.dhSendKeyPair.secretKey),i.dhSendPublicKey=(0, g.encodeBase64)(n.dhSendKeyPair.publicKey)),n.dhRecvPubKey&&(i.dhRecvPubKey=(0, g.encodeBase64)(n.dhRecvPubKey)),n.prevSendStep!==void 0&&(i.prevSendStep=n.prevSendStep),n.skippedKeys?.size&&(i.skippedKeys=Object.fromEntries([...n.skippedKeys].map(([f,d])=>[String(f),(0, g.encodeBase64)(d)]))),n.dhSkippedKeys?.size&&(i.dhSkippedKeys=Object.fromEntries([...n.dhSkippedKeys].map(([f,d])=>[f,(0, g.encodeBase64)(d)]))),e[t]=i;}return {did:this.did,apiKey:this.apiKey,signingSecretKey:(0, g.encodeBase64)(this.signingKeyPair.secretKey),encryptionSecretKey:(0, g.encodeBase64)(this.encryptionKeyPair.secretKey),signingPublicKey:(0, g.encodeBase64)(this.signingKeyPair.publicKey),encryptionPublicKey:(0, g.encodeBase64)(this.encryptionKeyPair.publicKey),...Object.keys(e).length>0?{ratchetStates:e}:{},...this.mlkemPublicKey?{mlkemPublicKey:(0, g.encodeBase64)(this.mlkemPublicKey)}:{},...this.mlkemSecretKey?{mlkemSecretKey:(0, g.encodeBase64)(this.mlkemSecretKey)}:{},...this._signedPrekey?{signedPrekeySecret:(0, g.encodeBase64)(this._signedPrekey.secretKey),signedPrekeyPublic:(0, g.encodeBase64)(this._signedPrekey.publicKey),signedPrekeyId:this._signedPrekeyId}:{},...this._peerDecryptFails.size>0?{peerDecryptFails:Object.fromEntries(this._peerDecryptFails)}:{}}}_derivePersistKey(){if(this._persistKey)return this._persistKey;let e=(0, g.decodeUTF8)("voidly-persist-v1"),t=new Uint8Array(this.signingKeyPair.secretKey.length+e.length);return t.set(this.signingKeyPair.secretKey,0),t.set(e,this.signingKeyPair.secretKey.length),this._persistKey=U.default.hash(t).slice(0,32),this._persistKey}async _persistRatchetState(){if(this._persistMode!=="memory")try{let e=this.exportCredentials(),t=JSON.stringify(e.ratchetStates||{}),n=this._derivePersistKey(),i=U.default.randomBytes(24),f=U.default.secretbox((0,g.decodeUTF8)(t),i,n),d=JSON.stringify({n:(0,g.encodeBase64)(i),c:(0,g.encodeBase64)(f),v:1});switch(this._persistMode){case "localStorage":typeof localStorage<"u"&&localStorage.setItem(`voidly-ratchet-${this.did}`,d);break;case "indexedDB":await this._idbPut(d);break;case "file":this._persistPath&&await(await import('fs/promises')).writeFile(this._persistPath,d,"utf-8");break;case "relay":await this._timedFetch(`${this.baseUrl}/v1/agent/memory/ratchet/state`,{method:"PUT",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({value:d})}).catch(y=>{console.warn(`[voidly] \u26A0 Relay ratchet persist failed: ${y instanceof Error?y.message:y}`);});break;case "custom":this._onPersist&&await this._onPersist(d);break}}catch(e){console.warn(`[voidly] \u26A0 Ratchet state persistence failed (${this._persistMode}): ${e instanceof Error?e.message:e}`);}}async _loadPersistedRatchetState(){if(this._persistMode==="memory")return;let e=null;try{switch(this._persistMode){case "localStorage":typeof localStorage<"u"&&(e=localStorage.getItem(`voidly-ratchet-${this.did}`));break;case "indexedDB":e=await this._idbGet();break;case "file":if(this._persistPath)try{e=await(await import('fs/promises')).readFile(this._persistPath,"utf-8");}catch{}break;case "relay":try{let t=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/ratchet/state`,{headers:{"X-Agent-Key":this.apiKey}});t.ok&&(e=(await t.json()).value);}catch(t){console.warn(`[voidly] \u26A0 Relay ratchet load failed: ${t instanceof Error?t.message:t}`);}break;case "custom":this._onLoad&&(e=await this._onLoad());break}}catch(t){console.warn(`[voidly] \u26A0 Ratchet state load failed (${this._persistMode}): ${t instanceof Error?t.message:t}`);return}if(e)try{let{n:t,c:n}=JSON.parse(e),i=this._derivePersistKey(),f=U.default.secretbox.open((0,g.decodeBase64)(n),(0,g.decodeBase64)(t),i);if(!f)return;let d=JSON.parse((0,g.encodeUTF8)(f));for(let[y,_]of Object.entries(d)){if(!_||typeof _.sendStep!="number"||typeof _.recvStep!="number"||typeof _.sendChainKey!="string"||typeof _.recvChainKey!="string"||_.sendStep<0||_.recvStep<0||_.sendStep>4294967295||_.recvStep>4294967295)continue;if(this._ratchetStates.has(y)){let m=this._ratchetStates.get(y),O=m.sendStep+m.recvStep;if((_.sendStep||0)+(_.recvStep||0)<=O)continue}let K={sendChainKey:(0,g.decodeBase64)(_.sendChainKey),sendStep:_.sendStep,recvChainKey:(0,g.decodeBase64)(_.recvChainKey),recvStep:_.recvStep,skippedKeys:new Map};_.rootKey&&typeof _.rootKey=="string"&&(K.rootKey=(0,g.decodeBase64)(_.rootKey)),typeof _.dhSendSecretKey=="string"&&typeof _.dhSendPublicKey=="string"&&(K.dhSendKeyPair={secretKey:(0,g.decodeBase64)(_.dhSendSecretKey),publicKey:(0,g.decodeBase64)(_.dhSendPublicKey)}),typeof _.dhRecvPubKey=="string"&&(K.dhRecvPubKey=(0,g.decodeBase64)(_.dhRecvPubKey)),typeof _.prevSendStep=="number"&&_.prevSendStep>=0&&(K.prevSendStep=_.prevSendStep),K.sendChainKey.length===32&&K.recvChainKey.length===32&&this._ratchetStates.set(y,K);}}catch(t){console.warn(`[voidly] \u26A0 Ratchet state restore failed (corrupt data, starting fresh): ${t instanceof Error?t.message:t}`);}}async _idbPut(e){if(!(typeof indexedDB>"u"))return new Promise((t,n)=>{let i=indexedDB.open("voidly-agent",1);i.onupgradeneeded=()=>{let f=i.result;f.objectStoreNames.contains("ratchet")||f.createObjectStore("ratchet");},i.onsuccess=()=>{let f=i.result.transaction("ratchet","readwrite");f.objectStore("ratchet").put(e,this.did),f.oncomplete=()=>t(),f.onerror=()=>n(f.error);},i.onerror=()=>n(i.error);})}async _idbGet(){return typeof indexedDB>"u"?null:new Promise((e,t)=>{let n=indexedDB.open("voidly-agent",1);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains("ratchet")||i.createObjectStore("ratchet");},n.onsuccess=()=>{let f=n.result.transaction("ratchet","readonly").objectStore("ratchet").get(this.did);f.onsuccess=()=>e(f.result||null),f.onerror=()=>t(f.error);},n.onerror=()=>t(n.error);})}async flushRatchetState(){let e=this._persistMode;e==="memory"&&(this._persistMode="file"),await this._persistRatchetState(),this._persistMode=e;}static async fromCredentialsAsync(e,t){let n=a.fromCredentials(e,t);return await n._loadPersistedRatchetState(),n}get decryptFailCount(){return this._decryptFailCount}get peerDecryptFails(){return Object.fromEntries(this._peerDecryptFails)}resetRatchet(e){let t=`${this.did}:${e}`,n=`${e}:${this.did}`,i=this._ratchetStates.delete(t),f=this._ratchetStates.delete(n);return this._peerDecryptFails.delete(e),(i||f)&&this._persistRatchetState().catch(()=>{}),i||f}get didKey(){let e=new Uint8Array(2+this.signingKeyPair.publicKey.length);return e[0]=237,e[1]=1,e.set(this.signingKeyPair.publicKey,2),`did:key:z${Zn(e)}`}async send(e,t,n={}){let i=n.retries??this.defaultRetries,f=!n.noPadding&&this.paddingEnabled,d=n.sealedSender??this.sealedSender,y=await this.getIdentity(e);if(!y)throw new Error(`Recipient ${e} not found`);this.autoPin&&!n.skipPin&&await this._autoPinKeys(e);let _=(0, g.decodeBase64)(y.encryption_public_key),K=t;d&&(K=Hn(this.did,t,{contentType:n.contentType,messageType:n.messageType,threadId:n.threadId,replyTo:n.replyTo}));let m;f?m=Dn((0, g.decodeUTF8)(K)):m=(0, g.decodeUTF8)(K);let O=`${this.did}:${e}`,J=this._ratchetStates.get(O),M=null,V=null;if(J)J.rootKey&&J.dhSendKeyPair&&(V=J.dhSendKeyPair.publicKey);else {let ue=U.default.box.before(_,this.encryptionKeyPair.secretKey),D;if(this.postQuantum&&y.mlkem_public_key)try{let z=(0,g.decodeBase64)(y.mlkem_public_key),ve=new et,[_e,pe]=await ve.encap(z);M=_e;let Re=new Uint8Array(ue.length+pe.length);Re.set(ue,0),Re.set(pe,ue.length),D=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Re));}catch{D=ue;}else D=ue;if(this.doubleRatchet){let z=U.default.box.keyPair(),ve=U.default.box.before(_,z.secretKey),{newRootKey:_e,newChainKey:pe}=await lt(D,ve);V=z.publicKey,J={sendChainKey:pe,sendStep:0,recvChainKey:D,recvStep:0,skippedKeys:new Map,rootKey:_e,dhSendKeyPair:z,dhRecvPubKey:void 0,prevSendStep:0,dhSkippedKeys:new Map};}else J={sendChainKey:D,sendStep:0,recvChainKey:D,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(O,J);}let{nextChainKey:H,messageKey:be}=await ft(J.sendChainKey);J.sendChainKey=H,J.sendStep++;let qe=J.sendStep,Ee=Xn;f&&(Ee|=Wr),d&&(Ee|=en),M&&(Ee|=qn),V&&(Ee|=Jn),this.deniable&&(Ee|=Vn);let $e=Yn(Ee,qe),Le=new Uint8Array($e.length+m.length);Le.set($e,0),Le.set(m,$e.length);let Ie=U.default.randomBytes(U.default.secretbox.nonceLength),Je=U.default.secretbox(Le,Ie,be);if(!Je)throw new Error("Encryption failed");if(this.jitterMs>0){let ue=Math.random()*this.jitterMs;await new Promise(D=>setTimeout(D,ue));}let De={from:this.did,to:e,timestamp:new Date().toISOString(),nonce:(0, g.encodeBase64)(Ie),ciphertext_hash:await ir((0, g.encodeBase64)(Je)),ratchet_step:qe};M&&(De.pq_ciphertext=(0, g.encodeBase64)(M)),V&&(De.dh_ratchet_key=(0, g.encodeBase64)(V),De.pn=J.prevSendStep||0);let Ve=JSON.stringify(De),he;if(this.deniable){let ue=U.default.box.before(_,this.encryptionKeyPair.secretKey);he=await tn(ue,(0, g.decodeUTF8)(Ve));}else he=U.default.sign.detached((0, g.decodeUTF8)(Ve),this.signingKeyPair.secretKey);let j={to:e,ciphertext:(0, g.encodeBase64)(Je),nonce:(0, g.encodeBase64)(Ie),signature:(0, g.encodeBase64)(he),envelope:Ve,ttl:n.ttl};d||(j.content_type=n.contentType||"text/plain",j.message_type=n.messageType||"text",j.thread_id=n.threadId,j.reply_to=n.replyTo),this._persistRatchetState().catch(()=>{});let P=[this.baseUrl,...this.fallbackRelays],xe=null;for(let ue of P)try{let D=await this._fetchWithRetry(`${ue}/v1/agent/send/encrypted`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(j)},{maxRetries:i,baseDelay:500,maxDelay:1e4});return {id:D.id,from:D.from,to:D.to,timestamp:D.timestamp,expiresAt:D.expires_at||D.expiresAt,encrypted:D.encrypted,clientSide:D.client_side||D.clientSide}}catch(D){if(xe=D instanceof Error?D:new Error(String(D)),xe.message.includes("(4"))break}throw xe&&!xe.message.includes("(4")&&this._offlineQueue.push({recipientDid:e,message:t,options:n,timestamp:Date.now()}),xe||new Error("Send failed")}async receive(e={}){let t=new URLSearchParams;e.since&&t.set("since",e.since),e.limit&&t.set("limit",String(e.limit)),e.from&&t.set("from",e.from),e.threadId&&t.set("thread_id",e.threadId),e.contentType&&t.set("content_type",e.contentType),e.messageType&&t.set("message_type",e.messageType),e.unreadOnly&&t.set("unread","true");let n=await this._resilientFetch(`/v1/agent/receive/raw?${t}`,{headers:{"X-Agent-Key":this.apiKey}});if(!n.ok){let y=await n.json().catch(()=>({}));throw new Error(`Receive failed: ${y.error?.message||y.error||n.statusText}`)}let i=await n.json(),{decrypted:f,failedIds:d}=await this._decryptMessages(i.messages);if(d.length>0)try{await this.markReadBatch(d);}catch{for(let y of d)try{await this.markRead(y);}catch{}}return f}async _decryptMessages(e){let t=[],n=[],i=new Set;for(let f of e)try{if(this._seenMessageIds.has(f.id))continue;let d,y=null;if(f.sender_encryption_key)d=(0,g.decodeBase64)(f.sender_encryption_key),f.sender_signing_key&&(y=(0,g.decodeBase64)(f.sender_signing_key));else if(f.envelope){let j=JSON.parse(f.envelope),P=await this.getIdentity(j.from);if(!P)continue;d=(0,g.decodeBase64)(P.encryption_public_key),P.signing_public_key&&(y=(0,g.decodeBase64)(P.signing_public_key));}else continue;let _=(0,g.decodeBase64)(f.ciphertext),K=(0,g.decodeBase64)(f.nonce),m=null,O=0,J=null,M=null,V=0;if(f.envelope)try{let j=JSON.parse(f.envelope);typeof j.ratchet_step=="number"&&Number.isInteger(j.ratchet_step)&&j.ratchet_step>=0&&j.ratchet_step<=4294967295&&(O=j.ratchet_step),typeof j.pq_ciphertext=="string"&&j.pq_ciphertext.length<=65536&&(J=j.pq_ciphertext),typeof j.dh_ratchet_key=="string"&&j.dh_ratchet_key.length<=256&&(M=j.dh_ratchet_key),typeof j.pn=="number"&&Number.isInteger(j.pn)&&j.pn>=0&&j.pn<=4294967295&&(V=j.pn);}catch{}if(O>0){let j=`${f.from}:${this.did}`,P=this._ratchetStates.get(j);if(P){if(M&&P.rootKey){let D=(0,g.decodeBase64)(M),z=P.dhRecvPubKey;if(!z||(0,g.encodeBase64)(D)!==(0,g.encodeBase64)(z)){if(V>P.recvStep){let Me=P.recvChainKey;for(let we=P.recvStep+1;we<=V&&we-P.recvStep<=Ot;we++){let{nextChainKey:Ae,messageKey:X}=await ft(Me),Se=`${z?(0,g.encodeBase64)(z):"init"}:${we}`;for(P.dhSkippedKeys||(P.dhSkippedKeys=new Map),P.dhSkippedKeys.set(Se,X),Me=Ae;P.dhSkippedKeys.size>Ot;){let He=P.dhSkippedKeys.keys().next().value;if(He!==void 0)P.dhSkippedKeys.delete(He);else break}}}P.dhRecvPubKey=D;let ve=P.dhSendKeyPair||this.encryptionKeyPair,_e=U.default.box.before(D,ve.secretKey),pe=await lt(P.rootKey,_e);P.rootKey=pe.newRootKey,P.recvChainKey=pe.newChainKey,P.recvStep=0,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0;let Re=U.default.box.before(D,P.dhSendKeyPair.secretKey),Ue=await lt(P.rootKey,Re);P.rootKey=Ue.newRootKey,P.sendChainKey=Ue.newChainKey;}}}else {let D=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(J&&this.mlkemSecretKey)try{let _e=(0,g.decodeBase64)(J),Re=await new et().decap(_e,this.mlkemSecretKey),Ue=new Uint8Array(D.length+Re.length);Ue.set(D,0),Ue.set(Re,D.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ue));}catch{z=D;}else z=D;if(M&&this.doubleRatchet){let _e=(0,g.decodeBase64)(M),pe=U.default.box.before(_e,this.encryptionKeyPair.secretKey),{newRootKey:Re,newChainKey:Ue}=await lt(z,pe);P={sendChainKey:z,sendStep:0,recvChainKey:Ue,recvStep:0,skippedKeys:new Map,rootKey:Re,dhSendKeyPair:void 0,dhRecvPubKey:_e,prevSendStep:0,dhSkippedKeys:new Map};}else P={sendChainKey:z,sendStep:0,recvChainKey:z,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(j,P);let ve=`${this.did}:${f.from}`;this._ratchetStates.delete(ve);}let xe=O,ue=M?`${M}:${xe}`:`init:${xe}`;if(P.dhSkippedKeys?.has(ue)){let D=P.dhSkippedKeys.get(ue);m=U.default.secretbox.open(_,K,D),P.dhSkippedKeys.delete(ue);}else if(P.skippedKeys.has(xe)){let D=P.skippedKeys.get(xe);m=U.default.secretbox.open(_,K,D),P.skippedKeys.delete(xe);}else if(xe>P.recvStep)if(xe-P.recvStep>Ot){this._decryptFailCount++,n.push(f.id);let z=f.from||"unknown",ve=this._peerDecryptFails.get(z)||0;this._peerDecryptFails.set(z,ve+1),this._autoResetThreshold>0&&ve+1>=this._autoResetThreshold&&(this.resetRatchet(z),i.add(z),this._onRatchetReset?.(z,ve+1));continue}else {let z=P.recvChainKey;for(let pe=P.recvStep+1;pe<xe;pe++){let{nextChainKey:Re,messageKey:Ue}=await ft(z);for(P.skippedKeys.set(pe,Ue),z=Re;P.skippedKeys.size>Ot;){let Me=P.skippedKeys.keys().next().value;if(Me!==void 0)P.skippedKeys.delete(Me);else break}}let{nextChainKey:ve,messageKey:_e}=await ft(z);P.recvChainKey=ve,P.recvStep=xe,m=U.default.secretbox.open(_,K,_e);}if(!m&&M&&this.doubleRatchet&&P)try{let D=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(J&&this.mlkemSecretKey)try{let X=(0,g.decodeBase64)(J),He=await new et().decap(X,this.mlkemSecretKey),Ge=new Uint8Array(D.length+He.length);Ge.set(D,0),Ge.set(He,D.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ge));}catch{z=D;}else z=D;let ve=(0,g.decodeBase64)(M),_e=U.default.box.before(ve,this.encryptionKeyPair.secretKey),{newRootKey:pe,newChainKey:Re}=await lt(z,_e),Ue=Re;for(let X=1;X<O;X++){let{nextChainKey:Se}=await ft(Ue);Ue=Se;}let{nextChainKey:Me,messageKey:we}=await ft(Ue),Ae=U.default.secretbox.open(_,K,we);if(Ae){m=Ae,P.recvChainKey=Me,P.recvStep=O,P.rootKey=pe,P.dhRecvPubKey=ve,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0,P.sendChainKey=z;let X=U.default.box.before(ve,P.dhSendKeyPair.secretKey),Se=await lt(P.rootKey,X);P.rootKey=Se.newRootKey,P.sendChainKey=Se.newChainKey,P.dhSkippedKeys&&P.dhSkippedKeys.clear(),P.skippedKeys&&P.skippedKeys.clear();let He=`${this.did}:${f.from}`;this._ratchetStates.delete(He);}}catch{}if(!m&&P){this.resetRatchet(f.from),i.add(f.from),this._onRatchetReset?.(f.from,1),n.push(f.id);continue}m||(m=U.default.box.open(_,K,d,this.encryptionKeyPair.secretKey));}else m=U.default.box.open(_,K,d,this.encryptionKeyPair.secretKey);if(!m){this._decryptFailCount++,n.push(f.id);let j=f.from||"unknown",P=this._peerDecryptFails.get(j)||0;this._peerDecryptFails.set(j,P+1),this._autoResetThreshold>0&&P+1>=this._autoResetThreshold&&(this.resetRatchet(j),i.add(j),this._onRatchetReset?.(j,P+1));continue}{let j=f.from||"unknown";this._peerDecryptFails.has(j)&&this._peerDecryptFails.delete(j);}let H=m,be=!1,qe=!1,Ee=Qn(m);if(Ee&&(be=!!(Ee.flags&Wr),qe=!!(Ee.flags&en),H=Ee.content),be)H=Zr(H);else if(!Ee&&m.length>=256&&(m.length&m.length-1)===0){let j=Zr(m);j.length<m.length&&(H=j);}let $e=(0,g.encodeUTF8)(H),Le=f.from,Ie,Je,De,Ve;if(qe||!Ee){let j=zn($e);j&&($e=j.msg,Le=j.from,Ie=j.contentType,Je=j.messageType,De=j.threadId,Ve=j.replyTo);}let he=!1;try{let j=(0,g.decodeBase64)(f.signature),P=f.envelope||JSON.stringify({from:Le,to:f.to,timestamp:f.timestamp,nonce:f.nonce,ciphertext_hash:await ir(f.ciphertext)});if(j.length===32){let xe=U.default.box.before(d,this.encryptionKeyPair.secretKey),ue=await tn(xe,(0,g.decodeUTF8)(P));if(ue.length===j.length){let D=0;for(let z=0;z<ue.length;z++)D|=ue[z]^j[z];he=D===0;}}else y&&(he=U.default.sign.detached.verify((0,g.decodeUTF8)(P),j,y));}catch{he=!1;}if(this.requireSignatures&&!he){this._decryptFailCount++,n.push(f.id);let j=f.from||"unknown",P=this._peerDecryptFails.get(j)||0;this._peerDecryptFails.set(j,P+1);continue}if(this._seenMessageIds.add(f.id),this._seenMessageIds.size>1e4){let j=this._seenMessageIds.values();for(let P=0;P<1e3;P++){let xe=j.next().value;xe!==void 0&&this._seenMessageIds.delete(xe);}}t.push({id:f.id,from:Le,to:f.to,content:$e,contentType:Ie||f.content_type||"text/plain",messageType:Je||f.message_type||"text",threadId:De||f.thread_id||null,replyTo:Ve||f.reply_to||null,signatureValid:he,timestamp:f.timestamp,expiresAt:f.expires_at});}catch{this._decryptFailCount++,n.push(f.id);let d=f.from||"unknown",y=this._peerDecryptFails.get(d)||0;this._peerDecryptFails.set(d,y+1),this._autoResetThreshold>0&&y+1>=this._autoResetThreshold&&(this.resetRatchet(d),i.add(d),this._onRatchetReset?.(d,y+1));}return (t.length>0||this._peerDecryptFails.size>0)&&this._persistRatchetState().catch(()=>{}),{decrypted:t,failedIds:n}}async deleteMessage(e){return (await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${e}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}})).ok}async getProfile(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/profile`,{headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error("Failed to fetch profile");return await e.json()}async updateProfile(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/profile`,{method:"PATCH",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(e)});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Profile update failed: ${n.error||t.statusText}`)}}async getIdentity(e){let t=this._identityCache.get(e);if(t&&Date.now()-t.cachedAt<3e5)return t.profile;let n=await this._resilientFetch(`/v1/agent/identity/${e}`);if(!n.ok)return null;let i=await n.json();if(this._identityCache.set(e,{profile:i,cachedAt:Date.now()}),this._identityCache.size>500){let f=this._identityCache.size-400,d=this._identityCache.keys();for(let y=0;y<f;y++){let _=d.next().value;_!==void 0&&this._identityCache.delete(_);}}return i}async discover(e={}){let t=new URLSearchParams;e.query&&t.set("query",e.query),e.capability&&t.set("capability",e.capability),e.limit&&t.set("limit",String(e.limit));let n=await this._resilientFetch(`/v1/agent/discover?${t}`);return n.ok?(await n.json()).agents:[]}async stats(){return await(await this._timedFetch(`${this.baseUrl}/v1/agent/stats`)).json()}async registerWebhook(e,t={}){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({webhook_url:e,events:t.events})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(`Webhook registration failed: ${i.error?.message||i.error||n.statusText}`)}return await n.json()}async listWebhooks(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`,{headers:{"X-Agent-Key":this.apiKey}});return e.ok?(await e.json()).webhooks:[]}async deleteWebhook(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks/${e}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Webhook delete failed: ${n.error||t.statusText}`)}}static async verifyWebhookSignature(e,t,n){let i=new TextEncoder;if(typeof globalThis.crypto?.subtle<"u"){let _=await globalThis.crypto.subtle.importKey("raw",i.encode(n),{name:"HMAC",hash:"SHA-256"},false,["sign"]),K=await globalThis.crypto.subtle.sign("HMAC",_,i.encode(e)),m=`sha256=${Array.from(new Uint8Array(K)).map(V=>V.toString(16).padStart(2,"0")).join("")}`;if(t.length!==m.length)return false;let O=i.encode(t),J=i.encode(m),M=0;for(let V=0;V<O.length;V++)M|=O[V]^J[V];return M===0}let{createHmac:f,timingSafeEqual:d}=await import('crypto'),y=`sha256=${f("sha256",n).update(e).digest("hex")}`;return t.length!==y.length?false:d(Buffer.from(t),Buffer.from(y))}async rotateKeys(){let e=U.default.sign.keyPair(),t=U.default.box.keyPair(),n=U.default.box.keyPair(),i=(this._signedPrekeyId||0)+1,f=U.default.sign.detached(n.publicKey,e.secretKey),d={signing_public_key:(0, g.encodeBase64)(e.publicKey),encryption_public_key:(0, g.encodeBase64)(t.publicKey),signed_prekey_public:(0, g.encodeBase64)(n.publicKey),signed_prekey_signature:(0, g.encodeBase64)(f),signed_prekey_id:i};if(this.postQuantum&&this.mlkemPublicKey&&(d.mlkem_public_key=this.mlkemPublicKey),!(await this._timedFetch(`${this.baseUrl}/v1/agent/rotate-keys`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(d)})).ok)throw new Error("Key rotation failed");this.signingKeyPair=e,this.encryptionKeyPair=t,this._signedPrekey=n,this._signedPrekeyId=i,this._identityCache.clear(),this._pinnedDids.clear(),await this.uploadPrekeys(10);}async createChannel(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/channels`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(e)});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Channel creation failed: ${n.error||t.statusText}`)}return await t.json()}async listChannels(e={}){let t=new URLSearchParams;e.topic&&t.set("topic",e.topic),e.query&&t.set("q",e.query),e.mine&&t.set("mine","true"),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/channels?${t}`,{headers:e.mine?{"X-Agent-Key":this.apiKey}:{}});return n.ok?(await n.json()).channels:[]}async joinChannel(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/join`,{method:"POST",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Join failed: ${n.error||t.statusText}`)}return await t.json()}async leaveChannel(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/leave`,{method:"POST",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Leave failed: ${n.error||t.statusText}`)}}async postToChannel(e,t,n){let i=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({message:t,reply_to:n})});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Post failed: ${f.error||i.statusText}`)}return await i.json()}async readChannel(e,t={}){let n=new URLSearchParams;t.since&&n.set("since",t.since),t.before&&n.set("before",t.before),t.limit&&n.set("limit",String(t.limit));let i=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/messages?${n}`,{headers:{"X-Agent-Key":this.apiKey}});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Read failed: ${f.error||i.statusText}`)}return await i.json()}async deactivate(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/deactivate`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!e.ok){let t=await e.json().catch(()=>({}));throw new Error(`Deactivate failed: ${t.error||e.statusText}`)}}async registerCapability(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({name:e.name,description:e.description,input_schema:e.inputSchema,output_schema:e.outputSchema,version:e.version})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Capability registration failed: ${n.error||t.statusText}`)}return await t.json()}async listCapabilities(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`,{headers:{"X-Agent-Key":this.apiKey}});return e.ok?(await e.json()).capabilities:[]}async searchCapabilities(e={}){let t=new URLSearchParams;e.query&&t.set("q",e.query),e.name&&t.set("name",e.name),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/search?${t}`);return n.ok?(await n.json()).results:[]}async deleteCapability(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/${e}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Delete failed: ${n.error||t.statusText}`)}}async createTask(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${e.to}`);if(!t.ok)throw new Error("Recipient agent not found");let n=await t.json(),i=(0, g.decodeBase64)(n.encryption_public_key),f=(0, g.decodeUTF8)(JSON.stringify(e.input)),d=U.default.randomBytes(U.default.box.nonceLength),y=U.default.box(f,d,i,this.encryptionKeyPair.secretKey),_=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({to:e.to,capability:e.capability,encrypted_input:(0, g.encodeBase64)(y),input_nonce:(0, g.encodeBase64)(d),priority:e.priority||"normal",expires_in:e.expiresIn})});if(!_.ok){let K=await _.json().catch(()=>({}));throw new Error(`Task creation failed: ${K.error||_.statusText}`)}return await _.json()}async listTasks(e={}){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.capability&&t.set("capability",e.capability),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks?${t}`,{headers:{"X-Agent-Key":this.apiKey}});return n.ok?(await n.json()).tasks:[]}async getTask(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${e}`,{headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Get task failed: ${n.error||t.statusText}`)}return await t.json()}async updateTask(e,t){let n={};if(t.status&&(n.status=t.status),t.rating!==void 0&&(n.rating=t.rating),t.ratingComment&&(n.rating_comment=t.ratingComment),t.output&&(t.status==="completed"||t.status==="failed")){let d=(await this.getTask(e)).from,y=await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${d}`);if(y.ok){let _=await y.json(),K=(0, g.decodeBase64)(_.encryption_public_key),m=(0, g.decodeUTF8)(JSON.stringify(t.output)),O=U.default.randomBytes(U.default.box.nonceLength),J=U.default.box(m,O,K,this.encryptionKeyPair.secretKey),M=U.default.sign.detached(m,this.signingKeyPair.secretKey);n.encrypted_output=(0, g.encodeBase64)(J),n.output_nonce=(0, g.encodeBase64)(O),n.output_signature=(0, g.encodeBase64)(M);}}let i=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(n)});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Task update failed: ${f.error||i.statusText}`)}return await i.json()}decryptTaskInput(e,t){try{let n=(0,g.decodeBase64)(e.encrypted_input),i=(0,g.decodeBase64)(e.input_nonce),f=U.default.box.open(n,i,t,this.encryptionKeyPair.secretKey);return f?JSON.parse((0,g.encodeUTF8)(f)):null}catch{return null}}decryptTaskOutput(e,t){try{let n=(0,g.decodeBase64)(e.encrypted_output),i=(0,g.decodeBase64)(e.output_nonce),f=U.default.box.open(n,i,t,this.encryptionKeyPair.secretKey);return f?JSON.parse((0,g.encodeUTF8)(f)):null}catch{return null}}async attest(e){let t=e.timestamp||new Date().toISOString(),n=e.claimType+JSON.stringify(e.claimData)+t,i=(0, g.decodeUTF8)(n),f=U.default.sign.detached(i,this.signingKeyPair.secretKey),d=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({claim_type:e.claimType,claim_data:e.claimData,signature:(0, g.encodeBase64)(f),timestamp:t,country:e.country,domain:e.domain,confidence:e.confidence,expires_in:e.expiresIn})});if(!d.ok){let y=await d.json().catch(()=>({}));throw new Error(`Attestation failed: ${y.error||d.statusText}`)}return await d.json()}async corroborate(e,t,n){let i=e+t,f=(0, g.decodeUTF8)(i),d=U.default.sign.detached(f,this.signingKeyPair.secretKey),y=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${e}/corroborate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({vote:t,signature:(0, g.encodeBase64)(d),comment:n})});if(!y.ok){let _=await y.json().catch(()=>({}));throw new Error(`Corroboration failed: ${_.error||y.statusText}`)}return await y.json()}async queryAttestations(e={}){let t=new URLSearchParams;e.country&&t.set("country",e.country),e.domain&&t.set("domain",e.domain),e.type&&t.set("type",e.type),e.agent&&t.set("agent",e.agent),e.minConsensus!==void 0&&t.set("min_consensus",String(e.minConsensus)),e.since&&t.set("since",e.since),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations?${t}`);return n.ok?(await n.json()).attestations:[]}async getAttestation(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${e}`);if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Get attestation failed: ${n.error||t.statusText}`)}return await t.json()}async getConsensus(e){let t=new URLSearchParams;e.country&&t.set("country",e.country),e.domain&&t.set("domain",e.domain),e.type&&t.set("type",e.type);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/consensus?${t}`);return n.ok?(await n.json()).consensus:[]}async inviteToChannel(e,t,n){let i=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/invite`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({did:t,message:n?.message,expires_hours:n?.expiresHours})});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Invite failed: ${f.error||i.statusText}`)}return await i.json()}async listInvites(e="pending"){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/invites?status=${e}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});return t.ok?(await t.json()).invites:[]}async respondToInvite(e,t){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/invites/${e}/respond`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({action:t})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(`Invite response failed: ${i.error||n.statusText}`)}return await n.json()}async getTrustScore(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/trust/${e}`);if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Trust score failed: ${n.error||t.statusText}`)}return await t.json()}async getTrustLeaderboard(e){let t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.minLevel&&t.set("min_level",e.minLevel);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/trust/leaderboard?${t}`);return n.ok?(await n.json()).leaderboard:[]}async markRead(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${e}/read`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!t.ok)throw new Error(`Failed to mark message as read: ${t.status}`);return await t.json()}async markReadBatch(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/messages/read-batch`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({message_ids:e})});if(!t.ok)throw new Error(`Failed to batch mark messages as read: ${t.status}`);return await t.json()}async getUnreadCount(e){let t=new URLSearchParams;e&&t.set("from",e);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/messages/unread-count?${t}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!n.ok)throw new Error(`Failed to get unread count: ${n.status}`);return await n.json()}async broadcastTask(e){let t=(0, g.decodeUTF8)(e.input),n=U.default.randomBytes(U.default.secretbox.nonceLength),i=U.default.secretbox(t,n,U.default.box.before(this.encryptionKeyPair.publicKey,this.encryptionKeyPair.secretKey)),f=U.default.sign.detached(t,this.signingKeyPair.secretKey),d=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcast`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({capability:e.capability,encrypted_input:(0, g.encodeBase64)(i),input_nonce:(0, g.encodeBase64)(n),input_signature:(0, g.encodeBase64)(f),priority:e.priority,max_agents:e.maxAgents,min_trust_level:e.minTrustLevel,expires_in:e.expiresIn})});if(!d.ok){let y=await d.json().catch(()=>({}));throw new Error(y.error||`Broadcast failed: ${d.status}`)}return await d.json()}async listBroadcasts(e){let t=new URLSearchParams;e&&t.set("status",e);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts?${t}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});return n.ok?(await n.json()).broadcasts:[]}async getBroadcast(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts/${e}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!t.ok)throw new Error(`Failed to get broadcast: ${t.status}`);return await t.json()}async getAnalytics(e){let t=new URLSearchParams;e&&t.set("period",e);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/analytics?${t}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!n.ok)throw new Error(`Failed to get analytics: ${n.status}`);return await n.json()}static verifyAttestation(e,t){try{let n=e.claim_type+JSON.stringify(e.claim_data)+e.timestamp,i=(0,g.decodeUTF8)(n),f=(0,g.decodeBase64)(e.signature),d=(0,g.decodeBase64)(t);return U.default.sign.detached.verify(i,f,d)}catch{return false}}async memorySet(e,t,n,i){let f=JSON.stringify(n),d=(0, g.decodeUTF8)(f),y=U.default.randomBytes(U.default.secretbox.nonceLength),_=new Uint8Array([...this.encryptionKeyPair.secretKey,77,69,77]),K;if(typeof globalThis.crypto?.subtle<"u")K=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",_));else {let{createHash:J}=await import('crypto');K=new Uint8Array(J("sha256").update(Buffer.from(_)).digest());}let m=U.default.secretbox(d,y,K),O=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({value:(0, g.encodeBase64)(m),value_type:`encrypted:${i?.valueType||(typeof n=="object"?"json":typeof n)}`,ttl:i?.ttl,client_nonce:(0, g.encodeBase64)(y)})});if(!O.ok)throw new Error(`Memory set failed: ${O.status} ${await O.text()}`);return O.json()}async memoryGet(e,t){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{headers:{"X-Agent-Key":this.apiKey}});if(n.status===404)return null;if(!n.ok)throw new Error(`Memory get failed: ${n.status} ${await n.text()}`);let i=await n.json();if(i.value_type?.startsWith("encrypted:")&&i.client_nonce)try{let f=new Uint8Array([...this.encryptionKeyPair.secretKey,77,69,77]),d;if(typeof globalThis.crypto?.subtle<"u")d=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",f));else {let{createHash:m}=await import('crypto');d=new Uint8Array(m("sha256").update(Buffer.from(f)).digest());}let y=(0,g.decodeBase64)(i.value),_=(0,g.decodeBase64)(i.client_nonce),K=U.default.secretbox.open(y,_,d);K&&(i.value=JSON.parse((0,g.encodeUTF8)(K)),i.value_type=i.value_type.replace("encrypted:",""));}catch{}return i}async memoryDelete(e,t){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!n.ok)throw new Error(`Memory delete failed: ${n.status} ${await n.text()}`);return n.json()}async memoryList(e,t){let n=e||"default",i=new URLSearchParams;t?.prefix&&i.set("prefix",t.prefix),t?.limit&&i.set("limit",String(t.limit));let f=i.toString()?`?${i.toString()}`:"",d=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(n)}${f}`,{headers:{"X-Agent-Key":this.apiKey}});if(!d.ok)throw new Error(`Memory list failed: ${d.status} ${await d.text()}`);return d.json()}async memoryNamespaces(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/memory`,{headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error(`Memory namespaces failed: ${e.status} ${await e.text()}`);return e.json()}async exportData(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/export`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({include_messages:e?.includeMessages,include_channels:e?.includeChannels,include_tasks:e?.includeTasks,include_attestations:e?.includeAttestations,include_memory:e?.includeMemory,include_trust:e?.includeTrust})});if(!t.ok)throw new Error(`Export failed: ${t.status} ${await t.text()}`);return t.json()}async listExports(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/exports`,{headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error(`List exports failed: ${e.status} ${await e.text()}`);return e.json()}async getRelayInfo(){let e=await this._timedFetch(`${this.baseUrl}/v1/relay/info`);if(!e.ok)throw new Error(`Relay info failed: ${e.status} ${await e.text()}`);return e.json()}async getRelayPeers(){let e=await this._timedFetch(`${this.baseUrl}/v1/relay/peers`);if(!e.ok)throw new Error(`Relay peers failed: ${e.status} ${await e.text()}`);return e.json()}async routeMessage(e,t,n){let i=await this.getIdentity(e);if(!i)throw new Error(`Recipient ${e} not found`);let f=(0, g.decodeBase64)(i.encryption_public_key),d=U.default.randomBytes(U.default.box.nonceLength),y=U.default.box((0, g.decodeUTF8)(t),d,f,this.encryptionKeyPair.secretKey);if(!y)throw new Error("Encryption failed");let _=(0, g.decodeUTF8)(JSON.stringify({from:this.did,to:e,nonce:(0, g.encodeBase64)(d),ciphertext_hash:await ir((0, g.encodeBase64)(y))})),K=U.default.sign.detached(_,this.signingKeyPair.secretKey),m=await this._timedFetch(`${this.baseUrl}/v1/relay/route`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({to:e,ciphertext:(0, g.encodeBase64)(y),nonce:(0, g.encodeBase64)(d),signature:(0, g.encodeBase64)(K),content_type:n?.contentType||"text/plain",thread_id:n?.threadId})});if(!m.ok)throw new Error(`Route failed: ${m.status} ${await m.text()}`);return m.json()}async ping(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/ping`,{method:"POST",headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error(`Ping failed: ${e.status}`);return e.json()}async checkOnline(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/ping/${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`Ping check failed: ${t.status}`);return t.json()}async pinKeys(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({did:e})});if(!t.ok)throw new Error(`Key pin failed: ${t.status}`);return t.json()}async listPinnedKeys(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status);let n=t.toString()?`?${t.toString()}`:"",i=await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pins${n}`,{headers:{"X-Agent-Key":this.apiKey}});if(!i.ok)throw new Error(`List pins failed: ${i.status}`);return i.json()}async verifyKeys(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/keys/verify/${encodeURIComponent(e)}`,{headers:{"X-Agent-Key":this.apiKey}});if(!t.ok)throw new Error(`Key verify failed: ${t.status}`);return t.json()}async uploadPrekeys(e=20){let t=[];for(let d=0;d<e;d++){let y=U.default.box.keyPair();t.push({id:Date.now()+d,public_key:(0, g.encodeBase64)(y.publicKey),secretKey:y.secretKey});}let n=U.default.box.keyPair();this._signedPrekeyId++;let i=U.default.sign.detached(n.publicKey,this.signingKeyPair.secretKey);this._signedPrekey=n;let f=await this._timedFetch(`${this.baseUrl}/v1/agent/prekeys`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({prekeys:t.map(d=>({id:d.id,public_key:d.public_key})),signed_prekey:{public_key:(0, g.encodeBase64)(n.publicKey),signature:(0, g.encodeBase64)(i),id:this._signedPrekeyId}})});if(!f.ok)throw new Error(`Prekey upload failed: ${f.status}`);return await f.json()}async fetchPrekeys(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/prekeys/${encodeURIComponent(e)}`);return t.ok?await t.json():null}async createEncryptedChannel(e){let t=U.default.randomBytes(32),n=await this._timedFetch(`${this.baseUrl}/v1/agent/channels`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(e)});if(!n.ok){let y=await n.json().catch(()=>({}));throw new Error(`Channel creation failed: ${y.error||n.statusText}`)}let i=await n.json(),f=U.default.randomBytes(U.default.box.nonceLength);U.default.box(t,f,this.encryptionKeyPair.publicKey,this.encryptionKeyPair.secretKey);return await this.memorySet("channel-keys",i.id,{key:(0, g.encodeBase64)(t),nonce:(0, g.encodeBase64)(f)}),{...i,channelKey:t}}async postEncrypted(e,t,n){let i=U.default.randomBytes(U.default.secretbox.nonceLength),f=U.default.secretbox((0, g.decodeUTF8)(t),i,n),d=new Uint8Array([...f,...i]),y=U.default.sign.detached(d,this.signingKeyPair.secretKey),_=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({message:JSON.stringify({v:3,ct:(0, g.encodeBase64)(f),n:(0, g.encodeBase64)(i),sig:(0, g.encodeBase64)(y),from:this.did})})});if(!_.ok)throw new Error(`Post failed: ${_.status}`);return await _.json()}async readEncrypted(e,t,n){let i=await this.readChannel(e,n),f=[];for(let d of i.messages)try{let y=JSON.parse(typeof d.content=="string"?d.content:d.message||"");if(y.v===3&&y.ct&&y.n){let _=(0,g.decodeBase64)(y.ct),K=(0,g.decodeBase64)(y.n),m=U.default.secretbox.open(_,K,t);if(m){let O=!1;if(y.sig&&y.from)try{let J=await this.getIdentity(y.from);if(J){let M=new Uint8Array([..._,...K]);O=U.default.sign.detached.verify(M,(0,g.decodeBase64)(y.sig),(0,g.decodeBase64)(J.signing_public_key));}}catch{}f.push({id:d.id,from:y.from||d.author||"unknown",content:(0,g.encodeUTF8)(m),timestamp:d.created_at||d.timestamp,signatureValid:O});}}}catch{}return {messages:f,count:f.length}}listen(e,t={},n){let i=Math.max(t.interval||2e3,500),f=t.adaptive!==false,d=t.autoMarkRead!==false,y=t.unreadOnly!==false,_=t.heartbeat!==false,K=t.heartbeatInterval||6e4,m=true,O=i,J=0,M,V=null,H=null,be={stop:()=>{m=false,V&&clearTimeout(V),H&&clearInterval(H),this._listeners.delete(be);},get active(){return m}};this._listeners.add(be),_&&(H=setInterval(async()=>{if(m)try{await this.ping();}catch{}},K),this.ping().catch(()=>{}));let qe=async he=>{for(let j of he)try{await e(j),d&&await this.markRead(j.id).catch(()=>{});}catch(P){n&&n(P instanceof Error?P:new Error(String(P)));}he.length>0&&(M=he[he.length-1].timestamp);},Ee="",$e=0,Le=async()=>{try{let he=new URLSearchParams;M&&he.set("since",M),t.from&&he.set("from",t.from);let j=`${this.baseUrl}/v1/agent/receive/sse?${he}`,P={"X-Agent-Key":this.apiKey};Ee&&(P["Last-Event-ID"]=Ee);let xe=new AbortController,ue=setTimeout(()=>xe.abort(),6e4),D;try{D=await fetch(j,{headers:P,signal:xe.signal});}catch(pe){throw clearTimeout(ue),pe}if(!D.ok||!D.body)return clearTimeout(ue),!1;let z=D.body.getReader(),ve=new TextDecoder,_e="";try{for(;m&&!t.signal?.aborted;){let{done:pe,value:Re}=await z.read();if(pe)break;_e+=ve.decode(Re,{stream:!0});let Ue=_e.split(`
3
- `);_e=Ue.pop()||"";let Me="",we="",Ae="";for(let X of Ue)if(X.startsWith("event: "))Me=X.slice(7).trim();else if(X.startsWith("data: "))we+=(we?`
4
- `:"")+X.slice(6);else if(X.startsWith("id: "))Ae=X.slice(4).trim();else if(X===""&&(we||Me)){if(Ae&&(Ee=Ae),Me==="message"&&we)try{let Se=JSON.parse(we),{decrypted:He,failedIds:Ge}=await this._decryptMessages([Se]);for(let st of Ge)try{await this.markRead(st);}catch{}He.length>0&&(J=0,$e=0,await qe(He));}catch{}else if(Me==="reconnect")break;Me="",we="",Ae="";}}}finally{z.releaseLock(),clearTimeout(ue);}return $e=0,!0}catch{return $e++,false}},Ie=async()=>{for(;m&&!t.signal?.aborted;){let he=await Le();if(!m||t.signal?.aborted)break;if(!he){if($e>=3){De();return}let j=Math.min(1e3*Math.pow(2,$e-1),4e3);await new Promise(P=>setTimeout(P,j));continue}await new Promise(j=>setTimeout(j,500));}},Je=this.longPoll,De=async()=>{if(!m||t.signal?.aborted){be.stop();return}try{let he=await this.receive({since:M,from:t.from,threadId:t.threadId,messageType:t.messageType,unreadOnly:y,limit:50});he.length>0?(J=0,f&&(O=Math.max(i/2,500)),await qe(he)):(J++,f&&J>3&&!Je&&(O=Math.min(O*1.5,i*4)));}catch(he){n&&n(he instanceof Error?he:new Error(String(he))),O=Math.min(O*2,i*8);}m&&!t.signal?.aborted&&(V=setTimeout(De,Je?100:O));};return this._transportPrefs.includes("sse")?Ie():De(),be}async*messages(e={}){let t=[],n=null,i=false,f=this.listen(d=>{t.push(d),n&&(n(),n=null);},{...e,autoMarkRead:e.autoMarkRead!==false});e.signal?.addEventListener("abort",()=>{i=true,f.stop(),n&&(n(),n=null);});try{for(;!i&&!e.signal?.aborted;)t.length>0?yield t.shift():await new Promise(d=>{n=d;});}finally{f.stop();}}stopAll(){for(let e of this._listeners)e.stop();this._listeners.clear(),this._rpcListener&&(this._rpcListener.stop(),this._rpcListener=null);for(let[e,t]of this._rpcPending)clearTimeout(t.timer),t.reject(new Error("Agent stopped"));this._rpcPending.clear(),this.disableCoverTraffic();}async invoke(e,t,n={},i=3e4){let f=`rpc-${Date.now()}-${Math.random().toString(36).slice(2,10)}`;return new Promise(async(d,y)=>{let _=setTimeout(()=>{this._rpcPending.delete(f),y(new Error(`RPC timeout: ${t}@${e} after ${i}ms`));},i);this._rpcPending.set(f,{resolve:d,reject:y,timer:_});try{await this.send(e,JSON.stringify({jsonrpc:"2.0",method:t,params:n,id:f}),{messageType:"rpc-request",threadId:f});}catch(K){clearTimeout(_),this._rpcPending.delete(f),y(K);}})}onInvoke(e,t){this._rpcHandlers.set(e,t),this._ensureRpcListener();}offInvoke(e){this._rpcHandlers.delete(e),this._rpcHandlers.size===0&&this._rpcListener&&(this._rpcListener.stop(),this._rpcListener=null);}_ensureRpcListener(){this._rpcListener||(this._rpcListener=this.listen(async e=>{try{let t=JSON.parse(e.content);if(t.jsonrpc!=="2.0")return;if(t.id&&(t.result!==void 0||t.error)){let n=this._rpcPending.get(t.id);n&&(clearTimeout(n.timer),this._rpcPending.delete(t.id),t.error?n.reject(new Error(t.error.message||"RPC error")):n.resolve(t.result));return}if(t.method&&t.id){let n=this._rpcHandlers.get(t.method);if(!n){await this.send(e.from,JSON.stringify({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Method not found: ${t.method}`}}),{messageType:"rpc-response",threadId:t.id});return}try{let i=await n(t.params||{},e.from);await this.send(e.from,JSON.stringify({jsonrpc:"2.0",id:t.id,result:i}),{messageType:"rpc-response",threadId:t.id});}catch(i){await this.send(e.from,JSON.stringify({jsonrpc:"2.0",id:t.id,error:{code:-32e3,message:i.message||"Handler error"}}),{messageType:"rpc-response",threadId:t.id});}}}catch{}},{interval:500,adaptive:false,heartbeat:false}));}async sendDirect(e,t,n={}){try{let f=await this.getIdentity(e);if(f){let d=await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${e}`,{headers:{"X-Agent-Key":this.apiKey}});if(d.ok){let _=(await d.json()).webhook_url;if(_){let K=U.default.randomBytes(U.default.box.nonceLength),m=(0,g.decodeBase64)(f.encryption_public_key),O=(0,g.decodeUTF8)(t),J=U.default.box(O,K,m,this.encryptionKeyPair.secretKey),M=JSON.stringify({from:this.did,to:e,ciphertext:(0,g.encodeBase64)(J),nonce:(0,g.encodeBase64)(K),timestamp:new Date().toISOString(),message_type:n.messageType||"text",thread_id:n.threadId}),V=U.default.sign.detached((0,g.decodeUTF8)(M),this.signingKeyPair.secretKey);if((await this._timedFetch(_,{method:"POST",headers:{"Content-Type":"application/json","X-Voidly-Signature":`sha256=${(0,g.encodeBase64)(V)}`,"X-Voidly-Sender":this.did},body:M})).ok){let be=new Date;return {id:`direct-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,from:this.did,to:e,timestamp:be.toISOString(),expiresAt:new Date(be.getTime()+864e5).toISOString(),encrypted:!0,clientSide:!0,direct:!0}}}}}}catch{}return {...await this.send(e,t,n),direct:false}}enableCoverTraffic(e={}){this.disableCoverTraffic();let t=e.intervalMs||3e4,n=async()=>{try{let f=U.default.randomBytes(128+Math.floor(Math.random()*384));await this.send(this.did,(0,g.encodeBase64)(f),{messageType:"ping",ttl:60});}catch{}},i=()=>{let f=t*(.5+Math.random());this._coverTrafficTimer=setTimeout(async()=>{await n(),this._coverTrafficTimer!==null&&i();},f);};i();}disableCoverTraffic(){this._coverTrafficTimer!==null&&(clearTimeout(this._coverTrafficTimer),this._coverTrafficTimer=null);}async _resilientFetch(e,t){let n=[this.baseUrl,...this.fallbackRelays],i=null;for(let f of n)try{let d=await this._timedFetch(`${f}${e}`,t);if(d.ok||d.status>=400&&d.status<500&&d.status!==429)return d;if(d.status===429){let y=d.headers.get("Retry-After"),_=y?Math.min(parseInt(y,10)*1e3,5e3):1e3;await new Promise(K=>setTimeout(K,_));}}catch(d){i=d instanceof Error?d:new Error(String(d));}throw i||new Error("All relays failed")}conversation(e,t){let n=t||`conv-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=`${e}:${n}`;if(this._conversations.has(i))return this._conversations.get(i);let f=new ar(this,e,n);return this._conversations.set(i,f),f}async _timedFetch(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);try{return await fetch(e,{...t,signal:n.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new Error(`Request timed out after ${this.timeout}ms: ${e.replace(this.baseUrl,"")}`):f}finally{clearTimeout(i);}}async _autoPinKeys(e){if(!this._pinnedDids.has(e)){this._pinnedDids.add(e);try{let t=await this.pinKeys(e);t.key_changed&&t.warning&&console.warn(`[voidly] \u26A0 Key change detected for ${e}: ${t.warning}`);}catch{}}}async _fetchWithRetry(e,t,n={}){let i=n.maxRetries??3,f=n.baseDelay??500,d=n.maxDelay??1e4,y=null;for(let _=0;_<=i;_++){try{let K=await this._timedFetch(e,t);if(K.ok)return await K.json();let m=await K.json().catch(()=>({})),O=m.error?.message||m.error||K.statusText;if(K.status>=400&&K.status<500)throw new Error(`Send failed (${K.status}): ${O}`);y=new Error(`Send failed (${K.status}): ${O}`);}catch(K){if(K instanceof Error&&K.message.startsWith("Send failed (4"))throw K;y=K instanceof Error?K:new Error(String(K));}if(_<i){let m=Math.min(f*Math.pow(2,_),d)*(.5+Math.random()*.5);await new Promise(O=>setTimeout(O,m));}}throw y||new Error("Send failed after retries")}async drainQueue(){let e=0,t=0,n=[];for(let i of this._offlineQueue){if(Date.now()-i.timestamp>864e5){t++;continue}try{await this.send(i.recipientDid,i.message,i.options),e++;}catch{n.push(i),t++;}}return this._offlineQueue=n,{sent:e,failed:t,remaining:n.length}}get queueLength(){return this._offlineQueue.length}threatModel(){return {relayCanSee:["Your DID (public identifier)","Recipient DIDs (relay needs them for routing)",...this.jitterMs>0?["Approximate timing (jittered timestamps)"]:["When you message (timestamps)"],...this.sealedSender?[]:["Message types, thread IDs, content types (sent in cleartext without sealed sender)"],"Channel membership (but NOT channel message content with client-side encryption)","Capability registrations","Approximate message size (even with padding, bounded to power-of-2)"],relayCannotSee:["Message content (E2E encrypted \u2014 nacl.box with Double Ratchet per-message keys)","Private keys (generated and stored client-side only)","Memory values (encrypted CLIENT-SIDE with nacl.secretbox before relay storage)","Past message keys (forward secrecy \u2014 hash ratchet + DH ratchet, old keys deleted)","Future message keys (post-compromise recovery via DH ratchet \u2014 compromise heals after one round-trip)","Channel message content (client-side nacl.secretbox encryption \u2014 relay stores only ciphertext)",...this.sealedSender?['Sender identity (sealed inside ciphertext \u2014 relay stores "sealed" not your DID)',"Message types, thread IDs, reply chains (packed inside ciphertext in v3)","Message count (not incremented for sealed senders)"]:[],...this.deniable?["Who authored a message (HMAC is symmetric \u2014 either party could have produced it)"]:[]],protections:[...this.doubleRatchet?["Double Ratchet (Signal Protocol) \u2014 DH ratchet for post-compromise recovery + hash ratchet for forward secrecy"]:["Hash ratchet forward secrecy \u2014 per-message key derivation, old keys deleted"],...this.postQuantum&&this.mlkemPublicKey?["ML-KEM-768 + X25519 hybrid key exchange (NIST FIPS 203 post-quantum, harvest-now-decrypt-later resistant)"]:[],"X3DH async key agreement (signed prekeys + one-time prekeys for offline session establishment)","X25519 key exchange + XSalsa20-Poly1305 authenticated encryption",...this.deniable?["Deniable authentication (HMAC-SHA256 with shared DH secret \u2014 both parties can produce the MAC)"]:["Ed25519 signatures on every message (envelope + ciphertext hash)"],"TOFU key pinning (MitM detection on key change)","Client-side memory encryption (relay never sees plaintext values)","Client-side channel encryption (nacl.secretbox \u2014 relay never sees channel plaintext)","Protocol version header (deterministic padding/sealing/ratchet detection, no heuristics)","Identity cache (reduced key lookups, 5-min TTL)","Message deduplication (track seen message IDs)","Request timeouts (AbortController on all HTTP, configurable)","Request validation (fromCredentials validates key sizes and format)",...this.paddingEnabled?["Message padding to power-of-2 boundary (traffic analysis resistance)"]:[],...this.sealedSender?["Sealed sender (relay cannot see who sent a message)","Metadata privacy (v3 \u2014 thread_id, message_type, reply_to packed inside ciphertext, stripped from relay storage)"]:[],...this.requireSignatures?["Strict signature enforcement (reject unsigned/invalid messages)"]:[],...this.fallbackRelays.length>0?[`Multi-relay fallback (${this.fallbackRelays.length} backup relays \u2014 receive, discover, identity all use fallbacks)`]:[],...this.jitterMs>0?[`Timing jitter (random ${this.jitterMs}ms delay \u2014 metadata timing protection)`]:[],...this._transportPrefs.includes("sse")?["SSE streaming transport (real-time push delivery from relay)"]:[],...this.longPoll?["Long-poll transport (25s server-held connection \u2014 near-real-time delivery)"]:[],...this._persistMode!=="memory"?[`Ratchet state auto-persistence (${this._persistMode} backend \u2014 survives process restart)`]:[],...this._coverTrafficTimer!==null?["Cover traffic (encrypted noise at random intervals \u2014 traffic analysis resistance)"]:[],"Agent RPC (invoke/onInvoke \u2014 synchronous function calls between agents)","P2P direct send (bypass relay via webhook \u2014 true peer-to-peer when possible)","Resilient operations (receive, discover, identity \u2014 all try fallback relays)","Auto-retry with exponential backoff","Offline message queue","did:key interoperability (W3C standard DID format)"],gaps:[...!this.postQuantum||!this.mlkemPublicKey?["No post-quantum protection \u2014 enable postQuantum option and re-register"]:[],...this.sealedSender?["Relay sees to_did (needed for routing) but NOT from_did, thread_id, or message_type"]:["Relay sees from_did, to_did, thread_id, message_type in cleartext \u2014 enable sealedSender to strip metadata"],"Relay sees channel membership, task delegation, trust scores (social graph)",...this.fallbackRelays.length===0?["Single relay with no fallbacks \u2014 configure fallbackRelays for resilience"]:[],...this._persistMode==="memory"?["Ratchet state is in-memory (lost on process restart \u2014 use persist option or exportCredentials)"]:[],...this.deniable?[]:["Ed25519 signatures are non-repudiable \u2014 enable deniable option for HMAC auth"],...this.doubleRatchet?[]:["Hash ratchet only \u2014 enable doubleRatchet option for post-compromise recovery"],...this.jitterMs===0?["No timing jitter \u2014 enable jitterMs option for metadata protection"]:[],...this._coverTrafficTimer===null?["No cover traffic \u2014 call enableCoverTraffic() to resist traffic analysis"]:[]]}}},ar=class{constructor(e,t,n){this._lastMessageId=null;this._messageHistory=[];this._listener=null;this._replyHandlers=[];this.agent=e,this.peerDid=t,this.threadId=n;}async say(e,t){let n=await this.agent.send(this.peerDid,e,{...t,threadId:this.threadId,replyTo:this._lastMessageId||void 0});return this._lastMessageId=n.id,this._messageHistory.length>=1e3&&this._messageHistory.splice(0,this._messageHistory.length-999),this._messageHistory.push({id:n.id,from:this.agent.did,content:e,timestamp:n.timestamp,signatureValid:true,messageType:t?.messageType||"text"}),n}async history(e){let t=await this.agent.receive({threadId:this.threadId,from:this.peerDid,limit:e?.limit||100}),n=[...this._messageHistory,...t.map(f=>({id:f.id,from:f.from,content:f.content,timestamp:f.timestamp,signatureValid:f.signatureValid,messageType:f.messageType}))],i=new Set;return n.filter(f=>i.has(f.id)?false:(i.add(f.id),true)).sort((f,d)=>new Date(f.timestamp).getTime()-new Date(d.timestamp).getTime())}onReply(e){this._replyHandlers.push(e),this._listener||(this._listener=this.agent.listen(async t=>{this._messageHistory.push({id:t.id,from:t.from,content:t.content,timestamp:t.timestamp,signatureValid:t.signatureValid,messageType:t.messageType}),this._lastMessageId=t.id;for(let n of this._replyHandlers)try{await n(t);}catch{}},{from:this.peerDid,threadId:this.threadId,autoMarkRead:true}));}async waitForReply(e=3e4){return new Promise((t,n)=>{let i=false,f=null,d=()=>{i=true,f&&(clearTimeout(f),f=null);},y=setTimeout(()=>{i||(d(),n(new Error(`No reply received within ${e}ms`)));},e),_=async()=>{if(!i){try{let K=await this.agent.receive({from:this.peerDid,threadId:this.threadId,unreadOnly:!0,limit:1});if(K.length>0&&!i){clearTimeout(y),d();let m=K[0];this._messageHistory.length>=1e3&&this._messageHistory.splice(0,this._messageHistory.length-999),this._messageHistory.push({id:m.id,from:m.from,content:m.content,timestamp:m.timestamp,signatureValid:m.signatureValid,messageType:m.messageType}),this._lastMessageId=m.id,await this.agent.markRead(m.id).catch(()=>{}),t(m);return}}catch(K){if(!i){clearTimeout(y),d(),n(K instanceof Error?K:new Error(String(K)));return}}i||(f=setTimeout(_,1500));}};_();})}close(){this._listener&&(this._listener.stop(),this._listener=null),this._replyHandlers=[];}get length(){return this._messageHistory.length}get lastMessage(){return this._messageHistory.length>0?this._messageHistory[this._messageHistory.length-1]:null}};var export_decodeBase64=g.decodeBase64;var export_decodeUTF8=g.decodeUTF8;var export_encodeBase64=g.encodeBase64;var export_encodeUTF8=g.encodeUTF8;var export_nacl=U.default;/*! Bundled license information:
2
+ var hn=Object.create;var gr=Object.defineProperty;var yn=Object.getOwnPropertyDescriptor;var un=Object.getOwnPropertyNames;var pn=Object.getPrototypeOf,gn=Object.prototype.hasOwnProperty;var Yt=(a=>typeof require$1<"u"?require$1:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require$1<"u"?require$1:e)[t]}):a)(function(a){if(typeof require$1<"u")return require$1.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var mr=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var mn=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of un(e))!gn.call(a,i)&&i!==t&&gr(a,i,{get:()=>e[i],enumerable:!(n=yn(e,i))||n.enumerable});return a};var br=(a,e,t)=>(t=a!=null?hn(pn(a)):{},mn(!a||!a.__esModule?gr(t,"default",{value:a,enumerable:true}):t,a));var xr=mr((es,Kt)=>{(function(a){var e=function(s){var c,o=new Float64Array(16);if(s)for(c=0;c<s.length;c++)o[c]=s[c];return o},t=function(){throw new Error("no PRNG")},n=new Uint8Array(16),i=new Uint8Array(32);i[0]=9;var f=e(),d=e([1]),y=e([56129,1]),_=e([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),K=e([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),m=e([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),O=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),J=e([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function M(s,c,o,r){s[c]=o>>24&255,s[c+1]=o>>16&255,s[c+2]=o>>8&255,s[c+3]=o&255,s[c+4]=r>>24&255,s[c+5]=r>>16&255,s[c+6]=r>>8&255,s[c+7]=r&255;}function V(s,c,o,r,l){var u,p=0;for(u=0;u<l;u++)p|=s[c+u]^o[r+u];return (1&p-1>>>8)-1}function H(s,c,o,r){return V(s,c,o,r,16)}function be(s,c,o,r){return V(s,c,o,r,32)}function qe(s,c,o,r){for(var l=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,u=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,p=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,v=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,T=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,L=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,R=c[0]&255|(c[1]&255)<<8|(c[2]&255)<<16|(c[3]&255)<<24,fe=c[4]&255|(c[5]&255)<<8|(c[6]&255)<<16|(c[7]&255)<<24,$=c[8]&255|(c[9]&255)<<8|(c[10]&255)<<16|(c[11]&255)<<24,Y=c[12]&255|(c[13]&255)<<8|(c[14]&255)<<16|(c[15]&255)<<24,Q=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,te=o[16]&255|(o[17]&255)<<8|(o[18]&255)<<16|(o[19]&255)<<24,ee=o[20]&255|(o[21]&255)<<8|(o[22]&255)<<16|(o[23]&255)<<24,G=o[24]&255|(o[25]&255)<<8|(o[26]&255)<<16|(o[27]&255)<<24,W=o[28]&255|(o[29]&255)<<8|(o[30]&255)<<16|(o[31]&255)<<24,Z=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,I=l,N=u,C=p,F=v,B=T,E=L,b=R,x=fe,k=$,w=Y,S=Q,A=te,q=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+q|0,B^=h<<7|h>>>25,h=B+I|0,k^=h<<9|h>>>23,h=k+B|0,q^=h<<13|h>>>19,h=q+k|0,I^=h<<18|h>>>14,h=E+N|0,w^=h<<7|h>>>25,h=w+E|0,re^=h<<9|h>>>23,h=re+w|0,N^=h<<13|h>>>19,h=N+re|0,E^=h<<18|h>>>14,h=S+b|0,se^=h<<7|h>>>25,h=se+S|0,C^=h<<9|h>>>23,h=C+se|0,b^=h<<13|h>>>19,h=b+C|0,S^=h<<18|h>>>14,h=ne+A|0,F^=h<<7|h>>>25,h=F+ne|0,x^=h<<9|h>>>23,h=x+F|0,A^=h<<13|h>>>19,h=A+x|0,ne^=h<<18|h>>>14,h=I+F|0,N^=h<<7|h>>>25,h=N+I|0,C^=h<<9|h>>>23,h=C+N|0,F^=h<<13|h>>>19,h=F+C|0,I^=h<<18|h>>>14,h=E+B|0,b^=h<<7|h>>>25,h=b+E|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,E^=h<<18|h>>>14,h=S+w|0,A^=h<<7|h>>>25,h=A+S|0,k^=h<<9|h>>>23,h=k+A|0,w^=h<<13|h>>>19,h=w+k|0,S^=h<<18|h>>>14,h=ne+se|0,q^=h<<7|h>>>25,h=q+ne|0,re^=h<<9|h>>>23,h=re+q|0,se^=h<<13|h>>>19,h=se+re|0,ne^=h<<18|h>>>14;I=I+l|0,N=N+u|0,C=C+p|0,F=F+v|0,B=B+T|0,E=E+L|0,b=b+R|0,x=x+fe|0,k=k+$|0,w=w+Y|0,S=S+Q|0,A=A+te|0,q=q+ee|0,re=re+G|0,se=se+W|0,ne=ne+Z|0,s[0]=I>>>0&255,s[1]=I>>>8&255,s[2]=I>>>16&255,s[3]=I>>>24&255,s[4]=N>>>0&255,s[5]=N>>>8&255,s[6]=N>>>16&255,s[7]=N>>>24&255,s[8]=C>>>0&255,s[9]=C>>>8&255,s[10]=C>>>16&255,s[11]=C>>>24&255,s[12]=F>>>0&255,s[13]=F>>>8&255,s[14]=F>>>16&255,s[15]=F>>>24&255,s[16]=B>>>0&255,s[17]=B>>>8&255,s[18]=B>>>16&255,s[19]=B>>>24&255,s[20]=E>>>0&255,s[21]=E>>>8&255,s[22]=E>>>16&255,s[23]=E>>>24&255,s[24]=b>>>0&255,s[25]=b>>>8&255,s[26]=b>>>16&255,s[27]=b>>>24&255,s[28]=x>>>0&255,s[29]=x>>>8&255,s[30]=x>>>16&255,s[31]=x>>>24&255,s[32]=k>>>0&255,s[33]=k>>>8&255,s[34]=k>>>16&255,s[35]=k>>>24&255,s[36]=w>>>0&255,s[37]=w>>>8&255,s[38]=w>>>16&255,s[39]=w>>>24&255,s[40]=S>>>0&255,s[41]=S>>>8&255,s[42]=S>>>16&255,s[43]=S>>>24&255,s[44]=A>>>0&255,s[45]=A>>>8&255,s[46]=A>>>16&255,s[47]=A>>>24&255,s[48]=q>>>0&255,s[49]=q>>>8&255,s[50]=q>>>16&255,s[51]=q>>>24&255,s[52]=re>>>0&255,s[53]=re>>>8&255,s[54]=re>>>16&255,s[55]=re>>>24&255,s[56]=se>>>0&255,s[57]=se>>>8&255,s[58]=se>>>16&255,s[59]=se>>>24&255,s[60]=ne>>>0&255,s[61]=ne>>>8&255,s[62]=ne>>>16&255,s[63]=ne>>>24&255;}function Ee(s,c,o,r){for(var l=r[0]&255|(r[1]&255)<<8|(r[2]&255)<<16|(r[3]&255)<<24,u=o[0]&255|(o[1]&255)<<8|(o[2]&255)<<16|(o[3]&255)<<24,p=o[4]&255|(o[5]&255)<<8|(o[6]&255)<<16|(o[7]&255)<<24,v=o[8]&255|(o[9]&255)<<8|(o[10]&255)<<16|(o[11]&255)<<24,T=o[12]&255|(o[13]&255)<<8|(o[14]&255)<<16|(o[15]&255)<<24,L=r[4]&255|(r[5]&255)<<8|(r[6]&255)<<16|(r[7]&255)<<24,R=c[0]&255|(c[1]&255)<<8|(c[2]&255)<<16|(c[3]&255)<<24,fe=c[4]&255|(c[5]&255)<<8|(c[6]&255)<<16|(c[7]&255)<<24,$=c[8]&255|(c[9]&255)<<8|(c[10]&255)<<16|(c[11]&255)<<24,Y=c[12]&255|(c[13]&255)<<8|(c[14]&255)<<16|(c[15]&255)<<24,Q=r[8]&255|(r[9]&255)<<8|(r[10]&255)<<16|(r[11]&255)<<24,te=o[16]&255|(o[17]&255)<<8|(o[18]&255)<<16|(o[19]&255)<<24,ee=o[20]&255|(o[21]&255)<<8|(o[22]&255)<<16|(o[23]&255)<<24,G=o[24]&255|(o[25]&255)<<8|(o[26]&255)<<16|(o[27]&255)<<24,W=o[28]&255|(o[29]&255)<<8|(o[30]&255)<<16|(o[31]&255)<<24,Z=r[12]&255|(r[13]&255)<<8|(r[14]&255)<<16|(r[15]&255)<<24,I=l,N=u,C=p,F=v,B=T,E=L,b=R,x=fe,k=$,w=Y,S=Q,A=te,q=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+q|0,B^=h<<7|h>>>25,h=B+I|0,k^=h<<9|h>>>23,h=k+B|0,q^=h<<13|h>>>19,h=q+k|0,I^=h<<18|h>>>14,h=E+N|0,w^=h<<7|h>>>25,h=w+E|0,re^=h<<9|h>>>23,h=re+w|0,N^=h<<13|h>>>19,h=N+re|0,E^=h<<18|h>>>14,h=S+b|0,se^=h<<7|h>>>25,h=se+S|0,C^=h<<9|h>>>23,h=C+se|0,b^=h<<13|h>>>19,h=b+C|0,S^=h<<18|h>>>14,h=ne+A|0,F^=h<<7|h>>>25,h=F+ne|0,x^=h<<9|h>>>23,h=x+F|0,A^=h<<13|h>>>19,h=A+x|0,ne^=h<<18|h>>>14,h=I+F|0,N^=h<<7|h>>>25,h=N+I|0,C^=h<<9|h>>>23,h=C+N|0,F^=h<<13|h>>>19,h=F+C|0,I^=h<<18|h>>>14,h=E+B|0,b^=h<<7|h>>>25,h=b+E|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,E^=h<<18|h>>>14,h=S+w|0,A^=h<<7|h>>>25,h=A+S|0,k^=h<<9|h>>>23,h=k+A|0,w^=h<<13|h>>>19,h=w+k|0,S^=h<<18|h>>>14,h=ne+se|0,q^=h<<7|h>>>25,h=q+ne|0,re^=h<<9|h>>>23,h=re+q|0,se^=h<<13|h>>>19,h=se+re|0,ne^=h<<18|h>>>14;s[0]=I>>>0&255,s[1]=I>>>8&255,s[2]=I>>>16&255,s[3]=I>>>24&255,s[4]=E>>>0&255,s[5]=E>>>8&255,s[6]=E>>>16&255,s[7]=E>>>24&255,s[8]=S>>>0&255,s[9]=S>>>8&255,s[10]=S>>>16&255,s[11]=S>>>24&255,s[12]=ne>>>0&255,s[13]=ne>>>8&255,s[14]=ne>>>16&255,s[15]=ne>>>24&255,s[16]=b>>>0&255,s[17]=b>>>8&255,s[18]=b>>>16&255,s[19]=b>>>24&255,s[20]=x>>>0&255,s[21]=x>>>8&255,s[22]=x>>>16&255,s[23]=x>>>24&255,s[24]=k>>>0&255,s[25]=k>>>8&255,s[26]=k>>>16&255,s[27]=k>>>24&255,s[28]=w>>>0&255,s[29]=w>>>8&255,s[30]=w>>>16&255,s[31]=w>>>24&255;}function $e(s,c,o,r){qe(s,c,o,r);}function Be(s,c,o,r){Ee(s,c,o,r);}var Me=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function Je(s,c,o,r,l,u,p){var v=new Uint8Array(16),T=new Uint8Array(64),L,R;for(R=0;R<16;R++)v[R]=0;for(R=0;R<8;R++)v[R]=u[R];for(;l>=64;){for($e(T,v,p,Me),R=0;R<64;R++)s[c+R]=o[r+R]^T[R];for(L=1,R=8;R<16;R++)L=L+(v[R]&255)|0,v[R]=L&255,L>>>=8;l-=64,c+=64,r+=64;}if(l>0)for($e(T,v,p,Me),R=0;R<l;R++)s[c+R]=o[r+R]^T[R];return 0}function Le(s,c,o,r,l){var u=new Uint8Array(16),p=new Uint8Array(64),v,T;for(T=0;T<16;T++)u[T]=0;for(T=0;T<8;T++)u[T]=r[T];for(;o>=64;){for($e(p,u,l,Me),T=0;T<64;T++)s[c+T]=p[T];for(v=1,T=8;T<16;T++)v=v+(u[T]&255)|0,u[T]=v&255,v>>>=8;o-=64,c+=64;}if(o>0)for($e(p,u,l,Me),T=0;T<o;T++)s[c+T]=p[T];return 0}function Ve(s,c,o,r,l){var u=new Uint8Array(32);Be(u,r,l,Me);for(var p=new Uint8Array(8),v=0;v<8;v++)p[v]=r[v+16];return Le(s,c,o,p,u)}function he(s,c,o,r,l,u,p){var v=new Uint8Array(32);Be(v,u,p,Me);for(var T=new Uint8Array(8),L=0;L<8;L++)T[L]=u[L+16];return Je(s,c,o,r,l,T,v)}var j=function(s){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var c,o,r,l,u,p,v,T;c=s[0]&255|(s[1]&255)<<8,this.r[0]=c&8191,o=s[2]&255|(s[3]&255)<<8,this.r[1]=(c>>>13|o<<3)&8191,r=s[4]&255|(s[5]&255)<<8,this.r[2]=(o>>>10|r<<6)&7939,l=s[6]&255|(s[7]&255)<<8,this.r[3]=(r>>>7|l<<9)&8191,u=s[8]&255|(s[9]&255)<<8,this.r[4]=(l>>>4|u<<12)&255,this.r[5]=u>>>1&8190,p=s[10]&255|(s[11]&255)<<8,this.r[6]=(u>>>14|p<<2)&8191,v=s[12]&255|(s[13]&255)<<8,this.r[7]=(p>>>11|v<<5)&8065,T=s[14]&255|(s[15]&255)<<8,this.r[8]=(v>>>8|T<<8)&8191,this.r[9]=T>>>5&127,this.pad[0]=s[16]&255|(s[17]&255)<<8,this.pad[1]=s[18]&255|(s[19]&255)<<8,this.pad[2]=s[20]&255|(s[21]&255)<<8,this.pad[3]=s[22]&255|(s[23]&255)<<8,this.pad[4]=s[24]&255|(s[25]&255)<<8,this.pad[5]=s[26]&255|(s[27]&255)<<8,this.pad[6]=s[28]&255|(s[29]&255)<<8,this.pad[7]=s[30]&255|(s[31]&255)<<8;};j.prototype.blocks=function(s,c,o){for(var r=this.fin?0:2048,l,u,p,v,T,L,R,fe,$,Y,Q,te,ee,G,W,Z,I,N,C,F=this.h[0],B=this.h[1],E=this.h[2],b=this.h[3],x=this.h[4],k=this.h[5],w=this.h[6],S=this.h[7],A=this.h[8],q=this.h[9],re=this.r[0],se=this.r[1],ne=this.r[2],h=this.r[3],ae=this.r[4],le=this.r[5],de=this.r[6],ie=this.r[7],oe=this.r[8],ce=this.r[9];o>=16;)l=s[c+0]&255|(s[c+1]&255)<<8,F+=l&8191,u=s[c+2]&255|(s[c+3]&255)<<8,B+=(l>>>13|u<<3)&8191,p=s[c+4]&255|(s[c+5]&255)<<8,E+=(u>>>10|p<<6)&8191,v=s[c+6]&255|(s[c+7]&255)<<8,b+=(p>>>7|v<<9)&8191,T=s[c+8]&255|(s[c+9]&255)<<8,x+=(v>>>4|T<<12)&8191,k+=T>>>1&8191,L=s[c+10]&255|(s[c+11]&255)<<8,w+=(T>>>14|L<<2)&8191,R=s[c+12]&255|(s[c+13]&255)<<8,S+=(L>>>11|R<<5)&8191,fe=s[c+14]&255|(s[c+15]&255)<<8,A+=(R>>>8|fe<<8)&8191,q+=fe>>>5|r,$=0,Y=$,Y+=F*re,Y+=B*(5*ce),Y+=E*(5*oe),Y+=b*(5*ie),Y+=x*(5*de),$=Y>>>13,Y&=8191,Y+=k*(5*le),Y+=w*(5*ae),Y+=S*(5*h),Y+=A*(5*ne),Y+=q*(5*se),$+=Y>>>13,Y&=8191,Q=$,Q+=F*se,Q+=B*re,Q+=E*(5*ce),Q+=b*(5*oe),Q+=x*(5*ie),$=Q>>>13,Q&=8191,Q+=k*(5*de),Q+=w*(5*le),Q+=S*(5*ae),Q+=A*(5*h),Q+=q*(5*ne),$+=Q>>>13,Q&=8191,te=$,te+=F*ne,te+=B*se,te+=E*re,te+=b*(5*ce),te+=x*(5*oe),$=te>>>13,te&=8191,te+=k*(5*ie),te+=w*(5*de),te+=S*(5*le),te+=A*(5*ae),te+=q*(5*h),$+=te>>>13,te&=8191,ee=$,ee+=F*h,ee+=B*ne,ee+=E*se,ee+=b*re,ee+=x*(5*ce),$=ee>>>13,ee&=8191,ee+=k*(5*oe),ee+=w*(5*ie),ee+=S*(5*de),ee+=A*(5*le),ee+=q*(5*ae),$+=ee>>>13,ee&=8191,G=$,G+=F*ae,G+=B*h,G+=E*ne,G+=b*se,G+=x*re,$=G>>>13,G&=8191,G+=k*(5*ce),G+=w*(5*oe),G+=S*(5*ie),G+=A*(5*de),G+=q*(5*le),$+=G>>>13,G&=8191,W=$,W+=F*le,W+=B*ae,W+=E*h,W+=b*ne,W+=x*se,$=W>>>13,W&=8191,W+=k*re,W+=w*(5*ce),W+=S*(5*oe),W+=A*(5*ie),W+=q*(5*de),$+=W>>>13,W&=8191,Z=$,Z+=F*de,Z+=B*le,Z+=E*ae,Z+=b*h,Z+=x*ne,$=Z>>>13,Z&=8191,Z+=k*se,Z+=w*re,Z+=S*(5*ce),Z+=A*(5*oe),Z+=q*(5*ie),$+=Z>>>13,Z&=8191,I=$,I+=F*ie,I+=B*de,I+=E*le,I+=b*ae,I+=x*h,$=I>>>13,I&=8191,I+=k*ne,I+=w*se,I+=S*re,I+=A*(5*ce),I+=q*(5*oe),$+=I>>>13,I&=8191,N=$,N+=F*oe,N+=B*ie,N+=E*de,N+=b*le,N+=x*ae,$=N>>>13,N&=8191,N+=k*h,N+=w*ne,N+=S*se,N+=A*re,N+=q*(5*ce),$+=N>>>13,N&=8191,C=$,C+=F*ce,C+=B*oe,C+=E*ie,C+=b*de,C+=x*le,$=C>>>13,C&=8191,C+=k*ae,C+=w*h,C+=S*ne,C+=A*se,C+=q*re,$+=C>>>13,C&=8191,$=($<<2)+$|0,$=$+Y|0,Y=$&8191,$=$>>>13,Q+=$,F=Y,B=Q,E=te,b=ee,x=G,k=W,w=Z,S=I,A=N,q=C,c+=16,o-=16;this.h[0]=F,this.h[1]=B,this.h[2]=E,this.h[3]=b,this.h[4]=x,this.h[5]=k,this.h[6]=w,this.h[7]=S,this.h[8]=A,this.h[9]=q;},j.prototype.finish=function(s,c){var o=new Uint16Array(10),r,l,u,p;if(this.leftover){for(p=this.leftover,this.buffer[p++]=1;p<16;p++)this.buffer[p]=0;this.fin=1,this.blocks(this.buffer,0,16);}for(r=this.h[1]>>>13,this.h[1]&=8191,p=2;p<10;p++)this.h[p]+=r,r=this.h[p]>>>13,this.h[p]&=8191;for(this.h[0]+=r*5,r=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=r,r=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=r,o[0]=this.h[0]+5,r=o[0]>>>13,o[0]&=8191,p=1;p<10;p++)o[p]=this.h[p]+r,r=o[p]>>>13,o[p]&=8191;for(o[9]-=8192,l=(r^1)-1,p=0;p<10;p++)o[p]&=l;for(l=~l,p=0;p<10;p++)this.h[p]=this.h[p]&l|o[p];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,u=this.h[0]+this.pad[0],this.h[0]=u&65535,p=1;p<8;p++)u=(this.h[p]+this.pad[p]|0)+(u>>>16)|0,this.h[p]=u&65535;s[c+0]=this.h[0]>>>0&255,s[c+1]=this.h[0]>>>8&255,s[c+2]=this.h[1]>>>0&255,s[c+3]=this.h[1]>>>8&255,s[c+4]=this.h[2]>>>0&255,s[c+5]=this.h[2]>>>8&255,s[c+6]=this.h[3]>>>0&255,s[c+7]=this.h[3]>>>8&255,s[c+8]=this.h[4]>>>0&255,s[c+9]=this.h[4]>>>8&255,s[c+10]=this.h[5]>>>0&255,s[c+11]=this.h[5]>>>8&255,s[c+12]=this.h[6]>>>0&255,s[c+13]=this.h[6]>>>8&255,s[c+14]=this.h[7]>>>0&255,s[c+15]=this.h[7]>>>8&255;},j.prototype.update=function(s,c,o){var r,l;if(this.leftover){for(l=16-this.leftover,l>o&&(l=o),r=0;r<l;r++)this.buffer[this.leftover+r]=s[c+r];if(o-=l,c+=l,this.leftover+=l,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0;}if(o>=16&&(l=o-o%16,this.blocks(s,c,l),c+=l,o-=l),o){for(r=0;r<o;r++)this.buffer[this.leftover+r]=s[c+r];this.leftover+=o;}};function P(s,c,o,r,l,u){var p=new j(u);return p.update(o,r,l),p.finish(s,c),0}function xe(s,c,o,r,l,u){var p=new Uint8Array(16);return P(p,0,o,r,l,u),H(s,c,p,0)}function pe(s,c,o,r,l){var u;if(o<32)return -1;for(he(s,0,c,0,o,r,l),P(s,16,s,32,o-32,s),u=0;u<16;u++)s[u]=0;return 0}function D(s,c,o,r,l){var u,p=new Uint8Array(32);if(o<32||(Ve(p,0,32,r,l),xe(c,16,c,32,o-32,p)!==0))return -1;for(he(s,0,c,0,o,r,l),u=0;u<32;u++)s[u]=0;return 0}function z(s,c){var o;for(o=0;o<16;o++)s[o]=c[o]|0;}function ve(s){var c,o,r=1;for(c=0;c<16;c++)o=s[c]+r+65535,r=Math.floor(o/65536),s[c]=o-r*65536;s[0]+=r-1+37*(r-1);}function _e(s,c,o){for(var r,l=~(o-1),u=0;u<16;u++)r=l&(s[u]^c[u]),s[u]^=r,c[u]^=r;}function ye(s,c){var o,r,l,u=e(),p=e();for(o=0;o<16;o++)p[o]=c[o];for(ve(p),ve(p),ve(p),r=0;r<2;r++){for(u[0]=p[0]-65517,o=1;o<15;o++)u[o]=p[o]-65535-(u[o-1]>>16&1),u[o-1]&=65535;u[15]=p[15]-32767-(u[14]>>16&1),l=u[15]>>16&1,u[14]&=65535,_e(p,u,1-l);}for(o=0;o<16;o++)s[2*o]=p[o]&255,s[2*o+1]=p[o]>>8;}function we(s,c){var o=new Uint8Array(32),r=new Uint8Array(32);return ye(o,s),ye(r,c),be(o,0,r,0)}function Se(s){var c=new Uint8Array(32);return ye(c,s),c[0]&1}function Ne(s,c){var o;for(o=0;o<16;o++)s[o]=c[2*o]+(c[2*o+1]<<8);s[15]&=32767;}function Ue(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]+o[r];}function Re(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]-o[r];}function X(s,c,o){var r,l,u=0,p=0,v=0,T=0,L=0,R=0,fe=0,$=0,Y=0,Q=0,te=0,ee=0,G=0,W=0,Z=0,I=0,N=0,C=0,F=0,B=0,E=0,b=0,x=0,k=0,w=0,S=0,A=0,q=0,re=0,se=0,ne=0,h=o[0],ae=o[1],le=o[2],de=o[3],ie=o[4],oe=o[5],ce=o[6],Te=o[7],ue=o[8],Ke=o[9],Pe=o[10],Ae=o[11],je=o[12],Ie=o[13],Fe=o[14],Oe=o[15];r=c[0],u+=r*h,p+=r*ae,v+=r*le,T+=r*de,L+=r*ie,R+=r*oe,fe+=r*ce,$+=r*Te,Y+=r*ue,Q+=r*Ke,te+=r*Pe,ee+=r*Ae,G+=r*je,W+=r*Ie,Z+=r*Fe,I+=r*Oe,r=c[1],p+=r*h,v+=r*ae,T+=r*le,L+=r*de,R+=r*ie,fe+=r*oe,$+=r*ce,Y+=r*Te,Q+=r*ue,te+=r*Ke,ee+=r*Pe,G+=r*Ae,W+=r*je,Z+=r*Ie,I+=r*Fe,N+=r*Oe,r=c[2],v+=r*h,T+=r*ae,L+=r*le,R+=r*de,fe+=r*ie,$+=r*oe,Y+=r*ce,Q+=r*Te,te+=r*ue,ee+=r*Ke,G+=r*Pe,W+=r*Ae,Z+=r*je,I+=r*Ie,N+=r*Fe,C+=r*Oe,r=c[3],T+=r*h,L+=r*ae,R+=r*le,fe+=r*de,$+=r*ie,Y+=r*oe,Q+=r*ce,te+=r*Te,ee+=r*ue,G+=r*Ke,W+=r*Pe,Z+=r*Ae,I+=r*je,N+=r*Ie,C+=r*Fe,F+=r*Oe,r=c[4],L+=r*h,R+=r*ae,fe+=r*le,$+=r*de,Y+=r*ie,Q+=r*oe,te+=r*ce,ee+=r*Te,G+=r*ue,W+=r*Ke,Z+=r*Pe,I+=r*Ae,N+=r*je,C+=r*Ie,F+=r*Fe,B+=r*Oe,r=c[5],R+=r*h,fe+=r*ae,$+=r*le,Y+=r*de,Q+=r*ie,te+=r*oe,ee+=r*ce,G+=r*Te,W+=r*ue,Z+=r*Ke,I+=r*Pe,N+=r*Ae,C+=r*je,F+=r*Ie,B+=r*Fe,E+=r*Oe,r=c[6],fe+=r*h,$+=r*ae,Y+=r*le,Q+=r*de,te+=r*ie,ee+=r*oe,G+=r*ce,W+=r*Te,Z+=r*ue,I+=r*Ke,N+=r*Pe,C+=r*Ae,F+=r*je,B+=r*Ie,E+=r*Fe,b+=r*Oe,r=c[7],$+=r*h,Y+=r*ae,Q+=r*le,te+=r*de,ee+=r*ie,G+=r*oe,W+=r*ce,Z+=r*Te,I+=r*ue,N+=r*Ke,C+=r*Pe,F+=r*Ae,B+=r*je,E+=r*Ie,b+=r*Fe,x+=r*Oe,r=c[8],Y+=r*h,Q+=r*ae,te+=r*le,ee+=r*de,G+=r*ie,W+=r*oe,Z+=r*ce,I+=r*Te,N+=r*ue,C+=r*Ke,F+=r*Pe,B+=r*Ae,E+=r*je,b+=r*Ie,x+=r*Fe,k+=r*Oe,r=c[9],Q+=r*h,te+=r*ae,ee+=r*le,G+=r*de,W+=r*ie,Z+=r*oe,I+=r*ce,N+=r*Te,C+=r*ue,F+=r*Ke,B+=r*Pe,E+=r*Ae,b+=r*je,x+=r*Ie,k+=r*Fe,w+=r*Oe,r=c[10],te+=r*h,ee+=r*ae,G+=r*le,W+=r*de,Z+=r*ie,I+=r*oe,N+=r*ce,C+=r*Te,F+=r*ue,B+=r*Ke,E+=r*Pe,b+=r*Ae,x+=r*je,k+=r*Ie,w+=r*Fe,S+=r*Oe,r=c[11],ee+=r*h,G+=r*ae,W+=r*le,Z+=r*de,I+=r*ie,N+=r*oe,C+=r*ce,F+=r*Te,B+=r*ue,E+=r*Ke,b+=r*Pe,x+=r*Ae,k+=r*je,w+=r*Ie,S+=r*Fe,A+=r*Oe,r=c[12],G+=r*h,W+=r*ae,Z+=r*le,I+=r*de,N+=r*ie,C+=r*oe,F+=r*ce,B+=r*Te,E+=r*ue,b+=r*Ke,x+=r*Pe,k+=r*Ae,w+=r*je,S+=r*Ie,A+=r*Fe,q+=r*Oe,r=c[13],W+=r*h,Z+=r*ae,I+=r*le,N+=r*de,C+=r*ie,F+=r*oe,B+=r*ce,E+=r*Te,b+=r*ue,x+=r*Ke,k+=r*Pe,w+=r*Ae,S+=r*je,A+=r*Ie,q+=r*Fe,re+=r*Oe,r=c[14],Z+=r*h,I+=r*ae,N+=r*le,C+=r*de,F+=r*ie,B+=r*oe,E+=r*ce,b+=r*Te,x+=r*ue,k+=r*Ke,w+=r*Pe,S+=r*Ae,A+=r*je,q+=r*Ie,re+=r*Fe,se+=r*Oe,r=c[15],I+=r*h,N+=r*ae,C+=r*le,F+=r*de,B+=r*ie,E+=r*oe,b+=r*ce,x+=r*Te,k+=r*ue,w+=r*Ke,S+=r*Pe,A+=r*Ae,q+=r*je,re+=r*Ie,se+=r*Fe,ne+=r*Oe,u+=38*N,p+=38*C,v+=38*F,T+=38*B,L+=38*E,R+=38*b,fe+=38*x,$+=38*k,Y+=38*w,Q+=38*S,te+=38*A,ee+=38*q,G+=38*re,W+=38*se,Z+=38*ne,l=1,r=u+l+65535,l=Math.floor(r/65536),u=r-l*65536,r=p+l+65535,l=Math.floor(r/65536),p=r-l*65536,r=v+l+65535,l=Math.floor(r/65536),v=r-l*65536,r=T+l+65535,l=Math.floor(r/65536),T=r-l*65536,r=L+l+65535,l=Math.floor(r/65536),L=r-l*65536,r=R+l+65535,l=Math.floor(r/65536),R=r-l*65536,r=fe+l+65535,l=Math.floor(r/65536),fe=r-l*65536,r=$+l+65535,l=Math.floor(r/65536),$=r-l*65536,r=Y+l+65535,l=Math.floor(r/65536),Y=r-l*65536,r=Q+l+65535,l=Math.floor(r/65536),Q=r-l*65536,r=te+l+65535,l=Math.floor(r/65536),te=r-l*65536,r=ee+l+65535,l=Math.floor(r/65536),ee=r-l*65536,r=G+l+65535,l=Math.floor(r/65536),G=r-l*65536,r=W+l+65535,l=Math.floor(r/65536),W=r-l*65536,r=Z+l+65535,l=Math.floor(r/65536),Z=r-l*65536,r=I+l+65535,l=Math.floor(r/65536),I=r-l*65536,u+=l-1+37*(l-1),l=1,r=u+l+65535,l=Math.floor(r/65536),u=r-l*65536,r=p+l+65535,l=Math.floor(r/65536),p=r-l*65536,r=v+l+65535,l=Math.floor(r/65536),v=r-l*65536,r=T+l+65535,l=Math.floor(r/65536),T=r-l*65536,r=L+l+65535,l=Math.floor(r/65536),L=r-l*65536,r=R+l+65535,l=Math.floor(r/65536),R=r-l*65536,r=fe+l+65535,l=Math.floor(r/65536),fe=r-l*65536,r=$+l+65535,l=Math.floor(r/65536),$=r-l*65536,r=Y+l+65535,l=Math.floor(r/65536),Y=r-l*65536,r=Q+l+65535,l=Math.floor(r/65536),Q=r-l*65536,r=te+l+65535,l=Math.floor(r/65536),te=r-l*65536,r=ee+l+65535,l=Math.floor(r/65536),ee=r-l*65536,r=G+l+65535,l=Math.floor(r/65536),G=r-l*65536,r=W+l+65535,l=Math.floor(r/65536),W=r-l*65536,r=Z+l+65535,l=Math.floor(r/65536),Z=r-l*65536,r=I+l+65535,l=Math.floor(r/65536),I=r-l*65536,u+=l-1+37*(l-1),s[0]=u,s[1]=p,s[2]=v,s[3]=T,s[4]=L,s[5]=R,s[6]=fe,s[7]=$,s[8]=Y,s[9]=Q,s[10]=te,s[11]=ee,s[12]=G,s[13]=W,s[14]=Z,s[15]=I;}function ke(s,c){X(s,c,c);}function He(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=253;r>=0;r--)ke(o,o),r!==2&&r!==4&&X(o,o,c);for(r=0;r<16;r++)s[r]=o[r];}function Ge(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=250;r>=0;r--)ke(o,o),r!==1&&X(o,o,c);for(r=0;r<16;r++)s[r]=o[r];}function st(s,c,o){var r=new Uint8Array(32),l=new Float64Array(80),u,p,v=e(),T=e(),L=e(),R=e(),fe=e(),$=e();for(p=0;p<31;p++)r[p]=c[p];for(r[31]=c[31]&127|64,r[0]&=248,Ne(l,o),p=0;p<16;p++)T[p]=l[p],R[p]=v[p]=L[p]=0;for(v[0]=R[0]=1,p=254;p>=0;--p)u=r[p>>>3]>>>(p&7)&1,_e(v,T,u),_e(L,R,u),Ue(fe,v,L),Re(v,v,L),Ue(L,T,R),Re(T,T,R),ke(R,fe),ke($,v),X(v,L,v),X(L,T,fe),Ue(fe,v,L),Re(v,v,L),ke(T,v),Re(L,R,$),X(v,L,y),Ue(v,v,R),X(L,L,v),X(v,R,$),X(R,T,l),ke(T,fe),_e(v,T,u),_e(L,R,u);for(p=0;p<16;p++)l[p+16]=v[p],l[p+32]=L[p],l[p+48]=T[p],l[p+64]=R[p];var Y=l.subarray(32),Q=l.subarray(16);return He(Y,Y),X(Q,Q,Y),ye(s,Q),0}function bt(s,c){return st(s,c,i)}function or(s,c){return t(c,32),bt(s,c)}function xt(s,c,o){var r=new Uint8Array(32);return st(r,o,c),Be(s,n,r,Me)}var cr=pe,sn=D;function an(s,c,o,r,l,u){var p=new Uint8Array(32);return xt(p,l,u),cr(s,c,o,r,p)}function on(s,c,o,r,l,u){var p=new Uint8Array(32);return xt(p,l,u),sn(s,c,o,r,p)}var fr=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function lr(s,c,o,r){for(var l=new Int32Array(16),u=new Int32Array(16),p,v,T,L,R,fe,$,Y,Q,te,ee,G,W,Z,I,N,C,F,B,E,b,x,k,w,S,A,q=s[0],re=s[1],se=s[2],ne=s[3],h=s[4],ae=s[5],le=s[6],de=s[7],ie=c[0],oe=c[1],ce=c[2],Te=c[3],ue=c[4],Ke=c[5],Pe=c[6],Ae=c[7],je=0;r>=128;){for(B=0;B<16;B++)E=8*B+je,l[B]=o[E+0]<<24|o[E+1]<<16|o[E+2]<<8|o[E+3],u[B]=o[E+4]<<24|o[E+5]<<16|o[E+6]<<8|o[E+7];for(B=0;B<80;B++)if(p=q,v=re,T=se,L=ne,R=h,fe=ae,$=le,Y=de,Q=ie,te=oe,ee=ce,G=Te,W=ue,Z=Ke,I=Pe,N=Ae,b=de,x=Ae,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=(h>>>14|ue<<18)^(h>>>18|ue<<14)^(ue>>>9|h<<23),x=(ue>>>14|h<<18)^(ue>>>18|h<<14)^(h>>>9|ue<<23),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=h&ae^~h&le,x=ue&Ke^~ue&Pe,k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=fr[B*2],x=fr[B*2+1],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=l[B%16],x=u[B%16],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,C=S&65535|A<<16,F=k&65535|w<<16,b=C,x=F,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=(q>>>28|ie<<4)^(ie>>>2|q<<30)^(ie>>>7|q<<25),x=(ie>>>28|q<<4)^(q>>>2|ie<<30)^(q>>>7|ie<<25),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=q&re^q&se^re&se,x=ie&oe^ie&ce^oe&ce,k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,Y=S&65535|A<<16,N=k&65535|w<<16,b=L,x=G,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=C,x=F,k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,L=S&65535|A<<16,G=k&65535|w<<16,re=p,se=v,ne=T,h=L,ae=R,le=fe,de=$,q=Y,oe=Q,ce=te,Te=ee,ue=G,Ke=W,Pe=Z,Ae=I,ie=N,B%16===15)for(E=0;E<16;E++)b=l[E],x=u[E],k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=l[(E+9)%16],x=u[(E+9)%16],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,C=l[(E+1)%16],F=u[(E+1)%16],b=(C>>>1|F<<31)^(C>>>8|F<<24)^C>>>7,x=(F>>>1|C<<31)^(F>>>8|C<<24)^(F>>>7|C<<25),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,C=l[(E+14)%16],F=u[(E+14)%16],b=(C>>>19|F<<13)^(F>>>29|C<<3)^C>>>6,x=(F>>>19|C<<13)^(C>>>29|F<<3)^(F>>>6|C<<26),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,l[E]=S&65535|A<<16,u[E]=k&65535|w<<16;b=q,x=ie,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[0],x=c[0],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[0]=q=S&65535|A<<16,c[0]=ie=k&65535|w<<16,b=re,x=oe,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[1],x=c[1],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[1]=re=S&65535|A<<16,c[1]=oe=k&65535|w<<16,b=se,x=ce,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[2],x=c[2],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[2]=se=S&65535|A<<16,c[2]=ce=k&65535|w<<16,b=ne,x=Te,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[3],x=c[3],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[3]=ne=S&65535|A<<16,c[3]=Te=k&65535|w<<16,b=h,x=ue,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[4],x=c[4],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[4]=h=S&65535|A<<16,c[4]=ue=k&65535|w<<16,b=ae,x=Ke,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[5],x=c[5],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[5]=ae=S&65535|A<<16,c[5]=Ke=k&65535|w<<16,b=le,x=Pe,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[6],x=c[6],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[6]=le=S&65535|A<<16,c[6]=Pe=k&65535|w<<16,b=de,x=Ae,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=s[7],x=c[7],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,s[7]=de=S&65535|A<<16,c[7]=Ae=k&65535|w<<16,je+=128,r-=128;}return r}function tt(s,c,o){var r=new Int32Array(8),l=new Int32Array(8),u=new Uint8Array(256),p,v=o;for(r[0]=1779033703,r[1]=3144134277,r[2]=1013904242,r[3]=2773480762,r[4]=1359893119,r[5]=2600822924,r[6]=528734635,r[7]=1541459225,l[0]=4089235720,l[1]=2227873595,l[2]=4271175723,l[3]=1595750129,l[4]=2917565137,l[5]=725511199,l[6]=4215389547,l[7]=327033209,lr(r,l,c,o),o%=128,p=0;p<o;p++)u[p]=c[v-o+p];for(u[o]=128,o=256-128*(o<112?1:0),u[o-9]=0,M(u,o-8,v/536870912|0,v<<3),lr(r,l,u,o),p=0;p<8;p++)M(s,8*p,r[p],l[p]);return 0}function _t(s,c){var o=e(),r=e(),l=e(),u=e(),p=e(),v=e(),T=e(),L=e(),R=e();Re(o,s[1],s[0]),Re(R,c[1],c[0]),X(o,o,R),Ue(r,s[0],s[1]),Ue(R,c[0],c[1]),X(r,r,R),X(l,s[3],c[3]),X(l,l,K),X(u,s[2],c[2]),Ue(u,u,u),Re(p,r,o),Re(v,u,l),Ue(T,u,l),Ue(L,r,o),X(s[0],p,v),X(s[1],L,T),X(s[2],T,v),X(s[3],p,L);}function dr(s,c,o){var r;for(r=0;r<4;r++)_e(s[r],c[r],o);}function Bt(s,c){var o=e(),r=e(),l=e();He(l,c[2]),X(o,c[0],l),X(r,c[1],l),ye(s,r),s[31]^=Se(o)<<7;}function Lt(s,c,o){var r,l;for(z(s[0],f),z(s[1],d),z(s[2],d),z(s[3],f),l=255;l>=0;--l)r=o[l/8|0]>>(l&7)&1,dr(s,c,r),_t(c,s),_t(s,s),dr(s,c,r);}function wt(s,c){var o=[e(),e(),e(),e()];z(o[0],m),z(o[1],O),z(o[2],d),X(o[3],m,O),Lt(s,o,c);}function Dt(s,c,o){var r=new Uint8Array(64),l=[e(),e(),e(),e()],u;for(o||t(c,32),tt(r,c,32),r[0]&=248,r[31]&=127,r[31]|=64,wt(l,r),Bt(s,l),u=0;u<32;u++)c[u+32]=s[u];return 0}var vt=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function Nt(s,c){var o,r,l,u;for(r=63;r>=32;--r){for(o=0,l=r-32,u=r-12;l<u;++l)c[l]+=o-16*c[r]*vt[l-(r-32)],o=Math.floor((c[l]+128)/256),c[l]-=o*256;c[l]+=o,c[r]=0;}for(o=0,l=0;l<32;l++)c[l]+=o-(c[31]>>4)*vt[l],o=c[l]>>8,c[l]&=255;for(l=0;l<32;l++)c[l]-=o*vt[l];for(r=0;r<32;r++)c[r+1]+=c[r]>>8,s[r]=c[r]&255;}function Ht(s){var c=new Float64Array(64),o;for(o=0;o<64;o++)c[o]=s[o];for(o=0;o<64;o++)s[o]=0;Nt(s,c);}function hr(s,c,o,r){var l=new Uint8Array(64),u=new Uint8Array(64),p=new Uint8Array(64),v,T,L=new Float64Array(64),R=[e(),e(),e(),e()];tt(l,r,32),l[0]&=248,l[31]&=127,l[31]|=64;var fe=o+64;for(v=0;v<o;v++)s[64+v]=c[v];for(v=0;v<32;v++)s[32+v]=l[32+v];for(tt(p,s.subarray(32),o+32),Ht(p),wt(R,p),Bt(s,R),v=32;v<64;v++)s[v]=r[v];for(tt(u,s,o+64),Ht(u),v=0;v<64;v++)L[v]=0;for(v=0;v<32;v++)L[v]=p[v];for(v=0;v<32;v++)for(T=0;T<32;T++)L[v+T]+=u[v]*l[T];return Nt(s.subarray(32),L),fe}function cn(s,c){var o=e(),r=e(),l=e(),u=e(),p=e(),v=e(),T=e();return z(s[2],d),Ne(s[1],c),ke(l,s[1]),X(u,l,_),Re(l,l,s[2]),Ue(u,s[2],u),ke(p,u),ke(v,p),X(T,v,p),X(o,T,l),X(o,o,u),Ge(o,o),X(o,o,l),X(o,o,u),X(o,o,u),X(s[0],o,u),ke(r,s[0]),X(r,r,u),we(r,l)&&X(s[0],s[0],J),ke(r,s[0]),X(r,r,u),we(r,l)?-1:(Se(s[0])===c[31]>>7&&Re(s[0],f,s[0]),X(s[3],s[0],s[1]),0)}function zt(s,c,o,r){var l,u=new Uint8Array(32),p=new Uint8Array(64),v=[e(),e(),e(),e()],T=[e(),e(),e(),e()];if(o<64||cn(T,r))return -1;for(l=0;l<o;l++)s[l]=c[l];for(l=0;l<32;l++)s[l+32]=r[l];if(tt(p,s,o),Ht(p),Lt(v,T,p),wt(T,c.subarray(32)),_t(v,T),Bt(u,v),o-=64,be(c,0,u,0)){for(l=0;l<o;l++)s[l]=0;return -1}for(l=0;l<o;l++)s[l]=c[l+64];return o}var Xt=32,St=24,dt=32,it=16,ht=32,kt=32,yt=32,ut=32,qt=32,yr=St,fn=dt,ln=it,Ye=64,rt=32,at=64,Jt=32,Vt=64;a.lowlevel={crypto_core_hsalsa20:Be,crypto_stream_xor:he,crypto_stream:Ve,crypto_stream_salsa20_xor:Je,crypto_stream_salsa20:Le,crypto_onetimeauth:P,crypto_onetimeauth_verify:xe,crypto_verify_16:H,crypto_verify_32:be,crypto_secretbox:pe,crypto_secretbox_open:D,crypto_scalarmult:st,crypto_scalarmult_base:bt,crypto_box_beforenm:xt,crypto_box_afternm:cr,crypto_box:an,crypto_box_open:on,crypto_box_keypair:or,crypto_hash:tt,crypto_sign:hr,crypto_sign_keypair:Dt,crypto_sign_open:zt,crypto_secretbox_KEYBYTES:Xt,crypto_secretbox_NONCEBYTES:St,crypto_secretbox_ZEROBYTES:dt,crypto_secretbox_BOXZEROBYTES:it,crypto_scalarmult_BYTES:ht,crypto_scalarmult_SCALARBYTES:kt,crypto_box_PUBLICKEYBYTES:yt,crypto_box_SECRETKEYBYTES:ut,crypto_box_BEFORENMBYTES:qt,crypto_box_NONCEBYTES:yr,crypto_box_ZEROBYTES:fn,crypto_box_BOXZEROBYTES:ln,crypto_sign_BYTES:Ye,crypto_sign_PUBLICKEYBYTES:rt,crypto_sign_SECRETKEYBYTES:at,crypto_sign_SEEDBYTES:Jt,crypto_hash_BYTES:Vt,gf:e,D:_,L:vt,pack25519:ye,unpack25519:Ne,M:X,A:Ue,S:ke,Z:Re,pow2523:Ge,add:_t,set25519:z,modL:Nt,scalarmult:Lt,scalarbase:wt};function ur(s,c){if(s.length!==Xt)throw new Error("bad key size");if(c.length!==St)throw new Error("bad nonce size")}function dn(s,c){if(s.length!==yt)throw new Error("bad public key size");if(c.length!==ut)throw new Error("bad secret key size")}function ze(){for(var s=0;s<arguments.length;s++)if(!(arguments[s]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function pr(s){for(var c=0;c<s.length;c++)s[c]=0;}a.randomBytes=function(s){var c=new Uint8Array(s);return t(c,s),c},a.secretbox=function(s,c,o){ze(s,c,o),ur(o,c);for(var r=new Uint8Array(dt+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+dt]=s[u];return pe(l,r,r.length,c,o),l.subarray(it)},a.secretbox.open=function(s,c,o){ze(s,c,o),ur(o,c);for(var r=new Uint8Array(it+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+it]=s[u];return r.length<32||D(l,r,r.length,c,o)!==0?null:l.subarray(dt)},a.secretbox.keyLength=Xt,a.secretbox.nonceLength=St,a.secretbox.overheadLength=it,a.scalarMult=function(s,c){if(ze(s,c),s.length!==kt)throw new Error("bad n size");if(c.length!==ht)throw new Error("bad p size");var o=new Uint8Array(ht);return st(o,s,c),o},a.scalarMult.base=function(s){if(ze(s),s.length!==kt)throw new Error("bad n size");var c=new Uint8Array(ht);return bt(c,s),c},a.scalarMult.scalarLength=kt,a.scalarMult.groupElementLength=ht,a.box=function(s,c,o,r){var l=a.box.before(o,r);return a.secretbox(s,c,l)},a.box.before=function(s,c){ze(s,c),dn(s,c);var o=new Uint8Array(qt);return xt(o,s,c),o},a.box.after=a.secretbox,a.box.open=function(s,c,o,r){var l=a.box.before(o,r);return a.secretbox.open(s,c,l)},a.box.open.after=a.secretbox.open,a.box.keyPair=function(){var s=new Uint8Array(yt),c=new Uint8Array(ut);return or(s,c),{publicKey:s,secretKey:c}},a.box.keyPair.fromSecretKey=function(s){if(ze(s),s.length!==ut)throw new Error("bad secret key size");var c=new Uint8Array(yt);return bt(c,s),{publicKey:c,secretKey:new Uint8Array(s)}},a.box.publicKeyLength=yt,a.box.secretKeyLength=ut,a.box.sharedKeyLength=qt,a.box.nonceLength=yr,a.box.overheadLength=a.secretbox.overheadLength,a.sign=function(s,c){if(ze(s,c),c.length!==at)throw new Error("bad secret key size");var o=new Uint8Array(Ye+s.length);return hr(o,s,s.length,c),o},a.sign.open=function(s,c){if(ze(s,c),c.length!==rt)throw new Error("bad public key size");var o=new Uint8Array(s.length),r=zt(o,s,s.length,c);if(r<0)return null;for(var l=new Uint8Array(r),u=0;u<l.length;u++)l[u]=o[u];return l},a.sign.detached=function(s,c){for(var o=a.sign(s,c),r=new Uint8Array(Ye),l=0;l<r.length;l++)r[l]=o[l];return r},a.sign.detached.verify=function(s,c,o){if(ze(s,c,o),c.length!==Ye)throw new Error("bad signature size");if(o.length!==rt)throw new Error("bad public key size");var r=new Uint8Array(Ye+s.length),l=new Uint8Array(Ye+s.length),u;for(u=0;u<Ye;u++)r[u]=c[u];for(u=0;u<s.length;u++)r[u+Ye]=s[u];return zt(l,r,r.length,o)>=0},a.sign.keyPair=function(){var s=new Uint8Array(rt),c=new Uint8Array(at);return Dt(s,c),{publicKey:s,secretKey:c}},a.sign.keyPair.fromSecretKey=function(s){if(ze(s),s.length!==at)throw new Error("bad secret key size");for(var c=new Uint8Array(rt),o=0;o<c.length;o++)c[o]=s[32+o];return {publicKey:c,secretKey:new Uint8Array(s)}},a.sign.keyPair.fromSeed=function(s){if(ze(s),s.length!==Jt)throw new Error("bad seed size");for(var c=new Uint8Array(rt),o=new Uint8Array(at),r=0;r<32;r++)o[r]=s[r];return Dt(c,o,true),{publicKey:c,secretKey:o}},a.sign.publicKeyLength=rt,a.sign.secretKeyLength=at,a.sign.seedLength=Jt,a.sign.signatureLength=Ye,a.hash=function(s){ze(s);var c=new Uint8Array(Vt);return tt(c,s,s.length),c},a.hash.hashLength=Vt,a.verify=function(s,c){return ze(s,c),s.length===0||c.length===0||s.length!==c.length?false:V(s,0,c,0,s.length)===0},a.setPRNG=function(s){t=s;},(function(){var s=typeof self<"u"?self.crypto||self.msCrypto:null;if(s&&s.getRandomValues){var c=65536;a.setPRNG(function(o,r){var l,u=new Uint8Array(r);for(l=0;l<r;l+=c)s.getRandomValues(u.subarray(l,l+Math.min(r-l,c)));for(l=0;l<r;l++)o[l]=u[l];pr(u);});}else typeof Yt<"u"&&(s=Yt("crypto"),s&&s.randomBytes&&a.setPRNG(function(o,r){var l,u=s.randomBytes(r);for(l=0;l<r;l++)o[l]=u[l];pr(u);}));})();})(typeof Kt<"u"&&Kt.exports?Kt.exports:self.nacl=self.nacl||{});});var wr=mr((_r,Pt)=>{(function(a,e){typeof Pt<"u"&&Pt.exports?Pt.exports=e():(a.nacl||(a.nacl={}),a.nacl.util=e());})(_r,function(){var a={};function e(t){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(t))throw new TypeError("invalid encoding")}return a.decodeUTF8=function(t){if(typeof t!="string")throw new TypeError("expected string");var n,i=unescape(encodeURIComponent(t)),f=new Uint8Array(i.length);for(n=0;n<i.length;n++)f[n]=i.charCodeAt(n);return f},a.encodeUTF8=function(t){var n,i=[];for(n=0;n<t.length;n++)i.push(String.fromCharCode(t[n]));return decodeURIComponent(escape(i.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(a.encodeBase64=function(t){return Buffer.from(t).toString("base64")},a.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(Buffer.from(t,"base64"),0))}):(a.encodeBase64=function(t){return new Buffer(t).toString("base64")},a.decodeBase64=function(t){return e(t),new Uint8Array(Array.prototype.slice.call(new Buffer(t,"base64"),0))}):(a.encodeBase64=function(t){var n,i=[],f=t.length;for(n=0;n<f;n++)i.push(String.fromCharCode(t[n]));return btoa(i.join(""))},a.decodeBase64=function(t){e(t);var n,i=atob(t),f=new Uint8Array(i.length);for(n=0;n<i.length;n++)f[n]=i.charCodeAt(n);return f}),a});});var U=br(xr()),g=br(wr());var Ze=class extends Error{constructor(e){let t;e instanceof Error?t=e.message:typeof e=="string"?t=e:t="",super(t),this.name=this.constructor.name;}};var At=[2285,2571,2970,1812,1493,1422,287,202,3158,622,1577,182,962,2127,1855,1468,573,2004,264,383,2500,1458,1727,3199,2648,1017,732,608,1787,411,3124,1758,1223,652,2777,1015,2036,1491,3047,1785,516,3321,3009,2663,1711,2167,126,1469,2476,3239,3058,830,107,1908,3082,2378,2931,961,1821,2604,448,2264,677,2054,2226,430,555,843,2078,871,1550,105,422,587,177,3094,3038,2869,1574,1653,3083,778,1159,3182,2552,1483,2727,1119,1739,644,2457,349,418,329,3173,3254,817,1097,603,610,1322,2044,1864,384,2114,3193,1218,1994,2455,220,2142,1670,2144,1799,2051,794,1819,2475,2459,478,3221,3021,996,991,958,1869,1522,1628],Qt=[1701,1807,1460,2371,2338,2333,308,108,2851,870,854,1510,2535,1278,1530,1185,1659,1187,3109,874,1335,2111,136,1215,2945,1465,1285,2007,2719,2726,2232,2512,75,156,3e3,2911,2980,872,2685,1590,2210,602,1846,777,147,2170,2551,246,1676,1755,460,291,235,3152,2742,2907,3224,1779,2458,1251,2486,2774,2899,1103,1275,2652,1065,2881,725,1508,2368,398,951,247,1421,3222,2499,271,90,853,1860,3203,1162,1618,666,320,8,2813,1544,282,1838,1293,2314,552,2677,2106,1571,205,2918,1542,2721,2597,2312,681,130,1602,1871,829,2946,3065,1325,2756,1861,1474,1202,2367,3147,1752,2707,171,3127,3042,1907,1836,1517,359,758,1441];var Tt=BigInt(4294967295),vr=BigInt(32);function bn(a,e=false){return e?{h:Number(a&Tt),l:Number(a>>vr&Tt)}:{h:Number(a>>vr&Tt)|0,l:Number(a&Tt)|0}}function Sr(a,e=false){let t=a.length,n=new Uint32Array(t),i=new Uint32Array(t);for(let f=0;f<t;f++){let{h:d,l:y}=bn(a[f],e);[n[f],i[f]]=[d,y];}return [n,i]}var kr=(a,e,t)=>a<<t|e>>>32-t,Kr=(a,e,t)=>e<<t|a>>>32-t,Pr=(a,e,t)=>e<<t-32|a>>>64-t,Ar=(a,e,t)=>a<<t-32|e>>>64-t;function xn(a){return a instanceof Uint8Array||ArrayBuffer.isView(a)&&a.constructor.name==="Uint8Array"}function Gt(a,e=""){if(!Number.isSafeInteger(a)||a<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >0, got ${a}`)}}function Ut(a,e,t=""){let n=xn(a),i=a?.length,f=e!==void 0;if(!n||f){let d=t&&`"${t}" `,y="",_=n?`length=${i}`:`type=${typeof a}`;throw new Error(d+"expected Uint8Array"+y+", got "+_)}return a}function Zt(a,e=true){if(a.destroyed)throw new Error("Hash instance has been destroyed");if(e&&a.finished)throw new Error("Hash#digest() has already been called")}function Tr(a,e){Ut(a,void 0,"digestInto() output");let t=e.outputLen;if(a.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Ur(a){return new Uint32Array(a.buffer,a.byteOffset,Math.floor(a.byteLength/4))}function Wt(...a){for(let e=0;e<a.length;e++)a[e].fill(0);}var _n=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function wn(a){return a<<24&4278190080|a<<8&16711680|a>>>8&65280|a>>>24&255}function vn(a){for(let e=0;e<a.length;e++)a[e]=wn(a[e]);return a}var er=_n?a=>a:vn;function tr(a,e={}){let t=(i,f)=>a(f).update(i).digest(),n=a(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=i=>a(i),Object.assign(t,e),Object.freeze(t)}var pt=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])});var Sn=BigInt(0),gt=BigInt(1),kn=BigInt(2),Kn=BigInt(7),Pn=BigInt(256),An=BigInt(113),jr=[],Cr=[],$r=[];for(let a=0,e=gt,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],jr.push(2*(5*n+t)),Cr.push((a+1)*(a+2)/2%64);let i=Sn;for(let f=0;f<7;f++)e=(e<<gt^(e>>Kn)*An)%Pn,e&kn&&(i^=gt<<(gt<<BigInt(f))-gt);$r.push(i);}var Mr=Sr($r,true),Tn=Mr[0],Un=Mr[1],Er=(a,e,t)=>t>32?Pr(a,e,t):kr(a,e,t),Rr=(a,e,t)=>t>32?Ar(a,e,t):Kr(a,e,t);function En(a,e=24){let t=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let d=0;d<10;d++)t[d]=a[d]^a[d+10]^a[d+20]^a[d+30]^a[d+40];for(let d=0;d<10;d+=2){let y=(d+8)%10,_=(d+2)%10,K=t[_],m=t[_+1],O=Er(K,m,1)^t[y],J=Rr(K,m,1)^t[y+1];for(let M=0;M<50;M+=10)a[d+M]^=O,a[d+M+1]^=J;}let i=a[2],f=a[3];for(let d=0;d<24;d++){let y=Cr[d],_=Er(i,f,y),K=Rr(i,f,y),m=jr[d];i=a[m],f=a[m+1],a[m]=_,a[m+1]=K;}for(let d=0;d<50;d+=10){for(let y=0;y<10;y++)t[y]=a[d+y];for(let y=0;y<10;y++)a[d+y]^=~t[(y+2)%10]&t[(y+4)%10];}a[0]^=Tn[n],a[1]^=Un[n];}Wt(t);}var Et=class a{constructor(e,t,n,i=false,f=24){if(Object.defineProperty(this,"state",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"pos",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"posOut",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"finished",{enumerable:true,configurable:true,writable:true,value:false}),Object.defineProperty(this,"state32",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"destroyed",{enumerable:true,configurable:true,writable:true,value:false}),Object.defineProperty(this,"blockLen",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"suffix",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"outputLen",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"enableXOF",{enumerable:true,configurable:true,writable:true,value:false}),Object.defineProperty(this,"rounds",{enumerable:true,configurable:true,writable:true,value:void 0}),this.blockLen=e,this.suffix=t,this.outputLen=n,this.enableXOF=i,this.rounds=f,Gt(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ur(this.state);}clone(){return this._cloneInto()}keccak(){er(this.state32),En(this.state32,this.rounds),er(this.state32),this.posOut=0,this.pos=0;}update(e){Zt(this),Ut(e);let{blockLen:t,state:n}=this,i=e.length;for(let f=0;f<i;){let d=Math.min(t-this.pos,i-f);for(let y=0;y<d;y++)n[this.pos++]^=e[f++];this.pos===t&&this.keccak();}return this}finish(){if(this.finished)return;this.finished=true;let{state:e,suffix:t,pos:n,blockLen:i}=this;e[n]^=t,(t&128)!==0&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak();}writeInto(e){Zt(this,false),Ut(e),this.finish();let t=this.state,{blockLen:n}=this;for(let i=0,f=e.length;i<f;){this.posOut>=n&&this.keccak();let d=Math.min(n-this.posOut,f-i);e.set(t.subarray(this.posOut,this.posOut+d),i),this.posOut+=d,i+=d;}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Gt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Tr(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true,Wt(this.state);}_cloneInto(e){let{blockLen:t,suffix:n,outputLen:i,rounds:f,enableXOF:d}=this;return e||(e=new a(t,n,i,d,f)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=f,e.suffix=n,e.outputLen=i,e.enableXOF=d,e.destroyed=this.destroyed,e}},Ir=(a,e,t,n={})=>tr(()=>new Et(e,a,t),n),Rt=Ir(6,136,32,pt(8)),jt=Ir(6,72,64,pt(10));var Fr=(a,e,t,n={})=>tr((i={})=>new Et(e,a,i.dkLen===void 0?t:i.dkLen,true),n),Ct=Fr(31,168,16,pt(11)),ot=Fr(31,136,32,pt(12));var Rn={},Or=jn(globalThis,Rn);function jn(a,e){return new Proxy(a,{get(t,n,i){return n in e?e[n]:a[n]},set(t,n,i){return n in e&&delete e[n],a[n]=i,true},deleteProperty(t,n){let i=false;return n in e&&(delete e[n],i=true),n in a&&(delete a[n],i=true),i},ownKeys(t){let n=Reflect.ownKeys(a),i=Reflect.ownKeys(e),f=new Set(i);return [...n.filter(d=>!f.has(d)),...i]},defineProperty(t,n,i){return n in e&&delete e[n],Reflect.defineProperty(a,n,i),true},getOwnPropertyDescriptor(t,n){return n in e?Reflect.getOwnPropertyDescriptor(e,n):Reflect.getOwnPropertyDescriptor(a,n)},has(t,n){return n in e||n in a}})}function Xe(a){return a%256}function De(a){return a>=-32768&&a<=32767?a:a<-32768?(a=a+32769,a=a%65536,32767+a):(a=a-32768,a=a%65536,-32768+a)}function ge(a){return a%65536}function $t(a){return a>=-2147483648&&a<=2147483647?a:a<-2147483648?(a=a+2147483649,a=a%4294967296,2147483647+a):(a=a-2147483648,a=a%4294967296,-2147483648+a)}function Qe(a){return a%4294967296}function Br(a,e){if(a.length!=e.length)return 0;let t=new Uint8Array([0]);for(let i=0;i<a.length;i++)t[0]|=a[i]^e[i];let n=new Uint8Array([0]);return n[0]=~(t[0]^n[0]),n[0]&=n[0]>>4,n[0]&=n[0]>>2,n[0]&=n[0]>>1,n[0]}function Lr(a,e){if(a.length!=e.length)return false;for(let t=0;t<a.length;t++)if(a[t]!==e[t])return false;return true}async function Dr(){if(typeof Or<"u"&&globalThis.crypto!==void 0)return globalThis.crypto;try{let{webcrypto:a}=await import('crypto');return a}catch{throw new Error("failed to load Crypto")}}function Mt(a,e,t){return ot.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}function Nr(a){let e=Qe(a[0]);return e|=Qe(a[1])<<8,e|=Qe(a[2])<<16,e|=Qe(a[3])<<24,Qe(e)}var ct=class{constructor(){Object.defineProperty(this,"_api",{enumerable:true,configurable:true,writable:true,value:void 0}),Object.defineProperty(this,"_k",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_du",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_dv",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_eta1",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_eta2",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_skSize",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_pkSize",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_compressedUSize",{enumerable:true,configurable:true,writable:true,value:0}),Object.defineProperty(this,"_compressedVSize",{enumerable:true,configurable:true,writable:true,value:0});}async generateKeyPair(){await this._setup();try{let e=new Uint8Array(64);return this._api.getRandomValues(e),this._deriveKeyPair(e)}catch(e){throw new Ze(e)}}async deriveKeyPair(e){await this._setup();try{if(e.byteLength!==64)throw new Error("seed must be 64 bytes in length");return this._deriveKeyPair(e)}catch(t){throw new Ze(t)}}async encap(e,t){await this._setup();try{if(e.length!==384*this._k+32)throw new Error("invalid encapsulation key");let n=this._getSeed(t),[i,f]=rr(n,Hr(e));return [this._encap(e,n,f),i]}catch(n){throw new Ze(n)}}async decap(e,t){await this._setup();try{if(e.byteLength!==this._compressedUSize+this._compressedVSize)throw new Error("Invalid ct size");if(t.length!==768*this._k+96)throw new Error("Invalid decapsulation key");let n=t.subarray(0,this._skSize),i=t.subarray(this._skSize,this._skSize+this._pkSize),f=t.subarray(this._skSize+this._pkSize,this._skSize+this._pkSize+32),d=t.subarray(this._skSize+this._pkSize+32,this._skSize+this._pkSize+64),y=this._decap(e,n),[_,K]=rr(y,f),m=Mn(d,e),O=this._encap(i,y,K);return Br(e,O)===1?_:m}catch(n){throw new Ze(n)}}async _setup(){this._api===void 0&&(this._api=await Dr());}_getSeed(e){if(e==null){let t=new Uint8Array(32);return this._api.getRandomValues(t),t}if(e.byteLength!==32)throw new Error("seed must be 32 bytes in length");return e}_deriveKeyPair(e){let t=e.subarray(0,32),n=e.subarray(32,64),[i,f]=this._deriveCpaKeyPair(t),d=Hr(i),y=new Uint8Array(this._skSize+this._pkSize+64);return y.set(f,0),y.set(i,this._skSize),y.set(d,this._skSize+this._pkSize),y.set(n,this._skSize+this._pkSize+32),[i,y]}_deriveCpaKeyPair(e){let[t,n]=rr(e,new Uint8Array([this._k])),i=this._sampleMatrix(t,false),f=this._sampleNoise1(n,0,this._k),d=this._sampleNoise1(n,this._k,this._k);for(let m=0;m<this._k;m++)f[m]=It(f[m]),f[m]=nt(f[m]),d[m]=It(d[m]);let y=new Array(this._k);for(let m=0;m<this._k;m++)y[m]=Bn(Ft(i[m],f)),y[m]=mt(y[m],d[m]),y[m]=nt(y[m]);let _=new Uint8Array(this._pkSize);for(let m=0;m<this._k;m++)_.set(nr(y[m]),m*384);_.set(t,this._skSize);let K=new Uint8Array(this._skSize);for(let m=0;m<this._k;m++)K.set(nr(f[m]),m*384);return [_,K]}_encap(e,t,n){let i=new Array(this._k),f=new Uint8Array(384*this._k);for(let H=0;H<this._k;H++)i[H]=zr(e.subarray(H*384,(H+1)*384)),f.set(nr(i[H]),H*384);if(!Lr(e.subarray(0,f.length),f))throw new Error("invalid encapsulation key");let d=e.subarray(this._skSize),y=this._sampleMatrix(d,true),_=this._sampleNoise1(n,0,this._k),K=this._sampleNoise2(n,this._k,this._k),m=this._sampleNoise2(n,this._k*2,1)[0];for(let H=0;H<this._k;H++)_[H]=It(_[H]),_[H]=nt(_[H]);let O=new Array(this._k);for(let H=0;H<this._k;H++)O[H]=Ft(y[H],_),O[H]=sr(O[H]),O[H]=mt(O[H],K[H]),O[H]=nt(O[H]);let J=On(t),M=Ft(i,_);M=sr(M),M=mt(M,m),M=mt(M,J),M=nt(M);let V=new Uint8Array(this._compressedUSize+this._compressedVSize);return this._compressU(V.subarray(0,this._compressedUSize),O),this._compressV(V.subarray(this._compressedUSize),M),V}_decap(e,t){let n=this._decompressU(e.subarray(0,this._compressedUSize)),i=this._decompressV(e.subarray(this._compressedUSize)),f=this._polyvecFromBytes(t);for(let y=0;y<this._k;y++)n[y]=It(n[y]);let d=Ft(f,n);return d=sr(d),d=Ln(i,d),d=nt(d),Fn(d)}_sampleMatrix(e,t){let n=new Array(this._k),i=new Uint8Array(2);for(let f=0,d=0;d<this._k;d++){n[d]=new Array(this._k);for(let y=0;y<this._k;y++){t?(i[0]=d,i[1]=y):(i[0]=y,i[1]=d);let _=In(e,i),K=Xr(_.subarray(0,504),504,256);for(n[d][y]=K[0],f=K[1];f<256;){let m=_.subarray(504,672),O=Xr(m,168,256-f),J=O[0],M=O[1];for(let V=f;V<256;V++)n[d][y][V]=J[V-f];f=f+M;}}}return n}_sampleNoise1(e,t,n){let i=new Array(n);for(let f=0;f<n;f++)i[f]=qr(Mt(this._eta1*256/4,e,t),this._eta1),t++;return i}_sampleNoise2(e,t,n){let i=new Array(n);for(let f=0;f<n;f++)i[f]=qr(Mt(this._eta2*256/4,e,t),this._eta2),t++;return i}_polyvecFromBytes(e){let t=new Array(this._k);for(let n=0;n<this._k;n++)t[n]=zr(e.subarray(n*384,(n+1)*384));return t}_compressU(e,t){let n=new Array(4);for(let i=0,f=0;f<this._k;f++)for(let d=0;d<256/4;d++){for(let y=0;y<4;y++)n[y]=((t[f][4*d+y]<<10)+3329/2)/3329&1023;e[i++]=Xe(n[0]>>0),e[i++]=Xe(n[0]>>8|n[1]<<2),e[i++]=Xe(n[1]>>6|n[2]<<4),e[i++]=Xe(n[2]>>4|n[3]<<6),e[i++]=Xe(n[3]>>2);}return e}_compressV(e,t){let n=new Uint8Array(8);for(let i=0,f=0;f<256/8;f++){for(let d=0;d<8;d++)n[d]=Xe(((t[8*f+d]<<4)+3329/2)/3329)&15;e[i++]=n[0]|n[1]<<4,e[i++]=n[2]|n[3]<<4,e[i++]=n[4]|n[5]<<4,e[i++]=n[6]|n[7]<<4;}return e}_decompressU(e){let t=new Array(this._k);for(let i=0;i<this._k;i++)t[i]=new Array(384);let n=new Array(4);for(let i=0,f=0;f<this._k;f++)for(let d=0;d<256/4;d++){n[0]=ge(e[i+0])>>0|ge(e[i+1])<<8,n[1]=ge(e[i+1])>>2|ge(e[i+2])<<6,n[2]=ge(e[i+2])>>4|ge(e[i+3])<<4,n[3]=ge(e[i+3])>>6|ge(e[i+4])<<2,i=i+5;for(let y=0;y<4;y++)t[f][4*d+y]=De(Qe(n[y]&1023)*Qe(3329)+512>>10);}return t}_decompressV(e){let t=new Array(384);for(let n=0,i=0;i<256/2;i++,n++)t[2*i+0]=De(ge(e[n]&15)*ge(3329)+8>>4),t[2*i+1]=De(ge(e[n]>>4)*ge(3329)+8>>4);return t}};function rr(a,e){let t=jt.create().update(a);e!==void 0&&t.update(e);let n=t.digest();return [n.subarray(0,32),n.subarray(32,64)]}function Hr(a){return Rt.create().update(a).digest()}function Mn(a,e){let t=ot.create({dkLen:32}).update(a);return e!==void 0&&t.update(e),t.digest()}function In(a,e){return Ct.create({dkLen:672}).update(a).update(e).digest()}function nr(a){let e=0,t=0,n=new Uint8Array(384),i=Gr(a);for(let f=0;f<256/2;f++)e=ge(i[2*f]),t=ge(i[2*f+1]),n[3*f+0]=Xe(e>>0),n[3*f+1]=Xe(e>>8)|Xe(t<<4),n[3*f+2]=Xe(t>>4);return n}function zr(a){let e=new Array(384).fill(0);for(let t=0;t<256/2;t++)e[2*t]=De((ge(a[3*t+0])>>0|ge(a[3*t+1])<<8)&4095),e[2*t+1]=De((ge(a[3*t+1])>>4|ge(a[3*t+2])<<4)&4095);return e}function Fn(a){let e=new Uint8Array(32),t,n=Gr(a);for(let i=0;i<256/8;i++){e[i]=0;for(let f=0;f<8;f++)t=((ge(n[8*i+f])<<1)+ge(3329/2))/ge(3329)&1,e[i]|=Xe(t<<f);}return e}function On(a){let e=new Array(384).fill(0),t;for(let n=0;n<256/8;n++)for(let i=0;i<8;i++)t=-1*De(a[n]>>i&1),e[8*n+i]=t&De(3330/2);return e}function Xr(a,e,t){let n=new Array(384).fill(0),i=0,f,d;for(let y=0;i<t&&y+3<=e;)f=(ge(a[y]>>0)|ge(a[y+1])<<8)&4095,d=(ge(a[y+1]>>4)|ge(a[y+2])<<4)&4095,y=y+3,f<3329&&(n[i]=f,i=i+1),i<t&&d<3329&&(n[i]=d,i=i+1);return [n,i]}function qr(a,e){let t,n,i,f,d=new Array(384).fill(0);for(let y=0;y<256/8;y++){t=Nr(a.subarray(4*y,a.length)),n=t&1431655765,n=n+(t>>1&1431655765);for(let _=0;_<8;_++)i=De(n>>4*_+0&3),f=De(n>>4*_+e&3),d[8*y+_]=i-f;}return d}function It(a){for(let e=0,t=1,n=128;n>=2;n>>=1)for(let i=0;i<256;i=e+n){let f=At[t];for(t=t+1,e=i;e<i+n;e++){let d=We(f,a[e+n]);a[e+n]=a[e]-d,a[e]=a[e]+d;}}return a}function We(a,e){return Qr(a*e)}function nt(a){for(let e=0;e<256;e++)a[e]=Yr(a[e]);return a}function Yr(a){let t=(16777216+3329/2)/3329*a>>24;return t=t*3329,a-t}function Qr(a){let t=De($t(a)*62209)*3329;return t=a-t,t>>=16,De(t)}function Bn(a){for(let t=0;t<256;t++)a[t]=Qr($t(a[t])*$t(1353));return a}function Ft(a,e){let t=Jr(a[0],e[0]),n;for(let i=1;i<a.length;i++)n=Jr(a[i],e[i]),t=mt(t,n);return nt(t)}function Jr(a,e){let t,n;for(let i=0;i<256/4;i++)t=Vr(a[4*i+0],a[4*i+1],e[4*i+0],e[4*i+1],At[64+i]),n=Vr(a[4*i+2],a[4*i+3],e[4*i+2],e[4*i+3],-At[64+i]),a[4*i+0]=t[0],a[4*i+1]=t[1],a[4*i+2]=n[0],a[4*i+3]=n[1];return a}function Vr(a,e,t,n,i){let f=new Array(2);return f[0]=We(e,n),f[0]=We(f[0],i),f[0]+=We(a,t),f[1]=We(a,n),f[1]+=We(e,t),f}function mt(a,e){let t=new Array(384);for(let n=0;n<256;n++)t[n]=a[n]+e[n];return t}function Ln(a,e){for(let t=0;t<256;t++)a[t]-=e[t];return a}function sr(a){let e=0;for(let t=0,n=2;n<=128;n<<=1)for(let i=0;i<256;i=e+n){let f=Qt[t];for(t=t+1,e=i;e<i+n;e++){let d=a[e];a[e]=Yr(d+a[e+n]),a[e+n]=d-a[e+n],a[e+n]=We(f,a[e+n]);}}for(e=0;e<256;e++)a[e]=We(a[e],Qt[127]);return a}function Gr(a){for(let e=0;e<256;e++)a[e]-=3329,a[e]+=a[e]>>31&3329;return a}var et=class extends ct{constructor(){super(),Object.defineProperty(this,"_k",{enumerable:true,configurable:true,writable:true,value:3}),Object.defineProperty(this,"_du",{enumerable:true,configurable:true,writable:true,value:10}),Object.defineProperty(this,"_dv",{enumerable:true,configurable:true,writable:true,value:4}),Object.defineProperty(this,"_eta1",{enumerable:true,configurable:true,writable:true,value:2}),Object.defineProperty(this,"_eta2",{enumerable:true,configurable:true,writable:true,value:2}),this._skSize=12*this._k*256/8,this._pkSize=this._skSize+32,this._compressedUSize=this._k*this._du*256/8,this._compressedVSize=this._dv*256/8;}};async function ir(a){if(typeof globalThis.crypto?.subtle<"u"){let t=new TextEncoder,n=await globalThis.crypto.subtle.digest("SHA-256",t.encode(a));return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}let{createHash:e}=await import('crypto');return e("sha256").update(a).digest("hex")}function Dn(a){let e=a.length,t=Math.max(256,Nn(e+2)),n=new Uint8Array(t);n[0]=e>>8&255,n[1]=e&255,n.set(a,2);let i=U.default.randomBytes(t-e-2);return n.set(i,e+2),n}function Zr(a){if(a.length<2)return a;let e=a[0]<<8|a[1];return e+2>a.length?a:a.slice(2,2+e)}function Nn(a){let e=1;for(;e<a;)e<<=1;return e}async function ft(a){new TextEncoder;if(typeof globalThis.crypto?.subtle<"u"){let f=new Uint8Array([...a,1]),d=new Uint8Array([...a,2]),y=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",f)),_=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",d));return {nextChainKey:y,messageKey:_}}let{createHash:t}=await import('crypto'),n=new Uint8Array(t("sha256").update(Buffer.from([...a,1])).digest()),i=new Uint8Array(t("sha256").update(Buffer.from([...a,2])).digest());return {nextChainKey:n,messageKey:i}}function Hn(a,e,t){let n={v:3,from:a,msg:e,ts:new Date().toISOString()};return t?.contentType&&t.contentType!=="text/plain"&&(n.ct=t.contentType),t?.messageType&&t.messageType!=="text"&&(n.mt=t.messageType),t?.threadId&&(n.tid=t.threadId),t?.replyTo&&(n.rto=t.replyTo),JSON.stringify(n)}function zn(a){try{let e=JSON.parse(a);if((e.v===2||e.v===3)&&e.from&&e.msg!==void 0){let t={from:e.from,msg:e.msg,ts:e.ts};return e.ct&&(t.contentType=e.ct),e.mt&&(t.messageType=e.mt),e.tid&&(t.threadId=e.tid),e.rto&&(t.replyTo=e.rto),t}return null}catch{return null}}var nn=86,Wr=1,en=2,Xn=4,qn=8,Jn=16,Vn=32;function Yn(a,e){return new Uint8Array([nn,a,e>>8&255,e&255])}function Qn(a){return a.length<4||a[0]!==nn?null:{flags:a[1],ratchetStep:a[2]<<8|a[3],content:a.slice(4)}}async function lt(a,e){let t=new Uint8Array(a.length+e.length);if(t.set(a,0),t.set(e,a.length),typeof globalThis.crypto?.subtle<"u"){let y=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",t.buffer)),_=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new Uint8Array([...y,1]).buffer)),K=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new Uint8Array([...y,2]).buffer));return {newRootKey:_,newChainKey:K}}let{createHash:n}=await import('crypto'),i=new Uint8Array(n("sha256").update(Buffer.from(t)).digest()),f=new Uint8Array(n("sha256").update(Buffer.from([...i,1])).digest()),d=new Uint8Array(n("sha256").update(Buffer.from([...i,2])).digest());return {newRootKey:f,newChainKey:d}}async function tn(a,e){if(typeof globalThis.crypto?.subtle<"u"){let n=await globalThis.crypto.subtle.importKey("raw",a.buffer,{name:"HMAC",hash:"SHA-256"},false,["sign"]);return new Uint8Array(await globalThis.crypto.subtle.sign("HMAC",n,e.buffer))}let{createHmac:t}=await import('crypto');return new Uint8Array(t("sha256",Buffer.from(a)).update(Buffer.from(e)).digest())}var Ot=1e3,Gn="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Zn(a){if(a.length===0)return "1";let e="",t=BigInt("0x"+Array.from(a).map(n=>n.toString(16).padStart(2,"0")).join(""));for(;t>0n;){let n=t%58n;t=t/58n,e=Gn[Number(n)]+e;}for(let n of a)if(n===0)e="1"+e;else break;return e||"1"}var rn=class a{constructor(e,t){this._signedPrekey=null;this._signedPrekeyId=0;this._pinnedDids=new Set;this._listeners=new Set;this._conversations=new Map;this._offlineQueue=[];this._ratchetStates=new Map;this._identityCache=new Map;this._seenMessageIds=new Set;this._decryptFailCount=0;this._peerDecryptFails=new Map;this._autoResetThreshold=10;this._rpcHandlers=new Map;this._rpcPending=new Map;this._coverTrafficTimer=null;this._rpcListener=null;this._persistMode="memory";this._persistKey=null;this._sendLocks=new Map;this._decryptLock=null;this.did=e.did,this.apiKey=e.apiKey,this.signingKeyPair=e.signingKeyPair,this.encryptionKeyPair=e.encryptionKeyPair,this.baseUrl=t?.baseUrl||"https://api.voidly.ai",this.autoPin=t?.autoPin!==false,this.defaultRetries=t?.retries??3,this.fallbackRelays=t?.fallbackRelays||[],this.paddingEnabled=t?.padding!==false,this.sealedSender=t?.sealedSender||false,this.requireSignatures=t?.requireSignatures||false,this.timeout=t?.timeout??3e4,this.postQuantum=t?.postQuantum!==false,this.deniable=t?.deniable||false,this.doubleRatchet=t?.doubleRatchet!==false,this.jitterMs=t?.jitterMs||0,this.longPoll=t?.longPoll!==false,this.mlkemPublicKey=e.mlkemPublicKey||null,this.mlkemSecretKey=e.mlkemSecretKey||null,this._persistMode=t?.persist||"memory",this._onPersist=t?.onPersist,this._onLoad=t?.onLoad,this._persistPath=t?.persistPath,this._transportPrefs=t?.transport||["sse","long-poll"],this._autoResetThreshold=t?.autoResetThreshold??10,this._onRatchetReset=t?.onRatchetReset;}static async register(e={},t){let n=t?.baseUrl||"https://api.voidly.ai",i=U.default.sign.keyPair(),f=U.default.box.keyPair(),d=t?.postQuantum!==false,y,_;d&&([y,_]=await new et().generateKeyPair());let K=U.default.box.keyPair(),m=1,O=U.default.sign.detached(K.publicKey,i.secretKey),J={name:e.name,capabilities:e.capabilities,signing_public_key:(0, g.encodeBase64)(i.publicKey),encryption_public_key:(0, g.encodeBase64)(f.publicKey),signed_prekey_public:(0, g.encodeBase64)(K.publicKey),signed_prekey_signature:(0, g.encodeBase64)(O),signed_prekey_id:m};y&&(J.mlkem_public_key=(0, g.encodeBase64)(y));let M=await fetch(`${n}/v1/agent/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)});if(!M.ok){let be=await M.json().catch(()=>({})),qe=be.error?.message||be.error||M.statusText;throw new Error(`Registration failed: ${qe}`)}let V=await M.json(),H=new a({did:V.did,apiKey:V.api_key,signingKeyPair:i,encryptionKeyPair:f,mlkemPublicKey:y,mlkemSecretKey:_},t);return H._signedPrekey=K,H._signedPrekeyId=m,H}static fromCredentials(e,t){if(!e.did||!e.did.startsWith("did:"))throw new Error('Invalid credentials: did must start with "did:"');if(!e.apiKey||e.apiKey.length<8)throw new Error("Invalid credentials: apiKey is missing or too short");if(!e.signingSecretKey||!e.encryptionSecretKey)throw new Error("Invalid credentials: secret keys are required");let n,i;try{n=(0,g.decodeBase64)(e.signingSecretKey),i=(0,g.decodeBase64)(e.encryptionSecretKey);}catch{throw new Error("Invalid credentials: secret keys must be valid base64")}if(n.length!==64)throw new Error(`Invalid credentials: signing key must be 64 bytes, got ${n.length}`);if(i.length!==32)throw new Error(`Invalid credentials: encryption key must be 32 bytes, got ${i.length}`);let f,d;if(e.mlkemPublicKey&&e.mlkemSecretKey)try{f=(0,g.decodeBase64)(e.mlkemPublicKey),d=(0,g.decodeBase64)(e.mlkemSecretKey),(f.length!==1184||d.length!==2400)&&(f=void 0,d=void 0);}catch{}let y=!d&&t?.postQuantum!==false?{...t,postQuantum:false}:t,_=new a({did:e.did,apiKey:e.apiKey,signingKeyPair:U.default.sign.keyPair.fromSecretKey(n),encryptionKeyPair:{publicKey:U.default.box.keyPair.fromSecretKey(i).publicKey,secretKey:i},mlkemPublicKey:f,mlkemSecretKey:d},y);if(e.ratchetStates)for(let[K,m]of Object.entries(e.ratchetStates))try{let O=(0,g.decodeBase64)(m.sendChainKey),J=(0,g.decodeBase64)(m.recvChainKey);if(O.length!==32||J.length!==32)continue;let M={sendChainKey:O,sendStep:m.sendStep||0,recvChainKey:J,recvStep:m.recvStep||0,skippedKeys:new Map};if(m.rootKey)try{M.rootKey=(0,g.decodeBase64)(m.rootKey),M.rootKey.length!==32&&(M.rootKey=void 0);}catch{}if(m.dhSendSecretKey&&m.dhSendPublicKey)try{let V=(0,g.decodeBase64)(m.dhSendSecretKey),H=(0,g.decodeBase64)(m.dhSendPublicKey);V.length===32&&H.length===32&&(M.dhSendKeyPair={publicKey:H,secretKey:V});}catch{}if(m.dhRecvPubKey)try{let V=(0,g.decodeBase64)(m.dhRecvPubKey);V.length===32&&(M.dhRecvPubKey=V);}catch{}if(m.prevSendStep!==void 0&&(M.prevSendStep=m.prevSendStep),M.dhSkippedKeys=new Map,m.skippedKeys&&typeof m.skippedKeys=="object")for(let[V,H]of Object.entries(m.skippedKeys))try{let be=(0,g.decodeBase64)(H);be.length===32&&M.skippedKeys.set(Number(V),be);}catch{}if(m.dhSkippedKeys&&typeof m.dhSkippedKeys=="object")for(let[V,H]of Object.entries(m.dhSkippedKeys))try{let be=(0,g.decodeBase64)(H);be.length===32&&M.dhSkippedKeys.set(V,be);}catch{}_._ratchetStates.set(K,M);}catch{}if(e.peerDecryptFails&&typeof e.peerDecryptFails=="object")for(let[K,m]of Object.entries(e.peerDecryptFails))typeof m=="number"&&m>0&&_._peerDecryptFails.set(K,m);if(e.signedPrekeySecret&&e.signedPrekeyPublic)try{let K=(0,g.decodeBase64)(e.signedPrekeySecret),m=(0,g.decodeBase64)(e.signedPrekeyPublic);K.length===32&&m.length===32&&(_._signedPrekey={publicKey:m,secretKey:K},_._signedPrekeyId=e.signedPrekeyId||0);}catch{}return _}exportCredentials(){let e={};for(let[t,n]of this._ratchetStates){let i={sendChainKey:(0, g.encodeBase64)(n.sendChainKey),sendStep:n.sendStep,recvChainKey:(0, g.encodeBase64)(n.recvChainKey),recvStep:n.recvStep};n.rootKey&&(i.rootKey=(0, g.encodeBase64)(n.rootKey)),n.dhSendKeyPair&&(i.dhSendSecretKey=(0, g.encodeBase64)(n.dhSendKeyPair.secretKey),i.dhSendPublicKey=(0, g.encodeBase64)(n.dhSendKeyPair.publicKey)),n.dhRecvPubKey&&(i.dhRecvPubKey=(0, g.encodeBase64)(n.dhRecvPubKey)),n.prevSendStep!==void 0&&(i.prevSendStep=n.prevSendStep),n.skippedKeys?.size&&(i.skippedKeys=Object.fromEntries([...n.skippedKeys].map(([f,d])=>[String(f),(0, g.encodeBase64)(d)]))),n.dhSkippedKeys?.size&&(i.dhSkippedKeys=Object.fromEntries([...n.dhSkippedKeys].map(([f,d])=>[f,(0, g.encodeBase64)(d)]))),e[t]=i;}return {did:this.did,apiKey:this.apiKey,signingSecretKey:(0, g.encodeBase64)(this.signingKeyPair.secretKey),encryptionSecretKey:(0, g.encodeBase64)(this.encryptionKeyPair.secretKey),signingPublicKey:(0, g.encodeBase64)(this.signingKeyPair.publicKey),encryptionPublicKey:(0, g.encodeBase64)(this.encryptionKeyPair.publicKey),...Object.keys(e).length>0?{ratchetStates:e}:{},...this.mlkemPublicKey?{mlkemPublicKey:(0, g.encodeBase64)(this.mlkemPublicKey)}:{},...this.mlkemSecretKey?{mlkemSecretKey:(0, g.encodeBase64)(this.mlkemSecretKey)}:{},...this._signedPrekey?{signedPrekeySecret:(0, g.encodeBase64)(this._signedPrekey.secretKey),signedPrekeyPublic:(0, g.encodeBase64)(this._signedPrekey.publicKey),signedPrekeyId:this._signedPrekeyId}:{},...this._peerDecryptFails.size>0?{peerDecryptFails:Object.fromEntries(this._peerDecryptFails)}:{}}}_derivePersistKey(){if(this._persistKey)return this._persistKey;let e=(0, g.decodeUTF8)("voidly-persist-v1"),t=new Uint8Array(this.signingKeyPair.secretKey.length+e.length);return t.set(this.signingKeyPair.secretKey,0),t.set(e,this.signingKeyPair.secretKey.length),this._persistKey=U.default.hash(t).slice(0,32),this._persistKey}async _persistRatchetState(){if(this._persistMode!=="memory")try{let e=this.exportCredentials(),t=JSON.stringify(e.ratchetStates||{}),n=this._derivePersistKey(),i=U.default.randomBytes(24),f=U.default.secretbox((0,g.decodeUTF8)(t),i,n),d=JSON.stringify({n:(0,g.encodeBase64)(i),c:(0,g.encodeBase64)(f),v:1});switch(this._persistMode){case "localStorage":typeof localStorage<"u"&&localStorage.setItem(`voidly-ratchet-${this.did}`,d);break;case "indexedDB":await this._idbPut(d);break;case "file":this._persistPath&&await(await import('fs/promises')).writeFile(this._persistPath,d,"utf-8");break;case "relay":await this._timedFetch(`${this.baseUrl}/v1/agent/memory/ratchet/state`,{method:"PUT",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({value:d})}).catch(y=>{console.warn(`[voidly] \u26A0 Relay ratchet persist failed: ${y instanceof Error?y.message:y}`);});break;case "custom":this._onPersist&&await this._onPersist(d);break}}catch(e){console.warn(`[voidly] \u26A0 Ratchet state persistence failed (${this._persistMode}): ${e instanceof Error?e.message:e}`);}}async _loadPersistedRatchetState(){if(this._persistMode==="memory")return;let e=null;try{switch(this._persistMode){case "localStorage":typeof localStorage<"u"&&(e=localStorage.getItem(`voidly-ratchet-${this.did}`));break;case "indexedDB":e=await this._idbGet();break;case "file":if(this._persistPath)try{e=await(await import('fs/promises')).readFile(this._persistPath,"utf-8");}catch{}break;case "relay":try{let t=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/ratchet/state`,{headers:{"X-Agent-Key":this.apiKey}});t.ok&&(e=(await t.json()).value);}catch(t){console.warn(`[voidly] \u26A0 Relay ratchet load failed: ${t instanceof Error?t.message:t}`);}break;case "custom":this._onLoad&&(e=await this._onLoad());break}}catch(t){console.warn(`[voidly] \u26A0 Ratchet state load failed (${this._persistMode}): ${t instanceof Error?t.message:t}`);return}if(e)try{let{n:t,c:n}=JSON.parse(e),i=this._derivePersistKey(),f=U.default.secretbox.open((0,g.decodeBase64)(n),(0,g.decodeBase64)(t),i);if(!f)return;let d=JSON.parse((0,g.encodeUTF8)(f));for(let[y,_]of Object.entries(d)){if(!_||typeof _.sendStep!="number"||typeof _.recvStep!="number"||typeof _.sendChainKey!="string"||typeof _.recvChainKey!="string"||_.sendStep<0||_.recvStep<0||_.sendStep>4294967295||_.recvStep>4294967295)continue;if(this._ratchetStates.has(y)){let m=this._ratchetStates.get(y),O=m.sendStep+m.recvStep;if((_.sendStep||0)+(_.recvStep||0)<=O)continue}let K={sendChainKey:(0,g.decodeBase64)(_.sendChainKey),sendStep:_.sendStep,recvChainKey:(0,g.decodeBase64)(_.recvChainKey),recvStep:_.recvStep,skippedKeys:new Map};_.rootKey&&typeof _.rootKey=="string"&&(K.rootKey=(0,g.decodeBase64)(_.rootKey)),typeof _.dhSendSecretKey=="string"&&typeof _.dhSendPublicKey=="string"&&(K.dhSendKeyPair={secretKey:(0,g.decodeBase64)(_.dhSendSecretKey),publicKey:(0,g.decodeBase64)(_.dhSendPublicKey)}),typeof _.dhRecvPubKey=="string"&&(K.dhRecvPubKey=(0,g.decodeBase64)(_.dhRecvPubKey)),typeof _.prevSendStep=="number"&&_.prevSendStep>=0&&(K.prevSendStep=_.prevSendStep),K.sendChainKey.length===32&&K.recvChainKey.length===32&&this._ratchetStates.set(y,K);}}catch(t){console.warn(`[voidly] \u26A0 Ratchet state restore failed (corrupt data, starting fresh): ${t instanceof Error?t.message:t}`);}}async _idbPut(e){if(!(typeof indexedDB>"u"))return new Promise((t,n)=>{let i=indexedDB.open("voidly-agent",1);i.onupgradeneeded=()=>{let f=i.result;f.objectStoreNames.contains("ratchet")||f.createObjectStore("ratchet");},i.onsuccess=()=>{let f=i.result.transaction("ratchet","readwrite");f.objectStore("ratchet").put(e,this.did),f.oncomplete=()=>t(),f.onerror=()=>n(f.error);},i.onerror=()=>n(i.error);})}async _idbGet(){return typeof indexedDB>"u"?null:new Promise((e,t)=>{let n=indexedDB.open("voidly-agent",1);n.onupgradeneeded=()=>{let i=n.result;i.objectStoreNames.contains("ratchet")||i.createObjectStore("ratchet");},n.onsuccess=()=>{let f=n.result.transaction("ratchet","readonly").objectStore("ratchet").get(this.did);f.onsuccess=()=>e(f.result||null),f.onerror=()=>t(f.error);},n.onerror=()=>t(n.error);})}async flushRatchetState(){let e=this._persistMode;e==="memory"&&(this._persistMode="file"),await this._persistRatchetState(),this._persistMode=e;}static async fromCredentialsAsync(e,t){let n=a.fromCredentials(e,t);return await n._loadPersistedRatchetState(),n}get decryptFailCount(){return this._decryptFailCount}get peerDecryptFails(){return Object.fromEntries(this._peerDecryptFails)}resetRatchet(e){let t=`${this.did}:${e}`,n=`${e}:${this.did}`,i=this._ratchetStates.delete(t),f=this._ratchetStates.delete(n);return this._peerDecryptFails.delete(e),(i||f)&&this._persistRatchetState().catch(()=>{}),i||f}get didKey(){let e=new Uint8Array(2+this.signingKeyPair.publicKey.length);return e[0]=237,e[1]=1,e.set(this.signingKeyPair.publicKey,2),`did:key:z${Zn(e)}`}async send(e,t,n={}){let i=`send:${e}`;for(;this._sendLocks.has(i);)await this._sendLocks.get(i);let f;this._sendLocks.set(i,new Promise(d=>{f=d;}));try{return await this._sendInner(e,t,n)}finally{this._sendLocks.delete(i),f();}}async _sendInner(e,t,n={}){let i=n.retries??this.defaultRetries,f=!n.noPadding&&this.paddingEnabled,d=n.sealedSender??this.sealedSender,y=await this.getIdentity(e);if(!y)throw new Error(`Recipient ${e} not found`);this.autoPin&&!n.skipPin&&await this._autoPinKeys(e);let _=(0, g.decodeBase64)(y.encryption_public_key),K=t;d&&(K=Hn(this.did,t,{contentType:n.contentType,messageType:n.messageType,threadId:n.threadId,replyTo:n.replyTo}));let m;f?m=Dn((0, g.decodeUTF8)(K)):m=(0, g.decodeUTF8)(K);let O=`${this.did}:${e}`,J=this._ratchetStates.get(O),M=null,V=null;if(J)J.rootKey&&J.dhSendKeyPair&&(V=J.dhSendKeyPair.publicKey);else {let pe=U.default.box.before(_,this.encryptionKeyPair.secretKey),D;if(this.postQuantum&&y.mlkem_public_key)try{let z=(0,g.decodeBase64)(y.mlkem_public_key),ve=new et,[_e,ye]=await ve.encap(z);M=_e;let we=new Uint8Array(pe.length+ye.length);we.set(pe,0),we.set(ye,pe.length),D=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",we));}catch{D=pe;}else D=pe;if(this.doubleRatchet){let z=U.default.box.keyPair(),ve=U.default.box.before(_,z.secretKey),{newRootKey:_e,newChainKey:ye}=await lt(D,ve);V=z.publicKey,J={sendChainKey:ye,sendStep:0,recvChainKey:D,recvStep:0,skippedKeys:new Map,rootKey:_e,dhSendKeyPair:z,dhRecvPubKey:void 0,prevSendStep:0,dhSkippedKeys:new Map};}else J={sendChainKey:D,sendStep:0,recvChainKey:D,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(O,J);}let{nextChainKey:H,messageKey:be}=await ft(J.sendChainKey);J.sendChainKey=H,J.sendStep++;let qe=J.sendStep,Ee=Xn;f&&(Ee|=Wr),d&&(Ee|=en),M&&(Ee|=qn),V&&(Ee|=Jn),this.deniable&&(Ee|=Vn);let $e=Yn(Ee,qe),Be=new Uint8Array($e.length+m.length);Be.set($e,0),Be.set(m,$e.length);let Me=U.default.randomBytes(U.default.secretbox.nonceLength),Je=U.default.secretbox(Be,Me,be);if(!Je)throw new Error("Encryption failed");if(this.jitterMs>0){let pe=Math.random()*this.jitterMs;await new Promise(D=>setTimeout(D,pe));}let Le={from:this.did,to:e,timestamp:new Date().toISOString(),nonce:(0, g.encodeBase64)(Me),ciphertext_hash:await ir((0, g.encodeBase64)(Je)),ratchet_step:qe};M&&(Le.pq_ciphertext=(0, g.encodeBase64)(M)),V&&(Le.dh_ratchet_key=(0, g.encodeBase64)(V),Le.pn=J.prevSendStep||0);let Ve=JSON.stringify(Le),he;if(this.deniable){let pe=U.default.box.before(_,this.encryptionKeyPair.secretKey);he=await tn(pe,(0, g.decodeUTF8)(Ve));}else he=U.default.sign.detached((0, g.decodeUTF8)(Ve),this.signingKeyPair.secretKey);let j={to:e,ciphertext:(0, g.encodeBase64)(Je),nonce:(0, g.encodeBase64)(Me),signature:(0, g.encodeBase64)(he),envelope:Ve,ttl:n.ttl};d||(j.content_type=n.contentType||"text/plain",j.message_type=n.messageType||"text",j.thread_id=n.threadId,j.reply_to=n.replyTo),this._persistRatchetState().catch(()=>{});let P=[this.baseUrl,...this.fallbackRelays],xe=null;for(let pe of P)try{let D=await this._fetchWithRetry(`${pe}/v1/agent/send/encrypted`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(j)},{maxRetries:i,baseDelay:500,maxDelay:1e4});return {id:D.id,from:D.from,to:D.to,timestamp:D.timestamp,expiresAt:D.expires_at||D.expiresAt,encrypted:D.encrypted,clientSide:D.client_side||D.clientSide}}catch(D){if(xe=D instanceof Error?D:new Error(String(D)),xe.message.includes("(4"))break}throw xe&&!xe.message.includes("(4")&&this._offlineQueue.push({recipientDid:e,message:t,options:n,timestamp:Date.now()}),xe||new Error("Send failed")}async receive(e={}){let t=new URLSearchParams;e.since&&t.set("since",e.since),e.limit&&t.set("limit",String(e.limit)),e.from&&t.set("from",e.from),e.threadId&&t.set("thread_id",e.threadId),e.contentType&&t.set("content_type",e.contentType),e.messageType&&t.set("message_type",e.messageType),e.unreadOnly&&t.set("unread","true");let n=await this._resilientFetch(`/v1/agent/receive/raw?${t}`,{headers:{"X-Agent-Key":this.apiKey}});if(!n.ok){let y=await n.json().catch(()=>({}));throw new Error(`Receive failed: ${y.error?.message||y.error||n.statusText}`)}let i=await n.json(),{decrypted:f,failedIds:d}=await this._decryptMessages(i.messages);if(d.length>0)try{await this.markReadBatch(d);}catch{for(let y of d)try{await this.markRead(y);}catch{}}return f}async _decryptMessages(e){for(;this._decryptLock;)await this._decryptLock;let t;this._decryptLock=new Promise(n=>{t=n;});try{return await this._decryptMessagesInner(e)}finally{this._decryptLock=null,t();}}async _decryptMessagesInner(e){let t=[],n=[],i=new Set;for(let f of e)try{if(this._seenMessageIds.has(f.id))continue;let d,y=null;if(f.sender_encryption_key)d=(0,g.decodeBase64)(f.sender_encryption_key),f.sender_signing_key&&(y=(0,g.decodeBase64)(f.sender_signing_key));else if(f.envelope){let j=JSON.parse(f.envelope),P=await this.getIdentity(j.from);if(!P)continue;d=(0,g.decodeBase64)(P.encryption_public_key),P.signing_public_key&&(y=(0,g.decodeBase64)(P.signing_public_key));}else continue;let _=(0,g.decodeBase64)(f.ciphertext),K=(0,g.decodeBase64)(f.nonce),m=null,O=0,J=null,M=null,V=0;if(f.envelope)try{let j=JSON.parse(f.envelope);typeof j.ratchet_step=="number"&&Number.isInteger(j.ratchet_step)&&j.ratchet_step>=0&&j.ratchet_step<=4294967295&&(O=j.ratchet_step),typeof j.pq_ciphertext=="string"&&j.pq_ciphertext.length<=65536&&(J=j.pq_ciphertext),typeof j.dh_ratchet_key=="string"&&j.dh_ratchet_key.length<=256&&(M=j.dh_ratchet_key),typeof j.pn=="number"&&Number.isInteger(j.pn)&&j.pn>=0&&j.pn<=4294967295&&(V=j.pn);}catch{}if(O>0){let j=`${f.from}:${this.did}`,P=this._ratchetStates.get(j);if(P){if(M&&P.rootKey){let D=(0,g.decodeBase64)(M),z=P.dhRecvPubKey;if(!z||(0,g.encodeBase64)(D)!==(0,g.encodeBase64)(z)){if(V>P.recvStep){let Ne=P.recvChainKey;for(let Ue=P.recvStep+1;Ue<=V&&Ue-P.recvStep<=Ot;Ue++){let{nextChainKey:Re,messageKey:X}=await ft(Ne),ke=`${z?(0,g.encodeBase64)(z):"init"}:${Ue}`;for(P.dhSkippedKeys||(P.dhSkippedKeys=new Map),P.dhSkippedKeys.set(ke,X),Ne=Re;P.dhSkippedKeys.size>Ot;){let He=P.dhSkippedKeys.keys().next().value;if(He!==void 0)P.dhSkippedKeys.delete(He);else break}}}P.dhRecvPubKey=D;let ve=P.dhSendKeyPair||this.encryptionKeyPair,_e=U.default.box.before(D,ve.secretKey),ye=await lt(P.rootKey,_e);P.rootKey=ye.newRootKey,P.recvChainKey=ye.newChainKey,P.recvStep=0,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0;let we=U.default.box.before(D,P.dhSendKeyPair.secretKey),Se=await lt(P.rootKey,we);P.rootKey=Se.newRootKey,P.sendChainKey=Se.newChainKey;}}}else {let D=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(J&&this.mlkemSecretKey)try{let _e=(0,g.decodeBase64)(J),we=await new et().decap(_e,this.mlkemSecretKey),Se=new Uint8Array(D.length+we.length);Se.set(D,0),Se.set(we,D.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Se));}catch{z=D;}else z=D;if(M&&this.doubleRatchet){let _e=(0,g.decodeBase64)(M),ye=U.default.box.before(_e,this.encryptionKeyPair.secretKey),{newRootKey:we,newChainKey:Se}=await lt(z,ye);P={sendChainKey:z,sendStep:0,recvChainKey:Se,recvStep:0,skippedKeys:new Map,rootKey:we,dhSendKeyPair:void 0,dhRecvPubKey:_e,prevSendStep:0,dhSkippedKeys:new Map};}else P={sendChainKey:z,sendStep:0,recvChainKey:z,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(j,P);let ve=`${this.did}:${f.from}`;this._ratchetStates.delete(ve);}let xe=O,pe=M?`${M}:${xe}`:`init:${xe}`;if(P.dhSkippedKeys?.has(pe)){let D=P.dhSkippedKeys.get(pe);m=U.default.secretbox.open(_,K,D),P.dhSkippedKeys.delete(pe);}else if(P.skippedKeys.has(xe)){let D=P.skippedKeys.get(xe);m=U.default.secretbox.open(_,K,D),P.skippedKeys.delete(xe);}else if(xe>P.recvStep)if(xe-P.recvStep>Ot){this._decryptFailCount++,n.push(f.id);let z=f.from||"unknown",ve=this._peerDecryptFails.get(z)||0;this._peerDecryptFails.set(z,ve+1),this._autoResetThreshold>0&&ve+1>=this._autoResetThreshold&&(this.resetRatchet(z),i.add(z),this._onRatchetReset?.(z,ve+1));continue}else {let z=P.recvChainKey;for(let ye=P.recvStep+1;ye<xe;ye++){let{nextChainKey:we,messageKey:Se}=await ft(z);for(P.skippedKeys.set(ye,Se),z=we;P.skippedKeys.size>Ot;){let Ne=P.skippedKeys.keys().next().value;if(Ne!==void 0)P.skippedKeys.delete(Ne);else break}}let{nextChainKey:ve,messageKey:_e}=await ft(z);P.recvChainKey=ve,P.recvStep=xe,m=U.default.secretbox.open(_,K,_e);}if(!m&&M&&this.doubleRatchet&&P)try{let D=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(J&&this.mlkemSecretKey)try{let X=(0,g.decodeBase64)(J),He=await new et().decap(X,this.mlkemSecretKey),Ge=new Uint8Array(D.length+He.length);Ge.set(D,0),Ge.set(He,D.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ge));}catch{z=D;}else z=D;let ve=(0,g.decodeBase64)(M),_e=U.default.box.before(ve,this.encryptionKeyPair.secretKey),{newRootKey:ye,newChainKey:we}=await lt(z,_e),Se=we;for(let X=1;X<O;X++){let{nextChainKey:ke}=await ft(Se);Se=ke;}let{nextChainKey:Ne,messageKey:Ue}=await ft(Se),Re=U.default.secretbox.open(_,K,Ue);if(Re){m=Re,P.recvChainKey=Ne,P.recvStep=O,P.rootKey=ye,P.dhRecvPubKey=ve,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0,P.sendChainKey=z;let X=U.default.box.before(ve,P.dhSendKeyPair.secretKey),ke=await lt(P.rootKey,X);P.rootKey=ke.newRootKey,P.sendChainKey=ke.newChainKey,P.dhSkippedKeys&&P.dhSkippedKeys.clear(),P.skippedKeys&&P.skippedKeys.clear();let He=`${this.did}:${f.from}`;this._ratchetStates.delete(He);}}catch{}if(!m&&P){this.resetRatchet(f.from),i.add(f.from),this._onRatchetReset?.(f.from,1),n.push(f.id);continue}m||(m=U.default.box.open(_,K,d,this.encryptionKeyPair.secretKey));}else m=U.default.box.open(_,K,d,this.encryptionKeyPair.secretKey);if(!m){this._decryptFailCount++,n.push(f.id);let j=f.from||"unknown",P=this._peerDecryptFails.get(j)||0;this._peerDecryptFails.set(j,P+1),this._autoResetThreshold>0&&P+1>=this._autoResetThreshold&&(this.resetRatchet(j),i.add(j),this._onRatchetReset?.(j,P+1));continue}{let j=f.from||"unknown";this._peerDecryptFails.has(j)&&this._peerDecryptFails.delete(j);}let H=m,be=!1,qe=!1,Ee=Qn(m);if(Ee&&(be=!!(Ee.flags&Wr),qe=!!(Ee.flags&en),H=Ee.content),be)H=Zr(H);else if(!Ee&&m.length>=256&&(m.length&m.length-1)===0){let j=Zr(m);j.length<m.length&&(H=j);}let $e=(0,g.encodeUTF8)(H),Be=f.from,Me,Je,Le,Ve;if(qe||!Ee){let j=zn($e);j&&($e=j.msg,Be=j.from,Me=j.contentType,Je=j.messageType,Le=j.threadId,Ve=j.replyTo);}let he=!1;try{let j=(0,g.decodeBase64)(f.signature),P=f.envelope||JSON.stringify({from:Be,to:f.to,timestamp:f.timestamp,nonce:f.nonce,ciphertext_hash:await ir(f.ciphertext)});if(j.length===32){let xe=U.default.box.before(d,this.encryptionKeyPair.secretKey),pe=await tn(xe,(0,g.decodeUTF8)(P));if(pe.length===j.length){let D=0;for(let z=0;z<pe.length;z++)D|=pe[z]^j[z];he=D===0;}}else y&&(he=U.default.sign.detached.verify((0,g.decodeUTF8)(P),j,y));}catch{he=!1;}if(this.requireSignatures&&!he){this._decryptFailCount++,n.push(f.id);let j=f.from||"unknown",P=this._peerDecryptFails.get(j)||0;this._peerDecryptFails.set(j,P+1);continue}if(this._seenMessageIds.add(f.id),this._seenMessageIds.size>1e4){let j=this._seenMessageIds.values();for(let P=0;P<1e3;P++){let xe=j.next().value;xe!==void 0&&this._seenMessageIds.delete(xe);}}t.push({id:f.id,from:Be,to:f.to,content:$e,contentType:Me||f.content_type||"text/plain",messageType:Je||f.message_type||"text",threadId:Le||f.thread_id||null,replyTo:Ve||f.reply_to||null,signatureValid:he,timestamp:f.timestamp,expiresAt:f.expires_at});}catch{this._decryptFailCount++,n.push(f.id);let d=f.from||"unknown",y=this._peerDecryptFails.get(d)||0;this._peerDecryptFails.set(d,y+1),this._autoResetThreshold>0&&y+1>=this._autoResetThreshold&&(this.resetRatchet(d),i.add(d),this._onRatchetReset?.(d,y+1));}return (t.length>0||this._peerDecryptFails.size>0)&&this._persistRatchetState().catch(()=>{}),{decrypted:t,failedIds:n}}async deleteMessage(e){return (await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${e}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}})).ok}async getProfile(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/profile`,{headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error("Failed to fetch profile");return await e.json()}async updateProfile(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/profile`,{method:"PATCH",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(e)});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Profile update failed: ${n.error||t.statusText}`)}}async getIdentity(e){let t=this._identityCache.get(e);if(t&&Date.now()-t.cachedAt<3e5)return t.profile;let n=await this._resilientFetch(`/v1/agent/identity/${e}`);if(!n.ok)return null;let i=await n.json();if(this._identityCache.set(e,{profile:i,cachedAt:Date.now()}),this._identityCache.size>500){let f=this._identityCache.size-400,d=this._identityCache.keys();for(let y=0;y<f;y++){let _=d.next().value;_!==void 0&&this._identityCache.delete(_);}}return i}async discover(e={}){let t=new URLSearchParams;e.query&&t.set("query",e.query),e.capability&&t.set("capability",e.capability),e.limit&&t.set("limit",String(e.limit));let n=await this._resilientFetch(`/v1/agent/discover?${t}`);return n.ok?(await n.json()).agents:[]}async stats(){return await(await this._timedFetch(`${this.baseUrl}/v1/agent/stats`)).json()}async registerWebhook(e,t={}){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({webhook_url:e,events:t.events})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(`Webhook registration failed: ${i.error?.message||i.error||n.statusText}`)}return await n.json()}async listWebhooks(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks`,{headers:{"X-Agent-Key":this.apiKey}});return e.ok?(await e.json()).webhooks:[]}async deleteWebhook(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/webhooks/${e}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Webhook delete failed: ${n.error||t.statusText}`)}}static async verifyWebhookSignature(e,t,n){let i=new TextEncoder;if(typeof globalThis.crypto?.subtle<"u"){let _=await globalThis.crypto.subtle.importKey("raw",i.encode(n),{name:"HMAC",hash:"SHA-256"},false,["sign"]),K=await globalThis.crypto.subtle.sign("HMAC",_,i.encode(e)),m=`sha256=${Array.from(new Uint8Array(K)).map(V=>V.toString(16).padStart(2,"0")).join("")}`;if(t.length!==m.length)return false;let O=i.encode(t),J=i.encode(m),M=0;for(let V=0;V<O.length;V++)M|=O[V]^J[V];return M===0}let{createHmac:f,timingSafeEqual:d}=await import('crypto'),y=`sha256=${f("sha256",n).update(e).digest("hex")}`;return t.length!==y.length?false:d(Buffer.from(t),Buffer.from(y))}async rotateKeys(){let e=U.default.sign.keyPair(),t=U.default.box.keyPair(),n=U.default.box.keyPair(),i=(this._signedPrekeyId||0)+1,f=U.default.sign.detached(n.publicKey,e.secretKey),d={signing_public_key:(0, g.encodeBase64)(e.publicKey),encryption_public_key:(0, g.encodeBase64)(t.publicKey),signed_prekey_public:(0, g.encodeBase64)(n.publicKey),signed_prekey_signature:(0, g.encodeBase64)(f),signed_prekey_id:i};if(this.postQuantum&&this.mlkemPublicKey&&(d.mlkem_public_key=this.mlkemPublicKey),!(await this._timedFetch(`${this.baseUrl}/v1/agent/rotate-keys`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(d)})).ok)throw new Error("Key rotation failed");this.signingKeyPair=e,this.encryptionKeyPair=t,this._signedPrekey=n,this._signedPrekeyId=i,this._identityCache.clear(),this._pinnedDids.clear(),await this.uploadPrekeys(10);}async createChannel(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/channels`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(e)});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Channel creation failed: ${n.error||t.statusText}`)}return await t.json()}async listChannels(e={}){let t=new URLSearchParams;e.topic&&t.set("topic",e.topic),e.query&&t.set("q",e.query),e.mine&&t.set("mine","true"),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/channels?${t}`,{headers:e.mine?{"X-Agent-Key":this.apiKey}:{}});return n.ok?(await n.json()).channels:[]}async joinChannel(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/join`,{method:"POST",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Join failed: ${n.error||t.statusText}`)}return await t.json()}async leaveChannel(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/leave`,{method:"POST",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Leave failed: ${n.error||t.statusText}`)}}async postToChannel(e,t,n){let i=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({message:t,reply_to:n})});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Post failed: ${f.error||i.statusText}`)}return await i.json()}async readChannel(e,t={}){let n=new URLSearchParams;t.since&&n.set("since",t.since),t.before&&n.set("before",t.before),t.limit&&n.set("limit",String(t.limit));let i=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/messages?${n}`,{headers:{"X-Agent-Key":this.apiKey}});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Read failed: ${f.error||i.statusText}`)}return await i.json()}async deactivate(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/deactivate`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!e.ok){let t=await e.json().catch(()=>({}));throw new Error(`Deactivate failed: ${t.error||e.statusText}`)}}async registerCapability(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({name:e.name,description:e.description,input_schema:e.inputSchema,output_schema:e.outputSchema,version:e.version})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Capability registration failed: ${n.error||t.statusText}`)}return await t.json()}async listCapabilities(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities`,{headers:{"X-Agent-Key":this.apiKey}});return e.ok?(await e.json()).capabilities:[]}async searchCapabilities(e={}){let t=new URLSearchParams;e.query&&t.set("q",e.query),e.name&&t.set("name",e.name),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/search?${t}`);return n.ok?(await n.json()).results:[]}async deleteCapability(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/capabilities/${e}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Delete failed: ${n.error||t.statusText}`)}}async createTask(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${e.to}`);if(!t.ok)throw new Error("Recipient agent not found");let n=await t.json(),i=(0, g.decodeBase64)(n.encryption_public_key),f=(0, g.decodeUTF8)(JSON.stringify(e.input)),d=U.default.randomBytes(U.default.box.nonceLength),y=U.default.box(f,d,i,this.encryptionKeyPair.secretKey),_=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({to:e.to,capability:e.capability,encrypted_input:(0, g.encodeBase64)(y),input_nonce:(0, g.encodeBase64)(d),priority:e.priority||"normal",expires_in:e.expiresIn})});if(!_.ok){let K=await _.json().catch(()=>({}));throw new Error(`Task creation failed: ${K.error||_.statusText}`)}return await _.json()}async listTasks(e={}){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.capability&&t.set("capability",e.capability),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks?${t}`,{headers:{"X-Agent-Key":this.apiKey}});return n.ok?(await n.json()).tasks:[]}async getTask(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${e}`,{headers:{"X-Agent-Key":this.apiKey}});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Get task failed: ${n.error||t.statusText}`)}return await t.json()}async updateTask(e,t){let n={};if(t.status&&(n.status=t.status),t.rating!==void 0&&(n.rating=t.rating),t.ratingComment&&(n.rating_comment=t.ratingComment),t.output&&(t.status==="completed"||t.status==="failed")){let d=(await this.getTask(e)).from,y=await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${d}`);if(y.ok){let _=await y.json(),K=(0, g.decodeBase64)(_.encryption_public_key),m=(0, g.decodeUTF8)(JSON.stringify(t.output)),O=U.default.randomBytes(U.default.box.nonceLength),J=U.default.box(m,O,K,this.encryptionKeyPair.secretKey),M=U.default.sign.detached(m,this.signingKeyPair.secretKey);n.encrypted_output=(0, g.encodeBase64)(J),n.output_nonce=(0, g.encodeBase64)(O),n.output_signature=(0, g.encodeBase64)(M);}}let i=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(n)});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Task update failed: ${f.error||i.statusText}`)}return await i.json()}decryptTaskInput(e,t){try{let n=(0,g.decodeBase64)(e.encrypted_input),i=(0,g.decodeBase64)(e.input_nonce),f=U.default.box.open(n,i,t,this.encryptionKeyPair.secretKey);return f?JSON.parse((0,g.encodeUTF8)(f)):null}catch{return null}}decryptTaskOutput(e,t){try{let n=(0,g.decodeBase64)(e.encrypted_output),i=(0,g.decodeBase64)(e.output_nonce),f=U.default.box.open(n,i,t,this.encryptionKeyPair.secretKey);return f?JSON.parse((0,g.encodeUTF8)(f)):null}catch{return null}}async attest(e){let t=e.timestamp||new Date().toISOString(),n=e.claimType+JSON.stringify(e.claimData)+t,i=(0, g.decodeUTF8)(n),f=U.default.sign.detached(i,this.signingKeyPair.secretKey),d=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({claim_type:e.claimType,claim_data:e.claimData,signature:(0, g.encodeBase64)(f),timestamp:t,country:e.country,domain:e.domain,confidence:e.confidence,expires_in:e.expiresIn})});if(!d.ok){let y=await d.json().catch(()=>({}));throw new Error(`Attestation failed: ${y.error||d.statusText}`)}return await d.json()}async corroborate(e,t,n){let i=e+t,f=(0, g.decodeUTF8)(i),d=U.default.sign.detached(f,this.signingKeyPair.secretKey),y=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${e}/corroborate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({vote:t,signature:(0, g.encodeBase64)(d),comment:n})});if(!y.ok){let _=await y.json().catch(()=>({}));throw new Error(`Corroboration failed: ${_.error||y.statusText}`)}return await y.json()}async queryAttestations(e={}){let t=new URLSearchParams;e.country&&t.set("country",e.country),e.domain&&t.set("domain",e.domain),e.type&&t.set("type",e.type),e.agent&&t.set("agent",e.agent),e.minConsensus!==void 0&&t.set("min_consensus",String(e.minConsensus)),e.since&&t.set("since",e.since),e.limit&&t.set("limit",String(e.limit));let n=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations?${t}`);return n.ok?(await n.json()).attestations:[]}async getAttestation(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/${e}`);if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Get attestation failed: ${n.error||t.statusText}`)}return await t.json()}async getConsensus(e){let t=new URLSearchParams;e.country&&t.set("country",e.country),e.domain&&t.set("domain",e.domain),e.type&&t.set("type",e.type);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/attestations/consensus?${t}`);return n.ok?(await n.json()).consensus:[]}async inviteToChannel(e,t,n){let i=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/invite`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({did:t,message:n?.message,expires_hours:n?.expiresHours})});if(!i.ok){let f=await i.json().catch(()=>({}));throw new Error(`Invite failed: ${f.error||i.statusText}`)}return await i.json()}async listInvites(e="pending"){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/invites?status=${e}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});return t.ok?(await t.json()).invites:[]}async respondToInvite(e,t){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/invites/${e}/respond`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({action:t})});if(!n.ok){let i=await n.json().catch(()=>({}));throw new Error(`Invite response failed: ${i.error||n.statusText}`)}return await n.json()}async getTrustScore(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/trust/${e}`);if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error(`Trust score failed: ${n.error||t.statusText}`)}return await t.json()}async getTrustLeaderboard(e){let t=new URLSearchParams;e?.limit&&t.set("limit",e.limit.toString()),e?.minLevel&&t.set("min_level",e.minLevel);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/trust/leaderboard?${t}`);return n.ok?(await n.json()).leaderboard:[]}async markRead(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/messages/${e}/read`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!t.ok)throw new Error(`Failed to mark message as read: ${t.status}`);return await t.json()}async markReadBatch(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/messages/read-batch`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({message_ids:e})});if(!t.ok)throw new Error(`Failed to batch mark messages as read: ${t.status}`);return await t.json()}async getUnreadCount(e){let t=new URLSearchParams;e&&t.set("from",e);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/messages/unread-count?${t}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!n.ok)throw new Error(`Failed to get unread count: ${n.status}`);return await n.json()}async broadcastTask(e){let t=(0, g.decodeUTF8)(e.input),n=U.default.randomBytes(U.default.secretbox.nonceLength),i=U.default.secretbox(t,n,U.default.box.before(this.encryptionKeyPair.publicKey,this.encryptionKeyPair.secretKey)),f=U.default.sign.detached(t,this.signingKeyPair.secretKey),d=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcast`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({capability:e.capability,encrypted_input:(0, g.encodeBase64)(i),input_nonce:(0, g.encodeBase64)(n),input_signature:(0, g.encodeBase64)(f),priority:e.priority,max_agents:e.maxAgents,min_trust_level:e.minTrustLevel,expires_in:e.expiresIn})});if(!d.ok){let y=await d.json().catch(()=>({}));throw new Error(y.error||`Broadcast failed: ${d.status}`)}return await d.json()}async listBroadcasts(e){let t=new URLSearchParams;e&&t.set("status",e);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts?${t}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});return n.ok?(await n.json()).broadcasts:[]}async getBroadcast(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/tasks/broadcasts/${e}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!t.ok)throw new Error(`Failed to get broadcast: ${t.status}`);return await t.json()}async getAnalytics(e){let t=new URLSearchParams;e&&t.set("period",e);let n=await this._timedFetch(`${this.baseUrl}/v1/agent/analytics?${t}`,{headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey}});if(!n.ok)throw new Error(`Failed to get analytics: ${n.status}`);return await n.json()}static verifyAttestation(e,t){try{let n=e.claim_type+JSON.stringify(e.claim_data)+e.timestamp,i=(0,g.decodeUTF8)(n),f=(0,g.decodeBase64)(e.signature),d=(0,g.decodeBase64)(t);return U.default.sign.detached.verify(i,f,d)}catch{return false}}async memorySet(e,t,n,i){let f=JSON.stringify(n),d=(0, g.decodeUTF8)(f),y=U.default.randomBytes(U.default.secretbox.nonceLength),_=new Uint8Array([...this.encryptionKeyPair.secretKey,77,69,77]),K;if(typeof globalThis.crypto?.subtle<"u")K=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",_));else {let{createHash:J}=await import('crypto');K=new Uint8Array(J("sha256").update(Buffer.from(_)).digest());}let m=U.default.secretbox(d,y,K),O=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({value:(0, g.encodeBase64)(m),value_type:`encrypted:${i?.valueType||(typeof n=="object"?"json":typeof n)}`,ttl:i?.ttl,client_nonce:(0, g.encodeBase64)(y)})});if(!O.ok)throw new Error(`Memory set failed: ${O.status} ${await O.text()}`);return O.json()}async memoryGet(e,t){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{headers:{"X-Agent-Key":this.apiKey}});if(n.status===404)return null;if(!n.ok)throw new Error(`Memory get failed: ${n.status} ${await n.text()}`);let i=await n.json();if(i.value_type?.startsWith("encrypted:")&&i.client_nonce)try{let f=new Uint8Array([...this.encryptionKeyPair.secretKey,77,69,77]),d;if(typeof globalThis.crypto?.subtle<"u")d=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",f));else {let{createHash:m}=await import('crypto');d=new Uint8Array(m("sha256").update(Buffer.from(f)).digest());}let y=(0,g.decodeBase64)(i.value),_=(0,g.decodeBase64)(i.client_nonce),K=U.default.secretbox.open(y,_,d);K&&(i.value=JSON.parse((0,g.encodeUTF8)(K)),i.value_type=i.value_type.replace("encrypted:",""));}catch{}return i}async memoryDelete(e,t){let n=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!n.ok)throw new Error(`Memory delete failed: ${n.status} ${await n.text()}`);return n.json()}async memoryList(e,t){let n=e||"default",i=new URLSearchParams;t?.prefix&&i.set("prefix",t.prefix),t?.limit&&i.set("limit",String(t.limit));let f=i.toString()?`?${i.toString()}`:"",d=await this._timedFetch(`${this.baseUrl}/v1/agent/memory/${encodeURIComponent(n)}${f}`,{headers:{"X-Agent-Key":this.apiKey}});if(!d.ok)throw new Error(`Memory list failed: ${d.status} ${await d.text()}`);return d.json()}async memoryNamespaces(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/memory`,{headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error(`Memory namespaces failed: ${e.status} ${await e.text()}`);return e.json()}async exportData(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/export`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({include_messages:e?.includeMessages,include_channels:e?.includeChannels,include_tasks:e?.includeTasks,include_attestations:e?.includeAttestations,include_memory:e?.includeMemory,include_trust:e?.includeTrust})});if(!t.ok)throw new Error(`Export failed: ${t.status} ${await t.text()}`);return t.json()}async listExports(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/exports`,{headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error(`List exports failed: ${e.status} ${await e.text()}`);return e.json()}async getRelayInfo(){let e=await this._timedFetch(`${this.baseUrl}/v1/relay/info`);if(!e.ok)throw new Error(`Relay info failed: ${e.status} ${await e.text()}`);return e.json()}async getRelayPeers(){let e=await this._timedFetch(`${this.baseUrl}/v1/relay/peers`);if(!e.ok)throw new Error(`Relay peers failed: ${e.status} ${await e.text()}`);return e.json()}async routeMessage(e,t,n){let i=await this.getIdentity(e);if(!i)throw new Error(`Recipient ${e} not found`);let f=(0, g.decodeBase64)(i.encryption_public_key),d=U.default.randomBytes(U.default.box.nonceLength),y=U.default.box((0, g.decodeUTF8)(t),d,f,this.encryptionKeyPair.secretKey);if(!y)throw new Error("Encryption failed");let _=(0, g.decodeUTF8)(JSON.stringify({from:this.did,to:e,nonce:(0, g.encodeBase64)(d),ciphertext_hash:await ir((0, g.encodeBase64)(y))})),K=U.default.sign.detached(_,this.signingKeyPair.secretKey),m=await this._timedFetch(`${this.baseUrl}/v1/relay/route`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({to:e,ciphertext:(0, g.encodeBase64)(y),nonce:(0, g.encodeBase64)(d),signature:(0, g.encodeBase64)(K),content_type:n?.contentType||"text/plain",thread_id:n?.threadId})});if(!m.ok)throw new Error(`Route failed: ${m.status} ${await m.text()}`);return m.json()}async ping(){let e=await this._timedFetch(`${this.baseUrl}/v1/agent/ping`,{method:"POST",headers:{"X-Agent-Key":this.apiKey}});if(!e.ok)throw new Error(`Ping failed: ${e.status}`);return e.json()}async checkOnline(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/ping/${encodeURIComponent(e)}`);if(!t.ok)throw new Error(`Ping check failed: ${t.status}`);return t.json()}async pinKeys(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({did:e})});if(!t.ok)throw new Error(`Key pin failed: ${t.status}`);return t.json()}async listPinnedKeys(e){let t=new URLSearchParams;e?.status&&t.set("status",e.status);let n=t.toString()?`?${t.toString()}`:"",i=await this._timedFetch(`${this.baseUrl}/v1/agent/keys/pins${n}`,{headers:{"X-Agent-Key":this.apiKey}});if(!i.ok)throw new Error(`List pins failed: ${i.status}`);return i.json()}async verifyKeys(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/keys/verify/${encodeURIComponent(e)}`,{headers:{"X-Agent-Key":this.apiKey}});if(!t.ok)throw new Error(`Key verify failed: ${t.status}`);return t.json()}async uploadPrekeys(e=20){let t=[];for(let d=0;d<e;d++){let y=U.default.box.keyPair();t.push({id:Date.now()+d,public_key:(0, g.encodeBase64)(y.publicKey),secretKey:y.secretKey});}let n=U.default.box.keyPair();this._signedPrekeyId++;let i=U.default.sign.detached(n.publicKey,this.signingKeyPair.secretKey);this._signedPrekey=n;let f=await this._timedFetch(`${this.baseUrl}/v1/agent/prekeys`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({prekeys:t.map(d=>({id:d.id,public_key:d.public_key})),signed_prekey:{public_key:(0, g.encodeBase64)(n.publicKey),signature:(0, g.encodeBase64)(i),id:this._signedPrekeyId}})});if(!f.ok)throw new Error(`Prekey upload failed: ${f.status}`);return await f.json()}async fetchPrekeys(e){let t=await this._timedFetch(`${this.baseUrl}/v1/agent/prekeys/${encodeURIComponent(e)}`);return t.ok?await t.json():null}async createEncryptedChannel(e){let t=U.default.randomBytes(32),n=await this._timedFetch(`${this.baseUrl}/v1/agent/channels`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(e)});if(!n.ok){let y=await n.json().catch(()=>({}));throw new Error(`Channel creation failed: ${y.error||n.statusText}`)}let i=await n.json(),f=U.default.randomBytes(U.default.box.nonceLength);U.default.box(t,f,this.encryptionKeyPair.publicKey,this.encryptionKeyPair.secretKey);return await this.memorySet("channel-keys",i.id,{key:(0, g.encodeBase64)(t),nonce:(0, g.encodeBase64)(f)}),{...i,channelKey:t}}async postEncrypted(e,t,n){let i=U.default.randomBytes(U.default.secretbox.nonceLength),f=U.default.secretbox((0, g.decodeUTF8)(t),i,n),d=new Uint8Array([...f,...i]),y=U.default.sign.detached(d,this.signingKeyPair.secretKey),_=await this._timedFetch(`${this.baseUrl}/v1/agent/channels/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({message:JSON.stringify({v:3,ct:(0, g.encodeBase64)(f),n:(0, g.encodeBase64)(i),sig:(0, g.encodeBase64)(y),from:this.did})})});if(!_.ok)throw new Error(`Post failed: ${_.status}`);return await _.json()}async readEncrypted(e,t,n){let i=await this.readChannel(e,n),f=[];for(let d of i.messages)try{let y=JSON.parse(typeof d.content=="string"?d.content:d.message||"");if(y.v===3&&y.ct&&y.n){let _=(0,g.decodeBase64)(y.ct),K=(0,g.decodeBase64)(y.n),m=U.default.secretbox.open(_,K,t);if(m){let O=!1;if(y.sig&&y.from)try{let J=await this.getIdentity(y.from);if(J){let M=new Uint8Array([..._,...K]);O=U.default.sign.detached.verify(M,(0,g.decodeBase64)(y.sig),(0,g.decodeBase64)(J.signing_public_key));}}catch{}f.push({id:d.id,from:y.from||d.author||"unknown",content:(0,g.encodeUTF8)(m),timestamp:d.created_at||d.timestamp,signatureValid:O});}}}catch{}return {messages:f,count:f.length}}listen(e,t={},n){let i=Math.max(t.interval||2e3,500),f=t.adaptive!==false,d=t.autoMarkRead!==false,y=t.unreadOnly!==false,_=t.heartbeat!==false,K=t.heartbeatInterval||6e4,m=true,O=i,J=0,M,V=null,H=null,be={stop:()=>{m=false,V&&clearTimeout(V),H&&clearInterval(H),this._listeners.delete(be);},get active(){return m}};this._listeners.add(be),_&&(H=setInterval(async()=>{if(m)try{await this.ping();}catch{}},K),this.ping().catch(()=>{}));let qe=async he=>{for(let j of he)try{await e(j),d&&await this.markRead(j.id).catch(()=>{});}catch(P){n&&n(P instanceof Error?P:new Error(String(P)));}he.length>0&&(M=he[he.length-1].timestamp);},Ee="",$e=0,Be=async()=>{try{let he=new URLSearchParams;M&&he.set("since",M),t.from&&he.set("from",t.from);let j=`${this.baseUrl}/v1/agent/receive/sse?${he}`,P={"X-Agent-Key":this.apiKey};Ee&&(P["Last-Event-ID"]=Ee);let xe=new AbortController,pe=setTimeout(()=>xe.abort(),6e4),D;try{D=await fetch(j,{headers:P,signal:xe.signal});}catch(ye){throw clearTimeout(pe),ye}if(!D.ok||!D.body)return clearTimeout(pe),!1;let z=D.body.getReader(),ve=new TextDecoder,_e="";try{let ye="",we="",Se="";for(;m&&!t.signal?.aborted;){let{done:Ne,value:Ue}=await z.read();if(Ne)break;_e+=ve.decode(Ue,{stream:!0});let Re=_e.split(`
3
+ `);_e=Re.pop()||"";for(let X of Re)if(X.startsWith("event: "))ye=X.slice(7).trim();else if(X.startsWith("data: "))we+=(we?`
4
+ `:"")+X.slice(6);else if(X.startsWith("id: "))Se=X.slice(4).trim();else if(X===""&&(we||ye)){if(Se&&(Ee=Se),ye==="message"&&we)try{let ke=JSON.parse(we),{decrypted:He,failedIds:Ge}=await this._decryptMessages([ke]);for(let st of Ge)try{await this.markRead(st);}catch{}He.length>0&&(J=0,$e=0,await qe(He));}catch{}else if(ye==="reconnect")break;ye="",we="",Se="";}}}finally{z.releaseLock(),clearTimeout(pe);}return $e=0,!0}catch{return $e++,false}},Me=async()=>{for(;m&&!t.signal?.aborted;){let he=await Be();if(!m||t.signal?.aborted)break;if(!he){if($e>=3){Le();return}let j=Math.min(1e3*Math.pow(2,$e-1),4e3);await new Promise(P=>setTimeout(P,j));continue}await new Promise(j=>setTimeout(j,500));}},Je=this.longPoll,Le=async()=>{if(!m||t.signal?.aborted){be.stop();return}try{let he=await this.receive({since:M,from:t.from,threadId:t.threadId,messageType:t.messageType,unreadOnly:y,limit:50});he.length>0?(J=0,f&&(O=Math.max(i/2,500)),await qe(he)):(J++,f&&J>3&&!Je&&(O=Math.min(O*1.5,i*4)));}catch(he){n&&n(he instanceof Error?he:new Error(String(he))),O=Math.min(O*2,i*8);}m&&!t.signal?.aborted&&(V=setTimeout(Le,Je?100:O));};return this._transportPrefs.includes("sse")?Me():Le(),be}async*messages(e={}){let t=[],n=null,i=false,f=this.listen(d=>{t.push(d),n&&(n(),n=null);},{...e,autoMarkRead:e.autoMarkRead!==false});e.signal?.addEventListener("abort",()=>{i=true,f.stop(),n&&(n(),n=null);});try{for(;!i&&!e.signal?.aborted;)t.length>0?yield t.shift():await new Promise(d=>{n=d;});}finally{f.stop();}}stopAll(){for(let e of this._listeners)e.stop();this._listeners.clear(),this._rpcListener&&(this._rpcListener.stop(),this._rpcListener=null);for(let[e,t]of this._rpcPending)clearTimeout(t.timer),t.reject(new Error("Agent stopped"));this._rpcPending.clear(),this.disableCoverTraffic();}async invoke(e,t,n={},i=3e4){let f=`rpc-${Date.now()}-${Math.random().toString(36).slice(2,10)}`;return new Promise(async(d,y)=>{let _=setTimeout(()=>{this._rpcPending.delete(f),y(new Error(`RPC timeout: ${t}@${e} after ${i}ms`));},i);this._rpcPending.set(f,{resolve:d,reject:y,timer:_});try{await this.send(e,JSON.stringify({jsonrpc:"2.0",method:t,params:n,id:f}),{messageType:"rpc-request",threadId:f});}catch(K){clearTimeout(_),this._rpcPending.delete(f),y(K);}})}onInvoke(e,t){this._rpcHandlers.set(e,t),this._ensureRpcListener();}offInvoke(e){this._rpcHandlers.delete(e),this._rpcHandlers.size===0&&this._rpcListener&&(this._rpcListener.stop(),this._rpcListener=null);}_ensureRpcListener(){this._rpcListener||(this._rpcListener=this.listen(async e=>{try{let t=JSON.parse(e.content);if(t.jsonrpc!=="2.0")return;if(t.id&&(t.result!==void 0||t.error)){let n=this._rpcPending.get(t.id);n&&(clearTimeout(n.timer),this._rpcPending.delete(t.id),t.error?n.reject(new Error(t.error.message||"RPC error")):n.resolve(t.result));return}if(t.method&&t.id){let n=this._rpcHandlers.get(t.method);if(!n){await this.send(e.from,JSON.stringify({jsonrpc:"2.0",id:t.id,error:{code:-32601,message:`Method not found: ${t.method}`}}),{messageType:"rpc-response",threadId:t.id});return}try{let i=await n(t.params||{},e.from);await this.send(e.from,JSON.stringify({jsonrpc:"2.0",id:t.id,result:i}),{messageType:"rpc-response",threadId:t.id});}catch(i){await this.send(e.from,JSON.stringify({jsonrpc:"2.0",id:t.id,error:{code:-32e3,message:i.message||"Handler error"}}),{messageType:"rpc-response",threadId:t.id});}}}catch{}},{interval:500,adaptive:false,heartbeat:false}));}async sendDirect(e,t,n={}){try{let f=await this.getIdentity(e);if(f){let d=await this._timedFetch(`${this.baseUrl}/v1/agent/identity/${e}`,{headers:{"X-Agent-Key":this.apiKey}});if(d.ok){let _=(await d.json()).webhook_url;if(_){let K=U.default.randomBytes(U.default.box.nonceLength),m=(0,g.decodeBase64)(f.encryption_public_key),O=(0,g.decodeUTF8)(t),J=U.default.box(O,K,m,this.encryptionKeyPair.secretKey),M=JSON.stringify({from:this.did,to:e,ciphertext:(0,g.encodeBase64)(J),nonce:(0,g.encodeBase64)(K),timestamp:new Date().toISOString(),message_type:n.messageType||"text",thread_id:n.threadId}),V=U.default.sign.detached((0,g.decodeUTF8)(M),this.signingKeyPair.secretKey);if((await this._timedFetch(_,{method:"POST",headers:{"Content-Type":"application/json","X-Voidly-Signature":`sha256=${(0,g.encodeBase64)(V)}`,"X-Voidly-Sender":this.did},body:M})).ok){let be=new Date;return {id:`direct-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,from:this.did,to:e,timestamp:be.toISOString(),expiresAt:new Date(be.getTime()+864e5).toISOString(),encrypted:!0,clientSide:!0,direct:!0}}}}}}catch{}return {...await this.send(e,t,n),direct:false}}enableCoverTraffic(e={}){this.disableCoverTraffic();let t=e.intervalMs||3e4,n=async()=>{try{let f=U.default.randomBytes(128+Math.floor(Math.random()*384));await this.send(this.did,(0,g.encodeBase64)(f),{messageType:"ping",ttl:60});}catch{}},i=()=>{let f=t*(.5+Math.random());this._coverTrafficTimer=setTimeout(async()=>{await n(),this._coverTrafficTimer!==null&&i();},f);};i();}disableCoverTraffic(){this._coverTrafficTimer!==null&&(clearTimeout(this._coverTrafficTimer),this._coverTrafficTimer=null);}async _resilientFetch(e,t){let n=[this.baseUrl,...this.fallbackRelays],i=null;for(let f of n)try{let d=await this._timedFetch(`${f}${e}`,t);if(d.ok||d.status>=400&&d.status<500&&d.status!==429)return d;if(d.status===429){let y=d.headers.get("Retry-After"),_=y?Math.min(parseInt(y,10)*1e3,5e3):1e3;await new Promise(K=>setTimeout(K,_));}}catch(d){i=d instanceof Error?d:new Error(String(d));}throw i||new Error("All relays failed")}conversation(e,t){let n=t||`conv-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,i=`${e}:${n}`;if(this._conversations.has(i))return this._conversations.get(i);let f=new ar(this,e,n);return this._conversations.set(i,f),f}async _timedFetch(e,t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);try{return await fetch(e,{...t,signal:n.signal})}catch(f){throw f instanceof Error&&f.name==="AbortError"?new Error(`Request timed out after ${this.timeout}ms: ${e.replace(this.baseUrl,"")}`):f}finally{clearTimeout(i);}}async _autoPinKeys(e){if(!this._pinnedDids.has(e)){this._pinnedDids.add(e);try{let t=await this.pinKeys(e);t.key_changed&&t.warning&&console.warn(`[voidly] \u26A0 Key change detected for ${e}: ${t.warning}`);}catch{}}}async _fetchWithRetry(e,t,n={}){let i=n.maxRetries??3,f=n.baseDelay??500,d=n.maxDelay??1e4,y=null;for(let _=0;_<=i;_++){try{let K=await this._timedFetch(e,t);if(K.ok)return await K.json();let m=await K.json().catch(()=>({})),O=m.error?.message||m.error||K.statusText;if(K.status>=400&&K.status<500)throw new Error(`Send failed (${K.status}): ${O}`);y=new Error(`Send failed (${K.status}): ${O}`);}catch(K){if(K instanceof Error&&K.message.startsWith("Send failed (4"))throw K;y=K instanceof Error?K:new Error(String(K));}if(_<i){let m=Math.min(f*Math.pow(2,_),d)*(.5+Math.random()*.5);await new Promise(O=>setTimeout(O,m));}}throw y||new Error("Send failed after retries")}async drainQueue(){let e=0,t=0,n=[];for(let i of this._offlineQueue){if(Date.now()-i.timestamp>864e5){t++;continue}try{await this.send(i.recipientDid,i.message,i.options),e++;}catch{n.push(i),t++;}}return this._offlineQueue=n,{sent:e,failed:t,remaining:n.length}}get queueLength(){return this._offlineQueue.length}threatModel(){return {relayCanSee:["Your DID (public identifier)","Recipient DIDs (relay needs them for routing)",...this.jitterMs>0?["Approximate timing (jittered timestamps)"]:["When you message (timestamps)"],...this.sealedSender?[]:["Message types, thread IDs, content types (sent in cleartext without sealed sender)"],"Channel membership (but NOT channel message content with client-side encryption)","Capability registrations","Approximate message size (even with padding, bounded to power-of-2)"],relayCannotSee:["Message content (E2E encrypted \u2014 nacl.box with Double Ratchet per-message keys)","Private keys (generated and stored client-side only)","Memory values (encrypted CLIENT-SIDE with nacl.secretbox before relay storage)","Past message keys (forward secrecy \u2014 hash ratchet + DH ratchet, old keys deleted)","Future message keys (post-compromise recovery via DH ratchet \u2014 compromise heals after one round-trip)","Channel message content (client-side nacl.secretbox encryption \u2014 relay stores only ciphertext)",...this.sealedSender?['Sender identity (sealed inside ciphertext \u2014 relay stores "sealed" not your DID)',"Message types, thread IDs, reply chains (packed inside ciphertext in v3)","Message count (not incremented for sealed senders)"]:[],...this.deniable?["Who authored a message (HMAC is symmetric \u2014 either party could have produced it)"]:[]],protections:[...this.doubleRatchet?["Double Ratchet (Signal Protocol) \u2014 DH ratchet for post-compromise recovery + hash ratchet for forward secrecy"]:["Hash ratchet forward secrecy \u2014 per-message key derivation, old keys deleted"],...this.postQuantum&&this.mlkemPublicKey?["ML-KEM-768 + X25519 hybrid key exchange (NIST FIPS 203 post-quantum, harvest-now-decrypt-later resistant)"]:[],"X3DH async key agreement (signed prekeys + one-time prekeys for offline session establishment)","X25519 key exchange + XSalsa20-Poly1305 authenticated encryption",...this.deniable?["Deniable authentication (HMAC-SHA256 with shared DH secret \u2014 both parties can produce the MAC)"]:["Ed25519 signatures on every message (envelope + ciphertext hash)"],"TOFU key pinning (MitM detection on key change)","Client-side memory encryption (relay never sees plaintext values)","Client-side channel encryption (nacl.secretbox \u2014 relay never sees channel plaintext)","Protocol version header (deterministic padding/sealing/ratchet detection, no heuristics)","Identity cache (reduced key lookups, 5-min TTL)","Message deduplication (track seen message IDs)","Request timeouts (AbortController on all HTTP, configurable)","Request validation (fromCredentials validates key sizes and format)",...this.paddingEnabled?["Message padding to power-of-2 boundary (traffic analysis resistance)"]:[],...this.sealedSender?["Sealed sender (relay cannot see who sent a message)","Metadata privacy (v3 \u2014 thread_id, message_type, reply_to packed inside ciphertext, stripped from relay storage)"]:[],...this.requireSignatures?["Strict signature enforcement (reject unsigned/invalid messages)"]:[],...this.fallbackRelays.length>0?[`Multi-relay fallback (${this.fallbackRelays.length} backup relays \u2014 receive, discover, identity all use fallbacks)`]:[],...this.jitterMs>0?[`Timing jitter (random ${this.jitterMs}ms delay \u2014 metadata timing protection)`]:[],...this._transportPrefs.includes("sse")?["SSE streaming transport (real-time push delivery from relay)"]:[],...this.longPoll?["Long-poll transport (25s server-held connection \u2014 near-real-time delivery)"]:[],...this._persistMode!=="memory"?[`Ratchet state auto-persistence (${this._persistMode} backend \u2014 survives process restart)`]:[],...this._coverTrafficTimer!==null?["Cover traffic (encrypted noise at random intervals \u2014 traffic analysis resistance)"]:[],"Agent RPC (invoke/onInvoke \u2014 synchronous function calls between agents)","P2P direct send (bypass relay via webhook \u2014 true peer-to-peer when possible)","Resilient operations (receive, discover, identity \u2014 all try fallback relays)","Auto-retry with exponential backoff","Offline message queue","did:key interoperability (W3C standard DID format)"],gaps:[...!this.postQuantum||!this.mlkemPublicKey?["No post-quantum protection \u2014 enable postQuantum option and re-register"]:[],...this.sealedSender?["Relay sees to_did (needed for routing) but NOT from_did, thread_id, or message_type"]:["Relay sees from_did, to_did, thread_id, message_type in cleartext \u2014 enable sealedSender to strip metadata"],"Relay sees channel membership, task delegation, trust scores (social graph)",...this.fallbackRelays.length===0?["Single relay with no fallbacks \u2014 configure fallbackRelays for resilience"]:[],...this._persistMode==="memory"?["Ratchet state is in-memory (lost on process restart \u2014 use persist option or exportCredentials)"]:[],...this.deniable?[]:["Ed25519 signatures are non-repudiable \u2014 enable deniable option for HMAC auth"],...this.doubleRatchet?[]:["Hash ratchet only \u2014 enable doubleRatchet option for post-compromise recovery"],...this.jitterMs===0?["No timing jitter \u2014 enable jitterMs option for metadata protection"]:[],...this._coverTrafficTimer===null?["No cover traffic \u2014 call enableCoverTraffic() to resist traffic analysis"]:[]]}}},ar=class{constructor(e,t,n){this._lastMessageId=null;this._messageHistory=[];this._listener=null;this._replyHandlers=[];this.agent=e,this.peerDid=t,this.threadId=n;}async say(e,t){let n=await this.agent.send(this.peerDid,e,{...t,threadId:this.threadId,replyTo:this._lastMessageId||void 0});return this._lastMessageId=n.id,this._messageHistory.length>=1e3&&this._messageHistory.splice(0,this._messageHistory.length-999),this._messageHistory.push({id:n.id,from:this.agent.did,content:e,timestamp:n.timestamp,signatureValid:true,messageType:t?.messageType||"text"}),n}async history(e){let t=await this.agent.receive({threadId:this.threadId,from:this.peerDid,limit:e?.limit||100}),n=[...this._messageHistory,...t.map(f=>({id:f.id,from:f.from,content:f.content,timestamp:f.timestamp,signatureValid:f.signatureValid,messageType:f.messageType}))],i=new Set;return n.filter(f=>i.has(f.id)?false:(i.add(f.id),true)).sort((f,d)=>new Date(f.timestamp).getTime()-new Date(d.timestamp).getTime())}onReply(e){this._replyHandlers.push(e),this._listener||(this._listener=this.agent.listen(async t=>{this._messageHistory.push({id:t.id,from:t.from,content:t.content,timestamp:t.timestamp,signatureValid:t.signatureValid,messageType:t.messageType}),this._lastMessageId=t.id;for(let n of this._replyHandlers)try{await n(t);}catch{}},{from:this.peerDid,threadId:this.threadId,autoMarkRead:true}));}async waitForReply(e=3e4){return new Promise((t,n)=>{let i=false,f=null,d=()=>{i=true,f&&(clearTimeout(f),f=null);},y=setTimeout(()=>{i||(d(),n(new Error(`No reply received within ${e}ms`)));},e),_=async()=>{if(!i){try{let K=await this.agent.receive({from:this.peerDid,threadId:this.threadId,unreadOnly:!0,limit:1});if(K.length>0&&!i){clearTimeout(y),d();let m=K[0];this._messageHistory.length>=1e3&&this._messageHistory.splice(0,this._messageHistory.length-999),this._messageHistory.push({id:m.id,from:m.from,content:m.content,timestamp:m.timestamp,signatureValid:m.signatureValid,messageType:m.messageType}),this._lastMessageId=m.id,await this.agent.markRead(m.id).catch(()=>{}),t(m);return}}catch(K){if(!i){clearTimeout(y),d(),n(K instanceof Error?K:new Error(String(K)));return}}i||(f=setTimeout(_,1500));}};_();})}close(){this._listener&&(this._listener.stop(),this._listener=null),this._replyHandlers=[];}get length(){return this._messageHistory.length}get lastMessage(){return this._messageHistory.length>0?this._messageHistory[this._messageHistory.length-1]:null}};var export_decodeBase64=g.decodeBase64;var export_decodeUTF8=g.decodeUTF8;var export_encodeBase64=g.encodeBase64;var export_encodeUTF8=g.encodeUTF8;var export_nacl=U.default;/*! Bundled license information:
5
5
 
6
6
  mlkem/esm/src/sha3/utils.js:
7
7
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)