@nekzus/liop 2.0.0-alpha.1 → 2.0.0-alpha.3

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 (124) hide show
  1. package/README.md +30 -20
  2. package/dist/bin/agent.d.ts +0 -1
  3. package/dist/bin/agent.js +5 -306
  4. package/dist/bin/agent.js.map +1 -0
  5. package/dist/{bridge/stream.d.ts → bridge.d.ts} +44 -3
  6. package/dist/bridge.js +2 -0
  7. package/dist/bridge.js.map +1 -0
  8. package/dist/chunk-7MAGL6ON.js +33 -0
  9. package/dist/chunk-7MAGL6ON.js.map +1 -0
  10. package/dist/chunk-ANFXJGMP.js +2 -0
  11. package/dist/chunk-ANFXJGMP.js.map +1 -0
  12. package/dist/chunk-DBXGYHKY.js +2 -0
  13. package/dist/chunk-DBXGYHKY.js.map +1 -0
  14. package/dist/chunk-FW6CICSY.js +29 -0
  15. package/dist/chunk-FW6CICSY.js.map +1 -0
  16. package/dist/chunk-HM77MWB6.js +2 -0
  17. package/dist/chunk-HM77MWB6.js.map +1 -0
  18. package/dist/chunk-HNDVAKEK.js +24 -0
  19. package/dist/chunk-HNDVAKEK.js.map +1 -0
  20. package/dist/chunk-HQZHZM6U.js +2 -0
  21. package/dist/chunk-HQZHZM6U.js.map +1 -0
  22. package/dist/chunk-JBMEAXYU.js +13 -0
  23. package/dist/chunk-JBMEAXYU.js.map +1 -0
  24. package/dist/chunk-LYULZHZO.js +3 -0
  25. package/dist/chunk-LYULZHZO.js.map +1 -0
  26. package/dist/chunk-P52IE4L6.js +2 -0
  27. package/dist/chunk-P52IE4L6.js.map +1 -0
  28. package/dist/chunk-PPCOS2NU.js +2 -0
  29. package/dist/chunk-PPCOS2NU.js.map +1 -0
  30. package/dist/chunk-RWRRBYG4.js +2 -0
  31. package/dist/chunk-RWRRBYG4.js.map +1 -0
  32. package/dist/chunk-S6RJHZV2.js +2 -0
  33. package/dist/chunk-S6RJHZV2.js.map +1 -0
  34. package/dist/chunk-UVTEJYHN.js +2 -0
  35. package/dist/chunk-UVTEJYHN.js.map +1 -0
  36. package/dist/client.d.ts +5 -0
  37. package/dist/client.js +2 -0
  38. package/dist/client.js.map +1 -0
  39. package/dist/{gateway/router.d.ts → gateway.d.ts} +30 -5
  40. package/dist/gateway.js +2 -0
  41. package/dist/gateway.js.map +1 -0
  42. package/dist/{client/index.d.ts → index-CyxNLlz7.d.ts} +24 -5
  43. package/dist/index.d.ts +313 -12
  44. package/dist/index.js +31 -12
  45. package/dist/index.js.map +1 -0
  46. package/dist/kyber-2WDOTUQX.js +2 -0
  47. package/dist/kyber-2WDOTUQX.js.map +1 -0
  48. package/dist/{mesh/node.d.ts → mesh.d.ts} +5 -3
  49. package/dist/mesh.js +2 -0
  50. package/dist/mesh.js.map +1 -0
  51. package/dist/{server/index.d.ts → server.d.ts} +125 -12
  52. package/dist/server.js +2 -0
  53. package/dist/server.js.map +1 -0
  54. package/dist/types.d.ts +17 -14
  55. package/dist/types.js +2 -26
  56. package/dist/types.js.map +1 -0
  57. package/dist/{crypto/verifier.d.ts → verifier-DTCD9imJ.d.ts} +3 -1
  58. package/dist/verifier-RQRYXA4C.js +2 -0
  59. package/dist/verifier-RQRYXA4C.js.map +1 -0
  60. package/dist/workers/logic-execution.d.ts +4 -2
  61. package/dist/workers/logic-execution.js +2 -123
  62. package/dist/workers/logic-execution.js.map +1 -0
  63. package/dist/workers/zk-verifier.d.ts +4 -2
  64. package/dist/workers/zk-verifier.js +2 -98
  65. package/dist/workers/zk-verifier.js.map +1 -0
  66. package/package.json +32 -19
  67. package/dist/bridge/index.d.ts +0 -37
  68. package/dist/bridge/index.js +0 -249
  69. package/dist/bridge/stream.js +0 -210
  70. package/dist/client/index.js +0 -275
  71. package/dist/crypto/logic-image-id.d.ts +0 -3
  72. package/dist/crypto/logic-image-id.js +0 -27
  73. package/dist/crypto/verifier.js +0 -97
  74. package/dist/economy/estimator.d.ts +0 -53
  75. package/dist/economy/estimator.js +0 -69
  76. package/dist/economy/index.d.ts +0 -5
  77. package/dist/economy/index.js +0 -3
  78. package/dist/economy/otel.d.ts +0 -38
  79. package/dist/economy/otel.js +0 -100
  80. package/dist/economy/telemetry.d.ts +0 -77
  81. package/dist/economy/telemetry.js +0 -224
  82. package/dist/errors.d.ts +0 -14
  83. package/dist/errors.js +0 -19
  84. package/dist/gateway/hybrid.d.ts +0 -23
  85. package/dist/gateway/hybrid.js +0 -199
  86. package/dist/gateway/router.js +0 -1054
  87. package/dist/mesh/index.d.ts +0 -1
  88. package/dist/mesh/index.js +0 -1
  89. package/dist/mesh/node.js +0 -853
  90. package/dist/prompts/adapters.d.ts +0 -16
  91. package/dist/prompts/adapters.js +0 -55
  92. package/dist/rpc/client.d.ts +0 -22
  93. package/dist/rpc/client.js +0 -40
  94. package/dist/rpc/codec/lpm.d.ts +0 -20
  95. package/dist/rpc/codec/lpm.js +0 -36
  96. package/dist/rpc/crypto/aes.d.ts +0 -22
  97. package/dist/rpc/crypto/aes.js +0 -47
  98. package/dist/rpc/crypto/kyber.d.ts +0 -27
  99. package/dist/rpc/crypto/kyber.js +0 -70
  100. package/dist/rpc/proto.d.ts +0 -2
  101. package/dist/rpc/proto.js +0 -33
  102. package/dist/rpc/server.d.ts +0 -13
  103. package/dist/rpc/server.js +0 -50
  104. package/dist/rpc/tls.d.ts +0 -26
  105. package/dist/rpc/tls.js +0 -54
  106. package/dist/rpc/types.d.ts +0 -28
  107. package/dist/rpc/types.js +0 -5
  108. package/dist/sandbox/guardian.d.ts +0 -18
  109. package/dist/sandbox/guardian.js +0 -58
  110. package/dist/sandbox/wasi.d.ts +0 -36
  111. package/dist/sandbox/wasi.js +0 -233
  112. package/dist/security/guardian.d.ts +0 -22
  113. package/dist/security/guardian.js +0 -52
  114. package/dist/security/zk.d.ts +0 -37
  115. package/dist/security/zk.js +0 -76
  116. package/dist/server/index.js +0 -1047
  117. package/dist/server/ner-scanner.d.ts +0 -29
  118. package/dist/server/ner-scanner.js +0 -141
  119. package/dist/server/pii.d.ts +0 -66
  120. package/dist/server/pii.js +0 -428
  121. package/dist/utils/logger.d.ts +0 -21
  122. package/dist/utils/logger.js +0 -70
  123. package/dist/utils/mcpCompact.d.ts +0 -11
  124. package/dist/utils/mcpCompact.js +0 -29
