@nekzus/liop 2.4.0-alpha.7 → 2.4.0-alpha.9

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.
Files changed (92) hide show
  1. package/NOTICE +19 -0
  2. package/README.md +36 -17
  3. package/dist/bin/agent.js +674 -82
  4. package/dist/bin/agent.js.map +1 -1
  5. package/dist/bridge.d.ts +2 -2
  6. package/dist/bridge.js +3 -3
  7. package/dist/{chunk-T5IUZF47.js → chunk-3L2O2XKG.js} +12 -5
  8. package/dist/chunk-3L2O2XKG.js.map +1 -0
  9. package/dist/{chunk-SONUORBT.js → chunk-7BSCUYUE.js} +2 -2
  10. package/dist/chunk-7BSCUYUE.js.map +1 -0
  11. package/dist/{chunk-QLCOEP5J.js → chunk-7PITYWOV.js} +2 -2
  12. package/dist/chunk-7PITYWOV.js.map +1 -0
  13. package/dist/{chunk-74CISO2I.js → chunk-7RXOIDXP.js} +28 -4
  14. package/dist/chunk-7RXOIDXP.js.map +1 -0
  15. package/dist/{chunk-GA3Q2S7O.js → chunk-BOISQ45Z.js} +5 -5
  16. package/dist/chunk-BOISQ45Z.js.map +1 -0
  17. package/dist/{chunk-547TYL27.js → chunk-DZ2FQGJD.js} +26 -1423
  18. package/dist/chunk-DZ2FQGJD.js.map +1 -0
  19. package/dist/{chunk-PYKRQAER.js → chunk-EG46XMJT.js} +2 -2
  20. package/dist/chunk-EG46XMJT.js.map +1 -0
  21. package/dist/chunk-ESRXG36Y.js +115 -0
  22. package/dist/chunk-ESRXG36Y.js.map +1 -0
  23. package/dist/chunk-FTF6AMF6.js +3 -0
  24. package/dist/{chunk-RWRRBYG4.js.map → chunk-FTF6AMF6.js.map} +1 -1
  25. package/dist/{chunk-72MNYFR6.js → chunk-HA6YZ42O.js} +2 -2
  26. package/dist/chunk-HA6YZ42O.js.map +1 -0
  27. package/dist/{chunk-WCCGE4QR.js → chunk-HD2N3IJX.js} +144 -30
  28. package/dist/chunk-HD2N3IJX.js.map +1 -0
  29. package/dist/{chunk-OUUTDSOW.js → chunk-IK7CGWAZ.js} +3 -3
  30. package/dist/chunk-IK7CGWAZ.js.map +1 -0
  31. package/dist/chunk-L6J72C5X.js +1477 -0
  32. package/dist/chunk-L6J72C5X.js.map +1 -0
  33. package/dist/{chunk-U5BZ66VX.js → chunk-PAICJCKJ.js} +60 -175
  34. package/dist/chunk-PAICJCKJ.js.map +1 -0
  35. package/dist/{chunk-32ADSAJS.js → chunk-PEN3KFLF.js} +14 -4
  36. package/dist/chunk-PEN3KFLF.js.map +1 -0
  37. package/dist/{chunk-CRZBVFDV.js → chunk-T7R5HUFD.js} +225 -66
  38. package/dist/chunk-T7R5HUFD.js.map +1 -0
  39. package/dist/{chunk-WSW6YJNY.js → chunk-TKRX6CFI.js} +3 -3
  40. package/dist/chunk-TKRX6CFI.js.map +1 -0
  41. package/dist/chunk-UCVP3XAL.js +279 -0
  42. package/dist/chunk-UCVP3XAL.js.map +1 -0
  43. package/dist/chunk-VH4K4U45.js +180 -0
  44. package/dist/chunk-VH4K4U45.js.map +1 -0
  45. package/dist/{chunk-JIJPZFR2.js → chunk-Y62GORQF.js} +2 -2
  46. package/dist/chunk-Y62GORQF.js.map +1 -0
  47. package/dist/chunk-ZP3VVXOI.js +66 -0
  48. package/dist/chunk-ZP3VVXOI.js.map +1 -0
  49. package/dist/client.d.ts +2 -2
  50. package/dist/client.js +11 -8
  51. package/dist/gateway.d.ts +3 -3
  52. package/dist/gateway.js +11 -9
  53. package/dist/{hybrid-CF__0YnC.d.ts → hybrid-CrKB50nh.d.ts} +2 -2
  54. package/dist/{index-cMV0_yD9.d.ts → index-CX43dvMs.d.ts} +2 -32
  55. package/dist/{index-BW95kAL4.d.ts → index-DoW2gzBZ.d.ts} +3 -21
  56. package/dist/index.d.ts +170 -46
  57. package/dist/index.js +20 -15
  58. package/dist/index.js.map +1 -1
  59. package/dist/kyber-CGOA7Q6A.js +3 -0
  60. package/dist/{kyber-3ULIJSE3.js.map → kyber-CGOA7Q6A.js.map} +1 -1
  61. package/dist/mesh.d.ts +27 -143
  62. package/dist/mesh.js +4 -3
  63. package/dist/node-B0b2vUFS.d.ts +164 -0
  64. package/dist/protocol/liop_core.proto +3 -0
  65. package/dist/server.d.ts +2 -2
  66. package/dist/server.js +7 -6
  67. package/dist/types.js +1 -1
  68. package/dist/verifier-HRFXBKT5.js +6 -0
  69. package/dist/{verifier-3FAKCFNN.js.map → verifier-HRFXBKT5.js.map} +1 -1
  70. package/dist/workers/logic-execution.js +3 -3
  71. package/dist/workers/logic-execution.js.map +1 -1
  72. package/dist/workers/zk-verifier.js +1 -1
  73. package/dist/workers/zk-verifier.js.map +1 -1
  74. package/package.json +8 -2
  75. package/dist/chunk-32ADSAJS.js.map +0 -1
  76. package/dist/chunk-547TYL27.js.map +0 -1
  77. package/dist/chunk-72MNYFR6.js.map +0 -1
  78. package/dist/chunk-74CISO2I.js.map +0 -1
  79. package/dist/chunk-CRZBVFDV.js.map +0 -1
  80. package/dist/chunk-GA3Q2S7O.js.map +0 -1
  81. package/dist/chunk-JIJPZFR2.js.map +0 -1
  82. package/dist/chunk-OUUTDSOW.js.map +0 -1
  83. package/dist/chunk-PYKRQAER.js.map +0 -1
  84. package/dist/chunk-QLCOEP5J.js.map +0 -1
  85. package/dist/chunk-RWRRBYG4.js +0 -3
  86. package/dist/chunk-SONUORBT.js.map +0 -1
  87. package/dist/chunk-T5IUZF47.js.map +0 -1
  88. package/dist/chunk-U5BZ66VX.js.map +0 -1
  89. package/dist/chunk-WCCGE4QR.js.map +0 -1
  90. package/dist/chunk-WSW6YJNY.js.map +0 -1
  91. package/dist/kyber-3ULIJSE3.js +0 -3
  92. package/dist/verifier-3FAKCFNN.js +0 -5
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  export { LiopBridgeOptions, LiopMcpBridge, LiopStreamBridge, LiopStreamBridgeOptions } from './bridge.js';
2
- import { L as LiopTlsOptions } from './index-cMV0_yD9.js';
3
- export { C as CertInfo, a as CertManager, b as CertManagerOptions, c as LiopClient } from './index-cMV0_yD9.js';
2
+ import { L as LiopTlsOptions } from './index-CX43dvMs.js';
3
+ export { C as CertInfo, a as CertManager, b as CertManagerOptions, c as LiopClient } from './index-CX43dvMs.js';
4
4
  import * as http from 'node:http';
5
- export { I as InMemoryRateLimiter, L as LiopHybridGateway, a as LiopMcpRouter, R as RateLimitStatus, b as RateLimiterOptions } from './hybrid-CF__0YnC.js';
6
- export { LiopManifest, MeshNode, MeshNodeConfig } from './mesh.js';
5
+ export { I as InMemoryRateLimiter, L as LiopHybridGateway, a as LiopMcpRouter, R as RateLimitStatus, b as RateLimiterOptions } from './hybrid-CrKB50nh.js';
6
+ export { L as LiopManifest, a as MeshNode, M as MeshNodeConfig } from './node-B0b2vUFS.js';
7
+ export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey } from './mesh.js';
7
8
  import * as grpc from '@grpc/grpc-js';
