@nekzus/liop 2.2.0 → 2.3.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.
Files changed (66) hide show
  1. package/LICENSE +201 -21
  2. package/NOTICE +5 -0
  3. package/README.md +61 -5
  4. package/dist/bin/agent.js +7 -5
  5. package/dist/bin/agent.js.map +1 -1
  6. package/dist/bridge.d.ts +2 -2
  7. package/dist/bridge.js +2 -1
  8. package/dist/{chunk-UVO7DII3.js → chunk-4LQPDN3W.js} +108 -15
  9. package/dist/chunk-4LQPDN3W.js.map +1 -0
  10. package/dist/{chunk-NJRSFFD7.js → chunk-74CISO2I.js} +60 -22
  11. package/dist/chunk-74CISO2I.js.map +1 -0
  12. package/dist/{chunk-E5QBDD5E.js → chunk-CRZBVFDV.js} +169 -22
  13. package/dist/chunk-CRZBVFDV.js.map +1 -0
  14. package/dist/chunk-GKV6M2PQ.js +208106 -0
  15. package/dist/chunk-GKV6M2PQ.js.map +1 -0
  16. package/dist/chunk-JIJPZFR2.js +51 -0
  17. package/dist/chunk-JIJPZFR2.js.map +1 -0
  18. package/dist/chunk-OIMJZ64E.js +441 -0
  19. package/dist/chunk-OIMJZ64E.js.map +1 -0
  20. package/dist/chunk-PYKRQAER.js +77 -0
  21. package/dist/chunk-PYKRQAER.js.map +1 -0
  22. package/dist/{chunk-J3WPBMJ5.js → chunk-SONUORBT.js} +95 -6
  23. package/dist/chunk-SONUORBT.js.map +1 -0
  24. package/dist/{chunk-2JLG4DET.js → chunk-UBOQZVV5.js} +261 -107
  25. package/dist/chunk-UBOQZVV5.js.map +1 -0
  26. package/dist/chunk-UCJEK75U.js +714 -0
  27. package/dist/chunk-UCJEK75U.js.map +1 -0
  28. package/dist/chunk-WSW6YJNY.js +168 -0
  29. package/dist/chunk-WSW6YJNY.js.map +1 -0
  30. package/dist/client.d.ts +3 -2
  31. package/dist/client.js +4 -3
  32. package/dist/gateway.d.ts +5 -110
  33. package/dist/gateway.js +5 -4
  34. package/dist/hybrid-CF__0YnC.d.ts +170 -0
  35. package/dist/{index-BlGc0iym.d.ts → index-BW95kAL4.d.ts} +63 -2
  36. package/dist/index-cMV0_yD9.d.ts +200 -0
  37. package/dist/index.d.ts +273 -18
  38. package/dist/index.js +266 -13
  39. package/dist/index.js.map +1 -1
  40. package/dist/mesh.d.ts +14 -0
  41. package/dist/mesh.js +1 -1
  42. package/dist/server.d.ts +2 -2
  43. package/dist/server.js +5 -4
  44. package/dist/{types-sKeUxuky.d.ts → types-lJIxBlWF.d.ts} +71 -1
  45. package/dist/types.d.ts +1 -1
  46. package/dist/types.js +1 -1
  47. package/dist/workers/logic-execution.d.ts +1 -0
  48. package/dist/workers/logic-execution.js +17 -1
  49. package/dist/workers/logic-execution.js.map +1 -1
  50. package/package.json +53 -33
  51. package/dist/chunk-2JLG4DET.js.map +0 -1
  52. package/dist/chunk-CT6NHSYP.js +0 -30
  53. package/dist/chunk-CT6NHSYP.js.map +0 -1
  54. package/dist/chunk-E5QBDD5E.js.map +0 -1
  55. package/dist/chunk-HB5DXX3Q.js +0 -1976
  56. package/dist/chunk-HB5DXX3Q.js.map +0 -1
  57. package/dist/chunk-IJHTRIZC.js +0 -56
  58. package/dist/chunk-IJHTRIZC.js.map +0 -1
  59. package/dist/chunk-J3WPBMJ5.js.map +0 -1
  60. package/dist/chunk-NJRSFFD7.js.map +0 -1
  61. package/dist/chunk-PHTWUTY7.js +0 -300
  62. package/dist/chunk-PHTWUTY7.js.map +0 -1
  63. package/dist/chunk-RDWCGZ2A.js +0 -87
  64. package/dist/chunk-RDWCGZ2A.js.map +0 -1
  65. package/dist/chunk-UVO7DII3.js.map +0 -1
  66. package/dist/index-qM8ZH8sC.d.ts +0 -101
