@voidly/agent-sdk 3.4.9 → 3.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/index.d.ts +42 -0
- package/dist/index.js +2 -2
- package/dist/index.mjs +2 -2
- package/package.json +5 -3
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]),q=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 J(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 J(s,c,o,r,16)}function xe(s,c,o,r){return J(s,c,o,r,32)}function Le(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,C=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,D=u,j=p,F=v,B=T,R=L,b=C,x=fe,k=$,w=Y,S=Q,A=te,X=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+X|0,B^=h<<7|h>>>25,h=B+I|0,k^=h<<9|h>>>23,h=k+B|0,X^=h<<13|h>>>19,h=X+k|0,I^=h<<18|h>>>14,h=R+D|0,w^=h<<7|h>>>25,h=w+R|0,re^=h<<9|h>>>23,h=re+w|0,D^=h<<13|h>>>19,h=D+re|0,R^=h<<18|h>>>14,h=S+b|0,se^=h<<7|h>>>25,h=se+S|0,j^=h<<9|h>>>23,h=j+se|0,b^=h<<13|h>>>19,h=b+j|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,D^=h<<7|h>>>25,h=D+I|0,j^=h<<9|h>>>23,h=j+D|0,F^=h<<13|h>>>19,h=F+j|0,I^=h<<18|h>>>14,h=R+B|0,b^=h<<7|h>>>25,h=b+R|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,R^=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,X^=h<<7|h>>>25,h=X+ne|0,re^=h<<9|h>>>23,h=re+X|0,se^=h<<13|h>>>19,h=se+re|0,ne^=h<<18|h>>>14;I=I+l|0,D=D+u|0,j=j+p|0,F=F+v|0,B=B+T|0,R=R+L|0,b=b+C|0,x=x+fe|0,k=k+$|0,w=w+Y|0,S=S+Q|0,A=A+te|0,X=X+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]=D>>>0&255,s[5]=D>>>8&255,s[6]=D>>>16&255,s[7]=D>>>24&255,s[8]=j>>>0&255,s[9]=j>>>8&255,s[10]=j>>>16&255,s[11]=j>>>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]=R>>>0&255,s[21]=R>>>8&255,s[22]=R>>>16&255,s[23]=R>>>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]=X>>>0&255,s[49]=X>>>8&255,s[50]=X>>>16&255,s[51]=X>>>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 Re(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,C=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,D=u,j=p,F=v,B=T,R=L,b=C,x=fe,k=$,w=Y,S=Q,A=te,X=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+X|0,B^=h<<7|h>>>25,h=B+I|0,k^=h<<9|h>>>23,h=k+B|0,X^=h<<13|h>>>19,h=X+k|0,I^=h<<18|h>>>14,h=R+D|0,w^=h<<7|h>>>25,h=w+R|0,re^=h<<9|h>>>23,h=re+w|0,D^=h<<13|h>>>19,h=D+re|0,R^=h<<18|h>>>14,h=S+b|0,se^=h<<7|h>>>25,h=se+S|0,j^=h<<9|h>>>23,h=j+se|0,b^=h<<13|h>>>19,h=b+j|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,D^=h<<7|h>>>25,h=D+I|0,j^=h<<9|h>>>23,h=j+D|0,F^=h<<13|h>>>19,h=F+j|0,I^=h<<18|h>>>14,h=R+B|0,b^=h<<7|h>>>25,h=b+R|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,R^=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,X^=h<<7|h>>>25,h=X+ne|0,re^=h<<9|h>>>23,h=re+X|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]=R>>>0&255,s[5]=R>>>8&255,s[6]=R>>>16&255,s[7]=R>>>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){Le(s,c,o,r);}function Ce(s,c,o,r){Re(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 Ve(s,c,o,r,l,u,p){var v=new Uint8Array(16),T=new Uint8Array(64),L,C;for(C=0;C<16;C++)v[C]=0;for(C=0;C<8;C++)v[C]=u[C];for(;l>=64;){for($e(T,v,p,Me),C=0;C<64;C++)s[c+C]=o[r+C]^T[C];for(L=1,C=8;C<16;C++)L=L+(v[C]&255)|0,v[C]=L&255,L>>>=8;l-=64,c+=64,r+=64;}if(l>0)for($e(T,v,p,Me),C=0;C<l;C++)s[c+C]=o[r+C]^T[C];return 0}function He(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 ze(s,c,o,r,l){var u=new Uint8Array(32);Ce(u,r,l,Me);for(var p=new Uint8Array(8),v=0;v<8;v++)p[v]=r[v+16];return He(s,c,o,p,u)}function De(s,c,o,r,l,u,p){var v=new Uint8Array(32);Ce(v,u,p,Me);for(var T=new Uint8Array(8),L=0;L<8;L++)T[L]=u[L+16];return Ve(s,c,o,r,l,T,v)}var E=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;};E.prototype.blocks=function(s,c,o){for(var r=this.fin?0:2048,l,u,p,v,T,L,C,fe,$,Y,Q,te,ee,G,W,Z,I,D,j,F=this.h[0],B=this.h[1],R=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],X=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,R+=(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,C=s[c+12]&255|(s[c+13]&255)<<8,S+=(L>>>11|C<<5)&8191,fe=s[c+14]&255|(s[c+15]&255)<<8,A+=(C>>>8|fe<<8)&8191,X+=fe>>>5|r,$=0,Y=$,Y+=F*re,Y+=B*(5*ce),Y+=R*(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+=X*(5*se),$+=Y>>>13,Y&=8191,Q=$,Q+=F*se,Q+=B*re,Q+=R*(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+=X*(5*ne),$+=Q>>>13,Q&=8191,te=$,te+=F*ne,te+=B*se,te+=R*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+=X*(5*h),$+=te>>>13,te&=8191,ee=$,ee+=F*h,ee+=B*ne,ee+=R*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+=X*(5*ae),$+=ee>>>13,ee&=8191,G=$,G+=F*ae,G+=B*h,G+=R*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+=X*(5*le),$+=G>>>13,G&=8191,W=$,W+=F*le,W+=B*ae,W+=R*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+=X*(5*de),$+=W>>>13,W&=8191,Z=$,Z+=F*de,Z+=B*le,Z+=R*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+=X*(5*ie),$+=Z>>>13,Z&=8191,I=$,I+=F*ie,I+=B*de,I+=R*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+=X*(5*oe),$+=I>>>13,I&=8191,D=$,D+=F*oe,D+=B*ie,D+=R*de,D+=b*le,D+=x*ae,$=D>>>13,D&=8191,D+=k*h,D+=w*ne,D+=S*se,D+=A*re,D+=X*(5*ce),$+=D>>>13,D&=8191,j=$,j+=F*ce,j+=B*oe,j+=R*ie,j+=b*de,j+=x*le,$=j>>>13,j&=8191,j+=k*ae,j+=w*h,j+=S*ne,j+=A*se,j+=X*re,$+=j>>>13,j&=8191,$=($<<2)+$|0,$=$+Y|0,Y=$&8191,$=$>>>13,Q+=$,F=Y,B=Q,R=te,b=ee,x=G,k=W,w=Z,S=I,A=D,X=j,c+=16,o-=16;this.h[0]=F,this.h[1]=B,this.h[2]=R,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]=X;},E.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;},E.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 E(u);return p.update(o,r,l),p.finish(s,c),0}function he(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(De(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 N(s,c,o,r,l){var u,p=new Uint8Array(32);if(o<32||(ze(p,0,32,r,l),he(c,16,c,32,o-32,p)!==0))return -1;for(De(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 we(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 Se(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 ge(s,c){var o,r,l,u=e(),p=e();for(o=0;o<16;o++)p[o]=c[o];for(we(p),we(p),we(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,Se(p,u,1-l);}for(o=0;o<16;o++)s[2*o]=p[o]&255,s[2*o+1]=p[o]>>8;}function _e(s,c){var o=new Uint8Array(32),r=new Uint8Array(32);return ge(o,s),ge(r,c),xe(o,0,r,0)}function ve(s){var c=new Uint8Array(32);return ge(c,s),c[0]&1}function Ie(s,c){var o;for(o=0;o<16;o++)s[o]=c[2*o]+(c[2*o+1]<<8);s[15]&=32767;}function Te(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]+o[r];}function je(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]-o[r];}function V(s,c,o){var r,l,u=0,p=0,v=0,T=0,L=0,C=0,fe=0,$=0,Y=0,Q=0,te=0,ee=0,G=0,W=0,Z=0,I=0,D=0,j=0,F=0,B=0,R=0,b=0,x=0,k=0,w=0,S=0,A=0,X=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],Ae=o[7],ye=o[8],ke=o[9],Ke=o[10],Pe=o[11],Ue=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,C+=r*oe,fe+=r*ce,$+=r*Ae,Y+=r*ye,Q+=r*ke,te+=r*Ke,ee+=r*Pe,G+=r*Ue,W+=r*Fe,Z+=r*Oe,I+=r*Be,r=c[1],p+=r*h,v+=r*ae,T+=r*le,L+=r*de,C+=r*ie,fe+=r*oe,$+=r*ce,Y+=r*Ae,Q+=r*ye,te+=r*ke,ee+=r*Ke,G+=r*Pe,W+=r*Ue,Z+=r*Fe,I+=r*Oe,D+=r*Be,r=c[2],v+=r*h,T+=r*ae,L+=r*le,C+=r*de,fe+=r*ie,$+=r*oe,Y+=r*ce,Q+=r*Ae,te+=r*ye,ee+=r*ke,G+=r*Ke,W+=r*Pe,Z+=r*Ue,I+=r*Fe,D+=r*Oe,j+=r*Be,r=c[3],T+=r*h,L+=r*ae,C+=r*le,fe+=r*de,$+=r*ie,Y+=r*oe,Q+=r*ce,te+=r*Ae,ee+=r*ye,G+=r*ke,W+=r*Ke,Z+=r*Pe,I+=r*Ue,D+=r*Fe,j+=r*Oe,F+=r*Be,r=c[4],L+=r*h,C+=r*ae,fe+=r*le,$+=r*de,Y+=r*ie,Q+=r*oe,te+=r*ce,ee+=r*Ae,G+=r*ye,W+=r*ke,Z+=r*Ke,I+=r*Pe,D+=r*Ue,j+=r*Fe,F+=r*Oe,B+=r*Be,r=c[5],C+=r*h,fe+=r*ae,$+=r*le,Y+=r*de,Q+=r*ie,te+=r*oe,ee+=r*ce,G+=r*Ae,W+=r*ye,Z+=r*ke,I+=r*Ke,D+=r*Pe,j+=r*Ue,F+=r*Fe,B+=r*Oe,R+=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*Ae,Z+=r*ye,I+=r*ke,D+=r*Ke,j+=r*Pe,F+=r*Ue,B+=r*Fe,R+=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*Ae,I+=r*ye,D+=r*ke,j+=r*Ke,F+=r*Pe,B+=r*Ue,R+=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*Ae,D+=r*ye,j+=r*ke,F+=r*Ke,B+=r*Pe,R+=r*Ue,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,D+=r*Ae,j+=r*ye,F+=r*ke,B+=r*Ke,R+=r*Pe,b+=r*Ue,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,D+=r*ce,j+=r*Ae,F+=r*ye,B+=r*ke,R+=r*Ke,b+=r*Pe,x+=r*Ue,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,D+=r*oe,j+=r*ce,F+=r*Ae,B+=r*ye,R+=r*ke,b+=r*Ke,x+=r*Pe,k+=r*Ue,w+=r*Fe,S+=r*Oe,A+=r*Be,r=c[12],G+=r*h,W+=r*ae,Z+=r*le,I+=r*de,D+=r*ie,j+=r*oe,F+=r*ce,B+=r*Ae,R+=r*ye,b+=r*ke,x+=r*Ke,k+=r*Pe,w+=r*Ue,S+=r*Fe,A+=r*Oe,X+=r*Be,r=c[13],W+=r*h,Z+=r*ae,I+=r*le,D+=r*de,j+=r*ie,F+=r*oe,B+=r*ce,R+=r*Ae,b+=r*ye,x+=r*ke,k+=r*Ke,w+=r*Pe,S+=r*Ue,A+=r*Fe,X+=r*Oe,re+=r*Be,r=c[14],Z+=r*h,I+=r*ae,D+=r*le,j+=r*de,F+=r*ie,B+=r*oe,R+=r*ce,b+=r*Ae,x+=r*ye,k+=r*ke,w+=r*Ke,S+=r*Pe,A+=r*Ue,X+=r*Fe,re+=r*Oe,se+=r*Be,r=c[15],I+=r*h,D+=r*ae,j+=r*le,F+=r*de,B+=r*ie,R+=r*oe,b+=r*ce,x+=r*Ae,k+=r*ye,w+=r*ke,S+=r*Ke,A+=r*Pe,X+=r*Ue,re+=r*Fe,se+=r*Oe,ne+=r*Be,u+=38*D,p+=38*j,v+=38*F,T+=38*B,L+=38*R,C+=38*b,fe+=38*x,$+=38*k,Y+=38*w,Q+=38*S,te+=38*A,ee+=38*X,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=C+l+65535,l=Math.floor(r/65536),C=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=C+l+65535,l=Math.floor(r/65536),C=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]=C,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 ue(s,c){V(s,c,c);}function Je(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=253;r>=0;r--)ue(o,o),r!==2&&r!==4&&V(o,o,c);for(r=0;r<16;r++)s[r]=o[r];}function Ye(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=250;r>=0;r--)ue(o,o),r!==1&&V(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(),C=e(),fe=e(),$=e();for(p=0;p<31;p++)r[p]=c[p];for(r[31]=c[31]&127|64,r[0]&=248,Ie(l,o),p=0;p<16;p++)T[p]=l[p],C[p]=v[p]=L[p]=0;for(v[0]=C[0]=1,p=254;p>=0;--p)u=r[p>>>3]>>>(p&7)&1,Se(v,T,u),Se(L,C,u),Te(fe,v,L),je(v,v,L),Te(L,T,C),je(T,T,C),ue(C,fe),ue($,v),V(v,L,v),V(L,T,fe),Te(fe,v,L),je(v,v,L),ue(T,v),je(L,C,$),V(v,L,y),Te(v,v,C),V(L,L,v),V(v,C,$),V(C,T,l),ue(T,fe),Se(v,T,u),Se(L,C,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]=C[p];var Y=l.subarray(32),Q=l.subarray(16);return Je(Y,Y),V(Q,Q,Y),ge(s,Q),0}function it(s,c){return st(s,c,i)}function or(s,c){return t(c,32),it(s,c)}function xt(s,c,o){var r=new Uint8Array(32);return st(r,o,c),Ce(s,n,r,Me)}var cr=pe,sn=N;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,C,fe,$,Y,Q,te,ee,G,W,Z,I,D,j,F,B,R,b,x,k,w,S,A,X=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],Ae=c[3],ye=c[4],ke=c[5],Ke=c[6],Pe=c[7],Ue=0;r>=128;){for(B=0;B<16;B++)R=8*B+Ue,l[B]=o[R+0]<<24|o[R+1]<<16|o[R+2]<<8|o[R+3],u[B]=o[R+4]<<24|o[R+5]<<16|o[R+6]<<8|o[R+7];for(B=0;B<80;B++)if(p=X,v=re,T=se,L=ne,C=h,fe=ae,$=le,Y=de,Q=ie,te=oe,ee=ce,G=Ae,W=ye,Z=ke,I=Ke,D=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,j=S&65535|A<<16,F=k&65535|w<<16,b=j,x=F,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=(X>>>28|ie<<4)^(ie>>>2|X<<30)^(ie>>>7|X<<25),x=(ie>>>28|X<<4)^(X>>>2|ie<<30)^(X>>>7|ie<<25),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,b=X&re^X&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,D=k&65535|w<<16,b=L,x=G,k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=j,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=C,le=fe,de=$,X=Y,oe=Q,ce=te,Ae=ee,ye=G,ke=W,Ke=Z,Pe=I,ie=D,B%16===15)for(R=0;R<16;R++)b=l[R],x=u[R],k=x&65535,w=x>>>16,S=b&65535,A=b>>>16,b=l[(R+9)%16],x=u[(R+9)%16],k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,j=l[(R+1)%16],F=u[(R+1)%16],b=(j>>>1|F<<31)^(j>>>8|F<<24)^j>>>7,x=(F>>>1|j<<31)^(F>>>8|j<<24)^(F>>>7|j<<25),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,j=l[(R+14)%16],F=u[(R+14)%16],b=(j>>>19|F<<13)^(F>>>29|j<<3)^j>>>6,x=(F>>>19|j<<13)^(j>>>29|F<<3)^(F>>>6|j<<26),k+=x&65535,w+=x>>>16,S+=b&65535,A+=b>>>16,w+=k>>>16,S+=w>>>16,A+=S>>>16,l[R]=S&65535|A<<16,u[R]=k&65535|w<<16;b=X,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]=X=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=Ae,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]=Ae=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,Ue+=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(),C=e();je(o,s[1],s[0]),je(C,c[1],c[0]),V(o,o,C),Te(r,s[0],s[1]),Te(C,c[0],c[1]),V(r,r,C),V(l,s[3],c[3]),V(l,l,K),V(u,s[2],c[2]),Te(u,u,u),je(p,r,o),je(v,u,l),Te(T,u,l),Te(L,r,o),V(s[0],p,v),V(s[1],L,T),V(s[2],T,v),V(s[3],p,L);}function dr(s,c,o){var r;for(r=0;r<4;r++)Se(s[r],c[r],o);}function Bt(s,c){var o=e(),r=e(),l=e();Je(l,c[2]),V(o,c[0],l),V(r,c[1],l),ge(s,r),s[31]^=ve(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),V(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),C=[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(C,p),Bt(s,C),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),Ie(s[1],c),ue(l,s[1]),V(u,l,_),je(l,l,s[2]),Te(u,s[2],u),ue(p,u),ue(v,p),V(T,v,p),V(o,T,l),V(o,o,u),Ye(o,o),V(o,o,l),V(o,o,u),V(o,o,u),V(s[0],o,u),ue(r,s[0]),V(r,r,u),_e(r,l)&&V(s[0],s[0],q),ue(r,s[0]),V(r,r,u),_e(r,l)?-1:(ve(s[0])===c[31]>>7&&je(s[0],f,s[0]),V(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,xe(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,ht=32,at=16,yt=32,kt=32,ut=32,pt=32,qt=32,yr=St,fn=ht,ln=at,Qe=64,rt=32,ot=64,Jt=32,Vt=64;a.lowlevel={crypto_core_hsalsa20:Ce,crypto_stream_xor:De,crypto_stream:ze,crypto_stream_salsa20_xor:Ve,crypto_stream_salsa20:He,crypto_onetimeauth:P,crypto_onetimeauth_verify:he,crypto_verify_16:H,crypto_verify_32:xe,crypto_secretbox:pe,crypto_secretbox_open:N,crypto_scalarmult:st,crypto_scalarmult_base:it,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:ht,crypto_secretbox_BOXZEROBYTES:at,crypto_scalarmult_BYTES:yt,crypto_scalarmult_SCALARBYTES:kt,crypto_box_PUBLICKEYBYTES:ut,crypto_box_SECRETKEYBYTES:pt,crypto_box_BEFORENMBYTES:qt,crypto_box_NONCEBYTES:yr,crypto_box_ZEROBYTES:fn,crypto_box_BOXZEROBYTES:ln,crypto_sign_BYTES:Qe,crypto_sign_PUBLICKEYBYTES:rt,crypto_sign_SECRETKEYBYTES:ot,crypto_sign_SEEDBYTES:Jt,crypto_hash_BYTES:Vt,gf:e,D:_,L:vt,pack25519:ge,unpack25519:Ie,M:V,A:Te,S:ue,Z:je,pow2523:Ye,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!==ut)throw new Error("bad public key size");if(c.length!==pt)throw new Error("bad secret key size")}function Xe(){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){Xe(s,c,o),ur(o,c);for(var r=new Uint8Array(ht+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+ht]=s[u];return pe(l,r,r.length,c,o),l.subarray(at)},a.secretbox.open=function(s,c,o){Xe(s,c,o),ur(o,c);for(var r=new Uint8Array(at+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+at]=s[u];return r.length<32||N(l,r,r.length,c,o)!==0?null:l.subarray(ht)},a.secretbox.keyLength=Xt,a.secretbox.nonceLength=St,a.secretbox.overheadLength=at,a.scalarMult=function(s,c){if(Xe(s,c),s.length!==kt)throw new Error("bad n size");if(c.length!==yt)throw new Error("bad p size");var o=new Uint8Array(yt);return st(o,s,c),o},a.scalarMult.base=function(s){if(Xe(s),s.length!==kt)throw new Error("bad n size");var c=new Uint8Array(yt);return it(c,s),c},a.scalarMult.scalarLength=kt,a.scalarMult.groupElementLength=yt,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){Xe(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(ut),c=new Uint8Array(pt);return or(s,c),{publicKey:s,secretKey:c}},a.box.keyPair.fromSecretKey=function(s){if(Xe(s),s.length!==pt)throw new Error("bad secret key size");var c=new Uint8Array(ut);return it(c,s),{publicKey:c,secretKey:new Uint8Array(s)}},a.box.publicKeyLength=ut,a.box.secretKeyLength=pt,a.box.sharedKeyLength=qt,a.box.nonceLength=yr,a.box.overheadLength=a.secretbox.overheadLength,a.sign=function(s,c){if(Xe(s,c),c.length!==ot)throw new Error("bad secret key size");var o=new Uint8Array(Qe+s.length);return hr(o,s,s.length,c),o},a.sign.open=function(s,c){if(Xe(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(Qe),l=0;l<r.length;l++)r[l]=o[l];return r},a.sign.detached.verify=function(s,c,o){if(Xe(s,c,o),c.length!==Qe)throw new Error("bad signature size");if(o.length!==rt)throw new Error("bad public key size");var r=new Uint8Array(Qe+s.length),l=new Uint8Array(Qe+s.length),u;for(u=0;u<Qe;u++)r[u]=c[u];for(u=0;u<s.length;u++)r[u+Qe]=s[u];return zt(l,r,r.length,o)>=0},a.sign.keyPair=function(){var s=new Uint8Array(rt),c=new Uint8Array(ot);return Dt(s,c),{publicKey:s,secretKey:c}},a.sign.keyPair.fromSecretKey=function(s){if(Xe(s),s.length!==ot)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(Xe(s),s.length!==Jt)throw new Error("bad seed size");for(var c=new Uint8Array(rt),o=new Uint8Array(ot),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=ot,a.sign.seedLength=Jt,a.sign.signatureLength=Qe,a.hash=function(s){Xe(s);var c=new Uint8Array(Vt);return tt(c,s,s.length),c},a.hash.hashLength=Vt,a.verify=function(s,c){return Xe(s,c),s.length===0||c.length===0||s.length!==c.length?false:J(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 gt=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])});var Sn=BigInt(0),mt=BigInt(1),kn=BigInt(2),Kn=BigInt(7),Pn=BigInt(256),An=BigInt(113),Cr=[],jr=[],$r=[];for(let a=0,e=mt,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],Cr.push(2*(5*n+t)),jr.push((a+1)*(a+2)/2%64);let i=Sn;for(let f=0;f<7;f++)e=(e<<mt^(e>>Kn)*An)%Pn,e&kn&&(i^=mt<<(mt<<BigInt(f))-mt);$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],q=Rr(K,m,1)^t[y+1];for(let M=0;M<50;M+=10)a[d+M]^=O,a[d+M+1]^=q;}let i=a[2],f=a[3];for(let d=0;d<24;d++){let y=jr[d],_=Er(i,f,y),K=Rr(i,f,y),m=Cr[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,gt(8)),Ct=Ir(6,72,64,gt(10));var Fr=(a,e,t,n={})=>tr((i={})=>new Et(e,a,i.dkLen===void 0?t:i.dkLen,true),n),jt=Fr(31,168,16,gt(11)),ct=Fr(31,136,32,gt(12));var Rn={},Or=Cn(globalThis,Rn);function Cn(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 qe(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 me(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 Ge(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 ct.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}function Nr(a){let e=Ge(a[0]);return e|=Ge(a[1])<<8,e|=Ge(a[2])<<16,e|=Ge(a[3])<<24,Ge(e)}var ft=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]=bt(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]=bt(O[H],K[H]),O[H]=nt(O[H]);let q=On(t),M=Ft(i,_);M=sr(M),M=bt(M,m),M=bt(M,q),M=nt(M);let J=new Uint8Array(this._compressedUSize+this._compressedVSize);return this._compressU(J.subarray(0,this._compressedUSize),O),this._compressV(J.subarray(this._compressedUSize),M),J}_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),q=O[0],M=O[1];for(let J=f;J<256;J++)n[d][y][J]=q[J-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++]=qe(n[0]>>0),e[i++]=qe(n[0]>>8|n[1]<<2),e[i++]=qe(n[1]>>6|n[2]<<4),e[i++]=qe(n[2]>>4|n[3]<<6),e[i++]=qe(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]=qe(((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]=me(e[i+0])>>0|me(e[i+1])<<8,n[1]=me(e[i+1])>>2|me(e[i+2])<<6,n[2]=me(e[i+2])>>4|me(e[i+3])<<4,n[3]=me(e[i+3])>>6|me(e[i+4])<<2,i=i+5;for(let y=0;y<4;y++)t[f][4*d+y]=Ne(Ge(n[y]&1023)*Ge(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(me(e[n]&15)*me(3329)+8>>4),t[2*i+1]=Ne(me(e[n]>>4)*me(3329)+8>>4);return t}};function rr(a,e){let t=Ct.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=ct.create({dkLen:32}).update(a);return e!==void 0&&t.update(e),t.digest()}function In(a,e){return jt.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=me(i[2*f]),t=me(i[2*f+1]),n[3*f+0]=qe(e>>0),n[3*f+1]=qe(e>>8)|qe(t<<4),n[3*f+2]=qe(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((me(a[3*t+0])>>0|me(a[3*t+1])<<8)&4095),e[2*t+1]=Ne((me(a[3*t+1])>>4|me(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=((me(n[8*i+f])<<1)+me(3329/2))/me(3329)&1,e[i]|=qe(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=(me(a[y]>>0)|me(a[y+1])<<8)&4095,d=(me(a[y+1]>>4)|me(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=bt(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 bt(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 ft{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 lt(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 dt(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),q={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&&(q.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(q)});if(!M.ok){let xe=await M.json().catch(()=>({})),Le=xe.error?.message||xe.error||M.statusText;throw new Error(`Registration failed: ${Le}`)}let J=await M.json(),H=new a({did:J.did,apiKey:J.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),q=(0,g.decodeBase64)(m.recvChainKey);if(O.length!==32||q.length!==32)continue;let M={sendChainKey:O,sendStep:m.sendStep||0,recvChainKey:q,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 J=(0,g.decodeBase64)(m.dhSendSecretKey),H=(0,g.decodeBase64)(m.dhSendPublicKey);J.length===32&&H.length===32&&(M.dhSendKeyPair={publicKey:H,secretKey:J});}catch{}if(m.dhRecvPubKey)try{let J=(0,g.decodeBase64)(m.dhRecvPubKey);J.length===32&&(M.dhRecvPubKey=J);}catch{}if(m.prevSendStep!==void 0&&(M.prevSendStep=m.prevSendStep),M.dhSkippedKeys=new Map,m.skippedKeys&&typeof m.skippedKeys=="object")for(let[J,H]of Object.entries(m.skippedKeys))try{let xe=(0,g.decodeBase64)(H);xe.length===32&&M.skippedKeys.set(Number(J),xe);}catch{}if(m.dhSkippedKeys&&typeof m.dhSkippedKeys=="object")for(let[J,H]of Object.entries(m.dhSkippedKeys))try{let xe=(0,g.decodeBase64)(H);xe.length===32&&M.dhSkippedKeys.set(J,xe);}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}`,q=this._ratchetStates.get(O),M=null,J=null;if(q)q.rootKey&&q.dhSendKeyPair&&(J=q.dhSendKeyPair.publicKey);else {let pe=U.default.box.before(_,this.encryptionKeyPair.secretKey),N;if(this.postQuantum&&y.mlkem_public_key)try{let z=(0,g.decodeBase64)(y.mlkem_public_key),we=new et,[Se,ge]=await we.encap(z);M=Se;let _e=new Uint8Array(pe.length+ge.length);_e.set(pe,0),_e.set(ge,pe.length),N=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",_e));}catch{N=pe;}else N=pe;if(this.doubleRatchet){let z=U.default.box.keyPair(),we=U.default.box.before(_,z.secretKey),{newRootKey:Se,newChainKey:ge}=await dt(N,we);J=z.publicKey,q={sendChainKey:ge,sendStep:0,recvChainKey:N,recvStep:0,skippedKeys:new Map,rootKey:Se,dhSendKeyPair:z,dhRecvPubKey:void 0,prevSendStep:0,dhSkippedKeys:new Map};}else q={sendChainKey:N,sendStep:0,recvChainKey:N,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(O,q);}let{nextChainKey:H,messageKey:xe}=await lt(q.sendChainKey);q.sendChainKey=H,q.sendStep++;let Le=q.sendStep,Re=Xn;f&&(Re|=Wr),d&&(Re|=en),M&&(Re|=qn),J&&(Re|=Jn),this.deniable&&(Re|=Vn);let $e=Yn(Re,Le),Ce=new Uint8Array($e.length+m.length);Ce.set($e,0),Ce.set(m,$e.length);let Me=U.default.randomBytes(U.default.secretbox.nonceLength),Ve=U.default.secretbox(Ce,Me,xe);if(!Ve)throw new Error("Encryption failed");if(this.jitterMs>0){let pe=Math.random()*this.jitterMs;await new Promise(N=>setTimeout(N,pe));}let He={from:this.did,to:e,timestamp:new Date().toISOString(),nonce:(0, g.encodeBase64)(Me),ciphertext_hash:await ir((0, g.encodeBase64)(Ve)),ratchet_step:Le};M&&(He.pq_ciphertext=(0, g.encodeBase64)(M)),J&&(He.dh_ratchet_key=(0, g.encodeBase64)(J),He.pn=q.prevSendStep||0);let ze=JSON.stringify(He),De;if(this.deniable){let pe=U.default.box.before(_,this.encryptionKeyPair.secretKey);De=await tn(pe,(0, g.decodeUTF8)(ze));}else De=U.default.sign.detached((0, g.decodeUTF8)(ze),this.signingKeyPair.secretKey);let E={to:e,ciphertext:(0, g.encodeBase64)(Ve),nonce:(0, g.encodeBase64)(Me),signature:(0, g.encodeBase64)(De),envelope:ze,ttl:n.ttl};d||(E.content_type=n.contentType||"text/plain",E.message_type=n.messageType||"text",E.thread_id=n.threadId,E.reply_to=n.replyTo);try{await this._persistRatchetState();}catch{}let P=[this.baseUrl,...this.fallbackRelays],he=null;for(let pe of P)try{let N=await this._fetchWithRetry(`${pe}/v1/agent/send/encrypted`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(E)},{maxRetries:i,baseDelay:500,maxDelay:1e4});return {id:N.id,from:N.from,to:N.to,timestamp:N.timestamp,expiresAt:N.expires_at||N.expiresAt,encrypted:N.encrypted,clientSide:N.client_side||N.clientSide}}catch(N){if(he=N instanceof Error?N:new Error(String(N)),he.message.includes("(4"))break}throw he&&!he.message.includes("(4")&&this._offlineQueue.push({recipientDid:e,message:t,options:n,timestamp:Date.now()}),he||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)){n.push(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 E=JSON.parse(f.envelope),P=await this.getIdentity(E.from);if(!P){n.push(f.id);continue}d=(0,g.decodeBase64)(P.encryption_public_key),P.signing_public_key&&(y=(0,g.decodeBase64)(P.signing_public_key));}else {n.push(f.id);continue}let _=(0,g.decodeBase64)(f.ciphertext),K=(0,g.decodeBase64)(f.nonce),m=null,O=0,q=null,M=null,J=0;if(f.envelope)try{let E=JSON.parse(f.envelope);typeof E.ratchet_step=="number"&&Number.isInteger(E.ratchet_step)&&E.ratchet_step>=0&&E.ratchet_step<=4294967295&&(O=E.ratchet_step),typeof E.pq_ciphertext=="string"&&E.pq_ciphertext.length<=65536&&(q=E.pq_ciphertext),typeof E.dh_ratchet_key=="string"&&E.dh_ratchet_key.length<=256&&(M=E.dh_ratchet_key),typeof E.pn=="number"&&Number.isInteger(E.pn)&&E.pn>=0&&E.pn<=4294967295&&(J=E.pn);}catch{}if(O>0){let E=`${f.from}:${this.did}`,P=this._ratchetStates.get(E);if(P){if(M&&P.rootKey){let N=(0,g.decodeBase64)(M),z=P.dhRecvPubKey;if(!z||(0,g.encodeBase64)(N)!==(0,g.encodeBase64)(z)){if(J>P.recvStep){let Ie=P.recvChainKey;for(let Te=P.recvStep+1;Te<=J&&Te-P.recvStep<=Ot;Te++){let{nextChainKey:je,messageKey:V}=await lt(Ie),ue=`${z?(0,g.encodeBase64)(z):"init"}:${Te}`;for(P.dhSkippedKeys||(P.dhSkippedKeys=new Map),P.dhSkippedKeys.set(ue,V),Ie=je;P.dhSkippedKeys.size>Ot;){let Je=P.dhSkippedKeys.keys().next().value;if(Je!==void 0)P.dhSkippedKeys.delete(Je);else break}}}P.dhRecvPubKey=N;let we=P.dhSendKeyPair||this.encryptionKeyPair,Se=U.default.box.before(N,we.secretKey),ge=await dt(P.rootKey,Se);P.rootKey=ge.newRootKey,P.recvChainKey=ge.newChainKey,P.recvStep=0,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0;let _e=U.default.box.before(N,P.dhSendKeyPair.secretKey),ve=await dt(P.rootKey,_e);P.rootKey=ve.newRootKey,P.sendChainKey=ve.newChainKey;}}}else {let N=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(q&&this.mlkemSecretKey)try{let Se=(0,g.decodeBase64)(q),_e=await new et().decap(Se,this.mlkemSecretKey),ve=new Uint8Array(N.length+_e.length);ve.set(N,0),ve.set(_e,N.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",ve));}catch{z=N;}else z=N;if(M&&this.doubleRatchet){let Se=(0,g.decodeBase64)(M),ge=U.default.box.before(Se,this.encryptionKeyPair.secretKey),{newRootKey:_e,newChainKey:ve}=await dt(z,ge);P={sendChainKey:z,sendStep:0,recvChainKey:ve,recvStep:0,skippedKeys:new Map,rootKey:_e,dhSendKeyPair:void 0,dhRecvPubKey:Se,prevSendStep:0,dhSkippedKeys:new Map};}else P={sendChainKey:z,sendStep:0,recvChainKey:z,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(E,P);let we=`${this.did}:${f.from}`;this._ratchetStates.delete(we);}let he=O,pe=M?`${M}:${he}`:`init:${he}`;if(P.dhSkippedKeys?.has(pe)){let N=P.dhSkippedKeys.get(pe);m=U.default.secretbox.open(_,K,N),P.dhSkippedKeys.delete(pe);}else if(P.skippedKeys.has(he)){let N=P.skippedKeys.get(he);m=U.default.secretbox.open(_,K,N),P.skippedKeys.delete(he);}else if(he>P.recvStep)if(he-P.recvStep>Ot){this._decryptFailCount++,n.push(f.id);let z=f.from||"unknown",we=this._peerDecryptFails.get(z)||0;this._peerDecryptFails.set(z,we+1),this._autoResetThreshold>0&&we+1>=this._autoResetThreshold&&(this.resetRatchet(z),i.add(z),this._onRatchetReset?.(z,we+1));continue}else {let z=P.recvChainKey;for(let ge=P.recvStep+1;ge<he;ge++){let{nextChainKey:_e,messageKey:ve}=await lt(z);for(P.skippedKeys.set(ge,ve),z=_e;P.skippedKeys.size>Ot;){let Ie=P.skippedKeys.keys().next().value;if(Ie!==void 0)P.skippedKeys.delete(Ie);else break}}let{nextChainKey:we,messageKey:Se}=await lt(z);P.recvChainKey=we,P.recvStep=he,m=U.default.secretbox.open(_,K,Se);}if(!m&&M&&this.doubleRatchet&&P)try{let N=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(q&&this.mlkemSecretKey)try{let V=(0,g.decodeBase64)(q),Je=await new et().decap(V,this.mlkemSecretKey),Ye=new Uint8Array(N.length+Je.length);Ye.set(N,0),Ye.set(Je,N.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ye));}catch{z=N;}else z=N;let we=(0,g.decodeBase64)(M),Se=U.default.box.before(we,this.encryptionKeyPair.secretKey),{newRootKey:ge,newChainKey:_e}=await dt(z,Se),ve=_e;for(let V=1;V<O;V++){let{nextChainKey:ue}=await lt(ve);ve=ue;}let{nextChainKey:Ie,messageKey:Te}=await lt(ve),je=U.default.secretbox.open(_,K,Te);if(je){m=je,P.recvChainKey=Ie,P.recvStep=O,P.rootKey=ge,P.dhRecvPubKey=we,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0;let V=U.default.box.before(we,P.dhSendKeyPair.secretKey),ue=await dt(P.rootKey,V);P.rootKey=ue.newRootKey,P.sendChainKey=ue.newChainKey,P.dhSkippedKeys&&P.dhSkippedKeys.clear(),P.skippedKeys&&P.skippedKeys.clear();let Je=`${this.did}:${f.from}`;this._ratchetStates.delete(Je);}}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 E=f.from||"unknown",P=this._peerDecryptFails.get(E)||0;this._peerDecryptFails.set(E,P+1),this._autoResetThreshold>0&&P+1>=this._autoResetThreshold&&(this.resetRatchet(E),i.add(E),this._onRatchetReset?.(E,P+1));continue}{let E=f.from||"unknown";this._peerDecryptFails.has(E)&&this._peerDecryptFails.delete(E);}let H=m,xe=!1,Le=!1,Re=Qn(m);if(Re&&(xe=!!(Re.flags&Wr),Le=!!(Re.flags&en),H=Re.content),xe)H=Zr(H);else if(!Re&&m.length>=256&&(m.length&m.length-1)===0){let E=Zr(m);E.length<m.length&&(H=E);}let $e=(0,g.encodeUTF8)(H),Ce=f.from,Me,Ve,He,ze;if(Le||!Re){let E=zn($e);E&&($e=E.msg,Ce=E.from,Me=E.contentType,Ve=E.messageType,He=E.threadId,ze=E.replyTo);}let De=!1;try{let E=(0,g.decodeBase64)(f.signature),P=f.envelope||JSON.stringify({from:Ce,to:f.to,timestamp:f.timestamp,nonce:f.nonce,ciphertext_hash:await ir(f.ciphertext)});if(E.length===32){let he=U.default.box.before(d,this.encryptionKeyPair.secretKey),pe=await tn(he,(0,g.decodeUTF8)(P));if(pe.length===E.length){let N=0;for(let z=0;z<pe.length;z++)N|=pe[z]^E[z];De=N===0;}}else y&&(De=U.default.sign.detached.verify((0,g.decodeUTF8)(P),E,y));}catch{De=!1;}if(this.requireSignatures&&!De){this._decryptFailCount++,n.push(f.id);let E=f.from||"unknown",P=this._peerDecryptFails.get(E)||0;this._peerDecryptFails.set(E,P+1);continue}if(this._seenMessageIds.add(f.id),this._seenMessageIds.size>1e4){let E=this._seenMessageIds.values();for(let P=0;P<1e3;P++){let he=E.next().value;he!==void 0&&this._seenMessageIds.delete(he);}}t.push({id:f.id,from:Ce,to:f.to,content:$e,contentType:Me||f.content_type||"text/plain",messageType:Ve||f.message_type||"text",threadId:He||f.thread_id||null,replyTo:ze||f.reply_to||null,signatureValid:De,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(J=>J.toString(16).padStart(2,"0")).join("")}`;if(t.length!==m.length)return false;let O=i.encode(t),q=i.encode(m),M=0;for(let J=0;J<O.length;J++)M|=O[J]^q[J];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),q=U.default.box(m,O,K,this.encryptionKeyPair.secretKey),M=U.default.sign.detached(m,this.signingKeyPair.secretKey);n.encrypted_output=(0, g.encodeBase64)(q),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:q}=await import('crypto');K=new Uint8Array(q("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 q=await this.getIdentity(y.from);if(q){let M=new Uint8Array([..._,...K]);O=U.default.sign.detached.verify(M,(0,g.decodeBase64)(y.sig),(0,g.decodeBase64)(q.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,q=0,M,J=null,H=null,xe=null,Le={stop:()=>{m=false,J&&clearTimeout(J),H&&clearInterval(H),xe&&(xe.abort(),xe=null),this._listeners.delete(Le);},get active(){return m}};this._listeners.add(Le),_&&(H=setInterval(async()=>{if(m)try{await this.ping();}catch{}},K),this.ping().catch(()=>{}));let Re=async E=>{for(let P of E)try{await e(P),d&&await this.markRead(P.id).catch(()=>{});}catch(he){n&&n(he instanceof Error?he:new Error(String(he)));}E.length>0&&(M=E[E.length-1].timestamp);},$e="",Ce=0,Me=async()=>{try{let E=new URLSearchParams;M&&E.set("since",M),t.from&&E.set("from",t.from);let P=`${this.baseUrl}/v1/agent/receive/sse?${E}`,he={"X-Agent-Key":this.apiKey};$e&&(he["Last-Event-ID"]=$e);let pe=new AbortController;xe=pe;let N=setTimeout(()=>pe.abort(),6e4),z;try{z=await fetch(P,{headers:he,signal:pe.signal});}catch(_e){throw clearTimeout(N),_e}if(!z.ok||!z.body)return clearTimeout(N),!1;let we=z.body.getReader(),Se=new TextDecoder,ge="";try{let _e="",ve="",Ie="";for(;m&&!t.signal?.aborted;){let{done:Te,value:je}=await we.read();if(Te)break;ge+=Se.decode(je,{stream:!0});let V=ge.split(`
|
|
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]),F=e([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),q=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 J(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 J(s,c,o,r,16)}function xe(s,c,o,r){return J(s,c,o,r,32)}function Le(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,C=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,j=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,D=u,$=p,O=v,B=T,R=L,b=C,x=fe,S=j,w=Y,k=Q,A=te,X=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+X|0,B^=h<<7|h>>>25,h=B+I|0,S^=h<<9|h>>>23,h=S+B|0,X^=h<<13|h>>>19,h=X+S|0,I^=h<<18|h>>>14,h=R+D|0,w^=h<<7|h>>>25,h=w+R|0,re^=h<<9|h>>>23,h=re+w|0,D^=h<<13|h>>>19,h=D+re|0,R^=h<<18|h>>>14,h=k+b|0,se^=h<<7|h>>>25,h=se+k|0,$^=h<<9|h>>>23,h=$+se|0,b^=h<<13|h>>>19,h=b+$|0,k^=h<<18|h>>>14,h=ne+A|0,O^=h<<7|h>>>25,h=O+ne|0,x^=h<<9|h>>>23,h=x+O|0,A^=h<<13|h>>>19,h=A+x|0,ne^=h<<18|h>>>14,h=I+O|0,D^=h<<7|h>>>25,h=D+I|0,$^=h<<9|h>>>23,h=$+D|0,O^=h<<13|h>>>19,h=O+$|0,I^=h<<18|h>>>14,h=R+B|0,b^=h<<7|h>>>25,h=b+R|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,R^=h<<18|h>>>14,h=k+w|0,A^=h<<7|h>>>25,h=A+k|0,S^=h<<9|h>>>23,h=S+A|0,w^=h<<13|h>>>19,h=w+S|0,k^=h<<18|h>>>14,h=ne+se|0,X^=h<<7|h>>>25,h=X+ne|0,re^=h<<9|h>>>23,h=re+X|0,se^=h<<13|h>>>19,h=se+re|0,ne^=h<<18|h>>>14;I=I+l|0,D=D+u|0,$=$+p|0,O=O+v|0,B=B+T|0,R=R+L|0,b=b+C|0,x=x+fe|0,S=S+j|0,w=w+Y|0,k=k+Q|0,A=A+te|0,X=X+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]=D>>>0&255,s[5]=D>>>8&255,s[6]=D>>>16&255,s[7]=D>>>24&255,s[8]=$>>>0&255,s[9]=$>>>8&255,s[10]=$>>>16&255,s[11]=$>>>24&255,s[12]=O>>>0&255,s[13]=O>>>8&255,s[14]=O>>>16&255,s[15]=O>>>24&255,s[16]=B>>>0&255,s[17]=B>>>8&255,s[18]=B>>>16&255,s[19]=B>>>24&255,s[20]=R>>>0&255,s[21]=R>>>8&255,s[22]=R>>>16&255,s[23]=R>>>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]=S>>>0&255,s[33]=S>>>8&255,s[34]=S>>>16&255,s[35]=S>>>24&255,s[36]=w>>>0&255,s[37]=w>>>8&255,s[38]=w>>>16&255,s[39]=w>>>24&255,s[40]=k>>>0&255,s[41]=k>>>8&255,s[42]=k>>>16&255,s[43]=k>>>24&255,s[44]=A>>>0&255,s[45]=A>>>8&255,s[46]=A>>>16&255,s[47]=A>>>24&255,s[48]=X>>>0&255,s[49]=X>>>8&255,s[50]=X>>>16&255,s[51]=X>>>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 Re(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,C=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,j=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,D=u,$=p,O=v,B=T,R=L,b=C,x=fe,S=j,w=Y,k=Q,A=te,X=ee,re=G,se=W,ne=Z,h,ae=0;ae<20;ae+=2)h=I+X|0,B^=h<<7|h>>>25,h=B+I|0,S^=h<<9|h>>>23,h=S+B|0,X^=h<<13|h>>>19,h=X+S|0,I^=h<<18|h>>>14,h=R+D|0,w^=h<<7|h>>>25,h=w+R|0,re^=h<<9|h>>>23,h=re+w|0,D^=h<<13|h>>>19,h=D+re|0,R^=h<<18|h>>>14,h=k+b|0,se^=h<<7|h>>>25,h=se+k|0,$^=h<<9|h>>>23,h=$+se|0,b^=h<<13|h>>>19,h=b+$|0,k^=h<<18|h>>>14,h=ne+A|0,O^=h<<7|h>>>25,h=O+ne|0,x^=h<<9|h>>>23,h=x+O|0,A^=h<<13|h>>>19,h=A+x|0,ne^=h<<18|h>>>14,h=I+O|0,D^=h<<7|h>>>25,h=D+I|0,$^=h<<9|h>>>23,h=$+D|0,O^=h<<13|h>>>19,h=O+$|0,I^=h<<18|h>>>14,h=R+B|0,b^=h<<7|h>>>25,h=b+R|0,x^=h<<9|h>>>23,h=x+b|0,B^=h<<13|h>>>19,h=B+x|0,R^=h<<18|h>>>14,h=k+w|0,A^=h<<7|h>>>25,h=A+k|0,S^=h<<9|h>>>23,h=S+A|0,w^=h<<13|h>>>19,h=w+S|0,k^=h<<18|h>>>14,h=ne+se|0,X^=h<<7|h>>>25,h=X+ne|0,re^=h<<9|h>>>23,h=re+X|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]=R>>>0&255,s[5]=R>>>8&255,s[6]=R>>>16&255,s[7]=R>>>24&255,s[8]=k>>>0&255,s[9]=k>>>8&255,s[10]=k>>>16&255,s[11]=k>>>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]=S>>>0&255,s[25]=S>>>8&255,s[26]=S>>>16&255,s[27]=S>>>24&255,s[28]=w>>>0&255,s[29]=w>>>8&255,s[30]=w>>>16&255,s[31]=w>>>24&255;}function je(s,c,o,r){Le(s,c,o,r);}function Ce(s,c,o,r){Re(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 Ve(s,c,o,r,l,u,p){var v=new Uint8Array(16),T=new Uint8Array(64),L,C;for(C=0;C<16;C++)v[C]=0;for(C=0;C<8;C++)v[C]=u[C];for(;l>=64;){for(je(T,v,p,Me),C=0;C<64;C++)s[c+C]=o[r+C]^T[C];for(L=1,C=8;C<16;C++)L=L+(v[C]&255)|0,v[C]=L&255,L>>>=8;l-=64,c+=64,r+=64;}if(l>0)for(je(T,v,p,Me),C=0;C<l;C++)s[c+C]=o[r+C]^T[C];return 0}function He(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(je(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(je(p,u,l,Me),T=0;T<o;T++)s[c+T]=p[T];return 0}function ze(s,c,o,r,l){var u=new Uint8Array(32);Ce(u,r,l,Me);for(var p=new Uint8Array(8),v=0;v<8;v++)p[v]=r[v+16];return He(s,c,o,p,u)}function De(s,c,o,r,l,u,p){var v=new Uint8Array(32);Ce(v,u,p,Me);for(var T=new Uint8Array(8),L=0;L<8;L++)T[L]=u[L+16];return Ve(s,c,o,r,l,T,v)}var E=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;};E.prototype.blocks=function(s,c,o){for(var r=this.fin?0:2048,l,u,p,v,T,L,C,fe,j,Y,Q,te,ee,G,W,Z,I,D,$,O=this.h[0],B=this.h[1],R=this.h[2],b=this.h[3],x=this.h[4],S=this.h[5],w=this.h[6],k=this.h[7],A=this.h[8],X=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,O+=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,R+=(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,S+=T>>>1&8191,L=s[c+10]&255|(s[c+11]&255)<<8,w+=(T>>>14|L<<2)&8191,C=s[c+12]&255|(s[c+13]&255)<<8,k+=(L>>>11|C<<5)&8191,fe=s[c+14]&255|(s[c+15]&255)<<8,A+=(C>>>8|fe<<8)&8191,X+=fe>>>5|r,j=0,Y=j,Y+=O*re,Y+=B*(5*ce),Y+=R*(5*oe),Y+=b*(5*ie),Y+=x*(5*de),j=Y>>>13,Y&=8191,Y+=S*(5*le),Y+=w*(5*ae),Y+=k*(5*h),Y+=A*(5*ne),Y+=X*(5*se),j+=Y>>>13,Y&=8191,Q=j,Q+=O*se,Q+=B*re,Q+=R*(5*ce),Q+=b*(5*oe),Q+=x*(5*ie),j=Q>>>13,Q&=8191,Q+=S*(5*de),Q+=w*(5*le),Q+=k*(5*ae),Q+=A*(5*h),Q+=X*(5*ne),j+=Q>>>13,Q&=8191,te=j,te+=O*ne,te+=B*se,te+=R*re,te+=b*(5*ce),te+=x*(5*oe),j=te>>>13,te&=8191,te+=S*(5*ie),te+=w*(5*de),te+=k*(5*le),te+=A*(5*ae),te+=X*(5*h),j+=te>>>13,te&=8191,ee=j,ee+=O*h,ee+=B*ne,ee+=R*se,ee+=b*re,ee+=x*(5*ce),j=ee>>>13,ee&=8191,ee+=S*(5*oe),ee+=w*(5*ie),ee+=k*(5*de),ee+=A*(5*le),ee+=X*(5*ae),j+=ee>>>13,ee&=8191,G=j,G+=O*ae,G+=B*h,G+=R*ne,G+=b*se,G+=x*re,j=G>>>13,G&=8191,G+=S*(5*ce),G+=w*(5*oe),G+=k*(5*ie),G+=A*(5*de),G+=X*(5*le),j+=G>>>13,G&=8191,W=j,W+=O*le,W+=B*ae,W+=R*h,W+=b*ne,W+=x*se,j=W>>>13,W&=8191,W+=S*re,W+=w*(5*ce),W+=k*(5*oe),W+=A*(5*ie),W+=X*(5*de),j+=W>>>13,W&=8191,Z=j,Z+=O*de,Z+=B*le,Z+=R*ae,Z+=b*h,Z+=x*ne,j=Z>>>13,Z&=8191,Z+=S*se,Z+=w*re,Z+=k*(5*ce),Z+=A*(5*oe),Z+=X*(5*ie),j+=Z>>>13,Z&=8191,I=j,I+=O*ie,I+=B*de,I+=R*le,I+=b*ae,I+=x*h,j=I>>>13,I&=8191,I+=S*ne,I+=w*se,I+=k*re,I+=A*(5*ce),I+=X*(5*oe),j+=I>>>13,I&=8191,D=j,D+=O*oe,D+=B*ie,D+=R*de,D+=b*le,D+=x*ae,j=D>>>13,D&=8191,D+=S*h,D+=w*ne,D+=k*se,D+=A*re,D+=X*(5*ce),j+=D>>>13,D&=8191,$=j,$+=O*ce,$+=B*oe,$+=R*ie,$+=b*de,$+=x*le,j=$>>>13,$&=8191,$+=S*ae,$+=w*h,$+=k*ne,$+=A*se,$+=X*re,j+=$>>>13,$&=8191,j=(j<<2)+j|0,j=j+Y|0,Y=j&8191,j=j>>>13,Q+=j,O=Y,B=Q,R=te,b=ee,x=G,S=W,w=Z,k=I,A=D,X=$,c+=16,o-=16;this.h[0]=O,this.h[1]=B,this.h[2]=R,this.h[3]=b,this.h[4]=x,this.h[5]=S,this.h[6]=w,this.h[7]=k,this.h[8]=A,this.h[9]=X;},E.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;},E.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 E(u);return p.update(o,r,l),p.finish(s,c),0}function he(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(De(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 N(s,c,o,r,l){var u,p=new Uint8Array(32);if(o<32||(ze(p,0,32,r,l),he(c,16,c,32,o-32,p)!==0))return -1;for(De(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 we(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 ke(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 ge(s,c){var o,r,l,u=e(),p=e();for(o=0;o<16;o++)p[o]=c[o];for(we(p),we(p),we(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,ke(p,u,1-l);}for(o=0;o<16;o++)s[2*o]=p[o]&255,s[2*o+1]=p[o]>>8;}function _e(s,c){var o=new Uint8Array(32),r=new Uint8Array(32);return ge(o,s),ge(r,c),xe(o,0,r,0)}function ve(s){var c=new Uint8Array(32);return ge(c,s),c[0]&1}function Ie(s,c){var o;for(o=0;o<16;o++)s[o]=c[2*o]+(c[2*o+1]<<8);s[15]&=32767;}function Te(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]+o[r];}function $e(s,c,o){for(var r=0;r<16;r++)s[r]=c[r]-o[r];}function V(s,c,o){var r,l,u=0,p=0,v=0,T=0,L=0,C=0,fe=0,j=0,Y=0,Q=0,te=0,ee=0,G=0,W=0,Z=0,I=0,D=0,$=0,O=0,B=0,R=0,b=0,x=0,S=0,w=0,k=0,A=0,X=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],Ae=o[7],ye=o[8],Se=o[9],Ke=o[10],Pe=o[11],Ue=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,C+=r*oe,fe+=r*ce,j+=r*Ae,Y+=r*ye,Q+=r*Se,te+=r*Ke,ee+=r*Pe,G+=r*Ue,W+=r*Fe,Z+=r*Oe,I+=r*Be,r=c[1],p+=r*h,v+=r*ae,T+=r*le,L+=r*de,C+=r*ie,fe+=r*oe,j+=r*ce,Y+=r*Ae,Q+=r*ye,te+=r*Se,ee+=r*Ke,G+=r*Pe,W+=r*Ue,Z+=r*Fe,I+=r*Oe,D+=r*Be,r=c[2],v+=r*h,T+=r*ae,L+=r*le,C+=r*de,fe+=r*ie,j+=r*oe,Y+=r*ce,Q+=r*Ae,te+=r*ye,ee+=r*Se,G+=r*Ke,W+=r*Pe,Z+=r*Ue,I+=r*Fe,D+=r*Oe,$+=r*Be,r=c[3],T+=r*h,L+=r*ae,C+=r*le,fe+=r*de,j+=r*ie,Y+=r*oe,Q+=r*ce,te+=r*Ae,ee+=r*ye,G+=r*Se,W+=r*Ke,Z+=r*Pe,I+=r*Ue,D+=r*Fe,$+=r*Oe,O+=r*Be,r=c[4],L+=r*h,C+=r*ae,fe+=r*le,j+=r*de,Y+=r*ie,Q+=r*oe,te+=r*ce,ee+=r*Ae,G+=r*ye,W+=r*Se,Z+=r*Ke,I+=r*Pe,D+=r*Ue,$+=r*Fe,O+=r*Oe,B+=r*Be,r=c[5],C+=r*h,fe+=r*ae,j+=r*le,Y+=r*de,Q+=r*ie,te+=r*oe,ee+=r*ce,G+=r*Ae,W+=r*ye,Z+=r*Se,I+=r*Ke,D+=r*Pe,$+=r*Ue,O+=r*Fe,B+=r*Oe,R+=r*Be,r=c[6],fe+=r*h,j+=r*ae,Y+=r*le,Q+=r*de,te+=r*ie,ee+=r*oe,G+=r*ce,W+=r*Ae,Z+=r*ye,I+=r*Se,D+=r*Ke,$+=r*Pe,O+=r*Ue,B+=r*Fe,R+=r*Oe,b+=r*Be,r=c[7],j+=r*h,Y+=r*ae,Q+=r*le,te+=r*de,ee+=r*ie,G+=r*oe,W+=r*ce,Z+=r*Ae,I+=r*ye,D+=r*Se,$+=r*Ke,O+=r*Pe,B+=r*Ue,R+=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*Ae,D+=r*ye,$+=r*Se,O+=r*Ke,B+=r*Pe,R+=r*Ue,b+=r*Fe,x+=r*Oe,S+=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,D+=r*Ae,$+=r*ye,O+=r*Se,B+=r*Ke,R+=r*Pe,b+=r*Ue,x+=r*Fe,S+=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,D+=r*ce,$+=r*Ae,O+=r*ye,B+=r*Se,R+=r*Ke,b+=r*Pe,x+=r*Ue,S+=r*Fe,w+=r*Oe,k+=r*Be,r=c[11],ee+=r*h,G+=r*ae,W+=r*le,Z+=r*de,I+=r*ie,D+=r*oe,$+=r*ce,O+=r*Ae,B+=r*ye,R+=r*Se,b+=r*Ke,x+=r*Pe,S+=r*Ue,w+=r*Fe,k+=r*Oe,A+=r*Be,r=c[12],G+=r*h,W+=r*ae,Z+=r*le,I+=r*de,D+=r*ie,$+=r*oe,O+=r*ce,B+=r*Ae,R+=r*ye,b+=r*Se,x+=r*Ke,S+=r*Pe,w+=r*Ue,k+=r*Fe,A+=r*Oe,X+=r*Be,r=c[13],W+=r*h,Z+=r*ae,I+=r*le,D+=r*de,$+=r*ie,O+=r*oe,B+=r*ce,R+=r*Ae,b+=r*ye,x+=r*Se,S+=r*Ke,w+=r*Pe,k+=r*Ue,A+=r*Fe,X+=r*Oe,re+=r*Be,r=c[14],Z+=r*h,I+=r*ae,D+=r*le,$+=r*de,O+=r*ie,B+=r*oe,R+=r*ce,b+=r*Ae,x+=r*ye,S+=r*Se,w+=r*Ke,k+=r*Pe,A+=r*Ue,X+=r*Fe,re+=r*Oe,se+=r*Be,r=c[15],I+=r*h,D+=r*ae,$+=r*le,O+=r*de,B+=r*ie,R+=r*oe,b+=r*ce,x+=r*Ae,S+=r*ye,w+=r*Se,k+=r*Ke,A+=r*Pe,X+=r*Ue,re+=r*Fe,se+=r*Oe,ne+=r*Be,u+=38*D,p+=38*$,v+=38*O,T+=38*B,L+=38*R,C+=38*b,fe+=38*x,j+=38*S,Y+=38*w,Q+=38*k,te+=38*A,ee+=38*X,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=C+l+65535,l=Math.floor(r/65536),C=r-l*65536,r=fe+l+65535,l=Math.floor(r/65536),fe=r-l*65536,r=j+l+65535,l=Math.floor(r/65536),j=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=C+l+65535,l=Math.floor(r/65536),C=r-l*65536,r=fe+l+65535,l=Math.floor(r/65536),fe=r-l*65536,r=j+l+65535,l=Math.floor(r/65536),j=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]=C,s[6]=fe,s[7]=j,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 ue(s,c){V(s,c,c);}function Je(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=253;r>=0;r--)ue(o,o),r!==2&&r!==4&&V(o,o,c);for(r=0;r<16;r++)s[r]=o[r];}function Ye(s,c){var o=e(),r;for(r=0;r<16;r++)o[r]=c[r];for(r=250;r>=0;r--)ue(o,o),r!==1&&V(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(),C=e(),fe=e(),j=e();for(p=0;p<31;p++)r[p]=c[p];for(r[31]=c[31]&127|64,r[0]&=248,Ie(l,o),p=0;p<16;p++)T[p]=l[p],C[p]=v[p]=L[p]=0;for(v[0]=C[0]=1,p=254;p>=0;--p)u=r[p>>>3]>>>(p&7)&1,ke(v,T,u),ke(L,C,u),Te(fe,v,L),$e(v,v,L),Te(L,T,C),$e(T,T,C),ue(C,fe),ue(j,v),V(v,L,v),V(L,T,fe),Te(fe,v,L),$e(v,v,L),ue(T,v),$e(L,C,j),V(v,L,y),Te(v,v,C),V(L,L,v),V(v,C,j),V(C,T,l),ue(T,fe),ke(v,T,u),ke(L,C,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]=C[p];var Y=l.subarray(32),Q=l.subarray(16);return Je(Y,Y),V(Q,Q,Y),ge(s,Q),0}function it(s,c){return st(s,c,i)}function or(s,c){return t(c,32),it(s,c)}function xt(s,c,o){var r=new Uint8Array(32);return st(r,o,c),Ce(s,n,r,Me)}var cr=pe,sn=N;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,C,fe,j,Y,Q,te,ee,G,W,Z,I,D,$,O,B,R,b,x,S,w,k,A,X=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],Ae=c[3],ye=c[4],Se=c[5],Ke=c[6],Pe=c[7],Ue=0;r>=128;){for(B=0;B<16;B++)R=8*B+Ue,l[B]=o[R+0]<<24|o[R+1]<<16|o[R+2]<<8|o[R+3],u[B]=o[R+4]<<24|o[R+5]<<16|o[R+6]<<8|o[R+7];for(B=0;B<80;B++)if(p=X,v=re,T=se,L=ne,C=h,fe=ae,j=le,Y=de,Q=ie,te=oe,ee=ce,G=Ae,W=ye,Z=Se,I=Ke,D=Pe,b=de,x=Pe,S=x&65535,w=x>>>16,k=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),S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,b=h&ae^~h&le,x=ye&Se^~ye&Ke,S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,b=fr[B*2],x=fr[B*2+1],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,b=l[B%16],x=u[B%16],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,$=k&65535|A<<16,O=S&65535|w<<16,b=$,x=O,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=(X>>>28|ie<<4)^(ie>>>2|X<<30)^(ie>>>7|X<<25),x=(ie>>>28|X<<4)^(X>>>2|ie<<30)^(X>>>7|ie<<25),S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,b=X&re^X&se^re&se,x=ie&oe^ie&ce^oe&ce,S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,Y=k&65535|A<<16,D=S&65535|w<<16,b=L,x=G,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=$,x=O,S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,L=k&65535|A<<16,G=S&65535|w<<16,re=p,se=v,ne=T,h=L,ae=C,le=fe,de=j,X=Y,oe=Q,ce=te,Ae=ee,ye=G,Se=W,Ke=Z,Pe=I,ie=D,B%16===15)for(R=0;R<16;R++)b=l[R],x=u[R],S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=l[(R+9)%16],x=u[(R+9)%16],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,$=l[(R+1)%16],O=u[(R+1)%16],b=($>>>1|O<<31)^($>>>8|O<<24)^$>>>7,x=(O>>>1|$<<31)^(O>>>8|$<<24)^(O>>>7|$<<25),S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,$=l[(R+14)%16],O=u[(R+14)%16],b=($>>>19|O<<13)^(O>>>29|$<<3)^$>>>6,x=(O>>>19|$<<13)^($>>>29|O<<3)^(O>>>6|$<<26),S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,l[R]=k&65535|A<<16,u[R]=S&65535|w<<16;b=X,x=ie,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[0],x=c[0],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[0]=X=k&65535|A<<16,c[0]=ie=S&65535|w<<16,b=re,x=oe,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[1],x=c[1],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[1]=re=k&65535|A<<16,c[1]=oe=S&65535|w<<16,b=se,x=ce,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[2],x=c[2],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[2]=se=k&65535|A<<16,c[2]=ce=S&65535|w<<16,b=ne,x=Ae,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[3],x=c[3],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[3]=ne=k&65535|A<<16,c[3]=Ae=S&65535|w<<16,b=h,x=ye,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[4],x=c[4],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[4]=h=k&65535|A<<16,c[4]=ye=S&65535|w<<16,b=ae,x=Se,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[5],x=c[5],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[5]=ae=k&65535|A<<16,c[5]=Se=S&65535|w<<16,b=le,x=Ke,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[6],x=c[6],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[6]=le=k&65535|A<<16,c[6]=Ke=S&65535|w<<16,b=de,x=Pe,S=x&65535,w=x>>>16,k=b&65535,A=b>>>16,b=s[7],x=c[7],S+=x&65535,w+=x>>>16,k+=b&65535,A+=b>>>16,w+=S>>>16,k+=w>>>16,A+=k>>>16,s[7]=de=k&65535|A<<16,c[7]=Pe=S&65535|w<<16,Ue+=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(),C=e();$e(o,s[1],s[0]),$e(C,c[1],c[0]),V(o,o,C),Te(r,s[0],s[1]),Te(C,c[0],c[1]),V(r,r,C),V(l,s[3],c[3]),V(l,l,K),V(u,s[2],c[2]),Te(u,u,u),$e(p,r,o),$e(v,u,l),Te(T,u,l),Te(L,r,o),V(s[0],p,v),V(s[1],L,T),V(s[2],T,v),V(s[3],p,L);}function dr(s,c,o){var r;for(r=0;r<4;r++)ke(s[r],c[r],o);}function Bt(s,c){var o=e(),r=e(),l=e();Je(l,c[2]),V(o,c[0],l),V(r,c[1],l),ge(s,r),s[31]^=ve(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],F),z(o[2],d),V(o[3],m,F),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),C=[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(C,p),Bt(s,C),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),Ie(s[1],c),ue(l,s[1]),V(u,l,_),$e(l,l,s[2]),Te(u,s[2],u),ue(p,u),ue(v,p),V(T,v,p),V(o,T,l),V(o,o,u),Ye(o,o),V(o,o,l),V(o,o,u),V(o,o,u),V(s[0],o,u),ue(r,s[0]),V(r,r,u),_e(r,l)&&V(s[0],s[0],q),ue(r,s[0]),V(r,r,u),_e(r,l)?-1:(ve(s[0])===c[31]>>7&&$e(s[0],f,s[0]),V(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,xe(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,kt=24,ht=32,at=16,yt=32,St=32,ut=32,pt=32,qt=32,yr=kt,fn=ht,ln=at,Qe=64,rt=32,ot=64,Jt=32,Vt=64;a.lowlevel={crypto_core_hsalsa20:Ce,crypto_stream_xor:De,crypto_stream:ze,crypto_stream_salsa20_xor:Ve,crypto_stream_salsa20:He,crypto_onetimeauth:P,crypto_onetimeauth_verify:he,crypto_verify_16:H,crypto_verify_32:xe,crypto_secretbox:pe,crypto_secretbox_open:N,crypto_scalarmult:st,crypto_scalarmult_base:it,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:kt,crypto_secretbox_ZEROBYTES:ht,crypto_secretbox_BOXZEROBYTES:at,crypto_scalarmult_BYTES:yt,crypto_scalarmult_SCALARBYTES:St,crypto_box_PUBLICKEYBYTES:ut,crypto_box_SECRETKEYBYTES:pt,crypto_box_BEFORENMBYTES:qt,crypto_box_NONCEBYTES:yr,crypto_box_ZEROBYTES:fn,crypto_box_BOXZEROBYTES:ln,crypto_sign_BYTES:Qe,crypto_sign_PUBLICKEYBYTES:rt,crypto_sign_SECRETKEYBYTES:ot,crypto_sign_SEEDBYTES:Jt,crypto_hash_BYTES:Vt,gf:e,D:_,L:vt,pack25519:ge,unpack25519:Ie,M:V,A:Te,S:ue,Z:$e,pow2523:Ye,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!==kt)throw new Error("bad nonce size")}function dn(s,c){if(s.length!==ut)throw new Error("bad public key size");if(c.length!==pt)throw new Error("bad secret key size")}function Xe(){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){Xe(s,c,o),ur(o,c);for(var r=new Uint8Array(ht+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+ht]=s[u];return pe(l,r,r.length,c,o),l.subarray(at)},a.secretbox.open=function(s,c,o){Xe(s,c,o),ur(o,c);for(var r=new Uint8Array(at+s.length),l=new Uint8Array(r.length),u=0;u<s.length;u++)r[u+at]=s[u];return r.length<32||N(l,r,r.length,c,o)!==0?null:l.subarray(ht)},a.secretbox.keyLength=Xt,a.secretbox.nonceLength=kt,a.secretbox.overheadLength=at,a.scalarMult=function(s,c){if(Xe(s,c),s.length!==St)throw new Error("bad n size");if(c.length!==yt)throw new Error("bad p size");var o=new Uint8Array(yt);return st(o,s,c),o},a.scalarMult.base=function(s){if(Xe(s),s.length!==St)throw new Error("bad n size");var c=new Uint8Array(yt);return it(c,s),c},a.scalarMult.scalarLength=St,a.scalarMult.groupElementLength=yt,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){Xe(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(ut),c=new Uint8Array(pt);return or(s,c),{publicKey:s,secretKey:c}},a.box.keyPair.fromSecretKey=function(s){if(Xe(s),s.length!==pt)throw new Error("bad secret key size");var c=new Uint8Array(ut);return it(c,s),{publicKey:c,secretKey:new Uint8Array(s)}},a.box.publicKeyLength=ut,a.box.secretKeyLength=pt,a.box.sharedKeyLength=qt,a.box.nonceLength=yr,a.box.overheadLength=a.secretbox.overheadLength,a.sign=function(s,c){if(Xe(s,c),c.length!==ot)throw new Error("bad secret key size");var o=new Uint8Array(Qe+s.length);return hr(o,s,s.length,c),o},a.sign.open=function(s,c){if(Xe(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(Qe),l=0;l<r.length;l++)r[l]=o[l];return r},a.sign.detached.verify=function(s,c,o){if(Xe(s,c,o),c.length!==Qe)throw new Error("bad signature size");if(o.length!==rt)throw new Error("bad public key size");var r=new Uint8Array(Qe+s.length),l=new Uint8Array(Qe+s.length),u;for(u=0;u<Qe;u++)r[u]=c[u];for(u=0;u<s.length;u++)r[u+Qe]=s[u];return zt(l,r,r.length,o)>=0},a.sign.keyPair=function(){var s=new Uint8Array(rt),c=new Uint8Array(ot);return Dt(s,c),{publicKey:s,secretKey:c}},a.sign.keyPair.fromSecretKey=function(s){if(Xe(s),s.length!==ot)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(Xe(s),s.length!==Jt)throw new Error("bad seed size");for(var c=new Uint8Array(rt),o=new Uint8Array(ot),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=ot,a.sign.seedLength=Jt,a.sign.signatureLength=Qe,a.hash=function(s){Xe(s);var c=new Uint8Array(Vt);return tt(c,s,s.length),c},a.hash.hashLength=Vt,a.verify=function(s,c){return Xe(s,c),s.length===0||c.length===0||s.length!==c.length?false:J(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 We=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 kr(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 Sr=(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 gt=a=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,a])});var kn=BigInt(0),mt=BigInt(1),Sn=BigInt(2),Kn=BigInt(7),Pn=BigInt(256),An=BigInt(113),Cr=[],$r=[],jr=[];for(let a=0,e=mt,t=1,n=0;a<24;a++){[t,n]=[n,(2*t+3*n)%5],Cr.push(2*(5*n+t)),$r.push((a+1)*(a+2)/2%64);let i=kn;for(let f=0;f<7;f++)e=(e<<mt^(e>>Kn)*An)%Pn,e&Sn&&(i^=mt<<(mt<<BigInt(f))-mt);jr.push(i);}var Mr=kr(jr,true),Tn=Mr[0],Un=Mr[1],Er=(a,e,t)=>t>32?Pr(a,e,t):Sr(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],F=Er(K,m,1)^t[y],q=Rr(K,m,1)^t[y+1];for(let M=0;M<50;M+=10)a[d+M]^=F,a[d+M+1]^=q;}let i=a[2],f=a[3];for(let d=0;d<24;d++){let y=$r[d],_=Er(i,f,y),K=Rr(i,f,y),m=Cr[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,gt(8)),Ct=Ir(6,72,64,gt(10));var Fr=(a,e,t,n={})=>tr((i={})=>new Et(e,a,i.dkLen===void 0?t:i.dkLen,true),n),$t=Fr(31,168,16,gt(11)),ct=Fr(31,136,32,gt(12));var Rn={},Or=Cn(globalThis,Rn);function Cn(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 qe(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 me(a){return a%65536}function jt(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 Ge(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 ct.create({dkLen:a}).update(e).update(new Uint8Array([t])).digest()}function Nr(a){let e=Ge(a[0]);return e|=Ge(a[1])<<8,e|=Ge(a[2])<<16,e|=Ge(a[3])<<24,Ge(e)}var ft=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 We(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 We(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 We(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),F=this._encap(i,y,K);return Br(e,F)===1?_:m}catch(n){throw new We(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]=bt(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 F=new Array(this._k);for(let H=0;H<this._k;H++)F[H]=Ft(y[H],_),F[H]=sr(F[H]),F[H]=bt(F[H],K[H]),F[H]=nt(F[H]);let q=On(t),M=Ft(i,_);M=sr(M),M=bt(M,m),M=bt(M,q),M=nt(M);let J=new Uint8Array(this._compressedUSize+this._compressedVSize);return this._compressU(J.subarray(0,this._compressedUSize),F),this._compressV(J.subarray(this._compressedUSize),M),J}_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),F=Xr(m,168,256-f),q=F[0],M=F[1];for(let J=f;J<256;J++)n[d][y][J]=q[J-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++]=qe(n[0]>>0),e[i++]=qe(n[0]>>8|n[1]<<2),e[i++]=qe(n[1]>>6|n[2]<<4),e[i++]=qe(n[2]>>4|n[3]<<6),e[i++]=qe(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]=qe(((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]=me(e[i+0])>>0|me(e[i+1])<<8,n[1]=me(e[i+1])>>2|me(e[i+2])<<6,n[2]=me(e[i+2])>>4|me(e[i+3])<<4,n[3]=me(e[i+3])>>6|me(e[i+4])<<2,i=i+5;for(let y=0;y<4;y++)t[f][4*d+y]=Ne(Ge(n[y]&1023)*Ge(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(me(e[n]&15)*me(3329)+8>>4),t[2*i+1]=Ne(me(e[n]>>4)*me(3329)+8>>4);return t}};function rr(a,e){let t=Ct.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=ct.create({dkLen:32}).update(a);return e!==void 0&&t.update(e),t.digest()}function In(a,e){return $t.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=me(i[2*f]),t=me(i[2*f+1]),n[3*f+0]=qe(e>>0),n[3*f+1]=qe(e>>8)|qe(t<<4),n[3*f+2]=qe(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((me(a[3*t+0])>>0|me(a[3*t+1])<<8)&4095),e[2*t+1]=Ne((me(a[3*t+1])>>4|me(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=((me(n[8*i+f])<<1)+me(3329/2))/me(3329)&1,e[i]|=qe(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=(me(a[y]>>0)|me(a[y+1])<<8)&4095,d=(me(a[y+1]>>4)|me(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=et(f,a[e+n]);a[e+n]=a[e]-d,a[e]=a[e]+d;}}return a}function et(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(jt(a)*62209)*3329;return t=a-t,t>>=16,Ne(t)}function Bn(a){for(let t=0;t<256;t++)a[t]=Qr(jt(a[t])*jt(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=bt(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]=et(e,n),f[0]=et(f[0],i),f[0]+=et(a,t),f[1]=et(a,n),f[1]+=et(e,t),f}function bt(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]=et(f,a[e+n]);}}for(e=0;e<256;e++)a[e]=et(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 Ze=class extends ft{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 lt(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 dt(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 Ze().generateKeyPair());let K=U.default.box.keyPair(),m=1,F=U.default.sign.detached(K.publicKey,i.secretKey),q={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)(F),signed_prekey_id:m};y&&(q.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(q)});if(!M.ok){let xe=await M.json().catch(()=>({})),Le=xe.error?.message||xe.error||M.statusText;throw new Error(`Registration failed: ${Le}`)}let J=await M.json(),H=new a({did:J.did,apiKey:J.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 F=(0,g.decodeBase64)(m.sendChainKey),q=(0,g.decodeBase64)(m.recvChainKey);if(F.length!==32||q.length!==32)continue;let M={sendChainKey:F,sendStep:m.sendStep||0,recvChainKey:q,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 J=(0,g.decodeBase64)(m.dhSendSecretKey),H=(0,g.decodeBase64)(m.dhSendPublicKey);J.length===32&&H.length===32&&(M.dhSendKeyPair={publicKey:H,secretKey:J});}catch{}if(m.dhRecvPubKey)try{let J=(0,g.decodeBase64)(m.dhRecvPubKey);J.length===32&&(M.dhRecvPubKey=J);}catch{}if(m.prevSendStep!==void 0&&(M.prevSendStep=m.prevSendStep),M.dhSkippedKeys=new Map,m.skippedKeys&&typeof m.skippedKeys=="object")for(let[J,H]of Object.entries(m.skippedKeys))try{let xe=(0,g.decodeBase64)(H);xe.length===32&&M.skippedKeys.set(Number(J),xe);}catch{}if(m.dhSkippedKeys&&typeof m.dhSkippedKeys=="object")for(let[J,H]of Object.entries(m.dhSkippedKeys))try{let xe=(0,g.decodeBase64)(H);xe.length===32&&M.dhSkippedKeys.set(J,xe);}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),F=m.sendStep+m.recvStep;if((_.sendStep||0)+(_.recvStep||0)<=F)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 F=`${this.did}:${e}`,q=this._ratchetStates.get(F),M=null,J=null;if(q)q.rootKey&&q.dhSendKeyPair&&(J=q.dhSendKeyPair.publicKey);else {let pe=U.default.box.before(_,this.encryptionKeyPair.secretKey),N;if(this.postQuantum&&y.mlkem_public_key)try{let z=(0,g.decodeBase64)(y.mlkem_public_key),we=new Ze,[ke,ge]=await we.encap(z);M=ke;let _e=new Uint8Array(pe.length+ge.length);_e.set(pe,0),_e.set(ge,pe.length),N=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",_e));}catch{N=pe;}else N=pe;if(this.doubleRatchet){let z=U.default.box.keyPair(),we=U.default.box.before(_,z.secretKey),{newRootKey:ke,newChainKey:ge}=await dt(N,we);J=z.publicKey,q={sendChainKey:ge,sendStep:0,recvChainKey:N,recvStep:0,skippedKeys:new Map,rootKey:ke,dhSendKeyPair:z,dhRecvPubKey:void 0,prevSendStep:0,dhSkippedKeys:new Map};}else q={sendChainKey:N,sendStep:0,recvChainKey:N,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(F,q);}let{nextChainKey:H,messageKey:xe}=await lt(q.sendChainKey);q.sendChainKey=H,q.sendStep++;let Le=q.sendStep,Re=Xn;f&&(Re|=Wr),d&&(Re|=en),M&&(Re|=qn),J&&(Re|=Jn),this.deniable&&(Re|=Vn);let je=Yn(Re,Le),Ce=new Uint8Array(je.length+m.length);Ce.set(je,0),Ce.set(m,je.length);let Me=U.default.randomBytes(U.default.secretbox.nonceLength),Ve=U.default.secretbox(Ce,Me,xe);if(!Ve)throw new Error("Encryption failed");if(this.jitterMs>0){let pe=Math.random()*this.jitterMs;await new Promise(N=>setTimeout(N,pe));}let He={from:this.did,to:e,timestamp:new Date().toISOString(),nonce:(0, g.encodeBase64)(Me),ciphertext_hash:await ir((0, g.encodeBase64)(Ve)),ratchet_step:Le};M&&(He.pq_ciphertext=(0, g.encodeBase64)(M)),J&&(He.dh_ratchet_key=(0, g.encodeBase64)(J),He.pn=q.prevSendStep||0);let ze=JSON.stringify(He),De;if(this.deniable){let pe=U.default.box.before(_,this.encryptionKeyPair.secretKey);De=await tn(pe,(0, g.decodeUTF8)(ze));}else De=U.default.sign.detached((0, g.decodeUTF8)(ze),this.signingKeyPair.secretKey);let E={to:e,ciphertext:(0, g.encodeBase64)(Ve),nonce:(0, g.encodeBase64)(Me),signature:(0, g.encodeBase64)(De),envelope:ze,ttl:n.ttl};d||(E.content_type=n.contentType||"text/plain",E.message_type=n.messageType||"text",E.thread_id=n.threadId,E.reply_to=n.replyTo);try{await this._persistRatchetState();}catch{}let P=[this.baseUrl,...this.fallbackRelays],he=null;for(let pe of P)try{let N=await this._fetchWithRetry(`${pe}/v1/agent/send/encrypted`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify(E)},{maxRetries:i,baseDelay:500,maxDelay:1e4});return {id:N.id,from:N.from,to:N.to,timestamp:N.timestamp,expiresAt:N.expires_at||N.expiresAt,encrypted:N.encrypted,clientSide:N.client_side||N.clientSide}}catch(N){if(he=N instanceof Error?N:new Error(String(N)),he.message.includes("(4"))break}throw he&&!he.message.includes("(4")&&this._offlineQueue.push({recipientDid:e,message:t,options:n,timestamp:Date.now()}),he||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)){n.push(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 E=JSON.parse(f.envelope),P=await this.getIdentity(E.from);if(!P){n.push(f.id);continue}d=(0,g.decodeBase64)(P.encryption_public_key),P.signing_public_key&&(y=(0,g.decodeBase64)(P.signing_public_key));}else {n.push(f.id);continue}let _=(0,g.decodeBase64)(f.ciphertext),K=(0,g.decodeBase64)(f.nonce),m=null,F=0,q=null,M=null,J=0;if(f.envelope)try{let E=JSON.parse(f.envelope);typeof E.ratchet_step=="number"&&Number.isInteger(E.ratchet_step)&&E.ratchet_step>=0&&E.ratchet_step<=4294967295&&(F=E.ratchet_step),typeof E.pq_ciphertext=="string"&&E.pq_ciphertext.length<=65536&&(q=E.pq_ciphertext),typeof E.dh_ratchet_key=="string"&&E.dh_ratchet_key.length<=256&&(M=E.dh_ratchet_key),typeof E.pn=="number"&&Number.isInteger(E.pn)&&E.pn>=0&&E.pn<=4294967295&&(J=E.pn);}catch{}if(F>0){let E=`${f.from}:${this.did}`,P=this._ratchetStates.get(E);if(P){if(M&&P.rootKey){let N=(0,g.decodeBase64)(M),z=P.dhRecvPubKey;if(!z||(0,g.encodeBase64)(N)!==(0,g.encodeBase64)(z)){if(J>P.recvStep){let Ie=P.recvChainKey;for(let Te=P.recvStep+1;Te<=J&&Te-P.recvStep<=Ot;Te++){let{nextChainKey:$e,messageKey:V}=await lt(Ie),ue=`${z?(0,g.encodeBase64)(z):"init"}:${Te}`;for(P.dhSkippedKeys||(P.dhSkippedKeys=new Map),P.dhSkippedKeys.set(ue,V),Ie=$e;P.dhSkippedKeys.size>Ot;){let Je=P.dhSkippedKeys.keys().next().value;if(Je!==void 0)P.dhSkippedKeys.delete(Je);else break}}}P.dhRecvPubKey=N;let we=P.dhSendKeyPair||this.encryptionKeyPair,ke=U.default.box.before(N,we.secretKey),ge=await dt(P.rootKey,ke);P.rootKey=ge.newRootKey,P.recvChainKey=ge.newChainKey,P.recvStep=0,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0;let _e=U.default.box.before(N,P.dhSendKeyPair.secretKey),ve=await dt(P.rootKey,_e);P.rootKey=ve.newRootKey,P.sendChainKey=ve.newChainKey;}}}else {let N=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(q&&this.mlkemSecretKey)try{let ke=(0,g.decodeBase64)(q),_e=await new Ze().decap(ke,this.mlkemSecretKey),ve=new Uint8Array(N.length+_e.length);ve.set(N,0),ve.set(_e,N.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",ve));}catch{z=N;}else z=N;if(M&&this.doubleRatchet){let ke=(0,g.decodeBase64)(M),ge=U.default.box.before(ke,this.encryptionKeyPair.secretKey),{newRootKey:_e,newChainKey:ve}=await dt(z,ge);P={sendChainKey:z,sendStep:0,recvChainKey:ve,recvStep:0,skippedKeys:new Map,rootKey:_e,dhSendKeyPair:void 0,dhRecvPubKey:ke,prevSendStep:0,dhSkippedKeys:new Map};}else P={sendChainKey:z,sendStep:0,recvChainKey:z,recvStep:0,skippedKeys:new Map};this._ratchetStates.set(E,P);let we=`${this.did}:${f.from}`;this._ratchetStates.delete(we);}let he=F,pe=M?`${M}:${he}`:`init:${he}`;if(P.dhSkippedKeys?.has(pe)){let N=P.dhSkippedKeys.get(pe);m=U.default.secretbox.open(_,K,N),P.dhSkippedKeys.delete(pe);}else if(P.skippedKeys.has(he)){let N=P.skippedKeys.get(he);m=U.default.secretbox.open(_,K,N),P.skippedKeys.delete(he);}else if(he>P.recvStep)if(he-P.recvStep>Ot){this._decryptFailCount++,n.push(f.id);let z=f.from||"unknown",we=this._peerDecryptFails.get(z)||0;this._peerDecryptFails.set(z,we+1),this._autoResetThreshold>0&&we+1>=this._autoResetThreshold&&(this.resetRatchet(z),i.add(z),this._onRatchetReset?.(z,we+1));continue}else {let z=P.recvChainKey;for(let ge=P.recvStep+1;ge<he;ge++){let{nextChainKey:_e,messageKey:ve}=await lt(z);for(P.skippedKeys.set(ge,ve),z=_e;P.skippedKeys.size>Ot;){let Ie=P.skippedKeys.keys().next().value;if(Ie!==void 0)P.skippedKeys.delete(Ie);else break}}let{nextChainKey:we,messageKey:ke}=await lt(z);P.recvChainKey=we,P.recvStep=he,m=U.default.secretbox.open(_,K,ke);}if(!m&&M&&this.doubleRatchet&&P)try{let N=U.default.box.before(d,this.encryptionKeyPair.secretKey),z;if(q&&this.mlkemSecretKey)try{let V=(0,g.decodeBase64)(q),Je=await new Ze().decap(V,this.mlkemSecretKey),Ye=new Uint8Array(N.length+Je.length);Ye.set(N,0),Ye.set(Je,N.length),z=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",Ye));}catch{z=N;}else z=N;let we=(0,g.decodeBase64)(M),ke=U.default.box.before(we,this.encryptionKeyPair.secretKey),{newRootKey:ge,newChainKey:_e}=await dt(z,ke),ve=_e;for(let V=1;V<F;V++){let{nextChainKey:ue}=await lt(ve);ve=ue;}let{nextChainKey:Ie,messageKey:Te}=await lt(ve),$e=U.default.secretbox.open(_,K,Te);if($e){m=$e,P.recvChainKey=Ie,P.recvStep=F,P.rootKey=ge,P.dhRecvPubKey=we,P.prevSendStep=P.sendStep,P.dhSendKeyPair=U.default.box.keyPair(),P.sendStep=0;let V=U.default.box.before(we,P.dhSendKeyPair.secretKey),ue=await dt(P.rootKey,V);P.rootKey=ue.newRootKey,P.sendChainKey=ue.newChainKey,P.dhSkippedKeys&&P.dhSkippedKeys.clear(),P.skippedKeys&&P.skippedKeys.clear();let Je=`${this.did}:${f.from}`;this._ratchetStates.delete(Je);}}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 E=f.from||"unknown",P=this._peerDecryptFails.get(E)||0;this._peerDecryptFails.set(E,P+1),this._autoResetThreshold>0&&P+1>=this._autoResetThreshold&&(this.resetRatchet(E),i.add(E),this._onRatchetReset?.(E,P+1));continue}{let E=f.from||"unknown";this._peerDecryptFails.has(E)&&this._peerDecryptFails.delete(E);}let H=m,xe=!1,Le=!1,Re=Qn(m);if(Re&&(xe=!!(Re.flags&Wr),Le=!!(Re.flags&en),H=Re.content),xe)H=Zr(H);else if(!Re&&m.length>=256&&(m.length&m.length-1)===0){let E=Zr(m);E.length<m.length&&(H=E);}let je=(0,g.encodeUTF8)(H),Ce=f.from,Me,Ve,He,ze;if(Le||!Re){let E=zn(je);E&&(je=E.msg,Ce=E.from,Me=E.contentType,Ve=E.messageType,He=E.threadId,ze=E.replyTo);}let De=!1;try{let E=(0,g.decodeBase64)(f.signature),P=f.envelope||JSON.stringify({from:Ce,to:f.to,timestamp:f.timestamp,nonce:f.nonce,ciphertext_hash:await ir(f.ciphertext)});if(E.length===32){let he=U.default.box.before(d,this.encryptionKeyPair.secretKey),pe=await tn(he,(0,g.decodeUTF8)(P));if(pe.length===E.length){let N=0;for(let z=0;z<pe.length;z++)N|=pe[z]^E[z];De=N===0;}}else y&&(De=U.default.sign.detached.verify((0,g.decodeUTF8)(P),E,y));}catch{De=!1;}if(this.requireSignatures&&!De){this._decryptFailCount++,n.push(f.id);let E=f.from||"unknown",P=this._peerDecryptFails.get(E)||0;this._peerDecryptFails.set(E,P+1);continue}if(this._seenMessageIds.add(f.id),this._seenMessageIds.size>1e4){let E=this._seenMessageIds.values();for(let P=0;P<1e3;P++){let he=E.next().value;he!==void 0&&this._seenMessageIds.delete(he);}}t.push({id:f.id,from:Ce,to:f.to,content:je,contentType:Me||f.content_type||"text/plain",messageType:Ve||f.message_type||"text",threadId:He||f.thread_id||null,replyTo:ze||f.reply_to||null,signatureValid:De,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(J=>J.toString(16).padStart(2,"0")).join("")}`;if(t.length!==m.length)return false;let F=i.encode(t),q=i.encode(m),M=0;for(let J=0;J<F.length;J++)M|=F[J]^q[J];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},y=null;if(this.postQuantum&&this.mlkemPublicKey){let K=new Ze,[m,F]=await K.generateKeyPair();d.mlkem_public_key=(0, g.encodeBase64)(m),y=F;}if(!(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,y&&(this.mlkemSecretKey=y,this.mlkemPublicKey=(0, g.decodeBase64)(d.mlkem_public_key)),this._identityCache.clear(),this._pinnedDids.clear(),await this.uploadPrekeys(10);}async claimUsername(e){let t=await this._resilientFetch("/v1/agent/username",{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({username:e})}),n=await t.json();if(!t.ok)throw new Error(n.error||`Claim failed (${t.status})`);return n}async changeUsername(e){let t=await this._resilientFetch("/v1/agent/username",{method:"PUT",headers:{"Content-Type":"application/json","X-Agent-Key":this.apiKey},body:JSON.stringify({username:e})}),n=await t.json();if(!t.ok)throw new Error(n.error||`Change failed (${t.status})`);return n}async releaseUsername(){let e=await this._resilientFetch("/v1/agent/username",{method:"DELETE",headers:{"X-Agent-Key":this.apiKey}});if(!e.ok){let t=await e.json();throw new Error(t.error||`Release failed (${e.status})`)}}async getMyUsername(){let e=await this._resilientFetch("/v1/agent/username",{method:"GET",headers:{"X-Agent-Key":this.apiKey}}),t=await e.json();return e.ok&&t.username||null}static async resolveUsername(e,t="https://api.voidly.ai"){let n=e.toLowerCase().replace(/^@/,""),i=new AbortController,f=setTimeout(()=>i.abort(),3e4);try{let d=await fetch(`${t}/v1/agent/username/${encodeURIComponent(n)}`,{signal:i.signal});return d.ok?await d.json():null}catch{return null}finally{clearTimeout(f);}}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}:{}});if(!n.ok){let f=await n.text().catch(()=>"");throw new Error(`listChannels failed: ${n.status} ${f.slice(0,200)}`)}return (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)),F=U.default.randomBytes(U.default.box.nonceLength),q=U.default.box(m,F,K,this.encryptionKeyPair.secretKey),M=U.default.sign.detached(m,this.signingKeyPair.secretKey);n.encrypted_output=(0, g.encodeBase64)(q),n.output_nonce=(0, g.encodeBase64)(F),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}});if(!t.ok){let i=await t.text().catch(()=>"");throw new Error(`listInvites failed: ${t.status} ${i.slice(0,200)}`)}return (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:q}=await import('crypto');K=new Uint8Array(q("sha256").update(Buffer.from(_)).digest());}let m=U.default.secretbox(d,y,K),F=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(!F.ok)throw new Error(`Memory set failed: ${F.status} ${await F.text()}`);return F.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 F=!1;if(y.sig&&y.from)try{let q=await this.getIdentity(y.from);if(q){let M=new Uint8Array([..._,...K]);F=U.default.sign.detached.verify(M,(0,g.decodeBase64)(y.sig),(0,g.decodeBase64)(q.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:F});}}}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,F=i,q=0,M,J=null,H=null,xe=null,Le={stop:()=>{m=false,J&&clearTimeout(J),H&&clearInterval(H),xe&&(xe.abort(),xe=null),this._listeners.delete(Le);},get active(){return m}};this._listeners.add(Le),_&&(H=setInterval(async()=>{if(m)try{await this.ping();}catch{}},K),this.ping().catch(()=>{}));let Re=async E=>{for(let P of E)try{await e(P),d&&await this.markRead(P.id).catch(()=>{});}catch(he){n&&n(he instanceof Error?he:new Error(String(he)));}E.length>0&&(M=E[E.length-1].timestamp);},je="",Ce=0,Me=async()=>{try{let E=new URLSearchParams;M&&E.set("since",M),t.from&&E.set("from",t.from);let P=`${this.baseUrl}/v1/agent/receive/sse?${E}`,he={"X-Agent-Key":this.apiKey};je&&(he["Last-Event-ID"]=je);let pe=new AbortController;xe=pe;let N=setTimeout(()=>pe.abort(),6e4),z;try{z=await fetch(P,{headers:he,signal:pe.signal});}catch(_e){throw clearTimeout(N),_e}if(!z.ok||!z.body)return clearTimeout(N),!1;let we=z.body.getReader(),ke=new TextDecoder,ge="";try{let _e="",ve="",Ie="";for(;m&&!t.signal?.aborted;){let{done:Te,value:$e}=await we.read();if(Te)break;ge+=ke.decode($e,{stream:!0});let V=ge.split(`
|
|
3
3
|
`);ge=V.pop()||"";for(let ue of V)if(ue.startsWith("event: "))_e=ue.slice(7).trim();else if(ue.startsWith("data: "))ve+=(ve?`
|
|
4
|
-
`:"")+ue.slice(6);else if(ue.startsWith("id: "))Ie=ue.slice(4).trim();else if(ue===""&&(ve||_e)){if(Ie&&($e=Ie),_e==="message"&&ve)try{let Je=JSON.parse(ve),{decrypted:Ye,failedIds:st}=await this._decryptMessages([Je]);for(let it of st)try{await this.markRead(it);}catch{}Ye.length>0&&(q=0,Ce=0,await Re(Ye));}catch{}else if(_e==="reconnect")break;_e="",ve="",Ie="";}}}finally{we.releaseLock(),clearTimeout(N);}return Ce=0,!0}catch{return Ce++,false}},Ve=async()=>{for(;m&&!t.signal?.aborted;){let E=await Me();if(!m||t.signal?.aborted)break;if(!E){if(Ce>=3){ze();return}let P=Math.min(1e3*Math.pow(2,Ce-1),4e3);await new Promise(he=>setTimeout(he,P));continue}await new Promise(P=>setTimeout(P,500));}},He=this.longPoll,ze=async()=>{if(!m||t.signal?.aborted){Le.stop();return}try{let E=await this.receive({since:M,from:t.from,threadId:t.threadId,messageType:t.messageType,unreadOnly:y,limit:50});E.length>0?(q=0,f&&(O=Math.max(i/2,500)),await Re(E)):(q++,f&&q>3&&!He&&(O=Math.min(O*1.5,i*4)));}catch(E){n&&n(E instanceof Error?E:new Error(String(E))),O=Math.min(O*2,i*8);}m&&!t.signal?.aborted&&(J=setTimeout(ze,He?100:O));};return this._transportPrefs.includes("sse")?Ve():ze(),Le}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),q=U.default.box(O,K,m,this.encryptionKeyPair.secretKey),M=JSON.stringify({from:this.did,to:e,ciphertext:(0,g.encodeBase64)(q),nonce:(0,g.encodeBase64)(K),timestamp:new Date().toISOString(),message_type:n.messageType||"text",thread_id:n.threadId}),J=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)(J)}`,"X-Voidly-Sender":this.did},body:M})).ok){let xe=new Date;return {id:`direct-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,from:this.did,to:e,timestamp:xe.toISOString(),expiresAt:new Date(xe.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:
|
|
4
|
+
`:"")+ue.slice(6);else if(ue.startsWith("id: "))Ie=ue.slice(4).trim();else if(ue===""&&(ve||_e)){if(Ie&&(je=Ie),_e==="message"&&ve)try{let Je=JSON.parse(ve),{decrypted:Ye,failedIds:st}=await this._decryptMessages([Je]);for(let it of st)try{await this.markRead(it);}catch{}Ye.length>0&&(q=0,Ce=0,await Re(Ye));}catch{}else if(_e==="reconnect")break;_e="",ve="",Ie="";}}}finally{we.releaseLock(),clearTimeout(N);}return Ce=0,!0}catch{return Ce++,false}},Ve=async()=>{for(;m&&!t.signal?.aborted;){let E=await Me();if(!m||t.signal?.aborted)break;if(!E){if(Ce>=3){ze();return}let P=Math.min(1e3*Math.pow(2,Ce-1),4e3);await new Promise(he=>setTimeout(he,P));continue}await new Promise(P=>setTimeout(P,500));}},He=this.longPoll,ze=async()=>{if(!m||t.signal?.aborted){Le.stop();return}try{let E=await this.receive({since:M,from:t.from,threadId:t.threadId,messageType:t.messageType,unreadOnly:y,limit:50});E.length>0?(q=0,f&&(F=Math.max(i/2,500)),await Re(E)):(q++,f&&q>3&&!He&&(F=Math.min(F*1.5,i*4)));}catch(E){n&&n(E instanceof Error?E:new Error(String(E))),F=Math.min(F*2,i*8);}m&&!t.signal?.aborted&&(J=setTimeout(ze,He?100:F));};return this._transportPrefs.includes("sse")?Ve():ze(),Le}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),F=(0,g.decodeUTF8)(t),q=U.default.box(F,K,m,this.encryptionKeyPair.secretKey),M=JSON.stringify({from:this.did,to:e,ciphertext:(0,g.encodeBase64)(q),nonce:(0,g.encodeBase64)(K),timestamp:new Date().toISOString(),message_type:n.messageType||"text",thread_id:n.threadId}),J=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)(J)}`,"X-Voidly-Sender":this.did},body:M})).ok){let xe=new Date;return {id:`direct-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,from:this.did,to:e,timestamp:xe.toISOString(),expiresAt:new Date(xe.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(()=>({})),F=m.error?.message||m.error||K.statusText;if(K.status>=400&&K.status<500)throw new Error(`Send failed (${K.status}): ${F}`);y=new Error(`Send failed (${K.status}): ${F}`);}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(F=>setTimeout(F,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) *)
|