8
- export { A as AUTH_DEFAULTS, b as AggregationPolicy, c as AuditEntry, d as AuditLogger, e as AuditRecordParams, f as AuditStatus, g as AuthRole, G as GENESIS_HASH, h as LiopAuthConfig, L as LiopServer, a as LiopServerOptions, i as LogicExecutionPolicy, N as NerScanner, O as OAuthClientConfig, j as OutputSanitizerConfig, P as PII_PATTERNS, k as PII_PRESETS, l as PiiRule, m as PiiScanner, T as ToolHandler, n as computeEntryHash, o as globalAuditLogger, s as sanitizeOutput } from './index-BW95kAL4.js';
9
+ export { A as AUTH_DEFAULTS, b as AggregationPolicy, c as AuditEntry, d as AuditLogger, e as AuditRecordParams, f as AuditStatus, g as AuthRole, G as GENESIS_HASH, h as LiopAuthConfig, L as LiopServer, a as LiopServerOptions, i as LogicExecutionPolicy, N as NerScanner, O as OAuthClientConfig, j as OutputSanitizerConfig, P as PII_PATTERNS, k as PII_PRESETS, l as PiiRule, m as PiiScanner, T as ToolHandler, n as computeEntryHash, o as globalAuditLogger, s as sanitizeOutput } from './index-DoW2gzBZ.js';
9
10
  import { A as AuthInfo } from './types-lJIxBlWF.js';
10
11
  export { e as CacheableResult, C as CallToolRequest, a as CallToolResult, D as DiscoverResult, G as GetPromptRequest, d as GetPromptResult, I as InputRequest, f as InputRequiredResult, g as InputResponse, J as JwtValidator, h as MCP_LEGACY_SUPPORT_ENABLED, i as MCP_PROTOCOL_VERSION, j as MCP_PROTOCOL_VERSION_LEGACY, M as McpEra, b as McpRequest, k as McpRequestMeta, c as McpResponse, P as Prompt, l as PromptSchema, R as Resource, m as ResourceSchema, S as ServerInfo, T as Tool, n as ToolSchema } from './types-lJIxBlWF.js';
11
12
  import * as jose from 'jose';
@@ -113,6 +114,7 @@ interface TokenOperationMetric {
113
114
  readonly toolName?: string;
114
115
  readonly peerId?: string;
115
116
  readonly durationMs?: number;
117
+ readonly originDatasetTokens?: number;
116
118
  }
117
119
  /** Session-level aggregate report */