package/dist/index.d.ts CHANGED
@@ -1,17 +1,19 @@
1
1
  export { LiopBridgeOptions, LiopMcpBridge, LiopStreamBridge, LiopStreamBridgeOptions } from './bridge.js';
2
- import { L as LiopTlsOptions } from './index-qM8ZH8sC.js';
3
- export { a as LiopClient } from './index-qM8ZH8sC.js';
4
- export { LiopHybridGateway } from './gateway.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';
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';
5
6
  export { LiopManifest, MeshNode, MeshNodeConfig } from './mesh.js';
6
7
  import * as grpc from '@grpc/grpc-js';
7
- export { A as AUTH_DEFAULTS, b as AggregationPolicy, c as AuthRole, d as LiopAuthConfig, L as LiopServer, a as LiopServerOptions, e as LogicExecutionPolicy, N as NerScanner, O as OAuthClientConfig, f as OutputSanitizerConfig, P as PII_PATTERNS, g as PII_PRESETS, h as PiiRule, i as PiiScanner, T as ToolHandler, s as sanitizeOutput } from './index-BlGc0iym.js';
8
- import { A as AuthInfo } from './types-sKeUxuky.js';
9
- export { C as CallToolRequest, a as CallToolResult, G as GetPromptRequest, c as GetPromptResult, J as JwtValidator, M as McpRequest, b as McpResponse, P as Prompt, d as PromptSchema, R as Resource, e as ResourceSchema, S as ServerInfo, T as Tool, f as ToolSchema } from './types-sKeUxuky.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
+ import { A as AuthInfo } from './types-lJIxBlWF.js';
10
+ 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';
10
11
  import * as jose from 'jose';
11
12
  import Provider from 'oidc-provider';
12
13
  import '@modelcontextprotocol/sdk/server/mcp.js';
13
14
  import 'zod';
14
15
  import './verifier-COnid_dg.js';
16
+ import 'node:events';
15
17
 
16
18
  /**
17
19
  * TokenEstimator — Pluggable strategy for counting tokens in text content.
@@ -26,7 +28,7 @@ interface TokenEstimator {
26
28
  readonly name: string;
27
29
  }
28
30
  /**
29
- * Exact BPE tokenizer using o200k_base encoding.
31
+ * Exact BPE tokenizer using inlined o200k_base encoding.
30
32
  *
31
33
  * o200k_base is the standard encoding for all modern OpenAI models
32
34
  * (GPT-4o, GPT-4.1, o1, o3, o4) and provides a reasonable baseline
@@ -34,7 +36,7 @@ interface TokenEstimator {
34
36
  *
35
37
  * - Synchronous: safe for hot-path usage without async overhead
36
38
  * - Merge cache reduced to 10K entries for long-running server processes
37
- * - Zero runtime dependencies beyond gpt-tokenizer itself
39
+ * - Inlined at build-time: zero external runtime dependencies in node_modules
38
40
  */