package/dist/index.d.ts CHANGED
@@ -1,12 +1,313 @@
1
- export * from "./bridge/index.js";
2
- export * from "./client/index.js";
3
- export * from "./economy/index.js";
4
- export * from "./errors.js";
5
- export * from "./gateway/hybrid.js";
6
- export * from "./mesh/node.js";
7
- export * from "./prompts/adapters.js";
8
- export * from "./rpc/client.js";
9
- export * from "./rpc/server.js";
10
- export * from "./sandbox/wasi.js";
11
- export * from "./server/index.js";
12
- export * from "./types.js";
1
+ export { LiopBridgeOptions, LiopMcpBridge, LiopStreamBridge, LiopStreamBridgeOptions } from './bridge.js';
2
+ import { L as LiopTlsOptions } from './index-CyxNLlz7.js';
3
+ export { a as LiopClient } from './index-CyxNLlz7.js';
4
+ export { LiopHybridGateway } from './gateway.js';
5
+ export { LiopManifest, MeshNode, MeshNodeConfig } from './mesh.js';
6
+ import * as grpc from '@grpc/grpc-js';
7
+ export { AggregationPolicy, LiopServer, LiopServerOptions, LogicExecutionPolicy, NerScanner, PII_PATTERNS, PII_PRESETS, PiiRule, PiiScanner, ToolHandler } from './server.js';
8
+ export { CallToolRequest, CallToolResult, GetPromptRequest, GetPromptResult, McpRequest, McpResponse, Prompt, PromptSchema, Resource, ResourceSchema, ServerInfo, Tool, ToolSchema } from './types.js';
9
+ import '@modelcontextprotocol/sdk/server/mcp.js';
10
+ import 'zod';
11
+ import './verifier-DTCD9imJ.js';
12
+
13
+ /**
14
+ * TokenEstimator — Pluggable strategy for counting tokens in text content.
15
+ *
16
+ * Implementations range from exact BPE tokenization to lightweight heuristics,
17
+ * allowing the SDK to choose the best trade-off for the runtime environment.
18
+ */
19
+ interface TokenEstimator {
20
+ /** Count the number of tokens in the given text */
21
+ countTokens(text: string): number;
22
+ /** Human-readable name of the estimation strategy */
23
+ readonly name: string;
24
+ }
25
+ /**
26
+ * Exact BPE tokenizer using o200k_base encoding.
27
+ *
28
+ * o200k_base is the standard encoding for all modern OpenAI models
29
+ * (GPT-4o, GPT-4.1, o1, o3, o4) and provides a reasonable baseline
30
+ * for Anthropic/Google models as well (~±5% variance).
31
+ *
32
+ * - Synchronous: safe for hot-path usage without async overhead
33
+ * - Merge cache reduced to 10K entries for long-running server processes
34
+ * - Zero runtime dependencies beyond gpt-tokenizer itself
35
+ */
36
+ declare class RealTokenEstimator implements TokenEstimator {
37
+ readonly name = "o200k_base";
38
+ private countFn;
39
+ constructor(countFn: (text: string) => number, setMergeCacheSizeFn?: (size: number) => void);
40
+ countTokens(text: string): number;
41
+ }
42
+ /**
43
+ * Fallback heuristic estimator: ~4 characters per token.
44
+ *
45
+ * Industry-standard approximation (±10% for English/code content).
46
+ * Used only when gpt-tokenizer fails to load in constrained environments.
47
+ */
48
+ declare class HeuristicTokenEstimator implements TokenEstimator {
49
+ readonly name = "heuristic (chars/4)";
50
+ countTokens(text: string): number;
51
+ }
52
+ /**
53
+ * Factory: creates a RealTokenEstimator with gpt-tokenizer,
54
+ * falling back to HeuristicTokenEstimator if the import fails.
55
+ *
56
+ * Uses dynamic import to avoid blocking SDK initialization and to
57
+ * gracefully degrade in environments where gpt-tokenizer is unavailable.
58
+ */
59
+ declare function createTokenEstimator(): Promise<TokenEstimator>;
60
+ /**
61
+ * Synchronous factory: creates a HeuristicTokenEstimator immediately.
62
+ * Used when the async factory cannot be awaited (e.g., constructor contexts).
63
+ * The engine should upgrade to the real estimator via setEstimator() later.
64
+ */
65
+ declare function createSyncTokenEstimator(): TokenEstimator;
66
+
67
+ /**
68
+ * LiopOTelBridge — OpenTelemetry gen_ai.* metric emitter.
69
+ *
70
+ * Pattern: Library Instrumentation (uses global MeterProvider only).
71
+ * Per official OTel JS documentation:
72
+ * - Libraries MUST NOT create their own MeterProvider
73
+ * - Libraries SHOULD use metrics.getMeter() from the global API
74
+ * - If no MeterProvider is registered by the application, all operations are NoOp
75
+ * with zero runtime overhead (confirmed by OTel JS source: NoopMeterProvider)
76
+ *
77
+ * Follows OpenTelemetry Generative AI Semantic Conventions (Development status).
78
+ * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/
79
+ */
80
+ declare class LiopOTelBridge {
81
+ private tokenUsage;
82
+ private operationDuration;
83
+ private active;
84
+ constructor();
85
+ /**
86
+ * Record token usage with gen_ai.* standard attributes.
87
+ *
88
+ * @param tokens - Number of tokens consumed
89
+ * @param tokenType - "input" or "output" (gen_ai.token.type)
90
+ * @param operationName - gen_ai.operation.name (e.g., "execute_tool", "chat")
91
+ * @param toolName - Optional LIOP-specific tool name for attribution
92
+ */
93
+ recordTokens(tokens: number, tokenType: "input" | "output", operationName: string, toolName?: string): void;
94
+ /**
95
+ * Record operation duration with gen_ai.* standard attributes.
96
+ *
97
+ * @param durationMs - Duration in milliseconds (converted to seconds for OTel)
98
+ * @param operationName - gen_ai.operation.name
99
+ * @param error - Optional error type string if the operation failed
100
+ */
101
+ recordDuration(durationMs: number, operationName: string, error?: string): void;
102
+ /** Whether the OTel bridge is actively connected to a MeterProvider */
103
+ isActive(): boolean;
104
+ }
105
+
106
+ /** Single MCP operation token footprint */
107
+ interface TokenOperationMetric {
108
+ readonly type: "tools_list" | "tool_call" | "resource_read" | "resource_list" | "prompt_get" | "prompt_list" | "diagnostic";
109
+ readonly method: string;
110
+ readonly estimatedInputTokens: number;
111
+ readonly estimatedOutputTokens: number;
112
+ readonly timestamp: number;
113
+ readonly toolName?: string;
114
+ readonly peerId?: string;
115
+ readonly durationMs?: number;
116
+ }
117
+ /** Session-level aggregate report */
118
+ interface TokenSessionReport {
119
+ readonly sessionId: string;
120
+ readonly operations: ReadonlyArray<TokenOperationMetric>;
121
+ readonly totalInputTokens: number;
122
+ readonly totalOutputTokens: number;
123
+ readonly estimatorName: string;
124
+ readonly sessionUptimeMs: number;
125
+ }
126
+ /** Per-tool aggregate breakdown */
127
+ interface ToolTokenBreakdown {
128
+ readonly input: number;
129
+ readonly output: number;
130
+ readonly calls: number;
131
+ readonly avgDurationMs: number;
132
+ }
133
+ /**
134
+ * TokenTelemetryEngine — Full-spectrum observational singleton for token cost measurement.
135
+ *
136
+ * Design principles:
137
+ * - Pure observer pattern: NEVER mutates MCP payloads or protocol flow.
138
+ * - Real tokenization: o200k_base BPE via gpt-tokenizer (async init, sync counting).
139
+ * - OTel gen_ai.* emission: standard metrics via @opentelemetry/api (NoOp if no provider).
140
+ * - Error isolation: telemetry failures never propagate to protocol operations.
141
+ */
142
+ declare class TokenTelemetryEngine {
143
+ private static instance;
144
+ private operations;
145
+ private readonly sessionId;
146
+ private readonly startedAt;
147
+ private estimator;
148
+ private otelBridge;
149
+ private constructor();
150
+ /** Async upgrade from heuristic to real BPE tokenizer */
151
+ private initRealEstimator;
152
+ static getInstance(): TokenTelemetryEngine;
153
+ /**
154
+ * Count tokens in a string using the active estimator.
155
+ * Delegates to o200k_base BPE tokenizer (or heuristic fallback).
156
+ */
157
+ countTokens(content: string): number;
158
+ /**
159
+ * Record a single MCP operation's token footprint.
160
+ * Emits both internal metrics and OTel gen_ai.* histograms.
161
+ */
162
+ record(metric: Omit<TokenOperationMetric, "timestamp">): void;
163
+ /**
164
+ * @deprecated Use countTokens() instead. Kept for backward compatibility.
165
+ */
166
+ estimateTokens(content: string): number;
167
+ /** Generate the full session report */
168
+ getReport(): TokenSessionReport;
169
+ /** Get per-tool token breakdown for diagnostic display */
170
+ getPerToolReport(): Map<string, ToolTokenBreakdown>;
171
+ /**
172
+ * Format a rich, human-readable summary block for LiopMeshStatus diagnostic.
173
+ * Returns empty string when no operations have been recorded.
174
+ */
175
+ formatStatusBlock(): string;
176
+ /** Format milliseconds into human-readable uptime string */
177
+ private formatUptime;
178
+ /** Reset all recorded metrics (used in tests) */
179
+ reset(): void;
180
+ /** Destroy the singleton (used in tests to guarantee isolation) */
181
+ static destroy(): void;
182
+ }
183
+
184
+ declare enum ErrorCode {
185
+ CapabilityViolation = "CapabilityViolation",
186
+ SandboxEscape = "SandboxEscape",
187
+ PiiLeak = "PiiLeak",
188
+ InvalidIntent = "InvalidIntent",
189
+ Throttled = "Throttled",
190
+ ZkVerificationFailed = "ZkVerificationFailed",
191
+ MeshUnavailable = "MeshUnavailable",
192
+ ConnectionFailed = "ConnectionFailed"
193
+ }
194
+ declare class LiopError extends Error {
195
+ readonly code: ErrorCode;
196
+ constructor(code: ErrorCode, message: string);
197
+ }
198
+
199
+ /**
200
+ * LIOP Cross-AI Prompt Adapters (Fase 92)
201
+ *
202
+ * Normalizes system instructions for different LLM providers (Claude, OpenAI, Gemini)
203
+ * to ensure they understand how to generate "Logic-on-Origin" WASM-compatible payload structures.
204
+ */
205
+ type AIProvider = "claude" | "openai" | "gemini";
206
+ interface PromptConfig {
207
+ xmlStandard: boolean;
208
+ jsonSchemaPreferred: boolean;
209
+ }
210
+ /**
211
+ * Generates specific System Prompts optimized for the provided AI.
212
+ * This instructs the LLM on how to bypass Context-Pulling and use Logic-Injection (Zero-Shot).
213
+ */
214
+ declare function generateSystemInstructions(provider: AIProvider): string;
215
+
216
+ /**
217
+ * TypeScript interfaces reflecting liop_core.proto (LIOP v1)
218
+ * Optimized for logic-on-origin and high-performance serialization.
219
+ */
220
+ interface IntentRequest {
221
+ agent_did: string;
222
+ capability_hash: string;
223
+ proof_of_intent: Uint8Array;
224
+ }
225
+ interface IntentResponse {
226
+ accepted: boolean;
227
+ session_token: string;
228
+ error_message: string;
229
+ kyber_public_key: Uint8Array;
230
+ }
231
+ interface LogicRequest {
232
+ session_token: string;
233
+ wasm_binary: Uint8Array;
234
+ inputs: Record<string, Uint8Array>;
235
+ pqc_ciphertext: Uint8Array;
236
+ aes_nonce: Uint8Array;
237
+ }
238
+ interface LogicResponse {
239
+ semantic_evidence: string;
240
+ cryptographic_proof: Uint8Array;
241
+ zk_receipt: Uint8Array;
242
+ is_error: boolean;
243
+ }
244
+
245
+ /**
246
+ * LIOP gRPC Client Implementation
247
+ * Provides a high-level interface for secure intent negotiation and logic execution.
248
+ */
249
+ declare class LiopRpcClient {
250
+ private client;
251
+ constructor(address: string, tls?: LiopTlsOptions);
252
+ /**
253
+ * Negotiates intent with the remote host.
254
+ * Returns the ephemeral Kyber public key for payload encryption.
255
+ */
256
+ negotiateIntent(request: IntentRequest): Promise<IntentResponse>;
257
+ /**
258
+ * Pushes the encrypted Logic-on-Origin payload to the origin.
259
+ * Returns a stream of semantic responses and ZK proofs.
260
+ */
261
+ executeLogic(request: LogicRequest): grpc.ClientReadableStream<LogicResponse>;
262
+ close(): void;
263
+ }
264
+
265
+ declare class LiopRpcServer {
266
+ private server;
267
+ constructor();
268
+ addService(handlers: {
269
+ negotiateIntent: (call: grpc.ServerUnaryCall<IntentRequest, IntentResponse>, callback: grpc.sendUnaryData<IntentResponse>) => void;
270
+ executeLogic: (call: grpc.ServerWritableStream<LogicRequest, LogicResponse>) => void;
271
+ }): void;
272
+ listen(port?: number, tls?: LiopTlsOptions): Promise<number>;
273
+ stop(): Promise<void>;
274
+ }
275
+
276
+ interface SandboxConfig {
277
+ allowEnv?: boolean;
278
+ allowedDirectories?: Record<string, string>;
279
+ memoryLimitMb?: number;
280
+ }
281
+ /**
282
+ * LIOP WasiSandbox (Industrial Grade)
283
+ *
284
+ * Provides a production-grade isolated environment for executing untrusted logic.
285
+ * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened
286
+ * V8 Isolate fallback for dynamic JS-to-WASM logic injection.
287
+ */
288
+ declare class WasiSandbox {
289
+ private wasi;
290
+ private sandboxId;
291
+ private workingDir;
292
+ private config;
293
+ private stdoutHandle;
294
+ private stderrHandle;
295
+ constructor(config?: SandboxConfig);
296
+ /**
297
+ * Initializes the physical sandbox environment with strict directory lockdown.
298
+ */
299
+ init(): Promise<void>;
300
+ /**
301
+ * Executes logic (WASM or JS-Wrapped) with hard resource limits.
302
+ */
303
+ execute(compiledLogic: Buffer | string, records?: Record<string, unknown>[], inputs?: Record<string, unknown>): Promise<{
304
+ output: unknown;
305
+ fuelConsumed: number;
306
+ }>;
307
+ /**
308
+ * Physically cleans up the sandbox and releases resources.
309
+ */
310
+ teardown(): Promise<void>;
311
+ }
312
+
313
+ export { type AIProvider, ErrorCode, HeuristicTokenEstimator, LiopError, LiopOTelBridge, LiopRpcClient, LiopRpcServer, type PromptConfig, RealTokenEstimator, type SandboxConfig, type TokenEstimator, type TokenOperationMetric, type TokenSessionReport, TokenTelemetryEngine, type ToolTokenBreakdown, WasiSandbox, createSyncTokenEstimator, createTokenEstimator, generateSystemInstructions };
package/dist/index.js CHANGED
@@ -1,12 +1,31 @@
1
- export * from "./bridge/index.js";
2
- export * from "./client/index.js";
3
- export * from "./economy/index.js";
4
- export * from "./errors.js";
5
- export * from "./gateway/hybrid.js";
6
- export * from "./mesh/node.js";
7
- export * from "./prompts/adapters.js";
8
- export * from "./rpc/client.js";
9
- export * from "./rpc/server.js";
10
- export * from "./sandbox/wasi.js";
11
- export * from "./server/index.js";
12
- export * from "./types.js";
1
+ export{b as WasiSandbox}from'./chunk-HNDVAKEK.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-P52IE4L6.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-HQZHZM6U.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-LYULZHZO.js';export{a as LiopHybridGateway}from'./chunk-JBMEAXYU.js';export{a as LiopRpcServer,f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-FW6CICSY.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-7MAGL6ON.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';export{a as MeshNode}from'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';var u=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(u||{}),n=class extends Error{code;constructor(t,o){super(o),this.name="LiopError",this.code=t;}};var f={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function D(a){let t=f[a],o=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
2
+ You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
3
+ Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
4
+
5
+ ### CORE PARADIGM
6
+ When you call a tool or resource, you MUST provide a payload that represents secure sandboxed logic to be executed on the remote Node.
7
+ The node will execute your logic securely on the raw secure data, and return only the RESULT, avoiding PII data egress.
8
+
9
+ ### EXECUTION RULES
10
+ 1. Provide a self-contained JavaScript syntax block that we will compile to WASM-Sandboxed logic.
11
+ 2. Rely only on standard ECMA script features (No Node.js polyfills).
12
+ 3. The logic must end by returning the calculated insights, not the raw data.
13
+ `;return t.xmlStandard?o+=`
14
+ ### PAYLOAD FORMATTING (CLAUDE-XML PREFERRED)
15
+ You must wrap your logic precisely within <liop_logic> tags.
16
+ Example:
17
+ <liop_logic>
18
+ const records = await liop.readResource("liop://vault/patients");
19
+ const filtered = records.filter(r => r.disease === "Hypertension");
20
+ return { alert: "High risk demographic", targetCount: filtered.length };
21
+ </liop_logic>
22
+ `:t.jsonSchemaPreferred&&(o+=`
23
+ ### PAYLOAD FORMATTING (JSON PARSING PREFERRED)
24
+ You must provide your logic strictly within a JSON string key called \`"logic_blob"\` inside your tool call parameters.
25
+ Example:
26
+ {
27
+ "target": "liop://vault/patients",
28
+ "logic_blob": "const records = await liop.readResource(args.target); return { targetCount: records.filter(r => r.disease === 'Hypertension').length };"
29
+ }
30
+ `),o}export{u as ErrorCode,n as LiopError,D as generateSystemInstructions};//# sourceMappingURL=index.js.map
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/prompts/adapters.ts"],"names":["ErrorCode","LiopError","code","message","PROVIDER_CONFIGS","generateSystemInstructions","provider","config","instructions"],"mappings":"60BAAO,IAAKA,OACXA,CAAAA,CAAA,mBAAA,CAAsB,qBAAA,CACtBA,CAAAA,CAAA,cAAgB,eAAA,CAChBA,CAAAA,CAAA,OAAA,CAAU,SAAA,CACVA,EAAA,aAAA,CAAgB,eAAA,CAChBA,EAAA,SAAA,CAAY,WAAA,CACZA,EAAA,oBAAA,CAAuB,sBAAA,CACvBA,CAAAA,CAAA,eAAA,CAAkB,kBAClBA,CAAAA,CAAA,gBAAA,CAAmB,kBAAA,CARRA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,IAWCC,CAAAA,CAAN,cAAwB,KAAM,CACpB,KAEhB,WAAA,CAAYC,CAAAA,CAAiBC,EAAiB,CAC7C,KAAA,CAAMA,CAAO,CAAA,CACb,IAAA,CAAK,IAAA,CAAO,WAAA,CACZ,KAAK,IAAA,CAAOD,EACb,CACD,ECLA,IAAME,CAAAA,CAAqD,CAC1D,MAAA,CAAQ,CAAE,YAAa,IAAA,CAAM,mBAAA,CAAqB,KAAM,CAAA,CACxD,MAAA,CAAQ,CAAE,WAAA,CAAa,KAAA,CAAO,mBAAA,CAAqB,IAAK,EACxD,MAAA,CAAQ,CAAE,YAAa,KAAA,CAAO,mBAAA,CAAqB,IAAK,CACzD,CAAA,CAMO,SAASC,CAAAA,CAA2BC,EAA8B,CACxE,IAAMC,EAASH,CAAAA,CAAiBE,CAAQ,EAEpCE,CAAAA,CAAe,CAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAcnB,OAAID,CAAAA,CAAO,WAAA,CACVC,CAAAA,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAUND,CAAAA,CAAO,sBACjBC,CAAAA,EAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA,CAAA,CAWVA,CACR","file":"index.js","sourcesContent":["export 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","/**\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\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"]}
@@ -0,0 +1,2 @@
1
+ export{a as Kyber768Wrapper}from'./chunk-DBXGYHKY.js';//# sourceMappingURL=kyber-2WDOTUQX.js.map
2
+ //# sourceMappingURL=kyber-2WDOTUQX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"kyber-2WDOTUQX.js"}
@@ -2,7 +2,7 @@
2
2
  * Manifest describing a node's capabilities in the LIOP Mesh.
3
3
  * Exchanged via the /liop/manifest/1.0.0 protocol stream.
4
4
  */
