@continuonai/rcan-ts 1.2.1 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.mts +2 -2
- package/dist/browser.mjs +2 -2
- package/dist/browser.mjs.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/rcan-validate.js +1 -1
- package/dist/rcan.iife.js +1 -1
- package/package.json +1 -1
package/dist/rcan-validate.js
CHANGED
package/dist/rcan.iife.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var RCAN=(()=>{var ms=Object.create;var nt=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var ys=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,_s=Object.prototype.hasOwnProperty;var ke=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var he=(t,e)=>()=>(t&&(e=t(t=0)),e);var on=(t,e)=>{for(var r in e)nt(t,r,{get:e[r],enumerable:!0})},sn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ys(e))!_s.call(t,o)&&o!==r&&nt(t,o,{get:()=>e[o],enumerable:!(n=hs(e,o))||n.enumerable});return t};var an=(t,e,r)=>(r=t!=null?ms(Rs(t)):{},sn(e||!t||!t.__esModule?nt(r,"default",{value:t,enumerable:!0}):r,t)),cn=t=>sn(nt({},"__esModule",{value:!0}),t);var d=he(()=>{});function br(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ar(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function O(t,e,r=""){let n=br(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",u=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+u)}return t}function Er(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vo(t,e){O(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function No(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Sr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Vs(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Gs(t){for(let e=0;e<t.length;e++)t[e]=Vs(t[e]);return t}function Tr(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];O(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Io(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Mo(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var Ks,Cr,kr,Mt=he(()=>{"use strict";d();Ks=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Cr=Ks?t=>t:Gs;kr=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});function Uo(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}var Po=he(()=>{"use strict";d();});function Js(t,e=!1){return e?{h:Number(t&Ut),l:Number(t>>Lo&Ut)}:{h:Number(t>>Lo&Ut)|0,l:Number(t&Ut)|0}}function Do(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Js(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ut,Lo,Bo,$o,jo,qo,Ho=he(()=>{"use strict";d();Ut=BigInt(4294967295),Lo=BigInt(32);Bo=(t,e,r)=>t<<r|e>>>32-r,$o=(t,e,r)=>e<<r|t>>>32-r,jo=(t,e,r)=>e<<r-32|t>>>64-r,qo=(t,e,r)=>t<<r-32|e>>>64-r});function ti(t,e=24){let r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)r[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,u=(i+2)%10,p=r[u],g=r[u+1],v=Fo(p,g,1)^r[a],k=Ko(p,g,1)^r[a+1];for(let b=0;b<50;b+=10)t[i+b]^=v,t[i+b+1]^=k}let o=t[2],s=t[3];for(let i=0;i<24;i++){let a=Go[i],u=Fo(o,s,a),p=Ko(o,s,a),g=Vo[i];o=t[g],s=t[g+1],t[g]=u,t[g+1]=p}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=t[i+a];for(let a=0;a<10;a++)t[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=Zs[n],t[1]^=ei[n]}Sr(r)}var Ys,Qe,Ws,Qs,zs,Xs,Vo,Go,Jo,Yo,Zs,ei,Fo,Ko,Or,Wo,Qo,X,vr=he(()=>{"use strict";d();Ho();Mt();Ys=BigInt(0),Qe=BigInt(1),Ws=BigInt(2),Qs=BigInt(7),zs=BigInt(256),Xs=BigInt(113),Vo=[],Go=[],Jo=[];for(let t=0,e=Qe,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Vo.push(2*(5*n+r)),Go.push((t+1)*(t+2)/2%64);let o=Ys;for(let s=0;s<7;s++)e=(e<<Qe^(e>>Qs)*Xs)%zs,e&Ws&&(o^=Qe<<(Qe<<BigInt(s))-Qe);Jo.push(o)}Yo=Do(Jo,!0),Zs=Yo[0],ei=Yo[1],Fo=(t,e,r)=>r>32?jo(t,e,r):Bo(t,e,r),Ko=(t,e,r)=>r>32?qo(t,e,r):$o(t,e,r);Or=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,r,n,o=!1,s=24){if(this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Ar(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=No(this.state)}clone(){return this._cloneInto()}keccak(){Cr(this.state32),ti(this.state32,this.rounds),Cr(this.state32),this.posOut=0,this.pos=0}update(e){Er(this),O(e);let{blockLen:r,state:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);for(let a=0;a<i;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:r,pos:n,blockLen:o}=this;e[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){Er(this,!1),O(e),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,s=e.length;o<s;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);e.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ar(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(vo(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=!0,Sr(this.state)}_cloneInto(e){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return e||=new t(r,n,o,i,s),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}},Wo=(t,e,r,n={})=>Io((o={})=>new Or(e,t,o.dkLen===void 0?r:o.dkLen,!0),n),Qo=Wo(31,168,16,kr(11)),X=Wo(31,136,32,kr(12))});function Nr(t){if(!Number.isSafeInteger(t)||t<0||t>4294967295)throw new Error("wrong u32 integer:"+t);return t}function Xo(t){return Nr(t),(t&t-1)===0&&t!==0}function Ir(t,e){Nr(t);let r=0;for(let n=0;n<e;n++,t>>>=1)r=r<<1|t&1;return r}function Zo(t){return Nr(t),31-Math.clz32(t)}function zo(t){let e=t.length;if(e<2||!Xo(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);let r=Zo(e);for(let n=0;n<e;n++){let o=Ir(n,r);if(n<o){let s=t[n];t[n]=t[o],t[o]=s}}return t}var Mr,es=he(()=>{"use strict";d();Mr=(t,e)=>{let{N:r,roots:n,dit:o,invertButterflies:s=!1,skipStages:i=0,brp:a=!0}=e,u=Zo(r);if(!Xo(r))throw new Error("FFT: Polynomial size should be power of two");let p=o!==s;return g=>{if(g.length!==r)throw new Error("FFT: wrong Polynomial length");o&&a&&zo(g);for(let v=0,k=1;v<u-i;v++){let b=o?v+1+i:u-v,M=1<<b,S=M>>1,L=r>>b;for(let K=0;K<r;K+=M)for(let _=0,w=k++;_<S;_++){let N=s?o?r-w:w:_*L,I=K+_,D=K+_+S,V=n[N],U=g[D],R=g[I];if(p){let P=t.mul(U,V);g[I]=t.add(R,P),g[D]=t.sub(R,P)}else s?(g[I]=t.add(U,R),g[D]=t.mul(t.sub(U,R),V)):(g[I]=t.add(R,U),g[D]=t.mul(t.sub(R,U),V))}}return!o&&a&&zo(g),g}}});function Pr(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Lr(t){if(typeof t!="object"||t===null||br(t))throw new Error("expected opts to be an object")}function Pt(t){Lr(t),t.context!==void 0&&O(t.context,void 0,"opts.context")}function Lt(t){Pt(t),t.extraEntropy!==!1&&t.extraEntropy!==void 0&&O(t.extraEntropy,void 0,"opts.extraEntropy")}function ze(t,...e){let r=o=>typeof o=="number"?o:o.bytesLen,n=e.reduce((o,s)=>o+r(s),0);return{bytesLen:n,encode:o=>{let s=new Uint8Array(n);for(let i=0,a=0;i<e.length;i++){let u=e[i],p=r(u),g=typeof u=="number"?o[i]:u.encode(o[i]);O(g,p,t),s.set(g,a),typeof u!="number"&&g.fill(0),a+=p}return s},decode:o=>{O(o,n,t);let s=[];for(let i of e){let a=r(i),u=o.subarray(0,a);s.push(typeof i=="number"?u:i.decode(u)),o=o.subarray(a)}return s}}}function Ie(t,e){let r=e*t.bytesLen;return{bytesLen:r,encode:n=>{if(n.length!==e)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${e}`);let o=new Uint8Array(r);for(let s=0,i=0;s<n.length;s++){let a=t.encode(n[s]);o.set(a,i),a.fill(0),i+=a.length}return o},decode:n=>{O(n,r);let o=[];for(let s=0;s<n.length;s+=t.bytesLen)o.push(t.decode(n.subarray(s,s+t.bytesLen)));return o}}}function pe(...t){for(let e of t)if(Array.isArray(e))for(let r of e)r.fill(0);else e.fill(0)}function Dr(t){return(1<<t)-1}function Br(t,e=ts){if(O(t),O(e),e.length>255)throw new Error("context should be less than 255 bytes");return Tr(new Uint8Array([0,e.length]),e,t)}function rs(t,e=0){if(!t.oid||!Pr(t.oid.subarray(0,10),ri))throw new Error("hash.oid is invalid: expected NIST hash");let r=t.outputLen*8/2;if(e>r)throw new Error("Pre-hash security strength too low: "+r+", required: "+e)}function $r(t,e,r=ts){if(O(e),O(r),r.length>255)throw new Error("context should be less than 255 bytes");let n=t(e);return Tr(new Uint8Array([1,r.length]),r,t.oid,n)}var Ur,ts,ri,jr=he(()=>{"use strict";d();Mt();Mt();Ur=Mo;ts=Uint8Array.of();ri=Uint8Array.from([6,9,96,134,72,1,101,3,4,2])});var ns,os,Dt,Bt,ss=he(()=>{"use strict";d();es();vr();jr();ns=t=>{let{newPoly:e,N:r,Q:n,F:o,ROOT_OF_UNITY:s,brvBits:i,isKyber:a}=t,u=(_,w=n)=>{let N=_%w|0;return(N>=0?N|0:w+N|0)|0},p=(_,w=n)=>{let N=u(_,w)|0;return(N>w>>1?N-w|0:N)|0};function g(){let _=e(r);for(let w=0;w<r;w++){let N=Ir(w,i),I=BigInt(s)**BigInt(N)%BigInt(n);_[w]=Number(I)|0}return _}let v=g(),k={add:(_,w)=>u((_|0)+(w|0))|0,sub:(_,w)=>u((_|0)-(w|0))|0,mul:(_,w)=>u((_|0)*(w|0))|0,inv:_=>{throw new Error("not implemented")}},b={N:r,roots:v,invertButterflies:!0,skipStages:a?1:0,brp:!1},M=Mr(k,{dit:!1,...b}),S=Mr(k,{dit:!0,...b});return{mod:u,smod:p,nttZetas:v,NTT:{encode:_=>M(_),decode:_=>{S(_);for(let w=0;w<_.length;w++)_[w]=u(o*_[w]);return _}},bitsCoder:(_,w)=>{let N=Dr(_),I=_*(r/8);return{bytesLen:I,encode:D=>{let V=new Uint8Array(I);for(let U=0,R=0,P=0,ae=0;U<D.length;U++)for(R|=(w.encode(D[U])&N)<<P,P+=_;P>=8;P-=8,R>>=8)V[ae++]=R&Dr(P);return V},decode:D=>{let V=e(r);for(let U=0,R=0,P=0,ae=0;U<D.length;U++)for(R|=D[U]<<P,P+=8;P>=_;P-=_,R>>=_)V[ae++]=w.decode(R&N);return V}}}}},os=t=>(e,r)=>{r||(r=t.blockLen);let n=new Uint8Array(e.length+2);n.set(e);let o=e.length,s=new Uint8Array(r),i=t.create({}),a=0,u=0;return{stats:()=>({calls:a,xofs:u}),get:(p,g)=>(n[o+0]=p,n[o+1]=g,i.destroy(),i=t.create({}).update(n),a++,()=>(u++,i.xofInto(s))),clean:()=>{i.destroy(),pe(s,n)}}},Dt=os(Qo),Bt=os(X)});var Kr={};on(Kr,{PARAMS:()=>qt,ml_dsa44:()=>ai,ml_dsa65:()=>ci,ml_dsa87:()=>ui});function is(t){Lr(t),t.externalMu!==void 0&&Uo(t.externalMu,"opts.externalMu")}function $t(t){let e=re(T);for(let r=0;r<T;){let n=t();if(n.length%3)throw new Error("RejNTTPoly: unaligned block");for(let o=0;r<T&&o<=n.length-3;o+=3){let s=(n[o+0]|n[o+1]<<8|n[o+2]<<16)&8388607;s<Ce&&(e[r++]=s)}}return e}function Fr(t){let{K:e,L:r,GAMMA1:n,GAMMA2:o,TAU:s,ETA:i,OMEGA:a}=t,{CRH_BYTES:u,TR_BYTES:p,C_TILDE_BYTES:g,XOF128:v,XOF256:k,securityLevel:b}=t;if(![2,4].includes(i))throw new Error("Wrong ETA");if(![1<<17,1<<19].includes(n))throw new Error("Wrong GAMMA1");if(![qr,Hr].includes(o))throw new Error("Wrong GAMMA2");let M=s*i,S=f=>{let h=Me(f),l=jt(h,2*o)|0;return h-l===Ce-1?{r1:0,r0:l-1|0}:{r1:Math.floor((h-l)/(2*o))|0,r0:l}},L=f=>S(f).r1,K=f=>S(f).r0,_=(f,h)=>f<=o||f>Ce-o||f===Ce-o&&h===0?0:1,w=(f,h)=>{let l=Math.floor((Ce-1)/(2*o)),{r1:m,r0:c}=S(h);return f===1?c>0?Me(m+1,l)|0:Me(m-1,l)|0:m|0},N=f=>{let h=Me(f),l=jt(h,2**Ue)|0;return{r1:Math.floor((h-l)/2**Ue)|0,r0:l}},I={bytesLen:a+e,encode:f=>{if(f===!1)throw new Error("hint.encode: hint is false");let h=new Uint8Array(a+e);for(let l=0,m=0;l<e;l++){for(let c=0;c<T;c++)f[l][c]!==0&&(h[m++]=c);h[a+l]=m}return h},decode:f=>{let h=[],l=0;for(let m=0;m<e;m++){let c=re(T);if(f[a+m]<l||f[a+m]>a)return!1;for(let A=l;A<f[a+m];A++){if(A>l&&f[A]<=f[A-1])return!1;c[f[A]]=1}l=f[a+m],h.push(c)}for(let m=l;m<a;m++)if(f[m]!==0)return!1;return h}},D=Xe(i===2?3:4,f=>i-f,f=>{if(!(-i<=f&&f<=i))throw new Error(`malformed key s1/s3 ${f} outside of ETA range [${-i}, ${i}]`);return f}),V=Xe(13,f=>(1<<Ue-1)-f),U=Xe(10),R=Xe(n===1<<17?18:20,f=>jt(n-f)),P=Xe(o===qr?6:4),ae=Ie(P,e),Te=ze("publicKey",32,Ie(U,e)),Pe=ze("secretKey",32,32,p,Ie(D,r),Ie(D,e),Ie(V,e)),Le=ze("signature",g,Ie(R,r),I),et=i===2?f=>f<15?2-f%5:!1:f=>f<9?4-f:!1;function Qr(f){let h=re(T);for(let l=0;l<T;){let m=f();for(let c=0;l<T&&c<m.length;c+=1){let A=et(m[c]&15),G=et(m[c]>>4&15);A!==!1&&(h[l++]=A),l<T&&G!==!1&&(h[l++]=G)}}return h}let zr=f=>{let h=re(T),l=X.create({}).update(f),m=new Uint8Array(X.blockLen);l.xofInto(m);let c=m.slice(0,8);for(let A=T-s,G=8,W=0,B=0;A<T;A++){let $=A+1;for(;$>A;)$=m[G++],!(G<X.blockLen)&&(l.xofInto(m),G=0);h[A]=h[$],h[$]=1-((c[W]>>B++&1)<<1),B>=8&&(W++,B=0)}return h},Xr=f=>{let h=re(T),l=re(T);for(let m=0;m<f.length;m++){let{r0:c,r1:A}=N(f[m]);h[m]=c,l[m]=A}return{r0:h,r1:l}},ls=(f,h)=>{for(let l=0;l<T;l++)f[l]=w(h[l],f[l]);return f},ps=(f,h)=>{let l=re(T),m=0;for(let c=0;c<T;c++){let A=_(f[c],h[c]);l[c]=A,m+=A}return{v:l,cnt:m}},Zr=32,en=ze("seed",32,64,32),se={info:{type:"internal-ml-dsa"},lengths:{secretKey:Pe.bytesLen,publicKey:Te.bytesLen,seed:32,signature:Le.bytesLen,signRand:Zr},keygen:f=>{let h=new Uint8Array(34),l=f===void 0;l&&(f=Ur(32)),O(f,32,"seed"),h.set(f),l&&pe(f),h[32]=e,h[33]=r;let[m,c,A]=en.decode(X(h,{dkLen:en.bytesLen})),G=k(c),W=[];for(let y=0;y<r;y++)W.push(Qr(G.get(y&255,y>>8&255)));let B=[];for(let y=r;y<r+e;y++)B.push(Qr(G.get(y&255,y>>8&255)));let $=W.map(y=>F.encode(y.slice())),j=[],J=[],ge=v(m),H=re(T);for(let y=0;y<e;y++){pe(H);for(let ee=0;ee<r;ee++){let ue=$t(ge.get(ee,y));Ee(H,Se(ue,$[ee]))}F.decode(H);let{r0:ne,r1:Z}=Xr(Ee(H,B[y]));j.push(ne),J.push(Z)}let ce=Te.encode([m,J]),me=X(ce,{dkLen:p}),De=Pe.encode([m,A,me,W,B,j]);return ge.clean(),G.clean(),pe(m,c,A,W,B,$,H,j,J,me,h),{publicKey:ce,secretKey:De}},getPublicKey:f=>{let[h,l,m,c,A,G]=Pe.decode(f),W=v(h),B=c.map(J=>F.encode(J.slice())),$=[],j=re(T);for(let J=0;J<e;J++){j.fill(0);for(let H=0;H<r;H++){let ce=$t(W.get(H,J));Ee(j,Se(ce,B[H]))}F.decode(j),Ee(j,A[J]);let{r1:ge}=Xr(j);$.push(ge)}return W.clean(),pe(j,B,G,c,A),Te.encode([h,$])},sign:(f,h,l={})=>{Lt(l),is(l);let{extraEntropy:m,externalMu:c=!1}=l,[A,G,W,B,$,j]=Pe.decode(h),J=[],ge=v(A);for(let y=0;y<e;y++){let ne=[];for(let Z=0;Z<r;Z++)ne.push($t(ge.get(Z,y)));J.push(ne)}ge.clean();for(let y=0;y<r;y++)F.encode(B[y]);for(let y=0;y<e;y++)F.encode($[y]),F.encode(j[y]);let H=c?f:X.create({dkLen:u}).update(W).update(f).digest(),ce=m===!1?new Uint8Array(32):m===void 0?Ur(Zr):m;O(ce,32,"extraEntropy");let me=X.create({dkLen:u}).update(G).update(ce).update(H).digest();O(me,u);let De=k(me,R.bytesLen);e:for(let y=0;;){let ne=[];for(let C=0;C<r;C++,y++)ne.push(R.decode(De.get(y&255,y>>8)()));let Z=ne.map(C=>F.encode(C.slice())),ee=[];for(let C=0;C<e;C++){let Fe=re(T);for(let _e=0;_e<r;_e++)Ee(Fe,Se(J[C][_e],Z[_e]));F.decode(Fe),ee.push(Fe)}let ue=ee.map(C=>C.map(L)),He=X.create({dkLen:g}).update(H).update(ae.encode(ue)).digest(),tt=F.encode(zr(He)),rt=B.map(C=>Se(C,tt));for(let C=0;C<r;C++)if(Ee(F.decode(rt[C]),ne[C]),Ze(rt[C],n-M))continue e;let tn=0,Ft=[];for(let C=0;C<e;C++){let Fe=F.decode(Se($[C],tt)),_e=cs(ee[C],Fe).map(K);if(Ze(_e,o-M))continue e;let rn=F.decode(Se(j[C],tt));if(Ze(rn,o))continue e;Ee(_e,rn);let nn=ps(_e,ue[C]);Ft.push(nn.v),tn+=nn.cnt}if(tn>a)continue;De.clean();let gs=Le.encode([He,rt,Ft]);return pe(He,rt,Ft,tt,ue,ee,Z,ne,me,H,B,$,j,...J),gs}throw new Error("Unreachable code path reached, report this error")},verify:(f,h,l,m={})=>{is(m);let{externalMu:c=!1}=m,[A,G]=Te.decode(l),W=X(l,{dkLen:p});if(f.length!==Le.bytesLen)return!1;let[B,$,j]=Le.decode(f);if(j===!1)return!1;for(let y=0;y<r;y++)if(Ze($[y],n-M))return!1;let J=c?h:X.create({dkLen:u}).update(W).update(h).digest(),ge=F.encode(zr(B)),H=$.map(y=>y.slice());for(let y=0;y<r;y++)F.encode(H[y]);let ce=[],me=v(A);for(let y=0;y<e;y++){let ne=Se(F.encode(ii(G[y])),ge),Z=re(T);for(let ue=0;ue<r;ue++){let He=$t(me.get(ue,y));Ee(Z,Se(He,H[ue]))}let ee=F.decode(cs(Z,ne));ce.push(ls(ee,j[y]))}me.clean();let De=X.create({dkLen:g}).update(J).update(ae.encode(ce)).digest();for(let y of j)if(!(y.reduce((Z,ee)=>Z+ee,0)<=a))return!1;for(let y of $)if(Ze(y,n-M))return!1;return Pr(B,De)}};return{info:{type:"ml-dsa"},internal:se,securityLevel:b,keygen:se.keygen,lengths:se.lengths,getPublicKey:se.getPublicKey,sign:(f,h,l={})=>{Lt(l);let m=Br(f,l.context),c=se.sign(m,h,l);return pe(m),c},verify:(f,h,l,m={})=>(Pt(m),se.verify(f,Br(h,m.context),l)),prehash:f=>(rs(f,b),{info:{type:"hashml-dsa"},securityLevel:b,lengths:se.lengths,keygen:se.keygen,getPublicKey:se.getPublicKey,sign:(h,l,m={})=>{Lt(m);let c=$r(f,h,m.context),A=se.sign(c,l,m);return pe(c),A},verify:(h,l,m,c={})=>(Pt(c),se.verify(h,$r(f,l,c.context),m))})}}var T,Ce,ni,oi,Ue,qr,Hr,qt,re,Me,jt,F,si,as,Xe,Ee,cs,ii,Ze,Se,ai,ci,ui,Vr=he(()=>{"use strict";d();Po();vr();ss();jr();T=256,Ce=8380417,ni=1753,oi=8347681,Ue=13,qr=Math.floor((Ce-1)/88)|0,Hr=Math.floor((Ce-1)/32)|0,qt={2:{K:4,L:4,D:Ue,GAMMA1:2**17,GAMMA2:qr,TAU:39,ETA:2,OMEGA:80},3:{K:6,L:5,D:Ue,GAMMA1:2**19,GAMMA2:Hr,TAU:49,ETA:4,OMEGA:55},5:{K:8,L:7,D:Ue,GAMMA1:2**19,GAMMA2:Hr,TAU:60,ETA:2,OMEGA:75}},re=t=>new Int32Array(t),{mod:Me,smod:jt,NTT:F,bitsCoder:si}=ns({N:T,Q:Ce,F:oi,ROOT_OF_UNITY:ni,newPoly:re,isKyber:!1,brvBits:8}),as=t=>t,Xe=(t,e=as,r=as)=>si(t,{encode:n=>e(r(n)),decode:n=>r(e(n))}),Ee=(t,e)=>{for(let r=0;r<t.length;r++)t[r]=Me(t[r]+e[r]);return t},cs=(t,e)=>{for(let r=0;r<t.length;r++)t[r]=Me(t[r]-e[r]);return t},ii=t=>{for(let e=0;e<T;e++)t[e]<<=Ue;return t},Ze=(t,e)=>{for(let r=0;r<T;r++)if(Math.abs(jt(t[r]))>=e)return!0;return!1},Se=(t,e)=>{let r=re(T);for(let n=0;n<t.length;n++)r[n]=Me(t[n]*e[n]);return r};ai=Fr({...qt[2],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:32,XOF128:Dt,XOF256:Bt,securityLevel:128}),ci=Fr({...qt[3],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:48,XOF128:Dt,XOF256:Bt,securityLevel:192}),ui=Fr({...qt[5],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:64,XOF128:Dt,XOF256:Bt,securityLevel:256})});var gi={};on(gi,{AUTHORITY_ERROR_CODES:()=>Co,AuditChain:()=>ct,AuditError:()=>at,COMPETITION_SCOPE_LEVEL:()=>gr,CONTRIBUTE_SCOPE_LEVEL:()=>pr,ClockDriftError:()=>Ke,CommitmentRecord:()=>Be,ConfidenceGate:()=>st,DEFAULT_LOA_POLICY:()=>Hn,DataCategory:()=>zt,FIRMWARE_MANIFEST_PATH:()=>Ro,FaultCode:()=>Xt,FederationSyncType:()=>nr,FirmwareIntegrityError:()=>Nt,GateError:()=>ye,HiTLGate:()=>it,KeyStore:()=>Et,LevelOfAssurance:()=>qn,M2MAuthError:()=>z,M2M_TRUSTED_ISSUER:()=>It,MLDSAKeyPair:()=>Ht,MediaEncoding:()=>ur,MessageType:()=>de,NodeClient:()=>Rt,OfflineModeManager:()=>kt,PRODUCTION_LOA_POLICY:()=>Fn,QoSAckTimeoutError:()=>xt,QoSLevel:()=>Yt,QoSManager:()=>wt,RCANAddressError:()=>ut,RCANConfigAuthorizationError:()=>ht,RCANDelegationChainError:()=>mt,RCANError:()=>Q,RCANGateError:()=>ft,RCANMessage:()=>E,RCANMessageError:()=>oe,RCANNodeError:()=>Ne,RCANNodeNotFoundError:()=>Re,RCANNodeSyncError:()=>Y,RCANNodeTrustError:()=>$e,RCANRegistryError:()=>ve,RCANReplayAttackError:()=>gt,RCANSignatureError:()=>lt,RCANValidationError:()=>dt,RCANVersionIncompatibleError:()=>pt,RCAN_VERSION:()=>pi,ROLE_JWT_LEVEL:()=>je,RRF_REVOCATION_CACHE_TTL_MS:()=>yr,RRF_REVOCATION_URL:()=>hr,RegistryClient:()=>yt,RegistryTier:()=>rr,ReplayCache:()=>At,RevocationCache:()=>Ve,RobotURI:()=>we,RobotURIError:()=>xe,Role:()=>be,SAFETY_MESSAGE_TYPE:()=>Wt,SCOPE_MIN_ROLE:()=>Zt,SDK_VERSION:()=>un,SPEC_VERSION:()=>q,TransportEncoding:()=>ir,TransportError:()=>ie,TrustAnchorCache:()=>vt,VERSION:()=>li,addDelegationHop:()=>ln,addMediaInline:()=>lr,addMediaRef:()=>no,addPQSignature:()=>ds,assertClockSynced:()=>On,authorityAccessFromWire:()=>Eo,authorityAccessToWire:()=>Ao,canonicalManifestJson:()=>wo,checkClockSync:()=>Qt,checkRevocation:()=>Un,decodeBleFrames:()=>eo,decodeCompact:()=>cr,decodeMinimal:()=>Xn,encodeBleFrames:()=>Zn,encodeCompact:()=>ar,encodeMinimal:()=>zn,extractIdentityFromJwt:()=>Vn,extractLoaFromJwt:()=>Ot,extractRoleFromJwt:()=>er,fetchCanonicalSchema:()=>_t,fetchRRFRevocations:()=>xr,isAuthorityRequestValid:()=>So,isM2mTrustedRevoked:()=>wr,isPreemptedBy:()=>lo,isSafetyMessage:()=>Sn,makeCloudRelayMessage:()=>fn,makeCompetitionEnter:()=>po,makeCompetitionScore:()=>go,makeConfigUpdate:()=>vn,makeConsentDeny:()=>Tt,makeConsentGrant:()=>Ct,makeConsentRequest:()=>St,makeContributeCancel:()=>uo,makeContributeRequest:()=>ao,makeContributeResult:()=>co,makeEstopMessage:()=>bn,makeEstopWithQoS:()=>wn,makeFaultReport:()=>jn,makeFederationSync:()=>Jn,makeKeyRotationMessage:()=>In,makePersonalResearchResult:()=>ho,makeResumeMessage:()=>En,makeRevocationBroadcast:()=>Pn,makeSeasonStanding:()=>mo,makeStopMessage:()=>An,makeStreamChunk:()=>io,makeTrainingConsentDeny:()=>Bn,makeTrainingConsentGrant:()=>Dn,makeTrainingConsentRequest:()=>Ln,makeTrainingDataMessage:()=>so,makeTransparencyMessage:()=>Tn,manifestFromWire:()=>xo,manifestToWire:()=>_o,parseM2mPeerToken:()=>ko,parseM2mTrustedToken:()=>Rr,roleFromJwtLevel:()=>Ge,selectTransport:()=>to,signMessage:()=>Yr,validateAuthorityAccess:()=>mr,validateCompetitionScope:()=>yo,validateConfig:()=>Rn,validateConfigAgainstSchema:()=>_n,validateConfigUpdate:()=>Nn,validateConsentMessage:()=>Mn,validateContributeScope:()=>fo,validateCrossRegistryCommand:()=>Yn,validateDelegationChain:()=>pn,validateLoaForScope:()=>Gn,validateManifest:()=>bo,validateMediaChunks:()=>oo,validateMessage:()=>yn,validateNodeAgainstSchema:()=>xn,validateReplay:()=>kn,validateRoleForScope:()=>tr,validateSafetyMessage:()=>Cn,validateTrainingDataMessage:()=>$n,validateURI:()=>hn,validateVersionCompat:()=>dn,verifyM2mTrustedToken:()=>Oo,verifyM2mTrustedTokenClaims:()=>_r,verifyMessage:()=>Wr,verifyPQSignature:()=>fs});d();d();var xe=class extends Error{constructor(e){super(e),this.name="RobotURIError"}},we=class t{registry;manufacturer;model;version;deviceId;constructor(e){this.registry=e.registry,this.manufacturer=e.manufacturer,this.model=e.model,this.version=e.version,this.deviceId=e.deviceId}static parse(e){if(!e.startsWith("rcan://"))throw new xe(`URI must start with 'rcan://' \u2014 got: ${e}`);let n=e.slice(7).split("/");if(n.length!==5)throw new xe(`URI must have exactly 5 path segments (registry/manufacturer/model/version/device-id) \u2014 got ${n.length} in: ${e}`);let[o,s,i,a,u]=n;for(let[p,g]of[["registry",o],["manufacturer",s],["model",i],["version",a],["device-id",u]])if(!g||g.trim()==="")throw new xe(`URI segment '${p}' must not be empty`);return new t({registry:o,manufacturer:s,model:i,version:a,deviceId:u})}static build(e){let r=e.registry??"registry.rcan.dev",{manufacturer:n,model:o,version:s,deviceId:i}=e;for(let[a,u]of[["manufacturer",n],["model",o],["version",s],["deviceId",i]])if(!u||u.trim()==="")throw new xe(`'${a}' must not be empty`);return new t({registry:r,manufacturer:n,model:o,version:s,deviceId:i})}toString(){return`rcan://${this.registry}/${this.manufacturer}/${this.model}/${this.version}/${this.deviceId}`}get namespace(){return`${this.manufacturer}/${this.model}`}get registryUrl(){return`https://${this.registry}/registry/${this.manufacturer}/${this.model}/${this.version}/${this.deviceId}`}equals(e){return this.toString()===e.toString()}toJSON(){return{uri:this.toString(),registry:this.registry,manufacturer:this.manufacturer,model:this.model,version:this.version,deviceId:this.deviceId}}};d();d();var q="2.2.0",un="1.2.1";function dn(t,e=q){let r=s=>{let i=s.split("."),a=parseInt(i[0]??"0",10),u=parseInt(i[1]??"0",10);return[isNaN(a)?0:a,isNaN(u)?0:u]},[n]=r(t),[o]=r(e);return n===o}var de=(c=>(c[c.COMMAND=1]="COMMAND",c[c.RESPONSE=2]="RESPONSE",c[c.STATUS=3]="STATUS",c[c.HEARTBEAT=4]="HEARTBEAT",c[c.CONFIG=5]="CONFIG",c[c.SAFETY=6]="SAFETY",c[c.AUTH=7]="AUTH",c[c.ERROR=8]="ERROR",c[c.DISCOVER=9]="DISCOVER",c[c.PENDING_AUTH=10]="PENDING_AUTH",c[c.INVOKE=11]="INVOKE",c[c.INVOKE_RESULT=12]="INVOKE_RESULT",c[c.INVOKE_CANCEL=13]="INVOKE_CANCEL",c[c.REGISTRY_REGISTER=14]="REGISTRY_REGISTER",c[c.REGISTRY_RESOLVE=15]="REGISTRY_RESOLVE",c[c.TRANSPARENCY=16]="TRANSPARENCY",c[c.COMMAND_ACK=17]="COMMAND_ACK",c[c.COMMAND_NACK=18]="COMMAND_NACK",c[c.ROBOT_REVOCATION=19]="ROBOT_REVOCATION",c[c.CONSENT_REQUEST=20]="CONSENT_REQUEST",c[c.CONSENT_GRANT=21]="CONSENT_GRANT",c[c.CONSENT_DENY=22]="CONSENT_DENY",c[c.FLEET_COMMAND=23]="FLEET_COMMAND",c[c.SUBSCRIBE=24]="SUBSCRIBE",c[c.UNSUBSCRIBE=25]="UNSUBSCRIBE",c[c.FAULT_REPORT=26]="FAULT_REPORT",c[c.KEY_ROTATION=27]="KEY_ROTATION",c[c.COMMAND_COMMIT=28]="COMMAND_COMMIT",c[c.SENSOR_DATA=29]="SENSOR_DATA",c[c.TRAINING_CONSENT_REQUEST=30]="TRAINING_CONSENT_REQUEST",c[c.TRAINING_CONSENT_GRANT=31]="TRAINING_CONSENT_GRANT",c[c.TRAINING_CONSENT_DENY=32]="TRAINING_CONSENT_DENY",c[c.CONTRIBUTE_REQUEST=33]="CONTRIBUTE_REQUEST",c[c.CONTRIBUTE_RESULT=34]="CONTRIBUTE_RESULT",c[c.CONTRIBUTE_CANCEL=35]="CONTRIBUTE_CANCEL",c[c.TRAINING_DATA=36]="TRAINING_DATA",c[c.COMPETITION_ENTER=37]="COMPETITION_ENTER",c[c.COMPETITION_SCORE=38]="COMPETITION_SCORE",c[c.SEASON_STANDING=39]="SEASON_STANDING",c[c.PERSONAL_RESEARCH_RESULT=40]="PERSONAL_RESEARCH_RESULT",c[c.AUTHORITY_ACCESS=41]="AUTHORITY_ACCESS",c[c.AUTHORITY_RESPONSE=42]="AUTHORITY_RESPONSE",c[c.FIRMWARE_ATTESTATION=43]="FIRMWARE_ATTESTATION",c[c.SBOM_UPDATE=44]="SBOM_UPDATE",c))(de||{}),oe=class extends Error{constructor(e){super(e),this.name="RCANMessageError"}},E=class t{rcan;rcanVersion;cmd;target;params;confidence;modelIdentity;signature;timestamp;senderType;cloudProvider;keyId;delegationChain;groupId;qos;presenceVerified;proximityMeters;readOnly;loa;transportEncoding;mediaChunks;firmwareHash;attestationRef;pqSig;constructor(e){if(!e.cmd||e.cmd.trim()==="")throw new oe("'cmd' is required");if(!e.target)throw new oe("'target' is required");if(this.rcan=e.rcan??q,this.rcanVersion=e.rcanVersion??q,this.cmd=e.cmd,this.target=e.target instanceof we?e.target.toString():String(e.target),this.params=e.params??{},this.confidence=e.confidence,this.modelIdentity=e.modelIdentity??e.model_identity,this.signature=e.signature,this.timestamp=e.timestamp??new Date().toISOString(),this.senderType=e.senderType,this.cloudProvider=e.cloudProvider,this.keyId=e.keyId,this.delegationChain=e.delegationChain,this.groupId=e.groupId,this.qos=e.qos,this.presenceVerified=e.presenceVerified,this.proximityMeters=e.proximityMeters,this.readOnly=e.readOnly,this.loa=e.loa,this.transportEncoding=e.transportEncoding,this.mediaChunks=e.mediaChunks,this.firmwareHash=e.firmwareHash,this.attestationRef=e.attestationRef,this.pqSig=e.pqSig,this.signature!==void 0&&this.signature.sig==="pending")throw new oe("signature.sig:'pending' is not valid in RCAN v2.1. Sign the message before sending.");if(this.confidence!==void 0&&(this.confidence<0||this.confidence>1))throw new oe(`confidence must be in [0.0, 1.0] \u2014 got ${this.confidence}`)}get isSigned(){return this.signature!==void 0&&this.signature.sig!==""}get isAiDriven(){return this.confidence!==void 0}toJSON(){let e={rcan:this.rcan,rcanVersion:this.rcanVersion,cmd:this.cmd,target:this.target,timestamp:this.timestamp};return Object.keys(this.params).length>0&&(e.params=this.params),this.confidence!==void 0&&(e.confidence=this.confidence),this.modelIdentity&&(e.model_identity=this.modelIdentity),this.signature&&(e.signature=this.signature),this.senderType!==void 0&&(e.senderType=this.senderType),this.cloudProvider!==void 0&&(e.cloudProvider=this.cloudProvider),this.keyId!==void 0&&(e.keyId=this.keyId),this.delegationChain!==void 0&&(e.delegationChain=this.delegationChain),this.groupId!==void 0&&(e.groupId=this.groupId),this.qos!==void 0&&(e.qos=this.qos),this.presenceVerified!==void 0&&(e.presenceVerified=this.presenceVerified),this.proximityMeters!==void 0&&(e.proximityMeters=this.proximityMeters),this.readOnly!==void 0&&(e.readOnly=this.readOnly),this.loa!==void 0&&(e.loa=this.loa),this.transportEncoding!==void 0&&(e.transportEncoding=this.transportEncoding),this.mediaChunks!==void 0&&(e.mediaChunks=this.mediaChunks),this.firmwareHash!==void 0&&(e.firmwareHash=this.firmwareHash),this.attestationRef!==void 0&&(e.attestationRef=this.attestationRef),e}toJSONString(e){return JSON.stringify(this.toJSON(),null,e)}static fromJSON(e){let r;if(typeof e=="string")try{r=JSON.parse(e)}catch{throw new oe("Invalid JSON string")}else r=e;if(!r.cmd)throw new oe("Missing required field: 'cmd'");if(!r.target)throw new oe("Missing required field: 'target'");if(!r.rcan)throw new oe("Missing required field: 'rcan'");return new t({rcan:r.rcan,rcanVersion:r.rcanVersion,cmd:r.cmd,target:r.target,params:r.params??{},confidence:r.confidence,modelIdentity:r.model_identity??r.modelIdentity,signature:r.signature,timestamp:r.timestamp,senderType:r.senderType,cloudProvider:r.cloudProvider,keyId:r.keyId,delegationChain:r.delegationChain,groupId:r.groupId,qos:r.qos,presenceVerified:r.presenceVerified,proximityMeters:r.proximityMeters,readOnly:r.readOnly,loa:r.loa,transportEncoding:r.transportEncoding,mediaChunks:r.mediaChunks,firmwareHash:r.firmwareHash,attestationRef:r.attestationRef,pqSig:r.pqSig})}};function fn(t,e){let r=t.toJSON();return r.senderType="cloud_function",r.cloudProvider=e,new E(r)}function ln(t,e){let r=t.delegationChain?[...t.delegationChain,e]:[e],n=t.toJSON();return n.delegationChain=r,new E(n)}function pn(t){if(t.length>4)return{valid:!1,reason:"DELEGATION_CHAIN_EXCEEDED: max depth is 4 hops"};for(let e=0;e<t.length;e++){let r=t[e];if(!r)return{valid:!1,reason:`hop ${e} is undefined`};if(!r.issuerRuri)return{valid:!1,reason:`hop ${e}: missing issuerRuri`};if(!r.humanSubject)return{valid:!1,reason:`hop ${e}: missing humanSubject`};if(!r.timestamp)return{valid:!1,reason:`hop ${e}: missing timestamp`};if(!r.scope)return{valid:!1,reason:`hop ${e}: missing scope`};if(!r.signature)return{valid:!1,reason:`hop ${e}: missing signature`}}return{valid:!0,reason:"ok"}}d();d();function ot(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{let{randomUUID:t}=ke("crypto");return t()}catch{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}}function Vt(t,e){return typeof process<"u",ws(t,e)}function Kt(t){let e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],r=1779033703,n=3144134277,o=1013904242,s=2773480762,i=1359893119,a=2600822924,u=528734635,p=1541459225,v=t.length*8,k=[...t];for(k.push(128);k.length%64!==56;)k.push(0);for(let S=7;S>=0;S--)k.push(v/Math.pow(2,S*8)&255);for(let S=0;S<k.length;S+=64){let L=[];for(let R=0;R<16;R++)L[R]=k[S+R*4]<<24|k[S+R*4+1]<<16|k[S+R*4+2]<<8|k[S+R*4+3];for(let R=16;R<64;R++){let P=fe(L[R-15],7)^fe(L[R-15],18)^L[R-15]>>>3,ae=fe(L[R-2],17)^fe(L[R-2],19)^L[R-2]>>>10;L[R]=L[R-16]+P+L[R-7]+ae>>>0}let[K,_,w,N,I,D,V,U]=[r,n,o,s,i,a,u,p];for(let R=0;R<64;R++){let P=fe(I,6)^fe(I,11)^fe(I,25),ae=I&D^~I&V,Te=U+P+ae+e[R]+L[R]>>>0,Pe=fe(K,2)^fe(K,13)^fe(K,22),Le=K&_^K&w^_&w,et=Pe+Le>>>0;[U,V,D,I,N,w,_,K]=[V,D,I,N+Te>>>0,w,_,K,Te+et>>>0]}r=r+K>>>0,n=n+_>>>0,o=o+w>>>0,s=s+N>>>0,i=i+I>>>0,a=a+D>>>0,u=u+V>>>0,p=p+U>>>0}let b=new Uint8Array(32),M=new DataView(b.buffer);return[r,n,o,s,i,a,u,p].forEach((S,L)=>M.setUint32(L*4,S)),b}function fe(t,e){return t>>>e|t<<32-e}function gn(t){if(typeof TextEncoder<"u")return new TextEncoder().encode(t);let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function xs(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function ws(t,e){let n=gn(t);n.length>64&&(n=Kt(n));let o=new Uint8Array(64),s=new Uint8Array(64);for(let g=0;g<64;g++)o[g]=(n[g]??0)^54,s[g]=(n[g]??0)^92;let i=gn(e),a=new Uint8Array(64+i.length);a.set(o),a.set(i,64);let u=Kt(a),p=new Uint8Array(96);return p.set(s),p.set(u,64),xs(Kt(p))}var ye=class extends Error{constructor(e){super(e),this.name="GateError"}},st=class{threshold;constructor(e=.8){if(e<0||e>1)throw new ye(`threshold must be in [0.0, 1.0] \u2014 got ${e}`);this.threshold=e}allows(e){return e>=this.threshold}margin(e){return e-this.threshold}assert(e,r){if(!this.allows(e)){let n=r?` for action '${r}'`:"";throw new ye(`Confidence ${e}${n} is below threshold ${this.threshold}`)}}},it=class{_pending=new Map;request(e,r={}){let n=ot();return this._pending.set(n,{token:n,action:e,context:r,createdAt:new Date().toISOString(),status:"pending"}),n}approve(e){let r=this._pending.get(e);if(!r)throw new ye(`Unknown token: ${e}`);r.status="approved"}deny(e,r){let n=this._pending.get(e);if(!n)throw new ye(`Unknown token: ${e}`);n.status="denied",r&&(n.reason=r)}check(e){let r=this._pending.get(e);if(!r)throw new ye(`Unknown token: ${e}`);return r.status}get pendingApprovals(){return Array.from(this._pending.values()).filter(e=>e.status==="pending")}getApproval(e){return this._pending.get(e)}clearResolved(){for(let[e,r]of this._pending.entries())r.status!=="pending"&&this._pending.delete(e)}};d();var at=class extends Error{constructor(e){super(e),this.name="AuditError"}};function bs(t,e,r,n,o){let s=JSON.stringify({recordId:t,action:e,robotUri:r,timestamp:n,params:o},Object.keys({recordId:t,action:e,robotUri:r,timestamp:n,params:o}).sort());return Vt("rcan-content-hash",s)}function mn(t,e){let{hmac:r,...n}=e,o=JSON.stringify(n,Object.keys(n).sort());return Vt(t,o)}var Be=class t{recordId;action;robotUri;confidence;modelIdentity;params;safetyApproved;timestamp;contentHash;previousHash;hmac;constructor(e){this.recordId=e.recordId,this.action=e.action,this.robotUri=e.robotUri,this.confidence=e.confidence,this.modelIdentity=e.modelIdentity,this.params=e.params,this.safetyApproved=e.safetyApproved,this.timestamp=e.timestamp,this.contentHash=e.contentHash,this.previousHash=e.previousHash,this.hmac=e.hmac}static create(e,r,n=null){let o=ot(),s=new Date().toISOString(),i=e.params??{},a=e.robotUri??"",u=bs(o,e.action,a,s,i),p={recordId:o,action:e.action,robotUri:a,confidence:e.confidence,modelIdentity:e.modelIdentity,params:i,safetyApproved:e.safetyApproved??!0,timestamp:s,contentHash:u,previousHash:n,hmac:""};return p.hmac=mn(r,p),new t(p)}verify(e){return mn(e,this.toJSON())===this.hmac}toJSON(){return{recordId:this.recordId,action:this.action,robotUri:this.robotUri,confidence:this.confidence,modelIdentity:this.modelIdentity,params:this.params,safetyApproved:this.safetyApproved,timestamp:this.timestamp,contentHash:this.contentHash,previousHash:this.previousHash,hmac:this.hmac}}static fromJSON(e){return new t(e)}},ct=class t{_records=[];_secret;constructor(e){this._secret=e}get records(){return this._records}append(e){let n=this._records[this._records.length-1]?.contentHash??null,o=Be.create(e,this._secret,n);return this._records.push(o),o}verifyAll(){let e=[],r=null;for(let n of this._records)n.verify(this._secret)||e.push(`HMAC invalid for record ${n.recordId.slice(0,8)}`),r!==null&&n.previousHash!==r&&e.push(`Chain broken at ${n.recordId.slice(0,8)}: expected prev=${r.slice(0,12)}`),r=n.contentHash;return{valid:e.length===0,count:this._records.length,errors:e}}toJSONL(){return this._records.map(e=>JSON.stringify(e.toJSON())).join(`
|
|
1
|
+
"use strict";var RCAN=(()=>{var ms=Object.create;var nt=Object.defineProperty;var hs=Object.getOwnPropertyDescriptor;var ys=Object.getOwnPropertyNames;var Rs=Object.getPrototypeOf,_s=Object.prototype.hasOwnProperty;var ke=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var he=(t,e)=>()=>(t&&(e=t(t=0)),e);var on=(t,e)=>{for(var r in e)nt(t,r,{get:e[r],enumerable:!0})},sn=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ys(e))!_s.call(t,o)&&o!==r&&nt(t,o,{get:()=>e[o],enumerable:!(n=hs(e,o))||n.enumerable});return t};var an=(t,e,r)=>(r=t!=null?ms(Rs(t)):{},sn(e||!t||!t.__esModule?nt(r,"default",{value:t,enumerable:!0}):r,t)),cn=t=>sn(nt({},"__esModule",{value:!0}),t);var d=he(()=>{});function br(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ar(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function O(t,e,r=""){let n=br(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",u=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+u)}return t}function Er(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vo(t,e){O(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function No(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Sr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Vs(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Gs(t){for(let e=0;e<t.length;e++)t[e]=Vs(t[e]);return t}function Tr(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];O(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function Io(t,e={}){let r=(o,s)=>t(s).update(o).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=o=>t(o),Object.assign(r,e),Object.freeze(r)}function Mo(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var Ks,Cr,kr,Mt=he(()=>{"use strict";d();Ks=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Cr=Ks?t=>t:Gs;kr=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});function Uo(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}var Po=he(()=>{"use strict";d();});function Js(t,e=!1){return e?{h:Number(t&Ut),l:Number(t>>Lo&Ut)}:{h:Number(t>>Lo&Ut)|0,l:Number(t&Ut)|0}}function Do(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Js(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ut,Lo,Bo,$o,jo,qo,Ho=he(()=>{"use strict";d();Ut=BigInt(4294967295),Lo=BigInt(32);Bo=(t,e,r)=>t<<r|e>>>32-r,$o=(t,e,r)=>e<<r|t>>>32-r,jo=(t,e,r)=>e<<r-32|t>>>64-r,qo=(t,e,r)=>t<<r-32|e>>>64-r});function ti(t,e=24){let r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let i=0;i<10;i++)r[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let a=(i+8)%10,u=(i+2)%10,p=r[u],g=r[u+1],v=Fo(p,g,1)^r[a],k=Ko(p,g,1)^r[a+1];for(let b=0;b<50;b+=10)t[i+b]^=v,t[i+b+1]^=k}let o=t[2],s=t[3];for(let i=0;i<24;i++){let a=Go[i],u=Fo(o,s,a),p=Ko(o,s,a),g=Vo[i];o=t[g],s=t[g+1],t[g]=u,t[g+1]=p}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=t[i+a];for(let a=0;a<10;a++)t[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=Zs[n],t[1]^=ei[n]}Sr(r)}var Ys,Qe,Ws,Qs,zs,Xs,Vo,Go,Jo,Yo,Zs,ei,Fo,Ko,Or,Wo,Qo,X,vr=he(()=>{"use strict";d();Ho();Mt();Ys=BigInt(0),Qe=BigInt(1),Ws=BigInt(2),Qs=BigInt(7),zs=BigInt(256),Xs=BigInt(113),Vo=[],Go=[],Jo=[];for(let t=0,e=Qe,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Vo.push(2*(5*n+r)),Go.push((t+1)*(t+2)/2%64);let o=Ys;for(let s=0;s<7;s++)e=(e<<Qe^(e>>Qs)*Xs)%zs,e&Ws&&(o^=Qe<<(Qe<<BigInt(s))-Qe);Jo.push(o)}Yo=Do(Jo,!0),Zs=Yo[0],ei=Yo[1],Fo=(t,e,r)=>r>32?jo(t,e,r):Bo(t,e,r),Ko=(t,e,r)=>r>32?qo(t,e,r):$o(t,e,r);Or=class t{state;pos=0;posOut=0;finished=!1;state32;destroyed=!1;blockLen;suffix;outputLen;enableXOF=!1;rounds;constructor(e,r,n,o=!1,s=24){if(this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=o,this.rounds=s,Ar(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=No(this.state)}clone(){return this._cloneInto()}keccak(){Cr(this.state32),ti(this.state32,this.rounds),Cr(this.state32),this.posOut=0,this.pos=0}update(e){Er(this),O(e);let{blockLen:r,state:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);for(let a=0;a<i;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:r,pos:n,blockLen:o}=this;e[n]^=r,(r&128)!==0&&n===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){Er(this,!1),O(e),this.finish();let r=this.state,{blockLen:n}=this;for(let o=0,s=e.length;o<s;){this.posOut>=n&&this.keccak();let i=Math.min(n-this.posOut,s-o);e.set(r.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ar(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(vo(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=!0,Sr(this.state)}_cloneInto(e){let{blockLen:r,suffix:n,outputLen:o,rounds:s,enableXOF:i}=this;return e||=new t(r,n,o,i,s),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}},Wo=(t,e,r,n={})=>Io((o={})=>new Or(e,t,o.dkLen===void 0?r:o.dkLen,!0),n),Qo=Wo(31,168,16,kr(11)),X=Wo(31,136,32,kr(12))});function Nr(t){if(!Number.isSafeInteger(t)||t<0||t>4294967295)throw new Error("wrong u32 integer:"+t);return t}function Xo(t){return Nr(t),(t&t-1)===0&&t!==0}function Ir(t,e){Nr(t);let r=0;for(let n=0;n<e;n++,t>>>=1)r=r<<1|t&1;return r}function Zo(t){return Nr(t),31-Math.clz32(t)}function zo(t){let e=t.length;if(e<2||!Xo(e))throw new Error("n must be a power of 2 and greater than 1. Got "+e);let r=Zo(e);for(let n=0;n<e;n++){let o=Ir(n,r);if(n<o){let s=t[n];t[n]=t[o],t[o]=s}}return t}var Mr,es=he(()=>{"use strict";d();Mr=(t,e)=>{let{N:r,roots:n,dit:o,invertButterflies:s=!1,skipStages:i=0,brp:a=!0}=e,u=Zo(r);if(!Xo(r))throw new Error("FFT: Polynomial size should be power of two");let p=o!==s;return g=>{if(g.length!==r)throw new Error("FFT: wrong Polynomial length");o&&a&&zo(g);for(let v=0,k=1;v<u-i;v++){let b=o?v+1+i:u-v,M=1<<b,S=M>>1,L=r>>b;for(let K=0;K<r;K+=M)for(let _=0,w=k++;_<S;_++){let N=s?o?r-w:w:_*L,I=K+_,D=K+_+S,V=n[N],U=g[D],R=g[I];if(p){let P=t.mul(U,V);g[I]=t.add(R,P),g[D]=t.sub(R,P)}else s?(g[I]=t.add(U,R),g[D]=t.mul(t.sub(U,R),V)):(g[I]=t.add(R,U),g[D]=t.mul(t.sub(R,U),V))}}return!o&&a&&zo(g),g}}});function Pr(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Lr(t){if(typeof t!="object"||t===null||br(t))throw new Error("expected opts to be an object")}function Pt(t){Lr(t),t.context!==void 0&&O(t.context,void 0,"opts.context")}function Lt(t){Pt(t),t.extraEntropy!==!1&&t.extraEntropy!==void 0&&O(t.extraEntropy,void 0,"opts.extraEntropy")}function ze(t,...e){let r=o=>typeof o=="number"?o:o.bytesLen,n=e.reduce((o,s)=>o+r(s),0);return{bytesLen:n,encode:o=>{let s=new Uint8Array(n);for(let i=0,a=0;i<e.length;i++){let u=e[i],p=r(u),g=typeof u=="number"?o[i]:u.encode(o[i]);O(g,p,t),s.set(g,a),typeof u!="number"&&g.fill(0),a+=p}return s},decode:o=>{O(o,n,t);let s=[];for(let i of e){let a=r(i),u=o.subarray(0,a);s.push(typeof i=="number"?u:i.decode(u)),o=o.subarray(a)}return s}}}function Ie(t,e){let r=e*t.bytesLen;return{bytesLen:r,encode:n=>{if(n.length!==e)throw new Error(`vecCoder.encode: wrong length=${n.length}. Expected: ${e}`);let o=new Uint8Array(r);for(let s=0,i=0;s<n.length;s++){let a=t.encode(n[s]);o.set(a,i),a.fill(0),i+=a.length}return o},decode:n=>{O(n,r);let o=[];for(let s=0;s<n.length;s+=t.bytesLen)o.push(t.decode(n.subarray(s,s+t.bytesLen)));return o}}}function pe(...t){for(let e of t)if(Array.isArray(e))for(let r of e)r.fill(0);else e.fill(0)}function Dr(t){return(1<<t)-1}function Br(t,e=ts){if(O(t),O(e),e.length>255)throw new Error("context should be less than 255 bytes");return Tr(new Uint8Array([0,e.length]),e,t)}function rs(t,e=0){if(!t.oid||!Pr(t.oid.subarray(0,10),ri))throw new Error("hash.oid is invalid: expected NIST hash");let r=t.outputLen*8/2;if(e>r)throw new Error("Pre-hash security strength too low: "+r+", required: "+e)}function $r(t,e,r=ts){if(O(e),O(r),r.length>255)throw new Error("context should be less than 255 bytes");let n=t(e);return Tr(new Uint8Array([1,r.length]),r,t.oid,n)}var Ur,ts,ri,jr=he(()=>{"use strict";d();Mt();Mt();Ur=Mo;ts=Uint8Array.of();ri=Uint8Array.from([6,9,96,134,72,1,101,3,4,2])});var ns,os,Dt,Bt,ss=he(()=>{"use strict";d();es();vr();jr();ns=t=>{let{newPoly:e,N:r,Q:n,F:o,ROOT_OF_UNITY:s,brvBits:i,isKyber:a}=t,u=(_,w=n)=>{let N=_%w|0;return(N>=0?N|0:w+N|0)|0},p=(_,w=n)=>{let N=u(_,w)|0;return(N>w>>1?N-w|0:N)|0};function g(){let _=e(r);for(let w=0;w<r;w++){let N=Ir(w,i),I=BigInt(s)**BigInt(N)%BigInt(n);_[w]=Number(I)|0}return _}let v=g(),k={add:(_,w)=>u((_|0)+(w|0))|0,sub:(_,w)=>u((_|0)-(w|0))|0,mul:(_,w)=>u((_|0)*(w|0))|0,inv:_=>{throw new Error("not implemented")}},b={N:r,roots:v,invertButterflies:!0,skipStages:a?1:0,brp:!1},M=Mr(k,{dit:!1,...b}),S=Mr(k,{dit:!0,...b});return{mod:u,smod:p,nttZetas:v,NTT:{encode:_=>M(_),decode:_=>{S(_);for(let w=0;w<_.length;w++)_[w]=u(o*_[w]);return _}},bitsCoder:(_,w)=>{let N=Dr(_),I=_*(r/8);return{bytesLen:I,encode:D=>{let V=new Uint8Array(I);for(let U=0,R=0,P=0,ae=0;U<D.length;U++)for(R|=(w.encode(D[U])&N)<<P,P+=_;P>=8;P-=8,R>>=8)V[ae++]=R&Dr(P);return V},decode:D=>{let V=e(r);for(let U=0,R=0,P=0,ae=0;U<D.length;U++)for(R|=D[U]<<P,P+=8;P>=_;P-=_,R>>=_)V[ae++]=w.decode(R&N);return V}}}}},os=t=>(e,r)=>{r||(r=t.blockLen);let n=new Uint8Array(e.length+2);n.set(e);let o=e.length,s=new Uint8Array(r),i=t.create({}),a=0,u=0;return{stats:()=>({calls:a,xofs:u}),get:(p,g)=>(n[o+0]=p,n[o+1]=g,i.destroy(),i=t.create({}).update(n),a++,()=>(u++,i.xofInto(s))),clean:()=>{i.destroy(),pe(s,n)}}},Dt=os(Qo),Bt=os(X)});var Kr={};on(Kr,{PARAMS:()=>qt,ml_dsa44:()=>ai,ml_dsa65:()=>ci,ml_dsa87:()=>ui});function is(t){Lr(t),t.externalMu!==void 0&&Uo(t.externalMu,"opts.externalMu")}function $t(t){let e=re(T);for(let r=0;r<T;){let n=t();if(n.length%3)throw new Error("RejNTTPoly: unaligned block");for(let o=0;r<T&&o<=n.length-3;o+=3){let s=(n[o+0]|n[o+1]<<8|n[o+2]<<16)&8388607;s<Ce&&(e[r++]=s)}}return e}function Fr(t){let{K:e,L:r,GAMMA1:n,GAMMA2:o,TAU:s,ETA:i,OMEGA:a}=t,{CRH_BYTES:u,TR_BYTES:p,C_TILDE_BYTES:g,XOF128:v,XOF256:k,securityLevel:b}=t;if(![2,4].includes(i))throw new Error("Wrong ETA");if(![1<<17,1<<19].includes(n))throw new Error("Wrong GAMMA1");if(![qr,Hr].includes(o))throw new Error("Wrong GAMMA2");let M=s*i,S=f=>{let h=Me(f),l=jt(h,2*o)|0;return h-l===Ce-1?{r1:0,r0:l-1|0}:{r1:Math.floor((h-l)/(2*o))|0,r0:l}},L=f=>S(f).r1,K=f=>S(f).r0,_=(f,h)=>f<=o||f>Ce-o||f===Ce-o&&h===0?0:1,w=(f,h)=>{let l=Math.floor((Ce-1)/(2*o)),{r1:m,r0:c}=S(h);return f===1?c>0?Me(m+1,l)|0:Me(m-1,l)|0:m|0},N=f=>{let h=Me(f),l=jt(h,2**Ue)|0;return{r1:Math.floor((h-l)/2**Ue)|0,r0:l}},I={bytesLen:a+e,encode:f=>{if(f===!1)throw new Error("hint.encode: hint is false");let h=new Uint8Array(a+e);for(let l=0,m=0;l<e;l++){for(let c=0;c<T;c++)f[l][c]!==0&&(h[m++]=c);h[a+l]=m}return h},decode:f=>{let h=[],l=0;for(let m=0;m<e;m++){let c=re(T);if(f[a+m]<l||f[a+m]>a)return!1;for(let A=l;A<f[a+m];A++){if(A>l&&f[A]<=f[A-1])return!1;c[f[A]]=1}l=f[a+m],h.push(c)}for(let m=l;m<a;m++)if(f[m]!==0)return!1;return h}},D=Xe(i===2?3:4,f=>i-f,f=>{if(!(-i<=f&&f<=i))throw new Error(`malformed key s1/s3 ${f} outside of ETA range [${-i}, ${i}]`);return f}),V=Xe(13,f=>(1<<Ue-1)-f),U=Xe(10),R=Xe(n===1<<17?18:20,f=>jt(n-f)),P=Xe(o===qr?6:4),ae=Ie(P,e),Te=ze("publicKey",32,Ie(U,e)),Pe=ze("secretKey",32,32,p,Ie(D,r),Ie(D,e),Ie(V,e)),Le=ze("signature",g,Ie(R,r),I),et=i===2?f=>f<15?2-f%5:!1:f=>f<9?4-f:!1;function Qr(f){let h=re(T);for(let l=0;l<T;){let m=f();for(let c=0;l<T&&c<m.length;c+=1){let A=et(m[c]&15),G=et(m[c]>>4&15);A!==!1&&(h[l++]=A),l<T&&G!==!1&&(h[l++]=G)}}return h}let zr=f=>{let h=re(T),l=X.create({}).update(f),m=new Uint8Array(X.blockLen);l.xofInto(m);let c=m.slice(0,8);for(let A=T-s,G=8,W=0,B=0;A<T;A++){let $=A+1;for(;$>A;)$=m[G++],!(G<X.blockLen)&&(l.xofInto(m),G=0);h[A]=h[$],h[$]=1-((c[W]>>B++&1)<<1),B>=8&&(W++,B=0)}return h},Xr=f=>{let h=re(T),l=re(T);for(let m=0;m<f.length;m++){let{r0:c,r1:A}=N(f[m]);h[m]=c,l[m]=A}return{r0:h,r1:l}},ls=(f,h)=>{for(let l=0;l<T;l++)f[l]=w(h[l],f[l]);return f},ps=(f,h)=>{let l=re(T),m=0;for(let c=0;c<T;c++){let A=_(f[c],h[c]);l[c]=A,m+=A}return{v:l,cnt:m}},Zr=32,en=ze("seed",32,64,32),se={info:{type:"internal-ml-dsa"},lengths:{secretKey:Pe.bytesLen,publicKey:Te.bytesLen,seed:32,signature:Le.bytesLen,signRand:Zr},keygen:f=>{let h=new Uint8Array(34),l=f===void 0;l&&(f=Ur(32)),O(f,32,"seed"),h.set(f),l&&pe(f),h[32]=e,h[33]=r;let[m,c,A]=en.decode(X(h,{dkLen:en.bytesLen})),G=k(c),W=[];for(let y=0;y<r;y++)W.push(Qr(G.get(y&255,y>>8&255)));let B=[];for(let y=r;y<r+e;y++)B.push(Qr(G.get(y&255,y>>8&255)));let $=W.map(y=>F.encode(y.slice())),j=[],J=[],ge=v(m),H=re(T);for(let y=0;y<e;y++){pe(H);for(let ee=0;ee<r;ee++){let ue=$t(ge.get(ee,y));Ee(H,Se(ue,$[ee]))}F.decode(H);let{r0:ne,r1:Z}=Xr(Ee(H,B[y]));j.push(ne),J.push(Z)}let ce=Te.encode([m,J]),me=X(ce,{dkLen:p}),De=Pe.encode([m,A,me,W,B,j]);return ge.clean(),G.clean(),pe(m,c,A,W,B,$,H,j,J,me,h),{publicKey:ce,secretKey:De}},getPublicKey:f=>{let[h,l,m,c,A,G]=Pe.decode(f),W=v(h),B=c.map(J=>F.encode(J.slice())),$=[],j=re(T);for(let J=0;J<e;J++){j.fill(0);for(let H=0;H<r;H++){let ce=$t(W.get(H,J));Ee(j,Se(ce,B[H]))}F.decode(j),Ee(j,A[J]);let{r1:ge}=Xr(j);$.push(ge)}return W.clean(),pe(j,B,G,c,A),Te.encode([h,$])},sign:(f,h,l={})=>{Lt(l),is(l);let{extraEntropy:m,externalMu:c=!1}=l,[A,G,W,B,$,j]=Pe.decode(h),J=[],ge=v(A);for(let y=0;y<e;y++){let ne=[];for(let Z=0;Z<r;Z++)ne.push($t(ge.get(Z,y)));J.push(ne)}ge.clean();for(let y=0;y<r;y++)F.encode(B[y]);for(let y=0;y<e;y++)F.encode($[y]),F.encode(j[y]);let H=c?f:X.create({dkLen:u}).update(W).update(f).digest(),ce=m===!1?new Uint8Array(32):m===void 0?Ur(Zr):m;O(ce,32,"extraEntropy");let me=X.create({dkLen:u}).update(G).update(ce).update(H).digest();O(me,u);let De=k(me,R.bytesLen);e:for(let y=0;;){let ne=[];for(let C=0;C<r;C++,y++)ne.push(R.decode(De.get(y&255,y>>8)()));let Z=ne.map(C=>F.encode(C.slice())),ee=[];for(let C=0;C<e;C++){let Fe=re(T);for(let _e=0;_e<r;_e++)Ee(Fe,Se(J[C][_e],Z[_e]));F.decode(Fe),ee.push(Fe)}let ue=ee.map(C=>C.map(L)),He=X.create({dkLen:g}).update(H).update(ae.encode(ue)).digest(),tt=F.encode(zr(He)),rt=B.map(C=>Se(C,tt));for(let C=0;C<r;C++)if(Ee(F.decode(rt[C]),ne[C]),Ze(rt[C],n-M))continue e;let tn=0,Ft=[];for(let C=0;C<e;C++){let Fe=F.decode(Se($[C],tt)),_e=cs(ee[C],Fe).map(K);if(Ze(_e,o-M))continue e;let rn=F.decode(Se(j[C],tt));if(Ze(rn,o))continue e;Ee(_e,rn);let nn=ps(_e,ue[C]);Ft.push(nn.v),tn+=nn.cnt}if(tn>a)continue;De.clean();let gs=Le.encode([He,rt,Ft]);return pe(He,rt,Ft,tt,ue,ee,Z,ne,me,H,B,$,j,...J),gs}throw new Error("Unreachable code path reached, report this error")},verify:(f,h,l,m={})=>{is(m);let{externalMu:c=!1}=m,[A,G]=Te.decode(l),W=X(l,{dkLen:p});if(f.length!==Le.bytesLen)return!1;let[B,$,j]=Le.decode(f);if(j===!1)return!1;for(let y=0;y<r;y++)if(Ze($[y],n-M))return!1;let J=c?h:X.create({dkLen:u}).update(W).update(h).digest(),ge=F.encode(zr(B)),H=$.map(y=>y.slice());for(let y=0;y<r;y++)F.encode(H[y]);let ce=[],me=v(A);for(let y=0;y<e;y++){let ne=Se(F.encode(ii(G[y])),ge),Z=re(T);for(let ue=0;ue<r;ue++){let He=$t(me.get(ue,y));Ee(Z,Se(He,H[ue]))}let ee=F.decode(cs(Z,ne));ce.push(ls(ee,j[y]))}me.clean();let De=X.create({dkLen:g}).update(J).update(ae.encode(ce)).digest();for(let y of j)if(!(y.reduce((Z,ee)=>Z+ee,0)<=a))return!1;for(let y of $)if(Ze(y,n-M))return!1;return Pr(B,De)}};return{info:{type:"ml-dsa"},internal:se,securityLevel:b,keygen:se.keygen,lengths:se.lengths,getPublicKey:se.getPublicKey,sign:(f,h,l={})=>{Lt(l);let m=Br(f,l.context),c=se.sign(m,h,l);return pe(m),c},verify:(f,h,l,m={})=>(Pt(m),se.verify(f,Br(h,m.context),l)),prehash:f=>(rs(f,b),{info:{type:"hashml-dsa"},securityLevel:b,lengths:se.lengths,keygen:se.keygen,getPublicKey:se.getPublicKey,sign:(h,l,m={})=>{Lt(m);let c=$r(f,h,m.context),A=se.sign(c,l,m);return pe(c),A},verify:(h,l,m,c={})=>(Pt(c),se.verify(h,$r(f,l,c.context),m))})}}var T,Ce,ni,oi,Ue,qr,Hr,qt,re,Me,jt,F,si,as,Xe,Ee,cs,ii,Ze,Se,ai,ci,ui,Vr=he(()=>{"use strict";d();Po();vr();ss();jr();T=256,Ce=8380417,ni=1753,oi=8347681,Ue=13,qr=Math.floor((Ce-1)/88)|0,Hr=Math.floor((Ce-1)/32)|0,qt={2:{K:4,L:4,D:Ue,GAMMA1:2**17,GAMMA2:qr,TAU:39,ETA:2,OMEGA:80},3:{K:6,L:5,D:Ue,GAMMA1:2**19,GAMMA2:Hr,TAU:49,ETA:4,OMEGA:55},5:{K:8,L:7,D:Ue,GAMMA1:2**19,GAMMA2:Hr,TAU:60,ETA:2,OMEGA:75}},re=t=>new Int32Array(t),{mod:Me,smod:jt,NTT:F,bitsCoder:si}=ns({N:T,Q:Ce,F:oi,ROOT_OF_UNITY:ni,newPoly:re,isKyber:!1,brvBits:8}),as=t=>t,Xe=(t,e=as,r=as)=>si(t,{encode:n=>e(r(n)),decode:n=>r(e(n))}),Ee=(t,e)=>{for(let r=0;r<t.length;r++)t[r]=Me(t[r]+e[r]);return t},cs=(t,e)=>{for(let r=0;r<t.length;r++)t[r]=Me(t[r]-e[r]);return t},ii=t=>{for(let e=0;e<T;e++)t[e]<<=Ue;return t},Ze=(t,e)=>{for(let r=0;r<T;r++)if(Math.abs(jt(t[r]))>=e)return!0;return!1},Se=(t,e)=>{let r=re(T);for(let n=0;n<t.length;n++)r[n]=Me(t[n]*e[n]);return r};ai=Fr({...qt[2],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:32,XOF128:Dt,XOF256:Bt,securityLevel:128}),ci=Fr({...qt[3],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:48,XOF128:Dt,XOF256:Bt,securityLevel:192}),ui=Fr({...qt[5],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:64,XOF128:Dt,XOF256:Bt,securityLevel:256})});var gi={};on(gi,{AUTHORITY_ERROR_CODES:()=>Co,AuditChain:()=>ct,AuditError:()=>at,COMPETITION_SCOPE_LEVEL:()=>gr,CONTRIBUTE_SCOPE_LEVEL:()=>pr,ClockDriftError:()=>Ke,CommitmentRecord:()=>Be,ConfidenceGate:()=>st,DEFAULT_LOA_POLICY:()=>Hn,DataCategory:()=>zt,FIRMWARE_MANIFEST_PATH:()=>Ro,FaultCode:()=>Xt,FederationSyncType:()=>nr,FirmwareIntegrityError:()=>Nt,GateError:()=>ye,HiTLGate:()=>it,KeyStore:()=>Et,LevelOfAssurance:()=>qn,M2MAuthError:()=>z,M2M_TRUSTED_ISSUER:()=>It,MLDSAKeyPair:()=>Ht,MediaEncoding:()=>ur,MessageType:()=>de,NodeClient:()=>Rt,OfflineModeManager:()=>kt,PRODUCTION_LOA_POLICY:()=>Fn,QoSAckTimeoutError:()=>xt,QoSLevel:()=>Yt,QoSManager:()=>wt,RCANAddressError:()=>ut,RCANConfigAuthorizationError:()=>ht,RCANDelegationChainError:()=>mt,RCANError:()=>Q,RCANGateError:()=>ft,RCANMessage:()=>E,RCANMessageError:()=>oe,RCANNodeError:()=>Ne,RCANNodeNotFoundError:()=>Re,RCANNodeSyncError:()=>Y,RCANNodeTrustError:()=>$e,RCANRegistryError:()=>ve,RCANReplayAttackError:()=>gt,RCANSignatureError:()=>lt,RCANValidationError:()=>dt,RCANVersionIncompatibleError:()=>pt,RCAN_VERSION:()=>pi,ROLE_JWT_LEVEL:()=>je,RRF_REVOCATION_CACHE_TTL_MS:()=>yr,RRF_REVOCATION_URL:()=>hr,RegistryClient:()=>yt,RegistryTier:()=>rr,ReplayCache:()=>At,RevocationCache:()=>Ve,RobotURI:()=>we,RobotURIError:()=>xe,Role:()=>be,SAFETY_MESSAGE_TYPE:()=>Wt,SCOPE_MIN_ROLE:()=>Zt,SDK_VERSION:()=>un,SPEC_VERSION:()=>q,TransportEncoding:()=>ir,TransportError:()=>ie,TrustAnchorCache:()=>vt,VERSION:()=>li,addDelegationHop:()=>ln,addMediaInline:()=>lr,addMediaRef:()=>no,addPQSignature:()=>ds,assertClockSynced:()=>On,authorityAccessFromWire:()=>Eo,authorityAccessToWire:()=>Ao,canonicalManifestJson:()=>wo,checkClockSync:()=>Qt,checkRevocation:()=>Un,decodeBleFrames:()=>eo,decodeCompact:()=>cr,decodeMinimal:()=>Xn,encodeBleFrames:()=>Zn,encodeCompact:()=>ar,encodeMinimal:()=>zn,extractIdentityFromJwt:()=>Vn,extractLoaFromJwt:()=>Ot,extractRoleFromJwt:()=>er,fetchCanonicalSchema:()=>_t,fetchRRFRevocations:()=>xr,isAuthorityRequestValid:()=>So,isM2mTrustedRevoked:()=>wr,isPreemptedBy:()=>lo,isSafetyMessage:()=>Sn,makeCloudRelayMessage:()=>fn,makeCompetitionEnter:()=>po,makeCompetitionScore:()=>go,makeConfigUpdate:()=>vn,makeConsentDeny:()=>Tt,makeConsentGrant:()=>Ct,makeConsentRequest:()=>St,makeContributeCancel:()=>uo,makeContributeRequest:()=>ao,makeContributeResult:()=>co,makeEstopMessage:()=>bn,makeEstopWithQoS:()=>wn,makeFaultReport:()=>jn,makeFederationSync:()=>Jn,makeKeyRotationMessage:()=>In,makePersonalResearchResult:()=>ho,makeResumeMessage:()=>En,makeRevocationBroadcast:()=>Pn,makeSeasonStanding:()=>mo,makeStopMessage:()=>An,makeStreamChunk:()=>io,makeTrainingConsentDeny:()=>Bn,makeTrainingConsentGrant:()=>Dn,makeTrainingConsentRequest:()=>Ln,makeTrainingDataMessage:()=>so,makeTransparencyMessage:()=>Tn,manifestFromWire:()=>xo,manifestToWire:()=>_o,parseM2mPeerToken:()=>ko,parseM2mTrustedToken:()=>Rr,roleFromJwtLevel:()=>Ge,selectTransport:()=>to,signMessage:()=>Yr,validateAuthorityAccess:()=>mr,validateCompetitionScope:()=>yo,validateConfig:()=>Rn,validateConfigAgainstSchema:()=>_n,validateConfigUpdate:()=>Nn,validateConsentMessage:()=>Mn,validateContributeScope:()=>fo,validateCrossRegistryCommand:()=>Yn,validateDelegationChain:()=>pn,validateLoaForScope:()=>Gn,validateManifest:()=>bo,validateMediaChunks:()=>oo,validateMessage:()=>yn,validateNodeAgainstSchema:()=>xn,validateReplay:()=>kn,validateRoleForScope:()=>tr,validateSafetyMessage:()=>Cn,validateTrainingDataMessage:()=>$n,validateURI:()=>hn,validateVersionCompat:()=>dn,verifyM2mTrustedToken:()=>Oo,verifyM2mTrustedTokenClaims:()=>_r,verifyMessage:()=>Wr,verifyPQSignature:()=>fs});d();d();var xe=class extends Error{constructor(e){super(e),this.name="RobotURIError"}},we=class t{registry;manufacturer;model;version;deviceId;constructor(e){this.registry=e.registry,this.manufacturer=e.manufacturer,this.model=e.model,this.version=e.version,this.deviceId=e.deviceId}static parse(e){if(!e.startsWith("rcan://"))throw new xe(`URI must start with 'rcan://' \u2014 got: ${e}`);let n=e.slice(7).split("/");if(n.length!==5)throw new xe(`URI must have exactly 5 path segments (registry/manufacturer/model/version/device-id) \u2014 got ${n.length} in: ${e}`);let[o,s,i,a,u]=n;for(let[p,g]of[["registry",o],["manufacturer",s],["model",i],["version",a],["device-id",u]])if(!g||g.trim()==="")throw new xe(`URI segment '${p}' must not be empty`);return new t({registry:o,manufacturer:s,model:i,version:a,deviceId:u})}static build(e){let r=e.registry??"registry.rcan.dev",{manufacturer:n,model:o,version:s,deviceId:i}=e;for(let[a,u]of[["manufacturer",n],["model",o],["version",s],["deviceId",i]])if(!u||u.trim()==="")throw new xe(`'${a}' must not be empty`);return new t({registry:r,manufacturer:n,model:o,version:s,deviceId:i})}toString(){return`rcan://${this.registry}/${this.manufacturer}/${this.model}/${this.version}/${this.deviceId}`}get namespace(){return`${this.manufacturer}/${this.model}`}get registryUrl(){return`https://${this.registry}/registry/${this.manufacturer}/${this.model}/${this.version}/${this.deviceId}`}equals(e){return this.toString()===e.toString()}toJSON(){return{uri:this.toString(),registry:this.registry,manufacturer:this.manufacturer,model:this.model,version:this.version,deviceId:this.deviceId}}};d();d();var q="2.2.1",un="1.2.2";function dn(t,e=q){let r=s=>{let i=s.split("."),a=parseInt(i[0]??"0",10),u=parseInt(i[1]??"0",10);return[isNaN(a)?0:a,isNaN(u)?0:u]},[n]=r(t),[o]=r(e);return n===o}var de=(c=>(c[c.COMMAND=1]="COMMAND",c[c.RESPONSE=2]="RESPONSE",c[c.STATUS=3]="STATUS",c[c.HEARTBEAT=4]="HEARTBEAT",c[c.CONFIG=5]="CONFIG",c[c.SAFETY=6]="SAFETY",c[c.AUTH=7]="AUTH",c[c.ERROR=8]="ERROR",c[c.DISCOVER=9]="DISCOVER",c[c.PENDING_AUTH=10]="PENDING_AUTH",c[c.INVOKE=11]="INVOKE",c[c.INVOKE_RESULT=12]="INVOKE_RESULT",c[c.INVOKE_CANCEL=13]="INVOKE_CANCEL",c[c.REGISTRY_REGISTER=14]="REGISTRY_REGISTER",c[c.REGISTRY_RESOLVE=15]="REGISTRY_RESOLVE",c[c.TRANSPARENCY=16]="TRANSPARENCY",c[c.COMMAND_ACK=17]="COMMAND_ACK",c[c.COMMAND_NACK=18]="COMMAND_NACK",c[c.ROBOT_REVOCATION=19]="ROBOT_REVOCATION",c[c.CONSENT_REQUEST=20]="CONSENT_REQUEST",c[c.CONSENT_GRANT=21]="CONSENT_GRANT",c[c.CONSENT_DENY=22]="CONSENT_DENY",c[c.FLEET_COMMAND=23]="FLEET_COMMAND",c[c.SUBSCRIBE=24]="SUBSCRIBE",c[c.UNSUBSCRIBE=25]="UNSUBSCRIBE",c[c.FAULT_REPORT=26]="FAULT_REPORT",c[c.KEY_ROTATION=27]="KEY_ROTATION",c[c.COMMAND_COMMIT=28]="COMMAND_COMMIT",c[c.SENSOR_DATA=29]="SENSOR_DATA",c[c.TRAINING_CONSENT_REQUEST=30]="TRAINING_CONSENT_REQUEST",c[c.TRAINING_CONSENT_GRANT=31]="TRAINING_CONSENT_GRANT",c[c.TRAINING_CONSENT_DENY=32]="TRAINING_CONSENT_DENY",c[c.CONTRIBUTE_REQUEST=33]="CONTRIBUTE_REQUEST",c[c.CONTRIBUTE_RESULT=34]="CONTRIBUTE_RESULT",c[c.CONTRIBUTE_CANCEL=35]="CONTRIBUTE_CANCEL",c[c.TRAINING_DATA=36]="TRAINING_DATA",c[c.COMPETITION_ENTER=37]="COMPETITION_ENTER",c[c.COMPETITION_SCORE=38]="COMPETITION_SCORE",c[c.SEASON_STANDING=39]="SEASON_STANDING",c[c.PERSONAL_RESEARCH_RESULT=40]="PERSONAL_RESEARCH_RESULT",c[c.AUTHORITY_ACCESS=41]="AUTHORITY_ACCESS",c[c.AUTHORITY_RESPONSE=42]="AUTHORITY_RESPONSE",c[c.FIRMWARE_ATTESTATION=43]="FIRMWARE_ATTESTATION",c[c.SBOM_UPDATE=44]="SBOM_UPDATE",c))(de||{}),oe=class extends Error{constructor(e){super(e),this.name="RCANMessageError"}},E=class t{rcan;rcanVersion;cmd;target;params;confidence;modelIdentity;signature;timestamp;senderType;cloudProvider;keyId;delegationChain;groupId;qos;presenceVerified;proximityMeters;readOnly;loa;transportEncoding;mediaChunks;firmwareHash;attestationRef;pqSig;constructor(e){if(!e.cmd||e.cmd.trim()==="")throw new oe("'cmd' is required");if(!e.target)throw new oe("'target' is required");if(this.rcan=e.rcan??q,this.rcanVersion=e.rcanVersion??q,this.cmd=e.cmd,this.target=e.target instanceof we?e.target.toString():String(e.target),this.params=e.params??{},this.confidence=e.confidence,this.modelIdentity=e.modelIdentity??e.model_identity,this.signature=e.signature,this.timestamp=e.timestamp??new Date().toISOString(),this.senderType=e.senderType,this.cloudProvider=e.cloudProvider,this.keyId=e.keyId,this.delegationChain=e.delegationChain,this.groupId=e.groupId,this.qos=e.qos,this.presenceVerified=e.presenceVerified,this.proximityMeters=e.proximityMeters,this.readOnly=e.readOnly,this.loa=e.loa,this.transportEncoding=e.transportEncoding,this.mediaChunks=e.mediaChunks,this.firmwareHash=e.firmwareHash,this.attestationRef=e.attestationRef,this.pqSig=e.pqSig,this.signature!==void 0&&this.signature.sig==="pending")throw new oe("signature.sig:'pending' is not valid in RCAN v2.1. Sign the message before sending.");if(this.confidence!==void 0&&(this.confidence<0||this.confidence>1))throw new oe(`confidence must be in [0.0, 1.0] \u2014 got ${this.confidence}`)}get isSigned(){return this.signature!==void 0&&this.signature.sig!==""}get isAiDriven(){return this.confidence!==void 0}toJSON(){let e={rcan:this.rcan,rcanVersion:this.rcanVersion,cmd:this.cmd,target:this.target,timestamp:this.timestamp};return Object.keys(this.params).length>0&&(e.params=this.params),this.confidence!==void 0&&(e.confidence=this.confidence),this.modelIdentity&&(e.model_identity=this.modelIdentity),this.signature&&(e.signature=this.signature),this.senderType!==void 0&&(e.senderType=this.senderType),this.cloudProvider!==void 0&&(e.cloudProvider=this.cloudProvider),this.keyId!==void 0&&(e.keyId=this.keyId),this.delegationChain!==void 0&&(e.delegationChain=this.delegationChain),this.groupId!==void 0&&(e.groupId=this.groupId),this.qos!==void 0&&(e.qos=this.qos),this.presenceVerified!==void 0&&(e.presenceVerified=this.presenceVerified),this.proximityMeters!==void 0&&(e.proximityMeters=this.proximityMeters),this.readOnly!==void 0&&(e.readOnly=this.readOnly),this.loa!==void 0&&(e.loa=this.loa),this.transportEncoding!==void 0&&(e.transportEncoding=this.transportEncoding),this.mediaChunks!==void 0&&(e.mediaChunks=this.mediaChunks),this.firmwareHash!==void 0&&(e.firmwareHash=this.firmwareHash),this.attestationRef!==void 0&&(e.attestationRef=this.attestationRef),e}toJSONString(e){return JSON.stringify(this.toJSON(),null,e)}static fromJSON(e){let r;if(typeof e=="string")try{r=JSON.parse(e)}catch{throw new oe("Invalid JSON string")}else r=e;if(!r.cmd)throw new oe("Missing required field: 'cmd'");if(!r.target)throw new oe("Missing required field: 'target'");if(!r.rcan)throw new oe("Missing required field: 'rcan'");return new t({rcan:r.rcan,rcanVersion:r.rcanVersion,cmd:r.cmd,target:r.target,params:r.params??{},confidence:r.confidence,modelIdentity:r.model_identity??r.modelIdentity,signature:r.signature,timestamp:r.timestamp,senderType:r.senderType,cloudProvider:r.cloudProvider,keyId:r.keyId,delegationChain:r.delegationChain,groupId:r.groupId,qos:r.qos,presenceVerified:r.presenceVerified,proximityMeters:r.proximityMeters,readOnly:r.readOnly,loa:r.loa,transportEncoding:r.transportEncoding,mediaChunks:r.mediaChunks,firmwareHash:r.firmwareHash,attestationRef:r.attestationRef,pqSig:r.pqSig})}};function fn(t,e){let r=t.toJSON();return r.senderType="cloud_function",r.cloudProvider=e,new E(r)}function ln(t,e){let r=t.delegationChain?[...t.delegationChain,e]:[e],n=t.toJSON();return n.delegationChain=r,new E(n)}function pn(t){if(t.length>4)return{valid:!1,reason:"DELEGATION_CHAIN_EXCEEDED: max depth is 4 hops"};for(let e=0;e<t.length;e++){let r=t[e];if(!r)return{valid:!1,reason:`hop ${e} is undefined`};if(!r.issuerRuri)return{valid:!1,reason:`hop ${e}: missing issuerRuri`};if(!r.humanSubject)return{valid:!1,reason:`hop ${e}: missing humanSubject`};if(!r.timestamp)return{valid:!1,reason:`hop ${e}: missing timestamp`};if(!r.scope)return{valid:!1,reason:`hop ${e}: missing scope`};if(!r.signature)return{valid:!1,reason:`hop ${e}: missing signature`}}return{valid:!0,reason:"ok"}}d();d();function ot(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{let{randomUUID:t}=ke("crypto");return t()}catch{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}}function Vt(t,e){return typeof process<"u",ws(t,e)}function Kt(t){let e=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],r=1779033703,n=3144134277,o=1013904242,s=2773480762,i=1359893119,a=2600822924,u=528734635,p=1541459225,v=t.length*8,k=[...t];for(k.push(128);k.length%64!==56;)k.push(0);for(let S=7;S>=0;S--)k.push(v/Math.pow(2,S*8)&255);for(let S=0;S<k.length;S+=64){let L=[];for(let R=0;R<16;R++)L[R]=k[S+R*4]<<24|k[S+R*4+1]<<16|k[S+R*4+2]<<8|k[S+R*4+3];for(let R=16;R<64;R++){let P=fe(L[R-15],7)^fe(L[R-15],18)^L[R-15]>>>3,ae=fe(L[R-2],17)^fe(L[R-2],19)^L[R-2]>>>10;L[R]=L[R-16]+P+L[R-7]+ae>>>0}let[K,_,w,N,I,D,V,U]=[r,n,o,s,i,a,u,p];for(let R=0;R<64;R++){let P=fe(I,6)^fe(I,11)^fe(I,25),ae=I&D^~I&V,Te=U+P+ae+e[R]+L[R]>>>0,Pe=fe(K,2)^fe(K,13)^fe(K,22),Le=K&_^K&w^_&w,et=Pe+Le>>>0;[U,V,D,I,N,w,_,K]=[V,D,I,N+Te>>>0,w,_,K,Te+et>>>0]}r=r+K>>>0,n=n+_>>>0,o=o+w>>>0,s=s+N>>>0,i=i+I>>>0,a=a+D>>>0,u=u+V>>>0,p=p+U>>>0}let b=new Uint8Array(32),M=new DataView(b.buffer);return[r,n,o,s,i,a,u,p].forEach((S,L)=>M.setUint32(L*4,S)),b}function fe(t,e){return t>>>e|t<<32-e}function gn(t){if(typeof TextEncoder<"u")return new TextEncoder().encode(t);let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r)&255;return e}function xs(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function ws(t,e){let n=gn(t);n.length>64&&(n=Kt(n));let o=new Uint8Array(64),s=new Uint8Array(64);for(let g=0;g<64;g++)o[g]=(n[g]??0)^54,s[g]=(n[g]??0)^92;let i=gn(e),a=new Uint8Array(64+i.length);a.set(o),a.set(i,64);let u=Kt(a),p=new Uint8Array(96);return p.set(s),p.set(u,64),xs(Kt(p))}var ye=class extends Error{constructor(e){super(e),this.name="GateError"}},st=class{threshold;constructor(e=.8){if(e<0||e>1)throw new ye(`threshold must be in [0.0, 1.0] \u2014 got ${e}`);this.threshold=e}allows(e){return e>=this.threshold}margin(e){return e-this.threshold}assert(e,r){if(!this.allows(e)){let n=r?` for action '${r}'`:"";throw new ye(`Confidence ${e}${n} is below threshold ${this.threshold}`)}}},it=class{_pending=new Map;request(e,r={}){let n=ot();return this._pending.set(n,{token:n,action:e,context:r,createdAt:new Date().toISOString(),status:"pending"}),n}approve(e){let r=this._pending.get(e);if(!r)throw new ye(`Unknown token: ${e}`);r.status="approved"}deny(e,r){let n=this._pending.get(e);if(!n)throw new ye(`Unknown token: ${e}`);n.status="denied",r&&(n.reason=r)}check(e){let r=this._pending.get(e);if(!r)throw new ye(`Unknown token: ${e}`);return r.status}get pendingApprovals(){return Array.from(this._pending.values()).filter(e=>e.status==="pending")}getApproval(e){return this._pending.get(e)}clearResolved(){for(let[e,r]of this._pending.entries())r.status!=="pending"&&this._pending.delete(e)}};d();var at=class extends Error{constructor(e){super(e),this.name="AuditError"}};function bs(t,e,r,n,o){let s=JSON.stringify({recordId:t,action:e,robotUri:r,timestamp:n,params:o},Object.keys({recordId:t,action:e,robotUri:r,timestamp:n,params:o}).sort());return Vt("rcan-content-hash",s)}function mn(t,e){let{hmac:r,...n}=e,o=JSON.stringify(n,Object.keys(n).sort());return Vt(t,o)}var Be=class t{recordId;action;robotUri;confidence;modelIdentity;params;safetyApproved;timestamp;contentHash;previousHash;hmac;constructor(e){this.recordId=e.recordId,this.action=e.action,this.robotUri=e.robotUri,this.confidence=e.confidence,this.modelIdentity=e.modelIdentity,this.params=e.params,this.safetyApproved=e.safetyApproved,this.timestamp=e.timestamp,this.contentHash=e.contentHash,this.previousHash=e.previousHash,this.hmac=e.hmac}static create(e,r,n=null){let o=ot(),s=new Date().toISOString(),i=e.params??{},a=e.robotUri??"",u=bs(o,e.action,a,s,i),p={recordId:o,action:e.action,robotUri:a,confidence:e.confidence,modelIdentity:e.modelIdentity,params:i,safetyApproved:e.safetyApproved??!0,timestamp:s,contentHash:u,previousHash:n,hmac:""};return p.hmac=mn(r,p),new t(p)}verify(e){return mn(e,this.toJSON())===this.hmac}toJSON(){return{recordId:this.recordId,action:this.action,robotUri:this.robotUri,confidence:this.confidence,modelIdentity:this.modelIdentity,params:this.params,safetyApproved:this.safetyApproved,timestamp:this.timestamp,contentHash:this.contentHash,previousHash:this.previousHash,hmac:this.hmac}}static fromJSON(e){return new t(e)}},ct=class t{_records=[];_secret;constructor(e){this._secret=e}get records(){return this._records}append(e){let n=this._records[this._records.length-1]?.contentHash??null,o=Be.create(e,this._secret,n);return this._records.push(o),o}verifyAll(){let e=[],r=null;for(let n of this._records)n.verify(this._secret)||e.push(`HMAC invalid for record ${n.recordId.slice(0,8)}`),r!==null&&n.previousHash!==r&&e.push(`Chain broken at ${n.recordId.slice(0,8)}: expected prev=${r.slice(0,12)}`),r=n.contentHash;return{valid:e.length===0,count:this._records.length,errors:e}}toJSONL(){return this._records.map(e=>JSON.stringify(e.toJSON())).join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`}static fromJSONL(e,r){let n=new t(r),o=e.trim().split(`
|
|
4
4
|
`).filter(s=>s.trim()!=="");for(let s of o){let i=JSON.parse(s);n._records.push(Be.fromJSON(i))}return n}};d();function Gt(){return{ok:!0,issues:[],warnings:[],info:[]}}function le(t,e){t.ok=!1,t.issues.push(e)}function Oe(t,e){t.warnings.push(e)}function te(t,e){t.info.push(e)}function hn(t){let e=Gt();try{let r=we.parse(t);te(e,"\u2705 Valid RCAN URI"),te(e,` Registry: ${r.registry}`),te(e,` Manufacturer: ${r.manufacturer}`),te(e,` Model: ${r.model}`),te(e,` Version: ${r.version}`),te(e,` Device ID: ${r.deviceId}`)}catch(r){le(e,`Invalid RCAN URI: ${r instanceof Error?r.message:r}`)}return e}function yn(t){let e=Gt(),r;if(typeof t=="string")try{r=JSON.parse(t)}catch{return le(e,"Invalid JSON string"),e}else if(typeof t=="object"&&t!==null)r=t;else return le(e,"Expected object or JSON string"),e;for(let n of["rcan","cmd","target"])(!(n in r)||!r[n])&&le(e,`Missing required field: '${n}'`);if(!e.ok)return e;try{let n=E.fromJSON(r);te(e,`\u2705 RCAN message valid (v${n.rcan})`),te(e,` cmd: ${n.cmd}`),te(e,` target: ${n.target}`),n.confidence!==void 0?te(e,` confidence: ${n.confidence}`):Oe(e,"No confidence score \u2014 add for RCAN \xA716 AI accountability"),n.isSigned?te(e,` signature: alg=${n.signature?.alg}, kid=${n.signature?.kid}`):Oe(e,"Message is unsigned (recommended for production)")}catch(n){le(e,`Message validation failed: ${n instanceof Error?n.message:n}`)}return e}function Rn(t){let e=Gt(),r=t.metadata??{},n=t.agent??{},o=t.rcan_protocol??{};for(let i of["rcan_version","metadata","agent"])(!(i in t)||t[i]===void 0||t[i]===null)&&le(e,`Missing required key: '${i}'`);let s=t.rcan_version;if(s&&(/^\d+\.\d+$/.test(s)||le(e,`rcan_version '${s}' must match pattern N.N (e.g. '1.2')`)),r.manufacturer||le(e,"L1: metadata.manufacturer is required (\xA72)"),r.model||le(e,"L1: metadata.model is required (\xA72)"),!r.device_id&&!r.robot_name&&le(e,"L1: metadata.device_id (or robot_name) is required (\xA72)"),o.jwt_auth?.enabled||Oe(e,"L2: jwt_auth not enabled (required for L2 conformance, \xA78)"),(!n.confidence_gates||n.confidence_gates.length===0)&&Oe(e,"L2: confidence_gates not configured (\xA716)"),(!n.hitl_gates||n.hitl_gates.length===0)&&Oe(e,"L3: hitl_gates not configured (\xA716)"),n.commitment_chain?.enabled||Oe(e,"L3: commitment_chain not enabled (\xA716)"),r.rrn?te(e,`\u2705 RRN registered: ${r.rrn}`):Oe(e,"Robot not registered \u2014 visit rcan.dev/registry/register"),e.ok&&e.issues.length===0){let i=!e.warnings.some(g=>g.startsWith("L1")),a=i&&!e.warnings.some(g=>g.startsWith("L2")),p=a&&!e.warnings.some(g=>g.startsWith("L3"))?"L3":a?"L2":i?"L1":"FAIL";te(e,`\u2705 Config valid \u2014 conformance level: ${p}`)}return e}d();var Q=class extends Error{constructor(e){super(e),this.name="RCANError",Object.setPrototypeOf(this,new.target.prototype)}},ut=class extends Q{constructor(e){super(e),this.name="RCANAddressError",Object.setPrototypeOf(this,new.target.prototype)}},dt=class extends Q{constructor(e){super(e),this.name="RCANValidationError",Object.setPrototypeOf(this,new.target.prototype)}},ft=class extends Q{constructor(r,n,o,s){super(r);this.gateType=n;this.value=o;this.threshold=s;this.name="RCANGateError",Object.setPrototypeOf(this,new.target.prototype)}},lt=class extends Q{constructor(e){super(e),this.name="RCANSignatureError",Object.setPrototypeOf(this,new.target.prototype)}},ve=class extends Q{constructor(e){super(e),this.name="RCANRegistryError",Object.setPrototypeOf(this,new.target.prototype)}},Ne=class t extends Q{constructor(r,n){super(r);this.nodeUrl=n;this.name="RCANNodeError",Object.setPrototypeOf(this,t.prototype)}},Re=class t extends Ne{constructor(r,n){super(`RRN not found in federation: ${r}`,n);this.rrn=r;this.name="RCANNodeNotFoundError",Object.setPrototypeOf(this,t.prototype)}},Y=class t extends Ne{constructor(r,n,o){super(r,n);this.cause=o;this.name="RCANNodeSyncError",Object.setPrototypeOf(this,t.prototype)}},$e=class t extends Ne{reason;constructor(e,r){super(`Node trust verification failed: ${e}`,r),this.name="RCANNodeTrustError",this.reason=e,Object.setPrototypeOf(this,t.prototype)}},pt=class t extends Q{constructor(e,r){super(`VERSION_INCOMPATIBLE: incoming=${e}, local=${r}`),this.name="RCANVersionIncompatibleError",Object.setPrototypeOf(this,t.prototype)}},gt=class t extends Q{constructor(e){super(`REPLAY_DETECTED: ${e}`),this.name="RCANReplayAttackError",Object.setPrototypeOf(this,t.prototype)}},mt=class t extends Q{constructor(e){super(`DELEGATION_CHAIN_ERROR: ${e}`),this.name="RCANDelegationChainError",Object.setPrototypeOf(this,t.prototype)}},ht=class t extends Q{constructor(e){super(`CONFIG_AUTH_ERROR: ${e}`),this.name="RCANConfigAuthorizationError",Object.setPrototypeOf(this,t.prototype)}};d();var As="https://rcan-spec.pages.dev",yt=class{baseUrl;apiKey;timeout;constructor(e){this.baseUrl=(e?.baseUrl??As).replace(/\/$/,""),this.apiKey=e?.apiKey,this.timeout=e?.timeout??1e4}async _fetch(e,r={}){let n=`${this.baseUrl}${e}`,o=new AbortController,s=setTimeout(()=>o.abort(),this.timeout);try{return await fetch(n,{...r,signal:o.signal,headers:{"Content-Type":"application/json",...r.headers??{}}})}finally{clearTimeout(s)}}_authHeaders(){if(!this.apiKey)throw new ve("API key required for write operations. Pass apiKey to RegistryClient.");return{Authorization:`Bearer ${this.apiKey}`}}async _checkResponse(e){if(!e.ok){let r=`Registry API error: ${e.status}`;try{let n=await e.json();n?.error&&(r=n.error)}catch{}throw new ve(r)}return await e.json()}async register(e){let r=await this._fetch("/api/v1/robots",{method:"POST",body:JSON.stringify(e)});return this._checkResponse(r)}async get(e){let r=await this._fetch(`/api/v1/robots/${encodeURIComponent(e)}`);return this._checkResponse(r)}async list(e){let r=new URLSearchParams;e?.limit!==void 0&&r.set("limit",String(e.limit)),e?.offset!==void 0&&r.set("offset",String(e.offset)),e?.tier&&r.set("tier",e.tier);let n=r.toString()?`?${r}`:"",o=await this._fetch(`/api/v1/robots${n}`);return this._checkResponse(o)}async patch(e,r){let n=await this._fetch(`/api/v1/robots/${encodeURIComponent(e)}`,{method:"PATCH",headers:this._authHeaders(),body:JSON.stringify(r)});return this._checkResponse(n)}async delete(e){let r=await this._fetch(`/api/v1/robots/${encodeURIComponent(e)}`,{method:"DELETE",headers:this._authHeaders()});r.ok||await this._checkResponse(r)}async search(e){let r=new URLSearchParams;e.q&&r.set("q",e.q),e.manufacturer&&r.set("manufacturer",e.manufacturer),e.model&&r.set("model",e.model),e.tier&&r.set("tier",e.tier);let n=r.toString()?`?${r}`:"",o=await this._fetch(`/api/v1/robots/search${n}`);if(!o.ok){let i=await this._fetch(`/api/v1/robots${n}`),a=await this._checkResponse(i);return"robots"in a?a.robots:"results"in a&&a.results?a.results:[]}let s=await o.json();return Array.isArray(s)?s:"results"in s&&s.results?s.results:"robots"in s?s.robots:[]}};d();var Es="https://rcan.dev",Ss="/.well-known/rcan-node.json",Cs=new Set(["root","authoritative","resolver","cache"]);function Ts(t){let e=t.match(/^RRN-([A-Z0-9]{2,8})-(\d{8,16})$/);if(e)return{type:"delegated",prefix:e[1],serial:e[2]};let r=t.match(/^RRN-(\d{8,16})$/);return r?{type:"root",serial:r[1]}:null}var Rt=class{rootUrl;timeoutMs;constructor(e=Es,r=1e4){this.rootUrl=e.replace(/\/$/,""),this.timeoutMs=r}async _fetch(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{return await globalThis.fetch(e,{signal:r.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Y(`Request timed out: ${e}`,e,o):new Y(`Network error fetching ${e}: ${o.message}`,e,o instanceof Error?o:void 0)}finally{clearTimeout(n)}}async getNodeManifest(e){let r=`${e.replace(/\/$/,"")}${Ss}`,n=await this._fetch(r);if(!n.ok)throw n.status===404?new Re(r,e):new Y(`Failed to fetch node manifest from ${e}: HTTP ${n.status}`,e);let o;try{o=await n.json()}catch(s){throw new Y(`Invalid JSON in node manifest from ${e}`,e,s instanceof Error?s:void 0)}if(!this.verifyNode(o))throw new $e("missing_pubkey",e);return o}async listNodes(e){let r=e?`?prefix=${encodeURIComponent(e)}`:"",n=`${this.rootUrl}/api/v1/nodes${r}`,o=await this._fetch(n);if(!o.ok)throw new Y(`Failed to list nodes from ${n}: HTTP ${o.status}`,n);let s;try{s=await o.json()}catch(i){throw new Y(`Invalid JSON in nodes list from ${n}`,n,i instanceof Error?i:void 0)}return Array.isArray(s)?s:s&&typeof s=="object"&&"nodes"in s?s.nodes:[]}async discover(e){let r=Ts(e);if(!r)throw new Re(e,this.rootUrl);if(r.type==="root")return this.getNodeManifest(this.rootUrl);let n=await this.listNodes(r.prefix);if(n.length===0)throw new Re(e,this.rootUrl);return n[0]}async resolve(e){let r=`${this.rootUrl}/api/v1/resolve/${encodeURIComponent(e)}`,n;try{n=await this._fetch(r)}catch(a){throw a}if(n.ok)try{return await n.json()}catch(a){throw new Y(`Invalid JSON in resolve response for ${e}`,this.rootUrl,a instanceof Error?a:void 0)}if(n.status!==404)throw new Y(`Unexpected HTTP ${n.status} resolving ${e}`,this.rootUrl);let o=await this.discover(e),s=`${o.api_base.replace(/\/$/,"")}/robots/${encodeURIComponent(e)}`,i=await this._fetch(s);if(!i.ok)throw i.status===404?new Re(e,o.api_base):new Y(`HTTP ${i.status} from authoritative node for ${e}`,o.api_base);try{return await i.json()}catch(a){throw new Y(`Invalid JSON in fallback resolve response for ${e}`,o.api_base,a instanceof Error?a:void 0)}}verifyNode(e){if(!e||typeof e!="object")return!1;let r=e;return!(typeof r.rcan_node_version!="string"||!r.rcan_node_version||typeof r.node_type!="string"||!Cs.has(r.node_type)||typeof r.operator!="string"||!r.operator||typeof r.namespace_prefix!="string"||!r.namespace_prefix||typeof r.public_key!="string"||!r.public_key.startsWith("ed25519:")||typeof r.api_base!="string"||!r.api_base.startsWith("https://"))}};d();var ks="https://rcan.dev/schemas",Jt=new Map;async function _t(t){if(Jt.has(t))return Jt.get(t);try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);r.unref?.();let n=await fetch(`${ks}/${t}`,{signal:e.signal});if(clearTimeout(r),!n.ok)return null;let o=await n.json();return Jt.set(t,o),o}catch{return null}}async function _n(t){let e=await _t("rcan-config.schema.json");if(!e)return{valid:!0,skipped:!0};let r=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Config must be an object"]};let n=t,o=e.required??[];for(let s of o)s in n||r.push(`Missing required field: ${s}`);return r.length===0?{valid:!0}:{valid:!1,errors:r}}async function xn(t){let e=await _t("rcan-node.schema.json");if(!e)return{valid:!0,skipped:!0};let r=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Manifest must be an object"]};let n=t,o=e.required??[];for(let s of o)s in n||r.push(`Missing required field: ${s}`);return r.length===0?{valid:!0}:{valid:!1,errors:r}}d();d();var Yt=(n=>(n[n.FIRE_AND_FORGET=0]="FIRE_AND_FORGET",n[n.ACKNOWLEDGED=1]="ACKNOWLEDGED",n[n.EXACTLY_ONCE=2]="EXACTLY_ONCE",n))(Yt||{}),xt=class t extends Error{constructor(e){super(`ACK timeout for message ${e} \u2014 safety halt required`),this.name="QoSAckTimeoutError",Object.setPrototypeOf(this,t.prototype)}},wt=class{_send;_waitForAck;constructor(e,r){this._send=e,this._waitForAck=r}async sendWithQoS(e,r={}){let n=r.qos??0,o=r.maxRetries??3,s=r.initialBackoffMs??100,i=r.ackTimeoutMs??500;if(n===0)return await this._send(e),{delivered:!0,attempts:1,reason:"fire-and-forget"};let a=e.message_id??e.msg_id??"unknown",u=0,p=s;for(;u<=o;){if(await this._send(e),u++,await this._waitForAck(a,i))return{delivered:!0,attempts:u,reason:n===2?"exactly-once":"acknowledged"};if(u>o)break;await vs(p),p=Math.min(p*2,5e3)}return{delivered:!1,attempts:u,reason:`ACK not received after ${o} retries`}}};function wn(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:Os(),qos:2}}function Os(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=Array.from({length:16},()=>Math.floor(Math.random()*256));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=t.map(r=>r.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function vs(t){return new Promise(e=>setTimeout(e,t))}var Wt=6;function bt(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=Array.from({length:16},()=>Math.floor(Math.random()*256));t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=t.map(r=>r.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function bn(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:bt(),qos:2}}function An(t,e){return{message_type:6,ruri:t,safety_event:"STOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:bt()}}function En(t,e){return{message_type:6,ruri:t,safety_event:"RESUME",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:bt()}}function Sn(t){return typeof t=="object"&&t!==null&&t.message_type===Wt}function Cn(t){let e=[];return t.message_type!==6&&e.push("message_type must be 6"),t.ruri||e.push("ruri is required"),["ESTOP","STOP","RESUME"].includes(t.safety_event??"")||e.push("safety_event must be ESTOP, STOP, or RESUME"),(!t.reason||t.reason.length===0)&&e.push("reason is required"),t.message_id||e.push("message_id is required"),(!t.timestamp_ms||t.timestamp_ms<=0)&&e.push("timestamp_ms must be positive"),e}function Tn(t,e,r){return{message_type:11,ruri:t,disclosure:e,timestamp_ms:Date.now(),message_id:bt(),delegation_chain:r}}d();var At=class{windowSeconds;maxSize;_seen;constructor(e=30,r=1e4){this.windowSeconds=e,this.maxSize=r,this._seen=new Map}checkAndRecord(e,r,n=!1){let o=Date.now();this._evict(o);let s=n?Math.min(this.windowSeconds,10):this.windowSeconds,i=Ns(r);if(i===null)return{allowed:!1,reason:`invalid timestamp format: ${r}`};let a=o-i,u=s*1e3;if(a>u)return{allowed:!1,reason:`message too old: age=${Math.round(a/1e3)}s > window=${s}s`};if(i>o+5e3)return{allowed:!1,reason:"message timestamp is in the future"};if(this._seen.has(e))return{allowed:!1,reason:`replay detected: msg_id ${e} already seen`};if(this._seen.size>=this.maxSize){let g=this._seen.keys().next().value;this._seen.delete(g)}let p=o+u;return this._seen.set(e,p),{allowed:!0,reason:"ok"}}_evict(e){for(let[r,n]of this._seen)n<=e&&this._seen.delete(r)}get size(){return this._seen.size}};function kn(t,e){let r=t,n=r.message_id??r.msg_id;if(!n)return{valid:!1,reason:"missing message_id / msg_id"};let o;if(typeof r.timestamp_ms=="number"?o=String(r.timestamp_ms/1e3):r.timestamp!==void 0&&(o=String(r.timestamp)),!o)return{valid:!1,reason:"missing timestamp"};let s=r.message_type===6||r.message_type===6,i=e.checkAndRecord(n,o,s);return{valid:i.allowed,reason:i.reason}}function Ns(t){if(t.includes("T")||t.includes("-")){let r=new Date(t);if(!isNaN(r.getTime()))return r.getTime()}let e=parseFloat(t);return isNaN(e)?null:e>1e12?e:e*1e3}d();var Ke=class t extends Error{offsetSeconds;constructor(e,r){super(`Clock drift too large: offset=${e.toFixed(3)}s > max=${r}s`),this.name="ClockDriftError",this.offsetSeconds=e,Object.setPrototypeOf(this,t.prototype)}};async function Qt(t){let e=t??"https://worldtimeapi.org/api/ip";try{let r=Date.now(),n=await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(3e3)}),o=Date.now(),s=n.headers.get("Date")??n.headers.get("date");if(!s)return{synchronized:!0,offsetSeconds:0,source:"assumed (no Date header)"};let i=new Date(s).getTime();if(isNaN(i))return{synchronized:!0,offsetSeconds:0,source:"assumed (unparseable Date header)"};let u=((r+o)/2-i)/1e3;return{synchronized:Math.abs(u)<=5,offsetSeconds:u,source:e}}catch{return{synchronized:!0,offsetSeconds:0,source:"assumed (network unavailable)"}}}async function On(t=5){let e=await Qt();if(!e.synchronized||Math.abs(e.offsetSeconds)>t)throw new Ke(e.offsetSeconds,t)}d();async function Is(t){let e=JSON.stringify(t,Object.keys(t).sort());if(typeof crypto<"u"&&crypto.subtle){let n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(o)).map(s=>s.toString(16).padStart(2,"0")).join("")}let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=r*16777619>>>0;return r.toString(16).padStart(8,"0")}async function vn(t,e,r,n="rcan://local/config",o=!1){let s=await Is(t);return new E({rcan:q,cmd:"CONFIG_UPDATE",target:n,params:{message_type:5,diff:t,rollback:r,scope:e,config_hash:s,safety_overrides:o}})}function Nn(t){let e=t.params;return!e.diff||typeof e.diff!="object"?{valid:!1,reason:"missing required field: params.diff"}:!e.config_hash||typeof e.config_hash!="string"?{valid:!1,reason:"missing required field: params.config_hash"}:"rollback"in e?e.safety_overrides===!0&&e.scope!=="creator"?{valid:!1,reason:"safety_overrides=true requires scope=creator (owner is insufficient)"}:{valid:!0,reason:"ok"}:{valid:!1,reason:"missing required field: params.rollback"}}d();function Ms(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}var Et=class{_keys=[];addKey(e){this._keys.push(e)}getJWKS(){return{keys:[...this._keys]}}findKey(e){return this._keys.find(r=>r.kid===e)}isKeyValid(e,r){let n=this.findKey(e);if(!n)return!1;let o=(r??Date.now())/1e3;return!(n.revoked_at!==void 0&&n.revoked_at<=o||n.exp!==void 0&&n.exp<o)}expireKey(e,r){let n=this.findKey(e);n&&(n.exp=r??Math.floor(Date.now()/1e3))}revokeKey(e){let r=this.findKey(e);r&&(r.revoked_at=Math.floor(Date.now()/1e3))}validKeys(e){return this._keys.filter(r=>this.isKeyValid(r.kid,e))}};function In(t,e,r=120,n="rcan://local/keys"){let o=Ms().slice(0,8);return new E({rcan:q,cmd:"KEY_ROTATION",target:n,params:{message_type:5,new_public_key:t,new_kid:o,old_kid:e,overlap_seconds:r,initiated_at:new Date().toISOString()},keyId:o})}d();function Us(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function St(t){let e=t.requestId??Us();return new E({rcan:q,cmd:"CONSENT_REQUEST",target:t.targetRuri,params:{message_type:20,requester_ruri:t.requesterRuri,requester_owner:t.requesterOwner,target_ruri:t.targetRuri,requested_scopes:t.requestedScopes,duration_hours:t.durationHours,justification:t.justification,request_id:e,consent_type:t.consentType??"cross_robot",data_categories:t.dataCategories??[]}})}function Ct(t){let e=t.expiresAt??new Date(Date.now()+864e5).toISOString();return new E({rcan:q,cmd:"CONSENT_GRANT",target:"rcan://local/consent",params:{message_type:21,request_id:t.requestId,granted_scopes:t.grantedScopes??[],expires_at:e,reason:t.reason??"approved"}})}function Tt(t){return new E({rcan:q,cmd:"CONSENT_DENY",target:"rcan://local/consent",params:{message_type:22,request_id:t.requestId,reason:t.reason??"denied"}})}function Mn(t){let e=t.cmd,r=t.params,n=r.message_type;return e==="CONSENT_REQUEST"?n!==20?{valid:!1,reason:"message_type must be CONSENT_REQUEST (20)"}:r.requester_ruri?r.target_ruri?!r.requested_scopes||!Array.isArray(r.requested_scopes)||r.requested_scopes.length===0?{valid:!1,reason:"requested_scopes must be a non-empty array"}:r.request_id?r.justification?{valid:!0,reason:"ok"}:{valid:!1,reason:"missing justification"}:{valid:!1,reason:"missing request_id"}:{valid:!1,reason:"missing target_ruri"}:{valid:!1,reason:"missing requester_ruri"}:e==="CONSENT_GRANT"?n!==21?{valid:!1,reason:"message_type must be CONSENT_GRANT (21)"}:r.request_id?r.expires_at?{valid:!0,reason:"ok"}:{valid:!1,reason:"missing expires_at"}:{valid:!1,reason:"missing request_id"}:e==="CONSENT_DENY"?n!==22?{valid:!1,reason:"message_type must be CONSENT_DENY (22)"}:r.request_id?{valid:!0,reason:"ok"}:{valid:!1,reason:"missing request_id"}:{valid:!1,reason:`unknown consent command: ${e}`}}d();var Ps=3600*1e3,Ve=class{_cache=new Map;get(e,r){let n=this._cache.get(e);if(!n)return;let o=r??Date.now();if(n.cachedUntil!==void 0&&n.cachedUntil<o){this._cache.delete(e);return}return n}set(e,r){let n=r??Date.now();this._cache.set(e.rrn,{...e,cachedUntil:n+Ps})}invalidate(e){this._cache.delete(e)}get size(){return this._cache.size}};async function Un(t,e,r){let n=r??new Ve,o=n.get(t);if(o)return o;let s=`${e.replace(/\/$/,"")}/api/v1/robots/${encodeURIComponent(t)}/revocation-status`;try{let i=await fetch(s,{signal:AbortSignal.timeout(5e3)});if(!i.ok){let p={rrn:t,status:"active",reason:`registry returned ${i.status}`};return n.set(p),p}let a=await i.json(),u={rrn:t,status:a.status??"active",revokedAt:a.revokedAt,reason:a.reason,authority:a.authority};return n.set(u),u}catch{return{rrn:t,status:"active",reason:"network unavailable"}}}function Pn(t,e){return new E({rcan:q,cmd:"ROBOT_REVOCATION",target:"rcan://broadcast/revocation",params:{message_type:19,rrn:t,reason:e,revoked_at:new Date().toISOString()}})}d();var zt=(s=>(s.VIDEO="video",s.AUDIO="audio",s.LOCATION="location",s.BIOMETRIC="biometric",s.TELEMETRY="telemetry",s))(zt||{});function Ln(t){return St({requesterRuri:t.requesterRuri,requesterOwner:t.requesterOwner,targetRuri:t.targetRuri,requestedScopes:["training_data"],durationHours:t.durationHours,justification:t.justification,requestId:t.requestId,consentType:"training_data",dataCategories:t.dataCategories})}function Dn(t){return Ct(t)}function Bn(t){return Tt(t)}function $n(t){if(t.params.message_type!==36)return{valid:!1,reason:"not a TRAINING_DATA message"};let e=t.params.consent_token;return!e||typeof e!="string"||e.trim()===""?{valid:!1,reason:"TRAINING_DATA message missing consent_token (\xA717)"}:{valid:!0,reason:"ok"}}d();var kt=class{crossOwnerGraceS;keyTtlS;_cachedKeys=[];constructor(e=3600,r=86400){this.crossOwnerGraceS=e,this.keyTtlS=r}canAcceptCommand(e,r,n,o=!0,s=!1,i,a){if(e&&e.message_type===6&&e.safety_event==="ESTOP")return{allowed:!0,reason:"ESTOP always accepted (Protocol 66)"};if(!r)return{allowed:!0,reason:"online mode"};if(!n)return{allowed:!1,reason:"offline mode: cross-network commands blocked"};if(!o)return{allowed:!1,reason:"offline mode: only owner-role commands accepted from local network"};if(s&&i!==void 0){let p=((a??Date.now())-i)/1e3;if(p>this.crossOwnerGraceS)return{allowed:!1,reason:`offline mode: cross-owner grace period expired (${Math.round(p)}s > ${this.crossOwnerGraceS}s)`}}return{allowed:!0,reason:"offline mode: owner command on local network accepted"}}cacheKey(e,r){let n=r??Date.now();this._cachedKeys=this._cachedKeys.filter(o=>o.kid!==e.kid),this._cachedKeys.push({...e,cachedAtMs:n,ttlSeconds:this.keyTtlS})}getCachedKey(e,r){let n=r??Date.now(),o=this._cachedKeys.find(i=>i.kid===e);if(!o)return;if((n-o.cachedAtMs)/1e3>o.ttlSeconds){this._cachedKeys=this._cachedKeys.filter(i=>i.kid!==e);return}return o}getManifestFields(e,r){if(e===void 0)return{offline_mode:!1,offline_since_s:0};let n=r??Date.now();return{offline_mode:!0,offline_since_s:Math.round((n-e)/1e3)}}};d();var Xt=(b=>(b.SENSOR_PROXIMITY_FAILURE="SENSOR_PROXIMITY_FAILURE",b.SENSOR_CAMERA_FAILURE="SENSOR_CAMERA_FAILURE",b.SENSOR_IMU_FAILURE="SENSOR_IMU_FAILURE",b.MOTOR_OVERCURRENT="MOTOR_OVERCURRENT",b.MOTOR_OVERTEMP="MOTOR_OVERTEMP",b.MOTOR_STALL="MOTOR_STALL",b.BATTERY_CRITICAL="BATTERY_CRITICAL",b.BATTERY_LOW="BATTERY_LOW",b.NETWORK_TIMEOUT="NETWORK_TIMEOUT",b.NETWORK_REGISTRY_UNREACHABLE="NETWORK_REGISTRY_UNREACHABLE",b.SAFETY_ESTOP_STUCK="SAFETY_ESTOP_STUCK",b.SAFETY_WATCHDOG_TIMEOUT="SAFETY_WATCHDOG_TIMEOUT",b.UNKNOWN="UNKNOWN",b))(Xt||{});function jn(t){return new E({rcan:q,cmd:"FAULT_REPORT",target:t.target??"rcan://local/fault",params:{message_type:26,fault_code:t.faultCode,severity:t.severity,subsystem:t.subsystem,affects_safety:t.affectsSafety,safe_to_continue:t.safeToContinue,description:t.description??"",reported_at:new Date().toISOString()}})}d();var be=(a=>(a[a.GUEST=1]="GUEST",a[a.OPERATOR=2]="OPERATOR",a[a.CONTRIBUTOR=3]="CONTRIBUTOR",a[a.ADMIN=4]="ADMIN",a[a.M2M_PEER=5]="M2M_PEER",a[a.CREATOR=6]="CREATOR",a[a.M2M_TRUSTED=7]="M2M_TRUSTED",a))(be||{}),qn=be,je={1:1,2:2,3:2.5,4:3,5:4,6:5,7:6},Ls=new Map(Object.entries(je).map(([t,e])=>[e,Number(t)]));function Ge(t){return Ls.get(t)}var Zt={status:1,discover:1,chat:1,observer:1,contribute:3,control:2,teleop:2,training:4,training_data:4,config:4,authority:4,admin:6,safety:6,estop:6,"fleet.trusted":7};var Hn={minRoleForDiscover:1,minRoleForStatus:1,minRoleForChat:1,minRoleForControl:1,minRoleForSafety:1},Fn={minRoleForDiscover:1,minRoleForStatus:1,minRoleForChat:1,minRoleForControl:2,minRoleForSafety:6};function Kn(t){try{let e=t.split(".");if(e.length<2)return null;let r=(e[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=r+"=".repeat((4-r.length%4)%4);return JSON.parse(atob(n))}catch{return null}}function er(t){let e=Kn(t);if(!e)return 1;let r=e.rcan_role;if(r!=null){let o=Ge(Number(r));if(o!==void 0)return o}let n=e.loa;if(n!=null){let o=Ge(Number(n));if(o!==void 0)return o}return 1}function Ot(t){return er(t)}function Vn(t){let e=Kn(t);if(!e)return{sub:"",role:1,jwtLevel:1,scopes:[]};let r=e.rcan_role,n=e.loa,o=r!==void 0?Number(r):n!==void 0?Number(n):1,s=Ge(o)??1,i=Array.isArray(e.rcan_scopes)?e.rcan_scopes:Array.isArray(e.scopes)?e.scopes:[];return{sub:String(e.sub??""),role:s,jwtLevel:je[s],registryUrl:e.registry_url,scopes:i,verifiedAt:e.verified_at,peerRrn:e.peer_rrn,fleetRrns:Array.isArray(e.fleet_rrns)?e.fleet_rrns:void 0}}function tr(t,e){let r=Zt[e.toLowerCase()];return r===void 0?t>=2?{ok:!0,reason:""}:{ok:!1,reason:`Unknown scope '${e}': applying OPERATOR minimum. Caller has ${be[t]}.`}:t>=r?{ok:!0,reason:""}:{ok:!1,reason:`Scope '${e}' requires ${be[r]} (JWT level ${je[r]}), but caller has ${be[t]} (JWT level ${je[t]})`}}function Gn(t,e){return tr(t,e)}d();var rr=(n=>(n.ROOT="root",n.AUTHORITATIVE="authoritative",n.COMMUNITY="community",n))(rr||{}),nr=(n=>(n.CONSENT="consent",n.REVOCATION="revocation",n.KEY="key",n))(nr||{}),Ds=1440*60*1e3,vt=class{store=new Map;set(e){this.store.set(e.registryUrl,{identity:e,expiresAt:Date.now()+Ds})}lookup(e){let r=this.store.get(e);if(r){if(Date.now()>r.expiresAt){this.store.delete(e);return}return r.identity}}async discoverViaDns(e){let r=`_rcan-registry.${e}`,n;try{n=await ke("dns").promises.resolveTxt(r)}catch{return}for(let o of n){let s=o.join("");try{let i=JSON.parse(s);if(i.registryUrl&&i.tier&&i.publicKeyPem&&i.domain){let a={registryUrl:i.registryUrl,tier:i.tier,publicKeyPem:i.publicKeyPem,domain:i.domain,verifiedAt:new Date().toISOString()};return this.set(a),a}}catch{}}}async verifyRegistryJwt(e,r){let n=this.lookup(r);if(!n)throw new Error(`REGISTRY_UNKNOWN: ${r} is not in the trust cache`);let o;try{let i=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),a=i+"=".repeat((4-i.length%4)%4),u;typeof atob<"u"?u=atob(a):u=Buffer.from(a,"base64").toString("utf-8");let p=JSON.parse(u);o=typeof p.iss=="string"?p.iss:void 0}catch{throw new Error("REGISTRY_JWT_MALFORMED: cannot decode token payload")}if(o!==r)throw new Error(`REGISTRY_JWT_ISS_MISMATCH: expected iss=${r}, got iss=${o??"(none)"}`);return n}};function Bs(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=Array.from({length:16},()=>Math.floor(Math.random()*256));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=t.map(r=>r.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function Jn(t,e,r,n){return new E({rcan:"2.1.0",rcanVersion:"2.1.0",cmd:"federation_sync",target:e,params:{msg_type:23,msg_id:Bs(),source_registry:t,target_registry:e,sync_type:r,payload:n},timestamp:new Date().toISOString()})}async function Yn(t,e,r){let n=t.params?.msg_type;if(n===6||n===6||t.cmd==="estop"||t.cmd==="ESTOP")return{valid:!0,reason:"ESTOP always permitted (P66 invariant)"};let s=t.params?.source_registry??t.params?.from_registry;if(!s||s===e)return{valid:!0,reason:"local registry; no federation check needed"};if(!r.lookup(s))return{valid:!1,reason:`REGISTRY_UNKNOWN: ${s} is not in the local trust cache`};let a=1,u=t.params?.registry_jwt;return u?a=Ot(u):typeof t.loa=="number"&&(a=t.loa),a<2?{valid:!1,reason:`LOA_INSUFFICIENT: cross-registry commands require LoA>=2 (OPERATOR), got role=${a}`}:{valid:!0,reason:"cross-registry command accepted"}}d();var ie=class t extends Error{constructor(e){super(e),this.name="TransportError",Object.setPrototypeOf(this,t.prototype)}},ir=(o=>(o.HTTP="http",o.COMPACT="compact",o.MINIMAL="minimal",o.BLE="ble",o))(ir||{}),or={msg_type:"t",msg_id:"i",timestamp:"ts",from_rrn:"f",to_rrn:"to",scope:"s",payload:"p",signature:"sig"},Wn=Object.fromEntries(Object.entries(or).map(([t,e])=>[e,t]));function ar(t){let e=t.toJSON(),r={};for(let[s,i]of Object.entries(e)){let a=or[s];r[a??s]=i}if(r.p&&typeof r.p=="object"){let s=r.p,i={};for(let[a,u]of Object.entries(s)){let p=or[a];i[p??a]=u}r.p=i}let n=JSON.stringify(r);return new TextEncoder().encode(n)}function cr(t){let r=new TextDecoder().decode(t),n=JSON.parse(r),o={};for(let[s,i]of Object.entries(n)){let a=Wn[s];o[a??s]=i}if(o.payload&&typeof o.payload=="object"){let s=o.payload,i={};for(let[a,u]of Object.entries(s)){let p=Wn[a];i[p??a]=u}o.payload=i}return new E({rcan:o.rcan??"1.6",rcanVersion:o.rcanVersion,cmd:o.cmd,target:o.target,params:o.params??o.payload??{},timestamp:o.timestamp,confidence:o.confidence,signature:o.signature})}var Ye=32,sr=6;async function Qn(t){let e=new TextEncoder().encode(t),r=new ArrayBuffer(e.byteLength);new Uint8Array(r).set(e);let o=await(globalThis.crypto?.subtle??(await import("crypto")).webcrypto.subtle).digest("SHA-256",r);return new Uint8Array(o)}async function zn(t){let e=t.params?.msg_type??0;if(e!==sr)throw new ie(`encodeMinimal only supports SAFETY (type 6) messages; got type=${e}`);let r=t.params?.from_rrn??t.target??"",n=t.params?.to_rrn??t.target??"",o=await Qn(r),s=await Qn(n),i=(t.signature?.sig??"").replace(/[^A-Za-z0-9+/=]/g,""),a;try{if(typeof atob<"u"){let M=atob(i.slice(0,16));a=new Uint8Array(M.length);for(let S=0;S<M.length;S++)a[S]=M.charCodeAt(S)}else a=Buffer.from(i.slice(0,16),"base64")}catch{a=new Uint8Array(8)}let p=(t.timestamp?Math.floor(new Date(t.timestamp).getTime()/1e3):Math.floor(Date.now()/1e3))>>>0,g=new Uint8Array(Ye),v=new DataView(g.buffer);v.setUint16(0,sr,!1),g.set(o.subarray(0,8),2),g.set(s.subarray(0,8),10),v.setUint32(18,p,!1);let k=new Uint8Array(8);k.set(a.subarray(0,Math.min(8,a.length))),g.set(k,22);let b=0;for(let M=0;M<30;M++)b^=g[M]??0;if(v.setUint16(30,b&65535,!1),g.length!==Ye)throw new ie(`encodeMinimal assertion failed: expected ${Ye} bytes, got ${g.length}`);return g}function Xn(t){if(t.length!==Ye)throw new ie(`decodeMinimal: expected ${Ye} bytes, got ${t.length}`);let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=e.getUint16(0,!1),n=t.subarray(2,10),o=t.subarray(10,18),s=e.getUint32(18,!1),i=t.subarray(22,30),a=new Date(s*1e3).toISOString(),u=p=>Array.from(p).map(g=>g.toString(16).padStart(2,"0")).join("");return{params:{msg_type:r,from_hash:u(n),to_hash:u(o),timestamp_s:s,sig_truncated:u(i)},timestamp:a}}var $s=251,Je=3;function Zn(t,e=$s){let r=ar(t),n=e-Je;if(n<=0)throw new ie(`MTU ${e} is too small (need at least ${Je+1})`);let o=Math.ceil(r.length/n),s=[];for(let i=0;i<o;i++){let a=r.subarray(i*n,(i+1)*n),u=new Uint8Array(Je+a.length);u[0]=i,u[1]=o,u[2]=i===o-1?1:0,u.set(a,Je),s.push(u)}return s}function eo(t){if(t.length===0)throw new ie("decodeBleFrames: no frames provided");let e=[...t].sort((a,u)=>(a[0]??0)-(u[0]??0)),r=e[0]?.[1]??e.length;if(e.length!==r)throw new ie(`decodeBleFrames: expected ${r} frames, got ${e.length}`);let n=e.map(a=>a.subarray(Je)),o=n.reduce((a,u)=>a+u.length,0),s=new Uint8Array(o),i=0;for(let a of n)s.set(a,i),i+=a.length;return cr(s)}function to(t,e){let n=(e.params?.msg_type??0)===sr,o=s=>t.includes(s);if(n){if(o("minimal"))return"minimal";if(o("ble"))return"ble";if(o("compact"))return"compact";if(o("http"))return"http"}else{if(o("http"))return"http";if(o("compact"))return"compact";if(o("ble"))return"ble"}throw new ie(`No suitable transport available from: [${t.join(", ")}]`)}d();var ur=(r=>(r.BASE64="base64",r.REF="ref",r))(ur||{});function We(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();let t=Array.from({length:16},()=>Math.floor(Math.random()*256));t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let e=t.map(r=>r.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}async function dr(t){let e=globalThis.crypto?.subtle??(await import("crypto")).webcrypto.subtle,r=new ArrayBuffer(t.byteLength);new Uint8Array(r).set(t);let n=await e.digest("SHA-256",r),o=new Uint8Array(n);return Array.from(o).map(s=>s.toString(16).padStart(2,"0")).join("")}function ro(t){if(typeof Buffer<"u")return Buffer.from(t).toString("base64");let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]??0);return btoa(e)}function fr(t,e){let r={...t.toJSON(),...e};return E.fromJSON(r)}async function lr(t,e,r){let n=await dr(e),o=ro(e),s={chunkId:We(),mimeType:r,encoding:"base64",hashSha256:n,dataB64:o,sizeBytes:e.length},i=t.mediaChunks??[];return fr(t,{mediaChunks:[...i,s]})}function no(t,e,r,n,o){let s={chunkId:We(),mimeType:r,encoding:"ref",hashSha256:n,refUrl:e,sizeBytes:o},i=t.mediaChunks??[];return fr(t,{mediaChunks:[...i,s]})}async function oo(t){let e=t.mediaChunks??[];if(e.length===0)return{valid:!0,reason:"no media chunks"};for(let r=0;r<e.length;r++){let n=e[r];if(!n.chunkId)return{valid:!1,reason:`chunk[${r}]: missing chunkId`};if(!n.mimeType)return{valid:!1,reason:`chunk[${r}]: missing mimeType`};if(!n.hashSha256)return{valid:!1,reason:`chunk[${r}]: missing hashSha256`};if(n.sizeBytes<0)return{valid:!1,reason:`chunk[${r}]: sizeBytes must be >= 0`};if(n.encoding==="base64"){if(!n.dataB64)return{valid:!1,reason:`chunk[${r}]: BASE64 encoding requires dataB64`};let o;try{if(typeof Buffer<"u")o=Buffer.from(n.dataB64,"base64");else{let i=atob(n.dataB64);o=new Uint8Array(i.length);for(let a=0;a<i.length;a++)o[a]=i.charCodeAt(a)}}catch{return{valid:!1,reason:`chunk[${r}]: failed to decode base64 data`}}let s=await dr(o);if(s!==n.hashSha256)return{valid:!1,reason:`chunk[${r}]: SHA-256 mismatch (expected ${n.hashSha256}, got ${s})`}}else if(n.encoding==="ref"){if(!n.refUrl)return{valid:!1,reason:`chunk[${r}]: REF encoding requires refUrl`}}else return{valid:!1,reason:`chunk[${r}]: unknown encoding '${n.encoding}'`}}return{valid:!0,reason:"ok"}}async function so(t){let e=new E({rcan:"1.6",rcanVersion:"1.6",cmd:"training_data",target:"rcan://training/data",params:{msg_type:36,msg_id:We()},timestamp:new Date().toISOString()});for(let r of t)e=await lr(e,r.data,r.mimeType);return e}async function io(t,e,r,n,o){let s=await dr(e),i=ro(e),a={chunkId:We(),mimeType:r,encoding:"base64",hashSha256:s,dataB64:i,sizeBytes:e.length},u={streamId:t,chunkIndex:n,isFinal:o,chunk:a},p=new E({rcan:"1.6",rcanVersion:"1.6",cmd:"stream_chunk",target:"rcan://streaming/chunk",params:{msg_type:29,msg_id:We(),stream_chunk:u},timestamp:new Date().toISOString()});return p=fr(p,{mediaChunks:[a]}),p}d();var pr=2.5,js=0;function qs(){return`cr-${Date.now()}-${++js}`}function ao(t={}){return{type:33,request_id:t.request_id??qs(),project_id:t.project_id??"",project_name:t.project_name??"",work_unit_id:t.work_unit_id??"",resource_type:t.resource_type??"cpu",estimated_duration_s:t.estimated_duration_s??0,priority:t.priority??0,payload:t.payload??{},timestamp:t.timestamp??Date.now()/1e3}}function co(t={}){let e={type:34,request_id:t.request_id??"",work_unit_id:t.work_unit_id??"",status:t.status??"completed",resource_type:t.resource_type??"cpu",duration_s:t.duration_s??0,compute_units:t.compute_units??0,result_payload:t.result_payload??{},timestamp:t.timestamp??Date.now()/1e3};return t.error_message!==void 0&&(e.error_message=t.error_message),e}function uo(t={}){return{type:35,request_id:t.request_id??"",work_unit_id:t.work_unit_id??"",reason:t.reason??"",timestamp:t.timestamp??Date.now()/1e3}}function fo(t,e="request"){return e==="request"||e==="result"?t>=pr:e==="cancel"?t>=2:!1}function lo(t){return t>=3}d();var gr=2,Hs=0;function Fs(){return`run-${Date.now()}-${++Hs}`}function po(t={}){return{type:37,competition_id:t.competition_id??"",competition_format:t.competition_format??"sprint",hardware_tier:t.hardware_tier??"",model_id:t.model_id??"",robot_rrn:t.robot_rrn??"",entered_at:t.entered_at??Date.now()/1e3}}function go(t={}){let e=t.score??0;if(e<0||e>1)throw new Error(`score must be in [0.0, 1.0], got ${e}`);return{type:38,competition_id:t.competition_id??"",candidate_id:t.candidate_id??"",score:e,hardware_tier:t.hardware_tier??"",verified:t.verified??!1,submitted_at:t.submitted_at??Date.now()/1e3}}function mo(t={}){return{type:39,season_id:t.season_id??"",class_id:t.class_id??"",standings:t.standings??[],days_remaining:t.days_remaining??0,broadcast_at:t.broadcast_at??Date.now()/1e3}}function ho(t={}){let e=t.score??0;if(e<0||e>1)throw new Error(`score must be in [0.0, 1.0], got ${e}`);return{type:40,run_id:t.run_id??Fs(),run_type:t.run_type??"personal",candidate_id:t.candidate_id??"",score:e,hardware_tier:t.hardware_tier??"",model_id:t.model_id??"",owner_uid:t.owner_uid??"",metrics:t.metrics??{success_rate:0,p66_rate:0,token_efficiency:0,latency_score:0},submitted_to_community:t.submitted_to_community??!1,created_at:t.created_at??Date.now()/1e3}}function yo(t){return t>=gr}d();var Ro="/.well-known/rcan-firmware-manifest.json";function _o(t){let e={rrn:t.rrn,firmware_version:t.firmwareVersion,build_hash:t.buildHash,components:t.components,signed_at:t.signedAt};return t.signature&&(e.signature=t.signature),e}function xo(t){return{rrn:t.rrn,firmwareVersion:t.firmware_version,buildHash:t.build_hash,components:t.components??[],signedAt:t.signed_at??"",signature:t.signature}}function wo(t){let e={build_hash:t.buildHash,components:t.components.map(r=>({hash:r.hash,name:r.name,version:r.version})),firmware_version:t.firmwareVersion,rrn:t.rrn,signed_at:t.signedAt};return JSON.stringify(e)}var Nt=class extends Error{constructor(e){super(e),this.name="FirmwareIntegrityError"}};function bo(t){let e=[];t.rrn||e.push("rrn is required"),t.firmwareVersion||e.push("firmwareVersion is required"),t.buildHash||e.push("buildHash is required"),t.buildHash.startsWith("sha256:")||e.push("buildHash must start with 'sha256:'"),t.signedAt||e.push("signedAt is required"),t.signature||e.push("signature is required (manifest must be signed)");for(let[r,n]of t.components.entries())n.name||e.push(`components[${r}].name is required`),n.version||e.push(`components[${r}].version is required`),n.hash.startsWith("sha256:")||e.push(`components[${r}].hash must start with 'sha256:'`);return e}d();function Ao(t){return{request_id:t.requestId,authority_id:t.authorityId,requested_data:t.requestedData,justification:t.justification,expires_at:t.expiresAt}}function Eo(t){return{requestId:t.request_id,authorityId:t.authority_id,requestedData:t.requested_data??[],justification:t.justification??"",expiresAt:t.expires_at??0}}function mr(t){let e=[];return t.requestId||e.push("requestId is required"),t.authorityId||e.push("authorityId is required"),(!t.requestedData||t.requestedData.length===0)&&e.push("requestedData must include at least one category"),t.justification||e.push("justification is required"),(!t.expiresAt||t.expiresAt<=0)&&e.push("expiresAt must be a positive Unix timestamp"),t.expiresAt<Date.now()/1e3&&e.push("expiresAt is in the past \u2014 request has expired"),e}function So(t){return Date.now()/1e3<t.expiresAt&&mr(t).length===0}var Co={NOT_RECOGNIZED:"AUTHORITY_NOT_RECOGNIZED",REQUEST_EXPIRED:"AUTHORITY_REQUEST_EXPIRED",INVALID_TOKEN:"AUTHORITY_INVALID_TOKEN",RATE_LIMITED:"AUTHORITY_RATE_LIMITED"};d();var hr="https://api.rrf.rcan.dev/v2/revocations",It="rrf.rcan.dev",yr=55e3;var z=class extends Error{constructor(e){super(e),this.name="M2MAuthError"}};function To(t){let e=t.split(".");if(e.length<2)throw new z("Invalid JWT structure");let r=(e[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=r+"=".repeat((4-r.length%4)%4);try{return JSON.parse(atob(n))}catch(o){throw new z(`JWT payload decode failed: ${String(o)}`)}}function ko(t){let e=To(t),r=Number(e.exp??0);if(r>0&&Date.now()/1e3>r)throw new z(`M2M_PEER token expired (sub=${String(e.sub)})`);let n=String(e.peer_rrn??"");if(!n)throw new z("M2M_PEER token missing peer_rrn claim");return{sub:String(e.sub??""),peerRrn:n,scopes:Array.isArray(e.rcan_scopes)?e.rcan_scopes:Array.isArray(e.scopes)?e.scopes:[],exp:r,iss:String(e.iss??"")}}function Rr(t){let e=To(t),r=String(e.iss??"");if(r!==It)throw new z(`M2M_TRUSTED issuer must be '${It}', got '${r}'`);let n=Array.isArray(e.rcan_scopes)?e.rcan_scopes:Array.isArray(e.scopes)?e.scopes:[];if(!n.includes("fleet.trusted"))throw new z("M2M_TRUSTED token missing required 'fleet.trusted' scope");let o=Number(e.exp??0);if(o>0&&Date.now()/1e3>o)throw new z(`M2M_TRUSTED token expired (sub=${String(e.sub)})`);let s=String(e.rrf_sig??"");if(!s)throw new z("M2M_TRUSTED token missing rrf_sig claim");let i=Array.isArray(e.fleet_rrns)?e.fleet_rrns:[];return{sub:String(e.sub??""),fleetRrns:i,scopes:n,exp:o,iss:r,rrfSig:s}}function _r(t,e){let r=Rr(t);if(!r.fleetRrns.includes(e))throw new z(`M2M_TRUSTED token does not authorize commanding '${e}'. Authorized fleet: [${r.fleetRrns.join(", ")}]`);return r}var Ae=null;async function xr(t=hr){let e=Date.now();if(Ae&&e-Ae.fetchedAt<yr)return Ae;try{let n=await(await fetch(t,{signal:AbortSignal.timeout?.(5e3)})).json();Ae={revokedOrchestrators:new Set(n.revoked_orchestrators??[]),revokedJtis:new Set(n.revoked_jtis??[]),fetchedAt:e}}catch{if(Ae)return Ae;Ae={revokedOrchestrators:new Set,revokedJtis:new Set,fetchedAt:e}}return Ae}async function wr(t,e){let r=await xr();return!!(r.revokedOrchestrators.has(t.sub)||e&&r.revokedJtis.has(e))}async function Oo(t,e,r){let n=_r(t,e);if(!r?.skipRevocationCheck&&await wr(n))throw new z(`M2M_TRUSTED orchestrator '${n.sub}' is on the RRF revocation list`);return n}d();function di(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function fi(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=atob(e),n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r.charCodeAt(o);return n}async function Gr(t){if(typeof crypto<"u"&&crypto.subtle){let r=await crypto.subtle.digest("SHA-256",t.buffer);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("").slice(0,8)}let{createHash:e}=ke("crypto");return e("sha256").update(t).digest("hex").slice(0,8)}var qe;async function Jr(){if(qe)return qe;if(typeof ke<"u")try{return qe=(Vr(),cn(Kr)),qe}catch{}try{return qe=await Promise.resolve().then(()=>(Vr(),Kr)),qe}catch{throw new Error("ML-DSA-65 signing requires @noble/post-quantum. Install with: npm install @noble/post-quantum")}}var Ht=class t{keyId;publicKey;secretKey;constructor(e){this.keyId=e.keyId,this.publicKey=e.publicKey,this.secretKey=e.secretKey}static async generate(){let r=(await Jr()).ml_dsa65.keygen(),n=await Gr(r.publicKey);return new t({publicKey:r.publicKey,secretKey:r.secretKey,keyId:n})}static async fromPublicKey(e){let r=await Gr(e);return new t({publicKey:e,keyId:r})}static async fromKeyMaterial(e,r){let n=await Gr(e);return new t({publicKey:e,secretKey:r,keyId:n})}get hasPrivateKey(){return this.secretKey!==void 0}async signBytes(e){if(!this.secretKey)throw new Error("Cannot sign: MLDSAKeyPair has no private key (verify-only)");return(await Jr()).ml_dsa65.sign(e,this.secretKey)}async verifyBytes(e,r){if(!(await Jr()).ml_dsa65.verify(r,e,this.publicKey))throw new Error("ML-DSA-65 signature verification failed")}toString(){return`MLDSAKeyPair(keyId=${this.keyId}, alg=ML-DSA-65, ${this.hasPrivateKey?"private+public":"public-only"})`}};function us(t){let e={rcan:t.rcan,msg_id:t.msgId??"",timestamp:t.timestamp,cmd:t.cmd,target:t.target,params:t.params};return new TextEncoder().encode(JSON.stringify(Object.fromEntries(Object.entries(e).sort())))}async function Yr(t,e){let r=us(t),n=await e.signBytes(r);return t.signature={alg:"ml-dsa-65",kid:e.keyId,sig:di(n)},t}async function Wr(t,e){let r=t.signature;if(!r)throw new Error("Message is unsigned \u2014 signature field missing");if(r.alg!=="ml-dsa-65")throw new Error(`Unsupported signature algorithm: ${r.alg}. RCAN v2.2 requires ml-dsa-65 (Ed25519 is deprecated).`);let n=e.find(s=>s.keyId===r.kid);if(!n)throw new Error(`No trusted ML-DSA-65 key with kid=${r.kid}. Known kids: [${e.map(s=>s.keyId).join(", ")}]`);let o;try{o=fi(r.sig)}catch(s){throw new Error(`Invalid base64url sig: ${s}`)}await n.verifyBytes(us(t),o)}var ds=Yr;async function fs(t,e,r=!0){return Wr(t,e)}var li="0.6.0",pi="1.6";return cn(gi);})();
|