@continuonai/rcan-ts 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.mts +90 -3
- package/dist/browser.mjs +169 -4
- package/dist/browser.mjs.map +1 -1
- package/dist/index.d.mts +90 -3
- package/dist/index.d.ts +90 -3
- package/dist/index.js +173 -5
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +169 -4
- package/dist/index.mjs.map +1 -1
- package/dist/rcan-validate.js +7 -2
- package/dist/rcan.iife.js +16 -3
- package/package.json +28 -5
package/dist/rcan-validate.js
CHANGED
|
@@ -2944,7 +2944,7 @@ var RobotURI = class _RobotURI {
|
|
|
2944
2944
|
};
|
|
2945
2945
|
|
|
2946
2946
|
// src/version.ts
|
|
2947
|
-
var SPEC_VERSION = "2.
|
|
2947
|
+
var SPEC_VERSION = "2.2.0";
|
|
2948
2948
|
|
|
2949
2949
|
// src/message.ts
|
|
2950
2950
|
var RCANMessageError = class extends Error {
|
|
@@ -2984,6 +2984,8 @@ var RCANMessage = class _RCANMessage {
|
|
|
2984
2984
|
firmwareHash;
|
|
2985
2985
|
/** v2.1: URI to sender's SBOM attestation endpoint */
|
|
2986
2986
|
attestationRef;
|
|
2987
|
+
/** v2.2: ML-DSA-65 post-quantum signature (field 16, FIPS 204). Hybrid alongside Ed25519. */
|
|
2988
|
+
pqSig;
|
|
2987
2989
|
constructor(data) {
|
|
2988
2990
|
if (!data.cmd || data.cmd.trim() === "") {
|
|
2989
2991
|
throw new RCANMessageError("'cmd' is required");
|
|
@@ -3014,6 +3016,7 @@ var RCANMessage = class _RCANMessage {
|
|
|
3014
3016
|
this.mediaChunks = data.mediaChunks;
|
|
3015
3017
|
this.firmwareHash = data.firmwareHash;
|
|
3016
3018
|
this.attestationRef = data.attestationRef;
|
|
3019
|
+
this.pqSig = data.pqSig;
|
|
3017
3020
|
if (this.signature !== void 0 && this.signature["sig"] === "pending") {
|
|
3018
3021
|
throw new RCANMessageError(
|
|
3019
3022
|
"signature.sig:'pending' is not valid in RCAN v2.1. Sign the message before sending."
|
|
@@ -3062,6 +3065,7 @@ var RCANMessage = class _RCANMessage {
|
|
|
3062
3065
|
if (this.mediaChunks !== void 0) obj.mediaChunks = this.mediaChunks;
|
|
3063
3066
|
if (this.firmwareHash !== void 0) obj.firmwareHash = this.firmwareHash;
|
|
3064
3067
|
if (this.attestationRef !== void 0) obj.attestationRef = this.attestationRef;
|
|
3068
|
+
if (this.pqSig !== void 0) obj.pqSig = this.pqSig;
|
|
3065
3069
|
return obj;
|
|
3066
3070
|
}
|
|
3067
3071
|
/** Serialize to JSON string */
|
|
@@ -3106,7 +3110,8 @@ var RCANMessage = class _RCANMessage {
|
|
|
3106
3110
|
transportEncoding: obj.transportEncoding,
|
|
3107
3111
|
mediaChunks: obj.mediaChunks,
|
|
3108
3112
|
firmwareHash: obj.firmwareHash,
|
|
3109
|
-
attestationRef: obj.attestationRef
|
|
3113
|
+
attestationRef: obj.attestationRef,
|
|
3114
|
+
pqSig: obj.pqSig
|
|
3110
3115
|
});
|
|
3111
3116
|
}
|
|
3112
3117
|
};
|
package/dist/rcan.iife.js
CHANGED
|
@@ -1,4 +1,17 @@
|
|
|
1
|
-
"use strict";var RCAN=(()=>{var qr=Object.create;var te=Object.defineProperty;var Fr=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Br=Object.getPrototypeOf,Vr=Object.prototype.hasOwnProperty;var re=(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 Kr=(t,e)=>{for(var r in e)te(t,r,{get:e[r],enumerable:!0})},gt=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Hr(e))!Vr.call(t,s)&&s!==r&&te(t,s,{get:()=>e[s],enumerable:!(n=Fr(e,s))||n.enumerable});return t};var ht=(t,e,r)=>(r=t!=null?qr(Br(t)):{},gt(e||!t||!t.__esModule?te(r,"default",{value:t,enumerable:!0}):r,t)),Jr=t=>gt(te({},"__esModule",{value:!0}),t);var Sn={};Kr(Sn,{AUTHORITY_ERROR_CODES:()=>Mr,AuditChain:()=>ae,AuditError:()=>ie,COMPETITION_SCOPE_LEVEL:()=>it,CONTRIBUTE_SCOPE_LEVEL:()=>ot,ClockDriftError:()=>G,CommitmentRecord:()=>F,ConfidenceGate:()=>se,DEFAULT_LOA_POLICY:()=>zt,DataCategory:()=>Be,FIRMWARE_MANIFEST_PATH:()=>wr,FaultCode:()=>Ve,FederationSyncType:()=>Ye,FirmwareIntegrityError:()=>Ne,GateError:()=>N,HiTLGate:()=>oe,KeyStore:()=>Ae,LevelOfAssurance:()=>Yt,M2MAuthError:()=>S,M2M_TRUSTED_ISSUER:()=>ke,MediaEncoding:()=>tt,MessageType:()=>x,NodeClient:()=>ye,OfflineModeManager:()=>Te,PRODUCTION_LOA_POLICY:()=>Qt,QoSAckTimeoutError:()=>_e,QoSLevel:()=>qe,QoSManager:()=>Se,RCANAddressError:()=>ce,RCANConfigAuthorizationError:()=>ge,RCANDelegationChainError:()=>pe,RCANError:()=>_,RCANGateError:()=>ue,RCANMessage:()=>m,RCANMessageError:()=>C,RCANNodeError:()=>q,RCANNodeNotFoundError:()=>k,RCANNodeSyncError:()=>R,RCANNodeTrustError:()=>H,RCANRegistryError:()=>j,RCANReplayAttackError:()=>me,RCANSignatureError:()=>fe,RCANValidationError:()=>de,RCANVersionIncompatibleError:()=>le,RCAN_VERSION:()=>_n,ROLE_JWT_LEVEL:()=>B,RRF_REVOCATION_CACHE_TTL_MS:()=>dt,RRF_REVOCATION_URL:()=>ct,RegistryClient:()=>he,RegistryTier:()=>We,ReplayCache:()=>be,RevocationCache:()=>W,RobotURI:()=>P,RobotURIError:()=>U,Role:()=>D,SAFETY_MESSAGE_TYPE:()=>Fe,SCOPE_MIN_ROLE:()=>Ke,SDK_VERSION:()=>yt,SPEC_VERSION:()=>h,TransportEncoding:()=>Xe,TransportError:()=>w,TrustAnchorCache:()=>Oe,VERSION:()=>Rn,addDelegationHop:()=>St,addMediaInline:()=>st,addMediaRef:()=>fr,assertClockSynced:()=>$t,authorityAccessFromWire:()=>kr,authorityAccessToWire:()=>Nr,canonicalManifestJson:()=>vr,checkClockSync:()=>He,checkRevocation:()=>Ht,decodeBleFrames:()=>cr,decodeCompact:()=>et,decodeMinimal:()=>ir,encodeBleFrames:()=>ar,encodeCompact:()=>Ze,encodeMinimal:()=>or,extractIdentityFromJwt:()=>Zt,extractLoaFromJwt:()=>ve,extractRoleFromJwt:()=>Je,fetchCanonicalSchema:()=>Re,fetchRRFRevocations:()=>lt,isAuthorityRequestValid:()=>Ir,isM2mTrustedRevoked:()=>mt,isPreemptedBy:()=>_r,isSafetyMessage:()=>Mt,makeCloudRelayMessage:()=>_t,makeCompetitionEnter:()=>Sr,makeCompetitionScore:()=>Er,makeConfigUpdate:()=>Lt,makeConsentDeny:()=>xe,makeConsentGrant:()=>we,makeConsentRequest:()=>Ce,makeContributeCancel:()=>yr,makeContributeRequest:()=>gr,makeContributeResult:()=>hr,makeEstopMessage:()=>Nt,makeEstopWithQoS:()=>Ot,makeFaultReport:()=>Wt,makeFederationSync:()=>tr,makeKeyRotationMessage:()=>qt,makePersonalResearchResult:()=>Ar,makeResumeMessage:()=>It,makeRevocationBroadcast:()=>Bt,makeSeasonStanding:()=>br,makeStopMessage:()=>kt,makeStreamChunk:()=>pr,makeTrainingConsentDeny:()=>Jt,makeTrainingConsentGrant:()=>Kt,makeTrainingConsentRequest:()=>Vt,makeTrainingDataMessage:()=>mr,makeTransparencyMessage:()=>Pt,manifestFromWire:()=>Tr,manifestToWire:()=>xr,parseM2mPeerToken:()=>Pr,parseM2mTrustedToken:()=>ut,roleFromJwtLevel:()=>Y,selectTransport:()=>dr,validateAuthorityAccess:()=>at,validateCompetitionScope:()=>Cr,validateConfig:()=>xt,validateConfigAgainstSchema:()=>Tt,validateConfigUpdate:()=>jt,validateConsentMessage:()=>Ft,validateContributeScope:()=>Rr,validateCrossRegistryCommand:()=>rr,validateDelegationChain:()=>Et,validateLoaForScope:()=>er,validateManifest:()=>Or,validateMediaChunks:()=>lr,validateMessage:()=>wt,validateNodeAgainstSchema:()=>vt,validateReplay:()=>Dt,validateRoleForScope:()=>Ge,validateSafetyMessage:()=>Ut,validateTrainingDataMessage:()=>Gt,validateURI:()=>Ct,validateVersionCompat:()=>Rt,verifyM2mTrustedToken:()=>Dr,verifyM2mTrustedTokenClaims:()=>ft});var U=class extends Error{constructor(e){super(e),this.name="RobotURIError"}},P=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 U(`URI must start with 'rcan://' \u2014 got: ${e}`);let n=e.slice(7).split("/");if(n.length!==5)throw new U(`URI must have exactly 5 path segments (registry/manufacturer/model/version/device-id) \u2014 got ${n.length} in: ${e}`);let[s,o,i,a,d]=n;for(let[u,l]of[["registry",s],["manufacturer",o],["model",i],["version",a],["device-id",d]])if(!l||l.trim()==="")throw new U(`URI segment '${u}' must not be empty`);return new t({registry:s,manufacturer:o,model:i,version:a,deviceId:d})}static build(e){let r=e.registry??"registry.rcan.dev",{manufacturer:n,model:s,version:o,deviceId:i}=e;for(let[a,d]of[["manufacturer",n],["model",s],["version",o],["deviceId",i]])if(!d||d.trim()==="")throw new U(`'${a}' must not be empty`);return new t({registry:r,manufacturer:n,model:s,version:o,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}}};var h="2.1.0",yt="1.1.0";function Rt(t,e=h){let r=o=>{let i=o.split("."),a=parseInt(i[0]??"0",10),d=parseInt(i[1]??"0",10);return[isNaN(a)?0:a,isNaN(d)?0:d]},[n]=r(t),[s]=r(e);return n===s}var x=(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))(x||{}),C=class extends Error{constructor(e){super(e),this.name="RCANMessageError"}},m=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;constructor(e){if(!e.cmd||e.cmd.trim()==="")throw new C("'cmd' is required");if(!e.target)throw new C("'target' is required");if(this.rcan=e.rcan??h,this.rcanVersion=e.rcanVersion??h,this.cmd=e.cmd,this.target=e.target instanceof P?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.signature!==void 0&&this.signature.sig==="pending")throw new C("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 C(`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 C("Invalid JSON string")}else r=e;if(!r.cmd)throw new C("Missing required field: 'cmd'");if(!r.target)throw new C("Missing required field: 'target'");if(!r.rcan)throw new C("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})}};function _t(t,e){let r=t.toJSON();return r.senderType="cloud_function",r.cloudProvider=e,new m(r)}function St(t,e){let r=t.delegationChain?[...t.delegationChain,e]:[e],n=t.toJSON();return n.delegationChain=r,new m(n)}function Et(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"}}function ne(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{let{randomUUID:t}=re("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 $e(t,e){return typeof process<"u",Wr(t,e)}function De(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,s=1013904242,o=2773480762,i=1359893119,a=2600822924,d=528734635,u=1541459225,V=t.length*8,A=[...t];for(A.push(128);A.length%64!==56;)A.push(0);for(let y=7;y>=0;y--)A.push(V/Math.pow(2,y*8)&255);for(let y=0;y<A.length;y+=64){let E=[];for(let p=0;p<16;p++)E[p]=A[y+p*4]<<24|A[y+p*4+1]<<16|A[y+p*4+2]<<8|A[y+p*4+3];for(let p=16;p<64;p++){let Ue=T(E[p-15],7)^T(E[p-15],18)^E[p-15]>>>3,Pe=T(E[p-2],17)^T(E[p-2],19)^E[p-2]>>>10;E[p]=E[p-16]+Ue+E[p-7]+Pe>>>0}let[I,K,J,Ie,M,Z,ee,Me]=[r,n,s,o,i,a,d,u];for(let p=0;p<64;p++){let Ue=T(M,6)^T(M,11)^T(M,25),Pe=M&Z^~M&ee,pt=Me+Ue+Pe+e[p]+E[p]>>>0,$r=T(I,2)^T(I,13)^T(I,22),Lr=I&K^I&J^K&J,jr=$r+Lr>>>0;[Me,ee,Z,M,Ie,J,K,I]=[ee,Z,M,Ie+pt>>>0,J,K,I,pt+jr>>>0]}r=r+I>>>0,n=n+K>>>0,s=s+J>>>0,o=o+Ie>>>0,i=i+M>>>0,a=a+Z>>>0,d=d+ee>>>0,u=u+Me>>>0}let g=new Uint8Array(32),O=new DataView(g.buffer);return[r,n,s,o,i,a,d,u].forEach((y,E)=>O.setUint32(E*4,y)),g}function T(t,e){return t>>>e|t<<32-e}function bt(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 Gr(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function Wr(t,e){let n=bt(t);n.length>64&&(n=De(n));let s=new Uint8Array(64),o=new Uint8Array(64);for(let l=0;l<64;l++)s[l]=(n[l]??0)^54,o[l]=(n[l]??0)^92;let i=bt(e),a=new Uint8Array(64+i.length);a.set(s),a.set(i,64);let d=De(a),u=new Uint8Array(96);return u.set(o),u.set(d,64),Gr(De(u))}var N=class extends Error{constructor(e){super(e),this.name="GateError"}},se=class{threshold;constructor(e=.8){if(e<0||e>1)throw new N(`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 N(`Confidence ${e}${n} is below threshold ${this.threshold}`)}}},oe=class{_pending=new Map;request(e,r={}){let n=ne();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 N(`Unknown token: ${e}`);r.status="approved"}deny(e,r){let n=this._pending.get(e);if(!n)throw new N(`Unknown token: ${e}`);n.status="denied",r&&(n.reason=r)}check(e){let r=this._pending.get(e);if(!r)throw new N(`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)}};var ie=class extends Error{constructor(e){super(e),this.name="AuditError"}};function Yr(t,e,r,n,s){let o=JSON.stringify({recordId:t,action:e,robotUri:r,timestamp:n,params:s},Object.keys({recordId:t,action:e,robotUri:r,timestamp:n,params:s}).sort());return $e("rcan-content-hash",o)}function At(t,e){let{hmac:r,...n}=e,s=JSON.stringify(n,Object.keys(n).sort());return $e(t,s)}var F=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 s=ne(),o=new Date().toISOString(),i=e.params??{},a=e.robotUri??"",d=Yr(s,e.action,a,o,i),u={recordId:s,action:e.action,robotUri:a,confidence:e.confidence,modelIdentity:e.modelIdentity,params:i,safetyApproved:e.safetyApproved??!0,timestamp:o,contentHash:d,previousHash:n,hmac:""};return u.hmac=At(r,u),new t(u)}verify(e){return At(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)}},ae=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,s=F.create(e,this._secret,n);return this._records.push(s),s}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 ps=Object.create;var nt=Object.defineProperty;var gs=Object.getOwnPropertyDescriptor;var ms=Object.getOwnPropertyNames;var hs=Object.getPrototypeOf,ys=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 nn=(t,e)=>{for(var r in e)nt(t,r,{get:e[r],enumerable:!0})},on=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ms(e))!ys.call(t,o)&&o!==r&&nt(t,o,{get:()=>e[o],enumerable:!(n=gs(e,o))||n.enumerable});return t};var Kt=(t,e,r)=>(r=t!=null?ps(hs(t)):{},on(e||!t||!t.__esModule?nt(r,"default",{value:t,enumerable:!0}):r,t)),sn=t=>on(nt({},"__esModule",{value:!0}),t);var d=he(()=>{});function Ar(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Sr(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=Ar(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 ko(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 Oo(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Cr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Fs(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Ks(t){for(let e=0;e<t.length;e++)t[e]=Fs(t[e]);return t}function kr(...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 vo(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 No(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 Hs,Tr,Or,Mt=he(()=>{"use strict";d();Hs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;Tr=Hs?t=>t:Ks;Or=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])})});function Io(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}var Mo=he(()=>{"use strict";d();});function Vs(t,e=!1){return e?{h:Number(t&Ut),l:Number(t>>Uo&Ut)}:{h:Number(t>>Uo&Ut)|0,l:Number(t&Ut)|0}}function Po(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}=Vs(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ut,Uo,Lo,Do,Bo,$o,jo=he(()=>{"use strict";d();Ut=BigInt(4294967295),Uo=BigInt(32);Lo=(t,e,r)=>t<<r|e>>>32-r,Do=(t,e,r)=>e<<r|t>>>32-r,Bo=(t,e,r)=>e<<r-32|t>>>64-r,$o=(t,e,r)=>t<<r-32|e>>>64-r});function Zs(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=qo(p,g,1)^r[a],k=Ho(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=Ko[i],u=qo(o,s,a),p=Ho(o,s,a),g=Fo[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]^=Xs[n]}Cr(r)}var Gs,Qe,Js,Ys,Ws,Qs,Fo,Ko,Vo,Go,zs,Xs,qo,Ho,vr,Jo,Yo,X,Nr=he(()=>{"use strict";d();jo();Mt();Gs=BigInt(0),Qe=BigInt(1),Js=BigInt(2),Ys=BigInt(7),Ws=BigInt(256),Qs=BigInt(113),Fo=[],Ko=[],Vo=[];for(let t=0,e=Qe,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Fo.push(2*(5*n+r)),Ko.push((t+1)*(t+2)/2%64);let o=Gs;for(let s=0;s<7;s++)e=(e<<Qe^(e>>Ys)*Qs)%Ws,e&Js&&(o^=Qe<<(Qe<<BigInt(s))-Qe);Vo.push(o)}Go=Po(Vo,!0),zs=Go[0],Xs=Go[1],qo=(t,e,r)=>r>32?Bo(t,e,r):Lo(t,e,r),Ho=(t,e,r)=>r>32?$o(t,e,r):Do(t,e,r);vr=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,Sr(n,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Oo(this.state)}clone(){return this._cloneInto()}keccak(){Tr(this.state32),Zs(this.state32,this.rounds),Tr(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 Sr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ko(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,Cr(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}},Jo=(t,e,r,n={})=>vo((o={})=>new vr(e,t,o.dkLen===void 0?r:o.dkLen,!0),n),Yo=Jo(31,168,16,Or(11)),X=Jo(31,136,32,Or(12))});function Ir(t){if(!Number.isSafeInteger(t)||t<0||t>4294967295)throw new Error("wrong u32 integer:"+t);return t}function Qo(t){return Ir(t),(t&t-1)===0&&t!==0}function Mr(t,e){Ir(t);let r=0;for(let n=0;n<e;n++,t>>>=1)r=r<<1|t&1;return r}function zo(t){return Ir(t),31-Math.clz32(t)}function Wo(t){let e=t.length;if(e<2||!Qo(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=Mr(n,r);if(n<o){let s=t[n];t[n]=t[o],t[o]=s}}return t}var Ur,Xo=he(()=>{"use strict";d();Ur=(t,e)=>{let{N:r,roots:n,dit:o,invertButterflies:s=!1,skipStages:i=0,brp:a=!0}=e,u=zo(r);if(!Qo(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&&Wo(g);for(let v=0,k=1;v<u-i;v++){let b=o?v+1+i:u-v,M=1<<b,E=M>>1,L=r>>b;for(let K=0;K<r;K+=M)for(let _=0,w=k++;_<E;_++){let N=s?o?r-w:w:_*L,I=K+_,D=K+_+E,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&&Wo(g),g}}});function Lr(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 Dr(t){if(typeof t!="object"||t===null||Ar(t))throw new Error("expected opts to be an object")}function Pt(t){Dr(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 Br(t){return(1<<t)-1}function $r(t,e=Zo){if(O(t),O(e),e.length>255)throw new Error("context should be less than 255 bytes");return kr(new Uint8Array([0,e.length]),e,t)}function es(t,e=0){if(!t.oid||!Lr(t.oid.subarray(0,10),ei))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 jr(t,e,r=Zo){if(O(e),O(r),r.length>255)throw new Error("context should be less than 255 bytes");let n=t(e);return kr(new Uint8Array([1,r.length]),r,t.oid,n)}var Pr,Zo,ei,qr=he(()=>{"use strict";d();Mt();Mt();Pr=No;Zo=Uint8Array.of();ei=Uint8Array.from([6,9,96,134,72,1,101,3,4,2])});var ts,rs,Dt,Bt,ns=he(()=>{"use strict";d();Xo();Nr();qr();ts=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=Mr(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=Ur(k,{dit:!1,...b}),E=Ur(k,{dit:!0,...b});return{mod:u,smod:p,nttZetas:v,NTT:{encode:_=>M(_),decode:_=>{E(_);for(let w=0;w<_.length;w++)_[w]=u(o*_[w]);return _}},bitsCoder:(_,w)=>{let N=Br(_),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&Br(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}}}}},rs=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=rs(Yo),Bt=rs(X)});var Vr={};nn(Vr,{PARAMS:()=>qt,ml_dsa44:()=>si,ml_dsa65:()=>ii,ml_dsa87:()=>ai});function os(t){Dr(t),t.externalMu!==void 0&&Io(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 Kr(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(![Hr,Fr].includes(o))throw new Error("Wrong GAMMA2");let M=s*i,E=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=>E(f).r1,K=f=>E(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}=E(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===Hr?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 Wr(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 Qr=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},zr=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}},ds=(f,h)=>{for(let l=0;l<T;l++)f[l]=w(h[l],f[l]);return f},fs=(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}},Xr=32,Zr=ze("seed",32,64,32),se={info:{type:"internal-ml-dsa"},lengths:{secretKey:Pe.bytesLen,publicKey:Te.bytesLen,seed:32,signature:Le.bytesLen,signRand:Xr},keygen:f=>{let h=new Uint8Array(34),l=f===void 0;l&&(f=Pr(32)),O(f,32,"seed"),h.set(f),l&&pe(f),h[32]=e,h[33]=r;let[m,c,A]=Zr.decode(X(h,{dkLen:Zr.bytesLen})),G=k(c),W=[];for(let y=0;y<r;y++)W.push(Wr(G.get(y&255,y>>8&255)));let B=[];for(let y=r;y<r+e;y++)B.push(Wr(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));Se(H,Ee(ue,$[ee]))}F.decode(H);let{r0:ne,r1:Z}=zr(Se(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));Se(j,Ee(ce,B[H]))}F.decode(j),Se(j,A[J]);let{r1:ge}=zr(j);$.push(ge)}return W.clean(),pe(j,B,G,c,A),Te.encode([h,$])},sign:(f,h,l={})=>{Lt(l),os(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?Pr(Xr):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++)Se(Fe,Ee(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(Qr(He)),rt=B.map(C=>Ee(C,tt));for(let C=0;C<r;C++)if(Se(F.decode(rt[C]),ne[C]),Ze(rt[C],n-M))continue e;let en=0,Ft=[];for(let C=0;C<e;C++){let Fe=F.decode(Ee($[C],tt)),_e=is(ee[C],Fe).map(K);if(Ze(_e,o-M))continue e;let tn=F.decode(Ee(j[C],tt));if(Ze(tn,o))continue e;Se(_e,tn);let rn=fs(_e,ue[C]);Ft.push(rn.v),en+=rn.cnt}if(en>a)continue;De.clean();let ls=Le.encode([He,rt,Ft]);return pe(He,rt,Ft,tt,ue,ee,Z,ne,me,H,B,$,j,...J),ls}throw new Error("Unreachable code path reached, report this error")},verify:(f,h,l,m={})=>{os(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(Qr(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=Ee(F.encode(oi(G[y])),ge),Z=re(T);for(let ue=0;ue<r;ue++){let He=$t(me.get(ue,y));Se(Z,Ee(He,H[ue]))}let ee=F.decode(is(Z,ne));ce.push(ds(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 Lr(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=$r(f,l.context),c=se.sign(m,h,l);return pe(m),c},verify:(f,h,l,m={})=>(Pt(m),se.verify(f,$r(h,m.context),l)),prehash:f=>(es(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=jr(f,h,m.context),A=se.sign(c,l,m);return pe(c),A},verify:(h,l,m,c={})=>(Pt(c),se.verify(h,jr(f,l,c.context),m))})}}var T,Ce,ti,ri,Ue,Hr,Fr,qt,re,Me,jt,F,ni,ss,Xe,Se,is,oi,Ze,Ee,si,ii,ai,Gr=he(()=>{"use strict";d();Mo();Nr();ns();qr();T=256,Ce=8380417,ti=1753,ri=8347681,Ue=13,Hr=Math.floor((Ce-1)/88)|0,Fr=Math.floor((Ce-1)/32)|0,qt={2:{K:4,L:4,D:Ue,GAMMA1:2**17,GAMMA2:Hr,TAU:39,ETA:2,OMEGA:80},3:{K:6,L:5,D:Ue,GAMMA1:2**19,GAMMA2:Fr,TAU:49,ETA:4,OMEGA:55},5:{K:8,L:7,D:Ue,GAMMA1:2**19,GAMMA2:Fr,TAU:60,ETA:2,OMEGA:75}},re=t=>new Int32Array(t),{mod:Me,smod:jt,NTT:F,bitsCoder:ni}=ts({N:T,Q:Ce,F:ri,ROOT_OF_UNITY:ti,newPoly:re,isKyber:!1,brvBits:8}),ss=t=>t,Xe=(t,e=ss,r=ss)=>ni(t,{encode:n=>e(r(n)),decode:n=>r(e(n))}),Se=(t,e)=>{for(let r=0;r<t.length;r++)t[r]=Me(t[r]+e[r]);return t},is=(t,e)=>{for(let r=0;r<t.length;r++)t[r]=Me(t[r]-e[r]);return t},oi=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},Ee=(t,e)=>{let r=re(T);for(let n=0;n<t.length;n++)r[n]=Me(t[n]*e[n]);return r};si=Kr({...qt[2],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:32,XOF128:Dt,XOF256:Bt,securityLevel:128}),ii=Kr({...qt[3],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:48,XOF128:Dt,XOF256:Bt,securityLevel:192}),ai=Kr({...qt[5],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:64,XOF128:Dt,XOF256:Bt,securityLevel:256})});var li={};nn(li,{AUTHORITY_ERROR_CODES:()=>So,AuditChain:()=>ct,AuditError:()=>at,COMPETITION_SCOPE_LEVEL:()=>mr,CONTRIBUTE_SCOPE_LEVEL:()=>gr,ClockDriftError:()=>Ke,CommitmentRecord:()=>Be,ConfidenceGate:()=>st,DEFAULT_LOA_POLICY:()=>jn,DataCategory:()=>Xt,FIRMWARE_MANIFEST_PATH:()=>ho,FaultCode:()=>Zt,FederationSyncType:()=>or,FirmwareIntegrityError:()=>Nt,GateError:()=>ye,HiTLGate:()=>it,KeyStore:()=>St,LevelOfAssurance:()=>$n,M2MAuthError:()=>z,M2M_TRUSTED_ISSUER:()=>It,MLDSAKeyPair:()=>Ht,MediaEncoding:()=>dr,MessageType:()=>de,NodeClient:()=>Rt,OfflineModeManager:()=>kt,PRODUCTION_LOA_POLICY:()=>qn,QoSAckTimeoutError:()=>xt,QoSLevel:()=>Wt,QoSManager:()=>wt,RCANAddressError:()=>ut,RCANConfigAuthorizationError:()=>ht,RCANDelegationChainError:()=>mt,RCANError:()=>Q,RCANGateError:()=>ft,RCANMessage:()=>S,RCANMessageError:()=>oe,RCANNodeError:()=>Ne,RCANNodeNotFoundError:()=>Re,RCANNodeSyncError:()=>Y,RCANNodeTrustError:()=>$e,RCANRegistryError:()=>ve,RCANReplayAttackError:()=>gt,RCANSignatureError:()=>lt,RCANValidationError:()=>dt,RCANVersionIncompatibleError:()=>pt,RCAN_VERSION:()=>fi,ROLE_JWT_LEVEL:()=>je,RRF_REVOCATION_CACHE_TTL_MS:()=>Rr,RRF_REVOCATION_URL:()=>yr,RegistryClient:()=>yt,RegistryTier:()=>nr,ReplayCache:()=>At,RevocationCache:()=>Ve,RobotURI:()=>we,RobotURIError:()=>xe,Role:()=>be,SAFETY_MESSAGE_TYPE:()=>Qt,SCOPE_MIN_ROLE:()=>er,SDK_VERSION:()=>an,SPEC_VERSION:()=>q,TransportEncoding:()=>ar,TransportError:()=>ie,TrustAnchorCache:()=>vt,VERSION:()=>di,addDelegationHop:()=>dn,addMediaInline:()=>pr,addMediaRef:()=>to,addPQSignature:()=>cs,assertClockSynced:()=>Tn,authorityAccessFromWire:()=>bo,authorityAccessToWire:()=>wo,canonicalManifestJson:()=>_o,checkClockSync:()=>zt,checkRevocation:()=>In,decodeBleFrames:()=>Xn,decodeCompact:()=>ur,decodeMinimal:()=>Qn,encodeBleFrames:()=>zn,encodeCompact:()=>cr,encodeMinimal:()=>Wn,extractIdentityFromJwt:()=>Fn,extractLoaFromJwt:()=>Ot,extractRoleFromJwt:()=>tr,fetchCanonicalSchema:()=>_t,fetchRRFRevocations:()=>wr,isAuthorityRequestValid:()=>Ao,isM2mTrustedRevoked:()=>br,isPreemptedBy:()=>uo,isSafetyMessage:()=>An,makeCloudRelayMessage:()=>un,makeCompetitionEnter:()=>fo,makeCompetitionScore:()=>lo,makeConfigUpdate:()=>kn,makeConsentDeny:()=>Tt,makeConsentGrant:()=>Ct,makeConsentRequest:()=>Et,makeContributeCancel:()=>ao,makeContributeRequest:()=>so,makeContributeResult:()=>io,makeEstopMessage:()=>xn,makeEstopWithQoS:()=>_n,makeFaultReport:()=>Bn,makeFederationSync:()=>Vn,makeKeyRotationMessage:()=>vn,makePersonalResearchResult:()=>go,makeResumeMessage:()=>bn,makeRevocationBroadcast:()=>Mn,makeSeasonStanding:()=>po,makeStopMessage:()=>wn,makeStreamChunk:()=>oo,makeTrainingConsentDeny:()=>Ln,makeTrainingConsentGrant:()=>Pn,makeTrainingConsentRequest:()=>Un,makeTrainingDataMessage:()=>no,makeTransparencyMessage:()=>En,manifestFromWire:()=>Ro,manifestToWire:()=>yo,parseM2mPeerToken:()=>Co,parseM2mTrustedToken:()=>_r,roleFromJwtLevel:()=>Ge,selectTransport:()=>Zn,validateAuthorityAccess:()=>hr,validateCompetitionScope:()=>mo,validateConfig:()=>hn,validateConfigAgainstSchema:()=>yn,validateConfigUpdate:()=>On,validateConsentMessage:()=>Nn,validateContributeScope:()=>co,validateCrossRegistryCommand:()=>Gn,validateDelegationChain:()=>fn,validateLoaForScope:()=>Kn,validateManifest:()=>xo,validateMediaChunks:()=>ro,validateMessage:()=>mn,validateNodeAgainstSchema:()=>Rn,validateReplay:()=>Cn,validateRoleForScope:()=>rr,validateSafetyMessage:()=>Sn,validateTrainingDataMessage:()=>Dn,validateURI:()=>gn,validateVersionCompat:()=>cn,verifyM2mTrustedToken:()=>To,verifyM2mTrustedTokenClaims:()=>xr,verifyPQSignature:()=>us});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",an="1.2.0";function cn(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"}},S=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),this.pqSig!==void 0&&(e.pqSig=this.pqSig),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 un(t,e){let r=t.toJSON();return r.senderType="cloud_function",r.cloudProvider=e,new S(r)}function dn(t,e){let r=t.delegationChain?[...t.delegationChain,e]:[e],n=t.toJSON();return n.delegationChain=r,new S(n)}function fn(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 Gt(t,e){return typeof process<"u",_s(t,e)}function Vt(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 E=7;E>=0;E--)k.push(v/Math.pow(2,E*8)&255);for(let E=0;E<k.length;E+=64){let L=[];for(let R=0;R<16;R++)L[R]=k[E+R*4]<<24|k[E+R*4+1]<<16|k[E+R*4+2]<<8|k[E+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((E,L)=>M.setUint32(L*4,E)),b}function fe(t,e){return t>>>e|t<<32-e}function ln(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 Rs(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function _s(t,e){let n=ln(t);n.length>64&&(n=Vt(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=ln(e),a=new Uint8Array(64+i.length);a.set(o),a.set(i,64);let u=Vt(a),p=new Uint8Array(96);return p.set(s),p.set(u,64),Rs(Vt(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 xs(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 Gt("rcan-content-hash",s)}function pn(t,e){let{hmac:r,...n}=e,o=JSON.stringify(n,Object.keys(n).sort());return Gt(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=xs(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=pn(r,p),new t(p)}verify(e){return pn(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
|
-
`}static fromJSONL(e,r){let n=new t(r),
|
|
4
|
-
`).filter(o=>o.trim()!=="");for(let o of s){let i=JSON.parse(o);n._records.push(F.fromJSON(i))}return n}};function Le(){return{ok:!0,issues:[],warnings:[],info:[]}}function v(t,e){t.ok=!1,t.issues.push(e)}function L(t,e){t.warnings.push(e)}function b(t,e){t.info.push(e)}function Ct(t){let e=Le();try{let r=P.parse(t);b(e,"\u2705 Valid RCAN URI"),b(e,` Registry: ${r.registry}`),b(e,` Manufacturer: ${r.manufacturer}`),b(e,` Model: ${r.model}`),b(e,` Version: ${r.version}`),b(e,` Device ID: ${r.deviceId}`)}catch(r){v(e,`Invalid RCAN URI: ${r instanceof Error?r.message:r}`)}return e}function wt(t){let e=Le(),r;if(typeof t=="string")try{r=JSON.parse(t)}catch{return v(e,"Invalid JSON string"),e}else if(typeof t=="object"&&t!==null)r=t;else return v(e,"Expected object or JSON string"),e;for(let n of["rcan","cmd","target"])(!(n in r)||!r[n])&&v(e,`Missing required field: '${n}'`);if(!e.ok)return e;try{let n=m.fromJSON(r);b(e,`\u2705 RCAN message valid (v${n.rcan})`),b(e,` cmd: ${n.cmd}`),b(e,` target: ${n.target}`),n.confidence!==void 0?b(e,` confidence: ${n.confidence}`):L(e,"No confidence score \u2014 add for RCAN \xA716 AI accountability"),n.isSigned?b(e,` signature: alg=${n.signature?.alg}, kid=${n.signature?.kid}`):L(e,"Message is unsigned (recommended for production)")}catch(n){v(e,`Message validation failed: ${n instanceof Error?n.message:n}`)}return e}function xt(t){let e=Le(),r=t.metadata??{},n=t.agent??{},s=t.rcan_protocol??{};for(let i of["rcan_version","metadata","agent"])(!(i in t)||t[i]===void 0||t[i]===null)&&v(e,`Missing required key: '${i}'`);let o=t.rcan_version;if(o&&(/^\d+\.\d+$/.test(o)||v(e,`rcan_version '${o}' must match pattern N.N (e.g. '1.2')`)),r.manufacturer||v(e,"L1: metadata.manufacturer is required (\xA72)"),r.model||v(e,"L1: metadata.model is required (\xA72)"),!r.device_id&&!r.robot_name&&v(e,"L1: metadata.device_id (or robot_name) is required (\xA72)"),s.jwt_auth?.enabled||L(e,"L2: jwt_auth not enabled (required for L2 conformance, \xA78)"),(!n.confidence_gates||n.confidence_gates.length===0)&&L(e,"L2: confidence_gates not configured (\xA716)"),(!n.hitl_gates||n.hitl_gates.length===0)&&L(e,"L3: hitl_gates not configured (\xA716)"),n.commitment_chain?.enabled||L(e,"L3: commitment_chain not enabled (\xA716)"),r.rrn?b(e,`\u2705 RRN registered: ${r.rrn}`):L(e,"Robot not registered \u2014 visit rcan.dev/registry/register"),e.ok&&e.issues.length===0){let i=!e.warnings.some(l=>l.startsWith("L1")),a=i&&!e.warnings.some(l=>l.startsWith("L2")),u=a&&!e.warnings.some(l=>l.startsWith("L3"))?"L3":a?"L2":i?"L1":"FAIL";b(e,`\u2705 Config valid \u2014 conformance level: ${u}`)}return e}var _=class extends Error{constructor(e){super(e),this.name="RCANError",Object.setPrototypeOf(this,new.target.prototype)}},ce=class extends _{constructor(e){super(e),this.name="RCANAddressError",Object.setPrototypeOf(this,new.target.prototype)}},de=class extends _{constructor(e){super(e),this.name="RCANValidationError",Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends _{constructor(r,n,s,o){super(r);this.gateType=n;this.value=s;this.threshold=o;this.name="RCANGateError",Object.setPrototypeOf(this,new.target.prototype)}},fe=class extends _{constructor(e){super(e),this.name="RCANSignatureError",Object.setPrototypeOf(this,new.target.prototype)}},j=class extends _{constructor(e){super(e),this.name="RCANRegistryError",Object.setPrototypeOf(this,new.target.prototype)}},q=class t extends _{constructor(r,n){super(r);this.nodeUrl=n;this.name="RCANNodeError",Object.setPrototypeOf(this,t.prototype)}},k=class t extends q{constructor(r,n){super(`RRN not found in federation: ${r}`,n);this.rrn=r;this.name="RCANNodeNotFoundError",Object.setPrototypeOf(this,t.prototype)}},R=class t extends q{constructor(r,n,s){super(r,n);this.cause=s;this.name="RCANNodeSyncError",Object.setPrototypeOf(this,t.prototype)}},H=class t extends q{reason;constructor(e,r){super(`Node trust verification failed: ${e}`,r),this.name="RCANNodeTrustError",this.reason=e,Object.setPrototypeOf(this,t.prototype)}},le=class t extends _{constructor(e,r){super(`VERSION_INCOMPATIBLE: incoming=${e}, local=${r}`),this.name="RCANVersionIncompatibleError",Object.setPrototypeOf(this,t.prototype)}},me=class t extends _{constructor(e){super(`REPLAY_DETECTED: ${e}`),this.name="RCANReplayAttackError",Object.setPrototypeOf(this,t.prototype)}},pe=class t extends _{constructor(e){super(`DELEGATION_CHAIN_ERROR: ${e}`),this.name="RCANDelegationChainError",Object.setPrototypeOf(this,t.prototype)}},ge=class t extends _{constructor(e){super(`CONFIG_AUTH_ERROR: ${e}`),this.name="RCANConfigAuthorizationError",Object.setPrototypeOf(this,t.prototype)}};var zr="https://rcan-spec.pages.dev",he=class{baseUrl;apiKey;timeout;constructor(e){this.baseUrl=(e?.baseUrl??zr).replace(/\/$/,""),this.apiKey=e?.apiKey,this.timeout=e?.timeout??1e4}async _fetch(e,r={}){let n=`${this.baseUrl}${e}`,s=new AbortController,o=setTimeout(()=>s.abort(),this.timeout);try{return await fetch(n,{...r,signal:s.signal,headers:{"Content-Type":"application/json",...r.headers??{}}})}finally{clearTimeout(o)}}_authHeaders(){if(!this.apiKey)throw new j("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 j(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}`:"",s=await this._fetch(`/api/v1/robots${n}`);return this._checkResponse(s)}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}`:"",s=await this._fetch(`/api/v1/robots/search${n}`);if(!s.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 o=await s.json();return Array.isArray(o)?o:"results"in o&&o.results?o.results:"robots"in o?o.robots:[]}};var Qr="https://rcan.dev",Xr="/.well-known/rcan-node.json",Zr=new Set(["root","authoritative","resolver","cache"]);function en(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 ye=class{rootUrl;timeoutMs;constructor(e=Qr,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(s){throw s instanceof Error&&s.name==="AbortError"?new R(`Request timed out: ${e}`,e,s):new R(`Network error fetching ${e}: ${s.message}`,e,s instanceof Error?s:void 0)}finally{clearTimeout(n)}}async getNodeManifest(e){let r=`${e.replace(/\/$/,"")}${Xr}`,n=await this._fetch(r);if(!n.ok)throw n.status===404?new k(r,e):new R(`Failed to fetch node manifest from ${e}: HTTP ${n.status}`,e);let s;try{s=await n.json()}catch(o){throw new R(`Invalid JSON in node manifest from ${e}`,e,o instanceof Error?o:void 0)}if(!this.verifyNode(s))throw new H("missing_pubkey",e);return s}async listNodes(e){let r=e?`?prefix=${encodeURIComponent(e)}`:"",n=`${this.rootUrl}/api/v1/nodes${r}`,s=await this._fetch(n);if(!s.ok)throw new R(`Failed to list nodes from ${n}: HTTP ${s.status}`,n);let o;try{o=await s.json()}catch(i){throw new R(`Invalid JSON in nodes list from ${n}`,n,i instanceof Error?i:void 0)}return Array.isArray(o)?o:o&&typeof o=="object"&&"nodes"in o?o.nodes:[]}async discover(e){let r=en(e);if(!r)throw new k(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 k(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 R(`Invalid JSON in resolve response for ${e}`,this.rootUrl,a instanceof Error?a:void 0)}if(n.status!==404)throw new R(`Unexpected HTTP ${n.status} resolving ${e}`,this.rootUrl);let s=await this.discover(e),o=`${s.api_base.replace(/\/$/,"")}/robots/${encodeURIComponent(e)}`,i=await this._fetch(o);if(!i.ok)throw i.status===404?new k(e,s.api_base):new R(`HTTP ${i.status} from authoritative node for ${e}`,s.api_base);try{return await i.json()}catch(a){throw new R(`Invalid JSON in fallback resolve response for ${e}`,s.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"||!Zr.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://"))}};var tn="https://rcan.dev/schemas",je=new Map;async function Re(t){if(je.has(t))return je.get(t);try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);r.unref?.();let n=await fetch(`${tn}/${t}`,{signal:e.signal});if(clearTimeout(r),!n.ok)return null;let s=await n.json();return je.set(t,s),s}catch{return null}}async function Tt(t){let e=await Re("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,s=e.required??[];for(let o of s)o in n||r.push(`Missing required field: ${o}`);return r.length===0?{valid:!0}:{valid:!1,errors:r}}async function vt(t){let e=await Re("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,s=e.required??[];for(let o of s)o in n||r.push(`Missing required field: ${o}`);return r.length===0?{valid:!0}:{valid:!1,errors:r}}var qe=(n=>(n[n.FIRE_AND_FORGET=0]="FIRE_AND_FORGET",n[n.ACKNOWLEDGED=1]="ACKNOWLEDGED",n[n.EXACTLY_ONCE=2]="EXACTLY_ONCE",n))(qe||{}),_e=class t extends Error{constructor(e){super(`ACK timeout for message ${e} \u2014 safety halt required`),this.name="QoSAckTimeoutError",Object.setPrototypeOf(this,t.prototype)}},Se=class{_send;_waitForAck;constructor(e,r){this._send=e,this._waitForAck=r}async sendWithQoS(e,r={}){let n=r.qos??0,s=r.maxRetries??3,o=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",d=0,u=o;for(;d<=s;){if(await this._send(e),d++,await this._waitForAck(a,i))return{delivered:!0,attempts:d,reason:n===2?"exactly-once":"acknowledged"};if(d>s)break;await nn(u),u=Math.min(u*2,5e3)}return{delivered:!1,attempts:d,reason:`ACK not received after ${s} retries`}}};function Ot(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:rn(),qos:2}}function rn(){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 nn(t){return new Promise(e=>setTimeout(e,t))}var Fe=6;function Ee(){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 Nt(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:Ee(),qos:2}}function kt(t,e){return{message_type:6,ruri:t,safety_event:"STOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:Ee()}}function It(t,e){return{message_type:6,ruri:t,safety_event:"RESUME",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:Ee()}}function Mt(t){return typeof t=="object"&&t!==null&&t.message_type===Fe}function Ut(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 Pt(t,e,r){return{message_type:11,ruri:t,disclosure:e,timestamp_ms:Date.now(),message_id:Ee(),delegation_chain:r}}var be=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 s=Date.now();this._evict(s);let o=n?Math.min(this.windowSeconds,10):this.windowSeconds,i=sn(r);if(i===null)return{allowed:!1,reason:`invalid timestamp format: ${r}`};let a=s-i,d=o*1e3;if(a>d)return{allowed:!1,reason:`message too old: age=${Math.round(a/1e3)}s > window=${o}s`};if(i>s+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 l=this._seen.keys().next().value;this._seen.delete(l)}let u=s+d;return this._seen.set(e,u),{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 Dt(t,e){let r=t,n=r.message_id??r.msg_id;if(!n)return{valid:!1,reason:"missing message_id / msg_id"};let s;if(typeof r.timestamp_ms=="number"?s=String(r.timestamp_ms/1e3):r.timestamp!==void 0&&(s=String(r.timestamp)),!s)return{valid:!1,reason:"missing timestamp"};let o=r.message_type===6||r.message_type===6,i=e.checkAndRecord(n,s,o);return{valid:i.allowed,reason:i.reason}}function sn(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}var G=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 He(t){let e=t??"https://worldtimeapi.org/api/ip";try{let r=Date.now(),n=await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(3e3)}),s=Date.now(),o=n.headers.get("Date")??n.headers.get("date");if(!o)return{synchronized:!0,offsetSeconds:0,source:"assumed (no Date header)"};let i=new Date(o).getTime();if(isNaN(i))return{synchronized:!0,offsetSeconds:0,source:"assumed (unparseable Date header)"};let d=((r+s)/2-i)/1e3;return{synchronized:Math.abs(d)<=5,offsetSeconds:d,source:e}}catch{return{synchronized:!0,offsetSeconds:0,source:"assumed (network unavailable)"}}}async function $t(t=5){let e=await He();if(!e.synchronized||Math.abs(e.offsetSeconds)>t)throw new G(e.offsetSeconds,t)}async function on(t){let e=JSON.stringify(t,Object.keys(t).sort());if(typeof crypto<"u"&&crypto.subtle){let n=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",n);return Array.from(new Uint8Array(s)).map(o=>o.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 Lt(t,e,r,n="rcan://local/config",s=!1){let o=await on(t);return new m({rcan:h,cmd:"CONFIG_UPDATE",target:n,params:{message_type:5,diff:t,rollback:r,scope:e,config_hash:o,safety_overrides:s}})}function jt(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"}}function an(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}var Ae=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 s=(r??Date.now())/1e3;return!(n.revoked_at!==void 0&&n.revoked_at<=s||n.exp!==void 0&&n.exp<s)}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 qt(t,e,r=120,n="rcan://local/keys"){let s=an().slice(0,8);return new m({rcan:h,cmd:"KEY_ROTATION",target:n,params:{message_type:5,new_public_key:t,new_kid:s,old_kid:e,overlap_seconds:r,initiated_at:new Date().toISOString()},keyId:s})}function cn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function Ce(t){let e=t.requestId??cn();return new m({rcan:h,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 we(t){let e=t.expiresAt??new Date(Date.now()+864e5).toISOString();return new m({rcan:h,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 xe(t){return new m({rcan:h,cmd:"CONSENT_DENY",target:"rcan://local/consent",params:{message_type:22,request_id:t.requestId,reason:t.reason??"denied"}})}function Ft(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}`}}var dn=3600*1e3,W=class{_cache=new Map;get(e,r){let n=this._cache.get(e);if(!n)return;let s=r??Date.now();if(n.cachedUntil!==void 0&&n.cachedUntil<s){this._cache.delete(e);return}return n}set(e,r){let n=r??Date.now();this._cache.set(e.rrn,{...e,cachedUntil:n+dn})}invalidate(e){this._cache.delete(e)}get size(){return this._cache.size}};async function Ht(t,e,r){let n=r??new W,s=n.get(t);if(s)return s;let o=`${e.replace(/\/$/,"")}/api/v1/robots/${encodeURIComponent(t)}/revocation-status`;try{let i=await fetch(o,{signal:AbortSignal.timeout(5e3)});if(!i.ok){let u={rrn:t,status:"active",reason:`registry returned ${i.status}`};return n.set(u),u}let a=await i.json(),d={rrn:t,status:a.status??"active",revokedAt:a.revokedAt,reason:a.reason,authority:a.authority};return n.set(d),d}catch{return{rrn:t,status:"active",reason:"network unavailable"}}}function Bt(t,e){return new m({rcan:h,cmd:"ROBOT_REVOCATION",target:"rcan://broadcast/revocation",params:{message_type:19,rrn:t,reason:e,revoked_at:new Date().toISOString()}})}var Be=(o=>(o.VIDEO="video",o.AUDIO="audio",o.LOCATION="location",o.BIOMETRIC="biometric",o.TELEMETRY="telemetry",o))(Be||{});function Vt(t){return Ce({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 Kt(t){return we(t)}function Jt(t){return xe(t)}function Gt(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"}}var Te=class{crossOwnerGraceS;keyTtlS;_cachedKeys=[];constructor(e=3600,r=86400){this.crossOwnerGraceS=e,this.keyTtlS=r}canAcceptCommand(e,r,n,s=!0,o=!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(!s)return{allowed:!1,reason:"offline mode: only owner-role commands accepted from local network"};if(o&&i!==void 0){let u=((a??Date.now())-i)/1e3;if(u>this.crossOwnerGraceS)return{allowed:!1,reason:`offline mode: cross-owner grace period expired (${Math.round(u)}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(s=>s.kid!==e.kid),this._cachedKeys.push({...e,cachedAtMs:n,ttlSeconds:this.keyTtlS})}getCachedKey(e,r){let n=r??Date.now(),s=this._cachedKeys.find(i=>i.kid===e);if(!s)return;if((n-s.cachedAtMs)/1e3>s.ttlSeconds){this._cachedKeys=this._cachedKeys.filter(i=>i.kid!==e);return}return s}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)}}};var Ve=(g=>(g.SENSOR_PROXIMITY_FAILURE="SENSOR_PROXIMITY_FAILURE",g.SENSOR_CAMERA_FAILURE="SENSOR_CAMERA_FAILURE",g.SENSOR_IMU_FAILURE="SENSOR_IMU_FAILURE",g.MOTOR_OVERCURRENT="MOTOR_OVERCURRENT",g.MOTOR_OVERTEMP="MOTOR_OVERTEMP",g.MOTOR_STALL="MOTOR_STALL",g.BATTERY_CRITICAL="BATTERY_CRITICAL",g.BATTERY_LOW="BATTERY_LOW",g.NETWORK_TIMEOUT="NETWORK_TIMEOUT",g.NETWORK_REGISTRY_UNREACHABLE="NETWORK_REGISTRY_UNREACHABLE",g.SAFETY_ESTOP_STUCK="SAFETY_ESTOP_STUCK",g.SAFETY_WATCHDOG_TIMEOUT="SAFETY_WATCHDOG_TIMEOUT",g.UNKNOWN="UNKNOWN",g))(Ve||{});function Wt(t){return new m({rcan:h,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()}})}var D=(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))(D||{}),Yt=D,B={1:1,2:2,3:2.5,4:3,5:4,6:5,7:6},un=new Map(Object.entries(B).map(([t,e])=>[e,Number(t)]));function Y(t){return un.get(t)}var Ke={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 zt={minRoleForDiscover:1,minRoleForStatus:1,minRoleForChat:1,minRoleForControl:1,minRoleForSafety:1},Qt={minRoleForDiscover:1,minRoleForStatus:1,minRoleForChat:1,minRoleForControl:2,minRoleForSafety:6};function Xt(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 Je(t){let e=Xt(t);if(!e)return 1;let r=e.rcan_role;if(r!=null){let s=Y(Number(r));if(s!==void 0)return s}let n=e.loa;if(n!=null){let s=Y(Number(n));if(s!==void 0)return s}return 1}function ve(t){return Je(t)}function Zt(t){let e=Xt(t);if(!e)return{sub:"",role:1,jwtLevel:1,scopes:[]};let r=e.rcan_role,n=e.loa,s=r!==void 0?Number(r):n!==void 0?Number(n):1,o=Y(s)??1,i=Array.isArray(e.rcan_scopes)?e.rcan_scopes:Array.isArray(e.scopes)?e.scopes:[];return{sub:String(e.sub??""),role:o,jwtLevel:B[o],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 Ge(t,e){let r=Ke[e.toLowerCase()];return r===void 0?t>=2?{ok:!0,reason:""}:{ok:!1,reason:`Unknown scope '${e}': applying OPERATOR minimum. Caller has ${D[t]}.`}:t>=r?{ok:!0,reason:""}:{ok:!1,reason:`Scope '${e}' requires ${D[r]} (JWT level ${B[r]}), but caller has ${D[t]} (JWT level ${B[t]})`}}function er(t,e){return Ge(t,e)}var We=(n=>(n.ROOT="root",n.AUTHORITATIVE="authoritative",n.COMMUNITY="community",n))(We||{}),Ye=(n=>(n.CONSENT="consent",n.REVOCATION="revocation",n.KEY="key",n))(Ye||{}),fn=1440*60*1e3,Oe=class{store=new Map;set(e){this.store.set(e.registryUrl,{identity:e,expiresAt:Date.now()+fn})}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 re("dns").promises.resolveTxt(r)}catch{return}for(let s of n){let o=s.join("");try{let i=JSON.parse(o);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 s;try{let i=(e.split(".")[1]??"").replace(/-/g,"+").replace(/_/g,"/"),a=i+"=".repeat((4-i.length%4)%4),d;typeof atob<"u"?d=atob(a):d=Buffer.from(a,"base64").toString("utf-8");let u=JSON.parse(d);s=typeof u.iss=="string"?u.iss:void 0}catch{throw new Error("REGISTRY_JWT_MALFORMED: cannot decode token payload")}if(s!==r)throw new Error(`REGISTRY_JWT_ISS_MISMATCH: expected iss=${r}, got iss=${s??"(none)"}`);return n}};function ln(){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 tr(t,e,r,n){return new m({rcan:"2.1.0",rcanVersion:"2.1.0",cmd:"federation_sync",target:e,params:{msg_type:23,msg_id:ln(),source_registry:t,target_registry:e,sync_type:r,payload:n},timestamp:new Date().toISOString()})}async function rr(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 o=t.params?.source_registry??t.params?.from_registry;if(!o||o===e)return{valid:!0,reason:"local registry; no federation check needed"};if(!r.lookup(o))return{valid:!1,reason:`REGISTRY_UNKNOWN: ${o} is not in the local trust cache`};let a=1,d=t.params?.registry_jwt;return d?a=ve(d):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"}}var w=class t extends Error{constructor(e){super(e),this.name="TransportError",Object.setPrototypeOf(this,t.prototype)}},Xe=(s=>(s.HTTP="http",s.COMPACT="compact",s.MINIMAL="minimal",s.BLE="ble",s))(Xe||{}),ze={msg_type:"t",msg_id:"i",timestamp:"ts",from_rrn:"f",to_rrn:"to",scope:"s",payload:"p",signature:"sig"},nr=Object.fromEntries(Object.entries(ze).map(([t,e])=>[e,t]));function Ze(t){let e=t.toJSON(),r={};for(let[o,i]of Object.entries(e)){let a=ze[o];r[a??o]=i}if(r.p&&typeof r.p=="object"){let o=r.p,i={};for(let[a,d]of Object.entries(o)){let u=ze[a];i[u??a]=d}r.p=i}let n=JSON.stringify(r);return new TextEncoder().encode(n)}function et(t){let r=new TextDecoder().decode(t),n=JSON.parse(r),s={};for(let[o,i]of Object.entries(n)){let a=nr[o];s[a??o]=i}if(s.payload&&typeof s.payload=="object"){let o=s.payload,i={};for(let[a,d]of Object.entries(o)){let u=nr[a];i[u??a]=d}s.payload=i}return new m({rcan:s.rcan??"1.6",rcanVersion:s.rcanVersion,cmd:s.cmd,target:s.target,params:s.params??s.payload??{},timestamp:s.timestamp,confidence:s.confidence,signature:s.signature})}var Q=32,Qe=6;async function sr(t){let e=new TextEncoder().encode(t),r=new ArrayBuffer(e.byteLength);new Uint8Array(r).set(e);let s=await(globalThis.crypto?.subtle??(await import("crypto")).webcrypto.subtle).digest("SHA-256",r);return new Uint8Array(s)}async function or(t){let e=t.params?.msg_type??0;if(e!==Qe)throw new w(`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??"",s=await sr(r),o=await sr(n),i=(t.signature?.sig??"").replace(/[^A-Za-z0-9+/=]/g,""),a;try{if(typeof atob<"u"){let O=atob(i.slice(0,16));a=new Uint8Array(O.length);for(let y=0;y<O.length;y++)a[y]=O.charCodeAt(y)}else a=Buffer.from(i.slice(0,16),"base64")}catch{a=new Uint8Array(8)}let u=(t.timestamp?Math.floor(new Date(t.timestamp).getTime()/1e3):Math.floor(Date.now()/1e3))>>>0,l=new Uint8Array(Q),V=new DataView(l.buffer);V.setUint16(0,Qe,!1),l.set(s.subarray(0,8),2),l.set(o.subarray(0,8),10),V.setUint32(18,u,!1);let A=new Uint8Array(8);A.set(a.subarray(0,Math.min(8,a.length))),l.set(A,22);let g=0;for(let O=0;O<30;O++)g^=l[O]??0;if(V.setUint16(30,g&65535,!1),l.length!==Q)throw new w(`encodeMinimal assertion failed: expected ${Q} bytes, got ${l.length}`);return l}function ir(t){if(t.length!==Q)throw new w(`decodeMinimal: expected ${Q} bytes, got ${t.length}`);let e=new DataView(t.buffer,t.byteOffset,t.byteLength),r=e.getUint16(0,!1),n=t.subarray(2,10),s=t.subarray(10,18),o=e.getUint32(18,!1),i=t.subarray(22,30),a=new Date(o*1e3).toISOString(),d=u=>Array.from(u).map(l=>l.toString(16).padStart(2,"0")).join("");return{params:{msg_type:r,from_hash:d(n),to_hash:d(s),timestamp_s:o,sig_truncated:d(i)},timestamp:a}}var mn=251,z=3;function ar(t,e=mn){let r=Ze(t),n=e-z;if(n<=0)throw new w(`MTU ${e} is too small (need at least ${z+1})`);let s=Math.ceil(r.length/n),o=[];for(let i=0;i<s;i++){let a=r.subarray(i*n,(i+1)*n),d=new Uint8Array(z+a.length);d[0]=i,d[1]=s,d[2]=i===s-1?1:0,d.set(a,z),o.push(d)}return o}function cr(t){if(t.length===0)throw new w("decodeBleFrames: no frames provided");let e=[...t].sort((a,d)=>(a[0]??0)-(d[0]??0)),r=e[0]?.[1]??e.length;if(e.length!==r)throw new w(`decodeBleFrames: expected ${r} frames, got ${e.length}`);let n=e.map(a=>a.subarray(z)),s=n.reduce((a,d)=>a+d.length,0),o=new Uint8Array(s),i=0;for(let a of n)o.set(a,i),i+=a.length;return et(o)}function dr(t,e){let n=(e.params?.msg_type??0)===Qe,s=o=>t.includes(o);if(n){if(s("minimal"))return"minimal";if(s("ble"))return"ble";if(s("compact"))return"compact";if(s("http"))return"http"}else{if(s("http"))return"http";if(s("compact"))return"compact";if(s("ble"))return"ble"}throw new w(`No suitable transport available from: [${t.join(", ")}]`)}var tt=(r=>(r.BASE64="base64",r.REF="ref",r))(tt||{});function X(){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 rt(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),s=new Uint8Array(n);return Array.from(s).map(o=>o.toString(16).padStart(2,"0")).join("")}function ur(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 nt(t,e){let r={...t.toJSON(),...e};return m.fromJSON(r)}async function st(t,e,r){let n=await rt(e),s=ur(e),o={chunkId:X(),mimeType:r,encoding:"base64",hashSha256:n,dataB64:s,sizeBytes:e.length},i=t.mediaChunks??[];return nt(t,{mediaChunks:[...i,o]})}function fr(t,e,r,n,s){let o={chunkId:X(),mimeType:r,encoding:"ref",hashSha256:n,refUrl:e,sizeBytes:s},i=t.mediaChunks??[];return nt(t,{mediaChunks:[...i,o]})}async function lr(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 s;try{if(typeof Buffer<"u")s=Buffer.from(n.dataB64,"base64");else{let i=atob(n.dataB64);s=new Uint8Array(i.length);for(let a=0;a<i.length;a++)s[a]=i.charCodeAt(a)}}catch{return{valid:!1,reason:`chunk[${r}]: failed to decode base64 data`}}let o=await rt(s);if(o!==n.hashSha256)return{valid:!1,reason:`chunk[${r}]: SHA-256 mismatch (expected ${n.hashSha256}, got ${o})`}}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 mr(t){let e=new m({rcan:"1.6",rcanVersion:"1.6",cmd:"training_data",target:"rcan://training/data",params:{msg_type:36,msg_id:X()},timestamp:new Date().toISOString()});for(let r of t)e=await st(e,r.data,r.mimeType);return e}async function pr(t,e,r,n,s){let o=await rt(e),i=ur(e),a={chunkId:X(),mimeType:r,encoding:"base64",hashSha256:o,dataB64:i,sizeBytes:e.length},d={streamId:t,chunkIndex:n,isFinal:s,chunk:a},u=new m({rcan:"1.6",rcanVersion:"1.6",cmd:"stream_chunk",target:"rcan://streaming/chunk",params:{msg_type:29,msg_id:X(),stream_chunk:d},timestamp:new Date().toISOString()});return u=nt(u,{mediaChunks:[a]}),u}var ot=2.5,pn=0;function gn(){return`cr-${Date.now()}-${++pn}`}function gr(t={}){return{type:33,request_id:t.request_id??gn(),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 hr(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 yr(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 Rr(t,e="request"){return e==="request"||e==="result"?t>=ot:e==="cancel"?t>=2:!1}function _r(t){return t>=3}var it=2,hn=0;function yn(){return`run-${Date.now()}-${++hn}`}function Sr(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 Er(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 br(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 Ar(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??yn(),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 Cr(t){return t>=it}var wr="/.well-known/rcan-firmware-manifest.json";function xr(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 Tr(t){return{rrn:t.rrn,firmwareVersion:t.firmware_version,buildHash:t.build_hash,components:t.components??[],signedAt:t.signed_at??"",signature:t.signature}}function vr(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 Ne=class extends Error{constructor(e){super(e),this.name="FirmwareIntegrityError"}};function Or(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}function Nr(t){return{request_id:t.requestId,authority_id:t.authorityId,requested_data:t.requestedData,justification:t.justification,expires_at:t.expiresAt}}function kr(t){return{requestId:t.request_id,authorityId:t.authority_id,requestedData:t.requested_data??[],justification:t.justification??"",expiresAt:t.expires_at??0}}function at(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 Ir(t){return Date.now()/1e3<t.expiresAt&&at(t).length===0}var Mr={NOT_RECOGNIZED:"AUTHORITY_NOT_RECOGNIZED",REQUEST_EXPIRED:"AUTHORITY_REQUEST_EXPIRED",INVALID_TOKEN:"AUTHORITY_INVALID_TOKEN",RATE_LIMITED:"AUTHORITY_RATE_LIMITED"};var ct="https://api.rrf.rcan.dev/v2/revocations",ke="rrf.rcan.dev",dt=55e3;var S=class extends Error{constructor(e){super(e),this.name="M2MAuthError"}};function Ur(t){let e=t.split(".");if(e.length<2)throw new S("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(s){throw new S(`JWT payload decode failed: ${String(s)}`)}}function Pr(t){let e=Ur(t),r=Number(e.exp??0);if(r>0&&Date.now()/1e3>r)throw new S(`M2M_PEER token expired (sub=${String(e.sub)})`);let n=String(e.peer_rrn??"");if(!n)throw new S("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 ut(t){let e=Ur(t),r=String(e.iss??"");if(r!==ke)throw new S(`M2M_TRUSTED issuer must be '${ke}', 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 S("M2M_TRUSTED token missing required 'fleet.trusted' scope");let s=Number(e.exp??0);if(s>0&&Date.now()/1e3>s)throw new S(`M2M_TRUSTED token expired (sub=${String(e.sub)})`);let o=String(e.rrf_sig??"");if(!o)throw new S("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:s,iss:r,rrfSig:o}}function ft(t,e){let r=ut(t);if(!r.fleetRrns.includes(e))throw new S(`M2M_TRUSTED token does not authorize commanding '${e}'. Authorized fleet: [${r.fleetRrns.join(", ")}]`);return r}var $=null;async function lt(t=ct){let e=Date.now();if($&&e-$.fetchedAt<dt)return $;try{let n=await(await fetch(t,{signal:AbortSignal.timeout?.(5e3)})).json();$={revokedOrchestrators:new Set(n.revoked_orchestrators??[]),revokedJtis:new Set(n.revoked_jtis??[]),fetchedAt:e}}catch{if($)return $;$={revokedOrchestrators:new Set,revokedJtis:new Set,fetchedAt:e}}return $}async function mt(t,e){let r=await lt();return!!(r.revokedOrchestrators.has(t.sub)||e&&r.revokedJtis.has(e))}async function Dr(t,e,r){let n=ft(t,e);if(!r?.skipRevocationCheck&&await mt(n))throw new S(`M2M_TRUSTED orchestrator '${n.sub}' is on the RRF revocation list`);return n}var Rn="0.6.0",_n="1.6";return Jr(Sn);})();
|
|
3
|
+
`}static fromJSONL(e,r){let n=new t(r),o=e.trim().split(`
|
|
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 Jt(){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 gn(t){let e=Jt();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 mn(t){let e=Jt(),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=S.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 hn(t){let e=Jt(),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 ws="https://rcan-spec.pages.dev",yt=class{baseUrl;apiKey;timeout;constructor(e){this.baseUrl=(e?.baseUrl??ws).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 bs="https://rcan.dev",As="/.well-known/rcan-node.json",Ss=new Set(["root","authoritative","resolver","cache"]);function Es(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=bs,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(/\/$/,"")}${As}`,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=Es(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"||!Ss.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 Cs="https://rcan.dev/schemas",Yt=new Map;async function _t(t){if(Yt.has(t))return Yt.get(t);try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3);r.unref?.();let n=await fetch(`${Cs}/${t}`,{signal:e.signal});if(clearTimeout(r),!n.ok)return null;let o=await n.json();return Yt.set(t,o),o}catch{return null}}async function yn(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 Rn(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 Wt=(n=>(n[n.FIRE_AND_FORGET=0]="FIRE_AND_FORGET",n[n.ACKNOWLEDGED=1]="ACKNOWLEDGED",n[n.EXACTLY_ONCE=2]="EXACTLY_ONCE",n))(Wt||{}),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 ks(p),p=Math.min(p*2,5e3)}return{delivered:!1,attempts:u,reason:`ACK not received after ${o} retries`}}};function _n(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:Ts(),qos:2}}function Ts(){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 ks(t){return new Promise(e=>setTimeout(e,t))}var Qt=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 xn(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 wn(t,e){return{message_type:6,ruri:t,safety_event:"STOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:bt()}}function bn(t,e){return{message_type:6,ruri:t,safety_event:"RESUME",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:bt()}}function An(t){return typeof t=="object"&&t!==null&&t.message_type===Qt}function Sn(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 En(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=Os(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 Cn(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 Os(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 zt(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 Tn(t=5){let e=await zt();if(!e.synchronized||Math.abs(e.offsetSeconds)>t)throw new Ke(e.offsetSeconds,t)}d();async function vs(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 kn(t,e,r,n="rcan://local/config",o=!1){let s=await vs(t);return new S({rcan:q,cmd:"CONFIG_UPDATE",target:n,params:{message_type:5,diff:t,rollback:r,scope:e,config_hash:s,safety_overrides:o}})}function On(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 Ns(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}var St=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 vn(t,e,r=120,n="rcan://local/keys"){let o=Ns().slice(0,8);return new S({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 Is(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function Et(t){let e=t.requestId??Is();return new S({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 S({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 S({rcan:q,cmd:"CONSENT_DENY",target:"rcan://local/consent",params:{message_type:22,request_id:t.requestId,reason:t.reason??"denied"}})}function Nn(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 Ms=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+Ms})}invalidate(e){this._cache.delete(e)}get size(){return this._cache.size}};async function In(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 Mn(t,e){return new S({rcan:q,cmd:"ROBOT_REVOCATION",target:"rcan://broadcast/revocation",params:{message_type:19,rrn:t,reason:e,revoked_at:new Date().toISOString()}})}d();var Xt=(s=>(s.VIDEO="video",s.AUDIO="audio",s.LOCATION="location",s.BIOMETRIC="biometric",s.TELEMETRY="telemetry",s))(Xt||{});function Un(t){return Et({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 Pn(t){return Ct(t)}function Ln(t){return Tt(t)}function Dn(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 Zt=(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))(Zt||{});function Bn(t){return new S({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||{}),$n=be,je={1:1,2:2,3:2.5,4:3,5:4,6:5,7:6},Us=new Map(Object.entries(je).map(([t,e])=>[e,Number(t)]));function Ge(t){return Us.get(t)}var er={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 jn={minRoleForDiscover:1,minRoleForStatus:1,minRoleForChat:1,minRoleForControl:1,minRoleForSafety:1},qn={minRoleForDiscover:1,minRoleForStatus:1,minRoleForChat:1,minRoleForControl:2,minRoleForSafety:6};function Hn(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 tr(t){let e=Hn(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 tr(t)}function Fn(t){let e=Hn(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 rr(t,e){let r=er[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 Kn(t,e){return rr(t,e)}d();var nr=(n=>(n.ROOT="root",n.AUTHORITATIVE="authoritative",n.COMMUNITY="community",n))(nr||{}),or=(n=>(n.CONSENT="consent",n.REVOCATION="revocation",n.KEY="key",n))(or||{}),Ps=1440*60*1e3,vt=class{store=new Map;set(e){this.store.set(e.registryUrl,{identity:e,expiresAt:Date.now()+Ps})}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 Ls(){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 Vn(t,e,r,n){return new S({rcan:"2.1.0",rcanVersion:"2.1.0",cmd:"federation_sync",target:e,params:{msg_type:23,msg_id:Ls(),source_registry:t,target_registry:e,sync_type:r,payload:n},timestamp:new Date().toISOString()})}async function Gn(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)}},ar=(o=>(o.HTTP="http",o.COMPACT="compact",o.MINIMAL="minimal",o.BLE="ble",o))(ar||{}),sr={msg_type:"t",msg_id:"i",timestamp:"ts",from_rrn:"f",to_rrn:"to",scope:"s",payload:"p",signature:"sig"},Jn=Object.fromEntries(Object.entries(sr).map(([t,e])=>[e,t]));function cr(t){let e=t.toJSON(),r={};for(let[s,i]of Object.entries(e)){let a=sr[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=sr[a];i[p??a]=u}r.p=i}let n=JSON.stringify(r);return new TextEncoder().encode(n)}function ur(t){let r=new TextDecoder().decode(t),n=JSON.parse(r),o={};for(let[s,i]of Object.entries(n)){let a=Jn[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=Jn[a];i[p??a]=u}o.payload=i}return new S({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,ir=6;async function Yn(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 Wn(t){let e=t.params?.msg_type??0;if(e!==ir)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 Yn(r),s=await Yn(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 E=0;E<M.length;E++)a[E]=M.charCodeAt(E)}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,ir,!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 Qn(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 Ds=251,Je=3;function zn(t,e=Ds){let r=cr(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 Xn(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 ur(s)}function Zn(t,e){let n=(e.params?.msg_type??0)===ir,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 dr=(r=>(r.BASE64="base64",r.REF="ref",r))(dr||{});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 fr(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 eo(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 lr(t,e){let r={...t.toJSON(),...e};return S.fromJSON(r)}async function pr(t,e,r){let n=await fr(e),o=eo(e),s={chunkId:We(),mimeType:r,encoding:"base64",hashSha256:n,dataB64:o,sizeBytes:e.length},i=t.mediaChunks??[];return lr(t,{mediaChunks:[...i,s]})}function to(t,e,r,n,o){let s={chunkId:We(),mimeType:r,encoding:"ref",hashSha256:n,refUrl:e,sizeBytes:o},i=t.mediaChunks??[];return lr(t,{mediaChunks:[...i,s]})}async function ro(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 fr(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 no(t){let e=new S({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 pr(e,r.data,r.mimeType);return e}async function oo(t,e,r,n,o){let s=await fr(e),i=eo(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 S({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=lr(p,{mediaChunks:[a]}),p}d();var gr=2.5,Bs=0;function $s(){return`cr-${Date.now()}-${++Bs}`}function so(t={}){return{type:33,request_id:t.request_id??$s(),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 io(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 ao(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 co(t,e="request"){return e==="request"||e==="result"?t>=gr:e==="cancel"?t>=2:!1}function uo(t){return t>=3}d();var mr=2,js=0;function qs(){return`run-${Date.now()}-${++js}`}function fo(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 lo(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 po(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 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:40,run_id:t.run_id??qs(),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 mo(t){return t>=mr}d();var ho="/.well-known/rcan-firmware-manifest.json";function yo(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 Ro(t){return{rrn:t.rrn,firmwareVersion:t.firmware_version,buildHash:t.build_hash,components:t.components??[],signedAt:t.signed_at??"",signature:t.signature}}function _o(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 xo(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 wo(t){return{request_id:t.requestId,authority_id:t.authorityId,requested_data:t.requestedData,justification:t.justification,expires_at:t.expiresAt}}function bo(t){return{requestId:t.request_id,authorityId:t.authority_id,requestedData:t.requested_data??[],justification:t.justification??"",expiresAt:t.expires_at??0}}function hr(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 Ao(t){return Date.now()/1e3<t.expiresAt&&hr(t).length===0}var So={NOT_RECOGNIZED:"AUTHORITY_NOT_RECOGNIZED",REQUEST_EXPIRED:"AUTHORITY_REQUEST_EXPIRED",INVALID_TOKEN:"AUTHORITY_INVALID_TOKEN",RATE_LIMITED:"AUTHORITY_RATE_LIMITED"};d();var yr="https://api.rrf.rcan.dev/v2/revocations",It="rrf.rcan.dev",Rr=55e3;var z=class extends Error{constructor(e){super(e),this.name="M2MAuthError"}};function Eo(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 Co(t){let e=Eo(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 _r(t){let e=Eo(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 xr(t,e){let r=_r(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 wr(t=yr){let e=Date.now();if(Ae&&e-Ae.fetchedAt<Rr)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 br(t,e){let r=await wr();return!!(r.revokedOrchestrators.has(t.sub)||e&&r.revokedJtis.has(e))}async function To(t,e,r){let n=xr(t,e);if(!r?.skipRevocationCheck&&await br(n))throw new z(`M2M_TRUSTED orchestrator '${n.sub}' is on the RRF revocation list`);return n}d();function ci(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 ui(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 Jr(t){let n=(typeof globalThis<"u"?globalThis:{}).crypto?.subtle;if(n){let s=await n.digest("SHA-256",t);return Array.from(new Uint8Array(s)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,8)}let o=await import("crypto").catch(()=>null);if(o)return o.createHash("sha256").update(t).digest("hex").slice(0,8);throw new Error("No SHA-256 implementation available")}var qe;async function Yr(){if(qe)return qe;if(typeof ke<"u")try{return qe=(Gr(),sn(Vr)),qe}catch{}try{return qe=await Promise.resolve().then(()=>(Gr(),Vr)),qe}catch{throw new Error("ML-DSA 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{ml_dsa65:e}=await Yr(),r=e.keygen(),n=await Jr(r.publicKey);return new t({publicKey:r.publicKey,secretKey:r.secretKey,keyId:n})}static async fromPublicKey(e){let r=await Jr(e);return new t({publicKey:e,keyId:r})}static async fromKeyMaterial(e,r){let n=await Jr(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)");let{ml_dsa65:r}=await Yr();return r.sign(e,this.secretKey)}async verifyBytes(e,r){let{ml_dsa65:n}=await Yr();if(!n.verify(r,e,this.publicKey))throw new Error("ML-DSA signature verification failed")}toString(){let e=this.hasPrivateKey?"private+public":"public-only";return`MLDSAKeyPair(keyId=${this.keyId}, alg=ML-DSA-65, ${e})`}};function as(t){let e=t,r={rcan:t.rcan,msg_id:e.msgId??e.msg_id??"",timestamp:t.timestamp,cmd:t.cmd,target:t.target,params:t.params},n=JSON.stringify(Object.fromEntries(Object.entries(r).sort()),null,void 0);return new TextEncoder().encode(n)}async function cs(t,e){let r=as(t),n=await e.signBytes(r),o={alg:"ml-dsa-65",kid:e.keyId,sig:ci(n)};return t.pqSig=o,t}async function us(t,e,r=!1){let n=t.pqSig;if(!n){if(r)throw new Error("ML-DSA signature (pqSig) required but missing from message");return}if(n.alg!=="ml-dsa-65")throw new Error(`Unsupported PQ signature algorithm: ${n.alg}`);let o=e.find(a=>a.keyId===n.kid);if(!o)throw new Error(`No trusted ML-DSA key with kid=${n.kid}. Known kids: [${e.map(a=>a.keyId).join(", ")}]`);let s;try{s=ui(n.sig)}catch(a){throw new Error(`Invalid base64url ML-DSA signature: ${a}`)}let i=as(t);await o.verifyBytes(i,s)}var di="0.6.0",fi="1.6";return sn(li);})();
|
|
5
|
+
/*! Bundled license information:
|
|
6
|
+
|
|
7
|
+
@noble/hashes/utils.js:
|
|
8
|
+
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
9
|
+
|
|
10
|
+
@noble/curves/utils.js:
|
|
11
|
+
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
12
|
+
|
|
13
|
+
@noble/post-quantum/utils.js:
|
|
14
|
+
@noble/post-quantum/_crystals.js:
|
|
15
|
+
@noble/post-quantum/ml-dsa.js:
|
|
16
|
+
(*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *)
|
|
17
|
+
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@continuonai/rcan-ts",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Official TypeScript SDK for the RCAN v1.6 robot communication protocol",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"scripts": {
|
|
17
17
|
"build": "tsup",
|
|
18
18
|
"postbuild": "chmod +x bin/rcan-validate.mjs",
|
|
19
|
-
"test": "jest",
|
|
19
|
+
"test": "node --experimental-vm-modules node_modules/.bin/jest",
|
|
20
20
|
"typecheck": "tsc --noEmit"
|
|
21
21
|
},
|
|
22
22
|
"keywords": [
|
|
@@ -41,14 +41,34 @@
|
|
|
41
41
|
"typescript": "^5.3.0"
|
|
42
42
|
},
|
|
43
43
|
"jest": {
|
|
44
|
-
"preset": "ts-jest",
|
|
44
|
+
"preset": "ts-jest/presets/default-esm",
|
|
45
45
|
"testEnvironment": "node",
|
|
46
46
|
"testMatch": [
|
|
47
47
|
"**/tests/**/*.test.ts"
|
|
48
48
|
],
|
|
49
|
+
"extensionsToTreatAsEsm": [
|
|
50
|
+
".ts"
|
|
51
|
+
],
|
|
49
52
|
"moduleNameMapper": {
|
|
50
53
|
"^(\\.{1,2}/.*)\\.js$": "$1"
|
|
51
|
-
}
|
|
54
|
+
},
|
|
55
|
+
"transform": {
|
|
56
|
+
"^.+\\.tsx?$": [
|
|
57
|
+
"ts-jest",
|
|
58
|
+
{
|
|
59
|
+
"useESM": true,
|
|
60
|
+
"tsconfig": {
|
|
61
|
+
"module": "ESNext",
|
|
62
|
+
"moduleResolution": "Bundler"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
]
|
|
66
|
+
},
|
|
67
|
+
"globals": {},
|
|
68
|
+
"injectGlobals": true,
|
|
69
|
+
"transformIgnorePatterns": [
|
|
70
|
+
"node_modules/(?!(@noble/post-quantum|@noble/hashes)/)"
|
|
71
|
+
]
|
|
52
72
|
},
|
|
53
73
|
"browser": "dist/browser.mjs",
|
|
54
74
|
"cdn": "./dist/rcan.iife.js",
|
|
@@ -65,5 +85,8 @@
|
|
|
65
85
|
"sideEffects": false,
|
|
66
86
|
"publishConfig": {
|
|
67
87
|
"access": "public"
|
|
88
|
+
},
|
|
89
|
+
"dependencies": {
|
|
90
|
+
"@noble/post-quantum": "^0.5.4"
|
|
68
91
|
}
|
|
69
|
-
}
|
|
92
|
+
}
|