@nekzus/liop 1.0.0-alpha.1

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 (87) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +24 -0
  3. package/README.md +641 -0
  4. package/dist/bin/agent.d.ts +1 -0
  5. package/dist/bin/agent.js +897 -0
  6. package/dist/bin/agent.js.map +1 -0
  7. package/dist/bridge.d.ts +105 -0
  8. package/dist/bridge.js +5 -0
  9. package/dist/bridge.js.map +1 -0
  10. package/dist/chunk-3L2O2XKG.js +723 -0
  11. package/dist/chunk-3L2O2XKG.js.map +1 -0
  12. package/dist/chunk-7BSCUYUE.js +421 -0
  13. package/dist/chunk-7BSCUYUE.js.map +1 -0
  14. package/dist/chunk-7PITYWOV.js +68 -0
  15. package/dist/chunk-7PITYWOV.js.map +1 -0
  16. package/dist/chunk-7RXOIDXP.js +877 -0
  17. package/dist/chunk-7RXOIDXP.js.map +1 -0
  18. package/dist/chunk-BOISQ45Z.js +558 -0
  19. package/dist/chunk-BOISQ45Z.js.map +1 -0
  20. package/dist/chunk-DZ2FQGJD.js +206712 -0
  21. package/dist/chunk-DZ2FQGJD.js.map +1 -0
  22. package/dist/chunk-EG46XMJT.js +77 -0
  23. package/dist/chunk-EG46XMJT.js.map +1 -0
  24. package/dist/chunk-ESRXG36Y.js +115 -0
  25. package/dist/chunk-ESRXG36Y.js.map +1 -0
  26. package/dist/chunk-FTF6AMF6.js +3 -0
  27. package/dist/chunk-FTF6AMF6.js.map +1 -0
  28. package/dist/chunk-HA6YZ42O.js +64 -0
  29. package/dist/chunk-HA6YZ42O.js.map +1 -0
  30. package/dist/chunk-HD2N3IJX.js +3634 -0
  31. package/dist/chunk-HD2N3IJX.js.map +1 -0
  32. package/dist/chunk-IK7CGWAZ.js +24 -0
  33. package/dist/chunk-IK7CGWAZ.js.map +1 -0
  34. package/dist/chunk-L6J72C5X.js +1477 -0
  35. package/dist/chunk-L6J72C5X.js.map +1 -0
  36. package/dist/chunk-PAICJCKJ.js +332 -0
  37. package/dist/chunk-PAICJCKJ.js.map +1 -0
  38. package/dist/chunk-PEN3KFLF.js +114 -0
  39. package/dist/chunk-PEN3KFLF.js.map +1 -0
  40. package/dist/chunk-T7R5HUFD.js +775 -0
  41. package/dist/chunk-T7R5HUFD.js.map +1 -0
  42. package/dist/chunk-TKRX6CFI.js +168 -0
  43. package/dist/chunk-TKRX6CFI.js.map +1 -0
  44. package/dist/chunk-UCVP3XAL.js +279 -0
  45. package/dist/chunk-UCVP3XAL.js.map +1 -0
  46. package/dist/chunk-VH4K4U45.js +180 -0
  47. package/dist/chunk-VH4K4U45.js.map +1 -0
  48. package/dist/chunk-Y62GORQF.js +51 -0
  49. package/dist/chunk-Y62GORQF.js.map +1 -0
  50. package/dist/chunk-ZP3VVXOI.js +66 -0
  51. package/dist/chunk-ZP3VVXOI.js.map +1 -0
  52. package/dist/client.d.ts +7 -0
  53. package/dist/client.js +13 -0
  54. package/dist/client.js.map +1 -0
  55. package/dist/gateway.d.ts +7 -0
  56. package/dist/gateway.js +13 -0
  57. package/dist/gateway.js.map +1 -0
  58. package/dist/hybrid-CrKB50nh.d.ts +170 -0
  59. package/dist/index-CX43dvMs.d.ts +170 -0
  60. package/dist/index-DoW2gzBZ.d.ts +566 -0
  61. package/dist/index.d.ts +810 -0
  62. package/dist/index.js +357 -0
  63. package/dist/index.js.map +1 -0
  64. package/dist/kyber-CGOA7Q6A.js +3 -0
  65. package/dist/kyber-CGOA7Q6A.js.map +1 -0
  66. package/dist/mesh.d.ts +32 -0
  67. package/dist/mesh.js +6 -0
  68. package/dist/mesh.js.map +1 -0
  69. package/dist/node-B0b2vUFS.d.ts +164 -0
  70. package/dist/protocol/liop_core.proto +47 -0
  71. package/dist/server.d.ts +5 -0
  72. package/dist/server.js +9 -0
  73. package/dist/server.js.map +1 -0
  74. package/dist/types-lJIxBlWF.d.ts +256 -0
  75. package/dist/types.d.ts +3 -0
  76. package/dist/types.js +3 -0
  77. package/dist/types.js.map +1 -0
  78. package/dist/verifier-COnid_dg.d.ts +31 -0
  79. package/dist/verifier-HRFXBKT5.js +6 -0
  80. package/dist/verifier-HRFXBKT5.js.map +1 -0
  81. package/dist/workers/logic-execution.d.ts +26 -0
  82. package/dist/workers/logic-execution.js +272 -0
  83. package/dist/workers/logic-execution.js.map +1 -0
  84. package/dist/workers/zk-verifier.d.ts +26 -0
  85. package/dist/workers/zk-verifier.js +174 -0
  86. package/dist/workers/zk-verifier.js.map +1 -0
  87. package/package.json +230 -0