118
120
  interface TokenSessionReport {
@@ -313,17 +315,22 @@ declare class MetricsRegistry {
313
315
  }
314
316
  declare const protocolMetrics: MetricsRegistry;
315
317
  declare const toolCallsTotal: Counter;
318
+ declare const toolCallErrorsTotal: Counter;
316
319
  declare const fuelConsumed: Histogram;
317
320
  declare const meshPeersConnected: Gauge;
318
321
  declare const manifestCacheSize: Gauge;
319
322
  declare const egressBlocksTotal: Counter;
320
323
  declare const zkVerificationDurationMs: Histogram;
324
+ declare const zkVerificationsTotal: Counter;
325
+ declare const tokensInputTotal: Counter;
326
+ declare const tokensOutputTotal: Counter;
327
+ declare const tokensSavedTotal: Counter;
328
+ declare const operationDurationMs: Histogram;
329
+ declare const pqcHandshakeDurationMs: Histogram;
330
+ declare const pqcHandshakesTotal: Counter;
331
+ declare const wireEgressBytesTotal: Counter;
332
+ declare const wireSavedBytesTotal: Counter;
321
333
 
322
- /**
323
- * LIOP OpenTelemetry Distributed Tracing (Phase Beta-3)
324
- * W3C TraceContext compliant distributed tracer for gRPC & MCP transports.
325
- * Spec: https://www.w3.org/TR/trace-context/
326
- */
327
334
  interface SpanContext {
328
335
  traceId: string;
329
336
  spanId: string;
@@ -407,6 +414,7 @@ interface LogicResponse {
407
414
  is_error: boolean;
408
415
  }
409
416
 
417
+ type TokenProvider = string | (() => Promise<string | undefined> | string | undefined);
410
418
  /**
411
419
  * LIOP gRPC Client Implementation
412
420
  * Provides a high-level interface for secure intent negotiation and logic execution.
@@ -414,8 +422,11 @@ interface LogicResponse {
414
422
  declare class LiopRpcClient {
415
423
  private client;
416
424
  private token?;
425
+ private lastResolvedToken?;
417
426
  readonly address: string;
418
- constructor(address: string, tls?: LiopTlsOptions, token?: string);
427
+ constructor(address: string, tls?: LiopTlsOptions, token?: TokenProvider);
428
+ setToken(token?: TokenProvider): void;
429
+ private resolveToken;
419
430
  /**
420
431
  * Negotiates intent with the remote host.
421
432
  * Returns the ephemeral Kyber public key for payload encryption.
@@ -430,17 +441,28 @@ declare class LiopRpcClient {
430
441
  }
431
442
 
432
443
  /**
433
- * LIOP Post-Quantum Digital Signature Wrapper
434
- * Implements ML-DSA-65 (CRYSTALS-Dilithium, NIST FIPS 204) for quantum-resistant
435
- * manifest attestation, node revocation receipts, and cryptographic integrity.
436
- *
437
- * Characteristics:
438
- * - Security Category: NIST Level 3 (~AES-192 equivalent quantum resistance)
439
- * - Public Key Length: 1952 bytes
440
- * - Secret Key Length: 4032 bytes
441
- * - Signature Length: 3309 bytes
442
- * - Implementation: Pure TypeScript/JS via @noble/post-quantum
444
+ * LIOP Symmetric Payload Encryption Wrapper
445
+ * Uses AES-256-GCM to secure WASM Code transport over Zero-Trust networks.
446
+ * Fully compatible with the `aes-gcm` Rust crate used by Wasmtime.
443
447
  */
448
+ declare const AesGcmWrapper: {
449
+ /**
450
+ * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.
451
+ *
452
+ * @param payload Raw incoming WASM byte array or string.
453
+ * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array
454
+ * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.
455
+ */
456
+ encryptPayload(payload: Uint8Array | Buffer, sharedSecret: Uint8Array): {
457
+ ciphertext: Buffer;
458
+ nonce: Buffer;
459
+ };
460
+ /**
461
+ * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.
462
+ */
463
+ decryptPayload(ciphertextBuffer: Buffer, nonce: Buffer, sharedSecret: Uint8Array): Buffer;
464
+ };
465
+
444
466
  declare const DILITHIUM65_CONSTANTS: {
445
467
  readonly PUBLIC_KEY_BYTES: 1952;
446
468
  readonly SECRET_KEY_BYTES: 4032;
@@ -527,6 +549,132 @@ declare class LiopRpcServer {
527
549
  stop(): Promise<void>;
528
550
  }
529
551
 
552
+ type TransportProvider = "http-gateway" | "p2p-grpc" | "local";
553
+ interface ToolDefinition {
554
+ name: string;
555
+ description?: string;
556
+ inputSchema?: Record<string, unknown>;
557
+ }
558
+ interface ToolRoute {
559
+ name: string;
560
+ provider: TransportProvider;
561
+ endpoint: string;
562
+ description?: string;
563
+ inputSchema?: Record<string, unknown>;
564
+ latencyMs: number;
565
+ failCount: number;
566
+ lastSuccess: number;
567
+ authRequired?: boolean;
568
+ }
569
+ declare class RoutingTable {
570
+ private routes;
571
+ private static readonly MAX_FAILURES;
572
+ /**
573
+ * Registers or updates a collection of tools exposed via an HTTP Gateway.
574
+ */
575
+ registerGatewayTools(tools: ToolDefinition[], mcpEndpoint: string, authRequired?: boolean): void;
576
+ /**
577
+ * Registers tools discovered directly over the P2P Mesh (gRPC).
578
+ */
579
+ registerMeshTools(tools: ToolDefinition[], grpcTarget: string, authRequired?: boolean): void;
580
+ /**
581
+ * Registers an in-process local tool (e.g. LiopMeshStatus).
582
+ */
583
+ registerLocalTool(tool: ToolDefinition): void;
584
+ /**
585
+ * Resolves the optimal route for a specific tool.
586
+ */
587
+ resolve(toolName: string): ToolRoute | undefined;
588
+ /**
589
+ * Records a successful invocation on a route, resetting failures and updating latency.
590
+ */
591
+ recordSuccess(toolName: string, latencyMs: number): void;
592
+ /**
593
+ * Records a failed invocation on a route.
594
+ */
595
+ recordFailure(toolName: string): void;
596
+ /**
597
+ * Lists all registered tools in sorted format for tools/list.
598
+ */
599
+ getAllToolDefinitions(): ToolDefinition[];
600
+ getRoute(toolName: string): ToolRoute | undefined;
601
+ size(): number;
602
+ clear(): void;
603
+ }
604
+
605
+ interface TokenManagerOptions {
606
+ tokenEndpoint: string;
607
+ clientId: string;
608
+ clientSecret: string;
609
+ audience?: string;
610
+ scopes?: string | string[];
611
+ staticToken?: string;
612
+ }
613
+ declare class TokenManager {
614
+ private cachedToken;
615
+ private expiresAt;
616
+ private pendingPromise;
617
+ private readonly tokenEndpoint;
618
+ private readonly clientId;
619
+ private readonly clientSecret;
620
+ private readonly audience;
621
+ private readonly scope;
622
+ private staticToken?;
623
+ private static readonly REFRESH_BUFFER_MS;
624
+ constructor(options: TokenManagerOptions);
625
+ /**
626
+ * Returns a valid OAuth 2.1 access token.
627
+ * Automatically performs preemptive refresh if the token is close to expiry.
628
+ */
629
+ getToken(): Promise<string>;
630
+ /**
631
+ * Force-invalidates cached token, e.g. after receiving a 401 Unauthorized response.
632
+ */
633
+ invalidate(): void;
634
+ /**
635
+ * Returns true if the token is absent or has passed the refresh threshold.
636
+ */
637
+ isExpired(): boolean;
638
+ getExpiresAt(): number;
639
+ private fetchNewToken;
640
+ }
641
+
642
+ interface GatewayTopologyInfo {
643
+ baseUrl: string;
644
+ mcpEndpoint: string;
645
+ healthEndpoint: string;
646
+ tokenEndpoint: string;
647
+ issuer: string;
648
+ audience: string;
649
+ scopes: string[];
650
+ tools: string[];
651
+ tier: number;
652
+ }
653
+ interface MeshTopologyInfo {
654
+ bootstrapNodes: string[];
655
+ identityPath?: string;
656
+ }
657
+ interface TopologyProbeResult {
658
+ mode: "gateway" | "mesh" | "hybrid";
659
+ gateway?: GatewayTopologyInfo;
660
+ mesh?: MeshTopologyInfo;
661
+ }
662
+ interface TopologyProbeOptions {
663
+ blgUrl?: string;
664
+ nexusUrl?: string;
665
+ clientId?: string;
666
+ clientSecret?: string;
667
+ audience?: string;
668
+ staticToken?: string;
669
+ bootstrapNodes?: string[];
670
+ identityPath?: string;
671
+ autoProbeLocal?: boolean;
672
+ }
673
+ /**
674
+ * Probes the runtime environment and determines the optimal architecture mode.
675
+ */
676
+ declare function probeTopology(options?: TopologyProbeOptions): Promise<TopologyProbeResult>;
677
+
530
678
  /**
531
679
  * Returns a filtered environment object containing only safe system variables,
532
680
  * preventing exposure of sensitive credentials and shell function injection.
@@ -574,21 +722,6 @@ declare class WasiSandbox {
574
722
  teardown(): Promise<void>;
575
723
  }
576
724
 
577
- /**
578
- * LIOP Embedded OAuth 2.1 Authorization Server
579
- *
580
- * Implements a lightweight, high-performance OAuth 2.1 / OIDC Authorization Server
581
- * for the Nexus node using `panva/node-oidc-provider`.
582
- *
583
- * Security Hardening:
584
- * - M2M (Machine-to-Machine) Client Credentials Grant ONLY (Zero human interaction interface).
585
- * - Algorithmic whitelist: EdDSA (Ed25519) for token signing.
586
- * - JWT Access Tokens: Allows stateless, cryptographically-secure validation on data nodes (NIST SP 800-207).
587
- * - Interaction Lockout: Throws exception on any interactive flow attempt to prevent hijack attacks (OWASP).
588
- *
589
- * Standards: OAuth 2.1, RFC 6749, RFC 7519, NIST SP 800-63B
590
- */
591
-
592
725
  interface OAuthServerClientConfig {
593
726
  client_id: string;
594
727
  client_secret: string;
@@ -610,15 +743,6 @@ interface OAuthServerResult {
610
743
  */
611
744
  declare function createOAuthServer(config: OAuthServerConfig): OAuthServerResult;
612
745
 
613
- /**
614
- * LIOP Protected Resource Metadata — RFC 9728
615
- *
616
- * Builds the JSON document served at /.well-known/oauth-protected-resource.
617
- * This enables MCP clients to discover the authorization server and
618
- * required scopes for accessing LIOP tools and resources.
619
- *
620
- * Standards: RFC 9728, MCP Spec 2025-11-25
621
- */
622
746
  /**
623
747
  * RFC 9728 Protected Resource Metadata response.
624
748
  *
@@ -683,4 +807,4 @@ declare function authorizeRequest(method: string, auth: AuthInfo | null, additio
683
807
  declare const LIOP_SCOPES: readonly ["liop:tools:list", "liop:tools:call", "liop:resources:read", "liop:schema:read", "liop:mesh:query"];
684
808
  type LiopScope = (typeof LIOP_SCOPES)[number];
685
809
 
686
- export { type AIProvider, AuthInfo, Counter, DILITHIUM65_CONSTANTS, Dilithium65Wrapper, ErrorCode, GRPC_CHANNEL_OPTIONS, GRPC_WEB_CONSTANTS, Gauge, type GrpcWebFrame, HeuristicTokenEstimator, Histogram, Kyber768Wrapper, LIOP_SCOPES, LiopError, LiopOTelBridge, LiopRpcClient, LiopRpcServer, type LiopScope, type LiopSpan, LiopTracer, type MetricDefinition, type MetricLabels, MetricsRegistry, type PromptConfig, RealTokenEstimator, type SandboxConfig, type SpanContext, type TokenEstimator, type TokenOperationMetric, type TokenSessionReport, TokenTelemetryEngine, type ToolTokenBreakdown, WasiSandbox, authorizeRequest, buildProtectedResourceMetadata, calculateAstInstructionFuel, createOAuthServer, createSyncTokenEstimator, createTokenEstimator, decodeFrames, defaultTracer, dispatchGrpcWebRequest, egressBlocksTotal, encodeDataFrame, encodeTrailerFrame, fuelConsumed, generateSystemInstructions, getDefaultEnvironment, isGrpcWebRequest, manifestCacheSize, meshPeersConnected, protocolMetrics, toolCallsTotal, zkVerificationDurationMs };
810
+ export { type AIProvider, AesGcmWrapper, AuthInfo, Counter, DILITHIUM65_CONSTANTS, Dilithium65Wrapper, ErrorCode, GRPC_CHANNEL_OPTIONS, GRPC_WEB_CONSTANTS, type GatewayTopologyInfo, Gauge, type GrpcWebFrame, HeuristicTokenEstimator, Histogram, Kyber768Wrapper, LIOP_SCOPES, LiopError, LiopOTelBridge, LiopRpcClient, LiopRpcServer, type LiopScope, type LiopSpan, LiopTracer, type MeshTopologyInfo, type MetricDefinition, type MetricLabels, MetricsRegistry, type PromptConfig, RealTokenEstimator, RoutingTable, type SandboxConfig, type SpanContext, type TokenEstimator, TokenManager, type TokenManagerOptions, type TokenOperationMetric, type TokenProvider, type TokenSessionReport, TokenTelemetryEngine, type ToolDefinition, type ToolRoute, type ToolTokenBreakdown, type TopologyProbeOptions, type TopologyProbeResult, type TransportProvider, WasiSandbox, authorizeRequest, buildProtectedResourceMetadata, calculateAstInstructionFuel, createOAuthServer, createSyncTokenEstimator, createTokenEstimator, decodeFrames, defaultTracer, dispatchGrpcWebRequest, egressBlocksTotal, encodeDataFrame, encodeTrailerFrame, fuelConsumed, generateSystemInstructions, getDefaultEnvironment, isGrpcWebRequest, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, probeTopology, protocolMetrics, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, wireEgressBytesTotal, wireSavedBytesTotal, zkVerificationDurationMs, zkVerificationsTotal };
package/dist/index.js CHANGED
@@ -1,18 +1,23 @@
1
- export { WasiSandbox, calculateAstInstructionFuel, getDefaultEnvironment } from './chunk-SONUORBT.js';
2
- export { LiopClient, LiopRpcClient } from './chunk-CRZBVFDV.js';
3
- export { LiopMcpBridge, LiopStreamBridge } from './chunk-GA3Q2S7O.js';
4
- export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, isGrpcWebRequest } from './chunk-T5IUZF47.js';
5
- export { AUTH_DEFAULTS, AuditLogger, GENESIS_HASH, JwtValidator, LiopRpcServer, LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner, computeEntryHash, createOAuthServer, globalAuditLogger } from './chunk-WCCGE4QR.js';
6
- export { sanitizeOutput } from './chunk-JIJPZFR2.js';
7
- export { HeuristicTokenEstimator, LiopMcpRouter, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator } from './chunk-547TYL27.js';
8
- import './chunk-32ADSAJS.js';
9
- import './chunk-OUUTDSOW.js';
10
- export { Kyber768Wrapper } from './chunk-QLCOEP5J.js';
11
- export { Counter, DILITHIUM65_CONSTANTS, Dilithium65Wrapper, Gauge, Histogram, LIOP_SCOPES, MetricsRegistry, authorizeRequest, egressBlocksTotal, fuelConsumed, manifestCacheSize, meshPeersConnected, protocolMetrics, toolCallsTotal, zkVerificationDurationMs } from './chunk-U5BZ66VX.js';
12
- export { GRPC_CHANNEL_OPTIONS } from './chunk-WSW6YJNY.js';
13
- export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema } from './chunk-PYKRQAER.js';
14
- export { MeshNode } from './chunk-74CISO2I.js';
15
- import { log } from './chunk-72MNYFR6.js';
1
+ export { WasiSandbox, calculateAstInstructionFuel, getDefaultEnvironment } from './chunk-7BSCUYUE.js';
2
+ export { AesGcmWrapper, LiopClient, LiopRpcClient } from './chunk-T7R5HUFD.js';
3
+ export { LiopMcpBridge, LiopStreamBridge } from './chunk-BOISQ45Z.js';
4
+ export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, isGrpcWebRequest } from './chunk-3L2O2XKG.js';
5
+ export { RoutingTable, probeTopology } from './chunk-UCVP3XAL.js';
6
+ export { TokenManager } from './chunk-ESRXG36Y.js';
7
+ export { AUTH_DEFAULTS, AuditLogger, GENESIS_HASH, JwtValidator, LiopRpcServer, LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner, computeEntryHash, createOAuthServer, globalAuditLogger } from './chunk-HD2N3IJX.js';
8
+ export { sanitizeOutput } from './chunk-Y62GORQF.js';
9
+ export { LiopMcpRouter } from './chunk-L6J72C5X.js';
10
+ export { HeuristicTokenEstimator, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator } from './chunk-DZ2FQGJD.js';
11
+ import './chunk-PEN3KFLF.js';
12
+ import './chunk-IK7CGWAZ.js';
13
+ export { Kyber768Wrapper } from './chunk-7PITYWOV.js';
14
+ export { DILITHIUM65_CONSTANTS, Dilithium65Wrapper, LIOP_SCOPES, authorizeRequest } from './chunk-VH4K4U45.js';
15
+ export { GRPC_CHANNEL_OPTIONS } from './chunk-TKRX6CFI.js';
16
+ export { Counter, Gauge, Histogram, MetricsRegistry, egressBlocksTotal, fuelConsumed, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, protocolMetrics, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, wireEgressBytesTotal, wireSavedBytesTotal, zkVerificationDurationMs, zkVerificationsTotal } from './chunk-PAICJCKJ.js';
17
+ export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema } from './chunk-EG46XMJT.js';
18
+ export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey } from './chunk-ZP3VVXOI.js';
19
+ export { MeshNode } from './chunk-7RXOIDXP.js';
20
+ import { log } from './chunk-HA6YZ42O.js';
16
21
  import * as crypto from 'crypto';
17
22
  import { EventEmitter } from 'events';
18
23
  import * as fs from 'fs';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/observability/tracing.ts","../src/prompts/adapters.ts","../src/security/cert-manager.ts"],"names":["ErrorCode","crypto2"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAO,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AACN,EAAAA,WAAA,qBAAA,CAAA,GAAsB,qBAAA;AACtB,EAAAA,WAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,WAAA,SAAA,CAAA,GAAU,SAAA;AACV,EAAAA,WAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,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tSandboxEscape = \"SandboxEscape\",\n\tPiiLeak = \"PiiLeak\",\n\tInvalidIntent = \"InvalidIntent\",\n\tThrottled = \"Throttled\",\n\tZkVerificationFailed = \"ZkVerificationFailed\",\n\tMeshUnavailable = \"MeshUnavailable\",\n\tConnectionFailed = \"ConnectionFailed\",\n}\n\nexport class LiopError extends Error {\n\tpublic readonly code: ErrorCode;\n\n\tconstructor(code: ErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"LiopError\";\n\t\tthis.code = code;\n\t}\n}\n","/**\n * LIOP OpenTelemetry Distributed Tracing (Phase Beta-3)\n * W3C TraceContext compliant distributed tracer for gRPC & MCP transports.\n * Spec: https://www.w3.org/TR/trace-context/\n */\n\nimport * as crypto from \"node:crypto\";\n\nexport interface SpanContext {\n\ttraceId: string;\n\tspanId: string;\n\tsampled: boolean;\n}\n\nexport interface LiopSpan {\n\treadonly name: string;\n\treadonly context: SpanContext;\n\treadonly startTime: number;\n\tendTime?: number;\n\tattributes: Record<string, string | number | boolean>;\n\tstatus: \"OK\" | \"ERROR\";\n\terror?: string;\n\tsetAttribute(key: string, value: string | number | boolean): LiopSpan;\n\trecordException(error: Error | string): LiopSpan;\n\tend(): void;\n}\n\nconst TRACEPARENT_REGEX =\n\t/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport class LiopTracer {\n\tpublic static generateTraceId(): string {\n\t\tlet id: string;\n\t\tdo {\n\t\t\tid = crypto.randomBytes(16).toString(\"hex\");\n\t\t} while (id === \"0\".repeat(32));\n\t\treturn id;\n\t}\n\n\tpublic static generateSpanId(): string {\n\t\tlet id: string;\n\t\tdo {\n\t\t\tid = crypto.randomBytes(8).toString(\"hex\");\n\t\t} while (id === \"0\".repeat(16));\n\t\treturn id;\n\t}\n\n\tpublic static formatTraceparent(\n\t\ttraceId: string,\n\t\tspanId: string,\n\t\tsampled = true,\n\t): string {\n\t\tconst flags = sampled ? \"01\" : \"00\";\n\t\treturn `00-${traceId}-${spanId}-${flags}`;\n\t}\n\n\tpublic static parseTraceparent(header?: string | null): SpanContext | null {\n\t\tif (!header || typeof header !== \"string\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst trimmed = header.trim();\n\t\tconst match = TRACEPARENT_REGEX.exec(trimmed);\n\t\tif (!match) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst [, version, traceId, spanId, flags] = match;\n\t\t// Version 00 cannot have all-zeros traceId or spanId\n\t\tif (version === \"00\") {\n\t\t\tif (traceId === \"0\".repeat(32) || spanId === \"0\".repeat(16)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tconst sampled = (Number.parseInt(flags, 16) & 0x01) === 1;\n\t\treturn {\n\t\t\ttraceId,\n\t\t\tspanId,\n\t\t\tsampled,\n\t\t};\n\t}\n\n\tpublic static injectTraceparent(\n\t\tcarrier: Record<string, string | string[] | undefined>,\n\t\tcontext: SpanContext,\n\t): void {\n\t\tcarrier.traceparent = LiopTracer.formatTraceparent(\n\t\t\tcontext.traceId,\n\t\t\tcontext.spanId,\n\t\t\tcontext.sampled,\n\t\t);\n\t}\n\n\tpublic static extractTraceparent(\n\t\tcarrier: Record<string, string | string[] | undefined>,\n\t): SpanContext | null {\n\t\tconst val = carrier.traceparent || carrier.Traceparent;\n\t\tif (Array.isArray(val)) {\n\t\t\treturn LiopTracer.parseTraceparent(val[0]);\n\t\t}\n\t\treturn LiopTracer.parseTraceparent(val);\n\t}\n\n\tpublic startSpan(\n\t\tname: string,\n\t\tparent?: SpanContext | null,\n\t\tattributes: Record<string, string | number | boolean> = {},\n\t): LiopSpan {\n\t\tconst traceId = parent?.traceId || LiopTracer.generateTraceId();\n\t\tconst spanId = LiopTracer.generateSpanId();\n\t\tconst sampled = parent ? parent.sampled : true;\n\n\t\tconst context: SpanContext = {\n\t\t\ttraceId,\n\t\t\tspanId,\n\t\t\tsampled,\n\t\t};\n\n\t\tconst span: LiopSpan = {\n\t\t\tname,\n\t\t\tcontext,\n\t\t\tstartTime: Date.now(),\n\t\t\tattributes: { ...attributes },\n\t\t\tstatus: \"OK\",\n\t\t\tsetAttribute(key, value) {\n\t\t\t\tthis.attributes[key] = value;\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\trecordException(err) {\n\t\t\t\tthis.status = \"ERROR\";\n\t\t\t\tthis.error = typeof err === \"string\" ? err : err.message;\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tend() {\n\t\t\t\tthis.endTime = Date.now();\n\t\t\t},\n\t\t};\n\n\t\treturn span;\n\t}\n}\n\nexport const defaultTracer = new LiopTracer();\n","/**\n * LIOP Cross-AI Prompt Adapters (Fase 92)\n *\n * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)\n * to ensure they understand how to generate \"Logic-on-Origin\" WASM-compatible payload structures.\n */\n\nexport type AIProvider = \"claude\" | \"openai\" | \"gemini\";\n\nexport interface PromptConfig {\n\txmlStandard: boolean;\n\tjsonSchemaPreferred: boolean;\n}\n\nconst PROVIDER_CONFIGS: Record<AIProvider, PromptConfig> = {\n\tclaude: { xmlStandard: true, jsonSchemaPreferred: false },\n\topenai: { xmlStandard: false, jsonSchemaPreferred: true },\n\tgemini: { xmlStandard: false, jsonSchemaPreferred: true },\n};\n\n/**\n * Generates specific System Prompts optimized for the provided AI.\n * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).\n */\nexport function generateSystemInstructions(provider: AIProvider): string {\n\tconst config = PROVIDER_CONFIGS[provider];\n\n\tlet instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]\nYou are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.\nUnlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.\n\n### CORE PARADIGM\nWhen you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.\nThe node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.\n\n### EXECUTION RULES\n1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.\n2. Rely only on standard ECMA script features (No Node.js polyfills).\n3. The logic must end by returning the calculated insights, not the raw data.\n\n### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)\nTo prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:\n- COUNT / LENGTH queries: To get EXACT integer values without noise, you MUST name return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.\n- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).\n- SUM / OTHER queries: Return keys without these semantic names receive full Laplace noise based on the global node sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.\n\n### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS\n- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).\n - Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').\n- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.\n- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.\n- K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.\n`;\n\n\tif (config.xmlStandard) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)\nYou must wrap your logic precisely within <liop_logic> tags.\nExample:\n<liop_logic>\nconst records = await liop.readResource(\"liop://vault/patients\");\nconst filtered = records.filter(r => r.disease === \"Hypertension\");\nreturn { alert: \"High risk demographic\", targetCount: filtered.length };\n</liop_logic>\n`;\n\t} else if (config.jsonSchemaPreferred) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (JSON PARSING PREFERRED)\nYou must provide your logic strictly within a JSON string key called \\`\"logic_blob\"\\` inside your tool call parameters.\nExample:\n{\n \"target\": \"liop://vault/patients\",\n \"logic_blob\": \"const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };\"\n}\n`;\n\t}\n\n\treturn instructions;\n}\n","/**\n * LIOP Certificate Manager (CertManager)\n * Provides automated certificate monitoring, X.509 validity inspection,\n * and hot-reloading for mutual TLS (mTLS) without node restarts.\n *\n * Compliance:\n * - NIST SP 800-52 Rev. 2: Guidelines for the Selection and Use of TLS\n * - Zero-Trust Architecture (NIST SP 800-207): Continuous cryptographic verification\n */\n\nimport * as crypto from \"node:crypto\";\nimport { EventEmitter } from \"node:events\";\nimport * as fs from \"node:fs\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface CertManagerOptions {\n\t/** Path to the root CA certificate (PEM format) */\n\trootCertPath?: string;\n\t/** Path to the server/client certificate chain (PEM format) */\n\tcertChainPath: string;\n\t/** Path to the private key (PEM format) */\n\tprivateKeyPath: string;\n\t/** Expiration warning threshold in days (default: 30) */\n\twarningDays?: number;\n\t/** Enable file watching for automatic hot-reloading (default: true) */\n\twatchFiles?: boolean;\n\t/** Debounce delay in ms for hot reloading (default: 150) */\n\tdebounceMs?: number;\n}\n\nexport interface CertInfo {\n\tsubject: string;\n\tissuer: string;\n\tvalidFrom: string;\n\tvalidTo: string;\n\tfingerprint256: string;\n\tdaysRemaining: number;\n\tisExpired: boolean;\n\tisExpiringSoon: boolean;\n}\n\nexport class CertManager extends EventEmitter {\n\tprivate rootCertBuffer: Buffer | null = null;\n\tprivate certChainBuffer: Buffer | null = null;\n\tprivate privateKeyBuffer: Buffer | null = null;\n\tprivate watchers: fs.FSWatcher[] = [];\n\tprivate reloadDebounceTimer: NodeJS.Timeout | null = null;\n\tprivate readonly warningDays: number;\n\tprivate readonly debounceMs: number;\n\n\tconstructor(private readonly options: CertManagerOptions) {\n\t\tsuper();\n\t\tthis.warningDays = options.warningDays ?? 30;\n\t\tthis.debounceMs = options.debounceMs ?? 150;\n\t\tthis.loadCertificates();\n\n\t\tif (options.watchFiles !== false) {\n\t\t\tthis.setupWatchers();\n\t\t}\n\t}\n\n\t/**\n\t * Synchronously loads or reloads certificates from filesystem into memory.\n\t */\n\tpublic loadCertificates(): void {\n\t\ttry {\n\t\t\tif (\n\t\t\t\tthis.options.rootCertPath &&\n\t\t\t\tfs.existsSync(this.options.rootCertPath)\n\t\t\t) {\n\t\t\t\tthis.rootCertBuffer = fs.readFileSync(this.options.rootCertPath);\n\t\t\t}\n\n\t\t\tif (!fs.existsSync(this.options.certChainPath)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Certificate chain file not found: ${this.options.certChainPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!fs.existsSync(this.options.privateKeyPath)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Private key file not found: ${this.options.privateKeyPath}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.certChainBuffer = fs.readFileSync(this.options.certChainPath);\n\t\t\tthis.privateKeyBuffer = fs.readFileSync(this.options.privateKeyPath);\n\n\t\t\tlog.info(\"[CertManager] Certificates loaded successfully.\");\n\t\t} catch (error) {\n\t\t\tlog.error(`[CertManager] Failed to load certificates: ${error}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Inspects the loaded server/client certificate chain using Node.js native X509Certificate.\n\t */\n\tpublic inspectCertificate(): CertInfo {\n\t\tif (!this.certChainBuffer) {\n\t\t\tthrow new Error(\"[CertManager] No certificate loaded to inspect.\");\n\t\t}\n\n\t\tconst x509 = new crypto.X509Certificate(this.certChainBuffer);\n\t\tconst validToDate = new Date(x509.validTo);\n\t\tconst now = new Date();\n\t\tconst msRemaining = validToDate.getTime() - now.getTime();\n\t\tconst daysRemaining = Math.max(\n\t\t\t0,\n\t\t\tMath.floor(msRemaining / (1000 * 60 * 60 * 24)),\n\t\t);\n\t\tconst isExpired = msRemaining <= 0;\n\t\tconst isExpiringSoon = daysRemaining <= this.warningDays;\n\n\t\treturn {\n\t\t\tsubject: x509.subject,\n\t\t\tissuer: x509.issuer,\n\t\t\tvalidFrom: x509.validFrom,\n\t\t\tvalidTo: x509.validTo,\n\t\t\tfingerprint256: x509.fingerprint256,\n\t\t\tdaysRemaining,\n\t\t\tisExpired,\n\t\t\tisExpiringSoon,\n\t\t};\n\t}\n\n\t/**\n\t * Sets up non-blocking filesystem watchers to detect certificate renewals\n\t * and trigger hot-reloading without process restarts.\n\t */\n\tprivate setupWatchers(): void {\n\t\tconst filesToWatch = [\n\t\t\tthis.options.certChainPath,\n\t\t\tthis.options.privateKeyPath,\n\t\t\tthis.options.rootCertPath,\n\t\t].filter((p): p is string => Boolean(p && fs.existsSync(p)));\n\n\t\tfor (const filePath of filesToWatch) {\n\t\t\ttry {\n\t\t\t\tconst watcher = fs.watch(filePath, () => {\n\t\t\t\t\tthis.scheduleReload();\n\t\t\t\t});\n\t\t\t\tthis.watchers.push(watcher);\n\t\t\t} catch (err) {\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[CertManager] Could not watch ${filePath} for hot reloading: ${err}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Debounces reload events to ensure files have finished writing.\n\t */\n\tprivate scheduleReload(): void {\n\t\tif (this.reloadDebounceTimer) {\n\t\t\tclearTimeout(this.reloadDebounceTimer);\n\t\t}\n\n\t\tthis.reloadDebounceTimer = setTimeout(() => {\n\t\t\ttry {\n\t\t\t\tthis.loadCertificates();\n\t\t\t\tconst certInfo = this.inspectCertificate();\n\t\t\t\tlog.info(\n\t\t\t\t\t`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`,\n\t\t\t\t);\n\t\t\t\tthis.emit(\"reload\", certInfo);\n\t\t\t} catch (error) {\n\t\t\t\tlog.error(`[CertManager] Hot reload failed: ${error}`);\n\t\t\t\tthis.emit(\"error\", error);\n\t\t\t}\n\t\t}, this.debounceMs);\n\t}\n\n\t/**\n\t * Manually triggers a reload of certificates and emits the 'reload' event.\n\t */\n\tpublic reload(): CertInfo {\n\t\tthis.loadCertificates();\n\t\tconst certInfo = this.inspectCertificate();\n\t\tlog.info(\n\t\t\t`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`,\n\t\t);\n\t\tthis.emit(\"reload\", certInfo);\n\t\treturn certInfo;\n\t}\n\n\tpublic getRootCert(): Buffer | null {\n\t\treturn this.rootCertBuffer;\n\t}\n\n\tpublic getCertChain(): Buffer {\n\t\tif (!this.certChainBuffer) {\n\t\t\tthrow new Error(\"[CertManager] Certificate chain not loaded.\");\n\t\t}\n\t\treturn this.certChainBuffer;\n\t}\n\n\tpublic getPrivateKey(): Buffer {\n\t\tif (!this.privateKeyBuffer) {\n\t\t\tthrow new Error(\"[CertManager] Private key not loaded.\");\n\t\t}\n\t\treturn this.privateKeyBuffer;\n\t}\n\n\t/**\n\t * Stops all active file watchers and releases resources.\n\t */\n\tpublic dispose(): void {\n\t\tif (this.reloadDebounceTimer) {\n\t\t\tclearTimeout(this.reloadDebounceTimer);\n\t\t\tthis.reloadDebounceTimer = null;\n\t\t}\n\t\tfor (const watcher of this.watchers) {\n\t\t\ttry {\n\t\t\t\twatcher.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore watcher close errors\n\t\t\t}\n\t\t}\n\t\tthis.watchers = [];\n\t\tthis.removeAllListeners();\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/observability/tracing.ts","../src/prompts/adapters.ts","../src/security/cert-manager.ts"],"names":["ErrorCode","crypto2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AACN,EAAAA,WAAA,qBAAA,CAAA,GAAsB,qBAAA;AACtB,EAAAA,WAAA,eAAA,CAAA,GAAgB,eAAA;AAChB,EAAAA,W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AA,EACzB;AACD","file":"index.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nexport enum ErrorCode {\n\tCapabilityViolation = \"CapabilityViolation\",\n\tSandboxEscape = \"SandboxEscape\",\n\tPiiLeak = \"PiiLeak\",\n\tInvalidIntent = \"InvalidIntent\",\n\tThrottled = \"Throttled\",\n\tZkVerificationFailed = \"ZkVerificationFailed\",\n\tMeshUnavailable = \"MeshUnavailable\",\n\tConnectionFailed = \"ConnectionFailed\",\n}\n\nexport class LiopError extends Error {\n\tpublic readonly code: ErrorCode;\n\n\tconstructor(code: ErrorCode, message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"LiopError\";\n\t\tthis.code = code;\n\t}\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP OpenTelemetry Distributed Tracing (Phase Beta-3)\n * W3C TraceContext compliant distributed tracer for gRPC & MCP transports.\n * Spec: https://www.w3.org/TR/trace-context/\n */\n\nimport * as crypto from \"node:crypto\";\n\nexport interface SpanContext {\n\ttraceId: string;\n\tspanId: string;\n\tsampled: boolean;\n}\n\nexport interface LiopSpan {\n\treadonly name: string;\n\treadonly context: SpanContext;\n\treadonly startTime: number;\n\tendTime?: number;\n\tattributes: Record<string, string | number | boolean>;\n\tstatus: \"OK\" | \"ERROR\";\n\terror?: string;\n\tsetAttribute(key: string, value: string | number | boolean): LiopSpan;\n\trecordException(error: Error | string): LiopSpan;\n\tend(): void;\n}\n\nconst TRACEPARENT_REGEX =\n\t/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;\n\nexport class LiopTracer {\n\tpublic static generateTraceId(): string {\n\t\tlet id: string;\n\t\tdo {\n\t\t\tid = crypto.randomBytes(16).toString(\"hex\");\n\t\t} while (id === \"0\".repeat(32));\n\t\treturn id;\n\t}\n\n\tpublic static generateSpanId(): string {\n\t\tlet id: string;\n\t\tdo {\n\t\t\tid = crypto.randomBytes(8).toString(\"hex\");\n\t\t} while (id === \"0\".repeat(16));\n\t\treturn id;\n\t}\n\n\tpublic static formatTraceparent(\n\t\ttraceId: string,\n\t\tspanId: string,\n\t\tsampled = true,\n\t): string {\n\t\tconst flags = sampled ? \"01\" : \"00\";\n\t\treturn `00-${traceId}-${spanId}-${flags}`;\n\t}\n\n\tpublic static parseTraceparent(header?: string | null): SpanContext | null {\n\t\tif (!header || typeof header !== \"string\") {\n\t\t\treturn null;\n\t\t}\n\t\tconst trimmed = header.trim();\n\t\tconst match = TRACEPARENT_REGEX.exec(trimmed);\n\t\tif (!match) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst [, version, traceId, spanId, flags] = match;\n\t\t// Version 00 cannot have all-zeros traceId or spanId\n\t\tif (version === \"00\") {\n\t\t\tif (traceId === \"0\".repeat(32) || spanId === \"0\".repeat(16)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tconst sampled = (Number.parseInt(flags, 16) & 0x01) === 1;\n\t\treturn {\n\t\t\ttraceId,\n\t\t\tspanId,\n\t\t\tsampled,\n\t\t};\n\t}\n\n\tpublic static injectTraceparent(\n\t\tcarrier: Record<string, string | string[] | undefined>,\n\t\tcontext: SpanContext,\n\t): void {\n\t\tcarrier.traceparent = LiopTracer.formatTraceparent(\n\t\t\tcontext.traceId,\n\t\t\tcontext.spanId,\n\t\t\tcontext.sampled,\n\t\t);\n\t}\n\n\tpublic static extractTraceparent(\n\t\tcarrier: Record<string, string | string[] | undefined>,\n\t): SpanContext | null {\n\t\tconst val = carrier.traceparent || carrier.Traceparent;\n\t\tif (Array.isArray(val)) {\n\t\t\treturn LiopTracer.parseTraceparent(val[0]);\n\t\t}\n\t\treturn LiopTracer.parseTraceparent(val);\n\t}\n\n\tpublic startSpan(\n\t\tname: string,\n\t\tparent?: SpanContext | null,\n\t\tattributes: Record<string, string | number | boolean> = {},\n\t): LiopSpan {\n\t\tconst traceId = parent?.traceId || LiopTracer.generateTraceId();\n\t\tconst spanId = LiopTracer.generateSpanId();\n\t\tconst sampled = parent ? parent.sampled : true;\n\n\t\tconst context: SpanContext = {\n\t\t\ttraceId,\n\t\t\tspanId,\n\t\t\tsampled,\n\t\t};\n\n\t\tconst span: LiopSpan = {\n\t\t\tname,\n\t\t\tcontext,\n\t\t\tstartTime: Date.now(),\n\t\t\tattributes: { ...attributes },\n\t\t\tstatus: \"OK\",\n\t\t\tsetAttribute(key, value) {\n\t\t\t\tthis.attributes[key] = value;\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\trecordException(err) {\n\t\t\t\tthis.status = \"ERROR\";\n\t\t\t\tthis.error = typeof err === \"string\" ? err : err.message;\n\t\t\t\treturn this;\n\t\t\t},\n\t\t\tend() {\n\t\t\t\tthis.endTime = Date.now();\n\t\t\t},\n\t\t};\n\n\t\treturn span;\n\t}\n}\n\nexport const defaultTracer = new LiopTracer();\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Cross-AI Prompt Adapters (Fase 92)\n *\n * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)\n * to ensure they understand how to generate \"Logic-on-Origin\" WASM-compatible payload structures.\n */\n\nexport type AIProvider = \"claude\" | \"openai\" | \"gemini\";\n\nexport interface PromptConfig {\n\txmlStandard: boolean;\n\tjsonSchemaPreferred: boolean;\n}\n\nconst PROVIDER_CONFIGS: Record<AIProvider, PromptConfig> = {\n\tclaude: { xmlStandard: true, jsonSchemaPreferred: false },\n\topenai: { xmlStandard: false, jsonSchemaPreferred: true },\n\tgemini: { xmlStandard: false, jsonSchemaPreferred: true },\n};\n\n/**\n * Generates specific System Prompts optimized for the provided AI.\n * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).\n */\nexport function generateSystemInstructions(provider: AIProvider): string {\n\tconst config = PROVIDER_CONFIGS[provider];\n\n\tlet instructions = `[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]\nYou are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.\nUnlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.\n\n### CORE PARADIGM\nWhen you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.\nThe node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.\n\n### EXECUTION RULES\n1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.\n2. Rely only on standard ECMA script features (No Node.js polyfills).\n3. The logic must end by returning the calculated insights, not the raw data.\n\n### DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism)\nTo prevent database reconstruction and inference attacks, numeric query outputs are processed by a Laplace DP engine:\n- COUNT / LENGTH queries: To get EXACT integer values without noise, you MUST name return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.\n- AVERAGE queries: Return keys containing 'avg', 'mean', or 'average' scale down noise automatically by dividing global sensitivity by the dataset size (sensitivity / n).\n- SUM / OTHER queries: Return keys without these semantic names receive full Laplace noise based on the global node sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.\n\n### SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS\n- Date is poisoned: The 'Date' class/constructor is undefined (calling 'new Date()', 'Date.now()', or 'Date.parse()' will crash the execution).\n - Workaround: Perform chronological sorting and comparisons lexicographically on ISO 8601 string dates (e.g. record.date >= '2024-01-01').\n- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.\n- Frozen prototypes: Modifications to Object.prototype, Array.prototype, etc., are blocked.\n- K-Anonymity constraints: Small datasets (< 10 records) limit outputs to max 3 scalar keys with NO nesting. Datasets with >= 10 records limit outputs to max 10 fields.\n`;\n\n\tif (config.xmlStandard) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)\nYou must wrap your logic precisely within <liop_logic> tags.\nExample:\n<liop_logic>\nconst records = await liop.readResource(\"liop://vault/patients\");\nconst filtered = records.filter(r => r.disease === \"Hypertension\");\nreturn { alert: \"High risk demographic\", targetCount: filtered.length };\n</liop_logic>\n`;\n\t} else if (config.jsonSchemaPreferred) {\n\t\tinstructions += `\n### PAYLOAD FORMATTING (JSON PARSING PREFERRED)\nYou must provide your logic strictly within a JSON string key called \\`\"logic_blob\"\\` inside your tool call parameters.\nExample:\n{\n \"target\": \"liop://vault/patients\",\n \"logic_blob\": \"const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };\"\n}\n`;\n\t}\n\n\treturn instructions;\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Certificate Manager (CertManager)\n * Provides automated certificate monitoring, X.509 validity inspection,\n * and hot-reloading for mutual TLS (mTLS) without node restarts.\n *\n * Compliance:\n * - NIST SP 800-52 Rev. 2: Guidelines for the Selection and Use of TLS\n * - Zero-Trust Architecture (NIST SP 800-207): Continuous cryptographic verification\n */\n\nimport * as crypto from \"node:crypto\";\nimport { EventEmitter } from \"node:events\";\nimport * as fs from \"node:fs\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface CertManagerOptions {\n\t/** Path to the root CA certificate (PEM format) */\n\trootCertPath?: string;\n\t/** Path to the server/client certificate chain (PEM format) */\n\tcertChainPath: string;\n\t/** Path to the private key (PEM format) */\n\tprivateKeyPath: string;\n\t/** Expiration warning threshold in days (default: 30) */\n\twarningDays?: number;\n\t/** Enable file watching for automatic hot-reloading (default: true) */\n\twatchFiles?: boolean;\n\t/** Debounce delay in ms for hot reloading (default: 150) */\n\tdebounceMs?: number;\n}\n\nexport interface CertInfo {\n\tsubject: string;\n\tissuer: string;\n\tvalidFrom: string;\n\tvalidTo: string;\n\tfingerprint256: string;\n\tdaysRemaining: number;\n\tisExpired: boolean;\n\tisExpiringSoon: boolean;\n}\n\nexport class CertManager extends EventEmitter {\n\tprivate rootCertBuffer: Buffer | null = null;\n\tprivate certChainBuffer: Buffer | null = null;\n\tprivate privateKeyBuffer: Buffer | null = null;\n\tprivate watchers: fs.FSWatcher[] = [];\n\tprivate reloadDebounceTimer: NodeJS.Timeout | null = null;\n\tprivate readonly warningDays: number;\n\tprivate readonly debounceMs: number;\n\n\tconstructor(private readonly options: CertManagerOptions) {\n\t\tsuper();\n\t\tthis.warningDays = options.warningDays ?? 30;\n\t\tthis.debounceMs = options.debounceMs ?? 150;\n\t\tthis.loadCertificates();\n\n\t\tif (options.watchFiles !== false) {\n\t\t\tthis.setupWatchers();\n\t\t}\n\t}\n\n\t/**\n\t * Synchronously loads or reloads certificates from filesystem into memory.\n\t */\n\tpublic loadCertificates(): void {\n\t\ttry {\n\t\t\tif (\n\t\t\t\tthis.options.rootCertPath &&\n\t\t\t\tfs.existsSync(this.options.rootCertPath)\n\t\t\t) {\n\t\t\t\tthis.rootCertBuffer = fs.readFileSync(this.options.rootCertPath);\n\t\t\t}\n\n\t\t\tif (!fs.existsSync(this.options.certChainPath)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Certificate chain file not found: ${this.options.certChainPath}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!fs.existsSync(this.options.privateKeyPath)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Private key file not found: ${this.options.privateKeyPath}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.certChainBuffer = fs.readFileSync(this.options.certChainPath);\n\t\t\tthis.privateKeyBuffer = fs.readFileSync(this.options.privateKeyPath);\n\n\t\t\tlog.info(\"[CertManager] Certificates loaded successfully.\");\n\t\t} catch (error) {\n\t\t\tlog.error(`[CertManager] Failed to load certificates: ${error}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Inspects the loaded server/client certificate chain using Node.js native X509Certificate.\n\t */\n\tpublic inspectCertificate(): CertInfo {\n\t\tif (!this.certChainBuffer) {\n\t\t\tthrow new Error(\"[CertManager] No certificate loaded to inspect.\");\n\t\t}\n\n\t\tconst x509 = new crypto.X509Certificate(this.certChainBuffer);\n\t\tconst validToDate = new Date(x509.validTo);\n\t\tconst now = new Date();\n\t\tconst msRemaining = validToDate.getTime() - now.getTime();\n\t\tconst daysRemaining = Math.max(\n\t\t\t0,\n\t\t\tMath.floor(msRemaining / (1000 * 60 * 60 * 24)),\n\t\t);\n\t\tconst isExpired = msRemaining <= 0;\n\t\tconst isExpiringSoon = daysRemaining <= this.warningDays;\n\n\t\treturn {\n\t\t\tsubject: x509.subject,\n\t\t\tissuer: x509.issuer,\n\t\t\tvalidFrom: x509.validFrom,\n\t\t\tvalidTo: x509.validTo,\n\t\t\tfingerprint256: x509.fingerprint256,\n\t\t\tdaysRemaining,\n\t\t\tisExpired,\n\t\t\tisExpiringSoon,\n\t\t};\n\t}\n\n\t/**\n\t * Sets up non-blocking filesystem watchers to detect certificate renewals\n\t * and trigger hot-reloading without process restarts.\n\t */\n\tprivate setupWatchers(): void {\n\t\tconst filesToWatch = [\n\t\t\tthis.options.certChainPath,\n\t\t\tthis.options.privateKeyPath,\n\t\t\tthis.options.rootCertPath,\n\t\t].filter((p): p is string => Boolean(p && fs.existsSync(p)));\n\n\t\tfor (const filePath of filesToWatch) {\n\t\t\ttry {\n\t\t\t\tconst watcher = fs.watch(filePath, () => {\n\t\t\t\t\tthis.scheduleReload();\n\t\t\t\t});\n\t\t\t\tthis.watchers.push(watcher);\n\t\t\t} catch (err) {\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[CertManager] Could not watch ${filePath} for hot reloading: ${err}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Debounces reload events to ensure files have finished writing.\n\t */\n\tprivate scheduleReload(): void {\n\t\tif (this.reloadDebounceTimer) {\n\t\t\tclearTimeout(this.reloadDebounceTimer);\n\t\t}\n\n\t\tthis.reloadDebounceTimer = setTimeout(() => {\n\t\t\ttry {\n\t\t\t\tthis.loadCertificates();\n\t\t\t\tconst certInfo = this.inspectCertificate();\n\t\t\t\tlog.info(\n\t\t\t\t\t`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`,\n\t\t\t\t);\n\t\t\t\tthis.emit(\"reload\", certInfo);\n\t\t\t} catch (error) {\n\t\t\t\tlog.error(`[CertManager] Hot reload failed: ${error}`);\n\t\t\t\tthis.emit(\"error\", error);\n\t\t\t}\n\t\t}, this.debounceMs);\n\t}\n\n\t/**\n\t * Manually triggers a reload of certificates and emits the 'reload' event.\n\t */\n\tpublic reload(): CertInfo {\n\t\tthis.loadCertificates();\n\t\tconst certInfo = this.inspectCertificate();\n\t\tlog.info(\n\t\t\t`[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`,\n\t\t);\n\t\tthis.emit(\"reload\", certInfo);\n\t\treturn certInfo;\n\t}\n\n\tpublic getRootCert(): Buffer | null {\n\t\treturn this.rootCertBuffer;\n\t}\n\n\tpublic getCertChain(): Buffer {\n\t\tif (!this.certChainBuffer) {\n\t\t\tthrow new Error(\"[CertManager] Certificate chain not loaded.\");\n\t\t}\n\t\treturn this.certChainBuffer;\n\t}\n\n\tpublic getPrivateKey(): Buffer {\n\t\tif (!this.privateKeyBuffer) {\n\t\t\tthrow new Error(\"[CertManager] Private key not loaded.\");\n\t\t}\n\t\treturn this.privateKeyBuffer;\n\t}\n\n\t/**\n\t * Stops all active file watchers and releases resources.\n\t */\n\tpublic dispose(): void {\n\t\tif (this.reloadDebounceTimer) {\n\t\t\tclearTimeout(this.reloadDebounceTimer);\n\t\t\tthis.reloadDebounceTimer = null;\n\t\t}\n\t\tfor (const watcher of this.watchers) {\n\t\t\ttry {\n\t\t\t\twatcher.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore watcher close errors\n\t\t\t}\n\t\t}\n\t\tthis.watchers = [];\n\t\tthis.removeAllListeners();\n\t}\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export { Kyber768Wrapper } from './chunk-7PITYWOV.js';
2
+ //# sourceMappingURL=kyber-CGOA7Q6A.js.map
3
+ //# sourceMappingURL=kyber-CGOA7Q6A.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"kyber-3ULIJSE3.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"kyber-CGOA7Q6A.js"}
package/dist/mesh.d.ts CHANGED
@@ -1,148 +1,32 @@
1
+ export { L as LiopManifest, a as MeshNode, M as MeshNodeConfig } from './node-B0b2vUFS.js';
2
+
3
+ declare const SWARM_KEY_BYTE_LENGTH = 95;
4
+ /**
5
+ * Creates a freshly generated 95-byte Pre-Shared Key (PSK) for libp2p Private Networks (pnet).
6
+ * Follows the canonical format `/key/swarm/psk/1.0.0/\n/base16/\n<hex>\n`.
7
+ */
8
+ declare function createSwarmKey(): Uint8Array;
9
+ /**
10
+ * Serializes a 95-byte PSK into a Base64 string for safe environment variable passing or JSON config.
11
+ */
12
+ declare function serializeSwarmKey(psk: Uint8Array): string;
13
+ /**
14
+ * Deserializes a Base64-encoded string into a 95-byte PSK Uint8Array.
15
+ */
16
+ declare function deserializeSwarmKey(base64Str: string): Uint8Array;
17
+ /**
18
+ * Parses raw text format PSK or Base64 string into a 95-byte PSK Uint8Array.
19
+ * Allows loading either the canonical multiline text (`/key/swarm/psk/1.0.0/...`) or Base64.
20
+ */
21
+ declare function parseSwarmKey(rawText: string): Uint8Array;
1
22
  /**
2
- * Manifest describing a node's capabilities in the LIOP Mesh.
3
- * Exchanged via the /liop/manifest/1.0.0 protocol stream.
23
+ * Saves a 95-byte Swarm Key to a file on disk (written as canonical text).
4
24
  */
5
- interface LiopManifest {
6
- peerId: string;
7
- grpcPort: number;
8
- tools: Array<{
9
- name: string;
10
- description?: string;
11
- inputSchema?: Record<string, unknown>;
12
- }>;
13
- resources: Array<{
14
- name: string;
15
- uri: string;
16
- description?: string;
17
- mimeType?: string;
18
- text?: string;
19
- }>;
20
- serverInfo: {
21
- name: string;
22
- version: string;
23
- };
24
- taxonomy?: {
25
- domain: string;
26
- clearanceTier: number;
27
- executionTypes: string[];
28
- };
29
- authRequired?: boolean;
30
- /** Canonical slug for deterministic token resolution. Agents resolve LIOP_TOKEN_<tokenSlug>. Must match /^[A-Z][A-Z0-9_]*$/. */
31
- tokenSlug?: string;
32
- /** ML-DSA-65 (FIPS 204) Post-Quantum Digital Signature for Manifest Attestation (Base64) */
33
- pqcSignature?: string;
34
- /** ML-DSA-65 (FIPS 204) Post-Quantum Public Key (Base64) */
35
- pqcPublicKey?: string;
36
- }
37
- interface MeshNodeConfig {
38
- listenAddresses?: string[];
39
- bootstrapNodes?: string[];
40
- identityPath?: string;
41
- enableWAN?: boolean;
42
- dhtStoragePath?: string;
43
- /** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */
44
- addressMapper?: (addr: string) => string | null;
45
- /** Enable AutoNAT reachability detection (default: true) */
46
- enableAutoNAT?: boolean;
47
- /** Enable Circuit Relay v2 transport & server for NAT traversal (default: true) */
48
- enableRelay?: boolean;
49
- /** Enable DCUtR decentralized hole punching (default: true) */
50
- enableDcutr?: boolean;
51
- /** Enable mDNS peer discovery for local networks (default: false in WAN, true in LAN) */
52
- enableMdns?: boolean;
53
- }
25
+ declare function saveSwarmKey(psk: Uint8Array, filePath: string): Promise<void>;
54
26
  /**
55
- * P2P Mesh Node backed by libp2p + Kademlia DHT.
56
- *
57
- * Provides capability advertisement via CID-based content routing
58
- * and decentralized peer discovery.
27
+ * Loads a 95-byte Swarm Key from a file on disk.
28
+ * Supports both raw binary/canonical format and Base64-encoded text.
59
29
  */
60
- declare class MeshNode {
61
- private node;
62
- private config;
63
- private manifestDialFailureState;
64
- private static readonly MANIFEST_DIAL_BASE_COOLDOWN_MS;
65
- private static readonly MANIFEST_DIAL_MAX_COOLDOWN_MS;
66
- private static readonly MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS;
67
- /**
68
- * Buffer of capability hashes that have been announced.
69
- * Used to re-announce capabilities when new peers connect
70
- * (critical for small / isolated clusters where the initial
71
- * provide() finds zero peers in the routing table).
72
- */
73
- private announcedCapabilities;
74
- /** Guards against concurrent re-announcement storms. */
75
- private reannouncing;
76
- /** Callback that returns the local node's manifest on request. */
77
- private manifestProvider;
78
- /** Flag to ensure the manifest protocol is only registered once. */
79
- private manifestProtocolRegistered;
80
- /** Local Ed25519 Private Key for protocol signatures */
81
- private localPrivateKey;
82
- constructor(config?: MeshNodeConfig);
83
- private shouldSkipManifestDial;
84
- private recordManifestDialFailure;
85
- private clearManifestDialFailure;
86
- /**
87
- * Loads a persistent identity from disk or generates a new Ed25519 keypair.
88
- * Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).
89
- */
90
- private loadOrCreateIdentity;
91
- /**
92
- * Persists the private key to disk using protobuf serialization (libp2p v3.x).
93
- */
94
- private saveIdentity;
95
- /**
96
- * Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.
97
- * Required by @libp2p/kad-dht v16+ for provide/findProviders.
98
- */
99
- private capabilityToCID;
100
- /**
101
- * Re-announces all buffered capabilities after a new peer connects.
102
- * Uses a small delay to allow the DHT protocol handshake to complete.
103
- */
104
- private reannounceAll;
105
- start(): Promise<void>;
106
- stop(): Promise<void>;
107
- private loadRoutingTable;
108
- private saveRoutingTable;
109
- /**
110
- * Internal logic to register protocol handlers against the libp2p node.
111
- * Can be called multiple times; handles idempotent registration.
112
- */
113
- private applyHandlers;
114
- /**
115
- * Registers a callback as the manifest provider.
116
- * Will be applied immediately if the node is already initialized.
117
- */
118
- registerManifestHandler(provider: () => LiopManifest): void;
119
- /**
120
- * Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.
121
- * Returns null if the peer doesn't support the protocol or is unreachable.
122
- */
123
- queryManifest(peerIdStr: string): Promise<LiopManifest | null>;
124
- /**
125
- * Discovers all peers in the DHT that have announced "liop:manifest".
126
- * Returns their PeerIDs for subsequent manifest queries.
127
- */
128
- discoverManifestProviders(): Promise<string[]>;
129
- /**
130
- * Announces this node as a manifest provider in the DHT.
131
- * Should be called after tools/resources have been registered.
132
- */
133
- announceManifest(): Promise<void>;
134
- /**
135
- * Returns the current size of the routing table for diagnostic purposes.
136
- */
137
- getRoutingTableSize(): number;
138
- getPeerId(): string;
139
- sign(data: Uint8Array): Promise<Uint8Array>;
140
- getMultiaddrs(): string[];
141
- announceCapability(hash: string): Promise<void>;
142
- findProviders(hash: string): Promise<string[]>;
143
- resolvePeer(peerIdStr: string): Promise<string[]>;
144
- isStarted(): boolean;
145
- getPeers(): string[];
146
- }
30
+ declare function loadSwarmKey(filePath: string): Promise<Uint8Array>;
147
31
 
148
- export { type LiopManifest, MeshNode, type MeshNodeConfig };
32
+ export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey };
package/dist/mesh.js CHANGED
@@ -1,5 +1,6 @@
1
- import './chunk-RWRRBYG4.js';
2
- export { MeshNode } from './chunk-74CISO2I.js';
3
- import './chunk-72MNYFR6.js';
1
+ import './chunk-FTF6AMF6.js';
2
+ export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey } from './chunk-ZP3VVXOI.js';
3
+ export { MeshNode } from './chunk-7RXOIDXP.js';
4
+ import './chunk-HA6YZ42O.js';
4
5
  //# sourceMappingURL=mesh.js.map
5
6
  //# sourceMappingURL=mesh.js.map