@nekzus/liop 2.4.0-alpha.22 → 2.4.0-alpha.24

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 (71) hide show
  1. package/README.md +72 -36
  2. package/dist/bin/agent.js +60 -22
  3. package/dist/bin/agent.js.map +1 -1
  4. package/dist/bridge.d.ts +4 -3
  5. package/dist/bridge.js +3 -2
  6. package/dist/{chunk-VRDZ5IKE.js → chunk-2VQS2XRH.js} +15 -9
  7. package/dist/chunk-2VQS2XRH.js.map +1 -0
  8. package/dist/{chunk-EJ426URA.js → chunk-53QKIQNF.js} +4 -4
  9. package/dist/{chunk-EJ426URA.js.map → chunk-53QKIQNF.js.map} +1 -1
  10. package/dist/{chunk-UJFWPRDM.js → chunk-GFGSHQN5.js} +3 -3
  11. package/dist/{chunk-UJFWPRDM.js.map → chunk-GFGSHQN5.js.map} +1 -1
  12. package/dist/{chunk-VRB5HUYU.js → chunk-IDTXJQBH.js} +27 -13
  13. package/dist/chunk-IDTXJQBH.js.map +1 -0
  14. package/dist/{chunk-XRDN232O.js → chunk-IHKKWXHJ.js} +24 -25
  15. package/dist/chunk-IHKKWXHJ.js.map +1 -0
  16. package/dist/{chunk-5SWHE62F.js → chunk-JWFLXXZS.js} +71 -11
  17. package/dist/chunk-JWFLXXZS.js.map +1 -0
  18. package/dist/{chunk-2KSO3W4A.js → chunk-KR5UZUEY.js} +24 -3
  19. package/dist/chunk-KR5UZUEY.js.map +1 -0
  20. package/dist/chunk-OHMZZMMC.js +58 -0
  21. package/dist/chunk-OHMZZMMC.js.map +1 -0
  22. package/dist/chunk-P34HDRN5.js +213 -0
  23. package/dist/chunk-P34HDRN5.js.map +1 -0
  24. package/dist/{chunk-PAICJCKJ.js → chunk-Q3FKHJ3B.js} +17 -4
  25. package/dist/chunk-Q3FKHJ3B.js.map +1 -0
  26. package/dist/{chunk-PUDETPL4.js → chunk-V47P2AQR.js} +5 -3
  27. package/dist/chunk-V47P2AQR.js.map +1 -0
  28. package/dist/{chunk-FCFTYOAS.js → chunk-ZJGVKM7G.js} +22 -12
  29. package/dist/chunk-ZJGVKM7G.js.map +1 -0
  30. package/dist/{chunk-2STZHJ24.js → chunk-ZRWNMP5L.js} +58 -7
  31. package/dist/chunk-ZRWNMP5L.js.map +1 -0
  32. package/dist/client.d.ts +5 -4
  33. package/dist/client.js +7 -6
  34. package/dist/gateway.d.ts +6 -5
  35. package/dist/gateway.js +7 -6
  36. package/dist/{hybrid-DWe1bMoV.d.ts → hybrid-Cb95yJFg.d.ts} +4 -4
  37. package/dist/{index-CdW8j8Bn.d.ts → index-D2P6Z_hP.d.ts} +25 -2
  38. package/dist/{index-BuEQtBHD.d.ts → index-DtovobWb.d.ts} +8 -4
  39. package/dist/index.d.ts +51 -9
  40. package/dist/index.js +13 -11
  41. package/dist/index.js.map +1 -1
  42. package/dist/mesh.d.ts +1 -1
  43. package/dist/mesh.js +1 -1
  44. package/dist/{node-B0b2vUFS.d.ts → node-Djzm6UYd.d.ts} +8 -0
  45. package/dist/protocol/liop_core.proto +22 -6
  46. package/dist/server.d.ts +4 -3
  47. package/dist/server.js +5 -4
  48. package/dist/{types-CzRSOlOo.d.ts → types-rxL19f0l.d.ts} +3 -0
  49. package/dist/types.d.ts +2 -1
  50. package/dist/types.js +2 -1
  51. package/dist/{verifier-COnid_dg.d.ts → verifier-EgKmGrh7.d.ts} +26 -4
  52. package/dist/verifier-UBJTZQSA.js +6 -0
  53. package/dist/{verifier-XFU7ZB2W.js.map → verifier-UBJTZQSA.js.map} +1 -1
  54. package/dist/workers/logic-execution.d.ts +6 -0
  55. package/dist/workers/logic-execution.js +56 -1
  56. package/dist/workers/logic-execution.js.map +1 -1
  57. package/dist/workers/zk-verifier.d.ts +9 -0
  58. package/dist/workers/zk-verifier.js +119 -47
  59. package/dist/workers/zk-verifier.js.map +1 -1
  60. package/dist/zk-CYImPsa6.d.ts +91 -0
  61. package/package.json +2 -1
  62. package/dist/chunk-2KSO3W4A.js.map +0 -1
  63. package/dist/chunk-2STZHJ24.js.map +0 -1
  64. package/dist/chunk-5SWHE62F.js.map +0 -1
  65. package/dist/chunk-FCFTYOAS.js.map +0 -1
  66. package/dist/chunk-PAICJCKJ.js.map +0 -1
  67. package/dist/chunk-PUDETPL4.js.map +0 -1
  68. package/dist/chunk-VRB5HUYU.js.map +0 -1
  69. package/dist/chunk-VRDZ5IKE.js.map +0 -1
  70. package/dist/chunk-XRDN232O.js.map +0 -1
  71. package/dist/verifier-XFU7ZB2W.js +0 -6
@@ -45,6 +45,27 @@ function adaptResponseForLegacyClient(response) {
45
45
  result: rawResult
46
46
  };
47
47
  }
48
+ var TOOL_ALIASES = {
49
+ bank_tool: "Analyze_Synthetic_Bank_Transactions",
50
+ bank_tool_XDwd: "Analyze_Synthetic_Bank_Transactions",
51
+ vault_tool: "Analyze_Synthetic_Medical_Records",
52
+ vault_tool_E8wP: "Analyze_Synthetic_Medical_Records",
53
+ oracle_tool: "Analyze_HFT_Market_Data",
54
+ compute_aggregate: "Analyze_Synthetic_Bank_Transactions"
55
+ };
56
+ function normalizeToolArguments(args) {
57
+ if (!args) return {};
58
+ const normalized = { ...args };
59
+ if (normalized.data !== void 0) {
60
+ if (normalized.payload === void 0) {
61
+ normalized.payload = normalized.data;
62
+ }
63
+ if (normalized.envelope === void 0) {
64
+ normalized.envelope = normalized.data;
65
+ }
66
+ }
67
+ return normalized;
68
+ }
48
69
 
49
70
  // src/types.ts
50
71
  var MCP_PROTOCOL_VERSION = "2026-07-28";
@@ -72,6 +93,6 @@ var PromptSchema = z.object({
72
93
  ).optional()
73
94
  });
74
95
 
