@continuonai/rcan-ts 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -96,7 +96,8 @@ var RobotURI = class _RobotURI {
96
96
  };
97
97
 
98
98
  // src/version.ts
99
- var SPEC_VERSION = "1.5";
99
+ var SPEC_VERSION = "1.6";
100
+ var SDK_VERSION = "0.6.0";
100
101
  function validateVersionCompat(incomingVersion, localVersion = SPEC_VERSION) {
101
102
  const parseParts = (v) => {
102
103
  const parts = v.split(".");
@@ -167,6 +168,12 @@ var RCANMessage = class _RCANMessage {
167
168
  presenceVerified;
168
169
  proximityMeters;
169
170
  readOnly;
171
+ /** v1.6: GAP-14 level of assurance */
172
+ loa;
173
+ /** v1.6: GAP-17 transport encoding hint */
174
+ transportEncoding;
175
+ /** v1.6: GAP-18 multi-modal media chunks */
176
+ mediaChunks;
170
177
  constructor(data) {
171
178
  if (!data.cmd || data.cmd.trim() === "") {
172
179
  throw new RCANMessageError("'cmd' is required");
@@ -192,6 +199,9 @@ var RCANMessage = class _RCANMessage {
192
199
  this.presenceVerified = data.presenceVerified;
193
200
  this.proximityMeters = data.proximityMeters;
194
201
  this.readOnly = data.readOnly;
202
+ this.loa = data.loa;
203
+ this.transportEncoding = data.transportEncoding;
204
+ this.mediaChunks = data.mediaChunks;
195
205
  if (this.confidence !== void 0) {
196
206
  if (this.confidence < 0 || this.confidence > 1) {
197
207
  throw new RCANMessageError(
@@ -230,6 +240,9 @@ var RCANMessage = class _RCANMessage {
230
240
  if (this.presenceVerified !== void 0) obj.presenceVerified = this.presenceVerified;
231
241
  if (this.proximityMeters !== void 0) obj.proximityMeters = this.proximityMeters;
232
242
  if (this.readOnly !== void 0) obj.readOnly = this.readOnly;
243
+ if (this.loa !== void 0) obj.loa = this.loa;
244
+ if (this.transportEncoding !== void 0) obj.transportEncoding = this.transportEncoding;
245
+ if (this.mediaChunks !== void 0) obj.mediaChunks = this.mediaChunks;
233
246
  return obj;
234
247
  }
235
248
  /** Serialize to JSON string */
@@ -269,7 +282,10 @@ var RCANMessage = class _RCANMessage {
269
282
  qos: obj.qos,
270
283
  presenceVerified: obj.presenceVerified,
271
284
  proximityMeters: obj.proximityMeters,
272
- readOnly: obj.readOnly
285
+ readOnly: obj.readOnly,
286
+ loa: obj.loa,
287
+ transportEncoding: obj.transportEncoding,
288
+ mediaChunks: obj.mediaChunks
273
289
  });
274
290
  }
275
291
  };
@@ -2021,23 +2037,643 @@ function makeFaultReport(params) {
2021
2037
  });
2022
2038
  }
2023
2039
 
2040
+ // src/identity.ts
2041
+ var LevelOfAssurance = /* @__PURE__ */ ((LevelOfAssurance2) => {
2042
+ LevelOfAssurance2[LevelOfAssurance2["ANONYMOUS"] = 1] = "ANONYMOUS";
2043
+ LevelOfAssurance2[LevelOfAssurance2["EMAIL_VERIFIED"] = 2] = "EMAIL_VERIFIED";
2044
+ LevelOfAssurance2[LevelOfAssurance2["HARDWARE_TOKEN"] = 3] = "HARDWARE_TOKEN";
2045
+ return LevelOfAssurance2;
2046
+ })(LevelOfAssurance || {});
2047
+ var DEFAULT_LOA_POLICY = {
2048
+ minLoaDiscover: 1 /* ANONYMOUS */,
2049
+ minLoaStatus: 1 /* ANONYMOUS */,
2050
+ minLoaChat: 1 /* ANONYMOUS */,
2051
+ minLoaControl: 1 /* ANONYMOUS */,
2052
+ minLoaSafety: 1 /* ANONYMOUS */
2053
+ };
2054
+ var PRODUCTION_LOA_POLICY = {
2055
+ minLoaDiscover: 1 /* ANONYMOUS */,
2056
+ minLoaStatus: 1 /* ANONYMOUS */,
2057
+ minLoaChat: 1 /* ANONYMOUS */,
2058
+ minLoaControl: 2 /* EMAIL_VERIFIED */,
2059
+ minLoaSafety: 3 /* HARDWARE_TOKEN */
2060
+ };
2061
+ function extractLoaFromJwt(token) {
2062
+ try {
2063
+ const parts = token.split(".");
2064
+ if (parts.length < 2) return 1 /* ANONYMOUS */;
2065
+ const payloadB64 = (parts[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
2066
+ const padded = payloadB64 + "=".repeat((4 - payloadB64.length % 4) % 4);
2067
+ let json;
2068
+ if (typeof atob !== "undefined") {
2069
+ json = atob(padded);
2070
+ } else {
2071
+ json = Buffer.from(padded, "base64").toString("utf-8");
2072
+ }
2073
+ const claims = JSON.parse(json);
2074
+ const loa = claims["loa"];
2075
+ if (typeof loa === "number" && loa >= 1 && loa <= 3) {
2076
+ return loa;
2077
+ }
2078
+ } catch {
2079
+ }
2080
+ return 1 /* ANONYMOUS */;
2081
+ }
2082
+ function minLoaForScope(scope, policy) {
2083
+ const s = scope.toLowerCase();
2084
+ switch (s) {
2085
+ case "discover":
2086
+ return policy.minLoaDiscover;
2087
+ case "status":
2088
+ return policy.minLoaStatus;
2089
+ case "chat":
2090
+ return policy.minLoaChat;
2091
+ case "control":
2092
+ return policy.minLoaControl;
2093
+ case "safety":
2094
+ return policy.minLoaSafety;
2095
+ default:
2096
+ return null;
2097
+ }
2098
+ }
2099
+ function validateLoaForScope(loa, scope, policy = DEFAULT_LOA_POLICY) {
2100
+ const min = minLoaForScope(scope, policy);
2101
+ if (min === null) {
2102
+ return { valid: true, reason: "unknown scope; allowed by default" };
2103
+ }
2104
+ if (loa >= min) {
2105
+ return { valid: true, reason: "ok" };
2106
+ }
2107
+ return {
2108
+ valid: false,
2109
+ reason: `LOA_INSUFFICIENT: scope=${scope} requires LoA>=${min}, caller has LoA=${loa}`
2110
+ };
2111
+ }
2112
+
2113
+ // src/federation.ts
2114
+ var RegistryTier = /* @__PURE__ */ ((RegistryTier2) => {
2115
+ RegistryTier2["ROOT"] = "root";
2116
+ RegistryTier2["AUTHORITATIVE"] = "authoritative";
2117
+ RegistryTier2["COMMUNITY"] = "community";
2118
+ return RegistryTier2;
2119
+ })(RegistryTier || {});
2120
+ var FederationSyncType = /* @__PURE__ */ ((FederationSyncType2) => {
2121
+ FederationSyncType2["CONSENT"] = "consent";
2122
+ FederationSyncType2["REVOCATION"] = "revocation";
2123
+ FederationSyncType2["KEY"] = "key";
2124
+ return FederationSyncType2;
2125
+ })(FederationSyncType || {});
2126
+ var CACHE_TTL_MS2 = 24 * 60 * 60 * 1e3;
2127
+ var TrustAnchorCache = class {
2128
+ store = /* @__PURE__ */ new Map();
2129
+ /** Store or refresh a registry identity. */
2130
+ set(identity) {
2131
+ this.store.set(identity.registryUrl, {
2132
+ identity,
2133
+ expiresAt: Date.now() + CACHE_TTL_MS2
2134
+ });
2135
+ }
2136
+ /**
2137
+ * Look up a registry URL.
2138
+ * Returns undefined when absent or when the TTL has expired.
2139
+ */
2140
+ lookup(url) {
2141
+ const entry = this.store.get(url);
2142
+ if (!entry) return void 0;
2143
+ if (Date.now() > entry.expiresAt) {
2144
+ this.store.delete(url);
2145
+ return void 0;
2146
+ }
2147
+ return entry.identity;
2148
+ }
2149
+ /**
2150
+ * Discover a registry via DNS TXT record `_rcan-registry.<domain>`.
2151
+ *
2152
+ * The TXT record is expected to contain a JSON object with the
2153
+ * RegistryIdentity fields. Returns the identity and caches it.
2154
+ *
2155
+ * Node.js only — returns undefined in environments without `dns.promises`.
2156
+ */
2157
+ async discoverViaDns(domain) {
2158
+ const hostname = `_rcan-registry.${domain}`;
2159
+ let records;
2160
+ try {
2161
+ const dnsModule = __require("dns");
2162
+ records = await dnsModule.promises.resolveTxt(hostname);
2163
+ } catch {
2164
+ return void 0;
2165
+ }
2166
+ for (const record of records) {
2167
+ const text = record.join("");
2168
+ try {
2169
+ const parsed = JSON.parse(text);
2170
+ if (parsed.registryUrl && parsed.tier && parsed.publicKeyPem && parsed.domain) {
2171
+ const identity = {
2172
+ registryUrl: parsed.registryUrl,
2173
+ tier: parsed.tier,
2174
+ publicKeyPem: parsed.publicKeyPem,
2175
+ domain: parsed.domain,
2176
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
2177
+ };
2178
+ this.set(identity);
2179
+ return identity;
2180
+ }
2181
+ } catch {
2182
+ }
2183
+ }
2184
+ return void 0;
2185
+ }
2186
+ /**
2187
+ * Verify a JWT was issued by the registry at `url`.
2188
+ *
2189
+ * Validates the `iss` claim and checks the registry is in the trust cache.
2190
+ * Full cryptographic signature verification requires the registry's public
2191
+ * key material — callers should perform additional checks using `publicKeyPem`
2192
+ * from the returned identity.
2193
+ */
2194
+ async verifyRegistryJwt(token, url) {
2195
+ const identity = this.lookup(url);
2196
+ if (!identity) {
2197
+ throw new Error(`REGISTRY_UNKNOWN: ${url} is not in the trust cache`);
2198
+ }
2199
+ let iss;
2200
+ try {
2201
+ const parts = token.split(".");
2202
+ const payloadB64 = (parts[1] ?? "").replace(/-/g, "+").replace(/_/g, "/");
2203
+ const padded = payloadB64 + "=".repeat((4 - payloadB64.length % 4) % 4);
2204
+ let json;
2205
+ if (typeof atob !== "undefined") {
2206
+ json = atob(padded);
2207
+ } else {
2208
+ json = Buffer.from(padded, "base64").toString("utf-8");
2209
+ }
2210
+ const claims = JSON.parse(json);
2211
+ iss = typeof claims["iss"] === "string" ? claims["iss"] : void 0;
2212
+ } catch {
2213
+ throw new Error("REGISTRY_JWT_MALFORMED: cannot decode token payload");
2214
+ }
2215
+ if (iss !== url) {
2216
+ throw new Error(
2217
+ `REGISTRY_JWT_ISS_MISMATCH: expected iss=${url}, got iss=${iss ?? "(none)"}`
2218
+ );
2219
+ }
2220
+ return identity;
2221
+ }
2222
+ };
2223
+ function generateId5() {
2224
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
2225
+ return crypto.randomUUID();
2226
+ }
2227
+ const bytes = Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
2228
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
2229
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2230
+ const hex = bytes.map((b) => b.toString(16).padStart(2, "0"));
2231
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
2232
+ }
2233
+ function makeFederationSync(source, target, syncType, payload) {
2234
+ return new RCANMessage({
2235
+ rcan: "1.6",
2236
+ rcanVersion: "1.6",
2237
+ cmd: "federation_sync",
2238
+ target,
2239
+ params: {
2240
+ msg_type: 12 /* FEDERATION_SYNC */,
2241
+ msg_id: generateId5(),
2242
+ source_registry: source,
2243
+ target_registry: target,
2244
+ sync_type: syncType,
2245
+ payload
2246
+ },
2247
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2248
+ });
2249
+ }
2250
+ async function validateCrossRegistryCommand(msg, localRegistry, trustCache) {
2251
+ const msgType = msg.params?.["msg_type"];
2252
+ const isEstop = msgType === 6 /* SAFETY */ || msgType === 6 || msg.cmd === "estop" || msg.cmd === "ESTOP";
2253
+ if (isEstop) {
2254
+ return { valid: true, reason: "ESTOP always permitted (P66 invariant)" };
2255
+ }
2256
+ const sourceRegistry = msg.params?.["source_registry"] ?? msg.params?.["from_registry"];
2257
+ if (!sourceRegistry || sourceRegistry === localRegistry) {
2258
+ return { valid: true, reason: "local registry; no federation check needed" };
2259
+ }
2260
+ const identity = trustCache.lookup(sourceRegistry);
2261
+ if (!identity) {
2262
+ return {
2263
+ valid: false,
2264
+ reason: `REGISTRY_UNKNOWN: ${sourceRegistry} is not in the local trust cache`
2265
+ };
2266
+ }
2267
+ let loa = 1 /* ANONYMOUS */;
2268
+ const registryJwt = msg.params?.["registry_jwt"];
2269
+ if (registryJwt) {
2270
+ loa = extractLoaFromJwt(registryJwt);
2271
+ } else if (typeof msg.loa === "number") {
2272
+ loa = msg.loa;
2273
+ }
2274
+ if (loa < 2 /* EMAIL_VERIFIED */) {
2275
+ return {
2276
+ valid: false,
2277
+ reason: `LOA_INSUFFICIENT: cross-registry commands require LoA>=2 (EMAIL_VERIFIED), got LoA=${loa}`
2278
+ };
2279
+ }
2280
+ return { valid: true, reason: "cross-registry command accepted" };
2281
+ }
2282
+
2283
+ // src/transport.ts
2284
+ var TransportError = class _TransportError extends Error {
2285
+ constructor(message) {
2286
+ super(message);
2287
+ this.name = "TransportError";
2288
+ Object.setPrototypeOf(this, _TransportError.prototype);
2289
+ }
2290
+ };
2291
+ var TransportEncoding = /* @__PURE__ */ ((TransportEncoding2) => {
2292
+ TransportEncoding2["HTTP"] = "http";
2293
+ TransportEncoding2["COMPACT"] = "compact";
2294
+ TransportEncoding2["MINIMAL"] = "minimal";
2295
+ TransportEncoding2["BLE"] = "ble";
2296
+ return TransportEncoding2;
2297
+ })(TransportEncoding || {});
2298
+ var COMPACT_ENCODE = {
2299
+ msg_type: "t",
2300
+ msg_id: "i",
2301
+ timestamp: "ts",
2302
+ from_rrn: "f",
2303
+ to_rrn: "to",
2304
+ scope: "s",
2305
+ payload: "p",
2306
+ signature: "sig"
2307
+ };
2308
+ var COMPACT_DECODE = Object.fromEntries(
2309
+ Object.entries(COMPACT_ENCODE).map(([k, v]) => [v, k])
2310
+ );
2311
+ function encodeCompact(message) {
2312
+ const full = message.toJSON();
2313
+ const compact = {};
2314
+ for (const [key, value] of Object.entries(full)) {
2315
+ const short = COMPACT_ENCODE[key];
2316
+ compact[short ?? key] = value;
2317
+ }
2318
+ if (compact["p"] && typeof compact["p"] === "object") {
2319
+ const params = compact["p"];
2320
+ const compactParams = {};
2321
+ for (const [k, v] of Object.entries(params)) {
2322
+ const short = COMPACT_ENCODE[k];
2323
+ compactParams[short ?? k] = v;
2324
+ }
2325
+ compact["p"] = compactParams;
2326
+ }
2327
+ const json = JSON.stringify(compact);
2328
+ const encoder = new TextEncoder();
2329
+ return encoder.encode(json);
2330
+ }
2331
+ function decodeCompact(data) {
2332
+ const decoder = new TextDecoder();
2333
+ const json = decoder.decode(data);
2334
+ const compact = JSON.parse(json);
2335
+ const full = {};
2336
+ for (const [key, value] of Object.entries(compact)) {
2337
+ const long = COMPACT_DECODE[key];
2338
+ full[long ?? key] = value;
2339
+ }
2340
+ if (full["payload"] && typeof full["payload"] === "object") {
2341
+ const params = full["payload"];
2342
+ const expandedParams = {};
2343
+ for (const [k, v] of Object.entries(params)) {
2344
+ const long = COMPACT_DECODE[k];
2345
+ expandedParams[long ?? k] = v;
2346
+ }
2347
+ full["payload"] = expandedParams;
2348
+ }
2349
+ return new RCANMessage({
2350
+ rcan: full["rcan"] ?? "1.6",
2351
+ rcanVersion: full["rcanVersion"],
2352
+ cmd: full["cmd"],
2353
+ target: full["target"],
2354
+ params: full["params"] ?? full["payload"] ?? {},
2355
+ timestamp: full["timestamp"],
2356
+ confidence: full["confidence"],
2357
+ signature: full["signature"]
2358
+ });
2359
+ }
2360
+ var MINIMAL_SIZE = 32;
2361
+ var SAFETY_TYPE = 6;
2362
+ async function sha256Bytes(input) {
2363
+ const encoded = new TextEncoder().encode(input);
2364
+ const ab = new ArrayBuffer(encoded.byteLength);
2365
+ new Uint8Array(ab).set(encoded);
2366
+ const hashBuffer = await crypto.subtle.digest("SHA-256", ab);
2367
+ return new Uint8Array(hashBuffer);
2368
+ }
2369
+ async function encodeMinimal(message) {
2370
+ const msgType = message.params?.["msg_type"] ?? 0;
2371
+ if (msgType !== SAFETY_TYPE) {
2372
+ throw new TransportError(
2373
+ `encodeMinimal only supports SAFETY (type 6) messages; got type=${msgType}`
2374
+ );
2375
+ }
2376
+ const fromRrn = message.params?.["from_rrn"] ?? message.target ?? "";
2377
+ const toRrn = message.params?.["to_rrn"] ?? message.target ?? "";
2378
+ const fromHash = await sha256Bytes(fromRrn);
2379
+ const toHash = await sha256Bytes(toRrn);
2380
+ const sig = (message.signature?.sig ?? "").replace(/[^A-Za-z0-9+/=]/g, "");
2381
+ let sigBytes;
2382
+ try {
2383
+ if (typeof atob !== "undefined") {
2384
+ const raw = atob(sig.slice(0, 16));
2385
+ sigBytes = new Uint8Array(raw.length);
2386
+ for (let i = 0; i < raw.length; i++) sigBytes[i] = raw.charCodeAt(i);
2387
+ } else {
2388
+ sigBytes = Buffer.from(sig.slice(0, 16), "base64");
2389
+ }
2390
+ } catch {
2391
+ sigBytes = new Uint8Array(8);
2392
+ }
2393
+ const ts = message.timestamp ? Math.floor(new Date(message.timestamp).getTime() / 1e3) : Math.floor(Date.now() / 1e3);
2394
+ const unix32 = ts >>> 0;
2395
+ const out = new Uint8Array(MINIMAL_SIZE);
2396
+ const view = new DataView(out.buffer);
2397
+ view.setUint16(0, SAFETY_TYPE, false);
2398
+ out.set(fromHash.subarray(0, 8), 2);
2399
+ out.set(toHash.subarray(0, 8), 10);
2400
+ view.setUint32(18, unix32, false);
2401
+ const sigSlice = new Uint8Array(8);
2402
+ sigSlice.set(sigBytes.subarray(0, Math.min(8, sigBytes.length)));
2403
+ out.set(sigSlice, 22);
2404
+ let checksum = 0;
2405
+ for (let i = 0; i < 30; i++) checksum ^= out[i] ?? 0;
2406
+ view.setUint16(30, checksum & 65535, false);
2407
+ if (out.length !== MINIMAL_SIZE) {
2408
+ throw new TransportError(
2409
+ `encodeMinimal assertion failed: expected ${MINIMAL_SIZE} bytes, got ${out.length}`
2410
+ );
2411
+ }
2412
+ return out;
2413
+ }
2414
+ function decodeMinimal(data) {
2415
+ if (data.length !== MINIMAL_SIZE) {
2416
+ throw new TransportError(
2417
+ `decodeMinimal: expected ${MINIMAL_SIZE} bytes, got ${data.length}`
2418
+ );
2419
+ }
2420
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
2421
+ const msgType = view.getUint16(0, false);
2422
+ const fromHash = data.subarray(2, 10);
2423
+ const toHash = data.subarray(10, 18);
2424
+ const unix32 = view.getUint32(18, false);
2425
+ const sigTrunc = data.subarray(22, 30);
2426
+ const timestamp = new Date(unix32 * 1e3).toISOString();
2427
+ const toHex2 = (b) => Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
2428
+ return {
2429
+ params: {
2430
+ msg_type: msgType,
2431
+ from_hash: toHex2(fromHash),
2432
+ to_hash: toHex2(toHash),
2433
+ timestamp_s: unix32,
2434
+ sig_truncated: toHex2(sigTrunc)
2435
+ },
2436
+ timestamp
2437
+ };
2438
+ }
2439
+ var DEFAULT_MTU = 251;
2440
+ var BLE_HEADER_SIZE = 3;
2441
+ function encodeBleFrames(message, mtu = DEFAULT_MTU) {
2442
+ const payload = encodeCompact(message);
2443
+ const chunkSize = mtu - BLE_HEADER_SIZE;
2444
+ if (chunkSize <= 0) {
2445
+ throw new TransportError(`MTU ${mtu} is too small (need at least ${BLE_HEADER_SIZE + 1})`);
2446
+ }
2447
+ const totalChunks = Math.ceil(payload.length / chunkSize);
2448
+ const frames = [];
2449
+ for (let i = 0; i < totalChunks; i++) {
2450
+ const chunk = payload.subarray(i * chunkSize, (i + 1) * chunkSize);
2451
+ const frame = new Uint8Array(BLE_HEADER_SIZE + chunk.length);
2452
+ frame[0] = i;
2453
+ frame[1] = totalChunks;
2454
+ frame[2] = i === totalChunks - 1 ? 1 : 0;
2455
+ frame.set(chunk, BLE_HEADER_SIZE);
2456
+ frames.push(frame);
2457
+ }
2458
+ return frames;
2459
+ }
2460
+ function decodeBleFrames(frames) {
2461
+ if (frames.length === 0) {
2462
+ throw new TransportError("decodeBleFrames: no frames provided");
2463
+ }
2464
+ const sorted = [...frames].sort((a, b) => (a[0] ?? 0) - (b[0] ?? 0));
2465
+ const expectedTotal = sorted[0]?.[1] ?? sorted.length;
2466
+ if (sorted.length !== expectedTotal) {
2467
+ throw new TransportError(
2468
+ `decodeBleFrames: expected ${expectedTotal} frames, got ${sorted.length}`
2469
+ );
2470
+ }
2471
+ const payloadChunks = sorted.map((f) => f.subarray(BLE_HEADER_SIZE));
2472
+ const totalLen = payloadChunks.reduce((s, c) => s + c.length, 0);
2473
+ const payload = new Uint8Array(totalLen);
2474
+ let offset = 0;
2475
+ for (const chunk of payloadChunks) {
2476
+ payload.set(chunk, offset);
2477
+ offset += chunk.length;
2478
+ }
2479
+ return decodeCompact(payload);
2480
+ }
2481
+ function selectTransport(available, message) {
2482
+ const msgType = message.params?.["msg_type"] ?? 0;
2483
+ const isSafety = msgType === SAFETY_TYPE;
2484
+ const has = (enc) => available.includes(enc);
2485
+ if (isSafety) {
2486
+ if (has("minimal" /* MINIMAL */)) return "minimal" /* MINIMAL */;
2487
+ if (has("ble" /* BLE */)) return "ble" /* BLE */;
2488
+ if (has("compact" /* COMPACT */)) return "compact" /* COMPACT */;
2489
+ if (has("http" /* HTTP */)) return "http" /* HTTP */;
2490
+ } else {
2491
+ if (has("http" /* HTTP */)) return "http" /* HTTP */;
2492
+ if (has("compact" /* COMPACT */)) return "compact" /* COMPACT */;
2493
+ if (has("ble" /* BLE */)) return "ble" /* BLE */;
2494
+ }
2495
+ throw new TransportError(
2496
+ `No suitable transport available from: [${available.join(", ")}]`
2497
+ );
2498
+ }
2499
+
2500
+ // src/multimodal.ts
2501
+ var MediaEncoding = /* @__PURE__ */ ((MediaEncoding2) => {
2502
+ MediaEncoding2["BASE64"] = "base64";
2503
+ MediaEncoding2["REF"] = "ref";
2504
+ return MediaEncoding2;
2505
+ })(MediaEncoding || {});
2506
+ function generateId6() {
2507
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
2508
+ return crypto.randomUUID();
2509
+ }
2510
+ const bytes = Array.from({ length: 16 }, () => Math.floor(Math.random() * 256));
2511
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
2512
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
2513
+ const hex = bytes.map((b) => b.toString(16).padStart(2, "0"));
2514
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
2515
+ }
2516
+ async function computeSha256Hex(data) {
2517
+ const ab = new ArrayBuffer(data.byteLength);
2518
+ new Uint8Array(ab).set(data);
2519
+ const hashBuffer = await crypto.subtle.digest("SHA-256", ab);
2520
+ const hashArray = new Uint8Array(hashBuffer);
2521
+ return Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
2522
+ }
2523
+ function uint8ToBase64(data) {
2524
+ if (typeof Buffer !== "undefined") {
2525
+ return Buffer.from(data).toString("base64");
2526
+ }
2527
+ let binary = "";
2528
+ for (let i = 0; i < data.length; i++) binary += String.fromCharCode(data[i] ?? 0);
2529
+ return btoa(binary);
2530
+ }
2531
+ function rebuildMessage(base, overrides) {
2532
+ const data = { ...base.toJSON(), ...overrides };
2533
+ return RCANMessage.fromJSON(data);
2534
+ }
2535
+ async function addMediaInline(message, data, mimeType) {
2536
+ const hashSha256 = await computeSha256Hex(data);
2537
+ const dataB64 = uint8ToBase64(data);
2538
+ const chunk = {
2539
+ chunkId: generateId6(),
2540
+ mimeType,
2541
+ encoding: "base64" /* BASE64 */,
2542
+ hashSha256,
2543
+ dataB64,
2544
+ sizeBytes: data.length
2545
+ };
2546
+ const existing = message.mediaChunks ?? [];
2547
+ return rebuildMessage(message, { mediaChunks: [...existing, chunk] });
2548
+ }
2549
+ function addMediaRef(message, refUrl, mimeType, hashSha256, sizeBytes) {
2550
+ const chunk = {
2551
+ chunkId: generateId6(),
2552
+ mimeType,
2553
+ encoding: "ref" /* REF */,
2554
+ hashSha256,
2555
+ refUrl,
2556
+ sizeBytes
2557
+ };
2558
+ const existing = message.mediaChunks ?? [];
2559
+ return rebuildMessage(message, { mediaChunks: [...existing, chunk] });
2560
+ }
2561
+ async function validateMediaChunks(message) {
2562
+ const chunks = message.mediaChunks ?? [];
2563
+ if (chunks.length === 0) {
2564
+ return { valid: true, reason: "no media chunks" };
2565
+ }
2566
+ for (let i = 0; i < chunks.length; i++) {
2567
+ const chunk = chunks[i];
2568
+ if (!chunk.chunkId) return { valid: false, reason: `chunk[${i}]: missing chunkId` };
2569
+ if (!chunk.mimeType) return { valid: false, reason: `chunk[${i}]: missing mimeType` };
2570
+ if (!chunk.hashSha256) return { valid: false, reason: `chunk[${i}]: missing hashSha256` };
2571
+ if (chunk.sizeBytes < 0) return { valid: false, reason: `chunk[${i}]: sizeBytes must be >= 0` };
2572
+ if (chunk.encoding === "base64" /* BASE64 */) {
2573
+ if (!chunk.dataB64) {
2574
+ return { valid: false, reason: `chunk[${i}]: BASE64 encoding requires dataB64` };
2575
+ }
2576
+ let decoded;
2577
+ try {
2578
+ if (typeof Buffer !== "undefined") {
2579
+ decoded = Buffer.from(chunk.dataB64, "base64");
2580
+ } else {
2581
+ const raw = atob(chunk.dataB64);
2582
+ decoded = new Uint8Array(raw.length);
2583
+ for (let j = 0; j < raw.length; j++) decoded[j] = raw.charCodeAt(j);
2584
+ }
2585
+ } catch {
2586
+ return { valid: false, reason: `chunk[${i}]: failed to decode base64 data` };
2587
+ }
2588
+ const actualHash = await computeSha256Hex(decoded);
2589
+ if (actualHash !== chunk.hashSha256) {
2590
+ return {
2591
+ valid: false,
2592
+ reason: `chunk[${i}]: SHA-256 mismatch (expected ${chunk.hashSha256}, got ${actualHash})`
2593
+ };
2594
+ }
2595
+ } else if (chunk.encoding === "ref" /* REF */) {
2596
+ if (!chunk.refUrl) {
2597
+ return { valid: false, reason: `chunk[${i}]: REF encoding requires refUrl` };
2598
+ }
2599
+ } else {
2600
+ return { valid: false, reason: `chunk[${i}]: unknown encoding '${chunk.encoding}'` };
2601
+ }
2602
+ }
2603
+ return { valid: true, reason: "ok" };
2604
+ }
2605
+ async function makeTrainingDataMessage(media) {
2606
+ let msg = new RCANMessage({
2607
+ rcan: "1.6",
2608
+ rcanVersion: "1.6",
2609
+ cmd: "training_data",
2610
+ target: "rcan://training/data",
2611
+ params: {
2612
+ msg_type: 10 /* TRAINING_DATA */,
2613
+ msg_id: generateId6()
2614
+ },
2615
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2616
+ });
2617
+ for (const item of media) {
2618
+ msg = await addMediaInline(msg, item.data, item.mimeType);
2619
+ }
2620
+ return msg;
2621
+ }
2622
+ async function makeStreamChunk(streamId, data, mimeType, chunkIndex, isFinal) {
2623
+ const hashSha256 = await computeSha256Hex(data);
2624
+ const dataB64 = uint8ToBase64(data);
2625
+ const chunk = {
2626
+ chunkId: generateId6(),
2627
+ mimeType,
2628
+ encoding: "base64" /* BASE64 */,
2629
+ hashSha256,
2630
+ dataB64,
2631
+ sizeBytes: data.length
2632
+ };
2633
+ const streamChunkMeta = {
2634
+ streamId,
2635
+ chunkIndex,
2636
+ isFinal,
2637
+ chunk
2638
+ };
2639
+ let msg = new RCANMessage({
2640
+ rcan: "1.6",
2641
+ rcanVersion: "1.6",
2642
+ cmd: "stream_chunk",
2643
+ target: "rcan://streaming/chunk",
2644
+ params: {
2645
+ msg_type: 7 /* SENSOR_DATA */,
2646
+ msg_id: generateId6(),
2647
+ stream_chunk: streamChunkMeta
2648
+ },
2649
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2650
+ });
2651
+ msg = rebuildMessage(msg, { mediaChunks: [chunk] });
2652
+ return msg;
2653
+ }
2654
+
2024
2655
  // src/index.ts
2025
- var VERSION = "0.5.0";
2026
- var RCAN_VERSION = "1.5";
2656
+ var VERSION = "0.6.0";
2657
+ var RCAN_VERSION = "1.6";
2027
2658
  export {
2028
2659
  AuditChain,
2029
2660
  AuditError,
2030
2661
  ClockDriftError,
2031
2662
  CommitmentRecord,
2032
2663
  ConfidenceGate,
2664
+ DEFAULT_LOA_POLICY,
2033
2665
  DataCategory,
2034
2666
  FaultCode,
2667
+ FederationSyncType,
2035
2668
  GateError,
2036
2669
  HiTLGate,
2037
2670
  KeyStore,
2671
+ LevelOfAssurance,
2672
+ MediaEncoding,
2038
2673
  MessageType,
2039
2674
  NodeClient,
2040
2675
  OfflineModeManager,
2676
+ PRODUCTION_LOA_POLICY,
2041
2677
  QoSAckTimeoutError,
2042
2678
  QoSLevel,
2043
2679
  QoSManager,
@@ -2059,17 +2695,31 @@ export {
2059
2695
  RCANVersionIncompatibleError,
2060
2696
  RCAN_VERSION,
2061
2697
  RegistryClient,
2698
+ RegistryTier,
2062
2699
  ReplayCache,
2063
2700
  RevocationCache,
2064
2701
  RobotURI,
2065
2702
  RobotURIError,
2066
2703
  SAFETY_MESSAGE_TYPE,
2704
+ SDK_VERSION,
2067
2705
  SPEC_VERSION,
2706
+ TransportEncoding,
2707
+ TransportError,
2708
+ TrustAnchorCache,
2068
2709
  VERSION,
2069
2710
  addDelegationHop,
2711
+ addMediaInline,
2712
+ addMediaRef,
2070
2713
  assertClockSynced,
2071
2714
  checkClockSync,
2072
2715
  checkRevocation,
2716
+ decodeBleFrames,
2717
+ decodeCompact,
2718
+ decodeMinimal,
2719
+ encodeBleFrames,
2720
+ encodeCompact,
2721
+ encodeMinimal,
2722
+ extractLoaFromJwt,
2073
2723
  fetchCanonicalSchema,
2074
2724
  isSafetyMessage,
2075
2725
  makeCloudRelayMessage,
@@ -2080,19 +2730,26 @@ export {
2080
2730
  makeEstopMessage,
2081
2731
  makeEstopWithQoS,
2082
2732
  makeFaultReport,
2733
+ makeFederationSync,
2083
2734
  makeKeyRotationMessage,
2084
2735
  makeResumeMessage,
2085
2736
  makeRevocationBroadcast,
2086
2737
  makeStopMessage,
2738
+ makeStreamChunk,
2087
2739
  makeTrainingConsentDeny,
2088
2740
  makeTrainingConsentGrant,
2089
2741
  makeTrainingConsentRequest,
2742
+ makeTrainingDataMessage,
2090
2743
  makeTransparencyMessage,
2744
+ selectTransport,
2091
2745
  validateConfig,
2092
2746
  validateConfigAgainstSchema,
2093
2747
  validateConfigUpdate,
2094
2748
  validateConsentMessage,
2749
+ validateCrossRegistryCommand,
2095
2750
  validateDelegationChain,
2751
+ validateLoaForScope,
2752
+ validateMediaChunks,
2096
2753
  validateMessage,
2097
2754
  validateNodeAgainstSchema,
2098
2755
  validateReplay,