@@ -0,0 +1,810 @@
1
+ export { LiopBridgeOptions, LiopMcpBridge, LiopStreamBridge, LiopStreamBridgeOptions } from './bridge.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
+ 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-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';
8
+ import * as grpc from '@grpc/grpc-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';
10
+ import { A as AuthInfo } from './types-lJIxBlWF.js';
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';
12
+ import * as jose from 'jose';
13
+ import Provider from 'oidc-provider';
14
+ import '@modelcontextprotocol/sdk/server/mcp.js';
15
+ import 'zod';
16
+ import './verifier-COnid_dg.js';
17
+ import 'node:events';
18
+
19
+ /**
20
+ * TokenEstimator — Pluggable strategy for counting tokens in text content.
21
+ *
22
+ * Implementations range from exact BPE tokenization to lightweight heuristics,
23
+ * allowing the SDK to choose the best trade-off for the runtime environment.
24
+ */
25
+ interface TokenEstimator {
26
+ /** Count the number of tokens in the given text */
27
+ countTokens(text: string): number;
28
+ /** Human-readable name of the estimation strategy */
29
+ readonly name: string;
30
+ }
31
+ /**
32
+ * Exact BPE tokenizer using inlined o200k_base encoding.
33
+ *
34
+ * o200k_base is the standard encoding for all modern OpenAI models
35
+ * (GPT-4o, GPT-4.1, o1, o3, o4) and provides a reasonable baseline
36
+ * for Anthropic/Google models as well (~±5% variance).
37
+ *
38
+ * - Synchronous: safe for hot-path usage without async overhead
39
+ * - Merge cache reduced to 10K entries for long-running server processes
40
+ * - Inlined at build-time: zero external runtime dependencies in node_modules
41
+ */
42
+ declare class RealTokenEstimator implements TokenEstimator {
43
+ readonly name = "o200k_base";
44
+ private countFn;
45
+ constructor(countFn: (text: string) => number, setMergeCacheSizeFn?: (size: number) => void);
46
+ countTokens(text: string): number;
47
+ }
48
+ /**
49
+ * Fallback heuristic estimator: ~4 characters per token.
50
+ *
51
+ * Industry-standard approximation (±10% for English/code content).
52
+ * Used only when tokenizer fails in constrained environments.
53
+ */
54
+ declare class HeuristicTokenEstimator implements TokenEstimator {
55
+ readonly name = "heuristic (chars/4)";
56
+ countTokens(text: string): number;
57
+ }
58
+ /**
59
+ * Factory: creates a RealTokenEstimator with inlined o200k_base,
60
+ * falling back to HeuristicTokenEstimator if an unexpected error occurs.
61
+ */
62
+ declare function createTokenEstimator(): Promise<TokenEstimator>;
63
+ /**
64
+ * Synchronous factory: creates a RealTokenEstimator immediately.
65
+ */
66
+ declare function createSyncTokenEstimator(): TokenEstimator;
67
+
68
+ /**
69
+ * LiopOTelBridge — OpenTelemetry gen_ai.* metric emitter.
70
+ *
71
+ * Pattern: Library Instrumentation (uses global MeterProvider only).
72
+ * Per official OTel JS documentation:
73
+ * - Libraries MUST NOT create their own MeterProvider
74
+ * - Libraries SHOULD use metrics.getMeter() from the global API
75
+ * - If no MeterProvider is registered by the application, all operations are NoOp
76
+ * with zero runtime overhead (confirmed by OTel JS source: NoopMeterProvider)
77
+ *
78
+ * Follows OpenTelemetry Generative AI Semantic Conventions (Development status).
79
+ * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/
80
+ */
81
+ declare class LiopOTelBridge {
82
+ private tokenUsage;
83
+ private operationDuration;
84
+ private active;
85
+ constructor();
86
+ /**
87
+ * Record token usage with gen_ai.* standard attributes.
88
+ *
89
+ * @param tokens - Number of tokens consumed
90
+ * @param tokenType - "input" or "output" (gen_ai.token.type)
91
+ * @param operationName - gen_ai.operation.name (e.g., "execute_tool", "chat")
92
+ * @param toolName - Optional LIOP-specific tool name for attribution
93
+ */
94
+ recordTokens(tokens: number, tokenType: "input" | "output", operationName: string, toolName?: string): void;
95
+ /**
96
+ * Record operation duration with gen_ai.* standard attributes.
97
+ *
98
+ * @param durationMs - Duration in milliseconds (converted to seconds for OTel)
99
+ * @param operationName - gen_ai.operation.name
100
+ * @param error - Optional error type string if the operation failed
101
+ */
102
+ recordDuration(durationMs: number, operationName: string, error?: string): void;
103
+ /** Whether the OTel bridge is actively connected to a MeterProvider */
104
+ isActive(): boolean;
105
+ }
106
+
107
+ /** Single MCP operation token footprint */
108
+ interface TokenOperationMetric {
109
+ readonly type: "tools_list" | "tool_call" | "resource_read" | "resource_list" | "prompt_get" | "prompt_list" | "diagnostic";
110
+ readonly method: string;
111
+ readonly estimatedInputTokens: number;
112
+ readonly estimatedOutputTokens: number;
113
+ readonly timestamp: number;
114
+ readonly toolName?: string;
115
+ readonly peerId?: string;
116
+ readonly durationMs?: number;
117
+ readonly originDatasetTokens?: number;
118
+ }
119
+ /** Session-level aggregate report */
120
+ interface TokenSessionReport {
121
+ readonly sessionId: string;
122
+ readonly operations: ReadonlyArray<TokenOperationMetric>;
123
+ readonly totalInputTokens: number;
124
+ readonly totalOutputTokens: number;
125
+ readonly estimatorName: string;
126
+ readonly sessionUptimeMs: number;
127
+ }
128
+ /** Per-tool aggregate breakdown */
129
+ interface ToolTokenBreakdown {
130
+ readonly input: number;
131
+ readonly output: number;
132
+ readonly calls: number;
133
+ readonly avgDurationMs: number;
134
+ }
135
+ /**
136
+ * TokenTelemetryEngine — Full-spectrum observational singleton for token cost measurement.
137
+ *
138
+ * Design principles:
139
+ * - Pure observer pattern: NEVER mutates MCP payloads or protocol flow.
140
+ * - Real tokenization: o200k_base BPE via gpt-tokenizer (async init, sync counting).
141
+ * - OTel gen_ai.* emission: standard metrics via @opentelemetry/api (NoOp if no provider).
142
+ * - Error isolation: telemetry failures never propagate to protocol operations.
143
+ */
144
+ declare class TokenTelemetryEngine {
145
+ private static instance;
146
+ private operations;
147
+ private readonly sessionId;
148
+ private readonly startedAt;
149
+ private estimator;
150
+ private otelBridge;
151
+ private constructor();
152
+ /** Async upgrade from heuristic to real BPE tokenizer */
153
+ private initRealEstimator;
154
+ static getInstance(): TokenTelemetryEngine;
155
+ /**
156
+ * Count tokens in a string using the active estimator.
157
+ * Delegates to o200k_base BPE tokenizer (or heuristic fallback).
158
+ */
159
+ countTokens(content: string): number;
160
+ /**
161
+ * Record a single MCP operation's token footprint.
162
+ * Emits both internal metrics and OTel gen_ai.* histograms.
163
+ */
164
+ record(metric: Omit<TokenOperationMetric, "timestamp">): void;
165
+ /**
166
+ * @deprecated Use countTokens() instead. Kept for backward compatibility.
167
+ */
168
+ estimateTokens(content: string): number;
169
+ /** Generate the full session report */
170
+ getReport(): TokenSessionReport;
171
+ /** Get per-tool token breakdown for diagnostic display */
172
+ getPerToolReport(): Map<string, ToolTokenBreakdown>;
173
+ /**
174
+ * Format a rich, human-readable summary block for LiopMeshStatus diagnostic.
175
+ * Returns empty string when no operations have been recorded.
176
+ */
177
+ formatStatusBlock(): string;
178
+ /** Format milliseconds into human-readable uptime string */
179
+ private formatUptime;
180
+ /** Reset all recorded metrics (used in tests) */
181
+ reset(): void;
182
+ /** Destroy the singleton (used in tests to guarantee isolation) */
183
+ static destroy(): void;
184
+ }
185
+
186
+ declare enum ErrorCode {
187
+ CapabilityViolation = "CapabilityViolation",
188
+ SandboxEscape = "SandboxEscape",
189
+ PiiLeak = "PiiLeak",
190
+ InvalidIntent = "InvalidIntent",
191
+ Throttled = "Throttled",
192
+ ZkVerificationFailed = "ZkVerificationFailed",
193
+ MeshUnavailable = "MeshUnavailable",
194
+ ConnectionFailed = "ConnectionFailed"
195
+ }
196
+ declare class LiopError extends Error {
197
+ readonly code: ErrorCode;
198
+ constructor(code: ErrorCode, message: string);
199
+ }
200
+
201
+ /**
202
+ * LIOP gRPC-Web Protocol Adapter (HTTP/1.1 Fallback)
203
+ *
204
+ * Implements standard gRPC-Web framing per the official gRPC-Web specification:
205
+ * https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md
206
+ *
207
+ * Allows web browsers, corporate Layer 7 HTTP/1.1 proxies, and enterprise WAFs
208
+ * to invoke LIOP nodes over HTTP/1.1 without requiring HTTP/2 streaming or h2c.
209
+ *
210
+ * Frame Format:
211
+ * - 1 byte: Frame Flag (0x00 = Data Frame, 0x80 = Trailers Frame)
212
+ * - 4 bytes: 32-bit Big-Endian Unsigned Integer (payload length in bytes)
213
+ * - N bytes: Message or Trailer payload
214
+ */
215
+
216
+ declare const GRPC_WEB_CONSTANTS: {
217
+ readonly FLAG_DATA: 0;
218
+ readonly FLAG_TRAILERS: 128;
219
+ readonly HEADER_LENGTH: 5;
220
+ readonly CONTENT_TYPE_PREFIX: "application/grpc-web";
221
+ readonly STATUS_OK: 0;
222
+ readonly STATUS_CANCELLED: 1;
223
+ readonly STATUS_UNKNOWN: 2;
224
+ readonly STATUS_INVALID_ARGUMENT: 3;
225
+ readonly STATUS_DEADLINE_EXCEEDED: 4;
226
+ readonly STATUS_NOT_FOUND: 5;
227
+ readonly STATUS_PERMISSION_DENIED: 7;
228
+ readonly STATUS_UNAUTHENTICATED: 16;
229
+ readonly STATUS_INTERNAL: 13;
230
+ };
231
+ interface GrpcWebFrame {
232
+ isTrailer: boolean;
233
+ payload: Buffer;
234
+ }
235
+ /**
236
+ * Checks if an incoming HTTP request is a gRPC-Web request.
237
+ */
238
+ declare function isGrpcWebRequest(contentType?: string): boolean;
239
+ /**
240
+ * Encodes a binary payload into a standard 5-byte framed gRPC-Web Data Frame.
241
+ */
242
+ declare function encodeDataFrame(payload: Buffer | Uint8Array): Buffer;
243
+ /**
244
+ * Encodes gRPC status and optional message into a 5-byte framed gRPC-Web Trailer Frame.
245
+ */
246
+ declare function encodeTrailerFrame(status?: number, message?: string, customTrailers?: Record<string, string>): Buffer;
247
+ /**
248
+ * Parses raw gRPC-Web byte streams into an array of frames.
249
+ */
250
+ declare function decodeFrames(buffer: Buffer): GrpcWebFrame[];
251
+ /**
252
+ * Dispatches an HTTP/1.1 gRPC-Web request to an underlying protocol handler
253
+ * and serializes data and trailer frames back to the client.
254
+ */
255
+ declare function dispatchGrpcWebRequest(req: http.IncomingMessage, res: http.ServerResponse, handler: (path: string, payload: Buffer) => Promise<{
256
+ status: number;
257
+ message?: string;
258
+ data?: Buffer;
259
+ }>): Promise<void>;
260
+
261
+ /**
262
+ * LIOP Prometheus Metrics Registry (Phase Beta-3)
263
+ * Lightweight, zero-dependency, high-performance metrics collector
264
+ * complying with Prometheus and OpenMetrics exposition format.
265
+ */
266
+ type MetricLabels = Record<string, string | number>;
267
+ interface MetricDefinition {
268
+ name: string;
269
+ help: string;
270
+ type: "counter" | "gauge" | "histogram";
271
+ buckets?: number[];
272
+ }
273
+ declare class Counter {
274
+ readonly name: string;
275
+ readonly help: string;
276
+ private values;
277
+ constructor(name: string, help: string);
278
+ inc(labels?: MetricLabels, value?: number): void;
279
+ get(labels?: MetricLabels): number;
280
+ reset(): void;
281
+ toPrometheus(): string[];
282
+ }
283
+ declare class Gauge {
284
+ readonly name: string;
285
+ readonly help: string;
286
+ private values;
287
+ constructor(name: string, help: string);
288
+ set(labelsOrValue: MetricLabels | number, maybeValue?: number): void;
289
+ inc(labels?: MetricLabels, value?: number): void;
290
+ dec(labels?: MetricLabels, value?: number): void;
291
+ get(labels?: MetricLabels): number;
292
+ reset(): void;
293
+ toPrometheus(): string[];
294
+ }
295
+ declare class Histogram {
296
+ readonly name: string;
297
+ readonly help: string;
298
+ readonly buckets: number[];
299
+ private observations;
300
+ constructor(name: string, help: string, buckets?: number[]);
301
+ observe(labelsOrValue: MetricLabels | number, maybeValue?: number): void;
302
+ reset(): void;
303
+ toPrometheus(): string[];
304
+ }
305
+ declare class MetricsRegistry {
306
+ private counters;
307
+ private gauges;
308
+ private histograms;
309
+ counter(name: string, help: string): Counter;
310
+ gauge(name: string, help: string): Gauge;
311
+ histogram(name: string, help: string, buckets?: number[]): Histogram;
312
+ collectProcessMetrics(): void;
313
+ exportPrometheusText(): string;
314
+ resetAll(): void;
315
+ }
316
+ declare const protocolMetrics: MetricsRegistry;
317
+ declare const toolCallsTotal: Counter;
318
+ declare const toolCallErrorsTotal: Counter;
319
+ declare const fuelConsumed: Histogram;
320
+ declare const meshPeersConnected: Gauge;
321
+ declare const manifestCacheSize: Gauge;
322
+ declare const egressBlocksTotal: Counter;
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;
333
+
334
+ interface SpanContext {
335
+ traceId: string;
336
+ spanId: string;
337
+ sampled: boolean;
338
+ }
339
+ interface LiopSpan {
340
+ readonly name: string;
341
+ readonly context: SpanContext;
342
+ readonly startTime: number;
343
+ endTime?: number;
344
+ attributes: Record<string, string | number | boolean>;
345
+ status: "OK" | "ERROR";
346
+ error?: string;
347
+ setAttribute(key: string, value: string | number | boolean): LiopSpan;
348
+ recordException(error: Error | string): LiopSpan;
349
+ end(): void;
350
+ }
351
+ declare class LiopTracer {
352
+ static generateTraceId(): string;
353
+ static generateSpanId(): string;
354
+ static formatTraceparent(traceId: string, spanId: string, sampled?: boolean): string;
355
+ static parseTraceparent(header?: string | null): SpanContext | null;
356
+ static injectTraceparent(carrier: Record<string, string | string[] | undefined>, context: SpanContext): void;
357
+ static extractTraceparent(carrier: Record<string, string | string[] | undefined>): SpanContext | null;
358
+ startSpan(name: string, parent?: SpanContext | null, attributes?: Record<string, string | number | boolean>): LiopSpan;
359
+ }
360
+ declare const defaultTracer: LiopTracer;
361
+
362
+ /**
363
+ * LIOP Cross-AI Prompt Adapters (Fase 92)
364
+ *
365
+ * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)
366
+ * to ensure they understand how to generate "Logic-on-Origin" WASM-compatible payload structures.
367
+ */
368
+ type AIProvider = "claude" | "openai" | "gemini";
369
+ interface PromptConfig {
370
+ xmlStandard: boolean;
371
+ jsonSchemaPreferred: boolean;
372
+ }
373
+ /**
374
+ * Generates specific System Prompts optimized for the provided AI.
375
+ * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).
376
+ */
377
+ declare function generateSystemInstructions(provider: AIProvider): string;
378
+
379
+ /**
380
+ * LIOP Production-Grade gRPC Channel Options
381
+ *
382
+ * Enforces bidirectional symmetry between LiopRpcServer, LiopRpcClient,
383
+ * and gateway proxy channels per NIST SP 800-207 continuous verification.
384
+ * Prevents silent disconnections behind corporate stateful firewalls and NAT gateways.
385
+ */
386
+ declare const GRPC_CHANNEL_OPTIONS: Readonly<Record<string, string | number>>;
387
+
388
+ /**
389
+ * TypeScript interfaces reflecting liop_core.proto (LIOP v1)
390
+ * Optimized for logic-on-origin and high-performance serialization.
391
+ */
392
+ interface IntentRequest {
393
+ agent_did: string;
394
+ capability_hash: string;
395
+ proof_of_intent: Uint8Array;
396
+ }
397
+ interface IntentResponse {
398
+ accepted: boolean;
399
+ session_token: string;
400
+ error_message: string;
401
+ kyber_public_key: Uint8Array;
402
+ }
403
+ interface LogicRequest {
404
+ session_token: string;
405
+ wasm_binary: Uint8Array;
406
+ inputs: Record<string, Uint8Array>;
407
+ pqc_ciphertext: Uint8Array;
408
+ aes_nonce: Uint8Array;
409
+ }
410
+ interface LogicResponse {
411
+ semantic_evidence: string;
412
+ cryptographic_proof: Uint8Array;
413
+ zk_receipt: Uint8Array;
414
+ is_error: boolean;
415
+ }
416
+
417
+ type TokenProvider = string | (() => Promise<string | undefined> | string | undefined);
418
+ /**
419
+ * LIOP gRPC Client Implementation
420
+ * Provides a high-level interface for secure intent negotiation and logic execution.
421
+ */
422
+ declare class LiopRpcClient {
423
+ private client;
424
+ private token?;
425
+ private lastResolvedToken?;
426
+ readonly address: string;
427
+ constructor(address: string, tls?: LiopTlsOptions, token?: TokenProvider);
428
+ setToken(token?: TokenProvider): void;
429
+ private resolveToken;
430
+ /**
431
+ * Negotiates intent with the remote host.
432
+ * Returns the ephemeral Kyber public key for payload encryption.
433
+ */
434
+ negotiateIntent(request: IntentRequest): Promise<IntentResponse>;
435
+ /**
436
+ * Pushes the encrypted Logic-on-Origin payload to the origin.
437
+ * Returns a stream of semantic responses and ZK proofs.
438
+ */
439
+ executeLogic(request: LogicRequest): grpc.ClientReadableStream<LogicResponse>;
440
+ close(): void;
441
+ }
442
+
443
+ /**
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.
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
+
466
+ declare const DILITHIUM65_CONSTANTS: {
467
+ readonly PUBLIC_KEY_BYTES: 1952;
468
+ readonly SECRET_KEY_BYTES: 4032;
469
+ readonly SIGNATURE_BYTES: 3309;
470
+ readonly DEFAULT_CONTEXT: Uint8Array<ArrayBuffer>;
471
+ };
472
+ declare const Dilithium65Wrapper: {
473
+ /** Constants */
474
+ PUBLIC_KEY_BYTES: 1952;
475
+ SECRET_KEY_BYTES: 4032;
476
+ SIGNATURE_BYTES: 3309;
477
+ /**
478
+ * Generates a new ML-DSA-65 (FIPS 204) key pair.
479
+ * Optionally accepts a 32-byte seed for deterministic key generation.
480
+ */
481
+ generateKeyPair(seed?: Uint8Array): {
482
+ publicKey: Uint8Array;
483
+ secretKey: Uint8Array;
484
+ };
485
+ /**
486
+ * Validates and imports a raw ML-DSA-65 public key.
487
+ */
488
+ importPublicKey(buffer: Uint8Array): Uint8Array;
489
+ /**
490
+ * Signs a message using the post-quantum secret key.
491
+ * Supports optional domain separation context (up to 255 bytes).
492
+ */
493
+ sign(message: Uint8Array | string, secretKey: Uint8Array, context?: Uint8Array): Uint8Array;
494
+ /**
495
+ * Verifies an ML-DSA-65 post-quantum digital signature.
496
+ */
497
+ verify(signature: Uint8Array, message: Uint8Array | string, publicKey: Uint8Array, context?: Uint8Array): boolean;
498
+ /**
499
+ * Signs a structured manifest (LiopManifest) using canonical JSON serialization.
500
+ * Returns base64-encoded signature and public key for transport over gRPC/MCP.
501
+ */
502
+ signManifest(manifest: Record<string, unknown>, secretKey: Uint8Array, publicKey: Uint8Array): {
503
+ signature: string;
504
+ publicKey: string;
505
+ };
506
+ /**
507
+ * Verifies the post-quantum signature of a structured manifest.
508
+ */
509
+ verifyManifest(manifest: Record<string, unknown>, signatureBase64: string, publicKeyBase64: string): boolean;
510
+ };
511
+
512
+ declare const Kyber768Wrapper: {
513
+ /**
514
+ * Extracts and validates the 1184-byte Public Key from the Rust LIOP Data Node
515
+ * @param buffer Raw buffer sent via gRPC IntentResponse
516
+ */
517
+ importPublicKey(buffer: Uint8Array): Uint8Array;
518
+ /**
519
+ * Encapsulates a shared secret using the server's public key.
520
+ * Returns the 1088-byte ciphertext to be sent back, and the 32-byte shared AES secret.
521
+ */
522
+ encapsulateAsymmetric(publicKey: Uint8Array): Promise<{
523
+ ciphertext: Uint8Array;
524
+ sharedSecret: Uint8Array;
525
+ }>;
526
+ /**
527
+ * Generates a Kyber768 KeyPair for the server to accept intents.
528
+ */
529
+ generateKeyPair(): Promise<{
530
+ publicKey: Uint8Array;
531
+ secretKey: Uint8Array;
532
+ }>;
533
+ /**
534
+ * Decapsulates the shared secret using the server's secret key.
535
+ * Zero-fills the shared secret buffer after extraction for side-channel protection.
536
+ */
537
+ decapsulateSymmetric(ciphertext: Uint8Array, secretKey: Uint8Array): Promise<Uint8Array>;
538
+ };
539
+
540
+ declare class LiopRpcServer {
541
+ private server;
542
+ constructor();
543
+ addService(handlers: {
544
+ negotiateIntent: (call: grpc.ServerUnaryCall<IntentRequest, IntentResponse>, callback: grpc.sendUnaryData<IntentResponse>) => void;
545
+ executeLogic: (call: grpc.ServerWritableStream<LogicRequest, LogicResponse>) => void;
546
+ }): void;
547
+ listen(port?: number, tls?: LiopTlsOptions): Promise<number>;
548
+ gracefulShutdown(timeoutMs?: number): Promise<void>;
549
+ stop(): Promise<void>;
550
+ }
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
+
678
+ /**
679
+ * Returns a filtered environment object containing only safe system variables,
680
+ * preventing exposure of sensitive credentials and shell function injection.
681
+ */
682
+ declare function getDefaultEnvironment(): Record<string, string>;
683
+ /**
684
+ * Calculates deterministic execution fuel units based on AST instruction complexity.
685
+ * Guarantees identical fuel consumption for the same logic across different hardware.
686
+ */
687
+ declare function calculateAstInstructionFuel(code: string): number;
688
+ interface SandboxConfig {
689
+ allowEnv?: boolean;
690
+ allowedDirectories?: Record<string, string>;
691
+ memoryLimitMb?: number;
692
+ }
693
+ /**
694
+ * LIOP WasiSandbox (Industrial Grade)
695
+ *
696
+ * Provides a production-grade isolated environment for executing untrusted logic.
697
+ * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened
698
+ * V8 Isolate fallback for dynamic JS-to-WASM logic injection.
699
+ */
700
+ declare class WasiSandbox {
701
+ private wasi;
702
+ private sandboxId;
703
+ private workingDir;
704
+ private config;
705
+ private stdoutHandle;
706
+ private stderrHandle;
707
+ constructor(config?: SandboxConfig);
708
+ /**
709
+ * Initializes the physical sandbox environment with strict directory lockdown.
710
+ */
711
+ init(): Promise<void>;
712
+ /**
713
+ * Executes logic (WASM or JS-Wrapped) with hard resource limits.
714
+ */
715
+ execute(compiledLogic: Buffer | string, records?: Record<string, unknown>[], inputs?: Record<string, unknown>): Promise<{
716
+ output: unknown;
717
+ fuelConsumed: number;
718
+ }>;
719
+ /**
720
+ * Physically cleans up the sandbox and releases resources.
721
+ */
722
+ teardown(): Promise<void>;
723
+ }
724
+
725
+ interface OAuthServerClientConfig {
726
+ client_id: string;
727
+ client_secret: string;
728
+ grant_types: string[];
729
+ scope: string;
730
+ }
731
+ interface OAuthServerConfig {
732
+ issuer: string;
733
+ clients: OAuthServerClientConfig[];
734
+ }
735
+ interface OAuthServerResult {
736
+ provider: Provider;
737
+ jwks: jose.JSONWebKeySet;
738
+ }
739
+ /**
740
+ * Creates and configures the embedded node-oidc-provider instance for the Nexus.
741
+ *
742
+ * @param config - Server configuration containing the issuer URL and allowed M2M clients.
743
+ */
744
+ declare function createOAuthServer(config: OAuthServerConfig): OAuthServerResult;
745
+
746
+ /**
747
+ * RFC 9728 Protected Resource Metadata response.
748
+ *
749
+ * @see https://datatracker.ietf.org/doc/rfc9728
750
+ */
751
+ interface ProtectedResourceMetadata {
752
+ /** Identifier for the protected resource. */
753
+ resource: string;
754
+ /** Array of authorization server issuer URLs that can issue tokens for this resource. */
755
+ authorization_servers: string[];
756
+ /** OAuth scopes accepted by this resource. */
757
+ scopes_supported: readonly string[];
758
+ /** Methods of presenting the bearer token (always "header" for LIOP). */
759
+ bearer_methods_supported: string[];
760
+ /** URL to the resource documentation. */
761
+ resource_documentation: string;
762
+ }
763
+ /**
764
+ * Builds the Protected Resource Metadata document (RFC 9728).
765
+ *
766
+ * @param issuer - OIDC issuer URL of the Nexus authorization server
767
+ * @param audience - JWT audience claim (resource identifier)
768
+ */
769
+ declare function buildProtectedResourceMetadata(issuer: string, audience: string): ProtectedResourceMetadata;
770
+
771
+ /**
772
+ * LIOP RBAC Engine — Scope-Based Authorization
773
+ *
774
+ * Maps MCP JSON-RPC methods to required LIOP OAuth scopes.
775
+ * Enforces least-privilege access at the router level before
776
+ * any tool execution or resource read occurs.
777
+ *
778
+ * Standards: NIST SP 800-207 §4.3 (least privilege), OWASP LLM06 (Excessive Agency),
779
+ * OWASP API-A01 (Broken Access Control)
780
+ */
781
+
782
+ /**
783
+ * Authorization result with optional denial reason for audit logging.
784
+ */
785
+ interface AuthorizationResult {
786
+ allowed: boolean;
787
+ reason?: string;
788
+ }
789
+ /**
790
+ * Evaluates whether a request is authorized based on JWT scopes.
791
+ *
792
+ * Decision logic:
793
+ * 1. Methods with no required scopes (initialize, ping) → always allowed.
794
+ * 2. Methods with required scopes but no auth → denied.
795
+ * 3. Methods with required scopes → all scopes must be present in the JWT.
796
+ * 4. Unknown methods with no auth → denied (fail-closed per NIST SP 800-207).
797
+ *
798
+ * @param method - MCP JSON-RPC method name (e.g., "tools/call")
799
+ * @param auth - Validated JWT context, or null if unauthenticated
800
+ * @param additionalScopes - Extra scopes required by specific node configuration
801
+ */
802
+ declare function authorizeRequest(method: string, auth: AuthInfo | null, additionalScopes?: readonly string[]): AuthorizationResult;
803
+ /**
804
+ * All LIOP OAuth scopes supported by the protocol.
805
+ * Used for PRM metadata and client registration.
806
+ */
807
+ declare const LIOP_SCOPES: readonly ["liop:tools:list", "liop:tools:call", "liop:resources:read", "liop:schema:read", "liop:mesh:query"];
808
+ type LiopScope = (typeof LIOP_SCOPES)[number];
809
+
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 };