@nekzus/liop 1.2.0-alpha.9 → 1.3.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 (53) hide show
  1. package/README.md +59 -47
  2. package/dist/bin/agent.js +222 -51
  3. package/dist/bridge/index.js +7 -6
  4. package/dist/bridge/stream.js +23 -15
  5. package/dist/client/index.js +53 -42
  6. package/dist/crypto/logic-image-id.d.ts +3 -0
  7. package/dist/crypto/logic-image-id.js +27 -0
  8. package/dist/crypto/verifier.d.ts +1 -1
  9. package/dist/crypto/verifier.js +9 -20
  10. package/dist/economy/estimator.d.ts +53 -0
  11. package/dist/economy/estimator.js +69 -0
  12. package/dist/economy/index.d.ts +5 -0
  13. package/dist/economy/index.js +3 -0
  14. package/dist/economy/otel.d.ts +38 -0
  15. package/dist/economy/otel.js +100 -0
  16. package/dist/economy/telemetry.d.ts +77 -0
  17. package/dist/economy/telemetry.js +224 -0
  18. package/dist/errors.d.ts +14 -0
  19. package/dist/errors.js +19 -0
  20. package/dist/gateway/hybrid.d.ts +3 -1
  21. package/dist/gateway/hybrid.js +38 -13
  22. package/dist/gateway/router.d.ts +25 -9
  23. package/dist/gateway/router.js +484 -133
  24. package/dist/index.d.ts +3 -0
  25. package/dist/index.js +3 -0
  26. package/dist/mesh/node.d.ts +16 -0
  27. package/dist/mesh/node.js +394 -113
  28. package/dist/prompts/adapters.d.ts +16 -0
  29. package/dist/prompts/adapters.js +55 -0
  30. package/dist/rpc/proto.js +2 -1
  31. package/dist/rpc/server.d.ts +1 -1
  32. package/dist/rpc/server.js +4 -3
  33. package/dist/rpc/tls.js +3 -2
  34. package/dist/sandbox/guardian.js +27 -4
  35. package/dist/sandbox/wasi.d.ts +1 -1
  36. package/dist/sandbox/wasi.js +44 -3
  37. package/dist/security/guardian.js +3 -2
  38. package/dist/security/zk.d.ts +3 -4
  39. package/dist/security/zk.js +33 -10
  40. package/dist/server/index.d.ts +53 -4
  41. package/dist/server/index.js +362 -49
  42. package/dist/server/pii.d.ts +12 -0
  43. package/dist/server/pii.js +90 -0
  44. package/dist/types.d.ts +16 -0
  45. package/dist/utils/logger.d.ts +21 -0
  46. package/dist/utils/logger.js +70 -0
  47. package/dist/utils/mcpCompact.d.ts +11 -0
  48. package/dist/utils/mcpCompact.js +29 -0
  49. package/dist/workers/logic-execution.d.ts +1 -1
  50. package/dist/workers/logic-execution.js +42 -22
  51. package/dist/workers/zk-verifier.d.ts +2 -0
  52. package/dist/workers/zk-verifier.js +52 -34
  53. package/package.json +16 -4
@@ -3,6 +3,7 @@ import { serve } from "@hono/node-server";
3
3
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
4
4
  import { Hono } from "hono";
5
5
  import { cors } from "hono/cors";
6
+ import { log } from "../utils/logger.js";
6
7
  import { LiopMcpBridge } from "./index.js";
7
8
  const DEFAULT_MAX_SESSIONS_PER_IP = 10;
8
9
  const DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
@@ -53,7 +54,7 @@ export class LiopStreamBridge {
53
54
  lastActivity: Date.now(),
54
55
  clientIp,
55
56
  });
56
- console.error(`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`);
57
+ log.info(`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`);
57
58
  },
58
59
  });
59
60
  // Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router
@@ -72,13 +73,13 @@ export class LiopStreamBridge {
72
73
  }
73
74
  }
74
75
  catch (err) {
75
- console.error("[LIOP-StreamBridge] JSON-RPC error:", err.message);
76
+ log.info("[LIOP-StreamBridge] JSON-RPC error:", err.message);
76
77
  }
77
78
  };
78
79
  transport.onclose = () => {
79
80
  if (transport.sessionId) {
80
81
  this.activeSessions.delete(transport.sessionId);
81
- console.error(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);
82
+ log.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);
82
83
  }
83
84
  };
84
85
  return transport;
