@nekzus/liop 2.4.0-alpha.7 → 2.4.0-alpha.8

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 (92) hide show
  1. package/NOTICE +19 -0
  2. package/README.md +36 -17
  3. package/dist/bin/agent.js +674 -82
  4. package/dist/bin/agent.js.map +1 -1
  5. package/dist/bridge.d.ts +2 -2
  6. package/dist/bridge.js +3 -3
  7. package/dist/{chunk-T5IUZF47.js → chunk-3L2O2XKG.js} +12 -5
  8. package/dist/chunk-3L2O2XKG.js.map +1 -0
  9. package/dist/{chunk-SONUORBT.js → chunk-7BSCUYUE.js} +2 -2
  10. package/dist/chunk-7BSCUYUE.js.map +1 -0
  11. package/dist/{chunk-QLCOEP5J.js → chunk-7PITYWOV.js} +2 -2
  12. package/dist/chunk-7PITYWOV.js.map +1 -0
  13. package/dist/{chunk-74CISO2I.js → chunk-7RXOIDXP.js} +28 -4
  14. package/dist/chunk-7RXOIDXP.js.map +1 -0
  15. package/dist/{chunk-GA3Q2S7O.js → chunk-BOISQ45Z.js} +5 -5
  16. package/dist/chunk-BOISQ45Z.js.map +1 -0
  17. package/dist/{chunk-547TYL27.js → chunk-DZ2FQGJD.js} +26 -1423
  18. package/dist/chunk-DZ2FQGJD.js.map +1 -0
  19. package/dist/{chunk-PYKRQAER.js → chunk-EG46XMJT.js} +2 -2
  20. package/dist/chunk-EG46XMJT.js.map +1 -0
  21. package/dist/chunk-ESRXG36Y.js +115 -0
  22. package/dist/chunk-ESRXG36Y.js.map +1 -0
  23. package/dist/chunk-FTF6AMF6.js +3 -0
  24. package/dist/{chunk-RWRRBYG4.js.map → chunk-FTF6AMF6.js.map} +1 -1
  25. package/dist/{chunk-72MNYFR6.js → chunk-HA6YZ42O.js} +2 -2
  26. package/dist/chunk-HA6YZ42O.js.map +1 -0
  27. package/dist/{chunk-WCCGE4QR.js → chunk-HD2N3IJX.js} +144 -30
  28. package/dist/chunk-HD2N3IJX.js.map +1 -0
  29. package/dist/{chunk-OUUTDSOW.js → chunk-IK7CGWAZ.js} +3 -3
  30. package/dist/chunk-IK7CGWAZ.js.map +1 -0
  31. package/dist/chunk-L6J72C5X.js +1477 -0
  32. package/dist/chunk-L6J72C5X.js.map +1 -0
  33. package/dist/{chunk-U5BZ66VX.js → chunk-PAICJCKJ.js} +60 -175
  34. package/dist/chunk-PAICJCKJ.js.map +1 -0
  35. package/dist/{chunk-32ADSAJS.js → chunk-PEN3KFLF.js} +14 -4
  36. package/dist/chunk-PEN3KFLF.js.map +1 -0
  37. package/dist/{chunk-CRZBVFDV.js → chunk-T7R5HUFD.js} +225 -66
  38. package/dist/chunk-T7R5HUFD.js.map +1 -0
  39. package/dist/{chunk-WSW6YJNY.js → chunk-TKRX6CFI.js} +3 -3
  40. package/dist/chunk-TKRX6CFI.js.map +1 -0
  41. package/dist/chunk-UCVP3XAL.js +279 -0
  42. package/dist/chunk-UCVP3XAL.js.map +1 -0
  43. package/dist/chunk-VH4K4U45.js +180 -0
  44. package/dist/chunk-VH4K4U45.js.map +1 -0
  45. package/dist/{chunk-JIJPZFR2.js → chunk-Y62GORQF.js} +2 -2
  46. package/dist/chunk-Y62GORQF.js.map +1 -0
  47. package/dist/chunk-ZP3VVXOI.js +66 -0
  48. package/dist/chunk-ZP3VVXOI.js.map +1 -0
  49. package/dist/client.d.ts +2 -2
  50. package/dist/client.js +11 -8
  51. package/dist/gateway.d.ts +3 -3
  52. package/dist/gateway.js +11 -9
  53. package/dist/{hybrid-CF__0YnC.d.ts → hybrid-CrKB50nh.d.ts} +2 -2
  54. package/dist/{index-cMV0_yD9.d.ts → index-CX43dvMs.d.ts} +2 -32
  55. package/dist/{index-BW95kAL4.d.ts → index-DoW2gzBZ.d.ts} +3 -21
  56. package/dist/index.d.ts +170 -46
  57. package/dist/index.js +20 -15
  58. package/dist/index.js.map +1 -1
  59. package/dist/kyber-CGOA7Q6A.js +3 -0
  60. package/dist/{kyber-3ULIJSE3.js.map → kyber-CGOA7Q6A.js.map} +1 -1
  61. package/dist/mesh.d.ts +27 -143
  62. package/dist/mesh.js +4 -3
  63. package/dist/node-B0b2vUFS.d.ts +164 -0
  64. package/dist/protocol/liop_core.proto +3 -0
  65. package/dist/server.d.ts +2 -2
  66. package/dist/server.js +7 -6
  67. package/dist/types.js +1 -1
  68. package/dist/verifier-HRFXBKT5.js +6 -0
  69. package/dist/{verifier-3FAKCFNN.js.map → verifier-HRFXBKT5.js.map} +1 -1
  70. package/dist/workers/logic-execution.js +3 -3
  71. package/dist/workers/logic-execution.js.map +1 -1
  72. package/dist/workers/zk-verifier.js +1 -1
  73. package/dist/workers/zk-verifier.js.map +1 -1
  74. package/package.json +8 -2
  75. package/dist/chunk-32ADSAJS.js.map +0 -1
  76. package/dist/chunk-547TYL27.js.map +0 -1
  77. package/dist/chunk-72MNYFR6.js.map +0 -1
  78. package/dist/chunk-74CISO2I.js.map +0 -1
  79. package/dist/chunk-CRZBVFDV.js.map +0 -1
  80. package/dist/chunk-GA3Q2S7O.js.map +0 -1
  81. package/dist/chunk-JIJPZFR2.js.map +0 -1
  82. package/dist/chunk-OUUTDSOW.js.map +0 -1
  83. package/dist/chunk-PYKRQAER.js.map +0 -1
  84. package/dist/chunk-QLCOEP5J.js.map +0 -1
  85. package/dist/chunk-RWRRBYG4.js +0 -3
  86. package/dist/chunk-SONUORBT.js.map +0 -1
  87. package/dist/chunk-T5IUZF47.js.map +0 -1
  88. package/dist/chunk-U5BZ66VX.js.map +0 -1
  89. package/dist/chunk-WCCGE4QR.js.map +0 -1
  90. package/dist/chunk-WSW6YJNY.js.map +0 -1
  91. package/dist/kyber-3ULIJSE3.js +0 -3
  92. package/dist/verifier-3FAKCFNN.js +0 -5
