@nekzus/liop 2.4.0-alpha.25 → 2.4.0-alpha.26

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 (61) hide show
  1. package/dist/bin/agent.js +27 -933
  2. package/dist/bridge.js +1 -5
  3. package/dist/chunk-2XHSALII.js +3 -0
  4. package/dist/chunk-2ZYX736J.js +2 -0
  5. package/dist/chunk-3WRKTVOF.js +2 -0
  6. package/dist/chunk-6KFKO6ZX.js +2 -0
  7. package/dist/chunk-6VK2XALI.js +2 -0
  8. package/dist/chunk-AYDF3IFZ.js +2 -0
  9. package/dist/chunk-CTTTLCGL.js +31 -0
  10. package/dist/chunk-ECRS6N33.js +4 -0
  11. package/dist/chunk-FDJMH4CB.js +2 -0
  12. package/dist/chunk-FTF6AMF6.js +0 -1
  13. package/dist/chunk-GWVSCZUS.js +2 -0
  14. package/dist/chunk-LEXMMIQI.js +15 -0
  15. package/dist/chunk-LM26HOJ6.js +31 -0
  16. package/dist/chunk-MQ5SU26J.js +2 -0
  17. package/dist/chunk-N35BC62H.js +2 -0
  18. package/dist/chunk-P6IJ3VBD.js +3 -0
  19. package/dist/chunk-TKLRW52V.js +2 -0
  20. package/dist/chunk-V35CXJQN.js +2 -0
  21. package/dist/chunk-WP5ER7RH.js +3 -0
  22. package/dist/chunk-XLVEDKM6.js +2 -0
  23. package/dist/chunk-Y675R34Z.js +2 -0
  24. package/dist/chunk-YD2AF2M6.js +46 -0
  25. package/dist/chunk-YLCNV764.js +3 -0
  26. package/dist/chunk-ZZMSFCJP.js +3 -0
  27. package/dist/client.js +1 -12
  28. package/dist/gateway.js +1 -13
  29. package/dist/index.js +4 -320
  30. package/dist/kyber-PULV7PQX.js +2 -0
  31. package/dist/mesh.js +1 -5
  32. package/dist/server.js +1 -10
  33. package/dist/types.js +1 -3
  34. package/dist/verifier-J4NQYZX5.js +2 -0
  35. package/dist/workers/logic-execution.js +1 -355
  36. package/dist/workers/zk-verifier.js +1 -275
  37. package/package.json +1 -1
  38. package/dist/chunk-3664H3CV.js +0 -136
  39. package/dist/chunk-3QH44NKZ.js +0 -115
  40. package/dist/chunk-6MYJBM2E.js +0 -818
  41. package/dist/chunk-7PITYWOV.js +0 -68
  42. package/dist/chunk-DSOB2JKM.js +0 -1507
  43. package/dist/chunk-ET6VRUK2.js +0 -58
  44. package/dist/chunk-FIVRGOA4.js +0 -280
  45. package/dist/chunk-IHKKWXHJ.js +0 -876
  46. package/dist/chunk-IK7CGWAZ.js +0 -24
  47. package/dist/chunk-JPWC6XG6.js +0 -941
  48. package/dist/chunk-K3DGJLUY.js +0 -106
  49. package/dist/chunk-KR5UZUEY.js +0 -98
  50. package/dist/chunk-NXCAFF73.js +0 -59
  51. package/dist/chunk-Q3FKHJ3B.js +0 -345
  52. package/dist/chunk-R52TZEIL.js +0 -426
  53. package/dist/chunk-S3RAZTEM.js +0 -807
  54. package/dist/chunk-V47P2AQR.js +0 -281
  55. package/dist/chunk-WXOWJXY6.js +0 -564
  56. package/dist/chunk-WXYDFCIW.js +0 -293
  57. package/dist/chunk-Y62GORQF.js +0 -51
  58. package/dist/chunk-ZP3VVXOI.js +0 -66
  59. package/dist/chunk-ZU3WVVLC.js +0 -3752
  60. package/dist/kyber-CGOA7Q6A.js +0 -3
  61. package/dist/verifier-55HW6AFN.js +0 -6