75
- export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, ToolSchema, adaptResponseForLegacyClient, buildLegacyInitializeResponse, isLegacyRequest };
76
- //# sourceMappingURL=chunk-2KSO3W4A.js.map
77
- //# sourceMappingURL=chunk-2KSO3W4A.js.map
96
+ export { MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY, PromptSchema, ResourceSchema, TOOL_ALIASES, ToolSchema, adaptResponseForLegacyClient, buildLegacyInitializeResponse, isLegacyRequest, normalizeToolArguments };
97
+ //# sourceMappingURL=chunk-KR5UZUEY.js.map
98
+ //# sourceMappingURL=chunk-KR5UZUEY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/gateway/mcp-compat.ts","../src/types.ts"],"names":[],"mappings":";;;;;AAiBO,IAAM,0BAAA,GAA6B;AAKnC,IAAM,2BAAA,GAA8B;AAKpC,SAAS,6BAAA,CACf,YACA,EAAA,EACc;AACd,EAAA,OAAO;AAAA,IACN,OAAA,EAAS,KAAA;AAAA,IACT,IAAI,EAAA,IAAM,IAAA;AAAA,IACV,MAAA,EAAQ;AAAA,MACP,eAAA,EAAiB,2BAAA;AAAA,MACjB,YAAA,EAAc;AAAA,QACb,KAAA,EAAO,EAAE,WAAA,EAAa,IAAA,EAAK;AAAA,QAC3B,SAAA,EAAW,EAAE,WAAA,EAAa,IAAA,EAAK;AAAA,QAC/B,OAAA,EAAS,EAAE,WAAA,EAAa,IAAA;AAAK,OAC9B;AAAA,MACA;AAAA;AACD,GACD;AACD;AAOO,SAAS,gBAAgB,OAAA,EAA8B;AAC7D,EAAA,IACC,OAAA,CAAQ,MAAA,KAAW,YAAA,IACnB,OAAA,CAAQ,WAAW,2BAAA,EAClB;AACD,IAAA,OAAO,IAAA;AAAA,EACR;AAEA,EAAA,MAAM,SAAS,OAAA,CAAQ,MAAA;AACvB,EAAA,MAAM,OAAO,MAAA,EAAQ,KAAA;AACrB,EAAA,MAAM,OAAA,GAAU,OAAO,yCAAyC,CAAA;AAEhE,EAAA,IAAI,CAAC,OAAA,IAAW,OAAA,KAAY,2BAAA,EAA6B;AACxD,IAAA,OAAO,IAAA;AAAA,EACR;AAEA,EAAA,OAAO,KAAA;AACR;AAMO,S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;AAAA,EACjC,WAAA,EAAa,EAAE,MAAA,CAAO,CAAA,CAAE,QAAO,EAAG,CAAA,CAAE,SAAS;AAAA;AAC9C,CAAC;AAIM,IAAM,cAAA,GAAiB,EAAE,MAAA,CAAO;AAAA,EACtC,GAAA,EAAK,EAAE,MAAA,EAAO;AAAA,EACd,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,EACf,WAAA,EAAa,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EACjC,QAAA,EAAU,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA;AACtB,CAAC;AAIM,IAAM,YAAA,GAAe,EAAE,MAAA,CAAO;AAAA,EACpC,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,EACf,WAAA,EAAa,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EACjC,WAAW,CAAA,CACT,KAAA;AAAA,IACA,EAAE,MAAA,CAAO;AAAA,MACR,IAAA,EAAM,EAAE,MAAA,EAAO;AAAA,MACf,WAAA,EAAa,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,MACjC,QAAA,EAAU,CAAA,CAAE,OAAA,EAAQ,CAAE,QAAA;AAAS,KAC/B;AAAA,IAED,QAAA;AACH,CAAC","file":"chunk-KR5UZUEY.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { McpRequest, McpResponse, ServerInfo } from \"../types.js\";\n\n/**\n * @mcp-legacy ENTIRE FILE — MCP 2025-era backward compatibility layer.\n * Remove this file when MCP v1 (2025-11-25) reaches EOL.\n *\n * SUNSET INSTRUCTION: Delete this file, then grep for \"@mcp-legacy\" in the\n * codebase to find and remove all remaining legacy seams.\n */\n\n/**\n * @mcp-legacy Master kill switch for MCP 2025-era backward compatibility.\n * Set to `false` when MCP v1 reaches End-of-Life (EOL) to disable all legacy seams.\n */\nexport const MCP_LEGACY_SUPPORT_ENABLED = true;\n\n/**\n * @mcp-legacy Legacy protocol version constant.\n */\nexport const MCP_PROTOCOL_VERSION_LEGACY = \"2025-11-25\" as const;\n\n/**\n * @mcp-legacy Build the legacy initialize handshake response.\n */\nexport function buildLegacyInitializeResponse(\n\tserverInfo: ServerInfo,\n\tid?: string | number | null,\n): McpResponse {\n\treturn {\n\t\tjsonrpc: \"2.0\",\n\t\tid: id ?? null,\n\t\tresult: {\n\t\t\tprotocolVersion: MCP_PROTOCOL_VERSION_LEGACY,\n\t\t\tcapabilities: {\n\t\t\t\ttools: { listChanged: true },\n\t\t\t\tresources: { listChanged: true },\n\t\t\t\tprompts: { listChanged: true },\n\t\t\t},\n\t\t\tserverInfo,\n\t\t},\n\t};\n}\n\n/**\n * @mcp-legacy Detect if a request is strictly from a 2025-era legacy client.\n * Legacy requests either invoke 'initialize', 'notifications/initialized',\n * or lack modern '_meta' protocol envelopes.\n */\nexport function isLegacyRequest(request: McpRequest): boolean {\n\tif (\n\t\trequest.method === \"initialize\" ||\n\t\trequest.method === \"notifications/initialized\"\n\t) {\n\t\treturn true;\n\t}\n\n\tconst params = request.params as Record<string, unknown> | undefined;\n\tconst meta = params?._meta as Record<string, unknown> | undefined;\n\tconst version = meta?.[\"io.modelcontextprotocol/protocolVersion\"];\n\n\tif (!version || version === MCP_PROTOCOL_VERSION_LEGACY) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n/**\n * @mcp-legacy Wrap and strip modern-era fields (resultType, ttlMs, cacheScope, etc.)\n * from a response to ensure 100% wire-compatibility with strict 2025 MCP clients.\n */\nexport function adaptResponseForLegacyClient(\n\tresponse: McpResponse,\n): McpResponse {\n\tif (!response.result || typeof response.result !== \"object\") {\n\t\treturn response;\n\t}\n\n\tconst rawResult = { ...(response.result as Record<string, unknown>) };\n\n\t// Strip modern-only envelope tags\n\tdelete rawResult.resultType;\n\tdelete rawResult.ttlMs;\n\tdelete rawResult.cacheScope;\n\n\treturn {\n\t\t...response,\n\t\tresult: rawResult,\n\t};\n}\n\n/**\n * Canonical tool aliases mapping legacy or shorthand tool names\n * to production enclave capabilities.\n */\nexport const TOOL_ALIASES: Record<string, string> = {\n\tbank_tool: \"Analyze_Synthetic_Bank_Transactions\",\n\tbank_tool_XDwd: \"Analyze_Synthetic_Bank_Transactions\",\n\tvault_tool: \"Analyze_Synthetic_Medical_Records\",\n\tvault_tool_E8wP: \"Analyze_Synthetic_Medical_Records\",\n\toracle_tool: \"Analyze_HFT_Market_Data\",\n\tcompute_aggregate: \"Analyze_Synthetic_Bank_Transactions\",\n};\n\n/**\n * Normalizes tool invocation parameters to satisfy dual parameter conventions.\n * If data is passed instead of payload or envelope, maps data to both fields.\n */\nexport function normalizeToolArguments(\n\targs?: Record<string, unknown>,\n): Record<string, unknown> {\n\tif (!args) return {};\n\tconst normalized = { ...args };\n\tif (normalized.data !== undefined) {\n\t\tif (normalized.payload === undefined) {\n\t\t\tnormalized.payload = normalized.data;\n\t\t}\n\t\tif (normalized.envelope === undefined) {\n\t\t\tnormalized.envelope = normalized.data;\n\t\t}\n\t}\n\treturn normalized;\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { z } from \"zod\";\n\n/**\n * Protocol Version Identifiers\n */\nexport const MCP_PROTOCOL_VERSION = \"2026-07-28\" as const;\n\nexport {\n\tMCP_LEGACY_SUPPORT_ENABLED,\n\tMCP_PROTOCOL_VERSION_LEGACY,\n} from \"./gateway/mcp-compat.js\";\n\n/**\n * Protocol Era Classification\n */\nexport type McpEra = \"legacy\" | \"modern\";\n\n/**\n * Caching Hints for MCP 2026-07-28 Spec\n */\nexport interface CacheableResult {\n\tttlMs?: number;\n\tcacheScope?: \"public\" | \"private\";\n}\n\n/**\n * Multi-Round-Trip Requests (MRTR) Specification Types\n */\nexport interface InputRequest {\n\tid: string;\n\tmessage: string;\n\tschema?: Record<string, unknown>;\n}\n\nexport interface InputResponse {\n\tid: string;\n\tvalue: unknown;\n}\n\nexport interface InputRequiredResult {\n\tresultType: \"input_required\";\n\tinputRequests: InputRequest[];\n\trequestState?: string;\n}\n\n/**\n * Modern Envelope Metadata (_meta)\n */\nexport interface McpRequestMeta {\n\t\"io.modelcontextprotocol/protocolVersion\"?: string;\n\t\"io.modelcontextprotocol/clientInfo\"?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\t\"io.modelcontextprotocol/clientCapabilities\"?: Record<string, unknown>;\n\t[key: string]: unknown;\n}\n\n/**\n * Base Protocol Types representing parity with Model Context Protocol\n */\n\nexport const ToolSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tinputSchema: z.record(z.string(), z.unknown()), // Represents a JSON Schema\n});\n\nexport type Tool = z.infer<typeof ToolSchema>;\n\nexport const ResourceSchema = z.object({\n\turi: z.string(),\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tmimeType: z.string().optional(),\n});\n\nexport type Resource = z.infer<typeof ResourceSchema>;\n\nexport const PromptSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\targuments: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string(),\n\t\t\t\tdescription: z.string().optional(),\n\t\t\t\trequired: z.boolean().optional(),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n});\n\nexport type Prompt = z.infer<typeof PromptSchema>;\n\nexport interface CallToolRequest {\n\tname: string;\n\targuments?: Record<string, unknown>;\n}\n\nexport interface CallToolResult {\n\tcontent: Array<{\n\t\ttype: \"text\" | \"image\" | \"resource\";\n\t\ttext?: string;\n\t\tdata?: string;\n\t\tmimeType?: string;\n\t\tresource?: {\n\t\t\turi: string;\n\t\t\ttext?: string;\n\t\t\tblob?: string;\n\t\t};\n\t}>;\n\tisError?: boolean;\n\tzkVerified?: boolean;\n\tzkProofType?: import(\"./security/zk.js\").ProofType;\n}\n\nexport interface GetPromptRequest {\n\tname: string;\n\targuments?: Record<string, string>;\n}\n\nexport interface GetPromptResult {\n\tdescription?: string;\n\tmessages: Array<{\n\t\trole: \"user\" | \"assistant\";\n\t\tcontent:\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| { type: \"image\"; data: string; mimeType: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"resource\";\n\t\t\t\t\tresource: { uri: string; text?: string; blob?: string };\n\t\t\t };\n\t}>;\n}\n\nexport interface ServerInfo {\n\tname: string;\n\tversion: string;\n\tcapabilities?: {\n\t\tprompts?: { listChanged?: boolean };\n\t\tresources?: { subscribe?: boolean; listChanged?: boolean };\n\t\ttools?: { listChanged?: boolean };\n\t\t/** @mcp-legacy @deprecated Deprecated in MCP 2026-07-28 spec */\n\t\tlogging?: Record<string, unknown>;\n\t};\n}\n\nexport interface DiscoverResult {\n\tresultType: \"complete\";\n\tsupportedVersions: string[];\n\tcapabilities: ServerInfo[\"capabilities\"];\n\tserverInfo: ServerInfo;\n\tinstructions?: string;\n}\n\nexport interface McpRequest {\n\tmethod: string;\n\tparams?: unknown;\n\tid?: string | number | null;\n\tjsonrpc?: \"2.0\";\n}\n\nexport interface McpResponse {\n\tjsonrpc: \"2.0\";\n\tid?: string | number | null;\n\tresult?: unknown;\n\terror?: {\n\t\tcode: number;\n\t\tmessage: string;\n\t\tdata?: unknown;\n\t};\n}\n\n/**\n * Re-export Gateway Interceptor types for consumer convenience.\n */\nexport type {\n\tGatewayAdmissionResult,\n\tGatewayInterceptor,\n\tGatewayInterceptorContext,\n\tGatewayInterceptorOptions,\n} from \"./gateway/interceptor.js\";\nexport type { AuditInterceptor } from \"./interceptors/audit-interceptor.js\";\n/**\n * Re-export Log & Audit Interceptor types for consumer convenience.\n */\nexport type {\n\tLogEvent,\n\tLogInterceptor,\n} from \"./interceptors/log-interceptor.js\";\n/**\n * Re-export AuthInfo from the security module for convenience.\n * Compatible with MCP TypeScript SDK AuthInfo interface shape.\n */\nexport type { AuthInfo } from \"./security/jwt-validator.js\";\nexport type {\n\tZkJournalV2,\n\tZkPolicy,\n\tZkReceipt,\n} from \"./security/zk.js\";\n/**\n * Re-export Zero-Knowledge Proof & Verification types for consumer convenience.\n */\nexport {\n\tProofType,\n\tRECEIPT_VERSION_V1,\n\tRECEIPT_VERSION_V2,\n\tZK_JOURNAL_V2_SIZE,\n} from \"./security/zk.js\";\n"]}
@@ -0,0 +1,58 @@
1
+ import { ZkVerificationError } from './chunk-P34HDRN5.js';
2
+ import { bn254, stringBigints } from 'micro-zk-proofs';
3
+
4
+ var VERIFICATION_LATENCY_BUDGET_MS = 250;
5
+ function verifyGroth16Proof(vkey, proofWithSignals) {
6
+ if (!vkey || !proofWithSignals?.proof) {
7
+ return false;
8
+ }
9
+ try {
10
+ return bn254.groth.verifyProof(vkey, proofWithSignals);
11
+ } catch (_error) {
12
+ return false;
13
+ }
14
+ }
15
+ function serializeVKey(vkey) {
16
+ try {
17
+ const encoded = stringBigints.encode(vkey);
18
+ return Buffer.from(JSON.stringify(encoded), "utf-8");
19
+ } catch (error) {
20
+ throw new ZkVerificationError(
21
+ `Failed to serialize VerificationKey: ${error instanceof Error ? error.message : String(error)}`
22
+ );
23
+ }
24
+ }
25
+ function deserializeVKey(buf) {
26
+ try {
27
+ const parsed = JSON.parse(buf.toString("utf-8"));
28
+ return stringBigints.decode(parsed);
29
+ } catch (error) {
30
+ throw new ZkVerificationError(
31
+ `Failed to deserialize VerificationKey: ${error instanceof Error ? error.message : String(error)}`
32
+ );
33
+ }
34
+ }
35
+ function serializeGrothProof(proofWithSignals) {
36
+ try {
37
+ const encoded = stringBigints.encode(proofWithSignals);
38
+ return Buffer.from(JSON.stringify(encoded), "utf-8");
39
+ } catch (error) {
40
+ throw new ZkVerificationError(
41
+ `Failed to serialize GrothProof: ${error instanceof Error ? error.message : String(error)}`
42
+ );
43
+ }
44
+ }
45
+ function deserializeGrothProof(buf) {
46
+ try {
47
+ const parsed = JSON.parse(buf.toString("utf-8"));
48
+ return stringBigints.decode(parsed);
49
+ } catch (error) {
50
+ throw new ZkVerificationError(
51
+ `Failed to deserialize GrothProof: ${error instanceof Error ? error.message : String(error)}`
52
+ );
53
+ }
54
+ }
55
+
56
+ export { VERIFICATION_LATENCY_BUDGET_MS, deserializeGrothProof, deserializeVKey, serializeGrothProof, serializeVKey, verifyGroth16Proof };
57
+ //# sourceMappingURL=chunk-OHMZZMMC.js.map
58
+ //# sourceMappingURL=chunk-OHMZZMMC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crypto/groth16-verifier.ts"],"names":[],"mappings":";;;AAWO,IAAM,8BAAA,GAAiC;AAQvC,SAAS,kBAAA,CACf,MACA,gBAAA,EACU;AACV,EAAA,IAAI,CAAC,IAAA,IAAQ,CAAC,gBAAA,EAAkB,KAAA,EAAO;AACtC,IAAA,OAAO,KAAA;AAAA,EACR;AAEA,EAAA,IAAI;AACH,IAAA,OAAO,KAAA,CAAM,KAAA,CAAM,WAAA,CAAY,IAAA,EAAM,gBAAgB,CAAA;AAAA,EACtD,SAAS,MAAA,EAAQ;AAEhB,IAAA,OAAO,KAAA;AAAA,EACR;AACD;AAKO,SAAS,cAAc,IAAA,EAA+B;AAC5D,EAAA,IAAI;AACH,IAAA,MAAM,OAAA,GAAU,aAAA,CAAc,MAAA,CAAO,IAAI,CAAA;AACzC,IAAA,OAAO,OAAO,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,OAAO,GAAG,OAAO,CAAA;AAAA,EACpD,SAAS,KAAA,EAAO;AACf,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,wCAAwC,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,KAC/F;AAAA,EACD;AACD;AAKO,SAAS,gBAAgB,GAAA,EAA8B;AAC7D,EAAA,IAAI;AACH,IAAA,MAAM,SAAS,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,QAAA,CAAS,OAAO,CAAC,CAAA;AAC/C,IAAA,OAAO,aAAA,CAAc,OAAO,MAAM,CAAA;AAAA,EACnC,SAAS,KAAA,EAAO;AACf,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,0CAA0C,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,KACjG;AAAA,EACD;AACD;AAKO,SAAS,oBACf,gBAAA,EACS;AACT,EAAA,IAAI;AACH,IAAA,MAAM,OAAA,GAAU,aAAA,CAAc,MAAA,CAAO,gBAAgB,CAAA;AACrD,IAAA,OAAO,OAAO,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,OAAO,GAAG,OAAO,CAAA;AAAA,EACpD,SAAS,KAAA,EAAO;AACf,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,mCAAmC,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,KAC1F;AAAA,EACD;AACD;AAKO,SAAS,sBAAsB,GAAA,EAA+B;AACpE,EAAA,IAAI;AACH,IAAA,MAAM,SAAS,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,QAAA,CAAS,OAAO,CAAC,CAAA;AAC/C,IAAA,OAAO,aAAA,CAAc,OAAO,MAAM,CAAA;AAAA,EACnC,SAAS,KAAA,EAAO;AACf,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,qCAAqC,KAAA,YAAiB,KAAA,GAAQ,MAAM,OAAA,GAAU,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,KAC5F;AAAA,EACD;AACD","file":"chunk-OHMZZMMC.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n\tbn254,\n\ttype ProofWithSignals,\n\tstringBigints,\n\ttype VerificationKey,\n} from \"micro-zk-proofs\";\nimport { ZkVerificationError } from \"../security/zk.js\";\n\nexport const VERIFICATION_LATENCY_BUDGET_MS = 250;\n\nexport type { ProofWithSignals, VerificationKey };\n\n/**\n * Verifies a Groth16 Zero-Knowledge proof against a verification key.\n * Traps curve validation errors gracefully to ensure safe verification.\n */\nexport function verifyGroth16Proof(\n\tvkey: VerificationKey,\n\tproofWithSignals: ProofWithSignals,\n): boolean {\n\tif (!vkey || !proofWithSignals?.proof) {\n\t\treturn false;\n\t}\n\n\ttry {\n\t\treturn bn254.groth.verifyProof(vkey, proofWithSignals);\n\t} catch (_error) {\n\t\t// Curve point validation or pairing failure (e.g. invalid curve point, subgroup violation)\n\t\treturn false;\n\t}\n}\n\n/**\n * Serializes a VerificationKey into a Buffer.\n */\nexport function serializeVKey(vkey: VerificationKey): Buffer {\n\ttry {\n\t\tconst encoded = stringBigints.encode(vkey);\n\t\treturn Buffer.from(JSON.stringify(encoded), \"utf-8\");\n\t} catch (error) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Failed to serialize VerificationKey: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n}\n\n/**\n * Deserializes a Buffer into a typed VerificationKey.\n */\nexport function deserializeVKey(buf: Buffer): VerificationKey {\n\ttry {\n\t\tconst parsed = JSON.parse(buf.toString(\"utf-8\"));\n\t\treturn stringBigints.decode(parsed) as VerificationKey;\n\t} catch (error) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Failed to deserialize VerificationKey: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n}\n\n/**\n * Serializes a ProofWithSignals into a Buffer.\n */\nexport function serializeGrothProof(\n\tproofWithSignals: ProofWithSignals,\n): Buffer {\n\ttry {\n\t\tconst encoded = stringBigints.encode(proofWithSignals);\n\t\treturn Buffer.from(JSON.stringify(encoded), \"utf-8\");\n\t} catch (error) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Failed to serialize GrothProof: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n}\n\n/**\n * Deserializes a Buffer into a typed ProofWithSignals.\n */\nexport function deserializeGrothProof(buf: Buffer): ProofWithSignals {\n\ttry {\n\t\tconst parsed = JSON.parse(buf.toString(\"utf-8\"));\n\t\treturn stringBigints.decode(parsed) as ProofWithSignals;\n\t} catch (error) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Failed to deserialize GrothProof: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n}\n"]}
@@ -0,0 +1,213 @@
1
+ import crypto from 'crypto';
2
+
3
+ // src/security/zk.ts
4
+ var ProofType = /* @__PURE__ */ ((ProofType2) => {
5
+ ProofType2[ProofType2["HMAC_LEGACY"] = 0] = "HMAC_LEGACY";
6
+ ProofType2[ProofType2["GROTH16"] = 2] = "GROTH16";
7
+ return ProofType2;
8
+ })(ProofType || {});
9
+ var RECEIPT_VERSION_V1 = 1;
10
+ var RECEIPT_VERSION_V2 = 2;
11
+ var ZK_JOURNAL_V2_SIZE = 144;
12
+ var ZkVerificationError = class extends Error {
13
+ constructor(message) {
14
+ super(`ZK Verification Failed: ${message}`);
15
+ this.name = "ZkVerificationError";
16
+ }
17
+ };
18
+ function encodeJournalV2(fields) {
19
+ if (fields.guestImageId.length !== 32) {
20
+ throw new ZkVerificationError(
21
+ `Invalid guestImageId size: expected 32 bytes, got ${fields.guestImageId.length}`
22
+ );
23
+ }
24
+ if (fields.logicDigest.length !== 32) {
25
+ throw new ZkVerificationError(
26
+ `Invalid logicDigest size: expected 32 bytes, got ${fields.logicDigest.length}`
27
+ );
28
+ }
29
+ if (fields.datasetDigest.length !== 32) {
30
+ throw new ZkVerificationError(
31
+ `Invalid datasetDigest size: expected 32 bytes, got ${fields.datasetDigest.length}`
32
+ );
33
+ }
34
+ if (fields.outputDigest.length !== 32) {
35
+ throw new ZkVerificationError(
36
+ `Invalid outputDigest size: expected 32 bytes, got ${fields.outputDigest.length}`
37
+ );
38
+ }
39
+ const buf = Buffer.alloc(ZK_JOURNAL_V2_SIZE);
40
+ fields.guestImageId.copy(buf, 0);
41
+ fields.logicDigest.copy(buf, 32);
42
+ fields.datasetDigest.copy(buf, 64);
43
+ fields.outputDigest.copy(buf, 96);
44
+ buf.writeBigUInt64BE(BigInt(fields.fuelConsumed), 128);
45
+ buf.writeBigUInt64BE(BigInt(fields.executionTimestamp), 136);
46
+ return buf;
47
+ }
48
+ function decodeJournalV2(buf) {
49
+ if (buf.length !== ZK_JOURNAL_V2_SIZE) {
50
+ throw new ZkVerificationError(
51
+ `Invalid ZkJournalV2 size: expected ${ZK_JOURNAL_V2_SIZE} bytes, got ${buf.length}`
52
+ );
53
+ }
54
+ return {
55
+ guestImageId: Buffer.from(buf.subarray(0, 32)),
56
+ logicDigest: Buffer.from(buf.subarray(32, 64)),
57
+ datasetDigest: Buffer.from(buf.subarray(64, 96)),
58
+ outputDigest: Buffer.from(buf.subarray(96, 128)),
59
+ fuelConsumed: buf.readBigUInt64BE(128),
60
+ executionTimestamp: buf.readBigUInt64BE(136)
61
+ };
62
+ }
63
+ var receiptCodec = {
64
+ /**
65
+ * Encodes a version 2 Binary Receipt with trailing SHA-256 checksum.
66
+ * Layout: [0x02][proofType: 1B][journalLen: 4B UInt32BE][journal][proof][checksum: 32B]
67
+ */
68
+ encodeV2(proofType, journal, proof) {
69
+ const header = Buffer.alloc(6);
70
+ header.writeUInt8(RECEIPT_VERSION_V2, 0);
71
+ header.writeUInt8(proofType, 1);
72
+ header.writeUInt32BE(journal.length, 2);
73
+ const payload = Buffer.concat([header, journal, proof]);
74
+ const checksum = crypto.createHash("sha256").update(payload).digest();
75
+ return Buffer.concat([payload, checksum]);
76
+ },
77
+ /**
78
+ * Decodes any LIOP Binary Receipt (v1 HMAC or v2 ZK).
79
+ */
80
+ decode(raw) {
81
+ if (!raw || raw.length === 0) {
82
+ throw new ZkVerificationError(
83
+ "Empty or malformed zero-knowledge proof array."
84
+ );
85
+ }
86
+ const version = raw[0];
87
+ if (version === RECEIPT_VERSION_V1) {
88
+ if (raw.length < 35) {
89
+ throw new ZkVerificationError(
90
+ "Malformed receipt: invalid header or length."
91
+ );
92
+ }
93
+ const journalLen = raw.readUInt16BE(1);
94
+ if (raw.length < 3 + journalLen + 32) {
95
+ throw new ZkVerificationError(
96
+ "Malformed receipt: truncated journal or seal."
97
+ );
98
+ }
99
+ const journal = Buffer.from(raw.subarray(3, 3 + journalLen));
100
+ const seal = Buffer.from(
101
+ raw.subarray(3 + journalLen, 3 + journalLen + 32)
102
+ );
103
+ return {
104
+ version: RECEIPT_VERSION_V1,
105
+ proofType: 0 /* HMAC_LEGACY */,
106
+ journal,
107
+ proof: seal,
108
+ raw
109
+ };
110
+ }
111
+ if (version === RECEIPT_VERSION_V2) {
112
+ if (raw.length < 38) {
113
+ throw new ZkVerificationError(
114
+ "Malformed receipt v2: buffer too short (< 38 bytes)."
115
+ );
116
+ }
117
+ const proofType = raw[1];
118
+ const journalLen = raw.readUInt32BE(2);
119
+ if (raw.length < 6 + journalLen + 32) {
120
+ throw new ZkVerificationError(
121
+ "Malformed receipt v2: truncated payload."
122
+ );
123
+ }
124
+ const payload = raw.subarray(0, raw.length - 32);
125
+ const expectedChecksum = raw.subarray(raw.length - 32);
126
+ const actualChecksum = crypto.createHash("sha256").update(payload).digest();
127
+ if (!crypto.timingSafeEqual(expectedChecksum, actualChecksum)) {
128
+ throw new ZkVerificationError("Receipt checksum verification failed.");
129
+ }
130
+ const journal = Buffer.from(raw.subarray(6, 6 + journalLen));
131
+ const proof = Buffer.from(raw.subarray(6 + journalLen, raw.length - 32));
132
+ return {
133
+ version: RECEIPT_VERSION_V2,
134
+ proofType,
135
+ journal,
136
+ proof,
137
+ raw
138
+ };
139
+ }
140
+ throw new ZkVerificationError(
141
+ `Unsupported receipt version: 0x${version.toString(16)}`
142
+ );
143
+ }
144
+ };
145
+ var ZkVerifier = {
146
+ /**
147
+ * Validates a ZK receipt using structural Binary Receipt verification.
148
+ * Parses the HMAC-SHA256 commitment format (v1) and verifies journal integrity.
149
+ *
150
+ * @param receipt - Complete ZkReceipt to verify
151
+ * @param expectedImageId - Hash or ImageID of the WASM file dispatched to the host
152
+ * @throws ZkVerificationError if the proof is invalid or image IDs mismatch
153
+ * @returns true if the proof mathematically verifies the execution
154
+ */
155
+ verify(receipt, expectedImageId, sessionSecret) {
156
+ if (!receipt.imageId.equals(expectedImageId)) {
157
+ throw new ZkVerificationError(
158
+ "ImageID mismatch. The remote origin executed a different WASM payload."
159
+ );
160
+ }
161
+ if (receipt.proof.length === 0) {
162
+ throw new ZkVerificationError(
163
+ "Empty or malformed zero-knowledge proof array."
164
+ );
165
+ }
166
+ const proofBuf = Buffer.from(receipt.proof);
167
+ if (proofBuf.length < 35 || proofBuf[0] !== 1) {
168
+ throw new ZkVerificationError(
169
+ "Malformed receipt: invalid header or length."
170
+ );
171
+ }
172
+ const journalLen = proofBuf.readUInt16BE(1);
173
+ const journal = proofBuf.subarray(3, 3 + journalLen);
174
+ const seal = proofBuf.subarray(3 + journalLen);
175
+ if (seal.length !== 32) {
176
+ throw new ZkVerificationError(
177
+ "Invalid seal: expected 32-byte HMAC-SHA256."
178
+ );
179
+ }
180
+ try {
181
+ const journalData = JSON.parse(journal.toString());
182
+ if (journalData.image_id !== receipt.imageId.toString("hex")) {
183
+ throw new ZkVerificationError(
184
+ "Journal imageId does not match receipt header."
185
+ );
186
+ }
187
+ } catch (_e) {
188
+ throw new ZkVerificationError("Failed to parse journal data.");
189
+ }
190
+ if (sessionSecret && sessionSecret.length > 0) {
191
+ const expectedSeal = crypto.createHmac("sha256", sessionSecret).update(journal).digest();
192
+ if (!crypto.timingSafeEqual(seal, expectedSeal)) {
193
+ throw new ZkVerificationError(
194
+ "Invalid seal: HMAC verification failed."
195
+ );
196
+ }
197
+ }
198
+ return true;
199
+ },
200
+ /**
201
+ * Derives a predictable ImageID (usually a Hash) from a raw WASM binary.
202
+ *
203
+ * @param wasmBytes - The raw bytes of the WASM logic file
204
+ * @returns The SHA-256 ImageID of the logic
205
+ */
206
+ deriveImageId(wasmBytes) {
207
+ return crypto.createHash("sha256").update(wasmBytes).digest();
208
+ }
209
+ };
210
+
211
+ export { ProofType, RECEIPT_VERSION_V1, RECEIPT_VERSION_V2, ZK_JOURNAL_V2_SIZE, ZkVerificationError, ZkVerifier, decodeJournalV2, encodeJournalV2, receiptCodec };
212
+ //# sourceMappingURL=chunk-P34HDRN5.js.map
213
+ //# sourceMappingURL=chunk-P34HDRN5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/zk.ts"],"names":["ProofType"],"mappings":";;;AAKO,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AACN,EAAAA,UAAAA,CAAAA,UAAAA,CAAA,iBAAc,CAAA,CAAA,GAAd,aAAA;AACA,EAAAA,UAAAA,CAAAA,UAAAA,CAAA,aAAU,CAAA,CAAA,GAAV,SAAA;AAFW,EAAA,OAAAA,UAAAA;AAAA,CAAA,EAAA,SAAA,IAAA,EAAA;AAKL,IAAM,kBAAA,GAAqB;AAC3B,IAAM,kBAAA,GAAqB;AAC3B,IAAM,kBAAA,GAAqB;AAgC3B,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC5B,IAAA,KAAA,CAAM,CAAA,wBAAA,EAA2B,OAAO,CAAA,CAAE,CAAA;AAC1C,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACb;AACD;AAKO,SAAS,gBAAgB,MAAA,EAA6B;AAC5D,EAAA,IAAI,MAAA,CAAO,YAAA,CAAa,MAAA,KAAW,EAAA,EAAI;AACtC,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,CAAA,kDAAA,EAAqD,MAAA,CAAO,YAAA,CAAa,MAAM,CAAA;AAAA,KAChF;AAAA,EACD;AACA,EAAA,IAAI,MAAA,CAAO,WAAA,CAAY,MAAA,KAAW,EAAA,EAAI;AACrC,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,CAAA,iDAAA,EAAoD,MAAA,CAAO,WAAA,CAAY,MAAM,CAAA;AAAA,KAC9E;AAAA,EACD;AACA,EAAA,IAAI,MAAA,CAAO,aAAA,CAAc,MAAA,KAAW,EAAA,EAAI;AACvC,IAAA,MAAM,IAAI,mBAAA;AAAA,MACT,CAAA,mDAAA,EAAs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AAA;AAAA,UACT;AAAA,SACD;AAAA,MACD;AAAA,IACD;AAEA,IAAA,OAAO,IAAA;AAAA,EACR,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,cAAc,SAAA,EAA2B;AACxC,IAAA,OAAO,OAAO,UAAA,CAAW,QAAQ,EAAE,MAAA,CAAO,SAAS,EAAE,MAAA,EAAO;AAAA,EAC7D;AACD","file":"chunk-P34HDRN5.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport crypto from \"node:crypto\";\n\nexport enum ProofType {\n\tHMAC_LEGACY = 0x00,\n\tGROTH16 = 0x02,\n}\n\nexport const RECEIPT_VERSION_V1 = 0x01;\nexport const RECEIPT_VERSION_V2 = 0x02;\nexport const ZK_JOURNAL_V2_SIZE = 144;\n\nexport interface ZkJournalV2 {\n\t/** Image ID (SHA-256) of the guest interpreter */\n\tguestImageId: Buffer;\n\t/** SHA-256 digest of injected logic */\n\tlogicDigest: Buffer;\n\t/** SHA-256 digest of dataset records */\n\tdatasetDigest: Buffer;\n\t/** SHA-256 digest of sanitized output */\n\toutputDigest: Buffer;\n\t/** Micro-instruction fuel consumed */\n\tfuelConsumed: bigint;\n\t/** Timestamp in milliseconds since unix epoch */\n\texecutionTimestamp: bigint;\n}\n\nexport type ZkPolicy = \"none\" | \"optimistic\" | \"required\";\n\nexport interface ZkReceipt {\n\t/** Cryptographic proof generated by a zero-knowledge VM (e.g., RISC Zero, SP1) or Groth16 */\n\tproof: Buffer;\n\t/** The public inputs/outputs of the execution (the \"Journal\" in RISC Zero terminology) */\n\tjournal: Buffer;\n\t/** The expected image ID / verification key of the WASM binary that was executed */\n\timageId: Buffer;\n\t/** Type of cryptographic proof (HMAC legacy or Groth16) */\n\tproofType?: ProofType;\n\t/** Binary receipt version (0x01 or 0x02) */\n\tversion?: number;\n}\n\nexport class ZkVerificationError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`ZK Verification Failed: ${message}`);\n\t\tthis.name = \"ZkVerificationError\";\n\t}\n}\n\n/**\n * Serializes a structured ZkJournalV2 into a strictly validated 144-byte binary layout.\n */\nexport function encodeJournalV2(fields: ZkJournalV2): Buffer {\n\tif (fields.guestImageId.length !== 32) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Invalid guestImageId size: expected 32 bytes, got ${fields.guestImageId.length}`,\n\t\t);\n\t}\n\tif (fields.logicDigest.length !== 32) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Invalid logicDigest size: expected 32 bytes, got ${fields.logicDigest.length}`,\n\t\t);\n\t}\n\tif (fields.datasetDigest.length !== 32) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Invalid datasetDigest size: expected 32 bytes, got ${fields.datasetDigest.length}`,\n\t\t);\n\t}\n\tif (fields.outputDigest.length !== 32) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Invalid outputDigest size: expected 32 bytes, got ${fields.outputDigest.length}`,\n\t\t);\n\t}\n\n\tconst buf = Buffer.alloc(ZK_JOURNAL_V2_SIZE);\n\tfields.guestImageId.copy(buf, 0);\n\tfields.logicDigest.copy(buf, 32);\n\tfields.datasetDigest.copy(buf, 64);\n\tfields.outputDigest.copy(buf, 96);\n\tbuf.writeBigUInt64BE(BigInt(fields.fuelConsumed), 128);\n\tbuf.writeBigUInt64BE(BigInt(fields.executionTimestamp), 136);\n\n\treturn buf;\n}\n\n/**\n * Deserializes and validates a 144-byte binary buffer into a typed ZkJournalV2.\n */\nexport function decodeJournalV2(buf: Buffer): ZkJournalV2 {\n\tif (buf.length !== ZK_JOURNAL_V2_SIZE) {\n\t\tthrow new ZkVerificationError(\n\t\t\t`Invalid ZkJournalV2 size: expected ${ZK_JOURNAL_V2_SIZE} bytes, got ${buf.length}`,\n\t\t);\n\t}\n\n\treturn {\n\t\tguestImageId: Buffer.from(buf.subarray(0, 32)),\n\t\tlogicDigest: Buffer.from(buf.subarray(32, 64)),\n\t\tdatasetDigest: Buffer.from(buf.subarray(64, 96)),\n\t\toutputDigest: Buffer.from(buf.subarray(96, 128)),\n\t\tfuelConsumed: buf.readBigUInt64BE(128),\n\t\texecutionTimestamp: buf.readBigUInt64BE(136),\n\t};\n}\n\nexport interface DecodedReceipt {\n\tversion: number;\n\tproofType: ProofType;\n\tjournal: Buffer;\n\tproof: Buffer;\n\traw: Buffer;\n}\n\nexport const receiptCodec = {\n\t/**\n\t * Encodes a version 2 Binary Receipt with trailing SHA-256 checksum.\n\t * Layout: [0x02][proofType: 1B][journalLen: 4B UInt32BE][journal][proof][checksum: 32B]\n\t */\n\tencodeV2(proofType: ProofType, journal: Buffer, proof: Buffer): Buffer {\n\t\tconst header = Buffer.alloc(6);\n\t\theader.writeUInt8(RECEIPT_VERSION_V2, 0);\n\t\theader.writeUInt8(proofType, 1);\n\t\theader.writeUInt32BE(journal.length, 2);\n\n\t\tconst payload = Buffer.concat([header, journal, proof]);\n\t\tconst checksum = crypto.createHash(\"sha256\").update(payload).digest();\n\n\t\treturn Buffer.concat([payload, checksum]);\n\t},\n\n\t/**\n\t * Decodes any LIOP Binary Receipt (v1 HMAC or v2 ZK).\n\t */\n\tdecode(raw: Buffer): DecodedReceipt {\n\t\tif (!raw || raw.length === 0) {\n\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\"Empty or malformed zero-knowledge proof array.\",\n\t\t\t);\n\t\t}\n\n\t\tconst version = raw[0];\n\n\t\tif (version === RECEIPT_VERSION_V1) {\n\t\t\tif (raw.length < 35) {\n\t\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\t\"Malformed receipt: invalid header or length.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst journalLen = raw.readUInt16BE(1);\n\t\t\tif (raw.length < 3 + journalLen + 32) {\n\t\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\t\"Malformed receipt: truncated journal or seal.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst journal = Buffer.from(raw.subarray(3, 3 + journalLen));\n\t\t\tconst seal = Buffer.from(\n\t\t\t\traw.subarray(3 + journalLen, 3 + journalLen + 32),\n\t\t\t);\n\n\t\t\treturn {\n\t\t\t\tversion: RECEIPT_VERSION_V1,\n\t\t\t\tproofType: ProofType.HMAC_LEGACY,\n\t\t\t\tjournal,\n\t\t\t\tproof: seal,\n\t\t\t\traw,\n\t\t\t};\n\t\t}\n\n\t\tif (version === RECEIPT_VERSION_V2) {\n\t\t\t// Minimum size: 1 (version) + 1 (proofType) + 4 (journalLen) + 0 (journal) + 0 (proof) + 32 (checksum) = 38\n\t\t\tif (raw.length < 38) {\n\t\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\t\"Malformed receipt v2: buffer too short (< 38 bytes).\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst proofType = raw[1] as ProofType;\n\t\t\tconst journalLen = raw.readUInt32BE(2);\n\n\t\t\tif (raw.length < 6 + journalLen + 32) {\n\t\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\t\"Malformed receipt v2: truncated payload.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst payload = raw.subarray(0, raw.length - 32);\n\t\t\tconst expectedChecksum = raw.subarray(raw.length - 32);\n\t\t\tconst actualChecksum = crypto\n\t\t\t\t.createHash(\"sha256\")\n\t\t\t\t.update(payload)\n\t\t\t\t.digest();\n\n\t\t\tif (!crypto.timingSafeEqual(expectedChecksum, actualChecksum)) {\n\t\t\t\tthrow new ZkVerificationError(\"Receipt checksum verification failed.\");\n\t\t\t}\n\n\t\t\tconst journal = Buffer.from(raw.subarray(6, 6 + journalLen));\n\t\t\tconst proof = Buffer.from(raw.subarray(6 + journalLen, raw.length - 32));\n\n\t\t\treturn {\n\t\t\t\tversion: RECEIPT_VERSION_V2,\n\t\t\t\tproofType,\n\t\t\t\tjournal,\n\t\t\t\tproof,\n\t\t\t\traw,\n\t\t\t};\n\t\t}\n\n\t\tthrow new ZkVerificationError(\n\t\t\t`Unsupported receipt version: 0x${version.toString(16)}`,\n\t\t);\n\t},\n};\n\n/**\n * ZK-Proofs Verifier for Logic-Injection-on-Origin Protocol (LIOP)\n *\n * Validates that an executed Logic (WASM) actually produced the reported output,\n * verifying the Zero-Knowledge receipt generated by the remote host's Trusted Execution\n * Environment (TEE) or zkVM (Zero-Knowledge Virtual Machine).\n */\nexport const ZkVerifier = {\n\t/**\n\t * Validates a ZK receipt using structural Binary Receipt verification.\n\t * Parses the HMAC-SHA256 commitment format (v1) and verifies journal integrity.\n\t *\n\t * @param receipt - Complete ZkReceipt to verify\n\t * @param expectedImageId - Hash or ImageID of the WASM file dispatched to the host\n\t * @throws ZkVerificationError if the proof is invalid or image IDs mismatch\n\t * @returns true if the proof mathematically verifies the execution\n\t */\n\tverify(\n\t\treceipt: ZkReceipt,\n\t\texpectedImageId: Buffer,\n\t\tsessionSecret?: Buffer,\n\t): boolean {\n\t\t// 1. Verify Image ID (Ensures the host executed the exact logic we sent, not a malicious one)\n\t\tif (!receipt.imageId.equals(expectedImageId)) {\n\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\"ImageID mismatch. The remote origin executed a different WASM payload.\",\n\t\t\t);\n\t\t}\n\n\t\t// 2. Validate Proof Structure\n\t\tif (receipt.proof.length === 0) {\n\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\"Empty or malformed zero-knowledge proof array.\",\n\t\t\t);\n\t\t}\n\n\t\t// 3. Cryptographic Validation (Binary Receipt)\n\t\tconst proofBuf = Buffer.from(receipt.proof);\n\t\tif (proofBuf.length < 35 || proofBuf[0] !== 0x01) {\n\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\"Malformed receipt: invalid header or length.\",\n\t\t\t);\n\t\t}\n\t\tconst journalLen = proofBuf.readUInt16BE(1);\n\t\tconst journal = proofBuf.subarray(3, 3 + journalLen);\n\t\tconst seal = proofBuf.subarray(3 + journalLen);\n\n\t\tif (seal.length !== 32) {\n\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\"Invalid seal: expected 32-byte HMAC-SHA256.\",\n\t\t\t);\n\t\t}\n\n\t\t// Verify journal contains matching imageId\n\t\ttry {\n\t\t\tconst journalData = JSON.parse(journal.toString());\n\t\t\tif (journalData.image_id !== receipt.imageId.toString(\"hex\")) {\n\t\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\t\"Journal imageId does not match receipt header.\",\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (_e) {\n\t\t\tthrow new ZkVerificationError(\"Failed to parse journal data.\");\n\t\t}\n\n\t\t// 4. Mathematical Verification (HMAC-SHA256)\n\t\tif (sessionSecret && sessionSecret.length > 0) {\n\t\t\tconst expectedSeal = crypto\n\t\t\t\t.createHmac(\"sha256\", sessionSecret)\n\t\t\t\t.update(journal)\n\t\t\t\t.digest();\n\t\t\tif (!crypto.timingSafeEqual(seal, expectedSeal)) {\n\t\t\t\tthrow new ZkVerificationError(\n\t\t\t\t\t\"Invalid seal: HMAC verification failed.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t},\n\n\t/**\n\t * Derives a predictable ImageID (usually a Hash) from a raw WASM binary.\n\t *\n\t * @param wasmBytes - The raw bytes of the WASM logic file\n\t * @returns The SHA-256 ImageID of the logic\n\t */\n\tderiveImageId(wasmBytes: Buffer): Buffer {\n\t\treturn crypto.createHash(\"sha256\").update(wasmBytes).digest();\n\t},\n};\n"]}
@@ -286,12 +286,25 @@ var egressBlocksTotal = protocolMetrics.counter(
286
286
  var zkVerificationDurationMs = protocolMetrics.histogram(
287
287
  "liop_zk_verification_duration_ms",
288
288
  "Duration of ZK-Receipt and HMAC cryptographic attestation in ms",
289
- [1, 2, 5, 10, 25, 50, 100]
289
+ [1, 2, 5, 10, 25, 50, 100, 250, 500]
290
290
  );
291
291
  var zkVerificationsTotal = protocolMetrics.counter(
292
292
  "liop_zk_verifications_total",
293
293
  "Total number of ZK-Receipt cryptographic attestation checks"
294
294
  );
295
+ var zkProofsByTypeTotal = protocolMetrics.counter(
296
+ "liop_zk_proofs_by_type_total",
297
+ "Total number of verified ZK receipts partitioned by proof type (groth16, hmac)"
298
+ );
299
+ var zkProvingDurationMs = protocolMetrics.histogram(
300
+ "liop_zk_proving_duration_ms",
301
+ "Duration of native ZK proof generation in ms",
302
+ [10, 25, 50, 100, 250, 500, 1e3, 2500]
303
+ );
304
+ var zkVkeyCacheSize = protocolMetrics.gauge(
305
+ "liop_zk_vkey_cache_size",
306
+ "Number of registered verification keys in memory cache"
307
+ );
295
308
  var tokensInputTotal = protocolMetrics.counter(
296
309
  "liop_tokens_input_total",
297
310
  "Total BPE input tokens processed by LIOP"
@@ -327,6 +340,6 @@ var wireSavedBytesTotal = protocolMetrics.counter(
327
340
  "Estimated wire egress bytes saved compared to MCP context extraction baseline"
328
341
  );
329
342
 
330
- export { Counter, Gauge, Histogram, MetricsRegistry, egressBlocksTotal, fuelConsumed, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, protocolMetrics, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, wireEgressBytesTotal, wireSavedBytesTotal, zkVerificationDurationMs, zkVerificationsTotal };
331
- //# sourceMappingURL=chunk-PAICJCKJ.js.map
332
- //# sourceMappingURL=chunk-PAICJCKJ.js.map
343
+ export { Counter, Gauge, Histogram, MetricsRegistry, egressBlocksTotal, fuelConsumed, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, protocolMetrics, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, wireEgressBytesTotal, wireSavedBytesTotal, zkProofsByTypeTotal, zkProvingDurationMs, zkVerificationDurationMs, zkVerificationsTotal, zkVkeyCacheSize };
344
+ //# sourceMappingURL=chunk-Q3FKHJ3B.js.map
345
+ //# sourceMappingURL=chunk-Q3FKHJ3B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/observability/metrics.ts"],"names":[],"mappings":";AAkBA,SAAS,a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,6BAAA;AAAA,EACA;AACD","file":"chunk-Q3FKHJ3B.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Prometheus Metrics Registry (Phase Beta-3)\n * Lightweight, zero-dependency, high-performance metrics collector\n * complying with Prometheus and OpenMetrics exposition format.\n */\n\nexport type MetricLabels = Record<string, string | number>;\n\nexport interface MetricDefinition {\n\tname: string;\n\thelp: string;\n\ttype: \"counter\" | \"gauge\" | \"histogram\";\n\tbuckets?: number[];\n}\n\nfunction formatLabels(labels?: MetricLabels): string {\n\tif (!labels || Object.keys(labels).length === 0) {\n\t\treturn \"\";\n\t}\n\tconst entries = Object.entries(labels)\n\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t.map(([k, v]) => `${k}=\"${String(v).replace(/\"/g, '\\\\\"')}\"`);\n\treturn `{${entries.join(\",\")}}`;\n}\n\nfunction labelsToKey(labels?: MetricLabels): string {\n\tif (!labels) return \"\";\n\treturn Object.entries(labels)\n\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t.map(([k, v]) => `${k}:${v}`)\n\t\t.join(\"|\");\n}\n\nexport class Counter {\n\tprivate values = new Map<string, { value: number; labels?: MetricLabels }>();\n\n\tconstructor(\n\t\tpublic readonly name: string,\n\t\tpublic readonly help: string,\n\t) {}\n\n\tinc(labels?: MetricLabels, value = 1): void {\n\t\tif (value < 0) {\n\t\t\tthrow new Error(\"Counter increments must be non-negative\");\n\t\t}\n\t\tconst key = labelsToKey(labels);\n\t\tconst current = this.values.get(key) || { value: 0, labels };\n\t\tcurrent.value += value;\n\t\tthis.values.set(key, current);\n\t}\n\n\tget(labels?: MetricLabels): number {\n\t\tconst key = labelsToKey(labels);\n\t\treturn this.values.get(key)?.value || 0;\n\t}\n\n\treset(): void {\n\t\tthis.values.clear();\n\t}\n\n\ttoPrometheus(): string[] {\n\t\tconst lines: string[] = [\n\t\t\t`# HELP ${this.name} ${this.help}`,\n\t\t\t`# TYPE ${this.name} counter`,\n\t\t];\n\t\tif (this.values.size === 0) {\n\t\t\tlines.push(`${this.name} 0`);\n\t\t\treturn lines;\n\t\t}\n\t\tfor (const entry of this.values.values()) {\n\t\t\tlines.push(`${this.name}${formatLabels(entry.labels)} ${entry.value}`);\n\t\t}\n\t\treturn lines;\n\t}\n}\n\nexport class Gauge {\n\tprivate values = new Map<string, { value: number; labels?: MetricLabels }>();\n\n\tconstructor(\n\t\tpublic readonly name: string,\n\t\tpublic readonly help: string,\n\t) {}\n\n\tset(labelsOrValue: MetricLabels | number, maybeValue?: number): void {\n\t\tif (typeof labelsOrValue === \"number\") {\n\t\t\tthis.values.set(\"\", { value: labelsOrValue });\n\t\t\treturn;\n\t\t}\n\t\tconst labels = labelsOrValue;\n\t\tconst val = typeof maybeValue === \"number\" ? maybeValue : 0;\n\t\tconst key = labelsToKey(labels);\n\t\tthis.values.set(key, { value: val, labels });\n\t}\n\n\tinc(labels?: MetricLabels, value = 1): void {\n\t\tconst key = labelsToKey(labels);\n\t\tconst current = this.values.get(key) || { value: 0, labels };\n\t\tcurrent.value += value;\n\t\tthis.values.set(key, current);\n\t}\n\n\tdec(labels?: MetricLabels, value = 1): void {\n\t\tconst key = labelsToKey(labels);\n\t\tconst current = this.values.get(key) || { value: 0, labels };\n\t\tcurrent.value -= value;\n\t\tthis.values.set(key, current);\n\t}\n\n\tget(labels?: MetricLabels): number {\n\t\tconst key = labelsToKey(labels);\n\t\treturn this.values.get(key)?.value || 0;\n\t}\n\n\treset(): void {\n\t\tthis.values.clear();\n\t}\n\n\ttoPrometheus(): string[] {\n\t\tconst lines: string[] = [\n\t\t\t`# HELP ${this.name} ${this.help}`,\n\t\t\t`# TYPE ${this.name} gauge`,\n\t\t];\n\t\tif (this.values.size === 0) {\n\t\t\tlines.push(`${this.name} 0`);\n\t\t\treturn lines;\n\t\t}\n\t\tfor (const entry of this.values.values()) {\n\t\t\tlines.push(`${this.name}${formatLabels(entry.labels)} ${entry.value}`);\n\t\t}\n\t\treturn lines;\n\t}\n}\n\nexport class Histogram {\n\tpublic readonly buckets: number[];\n\tprivate observations = new Map<\n\t\tstring,\n\t\t{\n\t\t\tcount: number;\n\t\t\tsum: number;\n\t\t\tbucketCounts: Map<number, number>;\n\t\t\tlabels?: MetricLabels;\n\t\t}\n\t>();\n\n\tconstructor(\n\t\tpublic readonly name: string,\n\t\tpublic readonly help: string,\n\t\tbuckets: number[] = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000],\n\t) {\n\t\tthis.buckets = [...buckets].sort((a, b) => a - b);\n\t}\n\n\tobserve(labelsOrValue: MetricLabels | number, maybeValue?: number): void {\n\t\tlet labels: MetricLabels | undefined;\n\t\tlet val: number;\n\n\t\tif (typeof labelsOrValue === \"number\") {\n\t\t\tval = labelsOrValue;\n\t\t} else {\n\t\t\tlabels = labelsOrValue;\n\t\t\tval = typeof maybeValue === \"number\" ? maybeValue : 0;\n\t\t}\n\n\t\tconst key = labelsToKey(labels);\n\t\tlet state = this.observations.get(key);\n\t\tif (!state) {\n\t\t\tstate = {\n\t\t\t\tcount: 0,\n\t\t\t\tsum: 0,\n\t\t\t\tbucketCounts: new Map(this.buckets.map((b) => [b, 0])),\n\t\t\t\tlabels,\n\t\t\t};\n\t\t\tthis.observations.set(key, state);\n\t\t}\n\n\t\tstate.count += 1;\n\t\tstate.sum += val;\n\n\t\tfor (const bound of this.buckets) {\n\t\t\tif (val <= bound) {\n\t\t\t\tconst cur = state.bucketCounts.get(bound) || 0;\n\t\t\t\tstate.bucketCounts.set(bound, cur + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\treset(): void {\n\t\tthis.observations.clear();\n\t}\n\n\ttoPrometheus(): string[] {\n\t\tconst lines: string[] = [\n\t\t\t`# HELP ${this.name} ${this.help}`,\n\t\t\t`# TYPE ${this.name} histogram`,\n\t\t];\n\t\tif (this.observations.size === 0) {\n\t\t\tlines.push(`${this.name}_count 0`);\n\t\t\tlines.push(`${this.name}_sum 0`);\n\t\t\treturn lines;\n\t\t}\n\n\t\tfor (const state of this.observations.values()) {\n\t\t\tconst baseLabels = state.labels || {};\n\t\t\tfor (const bound of this.buckets) {\n\t\t\t\tconst bucketLabels = { ...baseLabels, le: String(bound) };\n\t\t\t\tlines.push(\n\t\t\t\t\t`${this.name}_bucket${formatLabels(bucketLabels)} ${state.bucketCounts.get(bound) || 0}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst infLabels = { ...baseLabels, le: \"+Inf\" };\n\t\t\tlines.push(\n\t\t\t\t`${this.name}_bucket${formatLabels(infLabels)} ${state.count}`,\n\t\t\t);\n\t\t\tlines.push(`${this.name}_sum${formatLabels(baseLabels)} ${state.sum}`);\n\t\t\tlines.push(\n\t\t\t\t`${this.name}_count${formatLabels(baseLabels)} ${state.count}`,\n\t\t\t);\n\t\t}\n\t\treturn lines;\n\t}\n}\n\nexport class MetricsRegistry {\n\tprivate counters = new Map<string, Counter>();\n\tprivate gauges = new Map<string, Gauge>();\n\tprivate histograms = new Map<string, Histogram>();\n\n\tcounter(name: string, help: string): Counter {\n\t\tlet c = this.counters.get(name);\n\t\tif (!c) {\n\t\t\tc = new Counter(name, help);\n\t\t\tthis.counters.set(name, c);\n\t\t}\n\t\treturn c;\n\t}\n\n\tgauge(name: string, help: string): Gauge {\n\t\tlet g = this.gauges.get(name);\n\t\tif (!g) {\n\t\t\tg = new Gauge(name, help);\n\t\t\tthis.gauges.set(name, g);\n\t\t}\n\t\treturn g;\n\t}\n\n\thistogram(name: string, help: string, buckets?: number[]): Histogram {\n\t\tlet h = this.histograms.get(name);\n\t\tif (!h) {\n\t\t\th = new Histogram(name, help, buckets);\n\t\t\tthis.histograms.set(name, h);\n\t\t}\n\t\treturn h;\n\t}\n\n\tcollectProcessMetrics(): void {\n\t\tconst uptime = this.gauge(\n\t\t\t\"liop_process_uptime_seconds\",\n\t\t\t\"Process uptime in seconds\",\n\t\t);\n\t\tuptime.set(Math.floor(process.uptime()));\n\n\t\tconst health = this.gauge(\n\t\t\t\"liop_node_health_status\",\n\t\t\t\"Operational health status of the LIOP node (1 = healthy, 0 = degraded)\",\n\t\t);\n\t\thealth.set(1);\n\n\t\tif (typeof process.memoryUsage === \"function\") {\n\t\t\tconst mem = process.memoryUsage();\n\t\t\tconst rss = this.gauge(\n\t\t\t\t\"liop_process_memory_rss_bytes\",\n\t\t\t\t\"Resident set size memory in bytes\",\n\t\t\t);\n\t\t\trss.set(mem.rss);\n\n\t\t\tconst heapUsed = this.gauge(\n\t\t\t\t\"liop_process_memory_heap_used_bytes\",\n\t\t\t\t\"Heap memory used in bytes\",\n\t\t\t);\n\t\t\theapUsed.set(mem.heapUsed);\n\n\t\t\tconst heapTotal = this.gauge(\n\t\t\t\t\"liop_process_memory_heap_total_bytes\",\n\t\t\t\t\"Total V8 allocated heap memory in bytes\",\n\t\t\t);\n\t\t\theapTotal.set(mem.heapTotal);\n\n\t\t\tconst external = this.gauge(\n\t\t\t\t\"liop_process_memory_external_bytes\",\n\t\t\t\t\"External memory bound to C++ objects and buffers in bytes\",\n\t\t\t);\n\t\t\texternal.set(mem.external);\n\t\t}\n\t}\n\n\texportPrometheusText(): string {\n\t\tthis.collectProcessMetrics();\n\n\t\tconst lines: string[] = [];\n\t\tfor (const c of this.counters.values()) {\n\t\t\tlines.push(...c.toPrometheus());\n\t\t}\n\t\tfor (const g of this.gauges.values()) {\n\t\t\tlines.push(...g.toPrometheus());\n\t\t}\n\t\tfor (const h of this.histograms.values()) {\n\t\t\tlines.push(...h.toPrometheus());\n\t\t}\n\t\tlines.push(\"\"); // Trailing newline\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tresetAll(): void {\n\t\tfor (const c of this.counters.values()) c.reset();\n\t\tfor (const g of this.gauges.values()) g.reset();\n\t\tfor (const h of this.histograms.values()) h.reset();\n\t}\n}\n\n// ── Global Standard Protocol Metrics Instance ──────────────────────────────────\n\nexport const protocolMetrics = new MetricsRegistry();\n\nexport const toolCallsTotal = protocolMetrics.counter(\n\t\"liop_tool_calls_total\",\n\t\"Total number of tool logic-injection executions\",\n);\n\nexport const toolCallErrorsTotal = protocolMetrics.counter(\n\t\"liop_tool_call_errors_total\",\n\t\"Total number of failed tool logic-injection executions or policy rejections\",\n);\n\nexport const fuelConsumed = protocolMetrics.histogram(\n\t\"liop_fuel_consumed_total\",\n\t\"Deterministic fuel units consumed by injected logic\",\n\t[100, 500, 1000, 2500, 5000, 10000, 50000, 100000],\n);\n\nexport const meshPeersConnected = protocolMetrics.gauge(\n\t\"liop_mesh_peers_connected\",\n\t\"Active peer connections in the P2P mesh\",\n);\n\nexport const manifestCacheSize = protocolMetrics.gauge(\n\t\"liop_manifest_cache_size\",\n\t\"Number of verified remote tool manifests in cache\",\n);\n\nexport const egressBlocksTotal = protocolMetrics.counter(\n\t\"liop_egress_blocks_total\",\n\t\"Total number of outputs blocked by Egress Shield\",\n);\n\nexport const zkVerificationDurationMs = protocolMetrics.histogram(\n\t\"liop_zk_verification_duration_ms\",\n\t\"Duration of ZK-Receipt and HMAC cryptographic attestation in ms\",\n\t[1, 2, 5, 10, 25, 50, 100, 250, 500],\n);\n\nexport const zkVerificationsTotal = protocolMetrics.counter(\n\t\"liop_zk_verifications_total\",\n\t\"Total number of ZK-Receipt cryptographic attestation checks\",\n);\n\nexport const zkProofsByTypeTotal = protocolMetrics.counter(\n\t\"liop_zk_proofs_by_type_total\",\n\t\"Total number of verified ZK receipts partitioned by proof type (groth16, hmac)\",\n);\n\nexport const zkProvingDurationMs = protocolMetrics.histogram(\n\t\"liop_zk_proving_duration_ms\",\n\t\"Duration of native ZK proof generation in ms\",\n\t[10, 25, 50, 100, 250, 500, 1000, 2500],\n);\n\nexport const zkVkeyCacheSize = protocolMetrics.gauge(\n\t\"liop_zk_vkey_cache_size\",\n\t\"Number of registered verification keys in memory cache\",\n);\n\nexport const tokensInputTotal = protocolMetrics.counter(\n\t\"liop_tokens_input_total\",\n\t\"Total BPE input tokens processed by LIOP\",\n);\n\nexport const tokensOutputTotal = protocolMetrics.counter(\n\t\"liop_tokens_output_total\",\n\t\"Total BPE output tokens emitted by LIOP\",\n);\n\nexport const tokensSavedTotal = protocolMetrics.counter(\n\t\"liop_tokens_saved_total\",\n\t\"Estimated tokens saved compared to MCP context-pulling baseline\",\n);\n\nexport const operationDurationMs = protocolMetrics.histogram(\n\t\"liop_operation_duration_ms\",\n\t\"End-to-end operation duration in ms\",\n\t[5, 15, 30, 50, 100, 250, 500, 1000, 2500, 5000],\n);\n\nexport const pqcHandshakeDurationMs = protocolMetrics.histogram(\n\t\"liop_pqc_handshake_duration_ms\",\n\t\"Duration of ML-KEM-768 post-quantum cryptographic key encapsulation in ms\",\n\t[1, 5, 10, 25, 50, 100, 250, 500],\n);\n\nexport const pqcHandshakesTotal = protocolMetrics.counter(\n\t\"liop_pqc_handshakes_total\",\n\t\"Total number of ML-KEM-768 key encapsulation operations\",\n);\n\nexport const wireEgressBytesTotal = protocolMetrics.counter(\n\t\"liop_wire_egress_bytes_total\",\n\t\"Total wire egress bytes emitted by logic executions\",\n);\n\nexport const wireSavedBytesTotal = protocolMetrics.counter(\n\t\"liop_wire_saved_bytes_total\",\n\t\"Estimated wire egress bytes saved compared to MCP context extraction baseline\",\n);\n"]}
@@ -1,3 +1,4 @@
1
+ import { TOOL_ALIASES } from './chunk-KR5UZUEY.js';
1
2
  import { log } from './chunk-K3DGJLUY.js';
2
3
 
3
4
  // src/runtime/routing-table.ts
@@ -71,7 +72,8 @@ var RoutingTable = class _RoutingTable {
71
72
  * Resolves the optimal route for a specific tool.
72
73
  */
73
74
  resolve(toolName) {
74
- const route = this.routes.get(toolName);
75
+ const targetName = TOOL_ALIASES[toolName] || toolName;
76
+ const route = this.routes.get(targetName) ?? this.routes.get(toolName);
75
77
  if (!route) return void 0;
76
78
  if (route.failCount >= _RoutingTable.MAX_FAILURES) {
77
79
  log.warn(
@@ -275,5 +277,5 @@ async function probeTopology(options = {}) {
275
277
  }
276
278
 
277
279
  export { RoutingTable, probeTopology };
278
- //# sourceMappingURL=chunk-PUDETPL4.js.map
279
- //# sourceMappingURL=chunk-PUDETPL4.js.map
280
+ //# sourceMappingURL=chunk-V47P2AQR.js.map
281
+ //# sourceMappingURL=chunk-V47P2AQR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/routing-table.ts","../src/runtime/topology-probe.ts"],"names":[],"mappings":";;;;AAqCO,IAAM,YAAA,GAAN,MAAM,aAAA,CAAa;AAAA,EACjB,MAAA,uBAAa,GAAA,EAAuB;AAAA,EAC5C,OAAwB,YAAA,GAAe,CAAA;AAAA;AAAA;AAAA;AAAA,EAKhC,oBAAA,CACN,KAAA,EACA,WAAA,EACA,YAAA,GAAe,IAAA,EACR;AACP,IAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACzB,MAAA,MAAM,QAAA,GAAW,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,KAAK,IAAI,CAAA;AAC1C,MAAA,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,IAAA,EAAM;AAAA,QAC1B,MAAM,IAAA,CAAK,IAAA;AAAA,QACX,QAAA,EAAU,cAAA;AAAA,QACV,QAAA,EAAU,WAAA;AAAA,QACV,WAAA,EAAa,IAAA,CAAK,WAAA,IAAe,QAAA,EAAU,WAAA;AAAA,QAC3C,WAAA,EAAa,IAAA,CAAK,WAAA,IAAe,QAAA,EAAU,WAAA;AAAA,QAC3C,SAAA,EAAW,UAAU,SAAA,IAAa,CAAA;AAAA,QAClC,SAAA,EAAW,CAAA;AAAA,QACX,WAAA,EAAa,QAAA,EAAU,WAAA,IAAe,IAAA,CAAK,GAAA,EAAI;AAAA,QAC/C;AAAA,OACA,CAAA;AAAA,IACF;AACA,IAAA,GAAA,CAAI,IAAA;AAAA,MACH,CAAA,0BAAA,EAA6B,KAAA,CAAM,MAAM,CAAA,2BAAA,EAA8B,WAAW,CAAA,CAAA;AAAA,KACnF;AAAA,EACD;AAAA;AAAA;AAAA;AAAA,EAKO,iBA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ACvB,GACD;AACD","file":"chunk-V47P2AQR.js","sourcesContent":["// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Routing Table — Per-Tool Hybrid Routing & Resilience\n *\n * Maintains deterministic per-tool routes across heterogeneous transports:\n * - \"http-gateway\": Route through Border LIO Gateway or reverse proxy via HTTP/JSON-RPC.\n * - \"p2p-grpc\": Route directly to sovereign node via libp2p + gRPC (Kyber768/ZK-Receipt).\n * - \"local\": Handled in-process (e.g. LiopMeshStatus, diagnostic probes).\n *\n * Implements per-route latency tracking, failure backoff, and circuit breaking.\n */\n\nimport { TOOL_ALIASES } from \"../gateway/mcp-compat.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport type TransportProvider = \"http-gateway\" | \"p2p-grpc\" | \"local\";\n\nexport interface ToolDefinition {\n\tname: string;\n\tdescription?: string;\n\tinputSchema?: Record<string, unknown>;\n}\n\nexport interface ToolRoute {\n\tname: string;\n\tprovider: TransportProvider;\n\tendpoint: string;\n\tdescription?: string;\n\tinputSchema?: Record<string, unknown>;\n\tlatencyMs: number;\n\tfailCount: number;\n\tlastSuccess: number;\n\tauthRequired?: boolean;\n}\n\nexport class RoutingTable {\n\tprivate routes = new Map<string, ToolRoute>();\n\tprivate static readonly MAX_FAILURES = 5;\n\n\t/**\n\t * Registers or updates a collection of tools exposed via an HTTP Gateway.\n\t */\n\tpublic registerGatewayTools(\n\t\ttools: ToolDefinition[],\n\t\tmcpEndpoint: string,\n\t\tauthRequired = true,\n\t): void {\n\t\tfor (const tool of tools) {\n\t\t\tconst existing = this.routes.get(tool.name);\n\t\t\tthis.routes.set(tool.name, {\n\t\t\t\tname: tool.name,\n\t\t\t\tprovider: \"http-gateway\",\n\t\t\t\tendpoint: mcpEndpoint,\n\t\t\t\tdescription: tool.description ?? existing?.description,\n\t\t\t\tinputSchema: tool.inputSchema ?? existing?.inputSchema,\n\t\t\t\tlatencyMs: existing?.latencyMs ?? 0,\n\t\t\t\tfailCount: 0,\n\t\t\t\tlastSuccess: existing?.lastSuccess ?? Date.now(),\n\t\t\t\tauthRequired,\n\t\t\t});\n\t\t}\n\t\tlog.info(\n\t\t\t`[RoutingTable] Registered ${tools.length} tool(s) via HTTP Gateway (${mcpEndpoint})`,\n\t\t);\n\t}\n\n\t/**\n\t * Registers tools discovered directly over the P2P Mesh (gRPC).\n\t */\n\tpublic registerMeshTools(\n\t\ttools: ToolDefinition[],\n\t\tgrpcTarget: string,\n\t\tauthRequired = false,\n\t): void {\n\t\tfor (const tool of tools) {\n\t\t\tconst existing = this.routes.get(tool.name);\n\t\t\t// Do not overwrite healthy gateway routes unless explicitly preferred\n\t\t\tif (\n\t\t\t\texisting &&\n\t\t\t\texisting.provider === \"http-gateway\" &&\n\t\t\t\texisting.failCount === 0\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.routes.set(tool.name, {\n\t\t\t\tname: tool.name,\n\t\t\t\tprovider: \"p2p-grpc\",\n\t\t\t\tendpoint: grpcTarget,\n\t\t\t\tdescription: tool.description ?? existing?.description,\n\t\t\t\tinputSchema: tool.inputSchema ?? existing?.inputSchema,\n\t\t\t\tlatencyMs: existing?.latencyMs ?? 0,\n\t\t\t\tfailCount: 0,\n\t\t\t\tlastSuccess: existing?.lastSuccess ?? Date.now(),\n\t\t\t\tauthRequired,\n\t\t\t});\n\t\t}\n\t\tlog.info(\n\t\t\t`[RoutingTable] Registered ${tools.length} tool(s) via P2P Mesh gRPC (${grpcTarget})`,\n\t\t);\n\t}\n\n\t/**\n\t * Registers an in-process local tool (e.g. LiopMeshStatus).\n\t */\n\tpublic registerLocalTool(tool: ToolDefinition): void {\n\t\tthis.routes.set(tool.name, {\n\t\t\tname: tool.name,\n\t\t\tprovider: \"local\",\n\t\t\tendpoint: \"in-process\",\n\t\t\tdescription: tool.description,\n\t\t\tinputSchema: tool.inputSchema,\n\t\t\tlatencyMs: 0,\n\t\t\tfailCount: 0,\n\t\t\tlastSuccess: Date.now(),\n\t\t\tauthRequired: false,\n\t\t});\n\t}\n\n\t/**\n\t * Resolves the optimal route for a specific tool.\n\t */\n\tpublic resolve(toolName: string): ToolRoute | undefined {\n\t\tconst targetName = TOOL_ALIASES[toolName] || toolName;\n\t\tconst route = this.routes.get(targetName) ?? this.routes.get(toolName);\n\t\tif (!route) return undefined;\n\n\t\t// If circuit is tripped (excessive failures), still return route but log warning\n\t\tif (route.failCount >= RoutingTable.MAX_FAILURES) {\n\t\t\tlog.warn(\n\t\t\t\t`[RoutingTable] Tool '${toolName}' route has tripped circuit breaker (${route.failCount} consecutive failures).`,\n\t\t\t);\n\t\t}\n\n\t\treturn route;\n\t}\n\n\t/**\n\t * Records a successful invocation on a route, resetting failures and updating latency.\n\t */\n\tpublic recordSuccess(toolName: string, latencyMs: number): void {\n\t\tconst route = this.routes.get(toolName);\n\t\tif (route) {\n\t\t\troute.failCount = 0;\n\t\t\troute.latencyMs = latencyMs;\n\t\t\troute.lastSuccess = Date.now();\n\t\t}\n\t}\n\n\t/**\n\t * Records a failed invocation on a route.\n\t */\n\tpublic recordFailure(toolName: string): void {\n\t\tconst route = this.routes.get(toolName);\n\t\tif (route) {\n\t\t\troute.failCount += 1;\n\t\t\tlog.warn(\n\t\t\t\t`[RoutingTable] Failure recorded for tool '${toolName}' (failCount: ${route.failCount})`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Lists all registered tools in sorted format for tools/list.\n\t */\n\tpublic getAllToolDefinitions(): ToolDefinition[] {\n\t\tconst list: ToolDefinition[] = [];\n\t\tfor (const route of this.routes.values()) {\n\t\t\tlist.push({\n\t\t\t\tname: route.name,\n\t\t\t\tdescription: route.description,\n\t\t\t\tinputSchema: route.inputSchema,\n\t\t\t});\n\t\t}\n\t\treturn list.sort((a, b) => a.name.localeCompare(b.name));\n\t}\n\n\tpublic getRoute(toolName: string): ToolRoute | undefined {\n\t\treturn this.routes.get(toolName);\n\t}\n\n\tpublic size(): number {\n\t\treturn this.routes.size;\n\t}\n\n\tpublic clear(): void {\n\t\tthis.routes.clear();\n\t}\n}\n","// Copyright 2026 Nekzus Solutions and contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * LIOP Topology Probe — RFC 9728 PRM Chain & Adaptive Network Detection\n *\n * Implements single-URL auto-discovery of multi-tier mesh environments:\n * 1. Probes RFC 9728 Protected Resource Metadata (PRM) or /health endpoint.\n * 2. Chains discovery to obtain OAuth 2.1 authorization server endpoints.\n * 3. Identifies whether the node should operate in \"gateway\", \"mesh\", or \"hybrid\" mode.\n *\n * Standards: RFC 9728, RFC 8414, RFC 8707, NIST SP 800-207\n */\n\nimport { log } from \"../utils/logger.js\";\n\nexport interface GatewayTopologyInfo {\n\tbaseUrl: string;\n\tmcpEndpoint: string;\n\thealthEndpoint: string;\n\ttokenEndpoint: string;\n\tissuer: string;\n\taudience: string;\n\tscopes: string[];\n\ttools: string[];\n\ttier: number;\n}\n\nexport interface MeshTopologyInfo {\n\tbootstrapNodes: string[];\n\tidentityPath?: string;\n}\n\nexport interface TopologyProbeResult {\n\tmode: \"gateway\" | \"mesh\" | \"hybrid\";\n\tgateway?: GatewayTopologyInfo;\n\tmesh?: MeshTopologyInfo;\n}\n\nexport interface TopologyProbeOptions {\n\tblgUrl?: string;\n\tnexusUrl?: string;\n\tclientId?: string;\n\tclientSecret?: string;\n\taudience?: string;\n\tstaticToken?: string;\n\tbootstrapNodes?: string[];\n\tidentityPath?: string;\n\tautoProbeLocal?: boolean;\n}\n\n/**\n * Executes the RFC 9728 PRM chain and health probe on a candidate Gateway URL.\n */\nasync function probeGatewayUrl(\n\tcandidateUrl: string,\n\toptions: TopologyProbeOptions,\n): Promise<GatewayTopologyInfo | null> {\n\tconst trimmedUrl = candidateUrl.replace(/\\/+$/, \"\");\n\tconst healthUrl = `${trimmedUrl}/health`;\n\n\ttry {\n\t\tlog.info(`[TopologyProbe] Probing candidate Gateway at: ${healthUrl}`);\n\t\tconst healthRes = await fetch(healthUrl, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(3000),\n\t\t});\n\n\t\tif (!healthRes.ok) {\n\t\t\tlog.info(\n\t\t\t\t`[TopologyProbe] Probe failed at ${healthUrl} [HTTP ${healthRes.status}]`,\n\t\t\t);\n\t\t\treturn null;\n\t\t}\n\n\t\tconst healthData = (await healthRes.json()) as {\n\t\t\tstatus?: string;\n\t\t\ttools?: string[];\n\t\t\tauth?: {\n\t\t\t\tissuer?: string;\n\t\t\t\ttoken_endpoint?: string;\n\t\t\t\tjwks_uri?: string;\n\t\t\t};\n\t\t\ttopology?: {\n\t\t\t\ttier?: number;\n\t\t\t};\n\t\t};\n\n\t\tif (healthData.status !== \"healthy\") {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Discover OAuth metadata via PRM (RFC 9728)\n\t\tlet issuer = healthData.auth?.issuer || \"\";\n\t\tlet tokenEndpoint = healthData.auth?.token_endpoint || \"\";\n\t\tlet audience = options.audience || \"urn:liop:mesh:api\";\n\t\tlet scopes: string[] = [\n\t\t\t\"liop:tools:list\",\n\t\t\t\"liop:tools:call\",\n\t\t\t\"liop:resources:read\",\n\t\t\t\"liop:schema:read\",\n\t\t\t\"liop:mesh:query\",\n\t\t];\n\n\t\ttry {\n\t\t\tconst prmUrl = `${trimmedUrl}/.well-known/oauth-protected-resource`;\n\t\t\tconst prmRes = await fetch(prmUrl, {\n\t\t\t\theaders: { Accept: \"application/json\" },\n\t\t\t\tsignal: AbortSignal.timeout(2000),\n\t\t\t});\n\t\t\tif (prmRes.ok) {\n\t\t\t\tconst prmData = (await prmRes.json()) as {\n\t\t\t\t\tresource?: string;\n\t\t\t\t\tauthorization_servers?: string[];\n\t\t\t\t\tscopes_supported?: string[];\n\t\t\t\t};\n\t\t\t\tif (prmData.resource) audience = prmData.resource;\n\t\t\t\tif (prmData.authorization_servers?.length) {\n\t\t\t\t\tissuer = prmData.authorization_servers[0];\n\t\t\t\t}\n\t\t\t\tif (prmData.scopes_supported?.length) {\n\t\t\t\t\tscopes = prmData.scopes_supported;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Non-fatal if PRM endpoint is not present\n\t\t}\n\n\t\t// If token endpoint is not explicitly given, resolve from issuer\n\t\tif (!tokenEndpoint && issuer) {\n\t\t\tconst baseIssuer = issuer.endsWith(\"/oidc\") ? issuer : `${issuer}/oidc`;\n\t\t\ttokenEndpoint = `${baseIssuer}/token`;\n\t\t}\n\n\t\t// Normalize tokenEndpoint for Docker-to-Host bridge environments\n\t\tif (tokenEndpoint) {\n\t\t\ttry {\n\t\t\t\tconst parsedEndpoint = new URL(tokenEndpoint);\n\t\t\t\tif (options.nexusUrl) {\n\t\t\t\t\tconst nexusBase = options.nexusUrl.replace(/\\/+$/, \"\");\n\t\t\t\t\tconst nexusHost = new URL(nexusBase).host;\n\t\t\t\t\tparsedEndpoint.host = nexusHost;\n\t\t\t\t\ttokenEndpoint = parsedEndpoint.toString();\n\t\t\t\t} else if (\n\t\t\t\t\t(parsedEndpoint.hostname === \"nexus\" ||\n\t\t\t\t\t\tparsedEndpoint.hostname === \"nexus-prod\" ||\n\t\t\t\t\t\tparsedEndpoint.hostname.startsWith(\"172.\")) &&\n\t\t\t\t\ttrimmedUrl.includes(\"127.0.0.1\")\n\t\t\t\t) {\n\t\t\t\t\tparsedEndpoint.host = \"127.0.0.1:15000\";\n\t\t\t\t\ttokenEndpoint = parsedEndpoint.toString();\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t/* keep original tokenEndpoint */\n\t\t\t}\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[TopologyProbe] ✅ Verified Gateway at ${trimmedUrl} (Tools: ${healthData.tools?.length ?? 0}, Tier: ${healthData.topology?.tier ?? 2})`,\n\t\t);\n\n\t\treturn {\n\t\t\tbaseUrl: trimmedUrl,\n\t\t\tmcpEndpoint: `${trimmedUrl}/mcp`,\n\t\t\thealthEndpoint: `${trimmedUrl}/health`,\n\t\t\ttokenEndpoint,\n\t\t\tissuer,\n\t\t\taudience,\n\t\t\tscopes,\n\t\t\ttools: healthData.tools || [],\n\t\t\ttier: healthData.topology?.tier ?? 2,\n\t\t};\n\t} catch (err) {\n\t\tlog.info(\n\t\t\t`[TopologyProbe] Gateway probe unreachable at ${trimmedUrl}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t\treturn null;\n\t}\n}\n\n/**\n * Probes the runtime environment and determines the optimal architecture mode.\n */\nexport async function probeTopology(\n\toptions: TopologyProbeOptions = {},\n): Promise<TopologyProbeResult> {\n\tlog.info(\"[TopologyProbe] Starting adaptive network topology discovery...\");\n\n\tlet gatewayInfo: GatewayTopologyInfo | null = null;\n\n\t// 1. Check explicit Border LIO Gateway URL (Highest priority)\n\tif (options.blgUrl) {\n\t\tgatewayInfo = await probeGatewayUrl(options.blgUrl, options);\n\t}\n\n\t// 2. Auto-probing known local infrastructure ports if enabled/unspecified\n\tif (!gatewayInfo && (options.autoProbeLocal ?? true)) {\n\t\tconst candidateUrls = [\n\t\t\t\"http://127.0.0.1:15018\", // Production BLG port\n\t\t\t\"http://127.0.0.1:15000\", // Production Nexus port\n\t\t\t\"http://127.0.0.1:13000\", // Demo Nexus port\n\t\t];\n\n\t\tfor (const url of candidateUrls) {\n\t\t\t// Skip if already probed\n\t\t\tif (options.blgUrl && url.includes(new URL(options.blgUrl).port))\n\t\t\t\tcontinue;\n\n\t\t\tgatewayInfo = await probeGatewayUrl(url, options);\n\t\t\tif (gatewayInfo) break;\n\t\t}\n\t}\n\n\t// 3. Evaluate P2P Mesh connectivity\n\tconst bootstrapNodes = options.bootstrapNodes || [];\n\tconst hasMeshBootstraps = bootstrapNodes.length > 0;\n\n\t// 4. Decide runtime mode\n\tif (gatewayInfo && hasMeshBootstraps) {\n\t\tlog.info(\n\t\t\t`[TopologyProbe] ⚡ Mode Determined: HYBRID (Gateway: ${gatewayInfo.baseUrl} + ${bootstrapNodes.length} P2P bootstraps)`,\n\t\t);\n\t\treturn {\n\t\t\tmode: \"hybrid\",\n\t\t\tgateway: gatewayInfo,\n\t\t\tmesh: {\n\t\t\t\tbootstrapNodes,\n\t\t\t\tidentityPath: options.identityPath,\n\t\t\t},\n\t\t};\n\t}\n\n\tif (gatewayInfo) {\n\t\tlog.info(\n\t\t\t`[TopologyProbe] 🚀 Mode Determined: GATEWAY (Zero-P2P overhead, direct to ${gatewayInfo.baseUrl})`,\n\t\t);\n\t\treturn {\n\t\t\tmode: \"gateway\",\n\t\t\tgateway: gatewayInfo,\n\t\t};\n\t}\n\n\tlog.info(\n\t\t`[TopologyProbe] 🌐 Mode Determined: MESH (Standard P2P DHT, Bootstraps: ${bootstrapNodes.length})`,\n\t);\n\treturn {\n\t\tmode: \"mesh\",\n\t\tmesh: {\n\t\t\tbootstrapNodes,\n\t\t\tidentityPath: options.identityPath,\n\t\t},\n\t};\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { TokenManager } from './chunk-3QH44NKZ.js';
2
- import { LiopVerifier } from './chunk-2STZHJ24.js';
2
+ import { LiopVerifier } from './chunk-ZRWNMP5L.js';
3
3
  import { Kyber768Wrapper } from './chunk-7PITYWOV.js';
4
- import { createChannelCredentials, liopV1, GRPC_CHANNEL_OPTIONS, TokenTelemetryEngine } from './chunk-UJFWPRDM.js';
5
- import { pqcHandshakesTotal, pqcHandshakeDurationMs, zkVerificationsTotal, toolCallErrorsTotal, wireEgressBytesTotal } from './chunk-PAICJCKJ.js';
6
- import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION_LEGACY } from './chunk-2KSO3W4A.js';
7
- import { MeshNode } from './chunk-XRDN232O.js';
4
+ import { createChannelCredentials, liopV1, GRPC_CHANNEL_OPTIONS, TokenTelemetryEngine } from './chunk-GFGSHQN5.js';
5
+ import { pqcHandshakesTotal, pqcHandshakeDurationMs, zkVerificationsTotal, toolCallErrorsTotal, wireEgressBytesTotal } from './chunk-Q3FKHJ3B.js';
6
+ import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION_LEGACY } from './chunk-KR5UZUEY.js';
7
+ import { MeshNode } from './chunk-IHKKWXHJ.js';
8
8
  import { log } from './chunk-K3DGJLUY.js';
9
9
  import * as grpc from '@grpc/grpc-js';
10
10
  import { createDecipheriv, randomBytes, createCipheriv } from 'crypto';
@@ -369,7 +369,7 @@ var LiopClient = class {
369
369
  /**
370
370
  * Invokes a tool.
371
371
  */
372
- async callTool(request, _wasmPayload) {
372
+ async callTool(request, _wasmPayload, options) {
373
373
  if (!this.meshNode) {
374
374
  throw new Error("Client must be connected before calling tools.");
375
375
  }
@@ -551,13 +551,21 @@ var LiopClient = class {
551
551
  hasReceivedData = true;
552
552
  log.info("[LiopClient] Logic Executed. Verification in progress...");
553
553
  try {
554
+ let isV2 = false;
554
555
  if (!response.is_error) {
556
+ const receiptBuf = Buffer.from(response.zk_receipt);
557
+ isV2 = receiptBuf.length > 0 && receiptBuf[0] === 2;
558
+ const zkPolicy = options?.zkPolicy ?? (isV2 ? "required" : "none");
555
559
  const isValid = await this.verifier.verifyZkReceipt(
556
560
  _safePayload,
557
561
  Buffer.from(response.cryptographic_proof).toString("hex"),
558
- Buffer.from(response.zk_receipt),
559
- Buffer.from(sharedSecret),
560
- response.semantic_evidence
562
+ receiptBuf,
563
+ {
564
+ sessionSecret: Buffer.from(sharedSecret),
565
+ expectedOutput: response.semantic_evidence,
566
+ circuitName: options?.circuitName,
567
+ zkPolicy
568
+ }
561
569
  );
562
570
  try {
563
571
  zkVerificationsTotal.inc({
@@ -615,7 +623,9 @@ var LiopClient = class {
615
623
  text: response.semantic_evidence
616
624
  }
617
625
  ],
618
- isError: response.is_error
626
+ isError: response.is_error,
627
+ zkVerified: !response.is_error,
628
+ zkProofType: isV2 ? 2 /* GROTH16 */ : 0 /* HMAC_LEGACY */
619
629
  });
620
630
  } catch (err) {
621
631
  try {
@@ -789,5 +799,5 @@ var LiopClient = class {
789
799
  };
790
800
 
791
801
  export { AesGcmWrapper, LiopClient, LiopRpcClient };
792
- //# sourceMappingURL=chunk-FCFTYOAS.js.map
793
- //# sourceMappingURL=chunk-FCFTYOAS.js.map
802
+ //# sourceMappingURL=chunk-ZJGVKM7G.js.map
803
+ //# sourceMappingURL=chunk-ZJGVKM7G.js.map