5
- export interface LiopManifest {
5
+ interface LiopManifest {
6
6
  peerId: string;
7
7
  grpcPort: number;
8
8
  tools: Array<{
@@ -27,7 +27,7 @@ export interface LiopManifest {
27
27
  executionTypes: string[];
28
28
  };
29
29
  }
30
- export interface MeshNodeConfig {
30
+ interface MeshNodeConfig {
31
31
  listenAddresses?: string[];
32
32
  bootstrapNodes?: string[];
33
33
  identityPath?: string;
@@ -42,7 +42,7 @@ export interface MeshNodeConfig {
42
42
  * Provides capability advertisement via CID-based content routing
43
43
  * and decentralized peer discovery.
44
44
  */
45
- export declare class MeshNode {
45
+ declare class MeshNode {
46
46
  private node;
47
47
  private config;
48
48
  private manifestDialFailureState;
@@ -127,3 +127,5 @@ export declare class MeshNode {
127
127
  findProviders(hash: string): Promise<string[]>;
128
128
  resolvePeer(peerIdStr: string): Promise<string[]>;
129
129
  }
130
+
131
+ export { type LiopManifest, MeshNode, type MeshNodeConfig };
package/dist/mesh.js ADDED
@@ -0,0 +1,2 @@
1
+ import'./chunk-RWRRBYG4.js';export{a as MeshNode}from'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=mesh.js.map
2
+ //# sourceMappingURL=mesh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"mesh.js"}
@@ -1,13 +1,113 @@
1
- import { z } from "zod";
2
- import { MeshNode } from "../mesh/node.js";
3
- import type { CallToolRequest, CallToolResult, GetPromptRequest, GetPromptResult, Prompt, Resource, ServerInfo, Tool } from "../types.js";
4
- import { NerScanner } from "./ner-scanner.js";
5
- import { PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner } from "./pii.js";
6
- export { NerScanner, PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner };
7
- export type ToolHandler<T extends z.ZodRawShape = z.ZodRawShape> = (args: z.infer<z.ZodObject<T>>, extra: {
1
+ import { z } from 'zod';
2
+ import { MeshNode } from './mesh.js';
3
+ import { ServerInfo, CallToolResult, Prompt, GetPromptRequest, GetPromptResult, CallToolRequest, Tool, Resource } from './types.js';
4
+
5
+ /** Single named entity detected by the NER scanner. */
6
+ interface NerEntity {
7
+ type: "person" | "place" | "organization";
8
+ text: string;
9
+ }
10
+ /** Result of an NER scan operation. */
11
+ interface NerScanResult {
12
+ detected: boolean;
13
+ entities: NerEntity[];
14
+ }
15
+ /**
16
+ * Scans text content for named entities that may represent PII.
17
+ * Uses `compromise/three` for person, place, and organization detection.
18
+ *
19
+ * Designed for egress filtering — optimized for recall over precision
20
+ * to ensure sensitive data does not leak through aliased output keys.
21
+ */
22
+ declare class NerScanner {
23
+ private static nlp;
24
+ /**
25
+ * Lazy loads the compromise library only when needed.
26
+ */
27
+ private getNlp;
28
+ /**
29
+ * Scans a single string value for named entities.
30
+ * Returns detected entities if the text contains recognizable PII.
31
+ */
32
+ scan(text: string): Promise<NerScanResult>;
33
+ /**
34
+ * Recursively scans all string values within an object/array.
35
+ * Stops at the first detection for performance (fail-fast).
36
+ */
37
+ scanDeep(input: unknown, seen?: WeakSet<object>): Promise<NerScanResult>;
38
+ }
39
+
40
+ /**
41
+ * LIOP Professional PII Engine (The Shield V2 - Tier-1 Military Edition)
42
+ * Implements high-fidelity detection based on NIST and OWASP standards.
43
+ * Features Multi-Layer Verification (Regex + Algorithmic Validators).
44
+ */
45
+ type PiiRuleDefinition = {
46
+ name: string;
47
+ pattern: string | RegExp;
48
+ validator?: (match: string) => boolean;
49
+ };
50
+ type PiiRule = string | RegExp | PiiRuleDefinition;
51
+ declare const PII_PATTERNS: {
52
+ EMAIL: PiiRuleDefinition;
53
+ CREDIT_CARD: PiiRuleDefinition;
54
+ IP_ADDRESS: PiiRuleDefinition;
55
+ PHONE: PiiRuleDefinition;
56
+ SSN: PiiRuleDefinition;
57
+ IBAN: PiiRuleDefinition;
58
+ PASSPORT_MRZ: PiiRuleDefinition;
59
+ };
60
+ /**
61
+ * Regional and Cultural Security Presets for Out-Of-The-Box compliance.
62
+ * Developers can override, merge, or omit these based on local laws.
63
+ */
64
+ declare const PII_PRESETS: {
65
+ GLOBAL_STRICT: PiiRuleDefinition[];
66
+ US_COMPLIANT: PiiRuleDefinition[];
67
+ EU_GDPR: PiiRuleDefinition[];
68
+ };
69
+ declare class PiiScanner {
70
+ private patterns;
71
+ private forbiddenKeysSet;
72
+ private nerScanner;
73
+ /**
74
+ * Safelist of keys that contain forbidden substrings but are NOT PII.
75
+ * Prevents false positives from fuzzy matching (e.g., "grid" contains "id").
76
+ */
77
+ private static readonly KEY_SAFELIST;
78
+ /**
79
+ * Short forbidden tokens (< 4 chars) that require boundary-aware matching.
80
+ * Uses regex boundary detection to avoid false positives.
81
+ */
82
+ private shortTokenBoundaryPatterns;
83
+ /**
84
+ * Long forbidden tokens (>= 4 chars) that use substring containment.
85
+ */
86
+ private longForbiddenTokens;
87
+ constructor(patterns?: PiiRule[], forbiddenKeys?: string[], nerScanner?: NerScanner | null);
88
+ /**
89
+ * Scans any input (string, object, array) for PII violations.
90
+ * Returns the pattern/rule name that triggered the violation, or null if safe.
91
+ *
92
+ * Detection pipeline (fail-fast):
93
+ * 1. Exact key match (O(1) Set lookup)
94
+ * 2. Fuzzy key match (boundary detection for short tokens, substring for long)
95
+ * 3. Regex/algorithmic pattern match on string values
96
+ * 4. NER content scan on string values (if enabled)
97
+ */
98
+ scan(input: unknown, seen?: WeakSet<object>): Promise<string | null>;
99
+ /**
100
+ * Checks a key against fuzzy matching rules.
101
+ * Short tokens use boundary-aware regex; long tokens use substring containment.
102
+ */
103
+ private checkKeyFuzzy;
104
+ private checkString;
105
+ }
106
+
107
+ type ToolHandler<T extends z.ZodRawShape = z.ZodRawShape> = (args: z.infer<z.ZodObject<T>>, extra: {
8
108
  signal?: AbortSignal;
9
109
  }) => Promise<CallToolResult>;
10
- export interface LiopServerOptions {
110
+ interface LiopServerOptions {
11
111
  capabilities?: Record<string, unknown>;
12
112
  workerPool?: {
13
113
  enabled?: boolean;
@@ -24,8 +124,10 @@ export interface LiopServerOptions {
24
124
  enableNerScanning?: boolean;
25
125
  /** Rate limiting configuration for tool calls (OWASP A01). */
26
126
  rateLimit?: {
27
- /** Maximum calls per window per tool (default: 30). */
127
+ /** Maximum calls per window per tool (default: 15). */
28
128
  maxPerWindow?: number;
129
+ /** Maximum calls per window across ALL tools combined (default: 40). */
130
+ globalMaxPerWindow?: number;
29
131
  /** Sliding window duration in milliseconds (default: 60000 = 1 min). */
30
132
  windowMs?: number;
31
133
  };
@@ -36,13 +138,13 @@ export interface LiopServerOptions {
36
138
  executionTypes?: string[];
37
139
  };
38
140
  }
39
- export interface AggregationPolicy {
141
+ interface AggregationPolicy {
40
142
  /** Maximum number of object-type array elements allowed (default: 10) */
41
143
  maxOutputRows?: number;
42
144
  /** Allow arrays containing only primitive values (default: true) */
43
145
  allowPrimitiveArrays?: boolean;
44
146
  }
45
- export interface LogicExecutionPolicy {
147
+ interface LogicExecutionPolicy {
46
148
  /**
47
149
  * Validate the business payload returned by sandbox logic (post-execution).
48
150
  * This runs before final egress checks and blocks non-conforming outputs.
@@ -57,7 +159,7 @@ export interface LogicExecutionPolicy {
57
159
  */
58
160
  preflightDenyPatterns?: RegExp[];
59
161
  }
60
- export declare class LiopServer {
162
+ declare class LiopServer {
61
163
  private serverInfo;
62
164
  private config?;
63
165
  private logicCache;
@@ -68,6 +170,9 @@ export declare class LiopServer {
68
170
  private toolCallWindows;
69
171
  private readonly toolCallMaxPerWindow;
70
172
  private readonly toolCallWindowMs;
173
+ private globalCallWindow;
174
+ private readonly globalCallMaxPerWindow;
175
+ private readonly taintAnalyzer;
71
176
  private tools;
72
177
  private resources;
73
178
  private prompts;
@@ -150,6 +255,12 @@ export declare class LiopServer {
150
255
  * the full dataset field by field. (OWASP A01)
151
256
  */
152
257
  private checkToolCallRateLimit;
258
+ /**
259
+ * Global cross-tool rate limiter.
260
+ * Prevents attackers from distributing micro-queries across multiple tools
261
+ * to evade per-tool rate limits. (OWASP A01)
262
+ */
263
+ private checkGlobalRateLimit;
153
264
  /**
154
265
  * Emulates calling a tool (used locally or via LIOPMcpBridge)
155
266
  */
@@ -209,3 +320,5 @@ export declare class LiopServer {
209
320
  */
210
321
  close(): Promise<void>;
211
322
  }
323
+
324
+ export { type AggregationPolicy, LiopServer, type LiopServerOptions, type LogicExecutionPolicy, NerScanner, PII_PATTERNS, PII_PRESETS, type PiiRule, PiiScanner, type ToolHandler };
package/dist/server.js ADDED
@@ -0,0 +1,2 @@
1
+ export{f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-FW6CICSY.js';import'./chunk-HM77MWB6.js';import'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=server.js.map
2
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"server.js"}