@@ -0,0 +1,1477 @@
1
+ import { TokenTelemetryEngine } from './chunk-DZ2FQGJD.js';
2
+ import { LiopVerifier } from './chunk-PEN3KFLF.js';
3
+ import { Kyber768Wrapper } from './chunk-7PITYWOV.js';
4
+ import { authorizeRequest, Dilithium65Wrapper } from './chunk-VH4K4U45.js';
5
+ import { liopV1, createChannelCredentials, GRPC_CHANNEL_OPTIONS } from './chunk-TKRX6CFI.js';
6
+ import { toolCallErrorsTotal, pqcHandshakeDurationMs, pqcHandshakesTotal, zkVerificationsTotal, wireEgressBytesTotal } from './chunk-PAICJCKJ.js';
7
+ import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, isLegacyRequest, adaptResponseForLegacyClient, MCP_PROTOCOL_VERSION_LEGACY, buildLegacyInitializeResponse } from './chunk-EG46XMJT.js';
8
+ import { log } from './chunk-HA6YZ42O.js';
9
+ import * as crypto from 'crypto';
10
+ import * as grpc from '@grpc/grpc-js';
11
+
12
+ // src/utils/mcpCompact.ts
13
+ function mcpCompactToolDescriptions() {
14
+ const v = process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();
15
+ if (v === "0" || v === "false" || v === "no") return false;
16
+ return true;
17
+ }
18
+ function stripVerboseLiopToolDescription(description) {
19
+ let d = description;
20
+ const markers = [
21
+ "\n\n[LIOP-PROTO-V1:",
22
+ "\r\n\r\n[LIOP-PROTO-V1:",
23
+ "\n[LIOP-PROTO-V1:"
24
+ // rare
25
+ ];
26
+ for (const m of markers) {
27
+ const i = d.indexOf(m);
28
+ if (i !== -1) {
29
+ d = d.slice(0, i);
30
+ break;
31
+ }
32
+ }
33
+ return d.trimEnd();
34
+ }
35
+
36
+ // src/gateway/router.ts
37
+ var MANIFEST_CACHE_TTL_S = 300;
38
+ var MANIFEST_DISCOVERY_RETRIES = 5;
39
+ var LiopMcpRouter = class _LiopMcpRouter {
40
+ constructor(liopServer, meshNode = null, defaultRpcPort = 50051) {
41
+ this.liopServer = liopServer;
42
+ this.meshNode = meshNode;
43
+ this.defaultRpcPort = defaultRpcPort;
44
+ if (this.meshNode) {
45
+ this.meshNode.registerManifestHandler(() => {
46
+ const remoteTools = this.liopServer.listTools().map((t) => ({
47
+ name: t.name,
48
+ description: t.description,
49
+ inputSchema: t.inputSchema
50
+ }));
51
+ const resources = this.liopServer.listResources().map((r) => ({
52
+ name: r.name,
53
+ uri: r.uri,
54
+ description: r.description,
55
+ mimeType: r.mimeType
56
+ }));
57
+ const serverConfig = this.liopServer.config;
58
+ return {
59
+ peerId: this.meshNode?.getPeerId() || "unknown",
60
+ grpcPort: this.defaultRpcPort,
61
+ tools: [...remoteTools],
62
+ resources,
63
+ serverInfo: this.liopServer.getServerInfo(),
64
+ authRequired: this.liopServer.jwtValidator !== void 0,
65
+ tokenSlug: serverConfig?.tokenSlug,
66
+ taxonomy: serverConfig?.taxonomy ? {
67
+ domain: serverConfig.taxonomy.domain || "Unknown Domain",
68
+ clearanceTier: serverConfig.taxonomy.clearanceTier ?? 0,
69
+ executionTypes: serverConfig.taxonomy.executionTypes || []
70
+ } : void 0
71
+ };
72
+ });
73
+ this.meshNode.announceManifest().catch((err) => {
74
+ log.info(
75
+ `[LIOP-Router] Failed to announce manifest: ${err instanceof Error ? err.message : String(err)}`
76
+ );
77
+ });
78
+ }
79
+ if (process.env.LIOP_DIAGNOSTIC_LEVEL === "full") {
80
+ process.stderr.write(
81
+ "\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.\n"
82
+ );
83
+ }
84
+ }
85
+ liopServer;
86
+ meshNode;
87
+ defaultRpcPort;
88
+ /** Cached manifests from remote peers. Key = PeerID */
89
+ manifestCache = /* @__PURE__ */ new Map();
90
+ /** Guards against concurrent discovery storms */
91
+ currentDiscovery = null;
92
+ /** Verifier for Tier-0 integrity checks */
93
+ verifier = new LiopVerifier();
94
+ /** Callback when new remote tools are discovered */
95
+ onToolsChanged;
96
+ /** Circuit-breaker state for peers that repeatedly fail manifest queries. */
97
+ manifestFailureState = /* @__PURE__ */ new Map();
98
+ static MANIFEST_FAILURE_BASE_COOLDOWN_MS = 15e3;
99
+ static MANIFEST_FAILURE_MAX_COOLDOWN_MS = 5 * 6e4;
100
+ static MANIFEST_SKIP_LOG_THROTTLE_MS = 3e4;
101
+ getManifestCacheSize() {
102
+ return this.manifestCache.size;
103
+ }
104
+ shouldSkipManifestQuery(peerId) {
105
+ const state = this.manifestFailureState.get(peerId);
106
+ if (!state) return false;
107
+ const now = Date.now();
108
+ if (now >= state.cooldownUntil) return false;
109
+ if (now - state.lastSkipLogAt > _LiopMcpRouter.MANIFEST_SKIP_LOG_THROTTLE_MS) {
110
+ log.info(
111
+ `[LIOP-Router] Skipping manifest query for ${peerId} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1e3)}s remaining)`
112
+ );
113
+ state.lastSkipLogAt = now;
114
+ }
115
+ return true;
116
+ }
117
+ recordManifestQuerySuccess(peerId) {
118
+ this.manifestFailureState.delete(peerId);
119
+ }
120
+ recordManifestQueryFailure(peerId) {
121
+ const now = Date.now();
122
+ const prev = this.manifestFailureState.get(peerId);
123
+ const failures = (prev?.failures || 0) + 1;
124
+ const backoff = Math.min(
125
+ _LiopMcpRouter.MANIFEST_FAILURE_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),
126
+ _LiopMcpRouter.MANIFEST_FAILURE_MAX_COOLDOWN_MS
127
+ );
128
+ this.manifestFailureState.set(peerId, {
129
+ failures,
130
+ cooldownUntil: now + backoff,
131
+ lastSkipLogAt: 0
132
+ });
133
+ }
134
+ /**
135
+ * Detects the protocol era of an incoming request.
136
+ * Modern requests carry '_meta' with protocol version "2026-07-28" or use modern RPCs.
137
+ * Legacy requests use 'initialize' handshake or lack '_meta' envelopes.
138
+ */
139
+ detectEra(request) {
140
+ const params = request.params;
141
+ const meta = params?._meta;
142
+ const version = meta?.["io.modelcontextprotocol/protocolVersion"];
143
+ if (version === MCP_PROTOCOL_VERSION) {
144
+ return "modern";
145
+ }
146
+ if (MCP_LEGACY_SUPPORT_ENABLED && isLegacyRequest(request)) {
147
+ return "legacy";
148
+ }
149
+ return "modern";
150
+ }
151
+ async dispatch(request, authInfo) {
152
+ const { method, params, id } = request;
153
+ log.info(`[LIOP-Router] Processing: ${method}`);
154
+ if (this.liopServer.jwtValidator) {
155
+ const authResult = authorizeRequest(method, authInfo ?? null);
156
+ if (!authResult.allowed) {
157
+ log.info(
158
+ `[LIOP-Router] RBAC Access Denied for method '${method}': ${authResult.reason}`
159
+ );
160
+ return {
161
+ jsonrpc: "2.0",
162
+ id,
163
+ error: {
164
+ code: -32099,
165
+ // Custom authentication/authorization failure code
166
+ message: authResult.reason || "Access Denied"
167
+ }
168
+ };
169
+ }
170
+ }
171
+ switch (method) {
172
+ /** @mcp-legacy Initialize handshake for 2025-era clients. Remove when v1 EOL. */
173
+ case "initialize": {
174
+ if (!MCP_LEGACY_SUPPORT_ENABLED) {
175
+ return {
176
+ jsonrpc: "2.0",
177
+ id,
178
+ error: {
179
+ code: -32601,
180
+ message: "Method retired: initialize (MCP 2026-07-28 is stateless)"
181
+ }
182
+ };
183
+ }
184
+ log.info(
185
+ "[LIOP-Router] \u26A0\uFE0F Legacy MCP client detected (2025-era initialize)."
186
+ );
187
+ return buildLegacyInitializeResponse(
188
+ this.liopServer.getServerInfo(),
189
+ id
190
+ );
191
+ }
192
+ /** @mcp-legacy Initialized notification for 2025-era clients. Remove when v1 EOL. */
193
+ case "notifications/initialized":
194
+ if (!MCP_LEGACY_SUPPORT_ENABLED) return null;
195
+ this.kickDiscoveryAfterInitialized().catch(() => {
196
+ });
197
+ return null;
198
+ case "notifications/cancelled":
199
+ return null;
200
+ // No-op for MCP spec compliance
201
+ case "server/discover":
202
+ return {
203
+ jsonrpc: "2.0",
204
+ id,
205
+ result: {
206
+ resultType: "complete",
207
+ supportedVersions: MCP_LEGACY_SUPPORT_ENABLED ? [MCP_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_LEGACY] : [MCP_PROTOCOL_VERSION],
208
+ capabilities: {
209
+ tools: { listChanged: true },
210
+ resources: { listChanged: true },
211
+ prompts: { listChanged: true }
212
+ },
213
+ serverInfo: this.liopServer.getServerInfo()
214
+ }
215
+ };
216
+ case "ping":
217
+ return { jsonrpc: "2.0", id, result: {} };
218
+ case "tools/list": {
219
+ const localTools = this.liopServer.listTools();
220
+ const remoteTools = await this.getRemoteTools();
221
+ const listedLocals = mcpCompactToolDescriptions() ? localTools.map((t) => ({
222
+ ...t,
223
+ description: stripVerboseLiopToolDescription(t.description ?? "")
224
+ })) : localTools;
225
+ log.info(
226
+ `[LIOP-Router] tools/list: ${localTools.length} local, ${remoteTools.length} remote tools found`
227
+ );
228
+ const diagnosticTool = {
229
+ name: "LiopMeshStatus",
230
+ description: "LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",
231
+ inputSchema: {
232
+ type: "object",
233
+ properties: {},
234
+ additionalProperties: false
235
+ }
236
+ };
237
+ const allTools = [diagnosticTool, ...listedLocals, ...remoteTools].sort(
238
+ (a, b) => a.name.localeCompare(b.name)
239
+ );
240
+ const telemetry = TokenTelemetryEngine.getInstance();
241
+ const toolsPayload = JSON.stringify(allTools);
242
+ const toolsResponsePayload = JSON.stringify({ tools: allTools });
243
+ telemetry.record({
244
+ type: "tools_list",
245
+ method: "tools/list",
246
+ estimatedInputTokens: telemetry.countTokens(toolsPayload),
247
+ estimatedOutputTokens: telemetry.countTokens(toolsResponsePayload)
248
+ });
249
+ const era = this.detectEra(request);
250
+ let response = {
251
+ jsonrpc: "2.0",
252
+ id,
253
+ result: {
254
+ resultType: "complete",
255
+ ttlMs: 3e5,
256
+ cacheScope: "public",
257
+ tools: allTools
258
+ }
259
+ };
260
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
261
+ response = adaptResponseForLegacyClient(response);
262
+ }
263
+ return response;
264
+ }
265
+ case "tools/call": {
266
+ const response = await this.transcodeMcpToLiop(
267
+ id,
268
+ params,
269
+ authInfo?.token
270
+ );
271
+ if (!response) return null;
272
+ const era = this.detectEra(request);
273
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
274
+ return adaptResponseForLegacyClient(response);
275
+ }
276
+ if (response.result && typeof response.result === "object") {
277
+ const resObj = response.result;
278
+ if (!resObj.resultType) {
279
+ resObj.resultType = "complete";
280
+ }
281
+ }
282
+ return response;
283
+ }
284
+ case "resources/list": {
285
+ const localResources = this.liopServer.listResources();
286
+ const remoteResources = await this.getRemoteResources();
287
+ const allResources = [...localResources, ...remoteResources].sort(
288
+ (a, b) => a.uri.localeCompare(b.uri)
289
+ );
290
+ const rlTelemetry = TokenTelemetryEngine.getInstance();
291
+ const rlPayload = JSON.stringify(allResources);
292
+ rlTelemetry.record({
293
+ type: "resource_list",
294
+ method: "resources/list",
295
+ estimatedInputTokens: 0,
296
+ estimatedOutputTokens: rlTelemetry.countTokens(rlPayload)
297
+ });
298
+ const era = this.detectEra(request);
299
+ let response = {
300
+ jsonrpc: "2.0",
301
+ id,
302
+ result: {
303
+ resultType: "complete",
304
+ ttlMs: 3e5,
305
+ cacheScope: "public",
306
+ resources: allResources
307
+ }
308
+ };
309
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
310
+ response = adaptResponseForLegacyClient(response);
311
+ }
312
+ return response;
313
+ }
314
+ case "resources/read": {
315
+ const typedParams = params;
316
+ if (!typedParams?.uri)
317
+ return {
318
+ jsonrpc: "2.0",
319
+ id,
320
+ error: { code: -32602, message: "Missing resource uri" }
321
+ };
322
+ try {
323
+ const rrStartTime = Date.now();
324
+ const result = await this.liopServer.readResource(typedParams.uri);
325
+ const rrTelemetry = TokenTelemetryEngine.getInstance();
326
+ const rrOutputPayload = JSON.stringify(result);
327
+ rrTelemetry.record({
328
+ type: "resource_read",
329
+ method: "resources/read",
330
+ toolName: typedParams.uri,
331
+ estimatedInputTokens: rrTelemetry.countTokens(typedParams.uri),
332
+ estimatedOutputTokens: rrTelemetry.countTokens(rrOutputPayload),
333
+ durationMs: Date.now() - rrStartTime
334
+ });
335
+ const era = this.detectEra(request);
336
+ const rawResult = typeof result === "object" && result !== null ? {
337
+ resultType: "complete",
338
+ ttlMs: 6e4,
339
+ cacheScope: "private",
340
+ ...result
341
+ } : {
342
+ resultType: "complete",
343
+ ttlMs: 6e4,
344
+ cacheScope: "private",
345
+ contents: result
346
+ };
347
+ let response = { jsonrpc: "2.0", id, result: rawResult };
348
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
349
+ response = adaptResponseForLegacyClient(response);
350
+ }
351
+ return response;
352
+ } catch (err) {
353
+ const targetUri = typedParams.uri;
354
+ for (const { manifest } of this.manifestCache.values()) {
355
+ const remoteResource = manifest.resources.find(
356
+ (r) => r.uri === targetUri
357
+ );
358
+ if (remoteResource) {
359
+ log.info(
360
+ `[LIOP-Router] Resolved resource ${targetUri} from cache (Peer: ${manifest.peerId})`
361
+ );
362
+ const era = this.detectEra(request);
363
+ let response = {
364
+ jsonrpc: "2.0",
365
+ id,
366
+ result: {
367
+ resultType: "complete",
368
+ ttlMs: 6e4,
369
+ cacheScope: "private",
370
+ contents: [
371
+ {
372
+ uri: remoteResource.uri,
373
+ mimeType: remoteResource.mimeType || "text/plain",
374
+ text: remoteResource.text || remoteResource.description || "No content provided"
375
+ }
376
+ ]
377
+ }
378
+ };
379
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
380
+ response = adaptResponseForLegacyClient(response);
381
+ }
382
+ return response;
383
+ }
384
+ }
385
+ return {
386
+ jsonrpc: "2.0",
387
+ id,
388
+ error: {
389
+ code: -32e3,
390
+ message: err instanceof Error ? err.message : String(err)
391
+ }
392
+ };
393
+ }
394
+ }
395
+ case "prompts/list": {
396
+ const promptsList = this.liopServer.listPrompts().sort((a, b) => a.name.localeCompare(b.name));
397
+ const plTelemetry = TokenTelemetryEngine.getInstance();
398
+ const plPayload = JSON.stringify(promptsList);
399
+ plTelemetry.record({
400
+ type: "prompt_list",
401
+ method: "prompts/list",
402
+ estimatedInputTokens: 0,
403
+ estimatedOutputTokens: plTelemetry.countTokens(plPayload)
404
+ });
405
+ const era = this.detectEra(request);
406
+ let response = {
407
+ jsonrpc: "2.0",
408
+ id,
409
+ result: {
410
+ resultType: "complete",
411
+ ttlMs: 3e5,
412
+ cacheScope: "public",
413
+ prompts: promptsList
414
+ }
415
+ };
416
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
417
+ response = adaptResponseForLegacyClient(response);
418
+ }
419
+ return response;
420
+ }
421
+ case "prompts/get": {
422
+ const typedParams = params;
423
+ if (!typedParams?.name)
424
+ return {
425
+ jsonrpc: "2.0",
426
+ id,
427
+ error: { code: -32602, message: "Missing prompt name" }
428
+ };
429
+ try {
430
+ const pgStartTime = Date.now();
431
+ const result = await this.liopServer.getPrompt({
432
+ name: typedParams.name,
433
+ arguments: typedParams.arguments || {}
434
+ });
435
+ const pgTelemetry = TokenTelemetryEngine.getInstance();
436
+ const pgInputPayload = JSON.stringify({
437
+ name: typedParams.name,
438
+ arguments: typedParams.arguments
439
+ });
440
+ const pgOutputPayload = JSON.stringify(result);
441
+ pgTelemetry.record({
442
+ type: "prompt_get",
443
+ method: "prompts/get",
444
+ toolName: typedParams.name,
445
+ estimatedInputTokens: pgTelemetry.countTokens(pgInputPayload),
446
+ estimatedOutputTokens: pgTelemetry.countTokens(pgOutputPayload),
447
+ durationMs: Date.now() - pgStartTime
448
+ });
449
+ const era = this.detectEra(request);
450
+ const rawResult = typeof result === "object" && result !== null ? { resultType: "complete", ...result } : result;
451
+ let response = { jsonrpc: "2.0", id, result: rawResult };
452
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
453
+ response = adaptResponseForLegacyClient(response);
454
+ }
455
+ return response;
456
+ } catch (err) {
457
+ return {
458
+ jsonrpc: "2.0",
459
+ id,
460
+ error: {
461
+ code: -32e3,
462
+ message: err instanceof Error ? err.message : String(err)
463
+ }
464
+ };
465
+ }
466
+ }
467
+ case "resources/templates/list": {
468
+ const era = this.detectEra(request);
469
+ let response = {
470
+ jsonrpc: "2.0",
471
+ id,
472
+ result: {
473
+ resultType: "complete",
474
+ ttlMs: 3e5,
475
+ cacheScope: "public",
476
+ resourceTemplates: []
477
+ }
478
+ };
479
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
480
+ response = adaptResponseForLegacyClient(response);
481
+ }
482
+ return response;
483
+ }
484
+ case "subscriptions/listen": {
485
+ const era = this.detectEra(request);
486
+ let response = {
487
+ jsonrpc: "2.0",
488
+ id,
489
+ result: {
490
+ resultType: "complete"
491
+ }
492
+ };
493
+ if (era === "legacy" && MCP_LEGACY_SUPPORT_ENABLED) {
494
+ response = adaptResponseForLegacyClient(response);
495
+ }
496
+ return response;
497
+ }
498
+ default:
499
+ return {
500
+ jsonrpc: "2.0",
501
+ id,
502
+ error: { code: -32601, message: `Method not found: ${method}` }
503
+ };
504
+ }
505
+ }
506
+ /**
507
+ * MCP clients often send notifications/initialized then immediately tools/list.
508
+ * Start manifest discovery without blocking the notification handler.
509
+ */
510
+ kickDiscoveryAfterInitialized() {
511
+ return (async () => {
512
+ await new Promise((r) => setTimeout(r, 250));
513
+ await Promise.race([
514
+ this.refreshManifestCache(true),
515
+ new Promise((r) => setTimeout(r, 15e3))
516
+ ]).catch(() => {
517
+ });
518
+ })();
519
+ }
520
+ /**
521
+ * Discovers and caches manifests from all remote LIOP providers in the mesh.
522
+ * Uses Kademlia DHT to find "liop:manifest" providers, then opens
523
+ * /liop/manifest/1.0.0 protocol streams to retrieve their full metadata.
524
+ */
525
+ async refreshManifestCache(silent = false) {
526
+ if (!this.meshNode) return;
527
+ if (this.currentDiscovery) return this.currentDiscovery;
528
+ if (!silent && this.manifestCache.size > 0) {
529
+ const now = Date.now();
530
+ const allFresh = Array.from(this.manifestCache.values()).every(
531
+ ({ cachedAt }) => now - cachedAt < MANIFEST_CACHE_TTL_S * 1e3
532
+ );
533
+ if (allFresh) return;
534
+ }
535
+ this.currentDiscovery = (async () => {
536
+ try {
537
+ const prevCount = Array.from(this.manifestCache.values()).reduce(
538
+ (acc, { manifest }) => acc + manifest.tools.length,
539
+ 0
540
+ );
541
+ if (this.manifestCache.size === 0) {
542
+ for (let i = 0; i < 3; i++) {
543
+ const connections = (
544
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes for connection count
545
+ this.meshNode.node?.getConnections().length || 0
546
+ );
547
+ if (connections > 0) {
548
+ log.info(
549
+ `[LIOP-Router] P2P Connection established. Starting discovery...`
550
+ );
551
+ break;
552
+ }
553
+ log.info(
554
+ `[LIOP-Router] Waiting for P2P connections (attempt ${i + 1}/10)...`
555
+ );
556
+ await new Promise((r) => setTimeout(r, 1e3));
557
+ }
558
+ }
559
+ let providerIds = [];
560
+ const MAX_COLD_ATTEMPTS = this.manifestCache.size === 0 ? 5 : 1;
561
+ for (let coldAttempt = 0; coldAttempt < MAX_COLD_ATTEMPTS; coldAttempt++) {
562
+ for (let attempt = 0; attempt < MANIFEST_DISCOVERY_RETRIES; attempt++) {
563
+ providerIds = await this.meshNode?.discoverManifestProviders() || [];
564
+ const selfId2 = this.meshNode?.getPeerId();
565
+ const remoteIds = providerIds.filter((id) => id !== selfId2);
566
+ if (remoteIds.length > 0) break;
567
+ if (attempt < MANIFEST_DISCOVERY_RETRIES - 1) {
568
+ log.info(
569
+ `[LIOP-Router] DHT discovery attempt ${attempt + 1}/${MANIFEST_DISCOVERY_RETRIES}...`
570
+ );
571
+ await new Promise((r) => setTimeout(r, 1e3));
572
+ }
573
+ }
574
+ const activePeers = (
575
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
576
+ this.meshNode.node?.getConnections().map(
577
+ (c) => c.remotePeer.toString()
578
+ ) || []
579
+ );
580
+ if (activePeers.length > 0) {
581
+ providerIds = Array.from(/* @__PURE__ */ new Set([...providerIds, ...activePeers]));
582
+ }
583
+ const selfIdEnd = this.meshNode?.getPeerId();
584
+ const remoteIdsEnd = providerIds.filter((id) => id !== selfIdEnd);
585
+ if (remoteIdsEnd.length > 0) break;
586
+ if (coldAttempt < MAX_COLD_ATTEMPTS - 1) {
587
+ log.info(
588
+ `[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${coldAttempt + 1}/${MAX_COLD_ATTEMPTS})...`
589
+ );
590
+ await new Promise((r) => setTimeout(r, 1e3));
591
+ }
592
+ }
593
+ if (providerIds.length === 0) {
594
+ log.info(
595
+ `[LIOP-Router] No manifest providers found after all attempts.`
596
+ );
597
+ return;
598
+ }
599
+ if (!silent) {
600
+ log.info(
601
+ `[LIOP-Router] Discovered ${providerIds.length} candidate manifest providers`
602
+ );
603
+ }
604
+ const connectedPeers = new Set(
605
+ // biome-ignore lint/suspicious/noExplicitAny: internal node access for fast peer ordering
606
+ (this.meshNode.node?.getConnections?.() || []).map(
607
+ (c) => c.remotePeer.toString()
608
+ )
609
+ );
610
+ providerIds = [...providerIds].sort((a, b) => {
611
+ const aConnected = connectedPeers.has(a) ? 1 : 0;
612
+ const bConnected = connectedPeers.has(b) ? 1 : 0;
613
+ return bConnected - aConnected;
614
+ });
615
+ let successCount = 0;
616
+ let errorCount = 0;
617
+ let cacheUpdated = false;
618
+ const selfId = this.meshNode?.getPeerId();
619
+ const eligiblePeers = providerIds.filter((peerId) => {
620
+ if (!this.meshNode) return false;
621
+ if (peerId === selfId) return false;
622
+ if (this.shouldSkipManifestQuery(peerId)) return false;
623
+ const cached = this.manifestCache.get(peerId);
624
+ if (cached && Date.now() - cached.cachedAt < MANIFEST_CACHE_TTL_S * 1e3) {
625
+ successCount++;
626
+ return false;
627
+ }
628
+ return true;
629
+ });
630
+ const queryResults = await Promise.allSettled(
631
+ eligiblePeers.map(async (peerId) => {
632
+ if (!this.meshNode) return null;
633
+ log.info(`[LIOP-Router] Querying manifest from: ${peerId}`);
634
+ return {
635
+ peerId,
636
+ manifest: await this.meshNode.queryManifest(peerId)
637
+ };
638
+ })
639
+ );
640
+ for (const result of queryResults) {
641
+ if (result.status === "fulfilled" && result.value?.manifest) {
642
+ const { peerId, manifest } = result.value;
643
+ if (manifest.pqcSignature && manifest.pqcPublicKey) {
644
+ const isValid = Dilithium65Wrapper.verifyManifest(
645
+ manifest,
646
+ manifest.pqcSignature,
647
+ manifest.pqcPublicKey
648
+ );
649
+ if (!isValid) {
650
+ log.warn(
651
+ `[LIOP-Router] \u26A0\uFE0F Tampered manifest rejected for peer ${peerId} (ML-DSA-65 signature invalid)`
652
+ );
653
+ this.recordManifestQueryFailure(peerId);
654
+ errorCount++;
655
+ continue;
656
+ }
657
+ log.info(
658
+ `[LIOP-Router] \u{1F512} ML-DSA-65 (FIPS 204) Manifest attestation verified for peer ${peerId}`
659
+ );
660
+ }
661
+ this.manifestCache.set(peerId, {
662
+ manifest,
663
+ cachedAt: Date.now()
664
+ });
665
+ this.recordManifestQuerySuccess(peerId);
666
+ cacheUpdated = true;
667
+ successCount++;
668
+ log.info(
669
+ `[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`
670
+ );
671
+ } else if (result.status === "fulfilled" && result.value) {
672
+ this.recordManifestQueryFailure(result.value.peerId);
673
+ errorCount++;
674
+ log.info(
675
+ `[LIOP-Router] Manifest query returned NULL for ${result.value.peerId}`
676
+ );
677
+ } else if (result.status === "rejected") {
678
+ errorCount++;
679
+ log.info(
680
+ `[LIOP-Router] Fatal error querying manifest:`,
681
+ result.reason instanceof Error ? result.reason.message : String(result.reason)
682
+ );
683
+ }
684
+ }
685
+ this._discoveryStats = {
686
+ candidates: providerIds.length,
687
+ success: successCount,
688
+ failures: errorCount,
689
+ lastDiscovery: Date.now()
690
+ };
691
+ if (cacheUpdated) {
692
+ const newCount = Array.from(this.manifestCache.values()).reduce(
693
+ (acc, { manifest }) => acc + manifest.tools.length,
694
+ 0
695
+ );
696
+ if (newCount !== prevCount && this.onToolsChanged) {
697
+ process.stderr.write(
698
+ "[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\n"
699
+ );
700
+ this.onToolsChanged();
701
+ }
702
+ }
703
+ } finally {
704
+ this.currentDiscovery = null;
705
+ }
706
+ })();
707
+ return this.currentDiscovery;
708
+ }
709
+ /**
710
+ * Returns the current manifest cache size for external telemetry.
711
+ * Used by the adaptive polling system to detect topology stabilization.
712
+ */
713
+ getCacheSize() {
714
+ return this.manifestCache.size;
715
+ }
716
+ /**
717
+ * Returns all remote tools discovered via the manifest protocol.
718
+ */
719
+ async getRemoteTools() {
720
+ const EXPECTED_PROVIDERS = Number.parseInt(
721
+ process.env.LIOP_EXPECTED_PROVIDERS ?? "1",
722
+ 10
723
+ );
724
+ if (this.manifestCache.size < EXPECTED_PROVIDERS && this.meshNode) {
725
+ const initialTimeoutMs = Number.parseInt(
726
+ process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS ?? "8000",
727
+ 10
728
+ );
729
+ const boundedTimeoutMs = Number.isFinite(initialTimeoutMs) && initialTimeoutMs > 0 ? initialTimeoutMs : 12e3;
730
+ const deadline = Date.now() + boundedTimeoutMs;
731
+ let stableCount = 0;
732
+ let lastCacheSize = -1;
733
+ while (Date.now() < deadline) {
734
+ if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
735
+ await Promise.race([
736
+ this.refreshManifestCache(true),
737
+ new Promise((resolve) => setTimeout(resolve, 3e3))
738
+ ]).catch(() => {
739
+ });
740
+ if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
741
+ if (this.manifestCache.size === lastCacheSize) {
742
+ stableCount++;
743
+ if (stableCount >= 3 && this.manifestCache.size > 0) {
744
+ log.info(
745
+ `[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${EXPECTED_PROVIDERS}. Proceeding with available mesh.`
746
+ );
747
+ break;
748
+ }
749
+ } else {
750
+ stableCount = 0;
751
+ lastCacheSize = this.manifestCache.size;
752
+ }
753
+ await new Promise((r) => setTimeout(r, 1e3));
754
+ }
755
+ if (this.manifestCache.size < EXPECTED_PROVIDERS) {
756
+ log.info(
757
+ `[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${EXPECTED_PROVIDERS} providers. Some tools may be unavailable. Check Docker containers.`
758
+ );
759
+ this.refreshManifestCache(true).catch(() => {
760
+ });
761
+ }
762
+ }
763
+ const tools = [];
764
+ const seenNames = /* @__PURE__ */ new Set();
765
+ const localToolNames = new Set(
766
+ this.liopServer.listTools().map((t) => t.name)
767
+ );
768
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
769
+ for (const tool of manifest.tools) {
770
+ if (tool.name === "LiopMeshStatus") continue;
771
+ let finalName = tool.name;
772
+ if (seenNames.has(tool.name) || localToolNames.has(tool.name)) {
773
+ finalName = `${tool.name}_${peerId.slice(-4)}`;
774
+ }
775
+ seenNames.add(finalName);
776
+ const providerName = manifest.serverInfo?.name || "Unknown Provider";
777
+ const baseDesc = tool.description || `Remote tool from ${providerName}`;
778
+ const cleanTool = {
779
+ name: finalName,
780
+ description: mcpCompactToolDescriptions() ? stripVerboseLiopToolDescription(baseDesc) : baseDesc,
781
+ inputSchema: tool.inputSchema || {
782
+ type: "object",
783
+ properties: {}
784
+ }
785
+ };
786
+ if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.type) {
787
+ cleanTool.inputSchema.type = "object";
788
+ }
789
+ if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.properties) {
790
+ cleanTool.inputSchema.properties = {};
791
+ }
792
+ let blueprint = "";
793
+ if (manifest.taxonomy) {
794
+ blueprint = `
795
+ [LIOP-DOMAIN: ${manifest.taxonomy.domain}]`;
796
+ }
797
+ const properties = cleanTool.inputSchema.properties || {};
798
+ let envelopeDoc = "";
799
+ if (!mcpCompactToolDescriptions() && properties.payload) {
800
+ envelopeDoc = `
801
+ [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`;
802
+ }
803
+ if (!mcpCompactToolDescriptions() && cleanTool.description.includes("STRICT SCHEMA ADHERENCE")) {
804
+ cleanTool.description = cleanTool.description.replace(
805
+ "STRICT SCHEMA ADHERENCE:",
806
+ "[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"
807
+ );
808
+ }
809
+ const originStamp = mcpCompactToolDescriptions() ? `
810
+ (Peer: ${peerId.slice(-8)})${blueprint}` : `
811
+ (Origin: ${peerId.slice(-8)})${blueprint}${envelopeDoc}`;
812
+ cleanTool.description = `${cleanTool.description}${originStamp}`;
813
+ tools.push(cleanTool);
814
+ }
815
+ }
816
+ return tools;
817
+ }
818
+ /**
819
+ * Returns all remote resources discovered via the manifest protocol.
820
+ */
821
+ async getRemoteResources() {
822
+ if (!this.currentDiscovery) {
823
+ this.refreshManifestCache(true).catch(() => {
824
+ });
825
+ }
826
+ const resources = [];
827
+ const seenUris = new Set(this.liopServer.listResources().map((r) => r.uri));
828
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
829
+ for (const resource of manifest.resources) {
830
+ if (!seenUris.has(resource.uri)) {
831
+ const augmentedResource = { ...resource };
832
+ const providerName = manifest.serverInfo?.name || "Unknown Provider";
833
+ let blueprint = "";
834
+ if (manifest.taxonomy) {
835
+ blueprint = `
836
+
837
+ [LIOP Zero-Trust Blueprint]
838
+ Domain: ${manifest.taxonomy.domain}
839
+ Clearance Tier: ${manifest.taxonomy.clearanceTier}`;
840
+ if (manifest.taxonomy.executionTypes && manifest.taxonomy.executionTypes.length > 0) {
841
+ blueprint += `
842
+ Execution Types: ${manifest.taxonomy.executionTypes.join(", ")}`;
843
+ }
844
+ }
845
+ const originStamp = `
846
+
847
+ [LIOP Zero-Trust Origin]
848
+ Provider: ${providerName}
849
+ Network ID: ${peerId}${blueprint}`;
850
+ if (augmentedResource.uri.startsWith("liop://schema/")) {
851
+ augmentedResource.name = `[SCHEMA] ${augmentedResource.name}`;
852
+ augmentedResource.description = `[CRITICAL SCHEMA] ${augmentedResource.description || "Data Dictionary for Zero-Shot Autonomy"}${originStamp}`;
853
+ } else {
854
+ augmentedResource.description = augmentedResource.description ? `${augmentedResource.description}${originStamp}` : originStamp.trim();
855
+ }
856
+ resources.push(augmentedResource);
857
+ seenUris.add(resource.uri);
858
+ }
859
+ }
860
+ }
861
+ return resources;
862
+ }
863
+ /**
864
+ * Resolves the gRPC target (host:port) AND the peerId for a given tool name
865
+ * by searching the manifest cache. Supports exact names and suffixed names.
866
+ */
867
+ resolveManifestTarget(toolName) {
868
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
869
+ const tool = manifest.tools.find((t) => t.name === toolName);
870
+ if (tool) {
871
+ return {
872
+ peerId,
873
+ originalToolName: toolName
874
+ };
875
+ }
876
+ }
877
+ const parts = toolName.split("_");
878
+ if (parts.length > 1) {
879
+ const suffix = parts.pop();
880
+ const baseName = parts.join("_");
881
+ for (const [peerId, { manifest }] of this.manifestCache.entries()) {
882
+ if (peerId.endsWith(suffix || "")) {
883
+ const tool = manifest.tools.find((t) => t.name === baseName);
884
+ if (tool) {
885
+ return {
886
+ peerId,
887
+ originalToolName: baseName
888
+ };
889
+ }
890
+ }
891
+ }
892
+ }
893
+ return null;
894
+ }
895
+ /**
896
+ * Redacts a PeerID for external-facing diagnostics.
897
+ * LIOP_DIAGNOSTIC_LEVEL controls verbosity:
898
+ * - "redacted" (default): truncated to last 8 chars
899
+ * - "full": complete PeerID (development only)
900
+ */
901
+ redactPeerId(peerId) {
902
+ const level = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
903
+ if (level === "full") return peerId;
904
+ return `***${peerId.slice(-8)}`;
905
+ }
906
+ async transcodeMcpToLiop(id, params, token) {
907
+ const toolName = params.name;
908
+ if (toolName === "LiopMeshStatus") {
909
+ this.refreshManifestCache(true).catch(() => {
910
+ });
911
+ const stats = this._discoveryStats || {
912
+ candidates: 0,
913
+ success: 0,
914
+ failures: 0
915
+ };
916
+ const providerCount = this.manifestCache.size;
917
+ const meshState = this.meshNode ? "Active" : "Offline";
918
+ const cachedTools = Array.from(this.manifestCache.values()).reduce(
919
+ (acc, { manifest }) => acc + manifest.tools.length,
920
+ 0
921
+ );
922
+ const connections = this.meshNode ? (
923
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
924
+ this.meshNode.node?.getConnections().length
925
+ ) : 0;
926
+ const bootstrapNodes = this.meshNode && // biome-ignore lint/suspicious/noExplicitAny: access internal config
927
+ this.meshNode.config?.bootstrapNodes ? (
928
+ // biome-ignore lint/suspicious/noExplicitAny: access internal config
929
+ this.meshNode.config.bootstrapNodes
930
+ ) : [];
931
+ const bootstrapCount = bootstrapNodes.length;
932
+ const diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
933
+ const showBootstraps = diagLevel !== "minimal";
934
+ const bootstrapList = showBootstraps ? bootstrapNodes.map((addr) => {
935
+ const parts = addr.split("/");
936
+ const id2 = parts[parts.length - 1];
937
+ return ` \u2022 ${id2 ? id2.slice(-8) : "Unknown"} (bootstrap)`;
938
+ }).join("\n") : "";
939
+ const routingTableSize = this.meshNode ? (
940
+ // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
941
+ this.meshNode.getRoutingTableSize()
942
+ ) : 0;
943
+ const rawPeerId = this.meshNode?.getPeerId() || "Offline";
944
+ const localPeerId = rawPeerId === "Offline" ? rawPeerId : this.redactPeerId(rawPeerId);
945
+ const cachedToolList = Array.from(this.manifestCache.entries()).flatMap(
946
+ ([peerId, { manifest }]) => manifest.tools.map(
947
+ (t) => ` \u2022 ${t.name} (from origin: ${this.redactPeerId(peerId)})`
948
+ )
949
+ ).join("\n");
950
+ const statusText = [
951
+ `LIOP Mesh Status: ${meshState === "Active" ? "Active" : "Offline"}`,
952
+ `Local Agent Identity: ${localPeerId}`,
953
+ `Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,
954
+ showBootstraps && bootstrapCount > 0 ? `
955
+ Active Bootstraps:
956
+ ${bootstrapList}
957
+ ` : "",
958
+ `Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,
959
+ `Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,
960
+ cachedTools > 0 ? `
961
+ Discovered Remote Tools (Zero-Trust Origins):
962
+ ${cachedToolList}` : "\nNo remote tools discovered yet.",
963
+ // [Token Economy] Telemetry block (only appears when operations exist)
964
+ TokenTelemetryEngine.getInstance().formatStatusBlock()
965
+ ].filter((line) => line !== "").join("\n");
966
+ const diagTelemetry = TokenTelemetryEngine.getInstance();
967
+ diagTelemetry.record({
968
+ type: "diagnostic",
969
+ method: "tools/call",
970
+ toolName: "LiopMeshStatus",
971
+ estimatedInputTokens: 0,
972
+ estimatedOutputTokens: diagTelemetry.countTokens(statusText)
973
+ });
974
+ return {
975
+ jsonrpc: "2.0",
976
+ id,
977
+ result: {
978
+ content: [
979
+ {
980
+ type: "text",
981
+ text: statusText
982
+ }
983
+ ]
984
+ }
985
+ };
986
+ }
987
+ const isLocal = this.liopServer.listTools().some((t) => t.name === toolName);
988
+ if (!isLocal && this.meshNode) {
989
+ let target = this.resolveManifestTarget(toolName);
990
+ if (!target) {
991
+ await this.refreshManifestCache();
992
+ target = this.resolveManifestTarget(toolName);
993
+ }
994
+ if (target) {
995
+ log.info(
996
+ `[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`
997
+ );
998
+ const manifestEntry = this.manifestCache.get(target.peerId);
999
+ let effectiveToken = token;
1000
+ if (manifestEntry?.manifest.authRequired) {
1001
+ const resolvedToken = token || await this.getOrAcquireMeshAgentToken(target.peerId);
1002
+ if (!resolvedToken) {
1003
+ const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
1004
+ const slug = manifestEntry.manifest.tokenSlug;
1005
+ const shortId = target.peerId.slice(-8).toUpperCase();
1006
+ const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
1007
+ return {
1008
+ jsonrpc: "2.0",
1009
+ id,
1010
+ result: {
1011
+ content: [
1012
+ {
1013
+ type: "text",
1014
+ text: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`
1015
+ }
1016
+ ],
1017
+ isError: true
1018
+ }
1019
+ };
1020
+ }
1021
+ effectiveToken = resolvedToken;
1022
+ }
1023
+ return this.routeToRemoteProvider(
1024
+ id,
1025
+ target.originalToolName,
1026
+ target.peerId,
1027
+ params,
1028
+ effectiveToken
1029
+ );
1030
+ }
1031
+ let providers = [];
1032
+ for (let i = 0; i < 3; i++) {
1033
+ providers = await this.meshNode.findProviders(toolName);
1034
+ if (providers.length > 0) break;
1035
+ if (i < 2) await new Promise((r) => setTimeout(r, 1e3));
1036
+ }
1037
+ if (providers.length > 0) {
1038
+ return this.routeToRemoteProvider(
1039
+ id,
1040
+ toolName,
1041
+ providers[0],
1042
+ params,
1043
+ token
1044
+ );
1045
+ }
1046
+ }
1047
+ if (isLocal) {
1048
+ try {
1049
+ const localStartTime = Date.now();
1050
+ const result = await this.liopServer.callTool({
1051
+ name: toolName,
1052
+ arguments: params.arguments || {}
1053
+ });
1054
+ const localTelemetry = TokenTelemetryEngine.getInstance();
1055
+ const localInputPayload = JSON.stringify(params.arguments || {});
1056
+ const localOutputPayload = JSON.stringify(result);
1057
+ localTelemetry.record({
1058
+ type: "tool_call",
1059
+ method: "tools/call",
1060
+ toolName,
1061
+ estimatedInputTokens: localTelemetry.countTokens(localInputPayload),
1062
+ estimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),
1063
+ durationMs: Date.now() - localStartTime
1064
+ });
1065
+ return { jsonrpc: "2.0", id, result };
1066
+ } catch (err) {
1067
+ return {
1068
+ jsonrpc: "2.0",
1069
+ id,
1070
+ error: {
1071
+ code: -32e3,
1072
+ message: err instanceof Error ? err.message : String(err)
1073
+ }
1074
+ };
1075
+ }
1076
+ }
1077
+ return {
1078
+ jsonrpc: "2.0",
1079
+ id,
1080
+ error: {
1081
+ code: -32002,
1082
+ message: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`
1083
+ }
1084
+ };
1085
+ }
1086
+ async routeToRemoteProvider(id, toolName, peerId, params, token) {
1087
+ if (!this.meshNode)
1088
+ return {
1089
+ jsonrpc: "2.0",
1090
+ id,
1091
+ error: { code: -32603, message: "Mesh Node inactive" }
1092
+ };
1093
+ let manifestEntry = this.manifestCache.get(peerId);
1094
+ let grpcPort = this.defaultRpcPort;
1095
+ if (manifestEntry) {
1096
+ grpcPort = manifestEntry.manifest.grpcPort;
1097
+ } else {
1098
+ const manifest = await this.meshNode.queryManifest(peerId);
1099
+ if (manifest) {
1100
+ grpcPort = manifest.grpcPort;
1101
+ this.manifestCache.set(peerId, {
1102
+ manifest,
1103
+ cachedAt: Date.now()
1104
+ });
1105
+ manifestEntry = this.manifestCache.get(peerId);
1106
+ }
1107
+ }
1108
+ const addrs = await this.meshNode.resolvePeer(peerId);
1109
+ const nexusUrl = process.env.LIOP_NEXUS_URL || "";
1110
+ const isDockerDemo = nexusUrl.includes("127.0.0.1:13000") || nexusUrl.includes("localhost:13000") || nexusUrl.includes("127.0.0.1:13001") || nexusUrl.includes("localhost:13001");
1111
+ const isDockerPort = addrs.some(
1112
+ (a) => a.includes("13001") || a.includes("13003") || a.includes("13004") || a.includes("13005") || a.includes("13011") || a.includes("13021") || a.includes("13031")
1113
+ );
1114
+ const shouldRemapGrpcPorts = process.env.LIOP_USE_PUBLISHED_GRPC_PORTS === "1" || process.env.LIOP_DOCKER_MAP === "true" || process.env.LIOP_DEV_MODE === "true" || process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || isDockerDemo || isDockerPort;
1115
+ if (shouldRemapGrpcPorts) {
1116
+ const providerName = manifestEntry?.manifest?.serverInfo?.name?.toLowerCase() || "";
1117
+ const tn = toolName.toLowerCase();
1118
+ if (providerName.includes("vault") || tn.includes("medical")) {
1119
+ grpcPort = 13011;
1120
+ } else if (providerName.includes("bank") || tn.includes("bank")) {
1121
+ grpcPort = 13021;
1122
+ } else if (providerName.includes("oracle") || tn.includes("hft") || tn.includes("market")) {
1123
+ grpcPort = 13031;
1124
+ }
1125
+ }
1126
+ let targetAddr = null;
1127
+ if (shouldRemapGrpcPorts) {
1128
+ targetAddr = `127.0.0.1:${grpcPort}`;
1129
+ } else {
1130
+ const os = await import('os');
1131
+ const localInterfaces = Object.values(os.networkInterfaces()).flat().filter((i) => i?.family === "IPv4").map((i) => i?.address);
1132
+ for (const addr of addrs) {
1133
+ const parts = addr.split("/");
1134
+ const ipIdx = parts.indexOf("ip4");
1135
+ if (ipIdx !== -1) {
1136
+ const advertisedIp = parts[ipIdx + 1];
1137
+ if (advertisedIp === "127.0.0.1" || localInterfaces.includes(advertisedIp)) {
1138
+ targetAddr = `127.0.0.1:${grpcPort}`;
1139
+ break;
1140
+ }
1141
+ if (!targetAddr) {
1142
+ targetAddr = `${advertisedIp}:${grpcPort}`;
1143
+ }
1144
+ }
1145
+ }
1146
+ }
1147
+ if (!targetAddr) {
1148
+ targetAddr = `127.0.0.1:${grpcPort}`;
1149
+ }
1150
+ log.info(
1151
+ `[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`
1152
+ );
1153
+ const remoteClient = new liopV1.LogicMesh(
1154
+ targetAddr,
1155
+ createChannelCredentials(),
1156
+ GRPC_CHANNEL_OPTIONS
1157
+ );
1158
+ return this.performTranscoding(
1159
+ id,
1160
+ remoteClient,
1161
+ toolName,
1162
+ params,
1163
+ peerId,
1164
+ token
1165
+ );
1166
+ }
1167
+ /** Cached M2M token for dynamic gateway-to-node routing */
1168
+ meshAgentToken;
1169
+ /**
1170
+ * Dynamically acquires an M2M access token from the Nexus Authorization Server.
1171
+ * If peerId is provided, checks if there are node-specific environment tokens
1172
+ * before falling back to the global static token or Nexus acquisition.
1173
+ */
1174
+ async getOrAcquireMeshAgentToken(peerId) {
1175
+ if (peerId) {
1176
+ const manifestEntry = this.manifestCache.get(peerId);
1177
+ const providerName = manifestEntry?.manifest.serverInfo?.name?.toLowerCase() || "";
1178
+ let nodeToken;
1179
+ const slug = manifestEntry?.manifest.tokenSlug;
1180
+ if (slug) {
1181
+ const envKey = `LIOP_TOKEN_${slug}`;
1182
+ nodeToken = process.env[envKey] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];
1183
+ log.info(
1184
+ `[LIOP-Router] Step0 tokenSlug=${slug} envKey=${envKey} found=${!!nodeToken} peer=${peerId.slice(-8)}`
1185
+ );
1186
+ } else {
1187
+ log.info(
1188
+ `[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${peerId.slice(-8)} provider=${providerName}`
1189
+ );
1190
+ }
1191
+ if (!nodeToken) {
1192
+ const shortId = peerId.slice(-8).toUpperCase();
1193
+ nodeToken = process.env[`LIOP_TOKEN_${shortId}`] || process.env[`LIOP_OAUTH_TOKEN_${shortId}`];
1194
+ }
1195
+ if (!nodeToken && providerName) {
1196
+ const cleanName = providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
1197
+ nodeToken = process.env[`LIOP_TOKEN_${cleanName}`] || process.env[`LIOP_OAUTH_TOKEN_${cleanName}`];
1198
+ }
1199
+ if (nodeToken) {
1200
+ log.info(
1201
+ `[LIOP-Router] Resolved node-specific token for peer ${peerId.slice(-8)} (${providerName || "unknown"})`
1202
+ );
1203
+ return nodeToken;
1204
+ }
1205
+ }
1206
+ if (this.meshAgentToken) return this.meshAgentToken;
1207
+ const staticToken = process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;
1208
+ if (staticToken) {
1209
+ this.meshAgentToken = staticToken;
1210
+ return this.meshAgentToken;
1211
+ }
1212
+ const nexusUrl = process.env.LIOP_NEXUS_URL;
1213
+ if (!nexusUrl) return void 0;
1214
+ const clientId = process.env.LIOP_OAUTH_CLIENT_ID || process.env.LIOP_CLIENT_ID || "liop-mesh-agent";
1215
+ const clientSecret = process.env.LIOP_OAUTH_CLIENT_SECRET || process.env.LIOP_CLIENT_SECRET || "dev-secret-change-me";
1216
+ const audience = process.env.LIOP_OAUTH_AUDIENCE || process.env.LIOP_AUDIENCE || "urn:liop:mesh:api";
1217
+ try {
1218
+ const baseUrl = nexusUrl.endsWith("/oidc") ? nexusUrl : `${nexusUrl}/oidc`;
1219
+ const tokenUrl = `${baseUrl}/token`;
1220
+ log.info(
1221
+ `[LIOP-Router] Proactively acquiring M2M token from Nexus: ${tokenUrl}`
1222
+ );
1223
+ const params = new URLSearchParams({
1224
+ grant_type: "client_credentials",
1225
+ scope: "liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",
1226
+ resource: audience,
1227
+ client_id: clientId,
1228
+ client_secret: clientSecret
1229
+ });
1230
+ const response = await fetch(tokenUrl, {
1231
+ method: "POST",
1232
+ headers: {
1233
+ "Content-Type": "application/x-www-form-urlencoded"
1234
+ },
1235
+ body: params.toString()
1236
+ });
1237
+ if (!response.ok) {
1238
+ const text = await response.text();
1239
+ log.warn(
1240
+ `[LIOP-Router] M2M Token acquisition failed: ${response.status} ${text}`
1241
+ );
1242
+ return void 0;
1243
+ }
1244
+ const data = await response.json();
1245
+ if (data.access_token) {
1246
+ this.meshAgentToken = data.access_token;
1247
+ log.info(
1248
+ "[LIOP-Router] M2M Token acquired successfully for router routing."
1249
+ );
1250
+ return this.meshAgentToken;
1251
+ }
1252
+ } catch (err) {
1253
+ log.warn(
1254
+ `[LIOP-Router] Failed to acquire M2M token: ${err instanceof Error ? err.message : String(err)}`
1255
+ );
1256
+ }
1257
+ return void 0;
1258
+ }
1259
+ async performTranscoding(id, client, toolName, params, peerId, token) {
1260
+ const capabilityHash = toolName;
1261
+ const proofOfIntent = this.meshNode ? await this.meshNode.sign(Buffer.from(capabilityHash)) : Buffer.from([]);
1262
+ const transcodingStartTime = Date.now();
1263
+ let activeToken = token;
1264
+ if (!activeToken) {
1265
+ activeToken = await this.getOrAcquireMeshAgentToken(peerId);
1266
+ }
1267
+ if (peerId) {
1268
+ const manifestEntry = this.manifestCache.get(peerId);
1269
+ if (manifestEntry?.manifest.authRequired && !activeToken) {
1270
+ const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
1271
+ const slug = manifestEntry.manifest.tokenSlug;
1272
+ const shortId = peerId.slice(-8).toUpperCase();
1273
+ const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
1274
+ return {
1275
+ jsonrpc: "2.0",
1276
+ id,
1277
+ result: {
1278
+ content: [
1279
+ {
1280
+ type: "text",
1281
+ text: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`
1282
+ }
1283
+ ],
1284
+ isError: true
1285
+ }
1286
+ };
1287
+ }
1288
+ }
1289
+ return new Promise((resolve) => {
1290
+ const metadata = new grpc.Metadata();
1291
+ if (activeToken) {
1292
+ metadata.add("authorization", `Bearer ${activeToken}`);
1293
+ }
1294
+ client.negotiateIntent(
1295
+ {
1296
+ agent_did: `did:liop:${this.meshNode?.getPeerId() || "mcp-proxy"}`,
1297
+ capability_hash: capabilityHash,
1298
+ proof_of_intent: proofOfIntent
1299
+ },
1300
+ metadata,
1301
+ async (err, response) => {
1302
+ if (err || !response.accepted) {
1303
+ try {
1304
+ toolCallErrorsTotal.inc({
1305
+ capability: toolName,
1306
+ error_type: "handshake_failed"
1307
+ });
1308
+ } catch {
1309
+ }
1310
+ return resolve({
1311
+ jsonrpc: "2.0",
1312
+ id,
1313
+ result: {
1314
+ content: [
1315
+ {
1316
+ type: "text",
1317
+ text: `PQC Handshake Failed: ${err?.message || "Rejected"}`
1318
+ }
1319
+ ],
1320
+ isError: true
1321
+ }
1322
+ });
1323
+ }
1324
+ const pqcStart = performance.now();
1325
+ const { ciphertext, sharedSecret } = await Kyber768Wrapper.encapsulateAsymmetric(
1326
+ response.kyber_public_key
1327
+ );
1328
+ const pqcDuration = performance.now() - pqcStart;
1329
+ try {
1330
+ pqcHandshakeDurationMs.observe({ tool: toolName }, pqcDuration);
1331
+ pqcHandshakesTotal.inc({
1332
+ algorithm: "ml-kem-768",
1333
+ status: "success"
1334
+ });
1335
+ } catch {
1336
+ }
1337
+ const embeddedArgs = params?.arguments ?? (params?.payload !== void 0 ? params : {});
1338
+ const embeddedArgsJson = JSON.stringify(embeddedArgs);
1339
+ const proxyLogic = `return { "__liop_proxy_tool": "${toolName}", "__liop_proxy_args": ${embeddedArgsJson} };`;
1340
+ const nonce = crypto.randomBytes(12);
1341
+ const sealedLogic = this.encryptWithNonce(
1342
+ Buffer.from(proxyLogic),
1343
+ sharedSecret,
1344
+ nonce
1345
+ );
1346
+ const metadataCall = new grpc.Metadata();
1347
+ if (activeToken) {
1348
+ metadataCall.add("authorization", `Bearer ${activeToken}`);
1349
+ }
1350
+ const call = client.executeLogic(
1351
+ {
1352
+ session_token: response.session_token,
1353
+ wasm_binary: new Uint8Array(sealedLogic),
1354
+ inputs: {},
1355
+ pqc_ciphertext: ciphertext,
1356
+ aes_nonce: nonce
1357
+ },
1358
+ metadataCall
1359
+ );
1360
+ let resultBody = "";
1361
+ let lastResponse = null;
1362
+ call.on("data", (grpcRes) => {
1363
+ resultBody += grpcRes.semantic_evidence;
1364
+ lastResponse = grpcRes;
1365
+ });
1366
+ call.on("end", async () => {
1367
+ try {
1368
+ if (lastResponse) {
1369
+ if (!lastResponse.is_error) {
1370
+ const proofHex = Buffer.from(
1371
+ lastResponse.cryptographic_proof
1372
+ ).toString("hex");
1373
+ const isValid = await this.verifier.verifyZkReceipt(
1374
+ Buffer.from(proxyLogic),
1375
+ proofHex,
1376
+ Buffer.from(lastResponse.zk_receipt),
1377
+ Buffer.from(sharedSecret),
1378
+ resultBody
1379
+ );
1380
+ try {
1381
+ zkVerificationsTotal.inc({
1382
+ status: isValid ? "valid" : "invalid"
1383
+ });
1384
+ } catch {
1385
+ }
1386
+ if (!isValid) {
1387
+ try {
1388
+ toolCallErrorsTotal.inc({
1389
+ capability: toolName,
1390
+ error_type: "cryptographic_audit_failed"
1391
+ });
1392
+ } catch {
1393
+ }
1394
+ return resolve({
1395
+ jsonrpc: "2.0",
1396
+ id,
1397
+ result: {
1398
+ content: [
1399
+ {
1400
+ type: "text",
1401
+ text: "SECURITY ALERT: Remote response failed cryptographic integrity audit."
1402
+ }
1403
+ ],
1404
+ isError: true
1405
+ }
1406
+ });
1407
+ }
1408
+ } else {
1409
+ try {
1410
+ toolCallErrorsTotal.inc({
1411
+ capability: toolName,
1412
+ error_type: "remote_execution_error"
1413
+ });
1414
+ } catch {
1415
+ }
1416
+ }
1417
+ }
1418
+ const parsedResult = JSON.parse(resultBody);
1419
+ const remoteTelemetry = TokenTelemetryEngine.getInstance();
1420
+ remoteTelemetry.record({
1421
+ type: "tool_call",
1422
+ method: "tools/call",
1423
+ toolName,
1424
+ peerId,
1425
+ estimatedInputTokens: remoteTelemetry.countTokens(embeddedArgsJson),
1426
+ estimatedOutputTokens: remoteTelemetry.countTokens(resultBody),
1427
+ durationMs: Date.now() - transcodingStartTime
1428
+ });
1429
+ try {
1430
+ wireEgressBytesTotal.inc(
1431
+ { capability: toolName },
1432
+ Buffer.byteLength(resultBody)
1433
+ );
1434
+ } catch {
1435
+ }
1436
+ resolve({ jsonrpc: "2.0", id, result: parsedResult });
1437
+ } catch (_e) {
1438
+ resolve({
1439
+ jsonrpc: "2.0",
1440
+ id,
1441
+ result: { content: [{ type: "text", text: resultBody }] }
1442
+ });
1443
+ }
1444
+ });
1445
+ call.on("error", (e) => {
1446
+ try {
1447
+ toolCallErrorsTotal.inc({
1448
+ capability: toolName,
1449
+ error_type: "grpc_stream_error"
1450
+ });
1451
+ } catch {
1452
+ }
1453
+ resolve({
1454
+ jsonrpc: "2.0",
1455
+ id,
1456
+ result: {
1457
+ content: [
1458
+ { type: "text", text: `LIOP gRPC Error: ${e.message}` }
1459
+ ],
1460
+ isError: true
1461
+ }
1462
+ });
1463
+ });
1464
+ }
1465
+ );
1466
+ });
1467
+ }
1468
+ encryptWithNonce(payload, key, nonce) {
1469
+ const cipher = crypto.createCipheriv("aes-256-gcm", key, nonce);
1470
+ const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
1471
+ return Buffer.concat([encrypted, cipher.getAuthTag()]);
1472
+ }
1473
+ };
1474
+
1475
+ export { LiopMcpRouter };
1476
+ //# sourceMappingURL=chunk-L6J72C5X.js.map
1477
+ //# sourceMappingURL=chunk-L6J72C5X.js.map