@continuonai/rcan-ts 0.8.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/README.md +1 -0
- package/dist/browser.d.mts +482 -39
- package/dist/browser.mjs +627 -73
- package/dist/browser.mjs.map +1 -1
- package/dist/index.d.mts +482 -39
- package/dist/index.d.ts +482 -39
- package/dist/index.js +665 -74
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +627 -73
- package/dist/index.mjs.map +1 -1
- package/dist/rcan-validate.js +22 -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 = "
|
|
2947
|
+
var SPEC_VERSION = "2.2.0";
|
|
2948
2948
|
|
|
2949
2949
|
// src/message.ts
|
|
2950
2950
|
var RCANMessageError = class extends Error {
|
|
@@ -2980,6 +2980,12 @@ var RCANMessage = class _RCANMessage {
|
|
|
2980
2980
|
transportEncoding;
|
|
2981
2981
|
/** v1.6: GAP-18 multi-modal media chunks */
|
|
2982
2982
|
mediaChunks;
|
|
2983
|
+
/** v2.1: SHA-256 of sender's firmware manifest */
|
|
2984
|
+
firmwareHash;
|
|
2985
|
+
/** v2.1: URI to sender's SBOM attestation endpoint */
|
|
2986
|
+
attestationRef;
|
|
2987
|
+
/** v2.2: ML-DSA-65 post-quantum signature (field 16, FIPS 204). Hybrid alongside Ed25519. */
|
|
2988
|
+
pqSig;
|
|
2983
2989
|
constructor(data) {
|
|
2984
2990
|
if (!data.cmd || data.cmd.trim() === "") {
|
|
2985
2991
|
throw new RCANMessageError("'cmd' is required");
|
|
@@ -3008,6 +3014,14 @@ var RCANMessage = class _RCANMessage {
|
|
|
3008
3014
|
this.loa = data.loa;
|
|
3009
3015
|
this.transportEncoding = data.transportEncoding;
|
|
3010
3016
|
this.mediaChunks = data.mediaChunks;
|
|
3017
|
+
this.firmwareHash = data.firmwareHash;
|
|
3018
|
+
this.attestationRef = data.attestationRef;
|
|
3019
|
+
this.pqSig = data.pqSig;
|
|
3020
|
+
if (this.signature !== void 0 && this.signature["sig"] === "pending") {
|
|
3021
|
+
throw new RCANMessageError(
|
|
3022
|
+
"signature.sig:'pending' is not valid in RCAN v2.1. Sign the message before sending."
|
|
3023
|
+
);
|
|
3024
|
+
}
|
|
3011
3025
|
if (this.confidence !== void 0) {
|
|
3012
3026
|
if (this.confidence < 0 || this.confidence > 1) {
|
|
3013
3027
|
throw new RCANMessageError(
|
|
@@ -3049,6 +3063,9 @@ var RCANMessage = class _RCANMessage {
|
|
|
3049
3063
|
if (this.loa !== void 0) obj.loa = this.loa;
|
|
3050
3064
|
if (this.transportEncoding !== void 0) obj.transportEncoding = this.transportEncoding;
|
|
3051
3065
|
if (this.mediaChunks !== void 0) obj.mediaChunks = this.mediaChunks;
|
|
3066
|
+
if (this.firmwareHash !== void 0) obj.firmwareHash = this.firmwareHash;
|
|
3067
|
+
if (this.attestationRef !== void 0) obj.attestationRef = this.attestationRef;
|
|
3068
|
+
if (this.pqSig !== void 0) obj.pqSig = this.pqSig;
|
|
3052
3069
|
return obj;
|
|
3053
3070
|
}
|
|
3054
3071
|
/** Serialize to JSON string */
|
|
@@ -3091,7 +3108,10 @@ var RCANMessage = class _RCANMessage {
|
|
|
3091
3108
|
readOnly: obj.readOnly,
|
|
3092
3109
|
loa: obj.loa,
|
|
3093
3110
|
transportEncoding: obj.transportEncoding,
|
|
3094
|
-
mediaChunks: obj.mediaChunks
|
|
3111
|
+
mediaChunks: obj.mediaChunks,
|
|
3112
|
+
firmwareHash: obj.firmwareHash,
|
|
3113
|
+
attestationRef: obj.attestationRef,
|
|
3114
|
+
pqSig: obj.pqSig
|
|
3095
3115
|
});
|
|
3096
3116
|
}
|
|
3097
3117
|
};
|
package/dist/rcan.iife.js
CHANGED
|
@@ -1,4 +1,17 @@
|
|
|
1
|
-
"use strict";var RCAN=(()=>{var rn=Object.create;var z=Object.defineProperty;var sn=Object.getOwnPropertyDescriptor;var on=Object.getOwnPropertyNames;var an=Object.getPrototypeOf,cn=Object.prototype.hasOwnProperty;var Q=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var dn=(t,e)=>{for(var n in e)z(t,n,{get:e[n],enumerable:!0})},Ze=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of on(e))!cn.call(t,s)&&s!==n&&z(t,s,{get:()=>e[s],enumerable:!(r=sn(e,s))||r.enumerable});return t};var et=(t,e,n)=>(n=t!=null?rn(an(t)):{},Ze(e||!t||!t.__esModule?z(n,"default",{value:t,enumerable:!0}):n,t)),un=t=>Ze(z({},"__esModule",{value:!0}),t);var Pn={};dn(Pn,{AuditChain:()=>ne,AuditError:()=>te,CONTRIBUTE_SCOPE_LEVEL:()=>Qe,ClockDriftError:()=>H,CommitmentRecord:()=>$,ConfidenceGate:()=>Z,DEFAULT_LOA_POLICY:()=>je,DataCategory:()=>Le,FaultCode:()=>$e,FederationSyncType:()=>Be,GateError:()=>O,HiTLGate:()=>ee,KeyStore:()=>Re,LevelOfAssurance:()=>Ae,MediaEncoding:()=>Je,MessageType:()=>x,NodeClient:()=>le,OfflineModeManager:()=>Ce,PRODUCTION_LOA_POLICY:()=>Ut,QoSAckTimeoutError:()=>ge,QoSLevel:()=>Me,QoSManager:()=>pe,RCANAddressError:()=>re,RCANConfigAuthorizationError:()=>ue,RCANDelegationChainError:()=>de,RCANError:()=>_,RCANGateError:()=>oe,RCANMessage:()=>l,RCANMessageError:()=>A,RCANNodeError:()=>L,RCANNodeNotFoundError:()=>k,RCANNodeSyncError:()=>R,RCANNodeTrustError:()=>j,RCANRegistryError:()=>D,RCANReplayAttackError:()=>ce,RCANSignatureError:()=>ie,RCANValidationError:()=>se,RCANVersionIncompatibleError:()=>ae,RCAN_VERSION:()=>Mn,RegistryClient:()=>fe,RegistryTier:()=>qe,ReplayCache:()=>ye,RevocationCache:()=>K,RobotURI:()=>M,RobotURIError:()=>U,SAFETY_MESSAGE_TYPE:()=>Pe,SDK_VERSION:()=>tt,SPEC_VERSION:()=>h,TransportEncoding:()=>Ke,TransportError:()=>E,TrustAnchorCache:()=>xe,VERSION:()=>Un,addDelegationHop:()=>st,addMediaInline:()=>ze,addMediaRef:()=>Vt,assertClockSynced:()=>bt,checkClockSync:()=>De,checkRevocation:()=>wt,decodeBleFrames:()=>Ft,decodeCompact:()=>Ye,decodeMinimal:()=>qt,encodeBleFrames:()=>Bt,encodeCompact:()=>Ve,encodeMinimal:()=>jt,extractLoaFromJwt:()=>Ee,fetchCanonicalSchema:()=>me,isPreemptedBy:()=>Zt,isSafetyMessage:()=>yt,makeCloudRelayMessage:()=>rt,makeConfigUpdate:()=>Ct,makeConsentDeny:()=>be,makeConsentGrant:()=>Se,makeConsentRequest:()=>_e,makeContributeCancel:()=>Qt,makeContributeRequest:()=>Wt,makeContributeResult:()=>zt,makeEstopMessage:()=>gt,makeEstopWithQoS:()=>mt,makeFaultReport:()=>It,makeFederationSync:()=>Pt,makeKeyRotationMessage:()=>Et,makeResumeMessage:()=>ht,makeRevocationBroadcast:()=>vt,makeStopMessage:()=>pt,makeStreamChunk:()=>Gt,makeTrainingConsentDeny:()=>kt,makeTrainingConsentGrant:()=>Ot,makeTrainingConsentRequest:()=>Nt,makeTrainingDataMessage:()=>Jt,makeTransparencyMessage:()=>_t,selectTransport:()=>Ht,validateConfig:()=>ut,validateConfigAgainstSchema:()=>ft,validateConfigUpdate:()=>At,validateConsentMessage:()=>xt,validateContributeScope:()=>Xt,validateCrossRegistryCommand:()=>Dt,validateDelegationChain:()=>ot,validateLoaForScope:()=>Mt,validateMediaChunks:()=>Yt,validateMessage:()=>dt,validateNodeAgainstSchema:()=>lt,validateReplay:()=>St,validateSafetyMessage:()=>Rt,validateTrainingDataMessage:()=>Tt,validateURI:()=>ct,validateVersionCompat:()=>nt});var U=class extends Error{constructor(e){super(e),this.name="RobotURIError"}},M=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 r=e.slice(7).split("/");if(r.length!==5)throw new U(`URI must have exactly 5 path segments (registry/manufacturer/model/version/device-id) \u2014 got ${r.length} in: ${e}`);let[s,o,i,a,d]=r;for(let[u,f]of[["registry",s],["manufacturer",o],["model",i],["version",a],["device-id",d]])if(!f||f.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 n=e.registry??"registry.rcan.dev",{manufacturer:r,model:s,version:o,deviceId:i}=e;for(let[a,d]of[["manufacturer",r],["model",s],["version",o],["deviceId",i]])if(!d||d.trim()==="")throw new U(`'${a}' must not be empty`);return new t({registry:n,manufacturer:r,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="1.9.0",tt="0.8.0";function nt(t,e=h){let n=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]},[r]=n(t),[s]=n(e);return r===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.FEDERATION_SYNC=23]="FEDERATION_SYNC",c[c.ALERT=26]="ALERT",c[c.AUDIT=16]="AUDIT",c))(x||{}),A=class extends Error{constructor(e){super(e),this.name="RCANMessageError"}},l=class t{rcan;rcanVersion;cmd;target;params;confidence;modelIdentity;signature;timestamp;senderType;cloudProvider;keyId;delegationChain;groupId;qos;presenceVerified;proximityMeters;readOnly;loa;transportEncoding;mediaChunks;constructor(e){if(!e.cmd||e.cmd.trim()==="")throw new A("'cmd' is required");if(!e.target)throw new A("'target' is required");if(this.rcan=e.rcan??h,this.rcanVersion=e.rcanVersion??h,this.cmd=e.cmd,this.target=e.target instanceof M?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.confidence!==void 0&&(this.confidence<0||this.confidence>1))throw new A(`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),e}toJSONString(e){return JSON.stringify(this.toJSON(),null,e)}static fromJSON(e){let n;if(typeof e=="string")try{n=JSON.parse(e)}catch{throw new A("Invalid JSON string")}else n=e;if(!n.cmd)throw new A("Missing required field: 'cmd'");if(!n.target)throw new A("Missing required field: 'target'");if(!n.rcan)throw new A("Missing required field: 'rcan'");return new t({rcan:n.rcan,rcanVersion:n.rcanVersion,cmd:n.cmd,target:n.target,params:n.params??{},confidence:n.confidence,modelIdentity:n.model_identity??n.modelIdentity,signature:n.signature,timestamp:n.timestamp,senderType:n.senderType,cloudProvider:n.cloudProvider,keyId:n.keyId,delegationChain:n.delegationChain,groupId:n.groupId,qos:n.qos,presenceVerified:n.presenceVerified,proximityMeters:n.proximityMeters,readOnly:n.readOnly,loa:n.loa,transportEncoding:n.transportEncoding,mediaChunks:n.mediaChunks})}};function rt(t,e){let n=t.toJSON();return n.senderType="cloud_function",n.cloudProvider=e,new l(n)}function st(t,e){let n=t.delegationChain?[...t.delegationChain,e]:[e],r=t.toJSON();return r.delegationChain=n,new l(r)}function ot(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 n=t[e];if(!n)return{valid:!1,reason:`hop ${e} is undefined`};if(!n.issuerRuri)return{valid:!1,reason:`hop ${e}: missing issuerRuri`};if(!n.humanSubject)return{valid:!1,reason:`hop ${e}: missing humanSubject`};if(!n.timestamp)return{valid:!1,reason:`hop ${e}: missing timestamp`};if(!n.scope)return{valid:!1,reason:`hop ${e}: missing scope`};if(!n.signature)return{valid:!1,reason:`hop ${e}: missing signature`}}return{valid:!0,reason:"ok"}}function X(){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();try{let{randomUUID:t}=Q("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 Te(t,e){return typeof process<"u",ln(t,e)}function ke(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],n=1779033703,r=3144134277,s=1013904242,o=2773480762,i=1359893119,a=2600822924,d=528734635,u=1541459225,q=t.length*8,C=[...t];for(C.push(128);C.length%64!==56;)C.push(0);for(let y=7;y>=0;y--)C.push(q/Math.pow(2,y*8)&255);for(let y=0;y<C.length;y+=64){let S=[];for(let g=0;g<16;g++)S[g]=C[y+g*4]<<24|C[y+g*4+1]<<16|C[y+g*4+2]<<8|C[y+g*4+3];for(let g=16;g<64;g++){let Ne=w(S[g-15],7)^w(S[g-15],18)^S[g-15]>>>3,Oe=w(S[g-2],17)^w(S[g-2],19)^S[g-2]>>>10;S[g]=S[g-16]+Ne+S[g-7]+Oe>>>0}let[T,B,F,we,I,G,W,ve]=[n,r,s,o,i,a,d,u];for(let g=0;g<64;g++){let Ne=w(I,6)^w(I,11)^w(I,25),Oe=I&G^~I&W,Xe=ve+Ne+Oe+e[g]+S[g]>>>0,en=w(T,2)^w(T,13)^w(T,22),tn=T&B^T&F^B&F,nn=en+tn>>>0;[ve,W,G,I,we,F,B,T]=[W,G,I,we+Xe>>>0,F,B,T,Xe+nn>>>0]}n=n+T>>>0,r=r+B>>>0,s=s+F>>>0,o=o+we>>>0,i=i+I>>>0,a=a+G>>>0,d=d+W>>>0,u=u+ve>>>0}let p=new Uint8Array(32),N=new DataView(p.buffer);return[n,r,s,o,i,a,d,u].forEach((y,S)=>N.setUint32(S*4,y)),p}function w(t,e){return t>>>e|t<<32-e}function it(t){if(typeof TextEncoder<"u")return new TextEncoder().encode(t);let e=new Uint8Array(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n)&255;return e}function fn(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}function ln(t,e){let r=it(t);r.length>64&&(r=ke(r));let s=new Uint8Array(64),o=new Uint8Array(64);for(let f=0;f<64;f++)s[f]=(r[f]??0)^54,o[f]=(r[f]??0)^92;let i=it(e),a=new Uint8Array(64+i.length);a.set(s),a.set(i,64);let d=ke(a),u=new Uint8Array(96);return u.set(o),u.set(d,64),fn(ke(u))}var O=class extends Error{constructor(e){super(e),this.name="GateError"}},Z=class{threshold;constructor(e=.8){if(e<0||e>1)throw new O(`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,n){if(!this.allows(e)){let r=n?` for action '${n}'`:"";throw new O(`Confidence ${e}${r} is below threshold ${this.threshold}`)}}},ee=class{_pending=new Map;request(e,n={}){let r=X();return this._pending.set(r,{token:r,action:e,context:n,createdAt:new Date().toISOString(),status:"pending"}),r}approve(e){let n=this._pending.get(e);if(!n)throw new O(`Unknown token: ${e}`);n.status="approved"}deny(e,n){let r=this._pending.get(e);if(!r)throw new O(`Unknown token: ${e}`);r.status="denied",n&&(r.reason=n)}check(e){let n=this._pending.get(e);if(!n)throw new O(`Unknown token: ${e}`);return n.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,n]of this._pending.entries())n.status!=="pending"&&this._pending.delete(e)}};var te=class extends Error{constructor(e){super(e),this.name="AuditError"}};function mn(t,e,n,r,s){let o=JSON.stringify({recordId:t,action:e,robotUri:n,timestamp:r,params:s},Object.keys({recordId:t,action:e,robotUri:n,timestamp:r,params:s}).sort());return Te("rcan-content-hash",o)}function at(t,e){let{hmac:n,...r}=e,s=JSON.stringify(r,Object.keys(r).sort());return Te(t,s)}var $=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,n,r=null){let s=X(),o=new Date().toISOString(),i=e.params??{},a=e.robotUri??"",d=mn(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:r,hmac:""};return u.hmac=at(n,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)}},ne=class t{_records=[];_secret;constructor(e){this._secret=e}get records(){return this._records}append(e){let r=this._records[this._records.length-1]?.contentHash??null,s=$.create(e,this._secret,r);return this._records.push(s),s}verifyAll(){let e=[],n=null;for(let r of this._records)r.verify(this._secret)||e.push(`HMAC invalid for record ${r.recordId.slice(0,8)}`),n!==null&&r.previousHash!==n&&e.push(`Chain broken at ${r.recordId.slice(0,8)}: expected prev=${n.slice(0,12)}`),n=r.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,
|
|
4
|
-
`).filter(o=>o.trim()!=="");for(let o of s){let i=JSON.parse(o);r._records.push($.fromJSON(i))}return r}};function Ie(){return{ok:!0,issues:[],warnings:[],info:[]}}function v(t,e){t.ok=!1,t.issues.push(e)}function P(t,e){t.warnings.push(e)}function b(t,e){t.info.push(e)}function ct(t){let e=Ie();try{let n=M.parse(t);b(e,"\u2705 Valid RCAN URI"),b(e,` Registry: ${n.registry}`),b(e,` Manufacturer: ${n.manufacturer}`),b(e,` Model: ${n.model}`),b(e,` Version: ${n.version}`),b(e,` Device ID: ${n.deviceId}`)}catch(n){v(e,`Invalid RCAN URI: ${n instanceof Error?n.message:n}`)}return e}function dt(t){let e=Ie(),n;if(typeof t=="string")try{n=JSON.parse(t)}catch{return v(e,"Invalid JSON string"),e}else if(typeof t=="object"&&t!==null)n=t;else return v(e,"Expected object or JSON string"),e;for(let r of["rcan","cmd","target"])(!(r in n)||!n[r])&&v(e,`Missing required field: '${r}'`);if(!e.ok)return e;try{let r=l.fromJSON(n);b(e,`\u2705 RCAN message valid (v${r.rcan})`),b(e,` cmd: ${r.cmd}`),b(e,` target: ${r.target}`),r.confidence!==void 0?b(e,` confidence: ${r.confidence}`):P(e,"No confidence score \u2014 add for RCAN \xA716 AI accountability"),r.isSigned?b(e,` signature: alg=${r.signature?.alg}, kid=${r.signature?.kid}`):P(e,"Message is unsigned (recommended for production)")}catch(r){v(e,`Message validation failed: ${r instanceof Error?r.message:r}`)}return e}function ut(t){let e=Ie(),n=t.metadata??{},r=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')`)),n.manufacturer||v(e,"L1: metadata.manufacturer is required (\xA72)"),n.model||v(e,"L1: metadata.model is required (\xA72)"),!n.device_id&&!n.robot_name&&v(e,"L1: metadata.device_id (or robot_name) is required (\xA72)"),s.jwt_auth?.enabled||P(e,"L2: jwt_auth not enabled (required for L2 conformance, \xA78)"),(!r.confidence_gates||r.confidence_gates.length===0)&&P(e,"L2: confidence_gates not configured (\xA716)"),(!r.hitl_gates||r.hitl_gates.length===0)&&P(e,"L3: hitl_gates not configured (\xA716)"),r.commitment_chain?.enabled||P(e,"L3: commitment_chain not enabled (\xA716)"),n.rrn?b(e,`\u2705 RRN registered: ${n.rrn}`):P(e,"Robot not registered \u2014 visit rcan.dev/registry/register"),e.ok&&e.issues.length===0){let i=!e.warnings.some(f=>f.startsWith("L1")),a=i&&!e.warnings.some(f=>f.startsWith("L2")),u=a&&!e.warnings.some(f=>f.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)}},re=class extends _{constructor(e){super(e),this.name="RCANAddressError",Object.setPrototypeOf(this,new.target.prototype)}},se=class extends _{constructor(e){super(e),this.name="RCANValidationError",Object.setPrototypeOf(this,new.target.prototype)}},oe=class extends _{constructor(n,r,s,o){super(n);this.gateType=r;this.value=s;this.threshold=o;this.name="RCANGateError",Object.setPrototypeOf(this,new.target.prototype)}},ie=class extends _{constructor(e){super(e),this.name="RCANSignatureError",Object.setPrototypeOf(this,new.target.prototype)}},D=class extends _{constructor(e){super(e),this.name="RCANRegistryError",Object.setPrototypeOf(this,new.target.prototype)}},L=class t extends _{constructor(n,r){super(n);this.nodeUrl=r;this.name="RCANNodeError",Object.setPrototypeOf(this,t.prototype)}},k=class t extends L{constructor(n,r){super(`RRN not found in federation: ${n}`,r);this.rrn=n;this.name="RCANNodeNotFoundError",Object.setPrototypeOf(this,t.prototype)}},R=class t extends L{constructor(n,r,s){super(n,r);this.cause=s;this.name="RCANNodeSyncError",Object.setPrototypeOf(this,t.prototype)}},j=class t extends L{reason;constructor(e,n){super(`Node trust verification failed: ${e}`,n),this.name="RCANNodeTrustError",this.reason=e,Object.setPrototypeOf(this,t.prototype)}},ae=class t extends _{constructor(e,n){super(`VERSION_INCOMPATIBLE: incoming=${e}, local=${n}`),this.name="RCANVersionIncompatibleError",Object.setPrototypeOf(this,t.prototype)}},ce=class t extends _{constructor(e){super(`REPLAY_DETECTED: ${e}`),this.name="RCANReplayAttackError",Object.setPrototypeOf(this,t.prototype)}},de=class t extends _{constructor(e){super(`DELEGATION_CHAIN_ERROR: ${e}`),this.name="RCANDelegationChainError",Object.setPrototypeOf(this,t.prototype)}},ue=class t extends _{constructor(e){super(`CONFIG_AUTH_ERROR: ${e}`),this.name="RCANConfigAuthorizationError",Object.setPrototypeOf(this,t.prototype)}};var gn="https://rcan-spec.pages.dev",fe=class{baseUrl;apiKey;timeout;constructor(e){this.baseUrl=(e?.baseUrl??gn).replace(/\/$/,""),this.apiKey=e?.apiKey,this.timeout=e?.timeout??1e4}async _fetch(e,n={}){let r=`${this.baseUrl}${e}`,s=new AbortController,o=setTimeout(()=>s.abort(),this.timeout);try{return await fetch(r,{...n,signal:s.signal,headers:{"Content-Type":"application/json",...n.headers??{}}})}finally{clearTimeout(o)}}_authHeaders(){if(!this.apiKey)throw new D("API key required for write operations. Pass apiKey to RegistryClient.");return{Authorization:`Bearer ${this.apiKey}`}}async _checkResponse(e){if(!e.ok){let n=`Registry API error: ${e.status}`;try{let r=await e.json();r?.error&&(n=r.error)}catch{}throw new D(n)}return await e.json()}async register(e){let n=await this._fetch("/api/v1/robots",{method:"POST",body:JSON.stringify(e)});return this._checkResponse(n)}async get(e){let n=await this._fetch(`/api/v1/robots/${encodeURIComponent(e)}`);return this._checkResponse(n)}async list(e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.offset!==void 0&&n.set("offset",String(e.offset)),e?.tier&&n.set("tier",e.tier);let r=n.toString()?`?${n}`:"",s=await this._fetch(`/api/v1/robots${r}`);return this._checkResponse(s)}async patch(e,n){let r=await this._fetch(`/api/v1/robots/${encodeURIComponent(e)}`,{method:"PATCH",headers:this._authHeaders(),body:JSON.stringify(n)});return this._checkResponse(r)}async delete(e){let n=await this._fetch(`/api/v1/robots/${encodeURIComponent(e)}`,{method:"DELETE",headers:this._authHeaders()});n.ok||await this._checkResponse(n)}async search(e){let n=new URLSearchParams;e.q&&n.set("q",e.q),e.manufacturer&&n.set("manufacturer",e.manufacturer),e.model&&n.set("model",e.model),e.tier&&n.set("tier",e.tier);let r=n.toString()?`?${n}`:"",s=await this._fetch(`/api/v1/robots/search${r}`);if(!s.ok){let i=await this._fetch(`/api/v1/robots${r}`),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 pn="https://rcan.dev",hn="/.well-known/rcan-node.json",yn=new Set(["root","authoritative","resolver","cache"]);function Rn(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 n=t.match(/^RRN-(\d{8,16})$/);return n?{type:"root",serial:n[1]}:null}var le=class{rootUrl;timeoutMs;constructor(e=pn,n=1e4){this.rootUrl=e.replace(/\/$/,""),this.timeoutMs=n}async _fetch(e){let n=new AbortController,r=setTimeout(()=>n.abort(),this.timeoutMs);try{return await globalThis.fetch(e,{signal:n.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(r)}}async getNodeManifest(e){let n=`${e.replace(/\/$/,"")}${hn}`,r=await this._fetch(n);if(!r.ok)throw r.status===404?new k(n,e):new R(`Failed to fetch node manifest from ${e}: HTTP ${r.status}`,e);let s;try{s=await r.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 j("missing_pubkey",e);return s}async listNodes(e){let n=e?`?prefix=${encodeURIComponent(e)}`:"",r=`${this.rootUrl}/api/v1/nodes${n}`,s=await this._fetch(r);if(!s.ok)throw new R(`Failed to list nodes from ${r}: HTTP ${s.status}`,r);let o;try{o=await s.json()}catch(i){throw new R(`Invalid JSON in nodes list from ${r}`,r,i instanceof Error?i:void 0)}return Array.isArray(o)?o:o&&typeof o=="object"&&"nodes"in o?o.nodes:[]}async discover(e){let n=Rn(e);if(!n)throw new k(e,this.rootUrl);if(n.type==="root")return this.getNodeManifest(this.rootUrl);let r=await this.listNodes(n.prefix);if(r.length===0)throw new k(e,this.rootUrl);return r[0]}async resolve(e){let n=`${this.rootUrl}/api/v1/resolve/${encodeURIComponent(e)}`,r;try{r=await this._fetch(n)}catch(a){throw a}if(r.ok)try{return await r.json()}catch(a){throw new R(`Invalid JSON in resolve response for ${e}`,this.rootUrl,a instanceof Error?a:void 0)}if(r.status!==404)throw new R(`Unexpected HTTP ${r.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 n=e;return!(typeof n.rcan_node_version!="string"||!n.rcan_node_version||typeof n.node_type!="string"||!yn.has(n.node_type)||typeof n.operator!="string"||!n.operator||typeof n.namespace_prefix!="string"||!n.namespace_prefix||typeof n.public_key!="string"||!n.public_key.startsWith("ed25519:")||typeof n.api_base!="string"||!n.api_base.startsWith("https://"))}};var _n="https://rcan.dev/schemas",Ue=new Map;async function me(t){if(Ue.has(t))return Ue.get(t);try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3);n.unref?.();let r=await fetch(`${_n}/${t}`,{signal:e.signal});if(clearTimeout(n),!r.ok)return null;let s=await r.json();return Ue.set(t,s),s}catch{return null}}async function ft(t){let e=await me("rcan-config.schema.json");if(!e)return{valid:!0,skipped:!0};let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Config must be an object"]};let r=t,s=e.required??[];for(let o of s)o in r||n.push(`Missing required field: ${o}`);return n.length===0?{valid:!0}:{valid:!1,errors:n}}async function lt(t){let e=await me("rcan-node.schema.json");if(!e)return{valid:!0,skipped:!0};let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Manifest must be an object"]};let r=t,s=e.required??[];for(let o of s)o in r||n.push(`Missing required field: ${o}`);return n.length===0?{valid:!0}:{valid:!1,errors:n}}var Me=(r=>(r[r.FIRE_AND_FORGET=0]="FIRE_AND_FORGET",r[r.ACKNOWLEDGED=1]="ACKNOWLEDGED",r[r.EXACTLY_ONCE=2]="EXACTLY_ONCE",r))(Me||{}),ge=class t extends Error{constructor(e){super(`ACK timeout for message ${e} \u2014 safety halt required`),this.name="QoSAckTimeoutError",Object.setPrototypeOf(this,t.prototype)}},pe=class{_send;_waitForAck;constructor(e,n){this._send=e,this._waitForAck=n}async sendWithQoS(e,n={}){let r=n.qos??0,s=n.maxRetries??3,o=n.initialBackoffMs??100,i=n.ackTimeoutMs??500;if(r===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:r===2?"exactly-once":"acknowledged"};if(d>s)break;await bn(u),u=Math.min(u*2,5e3)}return{delivered:!1,attempts:d,reason:`ACK not received after ${s} retries`}}};function mt(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:Sn(),qos:2}}function Sn(){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(n=>n.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function bn(t){return new Promise(e=>setTimeout(e,t))}var Pe=6;function he(){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(n=>n.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 gt(t,e){return{message_type:6,ruri:t,safety_event:"ESTOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:he(),qos:2}}function pt(t,e){return{message_type:6,ruri:t,safety_event:"STOP",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:he()}}function ht(t,e){return{message_type:6,ruri:t,safety_event:"RESUME",reason:e.slice(0,512),timestamp_ms:Date.now(),message_id:he()}}function yt(t){return typeof t=="object"&&t!==null&&t.message_type===Pe}function Rt(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 _t(t,e,n){return{message_type:11,ruri:t,disclosure:e,timestamp_ms:Date.now(),message_id:he(),delegation_chain:n}}var ye=class{windowSeconds;maxSize;_seen;constructor(e=30,n=1e4){this.windowSeconds=e,this.maxSize=n,this._seen=new Map}checkAndRecord(e,n,r=!1){let s=Date.now();this._evict(s);let o=r?Math.min(this.windowSeconds,10):this.windowSeconds,i=Cn(n);if(i===null)return{allowed:!1,reason:`invalid timestamp format: ${n}`};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 f=this._seen.keys().next().value;this._seen.delete(f)}let u=s+d;return this._seen.set(e,u),{allowed:!0,reason:"ok"}}_evict(e){for(let[n,r]of this._seen)r<=e&&this._seen.delete(n)}get size(){return this._seen.size}};function St(t,e){let n=t,r=n.message_id??n.msg_id;if(!r)return{valid:!1,reason:"missing message_id / msg_id"};let s;if(typeof n.timestamp_ms=="number"?s=String(n.timestamp_ms/1e3):n.timestamp!==void 0&&(s=String(n.timestamp)),!s)return{valid:!1,reason:"missing timestamp"};let o=n.message_type===6||n.message_type===6,i=e.checkAndRecord(r,s,o);return{valid:i.allowed,reason:i.reason}}function Cn(t){if(t.includes("T")||t.includes("-")){let n=new Date(t);if(!isNaN(n.getTime()))return n.getTime()}let e=parseFloat(t);return isNaN(e)?null:e>1e12?e:e*1e3}var H=class t extends Error{offsetSeconds;constructor(e,n){super(`Clock drift too large: offset=${e.toFixed(3)}s > max=${n}s`),this.name="ClockDriftError",this.offsetSeconds=e,Object.setPrototypeOf(this,t.prototype)}};async function De(t){let e=t??"https://worldtimeapi.org/api/ip";try{let n=Date.now(),r=await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(3e3)}),s=Date.now(),o=r.headers.get("Date")??r.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=((n+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 bt(t=5){let e=await De();if(!e.synchronized||Math.abs(e.offsetSeconds)>t)throw new H(e.offsetSeconds,t)}async function An(t){let e=JSON.stringify(t,Object.keys(t).sort());if(typeof crypto<"u"&&crypto.subtle){let r=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=n*16777619>>>0;return n.toString(16).padStart(8,"0")}async function Ct(t,e,n,r="rcan://local/config",s=!1){let o=await An(t);return new l({rcan:h,cmd:"CONFIG_UPDATE",target:r,params:{message_type:5,diff:t,rollback:n,scope:e,config_hash:o,safety_overrides:s}})}function At(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 En(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}var Re=class{_keys=[];addKey(e){this._keys.push(e)}getJWKS(){return{keys:[...this._keys]}}findKey(e){return this._keys.find(n=>n.kid===e)}isKeyValid(e,n){let r=this.findKey(e);if(!r)return!1;let s=(n??Date.now())/1e3;return!(r.revoked_at!==void 0&&r.revoked_at<=s||r.exp!==void 0&&r.exp<s)}expireKey(e,n){let r=this.findKey(e);r&&(r.exp=n??Math.floor(Date.now()/1e3))}revokeKey(e){let n=this.findKey(e);n&&(n.revoked_at=Math.floor(Date.now()/1e3))}validKeys(e){return this._keys.filter(n=>this.isKeyValid(n.kid,e))}};function Et(t,e,n=120,r="rcan://local/keys"){let s=En().slice(0,8);return new l({rcan:h,cmd:"KEY_ROTATION",target:r,params:{message_type:5,new_public_key:t,new_kid:s,old_kid:e,overlap_seconds:n,initiated_at:new Date().toISOString()},keyId:s})}function xn(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function _e(t){let e=t.requestId??xn();return new l({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 Se(t){let e=t.expiresAt??new Date(Date.now()+864e5).toISOString();return new l({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 be(t){return new l({rcan:h,cmd:"CONSENT_DENY",target:"rcan://local/consent",params:{message_type:22,request_id:t.requestId,reason:t.reason??"denied"}})}function xt(t){let e=t.cmd,n=t.params,r=n.message_type;return e==="CONSENT_REQUEST"?r!==20?{valid:!1,reason:"message_type must be CONSENT_REQUEST (20)"}:n.requester_ruri?n.target_ruri?!n.requested_scopes||!Array.isArray(n.requested_scopes)||n.requested_scopes.length===0?{valid:!1,reason:"requested_scopes must be a non-empty array"}:n.request_id?n.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"?r!==21?{valid:!1,reason:"message_type must be CONSENT_GRANT (21)"}:n.request_id?n.expires_at?{valid:!0,reason:"ok"}:{valid:!1,reason:"missing expires_at"}:{valid:!1,reason:"missing request_id"}:e==="CONSENT_DENY"?r!==22?{valid:!1,reason:"message_type must be CONSENT_DENY (22)"}:n.request_id?{valid:!0,reason:"ok"}:{valid:!1,reason:"missing request_id"}:{valid:!1,reason:`unknown consent command: ${e}`}}var wn=3600*1e3,K=class{_cache=new Map;get(e,n){let r=this._cache.get(e);if(!r)return;let s=n??Date.now();if(r.cachedUntil!==void 0&&r.cachedUntil<s){this._cache.delete(e);return}return r}set(e,n){let r=n??Date.now();this._cache.set(e.rrn,{...e,cachedUntil:r+wn})}invalidate(e){this._cache.delete(e)}get size(){return this._cache.size}};async function wt(t,e,n){let r=n??new K,s=r.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 r.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 r.set(d),d}catch{return{rrn:t,status:"active",reason:"network unavailable"}}}function vt(t,e){return new l({rcan:h,cmd:"ROBOT_REVOCATION",target:"rcan://broadcast/revocation",params:{message_type:19,rrn:t,reason:e,revoked_at:new Date().toISOString()}})}var Le=(o=>(o.VIDEO="video",o.AUDIO="audio",o.LOCATION="location",o.BIOMETRIC="biometric",o.TELEMETRY="telemetry",o))(Le||{});function Nt(t){return _e({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 Ot(t){return Se(t)}function kt(t){return be(t)}function Tt(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 Ce=class{crossOwnerGraceS;keyTtlS;_cachedKeys=[];constructor(e=3600,n=86400){this.crossOwnerGraceS=e,this.keyTtlS=n}canAcceptCommand(e,n,r,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(!n)return{allowed:!0,reason:"online mode"};if(!r)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,n){let r=n??Date.now();this._cachedKeys=this._cachedKeys.filter(s=>s.kid!==e.kid),this._cachedKeys.push({...e,cachedAtMs:r,ttlSeconds:this.keyTtlS})}getCachedKey(e,n){let r=n??Date.now(),s=this._cachedKeys.find(i=>i.kid===e);if(!s)return;if((r-s.cachedAtMs)/1e3>s.ttlSeconds){this._cachedKeys=this._cachedKeys.filter(i=>i.kid!==e);return}return s}getManifestFields(e,n){if(e===void 0)return{offline_mode:!1,offline_since_s:0};let r=n??Date.now();return{offline_mode:!0,offline_since_s:Math.round((r-e)/1e3)}}};var $e=(p=>(p.SENSOR_PROXIMITY_FAILURE="SENSOR_PROXIMITY_FAILURE",p.SENSOR_CAMERA_FAILURE="SENSOR_CAMERA_FAILURE",p.SENSOR_IMU_FAILURE="SENSOR_IMU_FAILURE",p.MOTOR_OVERCURRENT="MOTOR_OVERCURRENT",p.MOTOR_OVERTEMP="MOTOR_OVERTEMP",p.MOTOR_STALL="MOTOR_STALL",p.BATTERY_CRITICAL="BATTERY_CRITICAL",p.BATTERY_LOW="BATTERY_LOW",p.NETWORK_TIMEOUT="NETWORK_TIMEOUT",p.NETWORK_REGISTRY_UNREACHABLE="NETWORK_REGISTRY_UNREACHABLE",p.SAFETY_ESTOP_STUCK="SAFETY_ESTOP_STUCK",p.SAFETY_WATCHDOG_TIMEOUT="SAFETY_WATCHDOG_TIMEOUT",p.UNKNOWN="UNKNOWN",p))($e||{});function It(t){return new l({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 Ae=(r=>(r[r.ANONYMOUS=1]="ANONYMOUS",r[r.EMAIL_VERIFIED=2]="EMAIL_VERIFIED",r[r.HARDWARE_TOKEN=3]="HARDWARE_TOKEN",r))(Ae||{}),je={minLoaDiscover:1,minLoaStatus:1,minLoaChat:1,minLoaControl:1,minLoaSafety:1},Ut={minLoaDiscover:1,minLoaStatus:1,minLoaChat:1,minLoaControl:2,minLoaSafety:3};function Ee(t){try{let e=t.split(".");if(e.length<2)return 1;let n=(e[1]??"").replace(/-/g,"+").replace(/_/g,"/"),r=n+"=".repeat((4-n.length%4)%4),s;typeof atob<"u"?s=atob(r):s=Buffer.from(r,"base64").toString("utf-8");let i=JSON.parse(s).loa;if(typeof i=="number"&&i>=1&&i<=3)return i}catch{}return 1}function vn(t,e){switch(t.toLowerCase()){case"discover":return e.minLoaDiscover;case"status":return e.minLoaStatus;case"chat":return e.minLoaChat;case"contribute":return e.minLoaChat;case"control":return e.minLoaControl;case"safety":return e.minLoaSafety;default:return null}}function Mt(t,e,n=je){let r=vn(e,n);return r===null?{valid:!0,reason:"unknown scope; allowed by default"}:t>=r?{valid:!0,reason:"ok"}:{valid:!1,reason:`LOA_INSUFFICIENT: scope=${e} requires LoA>=${r}, caller has LoA=${t}`}}var qe=(r=>(r.ROOT="root",r.AUTHORITATIVE="authoritative",r.COMMUNITY="community",r))(qe||{}),Be=(r=>(r.CONSENT="consent",r.REVOCATION="revocation",r.KEY="key",r))(Be||{}),Nn=1440*60*1e3,xe=class{store=new Map;set(e){this.store.set(e.registryUrl,{identity:e,expiresAt:Date.now()+Nn})}lookup(e){let n=this.store.get(e);if(n){if(Date.now()>n.expiresAt){this.store.delete(e);return}return n.identity}}async discoverViaDns(e){let n=`_rcan-registry.${e}`,r;try{r=await Q("dns").promises.resolveTxt(n)}catch{return}for(let s of r){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,n){let r=this.lookup(n);if(!r)throw new Error(`REGISTRY_UNKNOWN: ${n} 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!==n)throw new Error(`REGISTRY_JWT_ISS_MISMATCH: expected iss=${n}, got iss=${s??"(none)"}`);return r}};function On(){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(n=>n.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 Pt(t,e,n,r){return new l({rcan:"1.6",rcanVersion:"1.6",cmd:"federation_sync",target:e,params:{msg_type:23,msg_id:On(),source_registry:t,target_registry:e,sync_type:n,payload:r},timestamp:new Date().toISOString()})}async function Dt(t,e,n){let r=t.params?.msg_type;if(r===6||r===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(!n.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=Ee(d):typeof t.loa=="number"&&(a=t.loa),a<2?{valid:!1,reason:`LOA_INSUFFICIENT: cross-registry commands require LoA>=2 (EMAIL_VERIFIED), got LoA=${a}`}:{valid:!0,reason:"cross-registry command accepted"}}var E=class t extends Error{constructor(e){super(e),this.name="TransportError",Object.setPrototypeOf(this,t.prototype)}},Ke=(s=>(s.HTTP="http",s.COMPACT="compact",s.MINIMAL="minimal",s.BLE="ble",s))(Ke||{}),Fe={msg_type:"t",msg_id:"i",timestamp:"ts",from_rrn:"f",to_rrn:"to",scope:"s",payload:"p",signature:"sig"},Lt=Object.fromEntries(Object.entries(Fe).map(([t,e])=>[e,t]));function Ve(t){let e=t.toJSON(),n={};for(let[o,i]of Object.entries(e)){let a=Fe[o];n[a??o]=i}if(n.p&&typeof n.p=="object"){let o=n.p,i={};for(let[a,d]of Object.entries(o)){let u=Fe[a];i[u??a]=d}n.p=i}let r=JSON.stringify(n);return new TextEncoder().encode(r)}function Ye(t){let n=new TextDecoder().decode(t),r=JSON.parse(n),s={};for(let[o,i]of Object.entries(r)){let a=Lt[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=Lt[a];i[u??a]=d}s.payload=i}return new l({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 Y=32,He=6;async function $t(t){let e=new TextEncoder().encode(t),n=new ArrayBuffer(e.byteLength);new Uint8Array(n).set(e);let s=await(globalThis.crypto?.subtle??(await import("crypto")).webcrypto.subtle).digest("SHA-256",n);return new Uint8Array(s)}async function jt(t){let e=t.params?.msg_type??0;if(e!==He)throw new E(`encodeMinimal only supports SAFETY (type 6) messages; got type=${e}`);let n=t.params?.from_rrn??t.target??"",r=t.params?.to_rrn??t.target??"",s=await $t(n),o=await $t(r),i=(t.signature?.sig??"").replace(/[^A-Za-z0-9+/=]/g,""),a;try{if(typeof atob<"u"){let N=atob(i.slice(0,16));a=new Uint8Array(N.length);for(let y=0;y<N.length;y++)a[y]=N.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,f=new Uint8Array(Y),q=new DataView(f.buffer);q.setUint16(0,He,!1),f.set(s.subarray(0,8),2),f.set(o.subarray(0,8),10),q.setUint32(18,u,!1);let C=new Uint8Array(8);C.set(a.subarray(0,Math.min(8,a.length))),f.set(C,22);let p=0;for(let N=0;N<30;N++)p^=f[N]??0;if(q.setUint16(30,p&65535,!1),f.length!==Y)throw new E(`encodeMinimal assertion failed: expected ${Y} bytes, got ${f.length}`);return f}function qt(t){if(t.length!==Y)throw new E(`decodeMinimal: expected ${Y} bytes, got ${t.length}`);let e=new DataView(t.buffer,t.byteOffset,t.byteLength),n=e.getUint16(0,!1),r=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(f=>f.toString(16).padStart(2,"0")).join("");return{params:{msg_type:n,from_hash:d(r),to_hash:d(s),timestamp_s:o,sig_truncated:d(i)},timestamp:a}}var kn=251,V=3;function Bt(t,e=kn){let n=Ve(t),r=e-V;if(r<=0)throw new E(`MTU ${e} is too small (need at least ${V+1})`);let s=Math.ceil(n.length/r),o=[];for(let i=0;i<s;i++){let a=n.subarray(i*r,(i+1)*r),d=new Uint8Array(V+a.length);d[0]=i,d[1]=s,d[2]=i===s-1?1:0,d.set(a,V),o.push(d)}return o}function Ft(t){if(t.length===0)throw new E("decodeBleFrames: no frames provided");let e=[...t].sort((a,d)=>(a[0]??0)-(d[0]??0)),n=e[0]?.[1]??e.length;if(e.length!==n)throw new E(`decodeBleFrames: expected ${n} frames, got ${e.length}`);let r=e.map(a=>a.subarray(V)),s=r.reduce((a,d)=>a+d.length,0),o=new Uint8Array(s),i=0;for(let a of r)o.set(a,i),i+=a.length;return Ye(o)}function Ht(t,e){let r=(e.params?.msg_type??0)===He,s=o=>t.includes(o);if(r){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 E(`No suitable transport available from: [${t.join(", ")}]`)}var Je=(n=>(n.BASE64="base64",n.REF="ref",n))(Je||{});function J(){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(n=>n.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 Ge(t){let e=globalThis.crypto?.subtle??(await import("crypto")).webcrypto.subtle,n=new ArrayBuffer(t.byteLength);new Uint8Array(n).set(t);let r=await e.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(o=>o.toString(16).padStart(2,"0")).join("")}function Kt(t){if(typeof Buffer<"u")return Buffer.from(t).toString("base64");let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]??0);return btoa(e)}function We(t,e){let n={...t.toJSON(),...e};return l.fromJSON(n)}async function ze(t,e,n){let r=await Ge(e),s=Kt(e),o={chunkId:J(),mimeType:n,encoding:"base64",hashSha256:r,dataB64:s,sizeBytes:e.length},i=t.mediaChunks??[];return We(t,{mediaChunks:[...i,o]})}function Vt(t,e,n,r,s){let o={chunkId:J(),mimeType:n,encoding:"ref",hashSha256:r,refUrl:e,sizeBytes:s},i=t.mediaChunks??[];return We(t,{mediaChunks:[...i,o]})}async function Yt(t){let e=t.mediaChunks??[];if(e.length===0)return{valid:!0,reason:"no media chunks"};for(let n=0;n<e.length;n++){let r=e[n];if(!r.chunkId)return{valid:!1,reason:`chunk[${n}]: missing chunkId`};if(!r.mimeType)return{valid:!1,reason:`chunk[${n}]: missing mimeType`};if(!r.hashSha256)return{valid:!1,reason:`chunk[${n}]: missing hashSha256`};if(r.sizeBytes<0)return{valid:!1,reason:`chunk[${n}]: sizeBytes must be >= 0`};if(r.encoding==="base64"){if(!r.dataB64)return{valid:!1,reason:`chunk[${n}]: BASE64 encoding requires dataB64`};let s;try{if(typeof Buffer<"u")s=Buffer.from(r.dataB64,"base64");else{let i=atob(r.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[${n}]: failed to decode base64 data`}}let o=await Ge(s);if(o!==r.hashSha256)return{valid:!1,reason:`chunk[${n}]: SHA-256 mismatch (expected ${r.hashSha256}, got ${o})`}}else if(r.encoding==="ref"){if(!r.refUrl)return{valid:!1,reason:`chunk[${n}]: REF encoding requires refUrl`}}else return{valid:!1,reason:`chunk[${n}]: unknown encoding '${r.encoding}'`}}return{valid:!0,reason:"ok"}}async function Jt(t){let e=new l({rcan:"1.6",rcanVersion:"1.6",cmd:"training_data",target:"rcan://training/data",params:{msg_type:36,msg_id:J()},timestamp:new Date().toISOString()});for(let n of t)e=await ze(e,n.data,n.mimeType);return e}async function Gt(t,e,n,r,s){let o=await Ge(e),i=Kt(e),a={chunkId:J(),mimeType:n,encoding:"base64",hashSha256:o,dataB64:i,sizeBytes:e.length},d={streamId:t,chunkIndex:r,isFinal:s,chunk:a},u=new l({rcan:"1.6",rcanVersion:"1.6",cmd:"stream_chunk",target:"rcan://streaming/chunk",params:{msg_type:29,msg_id:J(),stream_chunk:d},timestamp:new Date().toISOString()});return u=We(u,{mediaChunks:[a]}),u}var Qe=2.5,Tn=0;function In(){return`cr-${Date.now()}-${++Tn}`}function Wt(t={}){return{type:33,request_id:t.request_id??In(),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 zt(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 Qt(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 Xt(t,e="request"){return e==="request"||e==="result"?t>=Qe:e==="cancel"?t>=2:!1}function Zt(t){return t>=3}var Un="0.6.0",Mn="1.6";return un(Pn);})();
|
|
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": "
|
|
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
|
+
}
|