@@ -109,7 +110,7 @@ export class LiopStreamBridge {
109
110
  const now = Date.now();
110
111
  for (const [sessionId, entry] of this.activeSessions) {
111
112
  if (now - entry.lastActivity > this.sessionTimeoutMs) {
112
- console.error(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);
113
+ log.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);
113
114
  entry.transport.close().catch(() => {
114
115
  /* Swallow close errors */
115
116
  });
@@ -119,17 +120,24 @@ export class LiopStreamBridge {
119
120
  }
120
121
  setupRoutes() {
121
122
  this.app.use("*", cors());
123
+ // Initialize strict zero-trust token if not provided
124
+ if (!process.env.ZERO_TRUST_TOKEN) {
125
+ process.env.ZERO_TRUST_TOKEN = randomUUID();
126
+ log.info("=".repeat(60));
127
+ log.info("⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️");
128
+ log.info("No ZERO_TRUST_TOKEN found in environment.");
129
+ log.info("A secure ephemeral token has been generated for this session:");
130
+ log.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);
131
+ log.info("=".repeat(60));
132
+ }
122
133
  // ZTA (Zero-Trust Architecture) Security Middleware
123
134
  this.app.use("/mcp", async (c, next) => {
124
135
  const auth = c.req.header("Authorization");
125
136
  const expectedToken = process.env.ZERO_TRUST_TOKEN;
126
- if (expectedToken) {
127
- if (!auth ||
128
- !auth.startsWith("Bearer ") ||
129
- auth.split(" ")[1] !== expectedToken) {
130
- console.error("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.");
131
- return c.json({ error: "Unauthorized: LIOP Zero-Trust Policy Enforced" }, 401);
132
- }
137
+ if (!auth?.startsWith("Bearer ") ||
138
+ auth.split(" ")[1] !== expectedToken) {
139
+ log.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.");
140
+ return c.json({ error: "Unauthorized: LIOP Zero-Trust Policy Enforced" }, 401);
133
141
  }
134
142
  await next();
135
143
  });
@@ -149,7 +157,7 @@ export class LiopStreamBridge {
149
157
  // Explicitly clean up the session from the Map.
150
158
  if (c.req.method === "DELETE") {
151
159
  this.activeSessions.delete(sessionId);
152
- console.error(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);
160
+ log.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);
153
161
  }
154
162
  return response;
155
163
  }
@@ -158,7 +166,7 @@ export class LiopStreamBridge {
158
166
  const clientIp = this.getClientIp(c);
159
167
  const currentSessions = this.countSessionsByIp(clientIp);
160
168
  if (currentSessions >= this.maxSessionsPerIp) {
161
- console.error(`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`);
169
+ log.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`);
162
170
  return c.json({ error: "Too Many Sessions: Rate limit exceeded" }, 429);
163
171
  }
164
172
  const transport = this.createSessionTransport(clientIp);
@@ -177,7 +185,7 @@ export class LiopStreamBridge {
177
185
  fetch: this.app.fetch,
178
186
  port: listenPort,
179
187
  }, (info) => {
180
- console.error(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`);
188
+ log.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`);
181
189
  resolve();
182
190
  });
183
191
  });
@@ -196,7 +204,7 @@ export class LiopStreamBridge {
196
204
  }
197
205
  if (this.httpServer) {
198
206
  this.httpServer.close();
199
- console.error("[LIOP-StreamBridge] HTTP ports released.");
207
+ log.info("[LIOP-StreamBridge] HTTP ports released.");
200
208
  }
201
209
  }
202
210
  }
@@ -3,6 +3,7 @@ import { MeshNode, } from "../mesh/node.js";
3
3
  import { LiopRpcClient } from "../rpc/client.js";
4
4
  import { AesGcmWrapper } from "../rpc/crypto/aes.js";
5
5
  import { Kyber768Wrapper } from "../rpc/crypto/kyber.js";
6
+ import { log } from "../utils/logger.js";
6
7
  /**
7
8
  * LIOP Client
8
9
  * High-level orchestration for discovery and execution in the Logic-Injection-on-Origin mesh.
@@ -24,11 +25,11 @@ export class LiopClient {
24
25
  async connect(address, options) {
25
26
  this.meshNode = new MeshNode(options?.meshConfig);
26
27
  await this.meshNode.start();
27
- console.error(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`);
28
+ log.info(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`);
28
29
  if (address) {
29
30
  this.rpcClients.set("static", new LiopRpcClient(address, this.tlsOptions));
30
31
  this.serverInfo = { name: `LiopServer (${address})`, version: "1.0.0" };
31
- console.error(`[LiopClient] Static gRPC configured for: ${address}`);
32
+ log.info(`[LiopClient] Static gRPC configured for: ${address}`);
32
33
  }
33
34
  else {
34
35
  this.serverInfo = { name: "LiopServer (Mesh Alpha)", version: "1.0.0" };
@@ -41,25 +42,25 @@ export class LiopClient {
41
42
  async resolveCapability(toolName) {
42
43
  if (!this.meshNode)
43
44
  throw new Error("Client must be connected to Mesh to resolve capabilities.");
44
- console.error(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);
45
+ log.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);
45
46
  const providers = await this.meshNode.findProviders(toolName);
46
47
  if (providers.length === 0) {
47
48
  throw new Error(`Kademlia DHT found zero providers for capability: ${toolName}`);
48
49
  }
49
50
  const providerId = providers[0];
50
- console.error(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);
51
+ log.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);
51
52
  let grpcPort = 50051;
52
53
  const manifest = await this.meshNode.queryManifest(providerId);
53
54
  if (manifest) {
54
55
  grpcPort = manifest.grpcPort;
55
- console.error(`[LiopClient] Manifest resolved: gRPC port ${grpcPort}`);
56
+ log.info(`[LiopClient] Manifest resolved: gRPC port ${grpcPort}`);
56
57
  }
57
58
  const addrs = await this.meshNode.resolvePeer(providerId);
58
59
  for (const maddr of addrs) {
59
60
  const parts = maddr.split("/");
60
61
  if (parts[1] === "ip4") {
61
62
  const grpcHost = `${parts[2]}:${grpcPort}`;
62
- console.error(`[LiopClient] Translated Multiaddr to gRPC Target: ${grpcHost}`);
63
+ log.info(`[LiopClient] Translated Multiaddr to gRPC Target: ${grpcHost}`);
63
64
  return grpcHost;
64
65
  }
65
66
  }
@@ -72,13 +73,13 @@ export class LiopClient {
72
73
  if (!this.meshNode) {
73
74
  throw new Error("Client must be connected before discovering tools.");
74
75
  }
75
- console.error(`[LiopClient] Discovery started...`);
76
+ log.info(`[LiopClient] Discovery started...`);
76
77
  const providerIds = await this.meshNode.discoverManifestProviders();
77
78
  const tools = [];
78
79
  const seenNames = new Set();
79
80
  for (const peerId of providerIds) {
80
81
  try {
81
- console.error(`[LiopClient] Querying manifest from: ${peerId}`);
82
+ log.info(`[LiopClient] Querying manifest from: ${peerId}`);
82
83
  const manifest = await this.meshNode.queryManifest(peerId);
83
84
  if (manifest) {
84
85
  this.manifests.set(peerId, manifest);
@@ -91,10 +92,10 @@ export class LiopClient {
91
92
  }
92
93
  }
93
94
  catch (err) {
94
- console.error(`[LiopClient] Error querying manifest from ${peerId}:`, err instanceof Error ? err.message : String(err));
95
+ log.info(`[LiopClient] Error querying manifest from ${peerId}:`, err instanceof Error ? err.message : String(err));
95
96
  }
96
97
  }
97
- console.error(`[LiopClient] Discovery finished. Found ${tools.length} unique tools.`);
98
+ log.info(`[LiopClient] Discovery finished. Found ${tools.length} unique tools.`);
98
99
  return tools;
99
100
  }
100
101
  /**
@@ -105,7 +106,7 @@ export class LiopClient {
105
106
  throw new Error("Client must be connected before calling tools.");
106
107
  }
107
108
  const toolName = request.name;
108
- console.error(`[LiopClient] Resolving Tool: ${toolName}`);
109
+ log.info(`[LiopClient] Resolving Tool: ${toolName}`);
109
110
  // [ALPHA-FIX] Bypass DHT discovery if we are already statically connected to a provider (Enterprise/Test mode)
110
111
  let rpcClient = this.rpcClients.get("static");
111
112
  if (!rpcClient) {
@@ -113,13 +114,20 @@ export class LiopClient {
113
114
  rpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);
114
115
  }
115
116
  else {
116
- console.error(`[LiopClient] Using existing static gRPC connection for ${toolName}.`);
117
+ log.info(`[LiopClient] Using existing static gRPC connection for ${toolName}.`);
117
118
  }
118
- console.error(`[LiopClient] Negotiating intent for ${toolName}...`);
119
+ log.info(`[LiopClient] Negotiating intent for ${toolName}...`);
120
+ const agentDid = this.meshNode
121
+ ? `did:liop:${this.meshNode.getPeerId()}`
122
+ : "did:liop:ephemeral";
123
+ const intentPayload = Buffer.from(`${toolName}:${Date.now()}`);
124
+ const proofOfIntent = this.meshNode
125
+ ? await this.meshNode.sign(intentPayload)
126
+ : intentPayload;
119
127
  const intentResponse = (await rpcClient.negotiateIntent({
120
- agent_did: "liop-client-alpha",
128
+ agent_did: agentDid,
121
129
  capability_hash: toolName,
122
- proof_of_intent: Buffer.from("alpha-intent-proof"),
130
+ proof_of_intent: proofOfIntent,
123
131
  }));
124
132
  if (!intentResponse.accepted) {
125
133
  throw new Error(`Intent denied by host: ${intentResponse.error_message}`);
@@ -128,30 +136,30 @@ export class LiopClient {
128
136
  const publicKey = intentResponse.kyber_public_key || intentResponse.kyberPublicKey;
129
137
  const sessionToken = intentResponse.session_token || intentResponse.sessionToken;
130
138
  if (!publicKey) {
131
- console.error("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.", intentResponse);
139
+ log.info("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.", intentResponse);
132
140
  throw new Error("Handshake failed: Remote host did not provide a valid Kyber Public Key.");
133
141
  }
134
142
  // 2. Post-Quantum Encapsulation (ML-KEM-768)
135
- console.error(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`);
143
+ log.info(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`);
136
144
  const { ciphertext: kyberCiphertext, sharedSecret } = await Kyber768Wrapper.encapsulateAsymmetric(publicKey);
137
145
  // 3. Symmetric Sealing (AES-256-GCM)
138
- console.error(`[LiopClient] Sealing WASM Payload and Inputs...`);
146
+ log.info(`[LiopClient] Sealing WASM Payload and Inputs...`);
139
147
  const _safePayload = _wasmPayload || Buffer.from("");
140
148
  // Encrypt WASM binary
141
149
  const { ciphertext: encryptedWasm, nonce: aesNonce } = AesGcmWrapper.encryptPayload(_safePayload, sharedSecret);
142
- // Encrypt inputs using the SAME session nonce for the multi-payload request (Standard LIOP V1)
150
+ // Encrypt inputs using a fresh random nonce per input to prevent AES-GCM nonce reuse
143
151
  const encryptedInputs = {};
152
+ const crypto = await import("node:crypto");
144
153
  for (const [key, value] of Object.entries(request.arguments || {})) {
145
- // We manually encrypt with the same nonce/key to match the Proto structure
146
- // ideally we'd have per-field nonces, but for Alpha we follow the liop_core.proto v1.
147
- const crypto = await import("node:crypto");
148
- const cipher = crypto.createCipheriv("aes-256-gcm", sharedSecret, aesNonce);
154
+ const inputNonce = crypto.randomBytes(12);
155
+ const cipher = crypto.createCipheriv("aes-256-gcm", sharedSecret, inputNonce);
149
156
  const encrypted = Buffer.concat([
150
157
  cipher.update(JSON.stringify(value)),
151
158
  cipher.final(),
152
159
  ]);
153
160
  const authTag = cipher.getAuthTag();
154
- encryptedInputs[key] = Buffer.concat([encrypted, authTag]);
161
+ // Prepend the 12-byte nonce to the ciphertext
162
+ encryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);
155
163
  }
156
164
  // 4. Assemble and Execute gRPC LogicRequest
157
165
  const logicRequest = {
@@ -173,9 +181,9 @@ export class LiopClient {
173
181
  if (resultFulfilled)
174
182
  return;
175
183
  hasReceivedData = true;
176
- console.error("[LiopClient] Logic Executed. Verification in progress...");
184
+ log.info("[LiopClient] Logic Executed. Verification in progress...");
177
185
  try {
178
- const isValid = await this.verifier.verifyZkReceipt(_safePayload, Buffer.from(response.cryptographic_proof).toString("hex"), Buffer.from(response.zk_receipt));
186
+ const isValid = await this.verifier.verifyZkReceipt(_safePayload, Buffer.from(response.cryptographic_proof).toString("hex"), Buffer.from(response.zk_receipt), Buffer.from(sharedSecret));
179
187
  if (!isValid) {
180
188
  reject(new Error("PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."));
181
189
  return;
@@ -198,7 +206,7 @@ export class LiopClient {
198
206
  stream.on("error", (err) => {
199
207
  if (resultFulfilled)
200
208
  return;
201
- console.error("[LiopClient] Stream Error:", err);
209
+ log.error("[LiopClient] Stream Error:", err);
202
210
  reject(err);
203
211
  });
204
212
  stream.on("end", () => {
@@ -226,26 +234,29 @@ export class LiopClient {
226
234
  if (!this.meshNode) {
227
235
  throw new Error("Client must be connected before reading resources.");
228
236
  }
229
- console.error(`[LiopClient] Querying Mesh for Resource: ${uri}...`);
230
- // For now, in Alpha v3, we assume the resource is provided by an active provider.
231
- // A more complex implementation would use resolveCapability(uri).
232
- // For the industrial demo, we'll simulate a direct read if connected or throw.
233
- const rpcClient = this.rpcClients.get("static") || Array.from(this.rpcClients.values())[0];
234
- if (!rpcClient) {
235
- throw new Error("Resource reading requires an active RPC connection to a provider.");
237
+ log.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);
238
+ // We search for the peer hosting the resource in the P2P Mesh
239
+ const providers = await this.meshNode.findProviders(uri);
240
+ if (providers.length === 0) {
241
+ throw new Error(`No mesh providers found for resource: ${uri}`);
242
+ }
243
+ // Query the remote peer's manifest
244
+ const manifest = await this.meshNode.queryManifest(providers[0]);
245
+ if (!manifest) {
246
+ throw new Error("Target peer did not return a valid LIOP Manifest.");
247
+ }
248
+ // Locate the exact resource metadata
249
+ const resourceDef = manifest.resources?.find((r) => r.uri === uri);
250
+ if (!resourceDef) {
251
+ throw new Error(`Resource ${uri} not listed in remote manifest.`);
236
252
  }
237
- // This emulates the resource retrieval.
238
- // In a full implementation, this might be a gRPC call.
253
+ // Return the declarative metadata (Logic-Injection is required for actual data extraction)
239
254
  return {
240
255
  contents: [
241
256
  {
242
257
  uri,
243
- mimeType: "application/json",
244
- text: JSON.stringify({
245
- status: "Alpha-Resource-Read-Success",
246
- uri,
247
- timestamp: new Date().toISOString(),
248
- }),
258
+ mimeType: resourceDef.mimeType || "application/json",
259
+ text: JSON.stringify(resourceDef, null, 2),
249
260
  },
250
261
  ],
251
262
  };
@@ -0,0 +1,3 @@
1
+ export declare function normalizeLogicSource(logicUtf8: string): string;
2
+ /** SHA-256 digest of logic bytes (WASM raw; JS UTF-8 after top-level envelope strip). */
3
+ export declare function deriveLogicImageDigest(logicPayload: Uint8Array): Buffer;
@@ -0,0 +1,27 @@
1
+ import crypto from "node:crypto";
2
+ /**
3
+ * Top-level LIOP v1 envelope only. Must NOT use multiline (^/$) mode:
4
+ * proxy logic embeds a full envelope inside JSON strings; `^` per line would
5
+ * incorrectly treat that as the document root and desync ImageID vs the worker.
6
+ */
7
+ const TOP_LEVEL_ENVELOPE = /^\s*@LIOP\{[^}]+\}\n?([\s\S]*?)\n?@END\s*$/;
8
+ export function normalizeLogicSource(logicUtf8) {
9
+ const match = logicUtf8.match(TOP_LEVEL_ENVELOPE);
10
+ if (match?.[1] !== undefined) {
11
+ return match[1].trim();
12
+ }
13
+ return logicUtf8.trim();
14
+ }
15
+ /** SHA-256 digest of logic bytes (WASM raw; JS UTF-8 after top-level envelope strip). */
16
+ export function deriveLogicImageDigest(logicPayload) {
17
+ const isWasm = logicPayload[0] === 0x00 && logicPayload[1] === 0x61;
18
+ if (isWasm) {
19
+ return crypto.createHash("sha256").update(logicPayload).digest();
20
+ }
21
+ const text = Buffer.from(logicPayload).toString("utf-8");
22
+ const normalized = normalizeLogicSource(text);
23
+ return crypto
24
+ .createHash("sha256")
25
+ .update(Buffer.from(normalized, "utf-8"))
26
+ .digest();
27
+ }
@@ -15,7 +15,7 @@ export declare class LiopVerifier {
15
15
  * @param remoteImageIdHex The ImageID reported by the provider (must match our local calculation).
16
16
  * @param zkReceipt The mathematical proof (Seal + Journal) from the zkVM.
17
17
  */
18
- verifyZkReceipt(logicPayload: Buffer, remoteImageIdHex: string, zkReceipt: Buffer): Promise<boolean>;
18
+ verifyZkReceipt(logicPayload: Buffer, remoteImageIdHex: string, zkReceipt: Buffer, sessionSecret?: Buffer): Promise<boolean>;
19
19
  /**
20
20
  * Verifies if a node is running inside an authenticated TEE (e.g. AWS Nitro).
21
21
  *
@@ -1,8 +1,9 @@
1
- import crypto from "node:crypto";
2
1
  import { createRequire } from "node:module";
3
2
  import path from "node:path";
4
3
  import { fileURLToPath, pathToFileURL } from "node:url";
5
4
  import { Piscina } from "piscina";
5
+ import { log } from "../utils/logger.js";
6
+ import { deriveLogicImageDigest } from "./logic-image-id.js";
6
7
  const __filename = fileURLToPath(import.meta.url);
7
8
  const __dirname = path.dirname(__filename);
8
9
  /**
@@ -48,7 +49,7 @@ export class LiopVerifier {
48
49
  * @param remoteImageIdHex The ImageID reported by the provider (must match our local calculation).
49
50
  * @param zkReceipt The mathematical proof (Seal + Journal) from the zkVM.
50
51
  */
51
- async verifyZkReceipt(logicPayload, remoteImageIdHex, zkReceipt) {
52
+ async verifyZkReceipt(logicPayload, remoteImageIdHex, zkReceipt, sessionSecret) {
52
53
  const pool = this.getZkPool();
53
54
  if (!pool)
54
55
  throw new Error("Worker pool initialization failed");
@@ -57,12 +58,13 @@ export class LiopVerifier {
57
58
  logicPayload: new Uint8Array(logicPayload),
58
59
  remoteImageIdHex,
59
60
  zkReceipt: new Uint8Array(zkReceipt),
61
+ sessionSecret: sessionSecret ? new Uint8Array(sessionSecret) : undefined,
60
62
  });
61
63
  if (result.verified) {
62
- console.error(`[LiopVerifier] ${result.message}`);
64
+ log.info(`[LiopVerifier] ${result.message}`);
63
65
  return true;
64
66
  }
65
- console.error(`[LiopVerifier] FAILED: ${result.message}`);
67
+ log.error(`[LiopVerifier] FAILED: ${result.message}`);
66
68
  return false;
67
69
  }
68
70
  /**
@@ -78,11 +80,11 @@ export class LiopVerifier {
78
80
  // 1. Decode CBOR/COSE
79
81
  // 2. Verify Signature against AWS Nitro Root CA
80
82
  // 3. Compare PCRs
81
- console.error("[LiopVerifier] TEE Attestation: AWS Nitro Enclave Signature Verified.");
83
+ log.info("[LiopVerifier] TEE Attestation: Not configured (no-op).");
82
84
  return true;
83
85
  }
84
86
  catch (err) {
85
- console.error("[LiopVerifier] TEE Verification Failed:", err);
87
+ log.error("[LiopVerifier] TEE Verification Failed:", err);
86
88
  return false;
87
89
  }
88
90
  }
@@ -90,19 +92,6 @@ export class LiopVerifier {
90
92
  * Derives the ImageID of a logic payload following the LIOP v1 Standard.
91
93
  */
92
94
  deriveImageId(logicPayload) {
93
- // Sanitization logic for JS payloads (Magic headers, etc.)
94
- let processed = logicPayload;
95
- const isWasm = logicPayload[0] === 0x00 && logicPayload[1] === 0x61; // \0asm
96
- if (!isWasm) {
97
- const text = logicPayload.toString("utf-8");
98
- const clean = text
99
- .replace(/^LIOP_MAGIC:.*?\n/g, "")
100
- .replace(/^MANIFEST:.*?\n/g, "")
101
- .replace(/---BEGIN_LOGIC---\n?/g, "")
102
- .replace(/\n?---END_LOGIC---/g, "")
103
- .trim();
104
- processed = Buffer.from(clean);
105
- }
106
- return crypto.createHash("sha256").update(processed).digest();
95
+ return deriveLogicImageDigest(logicPayload);
107
96
  }
108
97
  }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * TokenEstimator — Pluggable strategy for counting tokens in text content.
3
+ *
4
+ * Implementations range from exact BPE tokenization to lightweight heuristics,
5
+ * allowing the SDK to choose the best trade-off for the runtime environment.
6
+ */
7
+ export interface TokenEstimator {
8
+ /** Count the number of tokens in the given text */
9
+ countTokens(text: string): number;
10
+ /** Human-readable name of the estimation strategy */
11
+ readonly name: string;
12
+ }
13
+ /**
14
+ * Exact BPE tokenizer using o200k_base encoding.
15
+ *
16
+ * o200k_base is the standard encoding for all modern OpenAI models
17
+ * (GPT-4o, GPT-4.1, o1, o3, o4) and provides a reasonable baseline
18
+ * for Anthropic/Google models as well (~±5% variance).
19
+ *
20
+ * - Synchronous: safe for hot-path usage without async overhead
21
+ * - Merge cache reduced to 10K entries for long-running server processes
22
+ * - Zero runtime dependencies beyond gpt-tokenizer itself
23
+ */
24
+ export declare class RealTokenEstimator implements TokenEstimator {
25
+ readonly name = "o200k_base";
26
+ private countFn;
27
+ constructor(countFn: (text: string) => number, setMergeCacheSizeFn?: (size: number) => void);
28
+ countTokens(text: string): number;
29
+ }
30
+ /**
31
+ * Fallback heuristic estimator: ~4 characters per token.
32
+ *
33
+ * Industry-standard approximation (±10% for English/code content).
34
+ * Used only when gpt-tokenizer fails to load in constrained environments.
35
+ */
36
+ export declare class HeuristicTokenEstimator implements TokenEstimator {
37
+ readonly name = "heuristic (chars/4)";
38
+ countTokens(text: string): number;
39
+ }
40
+ /**
41
+ * Factory: creates a RealTokenEstimator with gpt-tokenizer,
42
+ * falling back to HeuristicTokenEstimator if the import fails.
43
+ *
44
+ * Uses dynamic import to avoid blocking SDK initialization and to
45
+ * gracefully degrade in environments where gpt-tokenizer is unavailable.
46
+ */
47
+ export declare function createTokenEstimator(): Promise<TokenEstimator>;
48
+ /**
49
+ * Synchronous factory: creates a HeuristicTokenEstimator immediately.
50
+ * Used when the async factory cannot be awaited (e.g., constructor contexts).
51
+ * The engine should upgrade to the real estimator via setEstimator() later.
52
+ */
53
+ export declare function createSyncTokenEstimator(): TokenEstimator;
@@ -0,0 +1,69 @@
1
+ import { log } from "../utils/logger.js";
2
+ /**
3
+ * Exact BPE tokenizer using o200k_base encoding.
4
+ *
5
+ * o200k_base is the standard encoding for all modern OpenAI models
6
+ * (GPT-4o, GPT-4.1, o1, o3, o4) and provides a reasonable baseline
7
+ * for Anthropic/Google models as well (~±5% variance).
8
+ *
9
+ * - Synchronous: safe for hot-path usage without async overhead
10
+ * - Merge cache reduced to 10K entries for long-running server processes
11
+ * - Zero runtime dependencies beyond gpt-tokenizer itself
12
+ */
13
+ export class RealTokenEstimator {
14
+ name = "o200k_base";
15
+ countFn;
16
+ constructor(countFn, setMergeCacheSizeFn) {
17
+ this.countFn = countFn;
18
+ // Reduce merge cache from default 100K to 10K for server processes
19
+ if (setMergeCacheSizeFn) {
20
+ setMergeCacheSizeFn(10_000);
21
+ }
22
+ }
23
+ countTokens(text) {
24
+ if (text.length === 0)
25
+ return 0;
26
+ return this.countFn(text);
27
+ }
28
+ }
29
+ /**
30
+ * Fallback heuristic estimator: ~4 characters per token.
31
+ *
32
+ * Industry-standard approximation (±10% for English/code content).
33
+ * Used only when gpt-tokenizer fails to load in constrained environments.
34
+ */
35
+ export class HeuristicTokenEstimator {
36
+ name = "heuristic (chars/4)";
37
+ countTokens(text) {
38
+ if (text.length === 0)
39
+ return 0;
40
+ return Math.ceil(text.length / 4);
41
+ }
42
+ }
43
+ /**
44
+ * Factory: creates a RealTokenEstimator with gpt-tokenizer,
45
+ * falling back to HeuristicTokenEstimator if the import fails.
46
+ *
47
+ * Uses dynamic import to avoid blocking SDK initialization and to
48
+ * gracefully degrade in environments where gpt-tokenizer is unavailable.
49
+ */
50
+ export async function createTokenEstimator() {
51
+ try {
52
+ const mod = await import("gpt-tokenizer");
53
+ const estimator = new RealTokenEstimator(mod.countTokens, mod.setMergeCacheSize);
54
+ log.debug("[LIOP-Economy] Token estimator initialized: o200k_base");
55
+ return estimator;
56
+ }
57
+ catch {
58
+ log.info("[LIOP-Economy] gpt-tokenizer unavailable, falling back to heuristic estimator");
59
+ return new HeuristicTokenEstimator();
60
+ }
61
+ }
62
+ /**
63
+ * Synchronous factory: creates a HeuristicTokenEstimator immediately.
64
+ * Used when the async factory cannot be awaited (e.g., constructor contexts).
65
+ * The engine should upgrade to the real estimator via setEstimator() later.
66
+ */
67
+ export function createSyncTokenEstimator() {
68
+ return new HeuristicTokenEstimator();
69
+ }
@@ -0,0 +1,5 @@
1
+ export type { TokenEstimator } from "./estimator.js";
2
+ export { createSyncTokenEstimator, createTokenEstimator, HeuristicTokenEstimator, RealTokenEstimator, } from "./estimator.js";
3
+ export { LiopOTelBridge } from "./otel.js";
4
+ export type { TokenOperationMetric, TokenSessionReport, ToolTokenBreakdown, } from "./telemetry.js";
5
+ export { TokenTelemetryEngine } from "./telemetry.js";
@@ -0,0 +1,3 @@
1
+ export { createSyncTokenEstimator, createTokenEstimator, HeuristicTokenEstimator, RealTokenEstimator, } from "./estimator.js";
2
+ export { LiopOTelBridge } from "./otel.js";
3
+ export { TokenTelemetryEngine } from "./telemetry.js";
@@ -0,0 +1,38 @@
1
+ /**
2
+ * LiopOTelBridge — OpenTelemetry gen_ai.* metric emitter.
3
+ *
4
+ * Pattern: Library Instrumentation (uses global MeterProvider only).
5
+ * Per official OTel JS documentation:
6
+ * - Libraries MUST NOT create their own MeterProvider
7
+ * - Libraries SHOULD use metrics.getMeter() from the global API
8
+ * - If no MeterProvider is registered by the application, all operations are NoOp
9
+ * with zero runtime overhead (confirmed by OTel JS source: NoopMeterProvider)
10
+ *
11
+ * Follows OpenTelemetry Generative AI Semantic Conventions (Development status).
12
+ * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/
13
+ */
14
+ export declare class LiopOTelBridge {
15
+ private tokenUsage;
16
+ private operationDuration;
17
+ private active;
18
+ constructor();
19
+ /**
20
+ * Record token usage with gen_ai.* standard attributes.
21
+ *
22
+ * @param tokens - Number of tokens consumed
23
+ * @param tokenType - "input" or "output" (gen_ai.token.type)
24
+ * @param operationName - gen_ai.operation.name (e.g., "execute_tool", "chat")
25
+ * @param toolName - Optional LIOP-specific tool name for attribution
26
+ */
27
+ recordTokens(tokens: number, tokenType: "input" | "output", operationName: string, toolName?: string): void;
28
+ /**
29
+ * Record operation duration with gen_ai.* standard attributes.
30
+ *
31
+ * @param durationMs - Duration in milliseconds (converted to seconds for OTel)
32
+ * @param operationName - gen_ai.operation.name
33
+ * @param error - Optional error type string if the operation failed
34
+ */
35
+ recordDuration(durationMs: number, operationName: string, error?: string): void;
36
+ /** Whether the OTel bridge is actively connected to a MeterProvider */
37
+ isActive(): boolean;
38
+ }