@@ -1,1507 +0,0 @@
1
- import { LiopVerifier } from './chunk-WXYDFCIW.js';
2
- import { Kyber768Wrapper } from './chunk-7PITYWOV.js';
3
- import { authorizeRequest } from './chunk-NXCAFF73.js';
4
- import { Dilithium65Wrapper } from './chunk-3664H3CV.js';
5
- import { TokenTelemetryEngine, liopV1, createChannelCredentials, GRPC_CHANNEL_OPTIONS } from './chunk-JPWC6XG6.js';
6
- import { toolCallsTotal, toolCallErrorsTotal, pqcHandshakeDurationMs, pqcHandshakesTotal, zkVerificationsTotal, wireEgressBytesTotal } from './chunk-Q3FKHJ3B.js';
7
- import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, isLegacyRequest, adaptResponseForLegacyClient, MCP_PROTOCOL_VERSION_LEGACY, buildLegacyInitializeResponse, TOOL_ALIASES, normalizeToolArguments } from './chunk-KR5UZUEY.js';
8
- import { log } from './chunk-K3DGJLUY.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
- await Promise.allSettled(
631
- eligiblePeers.map(async (peerId) => {
632
- if (!this.meshNode) return;
633
- log.info(`[LIOP-Router] Querying manifest from: ${peerId}`);
634
- try {
635
- const manifest = await this.meshNode.queryManifest(peerId);
636
- if (manifest) {
637
- if (manifest.pqcSignature && manifest.pqcPublicKey) {
638
- const isValid = Dilithium65Wrapper.verifyManifest(
639
- manifest,
640
- manifest.pqcSignature,
641
- manifest.pqcPublicKey
642
- );
643
- if (!isValid) {
644
- log.warn(
645
- `[LIOP-Router] \u26A0\uFE0F Tampered manifest rejected for peer ${peerId} (ML-DSA-65 signature invalid)`
646
- );
647
- this.recordManifestQueryFailure(peerId);
648
- errorCount++;
649
- return;
650
- }
651
- log.info(
652
- `[LIOP-Router] \u{1F512} ML-DSA-65 (FIPS 204) Manifest attestation verified for peer ${peerId}`
653
- );
654
- }
655
- this.manifestCache.set(peerId, {
656
- manifest,
657
- cachedAt: Date.now()
658
- });
659
- this.recordManifestQuerySuccess(peerId);
660
- cacheUpdated = true;
661
- successCount++;
662
- log.info(
663
- `[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`
664
- );
665
- } else {
666
- this.recordManifestQueryFailure(peerId);
667
- errorCount++;
668
- log.info(
669
- `[LIOP-Router] Manifest query returned NULL for ${peerId}`
670
- );
671
- }
672
- } catch (err) {
673
- errorCount++;
674
- log.info(
675
- `[LIOP-Router] Fatal error querying manifest:`,
676
- err instanceof Error ? err.message : String(err)
677
- );
678
- }
679
- })
680
- );
681
- this._discoveryStats = {
682
- candidates: providerIds.length,
683
- success: successCount,
684
- failures: errorCount,
685
- lastDiscovery: Date.now()
686
- };
687
- if (cacheUpdated) {
688
- const newCount = Array.from(this.manifestCache.values()).reduce(
689
- (acc, { manifest }) => acc + manifest.tools.length,
690
- 0
691
- );
692
- if (newCount !== prevCount && this.onToolsChanged) {
693
- process.stderr.write(
694
- "[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\n"
695
- );
696
- this.onToolsChanged();
697
- }
698
- }
699
- } finally {
700
- this.currentDiscovery = null;
701
- }
702
- })();
703
- return this.currentDiscovery;
704
- }
705
- /**
706
- * Returns the current manifest cache size for external telemetry.
707
- * Used by the adaptive polling system to detect topology stabilization.
708
- */
709
- getCacheSize() {
710
- return this.manifestCache.size;
711
- }
712
- /**
713
- * Returns all remote tools discovered via the manifest protocol.
714
- */
715
- async getRemoteTools() {
716
- const EXPECTED_PROVIDERS = Number.parseInt(
717
- process.env.LIOP_EXPECTED_PROVIDERS ?? "1",
718
- 10
719
- );
720
- if (this.manifestCache.size < EXPECTED_PROVIDERS && this.meshNode) {
721
- const initialTimeoutMs = Number.parseInt(
722
- process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS ?? "8000",
723
- 10
724
- );
725
- const boundedTimeoutMs = Number.isFinite(initialTimeoutMs) && initialTimeoutMs > 0 ? initialTimeoutMs : 12e3;
726
- const deadline = Date.now() + boundedTimeoutMs;
727
- let stableCount = 0;
728
- let lastCacheSize = -1;
729
- while (Date.now() < deadline) {
730
- if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
731
- await Promise.race([
732
- this.refreshManifestCache(true),
733
- new Promise((resolve) => setTimeout(resolve, 3e3))
734
- ]).catch(() => {
735
- });
736
- if (this.manifestCache.size >= EXPECTED_PROVIDERS) break;
737
- if (this.manifestCache.size === lastCacheSize) {
738
- stableCount++;
739
- if (stableCount >= 3 && this.manifestCache.size > 0) {
740
- log.info(
741
- `[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${EXPECTED_PROVIDERS}. Proceeding with available mesh.`
742
- );
743
- break;
744
- }
745
- } else {
746
- stableCount = 0;
747
- lastCacheSize = this.manifestCache.size;
748
- }
749
- await new Promise((r) => setTimeout(r, 1e3));
750
- }
751
- if (this.manifestCache.size < EXPECTED_PROVIDERS) {
752
- log.info(
753
- `[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${EXPECTED_PROVIDERS} providers. Some tools may be unavailable. Check Docker containers.`
754
- );
755
- this.refreshManifestCache(true).catch(() => {
756
- });
757
- }
758
- }
759
- const tools = [];
760
- const seenNames = /* @__PURE__ */ new Set();
761
- const localToolNames = new Set(
762
- this.liopServer.listTools().map((t) => t.name)
763
- );
764
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
765
- for (const tool of manifest.tools) {
766
- if (tool.name === "LiopMeshStatus") continue;
767
- let finalName = tool.name;
768
- if (seenNames.has(tool.name) || localToolNames.has(tool.name)) {
769
- finalName = `${tool.name}_${peerId.slice(-4)}`;
770
- }
771
- seenNames.add(finalName);
772
- const providerName = manifest.serverInfo?.name || "Unknown Provider";
773
- const baseDesc = tool.description || `Remote tool from ${providerName}`;
774
- const cleanTool = {
775
- name: finalName,
776
- description: mcpCompactToolDescriptions() ? stripVerboseLiopToolDescription(baseDesc) : baseDesc,
777
- inputSchema: tool.inputSchema || {
778
- type: "object",
779
- properties: {}
780
- }
781
- };
782
- if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.type) {
783
- cleanTool.inputSchema.type = "object";
784
- }
785
- if (typeof cleanTool.inputSchema === "object" && !cleanTool.inputSchema.properties) {
786
- cleanTool.inputSchema.properties = {};
787
- }
788
- let blueprint = "";
789
- if (manifest.taxonomy) {
790
- blueprint = `
791
- [LIOP-DOMAIN: ${manifest.taxonomy.domain}]`;
792
- }
793
- const properties = cleanTool.inputSchema.properties || {};
794
- let envelopeDoc = "";
795
- if (!mcpCompactToolDescriptions() && properties.payload) {
796
- envelopeDoc = `
797
- [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`;
798
- }
799
- if (!mcpCompactToolDescriptions() && cleanTool.description.includes("STRICT SCHEMA ADHERENCE")) {
800
- cleanTool.description = cleanTool.description.replace(
801
- "STRICT SCHEMA ADHERENCE:",
802
- "[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"
803
- );
804
- }
805
- const originStamp = mcpCompactToolDescriptions() ? `
806
- (Peer: ${peerId.slice(-8)})${blueprint}` : `
807
- (Origin: ${peerId.slice(-8)})${blueprint}${envelopeDoc}`;
808
- cleanTool.description = `${cleanTool.description}${originStamp}`;
809
- tools.push(cleanTool);
810
- }
811
- }
812
- return tools;
813
- }
814
- /**
815
- * Returns all remote resources discovered via the manifest protocol.
816
- */
817
- async getRemoteResources() {
818
- if (!this.currentDiscovery) {
819
- this.refreshManifestCache(true).catch(() => {
820
- });
821
- }
822
- const resources = [];
823
- const seenUris = new Set(this.liopServer.listResources().map((r) => r.uri));
824
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
825
- for (const resource of manifest.resources) {
826
- if (!seenUris.has(resource.uri)) {
827
- const augmentedResource = { ...resource };
828
- const providerName = manifest.serverInfo?.name || "Unknown Provider";
829
- let blueprint = "";
830
- if (manifest.taxonomy) {
831
- blueprint = `
832
-
833
- [LIOP Zero-Trust Blueprint]
834
- Domain: ${manifest.taxonomy.domain}
835
- Clearance Tier: ${manifest.taxonomy.clearanceTier}`;
836
- if (manifest.taxonomy.executionTypes && manifest.taxonomy.executionTypes.length > 0) {
837
- blueprint += `
838
- Execution Types: ${manifest.taxonomy.executionTypes.join(", ")}`;
839
- }
840
- }
841
- const originStamp = `
842
-
843
- [LIOP Zero-Trust Origin]
844
- Provider: ${providerName}
845
- Network ID: ${peerId}${blueprint}`;
846
- if (augmentedResource.uri.startsWith("liop://schema/")) {
847
- augmentedResource.name = `[SCHEMA] ${augmentedResource.name}`;
848
- augmentedResource.description = `[CRITICAL SCHEMA] ${augmentedResource.description || "Data Dictionary for Zero-Shot Autonomy"}${originStamp}`;
849
- } else {
850
- augmentedResource.description = augmentedResource.description ? `${augmentedResource.description}${originStamp}` : originStamp.trim();
851
- }
852
- resources.push(augmentedResource);
853
- seenUris.add(resource.uri);
854
- }
855
- }
856
- }
857
- return resources;
858
- }
859
- /**
860
- * Resolves the gRPC target (host:port) AND the peerId for a given tool name
861
- * by searching the manifest cache. Supports exact names and suffixed names.
862
- */
863
- resolveManifestTarget(toolName) {
864
- const targetCanonical = TOOL_ALIASES[toolName] || toolName;
865
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
866
- const tool = manifest.tools.find(
867
- (t) => t.name === toolName || t.name === targetCanonical
868
- );
869
- if (tool) {
870
- return {
871
- peerId,
872
- originalToolName: tool.name
873
- };
874
- }
875
- }
876
- const parts = toolName.split("_");
877
- if (parts.length > 1) {
878
- const suffix = parts.pop();
879
- const baseName = parts.join("_");
880
- const canonicalBase = TOOL_ALIASES[baseName] || baseName;
881
- for (const [peerId, { manifest }] of this.manifestCache.entries()) {
882
- if (peerId.endsWith(suffix || "")) {
883
- const tool = manifest.tools.find(
884
- (t) => t.name === baseName || t.name === canonicalBase
885
- );
886
- if (tool) {
887
- return {
888
- peerId,
889
- originalToolName: tool.name
890
- };
891
- }
892
- }
893
- }
894
- }
895
- return null;
896
- }
897
- /**
898
- * Redacts a PeerID for external-facing diagnostics.
899
- * LIOP_DIAGNOSTIC_LEVEL controls verbosity:
900
- * - "redacted" (default): truncated to last 8 chars
901
- * - "full": complete PeerID (development only)
902
- */
903
- redactPeerId(peerId) {
904
- const level = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
905
- if (level === "full") return peerId;
906
- return `***${peerId.slice(-8)}`;
907
- }
908
- async transcodeMcpToLiop(id, params, token) {
909
- if (params?.arguments) {
910
- params.arguments = normalizeToolArguments(params.arguments);
911
- }
912
- const toolName = params.name;
913
- if (toolName === "LiopMeshStatus") {
914
- this.refreshManifestCache(true).catch(() => {
915
- });
916
- const stats = this._discoveryStats || {
917
- candidates: 0,
918
- success: 0,
919
- failures: 0
920
- };
921
- const providerCount = this.manifestCache.size;
922
- const meshState = this.meshNode ? "Active" : "Offline";
923
- const cachedTools = Array.from(this.manifestCache.values()).reduce(
924
- (acc, { manifest }) => acc + manifest.tools.length,
925
- 0
926
- );
927
- const connections = this.meshNode ? (
928
- // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
929
- this.meshNode.node?.getConnections().length
930
- ) : 0;
931
- const bootstrapNodes = this.meshNode && // biome-ignore lint/suspicious/noExplicitAny: access internal config
932
- this.meshNode.config?.bootstrapNodes ? (
933
- // biome-ignore lint/suspicious/noExplicitAny: access internal config
934
- this.meshNode.config.bootstrapNodes
935
- ) : [];
936
- const bootstrapCount = bootstrapNodes.length;
937
- const diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || "redacted";
938
- const showBootstraps = diagLevel !== "minimal";
939
- const bootstrapList = showBootstraps ? bootstrapNodes.map((addr) => {
940
- const parts = addr.split("/");
941
- const id2 = parts[parts.length - 1];
942
- return ` \u2022 ${id2 ? id2.slice(-8) : "Unknown"} (bootstrap)`;
943
- }).join("\n") : "";
944
- const routingTableSize = this.meshNode ? (
945
- // biome-ignore lint/suspicious/noExplicitAny: access internal nodes
946
- this.meshNode.getRoutingTableSize()
947
- ) : 0;
948
- const rawPeerId = this.meshNode?.getPeerId() || "Offline";
949
- const localPeerId = rawPeerId === "Offline" ? rawPeerId : this.redactPeerId(rawPeerId);
950
- const cachedToolList = Array.from(this.manifestCache.entries()).flatMap(
951
- ([peerId, { manifest }]) => manifest.tools.map(
952
- (t) => ` \u2022 ${t.name} (from origin: ${this.redactPeerId(peerId)})`
953
- )
954
- ).join("\n");
955
- const statusText = [
956
- `LIOP Mesh Status: ${meshState === "Active" ? "Active" : "Offline"}`,
957
- `Local Agent Identity: ${localPeerId}`,
958
- `Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,
959
- showBootstraps && bootstrapCount > 0 ? `
960
- Active Bootstraps:
961
- ${bootstrapList}
962
- ` : "",
963
- `Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,
964
- `Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,
965
- cachedTools > 0 ? `
966
- Discovered Remote Tools (Zero-Trust Origins):
967
- ${cachedToolList}` : "\nNo remote tools discovered yet.",
968
- // [Token Economy] Telemetry block (only appears when operations exist)
969
- TokenTelemetryEngine.getInstance().formatStatusBlock()
970
- ].filter((line) => line !== "").join("\n");
971
- const diagTelemetry = TokenTelemetryEngine.getInstance();
972
- diagTelemetry.record({
973
- type: "diagnostic",
974
- method: "tools/call",
975
- toolName: "LiopMeshStatus",
976
- estimatedInputTokens: 0,
977
- estimatedOutputTokens: diagTelemetry.countTokens(statusText)
978
- });
979
- return {
980
- jsonrpc: "2.0",
981
- id,
982
- result: {
983
- content: [
984
- {
985
- type: "text",
986
- text: statusText
987
- }
988
- ]
989
- }
990
- };
991
- }
992
- const isLocal = this.liopServer.listTools().some((t) => t.name === toolName);
993
- if (!isLocal && this.meshNode) {
994
- let target = this.resolveManifestTarget(toolName);
995
- if (!target) {
996
- await this.refreshManifestCache();
997
- target = this.resolveManifestTarget(toolName);
998
- }
999
- if (target) {
1000
- log.info(
1001
- `[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`
1002
- );
1003
- const manifestEntry = this.manifestCache.get(target.peerId);
1004
- let effectiveToken = token;
1005
- if (manifestEntry?.manifest.authRequired) {
1006
- const resolvedToken = token || await this.getOrAcquireMeshAgentToken(target.peerId);
1007
- if (!resolvedToken) {
1008
- const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
1009
- const slug = manifestEntry.manifest.tokenSlug;
1010
- const shortId = target.peerId.slice(-8).toUpperCase();
1011
- const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
1012
- return {
1013
- jsonrpc: "2.0",
1014
- id,
1015
- result: {
1016
- content: [
1017
- {
1018
- type: "text",
1019
- 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.`
1020
- }
1021
- ],
1022
- isError: true
1023
- }
1024
- };
1025
- }
1026
- effectiveToken = resolvedToken;
1027
- }
1028
- return this.routeToRemoteProvider(
1029
- id,
1030
- target.originalToolName,
1031
- target.peerId,
1032
- params,
1033
- effectiveToken
1034
- );
1035
- }
1036
- let providers = [];
1037
- for (let i = 0; i < 3; i++) {
1038
- providers = await this.meshNode.findProviders(toolName);
1039
- if (providers.length > 0) break;
1040
- if (i < 2) await new Promise((r) => setTimeout(r, 1e3));
1041
- }
1042
- if (providers.length > 0) {
1043
- return this.routeToRemoteProvider(
1044
- id,
1045
- toolName,
1046
- providers[0],
1047
- params,
1048
- token
1049
- );
1050
- }
1051
- }
1052
- if (isLocal) {
1053
- try {
1054
- const localStartTime = Date.now();
1055
- const result = await this.liopServer.callTool({
1056
- name: toolName,
1057
- arguments: params.arguments || {}
1058
- });
1059
- const localTelemetry = TokenTelemetryEngine.getInstance();
1060
- const localInputPayload = JSON.stringify(params.arguments || {});
1061
- const localOutputPayload = JSON.stringify(result);
1062
- let originDatasetTokens;
1063
- const sandboxRecords = this.liopServer.getSandboxData();
1064
- if (sandboxRecords && sandboxRecords.length > 0) {
1065
- originDatasetTokens = localTelemetry.countTokens(
1066
- JSON.stringify(sandboxRecords)
1067
- );
1068
- }
1069
- localTelemetry.record({
1070
- type: "tool_call",
1071
- method: "tools/call",
1072
- toolName,
1073
- estimatedInputTokens: localTelemetry.countTokens(localInputPayload),
1074
- estimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),
1075
- durationMs: Date.now() - localStartTime,
1076
- originDatasetTokens
1077
- });
1078
- toolCallsTotal.inc({
1079
- capability: toolName,
1080
- tool: toolName,
1081
- status: result.isError ? "error" : "success",
1082
- role: "executor"
1083
- });
1084
- return { jsonrpc: "2.0", id, result };
1085
- } catch (err) {
1086
- return {
1087
- jsonrpc: "2.0",
1088
- id,
1089
- error: {
1090
- code: -32e3,
1091
- message: err instanceof Error ? err.message : String(err)
1092
- }
1093
- };
1094
- }
1095
- }
1096
- return {
1097
- jsonrpc: "2.0",
1098
- id,
1099
- error: {
1100
- code: -32002,
1101
- message: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`
1102
- }
1103
- };
1104
- }
1105
- async routeToRemoteProvider(id, toolName, peerId, params, token) {
1106
- if (!this.meshNode)
1107
- return {
1108
- jsonrpc: "2.0",
1109
- id,
1110
- error: { code: -32603, message: "Mesh Node inactive" }
1111
- };
1112
- let manifestEntry = this.manifestCache.get(peerId);
1113
- let grpcPort = this.defaultRpcPort;
1114
- if (manifestEntry) {
1115
- grpcPort = manifestEntry.manifest.grpcPort;
1116
- } else {
1117
- const manifest = await this.meshNode.queryManifest(peerId);
1118
- if (manifest) {
1119
- grpcPort = manifest.grpcPort;
1120
- this.manifestCache.set(peerId, {
1121
- manifest,
1122
- cachedAt: Date.now()
1123
- });
1124
- manifestEntry = this.manifestCache.get(peerId);
1125
- }
1126
- }
1127
- const addrs = await this.meshNode.resolvePeer(peerId);
1128
- const nexusUrl = process.env.LIOP_NEXUS_URL || "";
1129
- const isDockerDemo = nexusUrl.includes("127.0.0.1:13000") || nexusUrl.includes("localhost:13000") || nexusUrl.includes("127.0.0.1:13001") || nexusUrl.includes("localhost:13001");
1130
- const isDockerPort = addrs.some(
1131
- (a) => a.includes("13001") || a.includes("13003") || a.includes("13004") || a.includes("13005") || a.includes("13011") || a.includes("13021") || a.includes("13031")
1132
- );
1133
- 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;
1134
- if (shouldRemapGrpcPorts) {
1135
- const providerName = manifestEntry?.manifest?.serverInfo?.name?.toLowerCase() || "";
1136
- const tn = toolName.toLowerCase();
1137
- if (providerName.includes("vault") || tn.includes("medical")) {
1138
- grpcPort = 13011;
1139
- } else if (providerName.includes("bank") || tn.includes("bank")) {
1140
- grpcPort = 13021;
1141
- } else if (providerName.includes("oracle") || tn.includes("hft") || tn.includes("market")) {
1142
- grpcPort = 13031;
1143
- }
1144
- }
1145
- let targetAddr = null;
1146
- if (shouldRemapGrpcPorts) {
1147
- targetAddr = `127.0.0.1:${grpcPort}`;
1148
- } else {
1149
- const os = await import('os');
1150
- const localInterfaces = Object.values(os.networkInterfaces()).flat().filter((i) => i?.family === "IPv4").map((i) => i?.address);
1151
- for (const addr of addrs) {
1152
- const parts = addr.split("/");
1153
- const ipIdx = parts.indexOf("ip4");
1154
- if (ipIdx !== -1) {
1155
- const advertisedIp = parts[ipIdx + 1];
1156
- if (advertisedIp === "127.0.0.1" || localInterfaces.includes(advertisedIp)) {
1157
- targetAddr = `127.0.0.1:${grpcPort}`;
1158
- break;
1159
- }
1160
- if (!targetAddr) {
1161
- targetAddr = `${advertisedIp}:${grpcPort}`;
1162
- }
1163
- }
1164
- }
1165
- }
1166
- if (!targetAddr) {
1167
- targetAddr = `127.0.0.1:${grpcPort}`;
1168
- }
1169
- log.info(
1170
- `[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`
1171
- );
1172
- const remoteClient = new liopV1.LogicMesh(
1173
- targetAddr,
1174
- createChannelCredentials({ insecure: true, suppressWarning: true }),
1175
- GRPC_CHANNEL_OPTIONS
1176
- );
1177
- return this.performTranscoding(
1178
- id,
1179
- remoteClient,
1180
- toolName,
1181
- params,
1182
- peerId,
1183
- token
1184
- );
1185
- }
1186
- /** Cached M2M token for dynamic gateway-to-node routing */
1187
- meshAgentToken;
1188
- /**
1189
- * Dynamically acquires an M2M access token from the Nexus Authorization Server.
1190
- * If peerId is provided, checks if there are node-specific environment tokens
1191
- * before falling back to the global static token or Nexus acquisition.
1192
- */
1193
- async getOrAcquireMeshAgentToken(peerId) {
1194
- if (peerId) {
1195
- const manifestEntry = this.manifestCache.get(peerId);
1196
- const providerName = manifestEntry?.manifest.serverInfo?.name?.toLowerCase() || "";
1197
- let nodeToken;
1198
- const slug = manifestEntry?.manifest.tokenSlug;
1199
- if (slug) {
1200
- const envKey = `LIOP_TOKEN_${slug}`;
1201
- nodeToken = process.env[envKey] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];
1202
- log.info(
1203
- `[LIOP-Router] Step0 tokenSlug=${slug} envKey=${envKey} found=${!!nodeToken} peer=${peerId.slice(-8)}`
1204
- );
1205
- } else {
1206
- log.info(
1207
- `[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${peerId.slice(-8)} provider=${providerName}`
1208
- );
1209
- }
1210
- if (!nodeToken) {
1211
- const shortId = peerId.slice(-8).toUpperCase();
1212
- nodeToken = process.env[`LIOP_TOKEN_${shortId}`] || process.env[`LIOP_OAUTH_TOKEN_${shortId}`];
1213
- }
1214
- if (!nodeToken && providerName) {
1215
- const cleanName = providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
1216
- nodeToken = process.env[`LIOP_TOKEN_${cleanName}`] || process.env[`LIOP_OAUTH_TOKEN_${cleanName}`];
1217
- }
1218
- if (nodeToken) {
1219
- log.info(
1220
- `[LIOP-Router] Resolved node-specific token for peer ${peerId.slice(-8)} (${providerName || "unknown"})`
1221
- );
1222
- return nodeToken;
1223
- }
1224
- }
1225
- if (this.meshAgentToken) return this.meshAgentToken;
1226
- const staticToken = process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;
1227
- if (staticToken) {
1228
- this.meshAgentToken = staticToken;
1229
- return this.meshAgentToken;
1230
- }
1231
- const nexusUrl = process.env.LIOP_NEXUS_URL;
1232
- if (!nexusUrl) return void 0;
1233
- const clientId = process.env.LIOP_OAUTH_CLIENT_ID || process.env.LIOP_CLIENT_ID || "liop-mesh-agent";
1234
- const clientSecret = process.env.LIOP_OAUTH_CLIENT_SECRET || process.env.LIOP_CLIENT_SECRET || "dev-secret-change-me";
1235
- const audience = process.env.LIOP_OAUTH_AUDIENCE || process.env.LIOP_AUDIENCE || "urn:liop:mesh:api";
1236
- try {
1237
- const baseUrl = nexusUrl.endsWith("/oidc") ? nexusUrl : `${nexusUrl}/oidc`;
1238
- const tokenUrl = `${baseUrl}/token`;
1239
- log.info(
1240
- `[LIOP-Router] Proactively acquiring M2M token from Nexus: ${tokenUrl}`
1241
- );
1242
- const params = new URLSearchParams({
1243
- grant_type: "client_credentials",
1244
- scope: "liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",
1245
- resource: audience,
1246
- client_id: clientId,
1247
- client_secret: clientSecret
1248
- });
1249
- const response = await fetch(tokenUrl, {
1250
- method: "POST",
1251
- headers: {
1252
- "Content-Type": "application/x-www-form-urlencoded"
1253
- },
1254
- body: params.toString()
1255
- });
1256
- if (!response.ok) {
1257
- const text = await response.text();
1258
- log.warn(
1259
- `[LIOP-Router] M2M Token acquisition failed: ${response.status} ${text}`
1260
- );
1261
- return void 0;
1262
- }
1263
- const data = await response.json();
1264
- if (data.access_token) {
1265
- this.meshAgentToken = data.access_token;
1266
- log.info(
1267
- "[LIOP-Router] M2M Token acquired successfully for router routing."
1268
- );
1269
- return this.meshAgentToken;
1270
- }
1271
- } catch (err) {
1272
- log.warn(
1273
- `[LIOP-Router] Failed to acquire M2M token: ${err instanceof Error ? err.message : String(err)}`
1274
- );
1275
- }
1276
- return void 0;
1277
- }
1278
- async performTranscoding(id, client, toolName, params, peerId, token) {
1279
- const capabilityHash = toolName;
1280
- const proofOfIntent = this.meshNode ? await this.meshNode.sign(Buffer.from(capabilityHash)) : Buffer.from([]);
1281
- const transcodingStartTime = Date.now();
1282
- let activeToken = token;
1283
- if (!activeToken) {
1284
- activeToken = await this.getOrAcquireMeshAgentToken(peerId);
1285
- }
1286
- if (peerId) {
1287
- const manifestEntry = this.manifestCache.get(peerId);
1288
- if (manifestEntry?.manifest.authRequired && !activeToken) {
1289
- const providerName = manifestEntry.manifest.serverInfo?.name?.toLowerCase() || "unknown";
1290
- const slug = manifestEntry.manifest.tokenSlug;
1291
- const shortId = peerId.slice(-8).toUpperCase();
1292
- const primaryVar = slug ? `LIOP_TOKEN_${slug}` : `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_")}`;
1293
- return {
1294
- jsonrpc: "2.0",
1295
- id,
1296
- result: {
1297
- content: [
1298
- {
1299
- type: "text",
1300
- 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.`
1301
- }
1302
- ],
1303
- isError: true
1304
- }
1305
- };
1306
- }
1307
- }
1308
- return new Promise((resolve) => {
1309
- const metadata = new grpc.Metadata();
1310
- if (activeToken) {
1311
- metadata.add("authorization", `Bearer ${activeToken}`);
1312
- }
1313
- client.negotiateIntent(
1314
- {
1315
- agent_did: `did:liop:${this.meshNode?.getPeerId() || "mcp-proxy"}`,
1316
- capability_hash: capabilityHash,
1317
- proof_of_intent: proofOfIntent
1318
- },
1319
- metadata,
1320
- async (err, response) => {
1321
- if (err || !response.accepted) {
1322
- try {
1323
- toolCallErrorsTotal.inc({
1324
- capability: toolName,
1325
- error_type: "handshake_failed"
1326
- });
1327
- } catch {
1328
- }
1329
- return resolve({
1330
- jsonrpc: "2.0",
1331
- id,
1332
- result: {
1333
- content: [
1334
- {
1335
- type: "text",
1336
- text: `PQC Handshake Failed: ${err?.message || "Rejected"}`
1337
- }
1338
- ],
1339
- isError: true
1340
- }
1341
- });
1342
- }
1343
- const pqcStart = performance.now();
1344
- const { ciphertext, sharedSecret } = await Kyber768Wrapper.encapsulateAsymmetric(
1345
- response.kyber_public_key
1346
- );
1347
- const pqcDuration = performance.now() - pqcStart;
1348
- try {
1349
- pqcHandshakeDurationMs.observe({ tool: toolName }, pqcDuration);
1350
- pqcHandshakesTotal.inc({
1351
- algorithm: "ml-kem-768",
1352
- status: "success"
1353
- });
1354
- } catch {
1355
- }
1356
- const embeddedArgs = params?.arguments ?? (params?.payload !== void 0 ? params : {});
1357
- const embeddedArgsJson = JSON.stringify(embeddedArgs);
1358
- const proxyLogic = `return { "__liop_proxy_tool": "${toolName}", "__liop_proxy_args": ${embeddedArgsJson} };`;
1359
- const nonce = crypto.randomBytes(12);
1360
- const sealedLogic = this.encryptWithNonce(
1361
- Buffer.from(proxyLogic),
1362
- sharedSecret,
1363
- nonce
1364
- );
1365
- const metadataCall = new grpc.Metadata();
1366
- if (activeToken) {
1367
- metadataCall.add("authorization", `Bearer ${activeToken}`);
1368
- }
1369
- const call = client.executeLogic(
1370
- {
1371
- session_token: response.session_token,
1372
- wasm_binary: new Uint8Array(sealedLogic),
1373
- inputs: {},
1374
- pqc_ciphertext: ciphertext,
1375
- aes_nonce: nonce
1376
- },
1377
- metadataCall
1378
- );
1379
- let resultBody = "";
1380
- let lastResponse = null;
1381
- call.on("data", (grpcRes) => {
1382
- resultBody += grpcRes.semantic_evidence;
1383
- lastResponse = grpcRes;
1384
- });
1385
- call.on("end", async () => {
1386
- try {
1387
- if (lastResponse) {
1388
- if (!lastResponse.is_error) {
1389
- const proofHex = Buffer.from(
1390
- lastResponse.cryptographic_proof
1391
- ).toString("hex");
1392
- const receiptBuf = Buffer.from(lastResponse.zk_receipt);
1393
- const isV2 = receiptBuf.length > 0 && receiptBuf[0] === 2;
1394
- const isValid = await this.verifier.verifyZkReceipt(
1395
- Buffer.from(proxyLogic),
1396
- proofHex,
1397
- receiptBuf,
1398
- {
1399
- sessionSecret: Buffer.from(sharedSecret),
1400
- expectedOutput: resultBody,
1401
- zkPolicy: isV2 ? "required" : "none"
1402
- }
1403
- );
1404
- try {
1405
- zkVerificationsTotal.inc({
1406
- status: isValid ? "valid" : "invalid"
1407
- });
1408
- } catch {
1409
- }
1410
- if (!isValid) {
1411
- try {
1412
- toolCallErrorsTotal.inc({
1413
- capability: toolName,
1414
- error_type: "cryptographic_audit_failed"
1415
- });
1416
- } catch {
1417
- }
1418
- return resolve({
1419
- jsonrpc: "2.0",
1420
- id,
1421
- result: {
1422
- content: [
1423
- {
1424
- type: "text",
1425
- text: "SECURITY ALERT: Remote response failed cryptographic integrity audit."
1426
- }
1427
- ],
1428
- isError: true
1429
- }
1430
- });
1431
- }
1432
- } else {
1433
- try {
1434
- toolCallErrorsTotal.inc({
1435
- capability: toolName,
1436
- error_type: "remote_execution_error"
1437
- });
1438
- } catch {
1439
- }
1440
- }
1441
- }
1442
- const parsedResult = JSON.parse(resultBody);
1443
- const remoteTelemetry = TokenTelemetryEngine.getInstance();
1444
- remoteTelemetry.record({
1445
- type: "tool_call",
1446
- method: "tools/call",
1447
- toolName,
1448
- peerId,
1449
- estimatedInputTokens: remoteTelemetry.countTokens(embeddedArgsJson),
1450
- estimatedOutputTokens: remoteTelemetry.countTokens(resultBody),
1451
- durationMs: Date.now() - transcodingStartTime
1452
- });
1453
- try {
1454
- wireEgressBytesTotal.inc(
1455
- { capability: toolName },
1456
- Buffer.byteLength(resultBody)
1457
- );
1458
- } catch {
1459
- }
1460
- toolCallsTotal.inc({
1461
- capability: toolName,
1462
- tool: toolName,
1463
- status: parsedResult.isError ? "error" : "success",
1464
- role: "proxy"
1465
- });
1466
- resolve({ jsonrpc: "2.0", id, result: parsedResult });
1467
- } catch (_e) {
1468
- resolve({
1469
- jsonrpc: "2.0",
1470
- id,
1471
- result: { content: [{ type: "text", text: resultBody }] }
1472
- });
1473
- }
1474
- });
1475
- call.on("error", (e) => {
1476
- try {
1477
- toolCallErrorsTotal.inc({
1478
- capability: toolName,
1479
- error_type: "grpc_stream_error"
1480
- });
1481
- } catch {
1482
- }
1483
- resolve({
1484
- jsonrpc: "2.0",
1485
- id,
1486
- result: {
1487
- content: [
1488
- { type: "text", text: `LIOP gRPC Error: ${e.message}` }
1489
- ],
1490
- isError: true
1491
- }
1492
- });
1493
- });
1494
- }
1495
- );
1496
- });
1497
- }
1498
- encryptWithNonce(payload, key, nonce) {
1499
- const cipher = crypto.createCipheriv("aes-256-gcm", key, nonce);
1500
- const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
1501
- return Buffer.concat([encrypted, cipher.getAuthTag()]);
1502
- }
1503
- };
1504
-
1505
- export { LiopMcpRouter };
1506
- //# sourceMappingURL=chunk-DSOB2JKM.js.map
1507
- //# sourceMappingURL=chunk-DSOB2JKM.js.map