39
41
  declare class RealTokenEstimator implements TokenEstimator {
40
42
  readonly name = "o200k_base";
@@ -46,24 +48,19 @@ declare class RealTokenEstimator implements TokenEstimator {
46
48
  * Fallback heuristic estimator: ~4 characters per token.
47
49
  *
48
50
  * Industry-standard approximation (±10% for English/code content).
49
- * Used only when gpt-tokenizer fails to load in constrained environments.
51
+ * Used only when tokenizer fails in constrained environments.
50
52
  */
51
53
  declare class HeuristicTokenEstimator implements TokenEstimator {
52
54
  readonly name = "heuristic (chars/4)";
53
55
  countTokens(text: string): number;
54
56
  }
55
57
  /**
56
- * Factory: creates a RealTokenEstimator with gpt-tokenizer,
57
- * falling back to HeuristicTokenEstimator if the import fails.
58
- *
59
- * Uses dynamic import to avoid blocking SDK initialization and to
60
- * gracefully degrade in environments where gpt-tokenizer is unavailable.
58
+ * Factory: creates a RealTokenEstimator with inlined o200k_base,
59
+ * falling back to HeuristicTokenEstimator if an unexpected error occurs.
61
60
  */
62
61
  declare function createTokenEstimator(): Promise<TokenEstimator>;
63
62
  /**
64
- * Synchronous factory: creates a HeuristicTokenEstimator immediately.
65
- * Used when the async factory cannot be awaited (e.g., constructor contexts).
66
- * The engine should upgrade to the real estimator via setEstimator() later.
63
+ * Synchronous factory: creates a RealTokenEstimator immediately.
67
64
  */
68
65
  declare function createSyncTokenEstimator(): TokenEstimator;
69
66
 
@@ -199,6 +196,162 @@ declare class LiopError extends Error {
199
196
  constructor(code: ErrorCode, message: string);
200
197
  }
201
198
 
199
+ /**
200
+ * LIOP gRPC-Web Protocol Adapter (HTTP/1.1 Fallback)
201
+ *
202
+ * Implements standard gRPC-Web framing per the official gRPC-Web specification:
203
+ * https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
204
+ *
205
+ * Allows web browsers, corporate Layer 7 HTTP/1.1 proxies, and enterprise WAFs
206
+ * to invoke LIOP nodes over HTTP/1.1 without requiring HTTP/2 streaming or h2c.
207
+ *
208
+ * Frame Format:
209
+ * - 1 byte: Frame Flag (0x00 = Data Frame, 0x80 = Trailers Frame)
210
+ * - 4 bytes: 32-bit Big-Endian Unsigned Integer (payload length in bytes)
211
+ * - N bytes: Message or Trailer payload
212
+ */
213
+
214
+ declare const GRPC_WEB_CONSTANTS: {
215
+ readonly FLAG_DATA: 0;
216
+ readonly FLAG_TRAILERS: 128;
217
+ readonly HEADER_LENGTH: 5;
218
+ readonly CONTENT_TYPE_PREFIX: "application/grpc-web";
219
+ readonly STATUS_OK: 0;
220
+ readonly STATUS_CANCELLED: 1;
221
+ readonly STATUS_UNKNOWN: 2;
222
+ readonly STATUS_INVALID_ARGUMENT: 3;
223
+ readonly STATUS_DEADLINE_EXCEEDED: 4;
224
+ readonly STATUS_NOT_FOUND: 5;
225
+ readonly STATUS_PERMISSION_DENIED: 7;
226
+ readonly STATUS_UNAUTHENTICATED: 16;
227
+ readonly STATUS_INTERNAL: 13;
228
+ };
229
+ interface GrpcWebFrame {
230
+ isTrailer: boolean;
231
+ payload: Buffer;
232
+ }
233
+ /**
234
+ * Checks if an incoming HTTP request is a gRPC-Web request.
235
+ */
236
+ declare function isGrpcWebRequest(contentType?: string): boolean;
237
+ /**
238
+ * Encodes a binary payload into a standard 5-byte framed gRPC-Web Data Frame.
239
+ */
240
+ declare function encodeDataFrame(payload: Buffer | Uint8Array): Buffer;
241
+ /**
242
+ * Encodes gRPC status and optional message into a 5-byte framed gRPC-Web Trailer Frame.
243
+ */
244
+ declare function encodeTrailerFrame(status?: number, message?: string, customTrailers?: Record<string, string>): Buffer;
245
+ /**
246
+ * Parses raw gRPC-Web byte streams into an array of frames.
247
+ */
248
+ declare function decodeFrames(buffer: Buffer): GrpcWebFrame[];
249
+ /**
250
+ * Dispatches an HTTP/1.1 gRPC-Web request to an underlying protocol handler
251
+ * and serializes data and trailer frames back to the client.
252
+ */
253
+ declare function dispatchGrpcWebRequest(req: http.IncomingMessage, res: http.ServerResponse, handler: (path: string, payload: Buffer) => Promise<{
254
+ status: number;
255
+ message?: string;
256
+ data?: Buffer;
257
+ }>): Promise<void>;
258
+
259
+ /**
260
+ * LIOP Prometheus Metrics Registry (Phase Beta-3)
261
+ * Lightweight, zero-dependency, high-performance metrics collector
262
+ * complying with Prometheus and OpenMetrics exposition format.
263
+ */
264
+ type MetricLabels = Record<string, string | number>;
265
+ interface MetricDefinition {
266
+ name: string;
267
+ help: string;
268
+ type: "counter" | "gauge" | "histogram";
269
+ buckets?: number[];
270
+ }
271
+ declare class Counter {
272
+ readonly name: string;
273
+ readonly help: string;
274
+ private values;
275
+ constructor(name: string, help: string);
276
+ inc(labels?: MetricLabels, value?: number): void;
277
+ get(labels?: MetricLabels): number;
278
+ reset(): void;
279
+ toPrometheus(): string[];
280
+ }
281
+ declare class Gauge {
282
+ readonly name: string;
283
+ readonly help: string;
284
+ private values;
285
+ constructor(name: string, help: string);
286
+ set(labelsOrValue: MetricLabels | number, maybeValue?: number): void;
287
+ inc(labels?: MetricLabels, value?: number): void;
288
+ dec(labels?: MetricLabels, value?: number): void;
289
+ get(labels?: MetricLabels): number;
290
+ reset(): void;
291
+ toPrometheus(): string[];
292
+ }
293
+ declare class Histogram {
294
+ readonly name: string;
295
+ readonly help: string;
296
+ readonly buckets: number[];
297
+ private observations;
298
+ constructor(name: string, help: string, buckets?: number[]);
299
+ observe(labelsOrValue: MetricLabels | number, maybeValue?: number): void;
300
+ reset(): void;
301
+ toPrometheus(): string[];
302
+ }
303
+ declare class MetricsRegistry {
304
+ private counters;
305
+ private gauges;
306
+ private histograms;
307
+ counter(name: string, help: string): Counter;
308
+ gauge(name: string, help: string): Gauge;
309
+ histogram(name: string, help: string, buckets?: number[]): Histogram;
310
+ collectProcessMetrics(): void;
311
+ exportPrometheusText(): string;
312
+ resetAll(): void;
313
+ }
314
+ declare const protocolMetrics: MetricsRegistry;
315
+ declare const toolCallsTotal: Counter;
316
+ declare const fuelConsumed: Histogram;
317
+ declare const meshPeersConnected: Gauge;
318
+ declare const manifestCacheSize: Gauge;
319
+ declare const egressBlocksTotal: Counter;
320
+ declare const zkVerificationDurationMs: Histogram;
321
+
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
+ interface SpanContext {
328
+ traceId: string;
329
+ spanId: string;
330
+ sampled: boolean;
331
+ }
332
+ interface LiopSpan {
333
+ readonly name: string;
334
+ readonly context: SpanContext;
335
+ readonly startTime: number;
336
+ endTime?: number;
337
+ attributes: Record<string, string | number | boolean>;
338
+ status: "OK" | "ERROR";
339
+ error?: string;
340
+ setAttribute(key: string, value: string | number | boolean): LiopSpan;
341
+ recordException(error: Error | string): LiopSpan;
342
+ end(): void;
343
+ }
344
+ declare class LiopTracer {
345
+ static generateTraceId(): string;
346
+ static generateSpanId(): string;
347
+ static formatTraceparent(traceId: string, spanId: string, sampled?: boolean): string;
348
+ static parseTraceparent(header?: string | null): SpanContext | null;
349
+ static injectTraceparent(carrier: Record<string, string | string[] | undefined>, context: SpanContext): void;
350
+ static extractTraceparent(carrier: Record<string, string | string[] | undefined>): SpanContext | null;
351
+ startSpan(name: string, parent?: SpanContext | null, attributes?: Record<string, string | number | boolean>): LiopSpan;
352
+ }
353
+ declare const defaultTracer: LiopTracer;
354
+
202
355
  /**
203
356
  * LIOP Cross-AI Prompt Adapters (Fase 92)
204
357
  *
@@ -216,6 +369,15 @@ interface PromptConfig {
216
369
  */
217
370
  declare function generateSystemInstructions(provider: AIProvider): string;
218
371
 
372
+ /**
373
+ * LIOP Production-Grade gRPC Channel Options
374
+ *
375
+ * Enforces bidirectional symmetry between LiopRpcServer, LiopRpcClient,
376
+ * and gateway proxy channels per NIST SP 800-207 continuous verification.
377
+ * Prevents silent disconnections behind corporate stateful firewalls and NAT gateways.
378
+ */
379
+ declare const GRPC_CHANNEL_OPTIONS: Readonly<Record<string, string | number>>;
380
+
219
381
  /**
220
382
  * TypeScript interfaces reflecting liop_core.proto (LIOP v1)
221
383
  * Optimized for logic-on-origin and high-performance serialization.
@@ -252,6 +414,7 @@ interface LogicResponse {
252
414
  declare class LiopRpcClient {
253
415
  private client;
254
416
  private token?;
417
+ readonly address: string;
255
418
  constructor(address: string, tls?: LiopTlsOptions, token?: string);
256
419
  /**
257
420
  * Negotiates intent with the remote host.
@@ -266,6 +429,92 @@ declare class LiopRpcClient {
266
429
  close(): void;
267
430
  }
268
431
 
432
+ /**
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
443
+ */
444
+ declare const DILITHIUM65_CONSTANTS: {
445
+ readonly PUBLIC_KEY_BYTES: 1952;
446
+ readonly SECRET_KEY_BYTES: 4032;
447
+ readonly SIGNATURE_BYTES: 3309;
448
+ readonly DEFAULT_CONTEXT: Uint8Array<ArrayBuffer>;
449
+ };
450
+ declare const Dilithium65Wrapper: {
451
+ /** Constants */
452
+ PUBLIC_KEY_BYTES: 1952;
453
+ SECRET_KEY_BYTES: 4032;
454
+ SIGNATURE_BYTES: 3309;
455
+ /**
456
+ * Generates a new ML-DSA-65 (FIPS 204) key pair.
457
+ * Optionally accepts a 32-byte seed for deterministic key generation.
458
+ */
459
+ generateKeyPair(seed?: Uint8Array): {
460
+ publicKey: Uint8Array;
461
+ secretKey: Uint8Array;
462
+ };
463
+ /**
464
+ * Validates and imports a raw ML-DSA-65 public key.
465
+ */
466
+ importPublicKey(buffer: Uint8Array): Uint8Array;
467
+ /**
468
+ * Signs a message using the post-quantum secret key.
469
+ * Supports optional domain separation context (up to 255 bytes).
470
+ */
471
+ sign(message: Uint8Array | string, secretKey: Uint8Array, context?: Uint8Array): Uint8Array;
472
+ /**
473
+ * Verifies an ML-DSA-65 post-quantum digital signature.
474
+ */
475
+ verify(signature: Uint8Array, message: Uint8Array | string, publicKey: Uint8Array, context?: Uint8Array): boolean;
476
+ /**
477
+ * Signs a structured manifest (LiopManifest) using canonical JSON serialization.
478
+ * Returns base64-encoded signature and public key for transport over gRPC/MCP.
479
+ */
480
+ signManifest(manifest: Record<string, unknown>, secretKey: Uint8Array, publicKey: Uint8Array): {
481
+ signature: string;
482
+ publicKey: string;
483
+ };
484
+ /**
485
+ * Verifies the post-quantum signature of a structured manifest.
486
+ */
487
+ verifyManifest(manifest: Record<string, unknown>, signatureBase64: string, publicKeyBase64: string): boolean;
488
+ };
489
+
490
+ declare const Kyber768Wrapper: {
491
+ /**
492
+ * Extracts and validates the 1184-byte Public Key from the Rust LIOP Data Node
493
+ * @param buffer Raw buffer sent via gRPC IntentResponse
494
+ */
495
+ importPublicKey(buffer: Uint8Array): Uint8Array;
496
+ /**
497
+ * Encapsulates a shared secret using the server's public key.
498
+ * Returns the 1088-byte ciphertext to be sent back, and the 32-byte shared AES secret.
499
+ */
500
+ encapsulateAsymmetric(publicKey: Uint8Array): Promise<{
501
+ ciphertext: Uint8Array;
502
+ sharedSecret: Uint8Array;
503
+ }>;
504
+ /**
505
+ * Generates a Kyber768 KeyPair for the server to accept intents.
506
+ */
507
+ generateKeyPair(): Promise<{
508
+ publicKey: Uint8Array;
509
+ secretKey: Uint8Array;
510
+ }>;
511
+ /**
512
+ * Decapsulates the shared secret using the server's secret key.
513
+ * Zero-fills the shared secret buffer after extraction for side-channel protection.
514
+ */
515
+ decapsulateSymmetric(ciphertext: Uint8Array, secretKey: Uint8Array): Promise<Uint8Array>;
516
+ };
517
+
269
518
  declare class LiopRpcServer {
270
519
  private server;
271
520
  constructor();
@@ -274,6 +523,7 @@ declare class LiopRpcServer {
274
523
  executeLogic: (call: grpc.ServerWritableStream<LogicRequest, LogicResponse>) => void;
275
524
  }): void;
276
525
  listen(port?: number, tls?: LiopTlsOptions): Promise<number>;
526
+ gracefulShutdown(timeoutMs?: number): Promise<void>;
277
527
  stop(): Promise<void>;
278
528
  }
279
529
 
@@ -282,6 +532,11 @@ declare class LiopRpcServer {
282
532
  * preventing exposure of sensitive credentials and shell function injection.
283
533
  */
284
534
  declare function getDefaultEnvironment(): Record<string, string>;
535
+ /**
536
+ * Calculates deterministic execution fuel units based on AST instruction complexity.
537
+ * Guarantees identical fuel consumption for the same logic across different hardware.
538
+ */
539
+ declare function calculateAstInstructionFuel(code: string): number;
285
540
  interface SandboxConfig {
286
541
  allowEnv?: boolean;
287
542
  allowedDirectories?: Record<string, string>;
@@ -428,4 +683,4 @@ declare function authorizeRequest(method: string, auth: AuthInfo | null, additio
428
683
  declare const LIOP_SCOPES: readonly ["liop:tools:list", "liop:tools:call", "liop:resources:read", "liop:schema:read", "liop:mesh:query"];
429
684
  type LiopScope = (typeof LIOP_SCOPES)[number];
430
685
 
431
- export { type AIProvider, AuthInfo, ErrorCode, HeuristicTokenEstimator, LIOP_SCOPES, LiopError, LiopOTelBridge, LiopRpcClient, LiopRpcServer, type LiopScope, type PromptConfig, RealTokenEstimator, type SandboxConfig, type TokenEstimator, type TokenOperationMetric, type TokenSessionReport, TokenTelemetryEngine, type ToolTokenBreakdown, WasiSandbox, authorizeRequest, buildProtectedResourceMetadata, createOAuthServer, createSyncTokenEstimator, createTokenEstimator, generateSystemInstructions, getDefaultEnvironment };
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 };
package/dist/index.js CHANGED
@@ -1,17 +1,21 @@
1
- export { WasiSandbox, getDefaultEnvironment } from './chunk-J3WPBMJ5.js';
2
- export { LiopClient, LiopRpcClient } from './chunk-E5QBDD5E.js';
3
- export { PromptSchema, ResourceSchema, ToolSchema } from './chunk-CT6NHSYP.js';
4
- export { LiopMcpBridge, LiopStreamBridge } from './chunk-UVO7DII3.js';
5
- export { LiopHybridGateway, buildProtectedResourceMetadata } from './chunk-PHTWUTY7.js';
6
- export { AUTH_DEFAULTS, JwtValidator, LiopRpcServer, LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner, createOAuthServer, sanitizeOutput } from './chunk-2JLG4DET.js';
7
- export { HeuristicTokenEstimator, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator } from './chunk-HB5DXX3Q.js';
1
+ export { WasiSandbox, calculateAstInstructionFuel, getDefaultEnvironment } from './chunk-SONUORBT.js';
2
+ export { LiopClient, LiopRpcClient } from './chunk-CRZBVFDV.js';
3
+ export { LiopMcpBridge, LiopStreamBridge } from './chunk-4LQPDN3W.js';
4
+ export { GRPC_WEB_CONSTANTS, InMemoryRateLimiter, LiopHybridGateway, buildProtectedResourceMetadata, decodeFrames, dispatchGrpcWebRequest, encodeDataFrame, encodeTrailerFrame, isGrpcWebRequest } from './chunk-UCJEK75U.js';
5
+ export { AUTH_DEFAULTS, AuditLogger, GENESIS_HASH, JwtValidator, LiopRpcServer, LiopServer, NerScanner, PII_PATTERNS, PII_PRESETS, PiiScanner, computeEntryHash, createOAuthServer, globalAuditLogger } from './chunk-UBOQZVV5.js';
6
+ export { sanitizeOutput } from './chunk-JIJPZFR2.js';
7
+ export { HeuristicTokenEstimator, LiopMcpRouter, LiopOTelBridge, RealTokenEstimator, TokenTelemetryEngine, createSyncTokenEstimator, createTokenEstimator } from './chunk-GKV6M2PQ.js';
8
8
  import './chunk-32ADSAJS.js';
9
9
  import './chunk-OUUTDSOW.js';
10
- import './chunk-QLCOEP5J.js';
11
- export { LIOP_SCOPES, authorizeRequest } from './chunk-IJHTRIZC.js';
12
- import './chunk-RDWCGZ2A.js';
13
- export { MeshNode } from './chunk-NJRSFFD7.js';
14
- import './chunk-72MNYFR6.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-OIMJZ64E.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';
16
+ import * as crypto from 'crypto';
17
+ import { EventEmitter } from 'events';
18
+ import * as fs from 'fs';
15
19
 
16
20
  // src/errors.ts
17
21
  var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => {
@@ -33,6 +37,94 @@ var LiopError = class extends Error {
33
37
  this.code = code;
34
38
  }
35
39
  };
40
+ var TRACEPARENT_REGEX = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
41
+ var LiopTracer = class _LiopTracer {
42
+ static generateTraceId() {
43
+ let id;
44
+ do {
45
+ id = crypto.randomBytes(16).toString("hex");
46
+ } while (id === "0".repeat(32));
47
+ return id;
48
+ }
49
+ static generateSpanId() {
50
+ let id;
51
+ do {
52
+ id = crypto.randomBytes(8).toString("hex");
53
+ } while (id === "0".repeat(16));
54
+ return id;
55
+ }
56
+ static formatTraceparent(traceId, spanId, sampled = true) {
57
+ const flags = sampled ? "01" : "00";
58
+ return `00-${traceId}-${spanId}-${flags}`;
59
+ }
60
+ static parseTraceparent(header) {
61
+ if (!header || typeof header !== "string") {
62
+ return null;
63
+ }
64
+ const trimmed = header.trim();
65
+ const match = TRACEPARENT_REGEX.exec(trimmed);
66
+ if (!match) {
67
+ return null;
68
+ }
69
+ const [, version, traceId, spanId, flags] = match;
70
+ if (version === "00") {
71
+ if (traceId === "0".repeat(32) || spanId === "0".repeat(16)) {
72
+ return null;
73
+ }
74
+ }
75
+ const sampled = (Number.parseInt(flags, 16) & 1) === 1;
76
+ return {
77
+ traceId,
78
+ spanId,
79
+ sampled
80
+ };
81
+ }
82
+ static injectTraceparent(carrier, context) {
83
+ carrier.traceparent = _LiopTracer.formatTraceparent(
84
+ context.traceId,
85
+ context.spanId,
86
+ context.sampled
87
+ );
88
+ }
89
+ static extractTraceparent(carrier) {
90
+ const val = carrier.traceparent || carrier.Traceparent;
91
+ if (Array.isArray(val)) {
92
+ return _LiopTracer.parseTraceparent(val[0]);
93
+ }
94
+ return _LiopTracer.parseTraceparent(val);
95
+ }
96
+ startSpan(name, parent, attributes = {}) {
97
+ const traceId = parent?.traceId || _LiopTracer.generateTraceId();
98
+ const spanId = _LiopTracer.generateSpanId();
99
+ const sampled = parent ? parent.sampled : true;
100
+ const context = {
101
+ traceId,
102
+ spanId,
103
+ sampled
104
+ };
105
+ const span = {
106
+ name,
107
+ context,
108
+ startTime: Date.now(),
109
+ attributes: { ...attributes },
110
+ status: "OK",
111
+ setAttribute(key, value) {
112
+ this.attributes[key] = value;
113
+ return this;
114
+ },
115
+ recordException(err) {
116
+ this.status = "ERROR";
117
+ this.error = typeof err === "string" ? err : err.message;
118
+ return this;
119
+ },
120
+ end() {
121
+ this.endTime = Date.now();
122
+ }
123
+ };
124
+ return span;
125
+ }
126
+ };
127
+ var defaultTracer = new LiopTracer();
36
128
 
37
129
  // src/prompts/adapters.ts
38
130
  var PROVIDER_CONFIGS = {
@@ -92,7 +184,168 @@ Example:
92
184
  }
93
185
  return instructions;
94
186
  }
187
+ var CertManager = class extends EventEmitter {
188
+ constructor(options) {
189
+ super();
190
+ this.options = options;
191
+ this.warningDays = options.warningDays ?? 30;
192
+ this.debounceMs = options.debounceMs ?? 150;
193
+ this.loadCertificates();
194
+ if (options.watchFiles !== false) {
195
+ this.setupWatchers();
196
+ }
197
+ }
198
+ rootCertBuffer = null;
199
+ certChainBuffer = null;
200
+ privateKeyBuffer = null;
201
+ watchers = [];
202
+ reloadDebounceTimer = null;
203
+ warningDays;
204
+ debounceMs;
205
+ /**
206
+ * Synchronously loads or reloads certificates from filesystem into memory.
207
+ */
208
+ loadCertificates() {
209
+ try {
210
+ if (this.options.rootCertPath && fs.existsSync(this.options.rootCertPath)) {
211
+ this.rootCertBuffer = fs.readFileSync(this.options.rootCertPath);
212
+ }
213
+ if (!fs.existsSync(this.options.certChainPath)) {
214
+ throw new Error(
215
+ `Certificate chain file not found: ${this.options.certChainPath}`
216
+ );
217
+ }
218
+ if (!fs.existsSync(this.options.privateKeyPath)) {
219
+ throw new Error(
220
+ `Private key file not found: ${this.options.privateKeyPath}`
221
+ );
222
+ }
223
+ this.certChainBuffer = fs.readFileSync(this.options.certChainPath);
224
+ this.privateKeyBuffer = fs.readFileSync(this.options.privateKeyPath);
225
+ log.info("[CertManager] Certificates loaded successfully.");
226
+ } catch (error) {
227
+ log.error(`[CertManager] Failed to load certificates: ${error}`);
228
+ throw error;
229
+ }
230
+ }
231
+ /**
232
+ * Inspects the loaded server/client certificate chain using Node.js native X509Certificate.
233
+ */
234
+ inspectCertificate() {
235
+ if (!this.certChainBuffer) {
236
+ throw new Error("[CertManager] No certificate loaded to inspect.");
237
+ }
238
+ const x509 = new crypto.X509Certificate(this.certChainBuffer);
239
+ const validToDate = new Date(x509.validTo);
240
+ const now = /* @__PURE__ */ new Date();
241
+ const msRemaining = validToDate.getTime() - now.getTime();
242
+ const daysRemaining = Math.max(
243
+ 0,
244
+ Math.floor(msRemaining / (1e3 * 60 * 60 * 24))
245
+ );
246
+ const isExpired = msRemaining <= 0;
247
+ const isExpiringSoon = daysRemaining <= this.warningDays;
248
+ return {
249
+ subject: x509.subject,
250
+ issuer: x509.issuer,
251
+ validFrom: x509.validFrom,
252
+ validTo: x509.validTo,
253
+ fingerprint256: x509.fingerprint256,
254
+ daysRemaining,
255
+ isExpired,
256
+ isExpiringSoon
257
+ };
258
+ }
259
+ /**
260
+ * Sets up non-blocking filesystem watchers to detect certificate renewals
261
+ * and trigger hot-reloading without process restarts.
262
+ */
263
+ setupWatchers() {
264
+ const filesToWatch = [
265
+ this.options.certChainPath,
266
+ this.options.privateKeyPath,
267
+ this.options.rootCertPath
268
+ ].filter((p) => Boolean(p && fs.existsSync(p)));
269
+ for (const filePath of filesToWatch) {
270
+ try {
271
+ const watcher = fs.watch(filePath, () => {
272
+ this.scheduleReload();
273
+ });
274
+ this.watchers.push(watcher);
275
+ } catch (err) {
276
+ log.warn(
277
+ `[CertManager] Could not watch ${filePath} for hot reloading: ${err}`
278
+ );
279
+ }
280
+ }
281
+ }
282
+ /**
283
+ * Debounces reload events to ensure files have finished writing.
284
+ */
285
+ scheduleReload() {
286
+ if (this.reloadDebounceTimer) {
287
+ clearTimeout(this.reloadDebounceTimer);
288
+ }
289
+ this.reloadDebounceTimer = setTimeout(() => {
290
+ try {
291
+ this.loadCertificates();
292
+ const certInfo = this.inspectCertificate();
293
+ log.info(
294
+ `[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`
295
+ );
296
+ this.emit("reload", certInfo);
297
+ } catch (error) {
298
+ log.error(`[CertManager] Hot reload failed: ${error}`);
299
+ this.emit("error", error);
300
+ }
301
+ }, this.debounceMs);
302
+ }
303
+ /**
304
+ * Manually triggers a reload of certificates and emits the 'reload' event.
305
+ */
306
+ reload() {
307
+ this.loadCertificates();
308
+ const certInfo = this.inspectCertificate();
309
+ log.info(
310
+ `[CertManager] Hot reload complete. Certificate expires in ${certInfo.daysRemaining} days.`
311
+ );
312
+ this.emit("reload", certInfo);
313
+ return certInfo;
314
+ }
315
+ getRootCert() {
316
+ return this.rootCertBuffer;
317
+ }
318
+ getCertChain() {
319
+ if (!this.certChainBuffer) {
320
+ throw new Error("[CertManager] Certificate chain not loaded.");
321
+ }
322
+ return this.certChainBuffer;
323
+ }
324
+ getPrivateKey() {
325
+ if (!this.privateKeyBuffer) {
326
+ throw new Error("[CertManager] Private key not loaded.");
327
+ }
328
+ return this.privateKeyBuffer;
329
+ }
330
+ /**
331
+ * Stops all active file watchers and releases resources.
332
+ */
333
+ dispose() {
334
+ if (this.reloadDebounceTimer) {
335
+ clearTimeout(this.reloadDebounceTimer);
336
+ this.reloadDebounceTimer = null;
337
+ }
338
+ for (const watcher of this.watchers) {
339
+ try {
340
+ watcher.close();
341
+ } catch {
342
+ }
343
+ }
344
+ this.watchers = [];
345
+ this.removeAllListeners();
346
+ }
347
+ };
95
348
 
96
- export { ErrorCode, LiopError, generateSystemInstructions };
349
+ export { CertManager, ErrorCode, LiopError, LiopTracer, defaultTracer, generateSystemInstructions };
97
350
  //# sourceMappingURL=index.js.map
98
351
  //# sourceMappingURL=index.js.map