@nekzus/liop 2.0.0-alpha.2 → 2.0.0-alpha.20

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 (59) hide show
  1. package/README.md +58 -24
  2. package/dist/bin/agent.js +3 -3
  3. package/dist/bin/agent.js.map +1 -1
  4. package/dist/bridge.js +1 -1
  5. package/dist/chunk-2MGFSIXN.js +2 -0
  6. package/dist/chunk-2MGFSIXN.js.map +1 -0
  7. package/dist/chunk-4C666HHU.js +2 -0
  8. package/dist/chunk-4C666HHU.js.map +1 -0
  9. package/dist/{chunk-PPCOS2NU.js → chunk-7I6YJS3C.js} +2 -2
  10. package/dist/{chunk-PPCOS2NU.js.map → chunk-7I6YJS3C.js.map} +1 -1
  11. package/dist/{chunk-HNDVAKEK.js → chunk-C65RM2A3.js} +6 -6
  12. package/dist/chunk-C65RM2A3.js.map +1 -0
  13. package/dist/{chunk-P52IE4L6.js → chunk-ISKM7EAL.js} +2 -2
  14. package/dist/{chunk-P52IE4L6.js.map → chunk-ISKM7EAL.js.map} +1 -1
  15. package/dist/{chunk-XLVRRGOX.js → chunk-NWZ5KZDN.js} +3 -3
  16. package/dist/chunk-NWZ5KZDN.js.map +1 -0
  17. package/dist/{chunk-PIBCW4BD.js → chunk-SYMZRXI3.js} +3 -3
  18. package/dist/{chunk-PIBCW4BD.js.map → chunk-SYMZRXI3.js.map} +1 -1
  19. package/dist/chunk-TNMS53OP.js +2 -0
  20. package/dist/chunk-TNMS53OP.js.map +1 -0
  21. package/dist/chunk-UK7OBXGZ.js +33 -0
  22. package/dist/chunk-UK7OBXGZ.js.map +1 -0
  23. package/dist/chunk-V5MKJT6S.js +2 -0
  24. package/dist/chunk-V5MKJT6S.js.map +1 -0
  25. package/dist/chunk-WG353XMU.js +43 -0
  26. package/dist/chunk-WG353XMU.js.map +1 -0
  27. package/dist/client.d.ts +1 -1
  28. package/dist/client.js +1 -1
  29. package/dist/gateway.js +1 -1
  30. package/dist/{index-CyxNLlz7.d.ts → index-BihN3W-K.d.ts} +9 -0
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +1 -1
  33. package/dist/index.js.map +1 -1
  34. package/dist/kyber-NONMBQNH.js +2 -0
  35. package/dist/{kyber-2WDOTUQX.js.map → kyber-NONMBQNH.js.map} +1 -1
  36. package/dist/mesh.js +1 -1
  37. package/dist/server.d.ts +18 -0
  38. package/dist/server.js +1 -1
  39. package/dist/types.js +1 -1
  40. package/dist/verifier-6M7GY4TW.js +2 -0
  41. package/dist/{verifier-RQRYXA4C.js.map → verifier-6M7GY4TW.js.map} +1 -1
  42. package/dist/workers/logic-execution.d.ts +5 -0
  43. package/dist/workers/logic-execution.js +1 -1
  44. package/dist/workers/logic-execution.js.map +1 -1
  45. package/dist/workers/zk-verifier.js +1 -1
  46. package/dist/workers/zk-verifier.js.map +1 -1
  47. package/package.json +54 -49
  48. package/dist/chunk-4ABAFG44.js +0 -33
  49. package/dist/chunk-4ABAFG44.js.map +0 -1
  50. package/dist/chunk-HM77MWB6.js +0 -2
  51. package/dist/chunk-HM77MWB6.js.map +0 -1
  52. package/dist/chunk-HNDVAKEK.js.map +0 -1
  53. package/dist/chunk-HQZHZM6U.js +0 -2
  54. package/dist/chunk-HQZHZM6U.js.map +0 -1
  55. package/dist/chunk-X6FJATUE.js +0 -29
  56. package/dist/chunk-X6FJATUE.js.map +0 -1
  57. package/dist/chunk-XLVRRGOX.js.map +0 -1
  58. package/dist/kyber-2WDOTUQX.js +0 -2
  59. package/dist/verifier-RQRYXA4C.js +0 -2
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/economy/estimator.ts","../src/economy/otel.ts","../src/economy/telemetry.ts","../src/utils/mcpCompact.ts","../src/gateway/router.ts"],"names":["RealTokenEstimator","countFn","setMergeCacheSizeFn","text","HeuristicTokenEstimator","createTokenEstimator","mod","estimator","log","createSyncTokenEstimator","METER_NAME","METER_VERSION","TOKEN_USAGE_BUCKETS","DURATION_BUCKETS","LiopOTelBridge","meter","metrics","err","noopHistogram","tokens","tokenType","operationName","toolName","durationMs","error","OTEL_OPERATION_MAP","TokenTelemetryEngine","_TokenTelemetryEngine","real","content","metric","fullMetric","otelOp","sum","op","breakdown","key","existing","totalDuration","newCalls","report","uptimeStr","totalCombined","byType","typeEntries","typeLines","type","data","idx","prefix","outputPart","toolReport","toolEntries","toolLines","name","durationPart","timedOps","avgLatency","otelStatus","ms","seconds","minutes","remainingSeconds","hours","remainingMinutes","mcpCompactToolDescriptions","v","stripVerboseLiopToolDescription","description","d","markers","m","i","MANIFEST_CACHE_TTL_S","MANIFEST_DISCOVERY_RETRIES","LiopMcpRouter","_LiopMcpRouter","liopServer","meshNode","defaultRpcPort","remoteTools","t","resources","r","LiopVerifier","peerId","state","now","failures","backoff","request","method","params","id","localTools","listedLocals","allTools","telemetry","toolsPayload","toolsResponsePayload","localResources","remoteResources","allResources","rlTelemetry","rlPayload","typedParams","rrStartTime","result","rrTelemetry","rrOutputPayload","targetUri","manifest","remoteResource","promptsList","plTelemetry","plPayload","pgStartTime","pgTelemetry","pgInputPayload","pgOutputPayload","silent","cachedAt","prevCount","acc","providerIds","MAX_COLD_ATTEMPTS","coldAttempt","attempt","selfId","activePeers","c","selfIdEnd","connectedPeers","a","b","aConnected","successCount","errorCount","cacheUpdated","eligiblePeers","cached","queryResults","EXPECTED_PROVIDERS","initialTimeoutMs","boundedTimeoutMs","deadline","stableCount","lastCacheSize","resolve","tools","seenNames","localToolNames","tool","finalName","providerName","baseDesc","cleanTool","blueprint","properties","envelopeDoc","originStamp","seenUris","resource","augmentedResource","parts","suffix","baseName","stats","providerCount","meshState","cachedTools","connections","bootstrapNodes","bootstrapCount","showBootstraps","bootstrapList","addr","routingTableSize","rawPeerId","localPeerId","cachedToolList","statusText","line","diagTelemetry","isLocal","target","providers","localStartTime","localTelemetry","localInputPayload","localOutputPayload","manifestEntry","grpcPort","addrs","targetAddr","os","localInterfaces","ipIdx","advertisedIp","remoteClient","liopV1","createChannelCredentials","client","capabilityHash","proofOfIntent","transcodingStartTime","response","ciphertext","sharedSecret","Kyber768Wrapper","embeddedArgsJson","proxyLogic","nonce","sealedLogic","call","resultBody","lastResponse","grpcRes","parsedResult","remoteTelemetry","e","payload","cipher","encrypted"],"mappings":"yOA0BO,IAAMA,CAAAA,CAAN,KAAmD,CAChD,IAAA,CAAO,aAER,OAAA,CAER,WAAA,CACCC,CAAAA,CACAC,CAAAA,CACC,CACD,IAAA,CAAK,QAAUD,CAAAA,CAEXC,CAAAA,EACHA,EAAoB,GAAM,EAE5B,CAEA,WAAA,CAAYC,CAAAA,CAAsB,CACjC,OAAIA,CAAAA,CAAK,MAAA,GAAW,EAAU,CAAA,CACvB,IAAA,CAAK,QAAQA,CAAI,CACzB,CACD,CAAA,CAQaC,CAAAA,CAAN,KAAwD,CACrD,IAAA,CAAO,qBAAA,CAEhB,YAAYD,CAAAA,CAAsB,CACjC,OAAIA,CAAAA,CAAK,MAAA,GAAW,CAAA,CAAU,EACvB,IAAA,CAAK,IAAA,CAAKA,CAAAA,CAAK,MAAA,CAAS,CAAC,CACjC,CACD,EASA,eAAsBE,GAAgD,CACrE,GAAI,CACH,IAAMC,CAAAA,CAAM,MAAM,OAAO,eAAe,CAAA,CAClCC,EAAY,IAAIP,CAAAA,CACrBM,CAAAA,CAAI,WAAA,CACJA,CAAAA,CAAI,iBACL,EACA,OAAAE,CAAAA,CAAI,KAAA,CAAM,wDAAwD,CAAA,CAC3DD,CACR,MAAQ,CACP,OAAAC,EAAI,IAAA,CACH,+EACD,EACO,IAAIJ,CACZ,CACD,CAOO,SAASK,CAAAA,EAA2C,CAC1D,OAAO,IAAIL,CACZ,CCzFA,IAAMM,CAAAA,CAAa,cAAA,CACbC,CAAAA,CAAgB,eAAA,CAMhBC,EAAsB,CAC3B,CAAA,CAAG,EAAG,EAAA,CAAI,EAAA,CAAI,IAAK,IAAA,CAAM,IAAA,CAAM,KAAA,CAAO,KAAA,CAAO,MAAA,CAAQ,OAAA,C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,CACvD,CAAA,CACA,QAAS,IACV,CACD,CAAC,CACF,EACD,CACD,EACD,CAAC,CACF,CAEQ,gBAAA,CACPC,CAAAA,CACAzL,CAAAA,CACAgL,EACS,CACT,IAAMU,CAAAA,CAAgB,CAAA,CAAA,cAAA,CAAe,aAAA,CAAe1L,CAAAA,CAAKgL,CAAK,CAAA,CACxDW,CAAAA,CAAY,OAAO,MAAA,CAAO,CAACD,EAAO,MAAA,CAAOD,CAAO,CAAA,CAAGC,CAAAA,CAAO,KAAA,EAAO,CAAC,CAAA,CACxE,OAAO,MAAA,CAAO,MAAA,CAAO,CAACC,CAAAA,CAAWD,EAAO,UAAA,EAAY,CAAC,CACtD,CACD","file":"chunk-4ABAFG44.js","sourcesContent":["import { log } from \"../utils/logger.js\";\n\n/**\n * TokenEstimator — Pluggable strategy for counting tokens in text content.\n *\n * Implementations range from exact BPE tokenization to lightweight heuristics,\n * allowing the SDK to choose the best trade-off for the runtime environment.\n */\nexport interface TokenEstimator {\n\t/** Count the number of tokens in the given text */\n\tcountTokens(text: string): number;\n\t/** Human-readable name of the estimation strategy */\n\treadonly name: string;\n}\n\n/**\n * Exact BPE tokenizer using o200k_base encoding.\n *\n * o200k_base is the standard encoding for all modern OpenAI models\n * (GPT-4o, GPT-4.1, o1, o3, o4) and provides a reasonable baseline\n * for Anthropic/Google models as well (~±5% variance).\n *\n * - Synchronous: safe for hot-path usage without async overhead\n * - Merge cache reduced to 10K entries for long-running server processes\n * - Zero runtime dependencies beyond gpt-tokenizer itself\n */\nexport class RealTokenEstimator implements TokenEstimator {\n\treadonly name = \"o200k_base\";\n\n\tprivate countFn: (text: string) => number;\n\n\tconstructor(\n\t\tcountFn: (text: string) => number,\n\t\tsetMergeCacheSizeFn?: (size: number) => void,\n\t) {\n\t\tthis.countFn = countFn;\n\t\t// Reduce merge cache from default 100K to 10K for server processes\n\t\tif (setMergeCacheSizeFn) {\n\t\t\tsetMergeCacheSizeFn(10_000);\n\t\t}\n\t}\n\n\tcountTokens(text: string): number {\n\t\tif (text.length === 0) return 0;\n\t\treturn this.countFn(text);\n\t}\n}\n\n/**\n * Fallback heuristic estimator: ~4 characters per token.\n *\n * Industry-standard approximation (±10% for English/code content).\n * Used only when gpt-tokenizer fails to load in constrained environments.\n */\nexport class HeuristicTokenEstimator implements TokenEstimator {\n\treadonly name = \"heuristic (chars/4)\";\n\n\tcountTokens(text: string): number {\n\t\tif (text.length === 0) return 0;\n\t\treturn Math.ceil(text.length / 4);\n\t}\n}\n\n/**\n * Factory: creates a RealTokenEstimator with gpt-tokenizer,\n * falling back to HeuristicTokenEstimator if the import fails.\n *\n * Uses dynamic import to avoid blocking SDK initialization and to\n * gracefully degrade in environments where gpt-tokenizer is unavailable.\n */\nexport async function createTokenEstimator(): Promise<TokenEstimator> {\n\ttry {\n\t\tconst mod = await import(\"gpt-tokenizer\");\n\t\tconst estimator = new RealTokenEstimator(\n\t\t\tmod.countTokens,\n\t\t\tmod.setMergeCacheSize,\n\t\t);\n\t\tlog.debug(\"[LIOP-Economy] Token estimator initialized: o200k_base\");\n\t\treturn estimator;\n\t} catch {\n\t\tlog.info(\n\t\t\t\"[LIOP-Economy] gpt-tokenizer unavailable, falling back to heuristic estimator\",\n\t\t);\n\t\treturn new HeuristicTokenEstimator();\n\t}\n}\n\n/**\n * Synchronous factory: creates a HeuristicTokenEstimator immediately.\n * Used when the async factory cannot be awaited (e.g., constructor contexts).\n * The engine should upgrade to the real estimator via setEstimator() later.\n */\nexport function createSyncTokenEstimator(): TokenEstimator {\n\treturn new HeuristicTokenEstimator();\n}\n","import type { Histogram } from \"@opentelemetry/api\";\nimport { metrics } from \"@opentelemetry/api\";\nimport { log } from \"../utils/logger.js\";\n\n/** SDK identifier for the OTel Meter */\nconst METER_NAME = \"@nekzus/liop\";\nconst METER_VERSION = \"1.2.0-alpha.9\";\n\n/**\n * gen_ai.client.token.usage — Recommended explicit bucket boundaries.\n * Source: OpenTelemetry Generative AI Semantic Conventions (experimental).\n */\nconst TOKEN_USAGE_BUCKETS = [\n\t1, 4, 16, 64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304,\n\t16777216, 67108864,\n];\n\n/**\n * gen_ai.client.operation.duration — Recommended bucket boundaries (seconds).\n * Source: OpenTelemetry Generative AI Semantic Conventions.\n */\nconst DURATION_BUCKETS = [\n\t0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56, 5.12, 10.24, 20.48,\n\t40.96, 81.92,\n];\n\n/**\n * LiopOTelBridge — OpenTelemetry gen_ai.* metric emitter.\n *\n * Pattern: Library Instrumentation (uses global MeterProvider only).\n * Per official OTel JS documentation:\n * - Libraries MUST NOT create their own MeterProvider\n * - Libraries SHOULD use metrics.getMeter() from the global API\n * - If no MeterProvider is registered by the application, all operations are NoOp\n * with zero runtime overhead (confirmed by OTel JS source: NoopMeterProvider)\n *\n * Follows OpenTelemetry Generative AI Semantic Conventions (Development status).\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nexport class LiopOTelBridge {\n\tprivate tokenUsage: Histogram;\n\tprivate operationDuration: Histogram;\n\tprivate active = false;\n\n\tconstructor() {\n\t\ttry {\n\t\t\tconst meter = metrics.getMeter(METER_NAME, METER_VERSION);\n\n\t\t\tthis.tokenUsage = meter.createHistogram(\"gen_ai.client.token.usage\", {\n\t\t\t\tdescription: \"Number of tokens used in LIOP Logic-on-Origin operations\",\n\t\t\t\tunit: \"{token}\",\n\t\t\t\tadvice: { explicitBucketBoundaries: TOKEN_USAGE_BUCKETS },\n\t\t\t});\n\n\t\t\tthis.operationDuration = meter.createHistogram(\n\t\t\t\t\"gen_ai.client.operation.duration\",\n\t\t\t\t{\n\t\t\t\t\tdescription: \"Duration of LIOP operations\",\n\t\t\t\t\tunit: \"s\",\n\t\t\t\t\tadvice: { explicitBucketBoundaries: DURATION_BUCKETS },\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tthis.active = true;\n\t\t\tlog.debug(\"[LIOP-OTel] gen_ai.* metrics bridge initialized\");\n\t\t} catch (err: unknown) {\n\t\t\t// OTel API failed to load — degrade gracefully without affecting protocol\n\t\t\tlog.debug(\n\t\t\t\t`[LIOP-OTel] Bridge disabled: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t\tconst noopHistogram = {\n\t\t\t\trecord: () => {},\n\t\t\t} as unknown as Histogram;\n\t\t\tthis.tokenUsage = noopHistogram;\n\t\t\tthis.operationDuration = noopHistogram;\n\t\t}\n\t}\n\n\t/**\n\t * Record token usage with gen_ai.* standard attributes.\n\t *\n\t * @param tokens - Number of tokens consumed\n\t * @param tokenType - \"input\" or \"output\" (gen_ai.token.type)\n\t * @param operationName - gen_ai.operation.name (e.g., \"execute_tool\", \"chat\")\n\t * @param toolName - Optional LIOP-specific tool name for attribution\n\t */\n\trecordTokens(\n\t\ttokens: number,\n\t\ttokenType: \"input\" | \"output\",\n\t\toperationName: string,\n\t\ttoolName?: string,\n\t): void {\n\t\tthis.tokenUsage.record(tokens, {\n\t\t\t\"gen_ai.system\": \"liop\",\n\t\t\t\"gen_ai.operation.name\": operationName,\n\t\t\t\"gen_ai.token.type\": tokenType,\n\t\t\t\"gen_ai.request.model\": \"liop-mesh\",\n\t\t\t...(toolName ? { \"liop.tool.name\": toolName } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * Record operation duration with gen_ai.* standard attributes.\n\t *\n\t * @param durationMs - Duration in milliseconds (converted to seconds for OTel)\n\t * @param operationName - gen_ai.operation.name\n\t * @param error - Optional error type string if the operation failed\n\t */\n\trecordDuration(\n\t\tdurationMs: number,\n\t\toperationName: string,\n\t\terror?: string,\n\t): void {\n\t\tthis.operationDuration.record(durationMs / 1000, {\n\t\t\t\"gen_ai.system\": \"liop\",\n\t\t\t\"gen_ai.operation.name\": operationName,\n\t\t\t...(error ? { \"error.type\": error } : {}),\n\t\t});\n\t}\n\n\t/** Whether the OTel bridge is actively connected to a MeterProvider */\n\tisActive(): boolean {\n\t\treturn this.active;\n\t}\n}\n","import {\n\tcreateSyncTokenEstimator,\n\tcreateTokenEstimator,\n\ttype TokenEstimator,\n} from \"./estimator.js\";\nimport { LiopOTelBridge } from \"./otel.js\";\n\n/** Single MCP operation token footprint */\nexport interface TokenOperationMetric {\n\treadonly type:\n\t\t| \"tools_list\"\n\t\t| \"tool_call\"\n\t\t| \"resource_read\"\n\t\t| \"resource_list\"\n\t\t| \"prompt_get\"\n\t\t| \"prompt_list\"\n\t\t| \"diagnostic\";\n\treadonly method: string;\n\treadonly estimatedInputTokens: number;\n\treadonly estimatedOutputTokens: number;\n\treadonly timestamp: number;\n\treadonly toolName?: string;\n\treadonly peerId?: string;\n\treadonly durationMs?: number;\n}\n\n/** Session-level aggregate report */\nexport interface TokenSessionReport {\n\treadonly sessionId: string;\n\treadonly operations: ReadonlyArray<TokenOperationMetric>;\n\treadonly totalInputTokens: number;\n\treadonly totalOutputTokens: number;\n\treadonly estimatorName: string;\n\treadonly sessionUptimeMs: number;\n}\n\n/** Per-tool aggregate breakdown */\nexport interface ToolTokenBreakdown {\n\treadonly input: number;\n\treadonly output: number;\n\treadonly calls: number;\n\treadonly avgDurationMs: number;\n}\n\n/**\n * Maps operation types to OTel gen_ai.operation.name values.\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\nconst OTEL_OPERATION_MAP: Record<TokenOperationMetric[\"type\"], string> = {\n\ttools_list: \"chat\",\n\ttool_call: \"execute_tool\",\n\tresource_read: \"chat\",\n\tresource_list: \"chat\",\n\tprompt_get: \"chat\",\n\tprompt_list: \"chat\",\n\tdiagnostic: \"chat\",\n};\n\n/**\n * TokenTelemetryEngine — Full-spectrum observational singleton for token cost measurement.\n *\n * Design principles:\n * - Pure observer pattern: NEVER mutates MCP payloads or protocol flow.\n * - Real tokenization: o200k_base BPE via gpt-tokenizer (async init, sync counting).\n * - OTel gen_ai.* emission: standard metrics via @opentelemetry/api (NoOp if no provider).\n * - Error isolation: telemetry failures never propagate to protocol operations.\n */\nexport class TokenTelemetryEngine {\n\tprivate static instance: TokenTelemetryEngine | null = null;\n\tprivate operations: TokenOperationMetric[] = [];\n\tprivate readonly sessionId: string;\n\tprivate readonly startedAt: number;\n\tprivate estimator: TokenEstimator;\n\tprivate otelBridge: LiopOTelBridge;\n\n\tprivate constructor() {\n\t\tthis.sessionId = crypto.randomUUID();\n\t\tthis.startedAt = Date.now();\n\t\t// Start with sync heuristic estimator (available immediately)\n\t\tthis.estimator = createSyncTokenEstimator();\n\t\tthis.otelBridge = new LiopOTelBridge();\n\t\t// Upgrade to real tokenizer asynchronously\n\t\tthis.initRealEstimator();\n\t}\n\n\t/** Async upgrade from heuristic to real BPE tokenizer */\n\tprivate initRealEstimator(): void {\n\t\tcreateTokenEstimator()\n\t\t\t.then((real) => {\n\t\t\t\tthis.estimator = real;\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\t// Keep heuristic fallback — already assigned in constructor\n\t\t\t});\n\t}\n\n\tstatic getInstance(): TokenTelemetryEngine {\n\t\tif (!TokenTelemetryEngine.instance) {\n\t\t\tTokenTelemetryEngine.instance = new TokenTelemetryEngine();\n\t\t}\n\t\treturn TokenTelemetryEngine.instance;\n\t}\n\n\t/**\n\t * Count tokens in a string using the active estimator.\n\t * Delegates to o200k_base BPE tokenizer (or heuristic fallback).\n\t */\n\tcountTokens(content: string): number {\n\t\ttry {\n\t\t\treturn this.estimator.countTokens(content);\n\t\t} catch {\n\t\t\t// Fallback: never let counting failures break protocol flow\n\t\t\treturn Math.ceil(content.length / 4);\n\t\t}\n\t}\n\n\t/**\n\t * Record a single MCP operation's token footprint.\n\t * Emits both internal metrics and OTel gen_ai.* histograms.\n\t */\n\trecord(metric: Omit<TokenOperationMetric, \"timestamp\">): void {\n\t\tconst fullMetric: TokenOperationMetric = {\n\t\t\t...metric,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tthis.operations.push(fullMetric);\n\n\t\t// Emit to OTel bridge (NoOp if no MeterProvider configured)\n\t\ttry {\n\t\t\tconst otelOp = OTEL_OPERATION_MAP[metric.type] || \"chat\";\n\n\t\t\tif (metric.estimatedInputTokens > 0) {\n\t\t\t\tthis.otelBridge.recordTokens(\n\t\t\t\t\tmetric.estimatedInputTokens,\n\t\t\t\t\t\"input\",\n\t\t\t\t\totelOp,\n\t\t\t\t\tmetric.toolName,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (metric.estimatedOutputTokens > 0) {\n\t\t\t\tthis.otelBridge.recordTokens(\n\t\t\t\t\tmetric.estimatedOutputTokens,\n\t\t\t\t\t\"output\",\n\t\t\t\t\totelOp,\n\t\t\t\t\tmetric.toolName,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (metric.durationMs !== undefined) {\n\t\t\t\tthis.otelBridge.recordDuration(metric.durationMs, otelOp);\n\t\t\t}\n\t\t} catch {\n\t\t\t// OTel emission failure must never affect protocol operations\n\t\t}\n\t}\n\n\t/**\n\t * @deprecated Use countTokens() instead. Kept for backward compatibility.\n\t */\n\testimateTokens(content: string): number {\n\t\treturn this.countTokens(content);\n\t}\n\n\t/** Generate the full session report */\n\tgetReport(): TokenSessionReport {\n\t\treturn {\n\t\t\tsessionId: this.sessionId,\n\t\t\toperations: [...this.operations],\n\t\t\ttotalInputTokens: this.operations.reduce(\n\t\t\t\t(sum, op) => sum + op.estimatedInputTokens,\n\t\t\t\t0,\n\t\t\t),\n\t\t\ttotalOutputTokens: this.operations.reduce(\n\t\t\t\t(sum, op) => sum + op.estimatedOutputTokens,\n\t\t\t\t0,\n\t\t\t),\n\t\t\testimatorName: this.estimator.name,\n\t\t\tsessionUptimeMs: Date.now() - this.startedAt,\n\t\t};\n\t}\n\n\t/** Get per-tool token breakdown for diagnostic display */\n\tgetPerToolReport(): Map<string, ToolTokenBreakdown> {\n\t\tconst breakdown = new Map<string, ToolTokenBreakdown>();\n\n\t\tfor (const op of this.operations) {\n\t\t\tconst key = op.toolName || op.method;\n\t\t\tconst existing = breakdown.get(key) || {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcalls: 0,\n\t\t\t\tavgDurationMs: 0,\n\t\t\t};\n\n\t\t\tconst totalDuration =\n\t\t\t\texisting.avgDurationMs * existing.calls + (op.durationMs || 0);\n\t\t\tconst newCalls = existing.calls + 1;\n\n\t\t\tbreakdown.set(key, {\n\t\t\t\tinput: existing.input + op.estimatedInputTokens,\n\t\t\t\toutput: existing.output + op.estimatedOutputTokens,\n\t\t\t\tcalls: newCalls,\n\t\t\t\tavgDurationMs: newCalls > 0 ? totalDuration / newCalls : 0,\n\t\t\t});\n\t\t}\n\n\t\treturn breakdown;\n\t}\n\n\t/**\n\t * Format a rich, human-readable summary block for LiopMeshStatus diagnostic.\n\t * Returns empty string when no operations have been recorded.\n\t */\n\tformatStatusBlock(): string {\n\t\tconst report = this.getReport();\n\t\tif (report.operations.length === 0) return \"\";\n\n\t\tconst uptimeStr = this.formatUptime(report.sessionUptimeMs);\n\t\tconst totalCombined = report.totalInputTokens + report.totalOutputTokens;\n\n\t\t// Aggregate operations by type\n\t\tconst byType = new Map<\n\t\t\tstring,\n\t\t\t{ count: number; input: number; output: number }\n\t\t>();\n\t\tfor (const op of report.operations) {\n\t\t\tconst key = op.type;\n\t\t\tconst existing = byType.get(key) || {\n\t\t\t\tcount: 0,\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t};\n\t\t\tbyType.set(key, {\n\t\t\t\tcount: existing.count + 1,\n\t\t\t\tinput: existing.input + op.estimatedInputTokens,\n\t\t\t\toutput: existing.output + op.estimatedOutputTokens,\n\t\t\t});\n\t\t}\n\n\t\t// Build type breakdown lines\n\t\tconst typeEntries = Array.from(byType.entries());\n\t\tconst typeLines = typeEntries.map(([type, data], idx) => {\n\t\t\tconst prefix = idx === typeEntries.length - 1 ? \"│ └─\" : \"│ ├─\";\n\t\t\tconst outputPart =\n\t\t\t\tdata.output > 0 ? ` / ${data.output.toLocaleString()} out` : \"\";\n\t\t\treturn `${prefix} ${type} ×${data.count} → ${data.input.toLocaleString()} in${outputPart}`;\n\t\t});\n\n\t\t// Build per-tool breakdown\n\t\tconst toolReport = this.getPerToolReport();\n\t\tconst toolEntries = Array.from(toolReport.entries()).filter(\n\t\t\t([key]) => key !== \"tools/list\" && key !== \"LiopMeshStatus\",\n\t\t);\n\n\t\tconst toolLines: string[] = [];\n\t\tif (toolEntries.length > 0) {\n\t\t\ttoolLines.push(\"├─ By Tool:\");\n\t\t\ttoolEntries.forEach(([name, data], idx) => {\n\t\t\t\tconst prefix = idx === toolEntries.length - 1 ? \"│ └─\" : \"│ ├─\";\n\t\t\t\tconst outputPart =\n\t\t\t\t\tdata.output > 0 ? ` / ${data.output.toLocaleString()} out` : \"\";\n\t\t\t\tconst durationPart =\n\t\t\t\t\tdata.avgDurationMs > 0 ? ` ~${Math.round(data.avgDurationMs)}ms` : \"\";\n\t\t\t\ttoolLines.push(\n\t\t\t\t\t`${prefix} ${name}: ${data.input.toLocaleString()} in${outputPart} (×${data.calls})${durationPart}`,\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\n\t\t// Calculate average latency across all timed operations\n\t\tconst timedOps = report.operations.filter(\n\t\t\t(op) => op.durationMs !== undefined,\n\t\t);\n\t\tconst avgLatency =\n\t\t\ttimedOps.length > 0\n\t\t\t\t? Math.round(\n\t\t\t\t\t\ttimedOps.reduce((sum, op) => sum + (op.durationMs || 0), 0) /\n\t\t\t\t\t\t\ttimedOps.length,\n\t\t\t\t\t)\n\t\t\t\t: 0;\n\n\t\tconst otelStatus = this.otelBridge.isActive()\n\t\t\t? \"gen_ai.client.token.usage → active\"\n\t\t\t: \"disabled\";\n\n\t\tconst lines = [\n\t\t\t\"\\nToken Economy:\",\n\t\t\t`├─ Session: ${report.sessionId.slice(0, 8)} (${uptimeStr})`,\n\t\t\t`├─ Estimator: ${report.estimatorName}`,\n\t\t\t`├─ Operations: ${report.operations.length}`,\n\t\t\t...typeLines,\n\t\t\t`├─ Total: ${report.totalInputTokens.toLocaleString()} in / ${report.totalOutputTokens.toLocaleString()} out (${totalCombined.toLocaleString()} combined)`,\n\t\t\t...toolLines,\n\t\t\t...(avgLatency > 0 ? [`├─ Avg Latency: ${avgLatency}ms`] : []),\n\t\t\t`└─ OTel: ${otelStatus}`,\n\t\t];\n\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\t/** Format milliseconds into human-readable uptime string */\n\tprivate formatUptime(ms: number): string {\n\t\tconst seconds = Math.floor(ms / 1000);\n\t\tif (seconds < 60) return `${seconds}s`;\n\t\tconst minutes = Math.floor(seconds / 60);\n\t\tconst remainingSeconds = seconds % 60;\n\t\tif (minutes < 60) return `${minutes}m ${remainingSeconds}s`;\n\t\tconst hours = Math.floor(minutes / 60);\n\t\tconst remainingMinutes = minutes % 60;\n\t\treturn `${hours}h ${remainingMinutes}m`;\n\t}\n\n\t/** Reset all recorded metrics (used in tests) */\n\treset(): void {\n\t\tthis.operations = [];\n\t}\n\n\t/** Destroy the singleton (used in tests to guarantee isolation) */\n\tstatic destroy(): void {\n\t\tTokenTelemetryEngine.instance = null;\n\t}\n}\n","/**\n * MCP UX: optional compact tool descriptions for clients (e.g. cloud models)\n * that over-trigger on long \"envelope / injection\" wording in tools/list.\n *\n * Full LIOP payload format remains in prompts/get → liop_blind_analyst.\n */\nexport function mcpCompactToolDescriptions(): boolean {\n\tconst v =\n\t\tprocess.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();\n\treturn v === \"1\" || v === \"true\" || v === \"yes\";\n}\n\n/**\n * Removes SDK-appended LIOP specification blocks from a registered tool description.\n */\nexport function stripVerboseLiopToolDescription(description: string): string {\n\tlet d = description;\n\tconst markers = [\n\t\t\"\\n\\n[LIOP-PROTO-V1:\",\n\t\t\"\\r\\n\\r\\n[LIOP-PROTO-V1:\",\n\t\t\"\\n[LIOP-PROTO-V1:\", // rare\n\t];\n\tfor (const m of markers) {\n\t\tconst i = d.indexOf(m);\n\t\tif (i !== -1) {\n\t\t\td = d.slice(0, i);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn d.trimEnd();\n}\n","import * as crypto from \"node:crypto\";\nimport { LiopVerifier } from \"../crypto/verifier.js\";\nimport { TokenTelemetryEngine } from \"../economy/telemetry.js\";\nimport type { LiopManifest, MeshNode } from \"../mesh/index.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport { liopV1 } from \"../rpc/proto.js\";\nimport { createChannelCredentials } from \"../rpc/tls.js\";\nimport type { IntentResponse, LogicResponse } from \"../rpc/types.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport type { McpRequest, McpResponse } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\nimport {\n\tmcpCompactToolDescriptions,\n\tstripVerboseLiopToolDescription,\n} from \"../utils/mcpCompact.js\";\n\n/**\n * Time-to-live for cached manifests (seconds).\n * Aligned with libp2p Kademlia DHT TABLE_REFRESH_INTERVAL (5 minutes).\n * Provider records in the DHT are valid for 48 hours (PROVIDERS_VALIDITY),\n * so 300s is a conservative, network-friendly value.\n */\nconst MANIFEST_CACHE_TTL_S = 300;\n\n/** Maximum number of DHT query retries for manifest discovery */\nconst MANIFEST_DISCOVERY_RETRIES = 5;\n\n/**\n * LIOP MCP Router\n *\n * Core logic for routing MCP requests to local or remote LIOP providers.\n * Decoupled from transport (HTTP/Stdio).\n *\n * All tool discovery and port resolution is DYNAMIC via the\n * /liop/manifest/1.0.0 protocol stream over Kademlia DHT.\n */\nexport class LiopMcpRouter {\n\t/** Cached manifests from remote peers. Key = PeerID */\n\tprivate manifestCache: Map<\n\t\tstring,\n\t\t{ manifest: LiopManifest; cachedAt: number }\n\t> = new Map();\n\n\t/** Guards against concurrent discovery storms */\n\tprivate currentDiscovery: Promise<void> | null = null;\n\n\t/** Verifier for Tier-0 integrity checks */\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\n\t/** Callback when new remote tools are discovered */\n\tpublic onToolsChanged?: () => void;\n\n\t/** Circuit-breaker state for peers that repeatedly fail manifest queries. */\n\tprivate manifestFailureState: Map<\n\t\tstring,\n\t\t{ failures: number; cooldownUntil: number; lastSkipLogAt: number }\n\t> = new Map();\n\n\tprivate static readonly MANIFEST_FAILURE_BASE_COOLDOWN_MS = 15_000;\n\tprivate static readonly MANIFEST_FAILURE_MAX_COOLDOWN_MS = 5 * 60_000;\n\tprivate static readonly MANIFEST_SKIP_LOG_THROTTLE_MS = 30_000;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\tprivate defaultRpcPort = 50051,\n\t) {\n\t\t// Auto-register manifest handler if mesh node is provided\n\t\tif (this.meshNode) {\n\t\t\tthis.meshNode.registerManifestHandler(() => {\n\t\t\t\tconst remoteTools = this.liopServer.listTools().map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinputSchema: t.inputSchema as Record<string, unknown>,\n\t\t\t\t}));\n\n\t\t\t\tconst resources = this.liopServer.listResources().map((r) => ({\n\t\t\t\t\tname: r.name,\n\t\t\t\t\turi: r.uri,\n\t\t\t\t\tdescription: r.description,\n\t\t\t\t\tmimeType: r.mimeType,\n\t\t\t\t}));\n\n\t\t\t\treturn {\n\t\t\t\t\tpeerId: this.meshNode?.getPeerId() || \"unknown\",\n\t\t\t\t\tgrpcPort: this.defaultRpcPort,\n\t\t\t\t\ttools: [...remoteTools],\n\t\t\t\t\tresources,\n\t\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\t// Proactively announce manifest capability to the mesh\n\t\t\tthis.meshNode.announceManifest().catch((err: unknown) => {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Failed to announce manifest: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\n\t\t// [OWASP-A01] Startup warning when diagnostic level exposes full topology\n\t\tif (process.env.LIOP_DIAGNOSTIC_LEVEL === \"full\") {\n\t\t\tprocess.stderr.write(\n\t\t\t\t\"⚠️ [LIOP-Security] Diagnostic level set to FULL — \" +\n\t\t\t\t\t\"PeerIDs and network topology are exposed. Do NOT use in production.\\n\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate shouldSkipManifestQuery(peerId: string): boolean {\n\t\tconst state = this.manifestFailureState.get(peerId);\n\t\tif (!state) return false;\n\t\tconst now = Date.now();\n\t\tif (now >= state.cooldownUntil) return false;\n\n\t\tif (\n\t\t\tnow - state.lastSkipLogAt >\n\t\t\tLiopMcpRouter.MANIFEST_SKIP_LOG_THROTTLE_MS\n\t\t) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Router] Skipping manifest query for ${peerId} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1000)}s remaining)`,\n\t\t\t);\n\t\t\tstate.lastSkipLogAt = now;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate recordManifestQuerySuccess(peerId: string): void {\n\t\tthis.manifestFailureState.delete(peerId);\n\t}\n\n\tprivate recordManifestQueryFailure(peerId: string): void {\n\t\tconst now = Date.now();\n\t\tconst prev = this.manifestFailureState.get(peerId);\n\t\tconst failures = (prev?.failures || 0) + 1;\n\t\tconst backoff = Math.min(\n\t\t\tLiopMcpRouter.MANIFEST_FAILURE_BASE_COOLDOWN_MS *\n\t\t\t\t2 ** Math.max(0, failures - 1),\n\t\t\tLiopMcpRouter.MANIFEST_FAILURE_MAX_COOLDOWN_MS,\n\t\t);\n\t\tthis.manifestFailureState.set(peerId, {\n\t\t\tfailures,\n\t\t\tcooldownUntil: now + backoff,\n\t\t\tlastSkipLogAt: 0,\n\t\t});\n\t}\n\n\tpublic async dispatch(request: McpRequest): Promise<McpResponse | null> {\n\t\tconst { method, params, id } = request;\n\t\tlog.info(`[LIOP-Router] Processing: ${method}`);\n\n\t\tswitch (method) {\n\t\t\tcase \"initialize\":\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\t\t\tcapabilities: {\n\t\t\t\t\t\t\ttools: { listChanged: true },\n\t\t\t\t\t\t\tresources: { listChanged: true },\n\t\t\t\t\t\t\tprompts: { listChanged: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\tcase \"notifications/initialized\":\n\t\t\t\t// Cloud MCP clients often fire tools/list immediately; kick discovery early\n\t\t\t\t// so manifests populate before (or right after) that call completes.\n\t\t\t\tthis.kickDiscoveryAfterInitialized().catch(() => {});\n\t\t\t\treturn null;\n\t\t\tcase \"notifications/cancelled\":\n\t\t\t\treturn null; // No-op for MCP spec compliance\n\t\t\tcase \"ping\":\n\t\t\t\treturn { jsonrpc: \"2.0\", id, result: {} };\n\t\t\tcase \"tools/list\": {\n\t\t\t\tconst localTools = this.liopServer.listTools();\n\t\t\t\tconst remoteTools = await this.getRemoteTools();\n\n\t\t\t\tconst listedLocals = mcpCompactToolDescriptions()\n\t\t\t\t\t? localTools.map((t) => ({\n\t\t\t\t\t\t\t...t,\n\t\t\t\t\t\t\tdescription: stripVerboseLiopToolDescription(t.description ?? \"\"),\n\t\t\t\t\t\t}))\n\t\t\t\t\t: localTools;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] tools/list: ${localTools.length} local, ${remoteTools.length} remote tools found`,\n\t\t\t\t);\n\n\t\t\t\t// Inject a mandatory static diagnostic tool.\n\t\t\t\t// This ensures that the {tools: []} list is never empty on startup.\n\t\t\t\t// Claude Desktop silently hides the connector if it receives an empty array initially,\n\t\t\t\t// which broke the UX due to the ~3s warm-up time of the Kademlia DHT.\n\t\t\t\tconst diagnosticTool = {\n\t\t\t\t\tname: \"LiopMeshStatus\",\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.\",\n\t\t\t\t\tinputSchema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\t\t\tconst allTools = [diagnosticTool, ...listedLocals, ...remoteTools];\n\n\t\t\t\t// [Token Economy] Record telemetry for the tools/list response\n\t\t\t\tconst telemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst toolsPayload = JSON.stringify(allTools);\n\t\t\t\tconst toolsResponsePayload = JSON.stringify({ tools: allTools });\n\t\t\t\ttelemetry.record({\n\t\t\t\t\ttype: \"tools_list\",\n\t\t\t\t\tmethod: \"tools/list\",\n\t\t\t\t\testimatedInputTokens: telemetry.countTokens(toolsPayload),\n\t\t\t\t\testimatedOutputTokens: telemetry.countTokens(toolsResponsePayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\ttools: allTools,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"tools/call\":\n\t\t\t\treturn this.transcodeMcpToLiop(id, params as Record<string, unknown>);\n\t\t\tcase \"resources/list\": {\n\t\t\t\tconst localResources = this.liopServer.listResources();\n\t\t\t\tconst remoteResources = await this.getRemoteResources();\n\t\t\t\tconst allResources = [...localResources, ...remoteResources];\n\n\t\t\t\t// [Token Economy] Record resources/list telemetry\n\t\t\t\tconst rlTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst rlPayload = JSON.stringify(allResources);\n\t\t\t\trlTelemetry.record({\n\t\t\t\t\ttype: \"resource_list\",\n\t\t\t\t\tmethod: \"resources/list\",\n\t\t\t\t\testimatedInputTokens: 0,\n\t\t\t\t\testimatedOutputTokens: rlTelemetry.countTokens(rlPayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: { resources: allResources },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"resources/read\": {\n\t\t\t\tconst typedParams = params as { uri?: string } | undefined;\n\t\t\t\tif (!typedParams?.uri)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: { code: -32602, message: \"Missing resource uri\" },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst rrStartTime = Date.now();\n\t\t\t\t\tconst result = await this.liopServer.readResource(typedParams.uri);\n\n\t\t\t\t\t// [Token Economy] Record resources/read telemetry\n\t\t\t\t\tconst rrTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\tconst rrOutputPayload = JSON.stringify(result);\n\t\t\t\t\trrTelemetry.record({\n\t\t\t\t\t\ttype: \"resource_read\",\n\t\t\t\t\t\tmethod: \"resources/read\",\n\t\t\t\t\t\ttoolName: typedParams.uri,\n\t\t\t\t\t\testimatedInputTokens: rrTelemetry.countTokens(typedParams.uri),\n\t\t\t\t\t\testimatedOutputTokens: rrTelemetry.countTokens(rrOutputPayload),\n\t\t\t\t\t\tdurationMs: Date.now() - rrStartTime,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\t// Fallback: Resolve remotely from manifest cache\n\t\t\t\t\tconst targetUri = typedParams.uri;\n\t\t\t\t\tfor (const { manifest } of this.manifestCache.values()) {\n\t\t\t\t\t\tconst remoteResource = manifest.resources.find(\n\t\t\t\t\t\t\t(r) => r.uri === targetUri,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (remoteResource) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] Resolved resource ${targetUri} from cache (Peer: ${manifest.peerId})`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\tcontents: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\turi: remoteResource.uri,\n\t\t\t\t\t\t\t\t\t\t\tmimeType: remoteResource.mimeType || \"text/plain\",\n\t\t\t\t\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\t\t\t\t\tremoteResource.text ||\n\t\t\t\t\t\t\t\t\t\t\t\tremoteResource.description ||\n\t\t\t\t\t\t\t\t\t\t\t\t\"No content provided\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase \"prompts/list\": {\n\t\t\t\tconst promptsList = this.liopServer.listPrompts();\n\n\t\t\t\t// [Token Economy] Record prompts/list telemetry\n\t\t\t\tconst plTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst plPayload = JSON.stringify(promptsList);\n\t\t\t\tplTelemetry.record({\n\t\t\t\t\ttype: \"prompt_list\",\n\t\t\t\t\tmethod: \"prompts/list\",\n\t\t\t\t\testimatedInputTokens: 0,\n\t\t\t\t\testimatedOutputTokens: plTelemetry.countTokens(plPayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: { prompts: promptsList },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"prompts/get\": {\n\t\t\t\tconst typedParams = params as\n\t\t\t\t\t| { name?: string; arguments?: Record<string, string> }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (!typedParams?.name)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: { code: -32602, message: \"Missing prompt name\" },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst pgStartTime = Date.now();\n\t\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\t\tname: typedParams.name as string,\n\t\t\t\t\t\targuments: typedParams.arguments || {},\n\t\t\t\t\t});\n\n\t\t\t\t\t// [Token Economy] Record prompts/get telemetry\n\t\t\t\t\tconst pgTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\tconst pgInputPayload = JSON.stringify({\n\t\t\t\t\t\tname: typedParams.name,\n\t\t\t\t\t\targuments: typedParams.arguments,\n\t\t\t\t\t});\n\t\t\t\t\tconst pgOutputPayload = JSON.stringify(result);\n\t\t\t\t\tpgTelemetry.record({\n\t\t\t\t\t\ttype: \"prompt_get\",\n\t\t\t\t\t\tmethod: \"prompts/get\",\n\t\t\t\t\t\ttoolName: typedParams.name,\n\t\t\t\t\t\testimatedInputTokens: pgTelemetry.countTokens(pgInputPayload),\n\t\t\t\t\t\testimatedOutputTokens: pgTelemetry.countTokens(pgOutputPayload),\n\t\t\t\t\t\tdurationMs: Date.now() - pgStartTime,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\terror: { code: -32601, message: `Method not found: ${method}` },\n\t\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * MCP clients often send notifications/initialized then immediately tools/list.\n\t * Start manifest discovery without blocking the notification handler.\n\t */\n\tprivate kickDiscoveryAfterInitialized(): Promise<void> {\n\t\treturn (async () => {\n\t\t\tawait new Promise((r) => setTimeout(r, 250));\n\t\t\tawait Promise.race([\n\t\t\t\tthis.refreshManifestCache(true),\n\t\t\t\tnew Promise<void>((r) => setTimeout(r, 15_000)),\n\t\t\t]).catch(() => {});\n\t\t})();\n\t}\n\n\t/**\n\t * Discovers and caches manifests from all remote LIOP providers in the mesh.\n\t * Uses Kademlia DHT to find \"liop:manifest\" providers, then opens\n\t * /liop/manifest/1.0.0 protocol streams to retrieve their full metadata.\n\t */\n\tpublic async refreshManifestCache(silent = false): Promise<void> {\n\t\tif (!this.meshNode) return;\n\t\tif (this.currentDiscovery) return this.currentDiscovery;\n\n\t\t// Fast-path: Skip DHT query entirely when cache is fresh and populated.\n\t\t// Only background polls (silent=true) should bypass this to detect new nodes.\n\t\t// Foreground requests (tools/list, tools/call) can safely reuse valid cache.\n\t\tif (!silent && this.manifestCache.size > 0) {\n\t\t\tconst now = Date.now();\n\t\t\tconst allFresh = Array.from(this.manifestCache.values()).every(\n\t\t\t\t({ cachedAt }) => now - cachedAt < MANIFEST_CACHE_TTL_S * 1000,\n\t\t\t);\n\t\t\tif (allFresh) return;\n\t\t}\n\n\t\tthis.currentDiscovery = (async () => {\n\t\t\ttry {\n\t\t\t\tconst prevCount = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t\t0,\n\t\t\t\t);\n\n\t\t\t\t// Phase 0: Wait for at least one active connection if mesh is empty (Cold Start)\n\t\t\t\tif (this.manifestCache.size === 0) {\n\t\t\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\t\t\tconst connections =\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal nodes for connection count\n\t\t\t\t\t\t\t(this.meshNode as any).node?.getConnections().length || 0;\n\t\t\t\t\t\tif (connections > 0) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] P2P Connection established. Starting discovery...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Waiting for P2P connections (attempt ${i + 1}/10)...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Phase 1: Try DHT discovery + Fallback loop\n\t\t\t\tlet providerIds: string[] = [];\n\t\t\t\tconst MAX_COLD_ATTEMPTS = this.manifestCache.size === 0 ? 5 : 1;\n\n\t\t\t\tfor (\n\t\t\t\t\tlet coldAttempt = 0;\n\t\t\t\t\tcoldAttempt < MAX_COLD_ATTEMPTS;\n\t\t\t\t\tcoldAttempt++\n\t\t\t\t) {\n\t\t\t\t\t// 1.1 Try DHT discovery\n\t\t\t\t\tfor (\n\t\t\t\t\t\tlet attempt = 0;\n\t\t\t\t\t\tattempt < MANIFEST_DISCOVERY_RETRIES;\n\t\t\t\t\t\tattempt++\n\t\t\t\t\t) {\n\t\t\t\t\t\tproviderIds =\n\t\t\t\t\t\t\t(await this.meshNode?.discoverManifestProviders()) || [];\n\t\t\t\t\t\tconst selfId = this.meshNode?.getPeerId();\n\t\t\t\t\t\tconst remoteIds = providerIds.filter((id) => id !== selfId);\n\t\t\t\t\t\tif (remoteIds.length > 0) break;\n\t\t\t\t\t\tif (attempt < MANIFEST_DISCOVERY_RETRIES - 1) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] DHT discovery attempt ${attempt + 1}/${MANIFEST_DISCOVERY_RETRIES}...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// 1.2 Aggressively merge all active connections to bypass DHT propagation delays\n\t\t\t\t\tconst activePeers =\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t\t(this.meshNode as any).node\n\t\t\t\t\t\t\t?.getConnections()\n\t\t\t\t\t\t\t.map((c: { remotePeer: { toString: () => string } }) =>\n\t\t\t\t\t\t\t\tc.remotePeer.toString(),\n\t\t\t\t\t\t\t) || [];\n\n\t\t\t\t\tif (activePeers.length > 0) {\n\t\t\t\t\t\tproviderIds = Array.from(new Set([...providerIds, ...activePeers]));\n\t\t\t\t\t}\n\n\t\t\t\t\tconst selfIdEnd = this.meshNode?.getPeerId();\n\t\t\t\t\tconst remoteIdsEnd = providerIds.filter((id) => id !== selfIdEnd);\n\t\t\t\t\tif (remoteIdsEnd.length > 0) break;\n\n\t\t\t\t\tif (coldAttempt < MAX_COLD_ATTEMPTS - 1) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${coldAttempt + 1}/${MAX_COLD_ATTEMPTS})...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (providerIds.length === 0) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Router] No manifest providers found after all attempts.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!silent) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Router] Discovered ${providerIds.length} candidate manifest providers`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Prioritize already-connected peers to avoid blocking on stale providers.\n\t\t\t\t// This improves first tools/list latency on Linux/Ubuntu while preserving\n\t\t\t\t// full discovery for slower peers in subsequent refresh cycles.\n\t\t\t\tconst connectedPeers = new Set<string>(\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: internal node access for fast peer ordering\n\t\t\t\t\t((this.meshNode as any).node?.getConnections?.() || []).map(\n\t\t\t\t\t\t(c: { remotePeer: { toString: () => string } }) =>\n\t\t\t\t\t\t\tc.remotePeer.toString(),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tproviderIds = [...providerIds].sort((a, b) => {\n\t\t\t\t\tconst aConnected = connectedPeers.has(a) ? 1 : 0;\n\t\t\t\t\tconst bConnected = connectedPeers.has(b) ? 1 : 0;\n\t\t\t\t\treturn bConnected - aConnected;\n\t\t\t\t});\n\n\t\t\t\tlet successCount = 0;\n\t\t\t\tlet errorCount = 0;\n\t\t\t\tlet cacheUpdated = false;\n\n\t\t\t\t// Filter peers eligible for querying\n\t\t\t\tconst selfId = this.meshNode?.getPeerId();\n\t\t\t\tconst eligiblePeers = providerIds.filter((peerId) => {\n\t\t\t\t\tif (!this.meshNode) return false;\n\t\t\t\t\tif (peerId === selfId) return false;\n\t\t\t\t\tif (this.shouldSkipManifestQuery(peerId)) return false;\n\t\t\t\t\tconst cached = this.manifestCache.get(peerId);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcached &&\n\t\t\t\t\t\tDate.now() - cached.cachedAt < MANIFEST_CACHE_TTL_S * 1000\n\t\t\t\t\t) {\n\t\t\t\t\t\tsuccessCount++;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\t// Parallel manifest queries — eliminates sequential 100ms + retry delays\n\t\t\t\tconst queryResults = await Promise.allSettled(\n\t\t\t\t\teligiblePeers.map(async (peerId) => {\n\t\t\t\t\t\tif (!this.meshNode) return null;\n\t\t\t\t\t\tlog.info(`[LIOP-Router] Querying manifest from: ${peerId}`);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\tmanifest: await this.meshNode.queryManifest(peerId),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\tfor (const result of queryResults) {\n\t\t\t\t\tif (result.status === \"fulfilled\" && result.value?.manifest) {\n\t\t\t\t\t\tconst { peerId, manifest } = result.value;\n\t\t\t\t\t\tthis.manifestCache.set(peerId, {\n\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\tcachedAt: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.recordManifestQuerySuccess(peerId);\n\t\t\t\t\t\tcacheUpdated = true;\n\t\t\t\t\t\tsuccessCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (result.status === \"fulfilled\" && result.value) {\n\t\t\t\t\t\tthis.recordManifestQueryFailure(result.value.peerId);\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Manifest query returned NULL for ${result.value.peerId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (result.status === \"rejected\") {\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Fatal error querying manifest:`,\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason.message\n\t\t\t\t\t\t\t\t: String(result.reason),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Store discovery stats for LiopMeshStatus diagnostics\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: private stats for telemetry\n\t\t\t\t(this as any)._discoveryStats = {\n\t\t\t\t\tcandidates: providerIds.length,\n\t\t\t\t\tsuccess: successCount,\n\t\t\t\t\tfailures: errorCount,\n\t\t\t\t\tlastDiscovery: Date.now(),\n\t\t\t\t};\n\n\t\t\t\tif (cacheUpdated) {\n\t\t\t\t\tconst newCount = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t\t\t0,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (newCount !== prevCount && this.onToolsChanged) {\n\t\t\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t\t\t\"[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\\n\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.onToolsChanged();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis.currentDiscovery = null;\n\t\t\t}\n\t\t})();\n\n\t\treturn this.currentDiscovery;\n\t}\n\n\t/**\n\t * Returns the current manifest cache size for external telemetry.\n\t * Used by the adaptive polling system to detect topology stabilization.\n\t */\n\tpublic getCacheSize(): number {\n\t\treturn this.manifestCache.size;\n\t}\n\n\t/**\n\t * Returns all remote tools discovered via the manifest protocol.\n\t */\n\tprivate async getRemoteTools(): Promise<\n\t\tArray<{\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tinputSchema?: Record<string, unknown>;\n\t\t}>\n\t> {\n\t\tconst EXPECTED_PROVIDERS = Number.parseInt(\n\t\t\tprocess.env.LIOP_EXPECTED_PROVIDERS ?? \"4\",\n\t\t\t10,\n\t\t);\n\n\t\t// [Phase 106] Smart Warm-up with Stabilization Detection\n\t\t// Loops until EXPECTED_PROVIDERS are found, the deadline expires, or\n\t\t// the provider count stabilizes (same count for 3 consecutive checks).\n\t\t// This prevents a ~20s block when a node (e.g. Bank) is absent.\n\t\tif (this.manifestCache.size < EXPECTED_PROVIDERS && this.meshNode) {\n\t\t\tconst initialTimeoutMs = Number.parseInt(\n\t\t\t\tprocess.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS ?? \"12000\",\n\t\t\t\t10,\n\t\t\t);\n\t\t\tconst boundedTimeoutMs =\n\t\t\t\tNumber.isFinite(initialTimeoutMs) && initialTimeoutMs > 0\n\t\t\t\t\t? initialTimeoutMs\n\t\t\t\t\t: 12000;\n\n\t\t\tconst deadline = Date.now() + boundedTimeoutMs;\n\t\t\tlet stableCount = 0;\n\t\t\tlet lastCacheSize = -1;\n\n\t\t\twhile (Date.now() < deadline) {\n\t\t\t\tif (this.manifestCache.size >= EXPECTED_PROVIDERS) break;\n\n\t\t\t\tawait Promise.race([\n\t\t\t\t\tthis.refreshManifestCache(true),\n\t\t\t\t\tnew Promise<void>((resolve) => setTimeout(resolve, 3000)),\n\t\t\t\t]).catch(() => {});\n\n\t\t\t\tif (this.manifestCache.size >= EXPECTED_PROVIDERS) break;\n\n\t\t\t\t// Stabilization detection: exit early when provider count plateaus\n\t\t\t\tif (this.manifestCache.size === lastCacheSize) {\n\t\t\t\t\tstableCount++;\n\t\t\t\t\tif (stableCount >= 3 && this.manifestCache.size > 0) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${EXPECTED_PROVIDERS}. Proceeding with available mesh.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tstableCount = 0;\n\t\t\t\t\tlastCacheSize = this.manifestCache.size;\n\t\t\t\t}\n\n\t\t\t\t// Wait before the next iteration to avoid CPU spin\n\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t}\n\n\t\t\t// Diagnostic warning for partial mesh availability\n\t\t\tif (this.manifestCache.size < EXPECTED_PROVIDERS) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] ⚠️ Mesh partially available: ${this.manifestCache.size}/${EXPECTED_PROVIDERS} providers. Some tools may be unavailable. Check Docker containers.`,\n\t\t\t\t);\n\t\t\t\t// Trigger one more background refresh to catch late joiners\n\t\t\t\tthis.refreshManifestCache(true).catch(() => {});\n\t\t\t}\n\t\t}\n\n\t\t// biome-ignore lint/suspicious/noExplicitAny: Tool schema is polymorphic\n\t\tconst tools: any[] = [];\n\t\tconst seenNames = new Set<string>();\n\t\tconst localToolNames = new Set(\n\t\t\tthis.liopServer.listTools().map((t) => t.name),\n\t\t);\n\n\t\tfor (const [peerId, { manifest }] of this.manifestCache.entries()) {\n\t\t\tfor (const tool of manifest.tools) {\n\t\t\t\t// LiopMeshStatus is a local-only diagnostic — skip remote copies\n\t\t\t\tif (tool.name === \"LiopMeshStatus\") continue;\n\n\t\t\t\t// [LIOP-STABILITY] Allow discovery of ALL remote tools.\n\t\t\t\t// MCP Requires unique names per server session.\n\t\t\t\t// In a P2P mesh, multiple nodes might expose the same tool (e.g. LiopMeshStatus).\n\t\t\t\t// We suffix duplicate names with a short peer hash to ensure\n\t\t\t\t// ALL tools from ALL providers are correctly registered and visible.\n\t\t\t\tlet finalName = tool.name;\n\t\t\t\tif (seenNames.has(tool.name) || localToolNames.has(tool.name)) {\n\t\t\t\t\tfinalName = `${tool.name}_${peerId.slice(-4)}`;\n\t\t\t\t}\n\t\t\t\tseenNames.add(finalName);\n\n\t\t\t\tconst providerName = manifest.serverInfo?.name || \"Unknown Provider\";\n\n\t\t\t\t// [SANITIZATION] Create a clean MCP-compliant tool object\n\t\t\t\tconst baseDesc = tool.description || `Remote tool from ${providerName}`;\n\t\t\t\tconst cleanTool: {\n\t\t\t\t\tname: string;\n\t\t\t\t\tdescription: string;\n\t\t\t\t\tinputSchema: Record<string, unknown>;\n\t\t\t\t} = {\n\t\t\t\t\tname: finalName,\n\t\t\t\t\tdescription: mcpCompactToolDescriptions()\n\t\t\t\t\t\t? stripVerboseLiopToolDescription(baseDesc)\n\t\t\t\t\t\t: baseDesc,\n\t\t\t\t\tinputSchema: (tool.inputSchema || {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t}) as Record<string, unknown>,\n\t\t\t\t};\n\n\t\t\t\t// Ensure inputSchema has the mandatory 'type: object' for MCP compliance\n\t\t\t\tif (\n\t\t\t\t\ttypeof cleanTool.inputSchema === \"object\" &&\n\t\t\t\t\t!cleanTool.inputSchema.type\n\t\t\t\t) {\n\t\t\t\t\tcleanTool.inputSchema.type = \"object\";\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\ttypeof cleanTool.inputSchema === \"object\" &&\n\t\t\t\t\t!cleanTool.inputSchema.properties\n\t\t\t\t) {\n\t\t\t\t\tcleanTool.inputSchema.properties = {};\n\t\t\t\t}\n\n\t\t\t\tlet blueprint = \"\";\n\t\t\t\tif (manifest.taxonomy) {\n\t\t\t\t\tblueprint = `\\n[LIOP-DOMAIN: ${manifest.taxonomy.domain}]`;\n\t\t\t\t}\n\n\t\t\t\t// LIOP Logic-on-Origin Detection:\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic input schema\n\t\t\t\tconst properties = (cleanTool.inputSchema.properties || {}) as any;\n\t\t\t\tlet envelopeDoc = \"\";\n\t\t\t\tif (!mcpCompactToolDescriptions() && properties.payload) {\n\t\t\t\t\tenvelopeDoc = `\\n[REQUIRES: LIOP-PROTO-V1 ENVELOPE]`;\n\t\t\t\t}\n\n\t\t\t\t// INDUSTRIAL REPLICATION: Highlight schema adherence blocks\n\t\t\t\tif (\n\t\t\t\t\t!mcpCompactToolDescriptions() &&\n\t\t\t\t\tcleanTool.description.includes(\"STRICT SCHEMA ADHERENCE\")\n\t\t\t\t) {\n\t\t\t\t\tcleanTool.description = cleanTool.description.replace(\n\t\t\t\t\t\t\"STRICT SCHEMA ADHERENCE:\",\n\t\t\t\t\t\t\"[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst originStamp = mcpCompactToolDescriptions()\n\t\t\t\t\t? `\\n(Peer: ${peerId.slice(-8)})${blueprint}`\n\t\t\t\t\t: `\\n(Origin: ${peerId.slice(-8)})${blueprint}${envelopeDoc}`;\n\t\t\t\tcleanTool.description = `${cleanTool.description}${originStamp}`;\n\n\t\t\t\ttools.push(cleanTool);\n\t\t\t}\n\t\t}\n\n\t\treturn tools;\n\t}\n\n\t/**\n\t * Returns all remote resources discovered via the manifest protocol.\n\t */\n\tprivate async getRemoteResources(): Promise<\n\t\tArray<{\n\t\t\tname: string;\n\t\t\turi: string;\n\t\t\tdescription?: string;\n\t\t\tmimeType?: string;\n\t\t}>\n\t> {\n\t\t// Trigger background refresh if not already discovering\n\t\tif (!this.currentDiscovery) {\n\t\t\tthis.refreshManifestCache(true).catch(() => {});\n\t\t}\n\n\t\tconst resources: Array<{\n\t\t\tname: string;\n\t\t\turi: string;\n\t\t\tdescription?: string;\n\t\t\tmimeType?: string;\n\t\t}> = [];\n\t\tconst seenUris = new Set(this.liopServer.listResources().map((r) => r.uri));\n\n\t\tfor (const [peerId, { manifest }] of this.manifestCache.entries()) {\n\t\t\tfor (const resource of manifest.resources) {\n\t\t\t\tif (!seenUris.has(resource.uri)) {\n\t\t\t\t\tconst augmentedResource = { ...resource };\n\t\t\t\t\tconst providerName = manifest.serverInfo?.name || \"Unknown Provider\";\n\n\t\t\t\t\tlet blueprint = \"\";\n\t\t\t\t\tif (manifest.taxonomy) {\n\t\t\t\t\t\tblueprint = `\\n\\n[LIOP Zero-Trust Blueprint]\\nDomain: ${manifest.taxonomy.domain}\\nClearance Tier: ${manifest.taxonomy.clearanceTier}`;\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tmanifest.taxonomy.executionTypes &&\n\t\t\t\t\t\t\tmanifest.taxonomy.executionTypes.length > 0\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tblueprint += `\\nExecution Types: ${manifest.taxonomy.executionTypes.join(\", \")}`;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst originStamp = `\\n\\n[LIOP Zero-Trust Origin]\\nProvider: ${providerName}\\nNetwork ID: ${peerId}${blueprint}`;\n\n\t\t\t\t\t// INDUSTRIAL REPLICATION: Mark schema resources clearly\n\t\t\t\t\tif (augmentedResource.uri.startsWith(\"liop://schema/\")) {\n\t\t\t\t\t\taugmentedResource.name = `[SCHEMA] ${augmentedResource.name}`;\n\t\t\t\t\t\taugmentedResource.description = `[CRITICAL SCHEMA] ${augmentedResource.description || \"Data Dictionary for Zero-Shot Autonomy\"}${originStamp}`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\taugmentedResource.description = augmentedResource.description\n\t\t\t\t\t\t\t? `${augmentedResource.description}${originStamp}`\n\t\t\t\t\t\t\t: originStamp.trim();\n\t\t\t\t\t}\n\n\t\t\t\t\tresources.push(augmentedResource);\n\t\t\t\t\tseenUris.add(resource.uri);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn resources;\n\t}\n\n\t/**\n\t * Resolves the gRPC target (host:port) AND the peerId for a given tool name\n\t * by searching the manifest cache. Supports exact names and suffixed names.\n\t */\n\tprivate resolveManifestTarget(\n\t\ttoolName: string,\n\t): { peerId: string; originalToolName: string } | null {\n\t\t// 1. Try exact match\n\t\tfor (const [peerId, { manifest }] of this.manifestCache.entries()) {\n\t\t\tconst tool = manifest.tools.find((t) => t.name === toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn {\n\t\t\t\t\tpeerId,\n\t\t\t\t\toriginalToolName: toolName,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// 2. Try suffixed match (tool_xxxx)\n\t\tconst parts = toolName.split(\"_\");\n\t\tif (parts.length > 1) {\n\t\t\tconst suffix = parts.pop();\n\t\t\tconst baseName = parts.join(\"_\");\n\t\t\tfor (const [peerId, { manifest }] of this.manifestCache.entries()) {\n\t\t\t\tif (peerId.endsWith(suffix || \"\")) {\n\t\t\t\t\tconst tool = manifest.tools.find((t) => t.name === baseName);\n\t\t\t\t\tif (tool) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\toriginalToolName: baseName,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * Redacts a PeerID for external-facing diagnostics.\n\t * LIOP_DIAGNOSTIC_LEVEL controls verbosity:\n\t * - \"redacted\" (default): truncated to last 8 chars\n\t * - \"full\": complete PeerID (development only)\n\t */\n\tprivate redactPeerId(peerId: string): string {\n\t\tconst level = process.env.LIOP_DIAGNOSTIC_LEVEL || \"redacted\";\n\t\tif (level === \"full\") return peerId;\n\t\treturn `***${peerId.slice(-8)}`;\n\t}\n\n\t// biome-ignore lint/suspicious/noExplicitAny: MCP JSON-RPC params/id are polymorphic\n\tprivate async transcodeMcpToLiop(id: any, params: any): Promise<any> {\n\t\tconst toolName = params.name;\n\n\t\t// Intercept the static diagnostic tool\n\t\tif (toolName === \"LiopMeshStatus\") {\n\t\t\t// [INDUSTRIAL-FIX] Proactive warm-up: request a refresh when status is called.\n\t\t\t// This ensures that even if the DHT was cold, the next status call (or tools/list)\n\t\t\t// will have data.\n\t\t\tthis.refreshManifestCache(true).catch(() => {});\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: private stats for telemetry\n\t\t\tconst stats = (this as any)._discoveryStats || {\n\t\t\t\tcandidates: 0,\n\t\t\t\tsuccess: 0,\n\t\t\t\tfailures: 0,\n\t\t\t};\n\t\t\tconst providerCount = this.manifestCache.size;\n\t\t\tconst meshState = this.meshNode ? \"Active\" : \"Offline\";\n\t\t\tconst cachedTools = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tconst connections = this.meshNode\n\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t(this.meshNode as any).node?.getConnections().length\n\t\t\t\t: 0;\n\n\t\t\tconst bootstrapNodes: string[] =\n\t\t\t\tthis.meshNode &&\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal config\n\t\t\t\t(this.meshNode as any).config?.bootstrapNodes\n\t\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal config\n\t\t\t\t\t\t(this.meshNode as any).config.bootstrapNodes\n\t\t\t\t\t: [];\n\t\t\tconst bootstrapCount = bootstrapNodes.length;\n\n\t\t\tconst diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || \"redacted\";\n\t\t\tconst showBootstraps = diagLevel !== \"minimal\";\n\n\t\t\tconst bootstrapList = showBootstraps\n\t\t\t\t? bootstrapNodes\n\t\t\t\t\t\t.map((addr) => {\n\t\t\t\t\t\t\tconst parts = addr.split(\"/\");\n\t\t\t\t\t\t\tconst id = parts[parts.length - 1];\n\t\t\t\t\t\t\treturn ` • ${id ? id.slice(-8) : \"Unknown\"} (bootstrap)`;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t: \"\";\n\n\t\t\tconst routingTableSize = this.meshNode\n\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t(this.meshNode as any).getRoutingTableSize()\n\t\t\t\t: 0;\n\n\t\t\tconst rawPeerId = this.meshNode?.getPeerId() || \"Offline\";\n\t\t\tconst localPeerId =\n\t\t\t\trawPeerId === \"Offline\" ? rawPeerId : this.redactPeerId(rawPeerId);\n\n\t\t\tconst cachedToolList = Array.from(this.manifestCache.entries())\n\t\t\t\t.flatMap(([peerId, { manifest }]) =>\n\t\t\t\t\tmanifest.tools.map(\n\t\t\t\t\t\t(t) => ` • ${t.name} (from origin: ${this.redactPeerId(peerId)})`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.join(\"\\n\");\n\n\t\t\tconst statusText = [\n\t\t\t\t`LIOP Mesh Status: ${meshState === \"Active\" ? \"Active\" : \"Offline\"}`,\n\t\t\t\t`Local Agent Identity: ${localPeerId}`,\n\t\t\t\t`Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,\n\t\t\t\tshowBootstraps && bootstrapCount > 0\n\t\t\t\t\t? `\\nActive Bootstraps:\\n${bootstrapList}\\n`\n\t\t\t\t\t: \"\",\n\t\t\t\t`Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,\n\t\t\t\t`Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,\n\t\t\t\tcachedTools > 0\n\t\t\t\t\t? `\\nDiscovered Remote Tools (Zero-Trust Origins):\\n${cachedToolList}`\n\t\t\t\t\t: \"\\nNo remote tools discovered yet.\",\n\t\t\t\t// [Token Economy] Telemetry block (only appears when operations exist)\n\t\t\t\tTokenTelemetryEngine.getInstance().formatStatusBlock(),\n\t\t\t]\n\t\t\t\t.filter((line) => line !== \"\")\n\t\t\t\t.join(\"\\n\");\n\n\t\t\t// [Token Economy] Record diagnostic output telemetry\n\t\t\tconst diagTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\tdiagTelemetry.record({\n\t\t\t\ttype: \"diagnostic\",\n\t\t\t\tmethod: \"tools/call\",\n\t\t\t\ttoolName: \"LiopMeshStatus\",\n\t\t\t\testimatedInputTokens: 0,\n\t\t\t\testimatedOutputTokens: diagTelemetry.countTokens(statusText),\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\tresult: {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: statusText,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst isLocal = this.liopServer\n\t\t\t.listTools()\n\t\t\t.some((t) => t.name === toolName);\n\n\t\tif (!isLocal && this.meshNode) {\n\t\t\t// Phase 1: Cache-first — resolve directly from cached manifests (zero-latency)\n\t\t\t// Per MCP spec, tools don't change between notifications/tools/list_changed.\n\t\t\tlet target = this.resolveManifestTarget(toolName);\n\n\t\t\t// Phase 2: If not cached, trigger DHT refresh and retry\n\t\t\tif (!target) {\n\t\t\t\tawait this.refreshManifestCache();\n\t\t\t\ttarget = this.resolveManifestTarget(toolName);\n\t\t\t}\n\n\t\t\tif (target) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`,\n\t\t\t\t);\n\t\t\t\treturn this.routeToRemoteProvider(\n\t\t\t\t\tid,\n\t\t\t\t\ttarget.originalToolName,\n\t\t\t\t\ttarget.peerId,\n\t\t\t\t\tparams,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Phase 2: Try DHT-based dynamic provider discovery (fallback for unsuffixed names)\n\t\t\tlet providers: string[] = [];\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tproviders = await this.meshNode.findProviders(toolName);\n\t\t\t\tif (providers.length > 0) break;\n\t\t\t\tif (i < 2) await new Promise((r) => setTimeout(r, 1000));\n\t\t\t}\n\n\t\t\tif (providers.length > 0) {\n\t\t\t\treturn this.routeToRemoteProvider(id, toolName, providers[0], params);\n\t\t\t}\n\t\t}\n\n\t\t// If no remote provider found, try local execution\n\t\tif (isLocal) {\n\t\t\ttry {\n\t\t\t\tconst localStartTime = Date.now();\n\t\t\t\tconst result = await this.liopServer.callTool({\n\t\t\t\t\tname: toolName,\n\t\t\t\t\targuments: params.arguments || {},\n\t\t\t\t});\n\n\t\t\t\t// [Token Economy] Record local tool call telemetry\n\t\t\t\tconst localTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst localInputPayload = JSON.stringify(params.arguments || {});\n\t\t\t\tconst localOutputPayload = JSON.stringify(result);\n\t\t\t\tlocalTelemetry.record({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tmethod: \"tools/call\",\n\t\t\t\t\ttoolName,\n\t\t\t\t\testimatedInputTokens: localTelemetry.countTokens(localInputPayload),\n\t\t\t\t\testimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),\n\t\t\t\t\tdurationMs: Date.now() - localStartTime,\n\t\t\t\t});\n\n\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\terror: {\n\t\t\t\tcode: -32002,\n\t\t\t\tmessage: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async routeToRemoteProvider(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tid: any,\n\t\ttoolName: string,\n\t\tpeerId: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tparams: any,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t): Promise<any> {\n\t\tif (!this.meshNode)\n\t\t\treturn {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\terror: { code: -32603, message: \"Mesh Node inactive\" },\n\t\t\t};\n\n\t\t// Dynamic gRPC port resolution from manifest cache\n\t\tlet manifestEntry = this.manifestCache.get(peerId);\n\t\tlet grpcPort = this.defaultRpcPort;\n\n\t\tif (manifestEntry) {\n\t\t\tgrpcPort = manifestEntry.manifest.grpcPort;\n\t\t} else {\n\t\t\t// Try to query the manifest directly\n\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\tif (manifest) {\n\t\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\t\tthis.manifestCache.set(peerId, {\n\t\t\t\t\tmanifest,\n\t\t\t\t\tcachedAt: Date.now(),\n\t\t\t\t});\n\t\t\t\tmanifestEntry = this.manifestCache.get(peerId);\n\t\t\t}\n\t\t}\n\n\t\t// Host-mode convenience (opt-in):\n\t\t// Some Docker Desktop setups publish gRPC ports on the host as 13011/13021/13031.\n\t\t// Inside Docker networks we must keep the manifest-advertised container port.\n\t\tif (manifestEntry && process.env.LIOP_USE_PUBLISHED_GRPC_PORTS === \"1\") {\n\t\t\tconst providerName =\n\t\t\t\tmanifestEntry.manifest.serverInfo?.name?.toLowerCase() || \"\";\n\t\t\tif (providerName.includes(\"vault\")) grpcPort = 13011;\n\t\t\telse if (providerName.includes(\"bank\")) grpcPort = 13021;\n\t\t\telse if (providerName.includes(\"oracle\")) grpcPort = 13031;\n\t\t}\n\n\t\t// Resolve IP from active connections\n\t\tconst addrs = await this.meshNode.resolvePeer(peerId);\n\t\tlet targetAddr: string | null = null;\n\n\t\t// [LIOP-ALPHA] Check if the peer is running on the same physical machine\n\t\t// by comparing its advertised IPs against our local OS interfaces.\n\t\tconst os = await import(\"node:os\");\n\t\tconst localInterfaces = Object.values(os.networkInterfaces())\n\t\t\t.flat()\n\t\t\t.filter((i) => i?.family === \"IPv4\")\n\t\t\t.map((i) => i?.address);\n\n\t\t// Loop through all advertised addresses to find the optimal target\n\t\tfor (const addr of addrs) {\n\t\t\tconst parts = addr.split(\"/\");\n\t\t\tconst ipIdx = parts.indexOf(\"ip4\");\n\t\t\tif (ipIdx !== -1) {\n\t\t\t\tconst advertisedIp = parts[ipIdx + 1];\n\n\t\t\t\t// Loopback priority or Same-Machine detection\n\t\t\t\tif (\n\t\t\t\t\tadvertisedIp === \"127.0.0.1\" ||\n\t\t\t\t\tlocalInterfaces.includes(advertisedIp)\n\t\t\t\t) {\n\t\t\t\t\ttargetAddr = `127.0.0.1:${grpcPort}`;\n\t\t\t\t\tbreak; // Supreme priority for local execution\n\t\t\t\t}\n\n\t\t\t\t// Default to first discovered valid external IP\n\t\t\t\tif (!targetAddr) {\n\t\t\t\t\ttargetAddr = `${advertisedIp}:${grpcPort}`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!targetAddr) {\n\t\t\t// Fallback to localhost with the dynamically resolved port\n\t\t\ttargetAddr = `127.0.0.1:${grpcPort}`;\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`,\n\t\t);\n\n\t\tconst remoteClient = new liopV1.LogicMesh(\n\t\t\ttargetAddr,\n\t\t\tcreateChannelCredentials(),\n\t\t);\n\t\treturn this.performTranscoding(id, remoteClient, toolName, params, peerId);\n\t}\n\n\tprivate async performTranscoding(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tid: any,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: gRPC client from dynamic proto-loader\n\t\tclient: any,\n\t\ttoolName: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tparams: any,\n\t\tpeerId?: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t): Promise<any> {\n\t\tconst capabilityHash = toolName;\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(Buffer.from(capabilityHash))\n\t\t\t: Buffer.from([]);\n\n\t\tconst transcodingStartTime = Date.now();\n\n\t\treturn new Promise((resolve) => {\n\t\t\tclient.negotiateIntent(\n\t\t\t\t{\n\t\t\t\t\tagent_did: `did:liop:${this.meshNode?.getPeerId() || \"mcp-proxy\"}`,\n\t\t\t\t\tcapability_hash: capabilityHash,\n\t\t\t\t\tproof_of_intent: proofOfIntent,\n\t\t\t\t},\n\t\t\t\tasync (err: Error | null, response: IntentResponse) => {\n\t\t\t\t\tif (err || !response.accepted) {\n\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `PQC Handshake Failed: ${err?.message || \"Rejected\"}`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tconst { ciphertext, sharedSecret } =\n\t\t\t\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(\n\t\t\t\t\t\t\tresponse.kyber_public_key,\n\t\t\t\t\t\t);\n\t\t\t\t\t// SECURITY: Avoid AES-GCM nonce reuse across multiple ciphertexts.\n\t\t\t\t\t// We embed arguments directly into the proxy logic so we only encrypt ONE payload per session/nonce.\n\t\t\t\t\tconst embeddedArgsJson = JSON.stringify(params.arguments || {});\n\t\t\t\t\tconst proxyLogic = `return { \"__liop_proxy_tool\": \"${toolName}\", \"__liop_proxy_args\": ${embeddedArgsJson} };`;\n\t\t\t\t\tconst nonce = crypto.randomBytes(12);\n\n\t\t\t\t\tconst sealedLogic = this.encryptWithNonce(\n\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\tsharedSecret,\n\t\t\t\t\t\tnonce,\n\t\t\t\t\t);\n\n\t\t\t\t\tconst call = client.executeLogic({\n\t\t\t\t\t\tsession_token: response.session_token,\n\t\t\t\t\t\twasm_binary: new Uint8Array(sealedLogic),\n\t\t\t\t\t\tinputs: {},\n\t\t\t\t\t\tpqc_ciphertext: ciphertext,\n\t\t\t\t\t\taes_nonce: nonce,\n\t\t\t\t\t});\n\n\t\t\t\t\tlet resultBody = \"\";\n\t\t\t\t\tlet lastResponse: LogicResponse | null = null;\n\t\t\t\t\tcall.on(\"data\", (grpcRes: LogicResponse) => {\n\t\t\t\t\t\tresultBody += grpcRes.semantic_evidence;\n\t\t\t\t\t\tlastResponse = grpcRes;\n\t\t\t\t\t});\n\t\t\t\t\tcall.on(\"end\", async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (lastResponse) {\n\t\t\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.zk_receipt),\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: \"SECURITY ALERT: Remote response failed cryptographic integrity audit.\",\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst parsedResult = JSON.parse(resultBody);\n\n\t\t\t\t\t\t\t// [Token Economy] Record remote tool call telemetry\n\t\t\t\t\t\t\tconst remoteTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\t\t\tremoteTelemetry.record({\n\t\t\t\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\t\t\t\tmethod: \"tools/call\",\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\t\testimatedInputTokens:\n\t\t\t\t\t\t\t\t\tremoteTelemetry.countTokens(embeddedArgsJson),\n\t\t\t\t\t\t\t\testimatedOutputTokens: remoteTelemetry.countTokens(resultBody),\n\t\t\t\t\t\t\t\tdurationMs: Date.now() - transcodingStartTime,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tresolve({ jsonrpc: \"2.0\", id, result: parsedResult });\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tresult: { content: [{ type: \"text\", text: resultBody }] },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tcall.on(\"error\", (e: Error) =>\n\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{ type: \"text\", text: `LIOP gRPC Error: ${e.message}` },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate encryptWithNonce(\n\t\tpayload: Buffer,\n\t\tkey: Uint8Array,\n\t\tnonce: Buffer,\n\t): Buffer {\n\t\tconst cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce);\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\treturn Buffer.concat([encrypted, cipher.getAuthTag()]);\n\t}\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-S6RJHZV2.js';import n from'path';import {fileURLToPath}from'url';import*as r from'@grpc/grpc-js';import*as d from'@grpc/proto-loader';import*as t from'fs';var m=fileURLToPath(import.meta.url),s=n.dirname(m),u=[n.resolve(s,"./protocol/liop_core.proto"),n.resolve(s,"../protocol/liop_core.proto")],g=n.resolve(s,"../../../../protocol/proto/liop_core.proto"),p=u.find(e=>t.existsSync(e))||g;t.existsSync(p)||a.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${p}`);var S=d.loadSync(p,{keepCase:true,longs:String,enums:String,defaults:true,oneofs:true}),y=r.loadPackageDefinition(S),_=y.liop.v1;function x(e){if(!e?.certChain||!e?.privateKey)return r.ServerCredentials.createInsecure();try{let o=e.rootCert?t.readFileSync(e.rootCert):null,c=t.readFileSync(e.certChain),a=t.readFileSync(e.privateKey);return r.ServerCredentials.createSsl(o,[{cert_chain:c,private_key:a}])}catch(o){return a.info(`[LIOP-TLS] Failed to load certificates, falling back to insecure: ${o}`),r.ServerCredentials.createInsecure()}}function K(e){if(!e?.rootCert)return r.credentials.createInsecure();try{let o=t.readFileSync(e.rootCert),c=e.certChain?t.readFileSync(e.certChain):void 0,a=e.privateKey?t.readFileSync(e.privateKey):void 0;return r.credentials.createSsl(o,a,c)}catch(o){return a.info(`[LIOP-TLS] Failed to load certificates, falling back to insecure: ${o}`),r.credentials.createInsecure()}}export{_ as a,x as b,K as c};//# sourceMappingURL=chunk-HM77MWB6.js.map
2
- //# sourceMappingURL=chunk-HM77MWB6.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc/proto.ts","../src/rpc/tls.ts"],"names":["__filename","fileURLToPath","__dirname","path","PROD_PATHS","DEV_PROTO_PATH","PROTO_PATH","p","l","log","packageDefinition","liopProto","f","liopV1","createServerCredentials","tls","rootCert","certChain","privateKey","error","createChannelCredentials"],"mappings":"kLAKA,IAAMA,CAAAA,CAAaC,aAAAA,CAAc,YAAY,GAAG,CAAA,CAC1CC,CAAAA,CAAYC,CAAAA,CAAK,OAAA,CAAQH,CAAU,EAMnCI,CAAAA,CAAa,CAClBD,EAAK,OAAA,CAAQD,CAAAA,CAAW,4BAA4B,CAAA,CACpDC,CAAAA,CAAK,OAAA,CAAQD,CAAAA,CAAW,6BAA6B,CACtD,EAEMG,CAAAA,CAAiBF,CAAAA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AAAA,CACfL,CAAAA,CAC0B,CAC1B,GAAI,CAACA,GAAK,QAAA,CACT,OAAY,cAAY,cAAA,EAAe,CAGxC,GAAI,CACH,IAAMC,CAAAA,CAAc,eAAaD,CAAAA,CAAI,QAAQ,CAAA,CACvCE,CAAAA,CAAYF,CAAAA,CAAI,SAAA,CAChB,eAAaA,CAAAA,CAAI,SAAS,CAAA,CAC7B,KAAA,CAAA,CACGG,CAAAA,CAAaH,CAAAA,CAAI,WACjB,CAAA,CAAA,YAAA,CAAaA,CAAAA,CAAI,UAAU,CAAA,CAC9B,KAAA,CAAA,CAEH,OAAY,cAAY,SAAA,CAAUC,CAAAA,CAAUE,CAAAA,CAAYD,CAAS,CAClE,CAAA,MAASE,EAAO,CACf,OAAAV,CAAAA,CAAI,IAAA,CACH,CAAA,kEAAA,EAAqEU,CAAK,EAC3E,CAAA,CACY,CAAA,CAAA,WAAA,CAAY,cAAA,EACzB,CACD","file":"chunk-HM77MWB6.js","sourcesContent":["import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport * as protoLoader from \"@grpc/proto-loader\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nimport * as fs from \"node:fs\";\nimport { log } from \"../utils/logger.js\";\n\n// Selection logic: support both flat dist/ and original src/ structure\nconst PROD_PATHS = [\n\tpath.resolve(__dirname, \"./protocol/liop_core.proto\"), // Flat dist/ (tsup)\n\tpath.resolve(__dirname, \"../protocol/liop_core.proto\"), // dist/rpc/ (tsc)\n];\n\nconst DEV_PROTO_PATH = path.resolve(\n\t__dirname,\n\t\"../../../../protocol/proto/liop_core.proto\",\n);\n\n// Selection logic\nconst PROTO_PATH = PROD_PATHS.find((p) => fs.existsSync(p)) || DEV_PROTO_PATH;\n\nif (!fs.existsSync(PROTO_PATH)) {\n\tlog.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${PROTO_PATH}`);\n}\n\n/**\n * LIOP Proto Loader\n * Loads the core gRPC definitions for the Logic-Injection-on-Origin Protocol.\n */\nconst packageDefinition = protoLoader.loadSync(PROTO_PATH, {\n\tkeepCase: true,\n\tlongs: String,\n\tenums: String,\n\tdefaults: true,\n\toneofs: true,\n});\n\n// biome-ignore lint/suspicious/noExplicitAny: gRPC dynamic loading requires any for the service definition map\nexport const liopProto = grpc.loadPackageDefinition(packageDefinition) as any;\nexport const liopV1 = liopProto.liop.v1;\n","/**\n * LIOP TLS Configuration\n *\n * Provides conditional TLS credential factories for gRPC connections.\n * When TLS options are provided, connections are secured with mutual TLS.\n * Otherwise, falls back to insecure credentials (alpha/development mode).\n */\n\nimport * as fs from \"node:fs\";\nimport * as grpc from \"@grpc/grpc-js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopTlsOptions {\n\t/** Path to the root CA certificate (PEM format) */\n\trootCert?: string;\n\t/** Path to the server/client certificate (PEM format) */\n\tcertChain?: string;\n\t/** Path to the private key (PEM format) */\n\tprivateKey?: string;\n}\n\n/**\n * Creates gRPC server credentials from TLS options.\n * Falls back to insecure if no options are provided.\n */\nexport function createServerCredentials(\n\ttls?: LiopTlsOptions,\n): grpc.ServerCredentials {\n\tif (!tls?.certChain || !tls?.privateKey) {\n\t\treturn grpc.ServerCredentials.createInsecure();\n\t}\n\n\ttry {\n\t\tconst rootCert = tls.rootCert ? fs.readFileSync(tls.rootCert) : null;\n\t\tconst certChain = fs.readFileSync(tls.certChain);\n\t\tconst privateKey = fs.readFileSync(tls.privateKey);\n\n\t\treturn grpc.ServerCredentials.createSsl(rootCert, [\n\t\t\t{ cert_chain: certChain, private_key: privateKey },\n\t\t]);\n\t} catch (error) {\n\t\tlog.info(\n\t\t\t`[LIOP-TLS] Failed to load certificates, falling back to insecure: ${error}`,\n\t\t);\n\t\treturn grpc.ServerCredentials.createInsecure();\n\t}\n}\n\n/**\n * Creates gRPC channel credentials from TLS options.\n * Falls back to insecure if no options are provided.\n */\nexport function createChannelCredentials(\n\ttls?: LiopTlsOptions,\n): grpc.ChannelCredentials {\n\tif (!tls?.rootCert) {\n\t\treturn grpc.credentials.createInsecure();\n\t}\n\n\ttry {\n\t\tconst rootCert = fs.readFileSync(tls.rootCert);\n\t\tconst certChain = tls.certChain\n\t\t\t? fs.readFileSync(tls.certChain)\n\t\t\t: undefined;\n\t\tconst privateKey = tls.privateKey\n\t\t\t? fs.readFileSync(tls.privateKey)\n\t\t\t: undefined;\n\n\t\treturn grpc.credentials.createSsl(rootCert, privateKey, certChain);\n\t} catch (error) {\n\t\tlog.info(\n\t\t\t`[LIOP-TLS] Failed to load certificates, falling back to insecure: ${error}`,\n\t\t);\n\t\treturn grpc.credentials.createInsecure();\n\t}\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sandbox/guardian.ts","../src/sandbox/wasi.ts"],"names":["GuardianError","message","ASTGuardian","module","imports","_importCount","ALLOWED_WASI_FUNCTIONS","imp","originalEmit","name","data","args","WasiSandbox","config","crypto","WASI","error","compiledLogic","records","inputs","startTime","instance","stdoutPath","stderrPath","stdout","stderr","duration","sandboxEnv","env","key","value","deepFreeze","obj","processedLogic","scriptCode","script","vm","context","output","rawFuel","fuelUsed"],"mappings":"0IAAO,IAAMA,CAAAA,CAAN,cAA4B,KAAM,CACxC,YAAYC,CAAAA,CAAiB,CAC5B,KAAA,CAAM,CAAA,0BAAA,EAA6BA,CAAO,CAAA,CAAE,CAAA,CAC5C,IAAA,CAAK,IAAA,CAAO,gBACb,CACD,CAAA,CAQaC,CAAAA,CAAc,CAO1B,OAAA,CAAQC,CAAAA,CAAkC,CACzC,IAAMC,EAAU,WAAA,CAAY,MAAA,CAAO,OAAA,CAAQD,CAAM,EAC7CE,CAAAA,CAAe,CAAA,CAEbC,CAAAA,CAAyB,IAAI,IAAI,CACtC,UAAA,CACA,SAAA,CACA,UAAA,CACA,SAAA,CACA,aAAA,CACA,mBAAA,CACA,UAAA,CACA,iBACA,gBAAA,CACA,YAAA,CACA,WAAA,CACA,gBAA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AAcT,CAAAA,CAAY,CAC5C,IAAA,CAAM,cAAA,CACN,MAAA,CAAQ,gBACT,CAAC,CAAA,CAGKW,CAAAA,CAASH,CAAAA,CAAO,YAAA,CAAaE,CAAAA,CAAS,CAC3C,OAAA,CAAS,GAAA,CACT,aAAA,CAAe,CAAA,CAAA,CACf,aAAA,CAAe,CAAA,CAChB,CAAC,CAAA,CAEKX,CAAAA,CAAW,WAAA,CAAY,GAAA,EAAI,CAAIN,CAAAA,CAE/BmB,CAAAA,CAAU,IAAA,CAAK,KAAA,CAAMb,CAAAA,CAAW,IAAA,CAAO,GAAG,CAAA,CAC1Cc,CAAAA,CAAW,IAAA,CAAK,IAAA,CAAKD,CAAAA,CAAU,GAAG,EAAI,GAAA,CAE5C,GAAIC,CAAAA,CAAW,GAAA,CACd,MAAM,IAAI,KAAA,CACT,yDACD,CAAA,CAGD,OAAO,CAAE,MAAA,CAAAF,CAAAA,CAAQ,YAAA,CAAcE,CAAS,CACzC,CAAA,MAASxB,CAAAA,CAAO,CACf,MAAM,IAAI,KAAA,CACT,CAAA,kBAAA,EAAqBA,CAAAA,YAAiB,KAAA,CAAQA,CAAAA,CAAM,OAAA,CAAU,mBAAmB,CAAA,CAClF,CACD,CACD,CACD,CAKA,MAAa,QAAA,EAA0B,CACtC,GAAI,CACC,IAAA,CAAK,YAAA,EAAc,MAAM,IAAA,CAAK,YAAA,CAAa,KAAA,EAAM,CACjD,IAAA,CAAK,YAAA,EAAc,MAAM,IAAA,CAAK,YAAA,CAAa,KAAA,EAAM,CACrD,MAAS,CAAA,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAY,CAAE,SAAA,CAAW,CAAA,CAAA,CAAM,KAAA,CAAO,CAAA,CAAK,CAAC,EAC9D,CAAA,KAAa,CAEb,CACD,CACD","file":"chunk-HNDVAKEK.js","sourcesContent":["export class GuardianError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`AST Sec-Policy Violation: ${message}`);\n\t\tthis.name = \"GuardianError\";\n\t}\n}\n\n/**\n * The Guardian-TS Module\n * Scans the Abstract Syntax Tree (AST) imports of incoming WASM\n * before it reaches the V8 Wasmtime engine to prevent sandbox-escape\n * zero-days, resource exhaustion bombs, and evasive execution.\n */\nexport const ASTGuardian = {\n\t/**\n\t * Analyzes the WebAssembly Module interface proactively.\n\t *\n\t * @param module - The compiled WebAssembly.Module to inspect\n\t * @throws {GuardianError} If illegal imports or capabilities are detected\n\t */\n\tanalyze(module: WebAssembly.Module): void {\n\t\tconst imports = WebAssembly.Module.imports(module);\n\t\tlet _importCount = 0;\n\n\t\tconst ALLOWED_WASI_FUNCTIONS = new Set([\n\t\t\t\"fd_write\",\n\t\t\t\"fd_read\",\n\t\t\t\"fd_close\",\n\t\t\t\"fd_seek\",\n\t\t\t\"environ_get\",\n\t\t\t\"environ_sizes_get\",\n\t\t\t\"args_get\",\n\t\t\t\"args_sizes_get\",\n\t\t\t\"clock_time_get\",\n\t\t\t\"random_get\",\n\t\t\t\"proc_exit\",\n\t\t\t\"fd_prestat_get\",\n\t\t\t\"fd_prestat_dir_name\",\n\t\t\t\"fd_fdstat_get\",\n\t\t]);\n\n\t\tfor (const imp of imports) {\n\t\t\t// Strict Sandbox Validation: Only allow WASI preview 1 specific whitelisted functions.\n\t\t\tif (imp.module === \"wasi_snapshot_preview1\") {\n\t\t\t\tif (!ALLOWED_WASI_FUNCTIONS.has(imp.name)) {\n\t\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\t`Banned WASI Import Detected: ${imp.module}/${imp.name}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t`Banned Host Import Module Detected: ${imp.module}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t_importCount++;\n\n\t\t\tif (_importCount > 128) {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\"Import limit exceeded. Possible resource exhaustion attack.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// In Node.js / V8, the maximum module size and function limits\n\t\t// are natively enforced by the engine during compilation.\n\t\t// A successfully compiled WebAssembly.Module already passed structural checks.\n\t},\n};\n","import crypto from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport vm from \"node:vm\";\nimport { WASI } from \"node:wasi\";\nimport { ASTGuardian } from \"./guardian.js\";\n\n// Silence Node.js ExperimentalWarning for WASI (Industrial console parity)\nconst originalEmit = process.emit;\n// @ts-expect-error\nprocess.emit = (name, data, ...args) => {\n\tif (\n\t\t(name === \"warning\" &&\n\t\t\ttypeof data === \"object\" &&\n\t\t\t(data as Record<string, unknown>).name === \"ExperimentalWarning\" &&\n\t\t\tString((data as Record<string, unknown>).message).includes(\"WASI\")) ||\n\t\tString((data as Record<string, unknown>).message).includes(\"importing WASI\")\n\t) {\n\t\treturn false;\n\t}\n\treturn originalEmit.call(process, name, data, ...args);\n};\n\nexport interface SandboxConfig {\n\tallowEnv?: boolean;\n\tallowedDirectories?: Record<string, string>; // guestPath -> hostPath\n\tmemoryLimitMb?: number;\n}\n\n/**\n * LIOP WasiSandbox (Industrial Grade)\n *\n * Provides a production-grade isolated environment for executing untrusted logic.\n * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened\n * V8 Isolate fallback for dynamic JS-to-WASM logic injection.\n */\nexport class WasiSandbox {\n\tprivate wasi!: WASI;\n\tprivate sandboxId: string;\n\tprivate workingDir: string;\n\tprivate config: SandboxConfig;\n\tprivate stdoutHandle: fs.FileHandle | null = null;\n\tprivate stderrHandle: fs.FileHandle | null = null;\n\n\tconstructor(config: SandboxConfig = {}) {\n\t\tthis.sandboxId = crypto.randomUUID();\n\t\t// Use a dedicated LIOP directory in the OS temp folder\n\t\tthis.workingDir = path.join(\n\t\t\tos.tmpdir(),\n\t\t\t\"liop-mesh\",\n\t\t\t\"sandboxes\",\n\t\t\tthis.sandboxId,\n\t\t);\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Initializes the physical sandbox environment with strict directory lockdown.\n\t */\n\tpublic async init(): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.mkdir(this.workingDir, { recursive: true });\n\n\t\t\t// Initialize WASI with explicit limits\n\t\t\tthis.stdoutHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stdout.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\t\t\tthis.stderrHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stderr.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\n\t\t\tthis.wasi = new WASI({\n\t\t\t\tversion: \"preview1\",\n\t\t\t\targs: [\"liop_runtime\"],\n\t\t\t\tenv: this.config.allowEnv\n\t\t\t\t\t? process.env\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tNODE_ENV: \"production\",\n\t\t\t\t\t\t\tLIOP_NODE: \"true\",\n\t\t\t\t\t\t\tRUNTIME_ID: this.sandboxId,\n\t\t\t\t\t\t},\n\t\t\t\tpreopens: {\n\t\t\t\t\t\"/sandbox\": this.workingDir,\n\t\t\t\t\t...this.config.allowedDirectories,\n\t\t\t\t},\n\t\t\t\tstdout: this.stdoutHandle.fd,\n\t\t\t\tstderr: this.stderrHandle.fd,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Sandbox Initialization Failed: ${error instanceof Error ? error.message : \"FS Error\"}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Executes logic (WASM or JS-Wrapped) with hard resource limits.\n\t */\n\tpublic async execute(\n\t\tcompiledLogic: Buffer | string,\n\t\trecords: Record<string, unknown>[] = [],\n\t\tinputs: Record<string, unknown> = {},\n\t): Promise<{ output: unknown; fuelConsumed: number }> {\n\t\tconst startTime = performance.now();\n\n\t\tif (compiledLogic instanceof Buffer) {\n\t\t\t// Path A: Native WebAssembly Isolation\n\t\t\ttry {\n\t\t\t\tconst module = await WebAssembly.compile(new Uint8Array(compiledLogic));\n\n\t\t\t\t// Tier-0 Guardian: Static analysis to prevent sandbox escapes\n\t\t\t\tASTGuardian.analyze(module);\n\n\t\t\t\tconst instance = await WebAssembly.instantiate(\n\t\t\t\t\tmodule,\n\t\t\t\t\tthis.wasi.getImportObject() as WebAssembly.Imports,\n\t\t\t\t);\n\n\t\t\t\t// Standard entry point\n\t\t\t\tthis.wasi.start(instance);\n\n\t\t\t\t// Capture output from the sandbox\n\t\t\t\tconst stdoutPath = path.join(this.workingDir, \"stdout.log\");\n\t\t\t\tconst stderrPath = path.join(this.workingDir, \"stderr.log\");\n\t\t\t\tconst stdout = await fs.readFile(stdoutPath, \"utf-8\");\n\t\t\t\tconst stderr = await fs.readFile(stderrPath, \"utf-8\");\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\treturn {\n\t\t\t\t\toutput:\n\t\t\t\t\t\tstdout || (stderr ? `Error: ${stderr}` : \"WASM_EXECUTION_SUCCESS\"),\n\t\t\t\t\tfuelConsumed: Math.floor(duration * 1000),\n\t\t\t\t};\n\t\t\t} catch (error: unknown) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`WASM Runtime Error: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Path B: Hardened V8 Isolate Fallback\n\t\t\t// Uses node:vm with zero-prototype objects to prevent prototype pollution escapes.\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for Sandbox global poisoning\n\t\t\tconst sandboxEnv: any = Object.create(null); // Isolated global object\n\t\t\tconst env = { records, ...inputs };\n\n\t\t\t// Explicitly poison Node.js escape vectors in the context\n\t\t\tsandboxEnv.require = undefined;\n\t\t\tsandboxEnv.process = undefined;\n\t\t\tsandboxEnv.global = undefined;\n\t\t\tsandboxEnv.globalThis = undefined;\n\t\t\tsandboxEnv.Buffer = undefined;\n\t\t\tsandboxEnv.setTimeout = undefined;\n\t\t\tsandboxEnv.setInterval = undefined;\n\t\t\tsandboxEnv.setImmediate = undefined;\n\t\t\tsandboxEnv.queueMicrotask = undefined;\n\t\t\tsandboxEnv.eval = undefined;\n\t\t\tsandboxEnv.Function = undefined;\n\t\t\tsandboxEnv.SharedArrayBuffer = undefined;\n\t\t\tsandboxEnv.Date = undefined;\n\n\t\t\t// [DoS Defense] Block off-heap memory allocation vectors.\n\t\t\t// Logic-on-Origin operates on JSON data (env.records) — binary buffers\n\t\t\t// serve no legitimate purpose and enable memory exhaustion DoS.\n\t\t\t// (Uint8Array(2GB) bypassed Piscina's maxOldGenerationSizeMb limit)\n\t\t\tsandboxEnv.ArrayBuffer = undefined;\n\t\t\tsandboxEnv.Uint8Array = undefined;\n\t\t\tsandboxEnv.Int8Array = undefined;\n\t\t\tsandboxEnv.Uint16Array = undefined;\n\t\t\tsandboxEnv.Int16Array = undefined;\n\t\t\tsandboxEnv.Uint32Array = undefined;\n\t\t\tsandboxEnv.Int32Array = undefined;\n\t\t\tsandboxEnv.Float32Array = undefined;\n\t\t\tsandboxEnv.Float64Array = undefined;\n\t\t\tsandboxEnv.BigInt64Array = undefined;\n\t\t\tsandboxEnv.BigUint64Array = undefined;\n\t\t\tsandboxEnv.DataView = undefined;\n\n\t\t\t// Inject strictly monitored globals\n\t\t\tsandboxEnv.records = JSON.parse(JSON.stringify(records)); // Deep copy safety\n\t\t\tsandboxEnv.env = JSON.parse(JSON.stringify(env));\n\n\t\t\tfor (const [key, value] of Object.entries(inputs)) {\n\t\t\t\tsandboxEnv[key] = JSON.parse(JSON.stringify(value));\n\t\t\t}\n\n\t\t\t// Freeze the sandbox context to prevent mutation (SEC-GAP-1)\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for recursive deep freeze of unknown data\n\t\t\tconst deepFreeze = (obj: any) => {\n\t\t\t\tif (obj && typeof obj === \"object\" && !Object.isFrozen(obj)) {\n\t\t\t\t\tObject.freeze(obj);\n\t\t\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\t\t\tdeepFreeze(obj[key]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn obj;\n\t\t\t};\n\n\t\t\tdeepFreeze(sandboxEnv.records);\n\t\t\tdeepFreeze(sandboxEnv.env);\n\n\t\t\t// Prevent property addition/modification on global scope\n\t\t\tfor (const key of Object.keys(sandboxEnv)) {\n\t\t\t\tObject.defineProperty(sandboxEnv, key, {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// LIOP Execution Wrapper\n\t\t\t// Host-side logic transformation to avoid 'new Function' in sandbox\n\t\t\tlet processedLogic = String(compiledLogic);\n\t\t\tif (\n\t\t\t\t/^\\s*return\\s/m.test(processedLogic) ||\n\t\t\t\t!processedLogic.includes(\"function liop_main\")\n\t\t\t) {\n\t\t\t\tif (!processedLogic.includes(\"function liop_main\")) {\n\t\t\t\t\tprocessedLogic = `function liop_main(env) {\\n${processedLogic}\\n}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst scriptCode = `\n\t\t\t\t(function() {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tObject.freeze(Object.prototype);\n\t\t\t\t\t\tObject.freeze(Array.prototype);\n\t\t\t\t\t\tObject.freeze(String.prototype);\n\t\t\t\t\t\tObject.freeze(Number.prototype);\n\t\t\t\t\t\tObject.freeze(Boolean.prototype);\n\t\t\t\t\t\tObject.freeze(Object.getPrototypeOf(function(){}));\n\n\t\t\t\t\t\t${processedLogic}\n\t\t\t\t\t\tif (typeof liop_main === 'function') {\n\t\t\t\t\t\t\treturn liop_main(env);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"ERR_NO_ENTRY_POINT\";\n\t\t\t\t\t} catch(e) {\n\t\t\t\t\t\treturn \"LogicError: \" + e.message;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t`;\n\n\t\t\ttry {\n\t\t\t\tconst script = new vm.Script(scriptCode, {\n\t\t\t\t\tfilename: `liop-sandbox-${this.sandboxId.slice(0, 8)}.js`,\n\t\t\t\t});\n\n\t\t\t\tconst context = vm.createContext(sandboxEnv, {\n\t\t\t\t\tname: \"LIOP Isolate\",\n\t\t\t\t\torigin: \"liop://sandbox\",\n\t\t\t\t});\n\n\t\t\t\t// Execution with hard CPU and Memory limits (Fuel)\n\t\t\t\tconst output = script.runInContext(context, {\n\t\t\t\t\ttimeout: 5000,\n\t\t\t\t\tbreakOnSigint: true,\n\t\t\t\t\tdisplayErrors: true,\n\t\t\t\t});\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\t// SEC: Normalize fuel to buckets of 100 to prevent timing side-channel inference\n\t\t\t\tconst rawFuel = Math.floor(duration * 1500 + 100);\n\t\t\t\tconst fuelUsed = Math.ceil(rawFuel / 100) * 100;\n\n\t\t\t\tif (fuelUsed > 1000000) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn { output, fuelConsumed: fuelUsed };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`V8 Isolate Fault: ${error instanceof Error ? error.message : \"Execution Timeout\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Physically cleans up the sandbox and releases resources.\n\t */\n\tpublic async teardown(): Promise<void> {\n\t\ttry {\n\t\t\tif (this.stdoutHandle) await this.stdoutHandle.close();\n\t\t\tif (this.stderrHandle) await this.stderrHandle.close();\n\t\t\tawait fs.rm(this.workingDir, { recursive: true, force: true });\n\t\t} catch (_e) {\n\t\t\t// Silent fail on teardown to prevent process crashes\n\t\t}\n\t}\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {z}from'zod';var o=z.object({name:z.string(),description:z.string().optional(),inputSchema:z.record(z.string(),z.unknown())}),i=z.object({uri:z.string(),name:z.string(),description:z.string().optional(),mimeType:z.string().optional()}),s=z.object({name:z.string(),description:z.string().optional(),arguments:z.array(z.object({name:z.string(),description:z.string().optional(),required:z.boolean().optional()})).optional()});export{o as a,i as b,s as c};//# sourceMappingURL=chunk-HQZHZM6U.js.map
2
- //# sourceMappingURL=chunk-HQZHZM6U.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/types.ts"],"names":["ToolSchema","z","ResourceSchema","PromptSchema"],"mappings":"oBAMO,IAAMA,EAAaC,CAAAA,CAAE,MAAA,CAAO,CAClC,IAAA,CAAMA,CAAAA,CAAE,QAAO,CACf,WAAA,CAAaA,EAAE,MAAA,EAAO,CAAE,UAAS,CACjC,WAAA,CAAaA,CAAAA,CAAE,MAAA,CAAOA,CAAAA,CAAE,MAAA,GAAUA,CAAAA,CAAE,OAAA,EAAS,CAC9C,CAAC,EAIYC,CAAAA,CAAiBD,CAAAA,CAAE,OAAO,CACtC,GAAA,CAAKA,EAAE,MAAA,EAAO,CACd,KAAMA,CAAAA,CAAE,MAAA,GACR,WAAA,CAAaA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS,CACjC,SAAUA,CAAAA,CAAE,MAAA,GAAS,QAAA,EACtB,CAAC,CAAA,CAIYE,CAAAA,CAAeF,EAAE,MAAA,CAAO,CACpC,KAAMA,CAAAA,CAAE,MAAA,GACR,WAAA,CAAaA,CAAAA,CAAE,QAAO,CAAE,QAAA,EAAS,CACjC,SAAA,CAAWA,CAAAA,CACT,KAAA,CACAA,EAAE,MAAA,CAAO,CACR,KAAMA,CAAAA,CAAE,MAAA,GACR,WAAA,CAAaA,CAAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS,CACjC,SAAUA,CAAAA,CAAE,OAAA,GAAU,QAAA,EACvB,CAAC,CACF,CAAA,CACC,QAAA,EACH,CAAC","file":"chunk-HQZHZM6U.js","sourcesContent":["import { z } from \"zod\";\n\n/**\n * Base Protocol Types representing parity with Model Context Protocol\n */\n\nexport const ToolSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tinputSchema: z.record(z.string(), z.unknown()), // Represents a JSON Schema\n});\n\nexport type Tool = z.infer<typeof ToolSchema>;\n\nexport const ResourceSchema = z.object({\n\turi: z.string(),\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tmimeType: z.string().optional(),\n});\n\nexport type Resource = z.infer<typeof ResourceSchema>;\n\nexport const PromptSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\targuments: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string(),\n\t\t\t\tdescription: z.string().optional(),\n\t\t\t\trequired: z.boolean().optional(),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n});\n\nexport type Prompt = z.infer<typeof PromptSchema>;\n\nexport interface CallToolRequest {\n\tname: string;\n\targuments?: Record<string, unknown>;\n}\n\nexport interface CallToolResult {\n\tcontent: Array<{\n\t\ttype: \"text\" | \"image\" | \"resource\";\n\t\ttext?: string;\n\t\tdata?: string;\n\t\tmimeType?: string;\n\t\tresource?: {\n\t\t\turi: string;\n\t\t\ttext?: string;\n\t\t\tblob?: string;\n\t\t};\n\t}>;\n\tisError?: boolean;\n}\n\nexport interface GetPromptRequest {\n\tname: string;\n\targuments?: Record<string, string>;\n}\n\nexport interface GetPromptResult {\n\tdescription?: string;\n\tmessages: Array<{\n\t\trole: \"user\" | \"assistant\";\n\t\tcontent:\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| { type: \"image\"; data: string; mimeType: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"resource\";\n\t\t\t\t\tresource: { uri: string; text?: string; blob?: string };\n\t\t\t };\n\t}>;\n}\n\nexport interface ServerInfo {\n\tname: string;\n\tversion: string;\n\tcapabilities?: {\n\t\tprompts?: { listChanged?: boolean };\n\t\tresources?: { subscribe?: boolean; listChanged?: boolean };\n\t\ttools?: { listChanged?: boolean };\n\t\tlogging?: Record<string, unknown>;\n\t};\n}\n\nexport interface McpRequest {\n\tmethod: string;\n\tparams?: unknown;\n\tid?: string | number | null;\n\tjsonrpc?: \"2.0\";\n}\n\nexport interface McpResponse {\n\tjsonrpc: \"2.0\";\n\tid?: string | number | null;\n\tresult?: unknown;\n\terror?: {\n\t\tcode: number;\n\t\tmessage: string;\n\t\tdata?: unknown;\n\t};\n}\n"]}
@@ -1,29 +0,0 @@
1
- import {a,b}from'./chunk-HM77MWB6.js';import {a as a$2}from'./chunk-PPCOS2NU.js';import {a as a$1}from'./chunk-S6RJHZV2.js';import {Buffer}from'buffer';import G from'crypto';import*as Z from'fs';import {createRequire}from'module';import w from'path';import {fileURLToPath,pathToFileURL}from'url';import*as W from'@grpc/grpc-js';import {Piscina,FixedQueue}from'piscina';import {z as z$1}from'zod';import {zodToJsonSchema}from'zod-to-json-schema';import*as z from'acorn';import {simple}from'acorn-walk';var J={"grpc.keepalive_time_ms":3e4,"grpc.keepalive_timeout_ms":1e4,"grpc.keepalive_permit_without_calls":1,"grpc.max_send_message_length":-1,"grpc.max_receive_message_length":-1,"grpc.enable_retries":1},T=class{server;constructor(){this.server=new W.Server(J);}addService(e){this.server.addService(a.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,t){let r=b(t);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,r,(s,o)=>{if(s){n(s);return}a$1.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async stop(){return new Promise(e=>{this.server.tryShutdown(()=>{a$1.info("[LIOP-RPC] Server shut down"),e();});})}};var A=class l{piiFields;static TAINT_PROPAGATING_METHODS=new Set(["charCodeAt","codePointAt","charAt","at","indexOf","lastIndexOf","search","localeCompare","startsWith","endsWith","includes","substring","slice","substr","split","match","matchAll","replace","replaceAll","normalize","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat"]);static ARRAY_CALLBACK_METHODS=new Set(["map","forEach","filter","find","some","every","flatMap","findIndex"]);static REDUCE_METHODS=new Set(["reduce","reduceRight"]);constructor(e){this.piiFields=new Set(e.map(t=>t.toLowerCase()));}analyze(e){let t;try{let n=`function liop_analysis_wrapper(env) {
2
- ${e}
3
- }`;t=z.parse(n,{ecmaVersion:2022,sourceType:"script",locations:!0});}catch{return null}let r=new Set,i=new Set;return this.identifyRecordBoundVars(t,r),this.propagateTaint(t,r,i),this.checkReturnStatements(t,r,i)}identifyRecordBoundVars(e,t){simple(e,{CallExpression:n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isEnvRecordsAccess(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(l.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let p=c.params[0];p.type==="Identifier"&&t.add(p.name);}if(l.REDUCE_METHODS.has(o)&&c.params.length>1){let p=c.params[1];p.type==="Identifier"&&t.add(p.name);}}},ForOfStatement:n=>{if(this.isEnvRecordsAccess(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&t.add(s.id.name);}}),simple(e,{VariableDeclarator:n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isEnvRecordsAccess(s.object)&&t.add(n.id.name);}}});}propagateTaint(e,t,r){for(let i=0;i<3;i++){let n=r.size;if(simple(e,{VariableDeclarator:o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,t,r)&&r.add(o.id.name);},AssignmentExpression:o=>{o.left.type==="Identifier"&&this.isExpressionTainted(o.right,t,r)&&r.add(o.left.name);},CallExpression:o=>{if(o.callee.type!=="MemberExpression")return;let a=o.callee;this.getPropertyName(a)==="push"&&a.object.type==="Identifier"&&o.arguments.some(p=>this.isExpressionTainted(p,t,r))&&r.add(a.object.name);}}),r.size===n)break}}checkReturnStatements(e,t,r){let i=null;return simple(e,{ReturnStatement:s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,t,r)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,t,r);i={reason:`PII side-channel detected: output contains values derived from restricted fields. ${a?`Operation: ${a}. `:""}Use only non-PII fields (e.g., numeric/date columns) for aggregations.`,line:o,operation:a};}}}),i}isExpressionTainted(e,t,r){switch(e.type){case "Identifier":return r.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,t,r);case "CallExpression":return this.isCallExprTainted(e,t,r);case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,t,r)||this.isExpressionTainted(i.right,t,r)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,t,r)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,t,r)||this.isExpressionTainted(i.consequent,t,r)||this.isExpressionTainted(i.alternate,t,r)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"&&this.isExpressionTainted(n.value,t,r));case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,t,r));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,t,r));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,t,r)}default:return false}}isMemberExprTainted(e,t,r){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&t.has(e.object.name)&&i&&this.piiFields.has(i.toLowerCase()))return true;if(e.object.type==="MemberExpression"&&i&&this.piiFields.has(i.toLowerCase())){let n=e.object;if(n.computed&&this.isEnvRecordsAccess(n.object))return true}if(this.isExpressionTainted(e.object,t,r))return true;if(e.computed&&e.object.type==="Identifier"&&t.has(e.object.name)&&e.property.type==="Literal"){let n=e.property.value;if(typeof n=="string"&&this.piiFields.has(n.toLowerCase()))return true}return false}isCallExprTainted(e,t,r){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&l.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,t,r))return true;if(this.isEnvRecordsAccess(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,t,r)}if(this.isExpressionTainted(i.object,t,r)||e.arguments.some(s=>this.isExpressionTainted(s,t,r)))return true}if(e.callee.type==="MemberExpression"){let i=e.callee;this.getPropertyName(i)==="push"&&i.object.type==="Identifier"&&e.arguments.some(s=>this.isExpressionTainted(s,t,r))&&r.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,t,r))}return false}doesCallbackProduceTaint(e,t,r,i){let n=new Set(r),s=new Set(i);if(e.params.length>0){let p=t!==null&&l.REDUCE_METHODS.has(t)?1:0;e.params.length>p&&e.params[p].type==="Identifier"&&n.add(e.params[p].name);}if(e.type==="ArrowFunctionExpression"&&e.body.type!=="BlockStatement")return this.isExpressionTainted(e.body,n,s);let o=false,a={ReturnStatement:c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);}};return simple(e.body,a),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let t=e.property.value;if(typeof t=="string")return t}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let t=e;if(this.getPropertyName(t)==="records"&&t.object.type==="Identifier"&&t.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,t,r){if(e.type==="Identifier"){let i=e.name;if(r.has(i))return `variable '${i}' is PII-derived`}if(e.type==="ObjectExpression"){let i=e;for(let n of i.properties)if(n.type==="Property"&&this.isExpressionTainted(n.value,t,r))return `property '${n.key.type==="Identifier"?n.key.name:"unknown"}' contains PII-derived value`}if(e.type==="CallExpression"){let i=e;if(i.callee.type==="MemberExpression"){let n=this.getPropertyName(i.callee);if(n)return `result of .${n}() on PII data`}}}};var B={aspirin:"Medication",lisinopril:"Medication",metformin:"Medication",amlodipine:"Medication",atorvastatin:"Medication",omeprazole:"Medication",losartan:"Medication",simvastatin:"Medication",levothyroxine:"Medication",ibuprofen:"Medication",acetaminophen:"Medication",amoxicillin:"Medication",ciprofloxacin:"Medication",prednisone:"Medication",warfarin:"Medication",insulin:"Medication",hydrochlorothiazide:"Medication",gabapentin:"Medication",albuterol:"Medication",pantoprazole:"Medication",hypertension:"Condition",diabetes:"Condition",bronchitis:"Condition",pneumonia:"Condition",asthma:"Condition"},_=4,V=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,O=class l{static nlp=null;async getNlp(){if(!l.nlp){let e=await import('compromise/three');l.nlp=e.default||e,l.nlp.addWords(B);}return l.nlp}async scan(e){if(e.length<_||V.test(e))return {detected:false,entities:[]};let r=(await this.getNlp())(e),i=[],n=r.people().out("array");for(let a of n){let c=a.trim();c.length>=_&&i.push({type:"person",text:c});}let s=r.places().out("array");for(let a of s){let c=a.trim();c.length>=_&&i.push({type:"place",text:c});}let o=r.organizations().out("array");for(let a of o){let c=a.trim();c.length>=_&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,t=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(t.has(e))return {detected:false,entities:[]};t.add(e);let r=Array.isArray(e)?e:Object.values(e),i=[];for(let n of r){let s=await this.scanDeep(n,t);if(s.detected&&(i.push(...s.entities),s.entities.some(o=>o.type==="person")))return {detected:true,entities:i}}return {detected:i.length>0,entities:i}}return {detected:false,entities:[]}}};function X(l){let e=l.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let t=0,r=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);r&&(n*=2,n>9&&(n-=9)),t+=n,r=!r;}return t%10===0}function Q(l){let e=l.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let t=e.substring(4)+e.substring(0,4),r="";for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n>=65&&n<=90)r+=(n-55).toString();else if(n>=48&&n<=57)r+=t.charAt(i);else return false}try{return BigInt(r)%97n===1n}catch{return false}}var f={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:l=>!l.endsWith("@example.com")&&!l.endsWith("@test.com")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:X},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:l=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(l)?false:l.split(".").map(Number).every(r=>r>=0&&r<=255)},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:l=>{let e=l.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")}},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:l=>{let e=l.replace(/\D/g,"");if(e.length!==9)return false;let t=parseInt(e.substring(0,3),10);return !(t===0||t===666||t>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")}},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Q},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},H={GLOBAL_STRICT:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.PASSPORT_MRZ,f.IBAN],US_COMPLIANT:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.SSN,f.PASSPORT_MRZ],EU_GDPR:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.IBAN,f.PASSPORT_MRZ]},N=class l{patterns;forbiddenKeysSet;nerScanner;static KEY_SAFELIST=new Set(["grid","video","android","identity","provide","override","validate","hidden","widget","guidelines","beside","guideline","outside","inside","collide","decide","divide","aside","ride","side","wide","hide","tide","pride","bride","slide","guide","stride","oxide","dioxide","suicide","homicide","pesticide","valid","invalid","void","avoid","diagnosis","medication","namespace","namesake","rename","filename","hostname","typename","unnamed","renamed","phonetic","phoneme","microphone","headphone","telephone","saxophone","smartphone","streetview","addressable","addressing","cityscape","electricity","capacity","velocity","opacity","timestamp","timezone","image_id","computation_result","zk_receipt","testid","toolid","sessionid","peerid","nodeid","requestid","correlationid","traceid","spanid"]);shortTokenBoundaryPatterns;longForbiddenTokens;constructor(e=[],t=[],r){this.patterns=e,this.forbiddenKeysSet=new Set(t.map(i=>i.toLowerCase())),this.nerScanner=r??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp(`(?:^|[_-])${i}(?:$|[_-])|(?:^|[a-z])${i.charAt(0).toUpperCase()}${i.slice(1)}|^${i}$`,"i")):this.longForbiddenTokens.push(i);}async scan(e,t=new WeakSet){if(e==null)return null;if(typeof e=="string"){let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{let n=JSON.parse(r),s=await this.scan(n,t);if(s)return s}catch{}let i=this.checkString(e);if(i)return i;if(this.nerScanner){let n=await this.nerScanner.scan(e);if(n.detected){let s=n.entities.find(o=>o.type==="person");if(s)return `PII Entity Detected: person name "${s.text}"`}}return null}if(typeof e=="object"){if(t.has(e))return null;if(t.add(e),Array.isArray(e))for(let r of e){let i=await this.scan(r,t);if(i)return i}else for(let[r,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(r.toLowerCase()))return `Forbidden Key: ${r}`;let n=this.checkKeyFuzzy(r);if(n)return n;let s=await this.scan(i,t);if(s)return s}}return null}checkKeyFuzzy(e){let t=e.toLowerCase();if(l.KEY_SAFELIST.has(t))return null;for(let[r,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${r}"`;for(let r of this.longForbiddenTokens)if(t.includes(r))return `Forbidden Key (fuzzy): ${e} contains restricted token "${r}"`;return null}checkString(e){for(let t of this.patterns)if(typeof t=="string"){if(e.toLowerCase().includes(t.toLowerCase()))return t}else if(t instanceof RegExp){if(t.global&&(t.lastIndex=0),t.test(e))return t.source}else if(typeof t=="object"&&t!==null){let r=t;if(typeof r.pattern=="string"){if(e.toLowerCase().includes(r.pattern.toLowerCase())&&(!r.validator||r.validator(r.pattern)))return r.name}else if(r.pattern instanceof RegExp){r.pattern.global&&(r.pattern.lastIndex=0);let i=r.pattern.exec(e);for(;i!==null;){let n=i[0];if(!r.validator||r.validator(n))return r.name;if(!r.pattern.global)break;i=r.pattern.exec(e);}}}return null}};function oe(){let l=process.env.LIOP_RESPECT_PLAIN_TOOL_PAYLOAD?.toLowerCase().trim();return l==="1"||l==="true"||l==="yes"}var U=w.dirname(fileURLToPath(import.meta.url)),K=class l{constructor(e,t){this.serverInfo=e;this.config=t;let r=this.config?.security?.enableNerScanning?new O:null;this.piiScanner=new N(this.config?.security?.piiPatterns??H.GLOBAL_STRICT,this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],r);let i=this.config?.security?.rateLimit;this.toolCallWindowMs=i?.windowMs??Number.parseInt(process.env.LIOP_RATE_LIMIT_WINDOW_MS??"60000",10),this.toolCallMaxPerWindow=i?.maxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_MAX??"15",10),this.globalCallMaxPerWindow=i?.globalMaxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_GLOBAL_MAX??"40",10);let n=this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"];this.taintAnalyzer=new A(n);let s=import.meta.url.endsWith(".ts"),o=s?".ts":".js",a=[];if(s)try{let h=createRequire(import.meta.url).resolve("tsx/package.json");a=["--import",pathToFileURL(w.join(w.dirname(h),"dist","loader.mjs")).href];}catch{a=["--import","tsx"];}let c=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let p=[w.resolve(U,`./workers/logic-execution${o}`),w.resolve(U,`../workers/logic-execution${o}`)],u=p.find(d=>Z.existsSync(d))||p[1];this.workerPool=new Piscina({filename:u,minThreads:this.config?.workerPool?.minThreads??(c?0:2),maxThreads:this.config?.workerPool?.maxThreads??(c?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(c?500:5e3),maxQueue:"auto",taskQueue:new FixedQueue,execArgv:a,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}}),this.resource("LIOP Envelope Specification","liop://protocol/envelope-spec","Complete Logic-on-Origin envelope format, execution rules, and security constraints","text/plain",()=>Promise.resolve(this.buildEnvelopeSpec()));}logicCache=new Map;connectionStats=new Map;CACHE_TTL_MS=1440*60*1e3;THROTTLE_THRESHOLD=5;THROTTLE_COOLDOWN_MS=60*1e3;toolCallWindows=new Map;toolCallMaxPerWindow;toolCallWindowMs;globalCallWindow=[];globalCallMaxPerWindow;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;sessions=new Map;static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,(?<name>[^}]*))?\}\n(?<logic>[\s\S]*?)\n@END/m;extractLogic(e){let t=e.match(l.LIOP_COMPACT_REGEX);return t?.groups?.logic?t.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}runPreflightPolicy(e,t,r){if(r){let n=t.replace(/\s+/g," ");if(r.enforceAggregationFirst&&[/return\s+env\.records(?!\s*\.\s*(?:reduce|length|filter|every|some|find)\b)/i,/return\s*\{[\s\S]*\b(accounts|patients|rows|records)\s*:\s*env\.records(?!\s*\.\s*(?:reduce|length|filter)\b)/i].some(o=>o.test(n)))return "Preflight policy rejected: potential row-level export pattern detected.";if(r.preflightDenyPatterns?.some(s=>s.test(n)))return "Preflight policy rejected: custom deny pattern matched."}let i=this.taintAnalyzer.analyze(t);return i?`Preflight policy rejected: ${i.reason}`:null}validateOutputPolicy(e,t,r){if(!r)return null;let i=this.parseUnknownJson(t);if(r.outputSchema){let s=(()=>{if(!(r.outputSchema instanceof z$1.ZodObject))return r.outputSchema;let o=r.outputSchema;return o._def.catchall instanceof z$1.ZodNever?o.strict():o})().safeParse(i);if(!s.success)return `[LIOP] Output schema violation for ${e}: ${s.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}. HINT: Your output must conform to the declared schema. Use 'env.records' to access the dataset and return only allowed fields.`}return r.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),r.enforceAggregationFirst,this.sandboxRecords.length)?process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?"Aggregation-First Policy Violation: row-level export or K-Anonymity violation blocked. HINT: Use .reduce() to produce a flat {key:value} object. Do NOT use .map() to create arrays of objects. Ensure dataset size > 10 for detailed results.":"Aggregation-First Policy Violation: Output blocked due to privacy constraints.":null}unwrapForAggregationPolicyScan(e){if(typeof e=="string"){let n=e.trim();if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{return this.unwrapForAggregationPolicyScan(JSON.parse(n))}catch{return e}return e}if(!e||typeof e!="object")return e;let t=e;if(!Array.isArray(t.content)||t.content.length===0)return e;let r=[];for(let n of t.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&r.push(s);}if(r.length===0)return e;let i=r.length===1?r[0]:r.join(`
4
- `);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,t,r){let i=typeof t=="object"&&typeof t.maxOutputRows=="number"?t.maxOutputRows:10,n=typeof t=="object"&&typeof t.allowPrimitiveArrays=="boolean"?t.allowPrimitiveArrays:true;if(typeof e=="string"){let s=e.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(s),t,r)}catch{return false}return false}if(Array.isArray(e))return e.length>0&&e.every(s=>typeof s=="object"&&s!==null)?e.length>i?true:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r));if(e&&typeof e=="object"){let s=Object.keys(e);return r!==void 0&&r>0&&r<10&&(s.length>3||Object.values(e).some(a=>Array.isArray(a)||typeof a=="object"&&a!==null))||s.length>i?true:Object.values(e).some(o=>this.violatesAggregationFirstPolicy(o,t,r))}return false}buildEnvelopeSpec(){let e=["LIOP v1 Envelope Specification","================================","","FORMAT:","","Compact Envelope:"," @LIOP{wasi_v1,TaskName}"," <JavaScript code>"," @END","","RUNTIME ENVIRONMENT:","- env.records: Array of data objects from the origin","- Must use 'return' to output results","- Zero-Trust WASI Sandbox (Node.js Worker Pool)","- Return aggregated objects, NOT raw row-level arrays","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution"];return this.config?.security?.forbiddenKeys?.length&&e.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),e.push("","TAINT TRACKING (Phase 108):","- AST-level analysis blocks PII-derived scalars (charCodeAt, charAt, etc.)","- Operations on restricted fields are tracked through variable assignments","- Boolean inference (field.charCodeAt(0) < N ? 1 : 0) is blocked","- Allowed: aggregations on non-PII fields (balance, amount, date)","","K-ANONYMITY:","- Datasets < 10 records: max 3 scalar output fields, no nesting","- Datasets >= 10 records: max 10 output fields","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)"),e.join(`
5
- `)}extractSchemaFieldSummary(e,t=0){if(t>3)return "{...}";let r=e.type,i=e.properties,n=e.items;return i?`{${Object.entries(i).map(([o,a])=>{let c=a.type;if(c==="array"&&a.items){let p=this.extractSchemaFieldSummary(a.items,t+1);return `${o}(array of ${p})`}if(c==="object"&&a.properties){let p=this.extractSchemaFieldSummary(a,t+1);return `${o}(${p})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:r==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,t+1)}`:r||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,t,r,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z$1.object(r),o=zodToJsonSchema(s),a=t,c=i;if(r.payload&&r.payload instanceof z$1.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a+=`
6
-
7
- Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a+=`
8
- Restricted fields: ${u.join(", ")}.`),this.activeSchema){let d=this.extractSchemaFieldSummary(this.activeSchema);a+=`
9
- Data structure: ${d}. Full schema: resource liop://schema/global`;}c=async(d,h)=>{let y="global_connection",b=Date.now(),m=this.connectionStats.get(y)||{failures:0,lastAttempt:0};if(m.failures>=this.THROTTLE_THRESHOLD&&b-m.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let M=d.payload,Y=d.__liop_bypass_ast_cache===true,L=G.createHash("sha256").update(M).digest("hex"),S=this.extractLogic(M),C=this.logicCache.get(L);if(!Y&&C&&b-C.timestamp<this.CACHE_TTL_MS&&S){d.payload=S;let v=this.runPreflightPolicy(e,S,n);return v?{content:[{type:"text",text:v}],isError:true}:await this.executeInWorkerPool(d,S,e)}if(!S)return oe()?await i(d,h):(m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:"Error: Malformed payload. Missing @LIOP boundary.\\nYou MUST wrap your logic exactly like this:\\n\\n@LIOP{wasi_v1,DynamicAudit}\\n// Your JS code here\\n@END"}],isError:true});try{let v=this.extractLogic(d.payload);d.payload=v;let R=this.runPreflightPolicy(e,v,n);if(R)return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:R}],isError:!0};let D=await this.executeInWorkerPool(d,v,e);return D.isError?(m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m)):(this.connectionStats.set(y,{failures:0,lastAttempt:b}),this.logicCache.set(L,{hash:L,timestamp:b})),D}catch(v){let R=v;return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:`ExecutionRuntimeException: ${R.message}`}],isError:true}}};}let p={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a,inputSchema:p},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{a$1.info(`[LIOP-Mesh] Failed to auto-announce tool ${e}: ${u.message}`);});}prompt(e,t,r,i){if(this.prompts.has(e))throw new Error(`Prompt already registered: ${e}`);this.prompts.set(e,{prompt:{name:e,description:t,arguments:r},handler:i});}enableZeroShotAutonomy(){this.prompt("liop_blind_analyst","The official Logic-Injection-on-Origin Protocol system prompt. Instructs the LLM on how to securely inject Logic-on-Origin without violating PII or safety constraints.",[],e=>({description:"LIOP Blind Analyst Instructions",messages:[{role:"user",content:{type:"text",text:`You are the "Blind Analyst" operating within the Logic-Injection-on-Origin Protocol (LIOP) ecosystem.
10
- Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
11
-
12
- INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
13
- 1. DATA PRIVACY: NEVER attempt to export Personally Identifiable Information (PII). The LIOP Egress Shield will block any response containing raw IDs, names, or addresses.
14
- 2. AGGREGATION FIRST: Always prefer returning counts, averages, or anonymized summaries.
15
- 3. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
16
- Structure:
17
- @LIOP{wasi_v1,AnalysisTask}
18
- // Your JS Code Here
19
- @END
20
- 4. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
21
- 5. LOCALIZATION: Format all JSON response keys in the language used by the user in their query (e.g., use Spanish keys if the query is in Spanish).
22
- 6. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.${this.activeSchema?`
23
-
24
- CURRENT DATA DICTIONARY (STRICT):
25
- ${JSON.stringify(this.activeSchema,null,2)}`:""}
26
-
27
- Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,t,r,i,n){if(this.resources.has(t))throw new Error(`Resource URI already registered: ${t}`);this.resources.set(t,{name:e,uri:t,description:r,mimeType:i,content:n});}dataDictionary(e,t="Global Medical Data Dictionary",r="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){this.activeSchema=e;let n=this.extractSchemaFieldSummary(e);for(let[s,o]of this.tools.entries())o.schema.shape.payload&&o.schema.shape.payload instanceof z$1.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
28
- Data structure: ${n}. Full schema: resource ${r}`,this.tools.set(s,o));this.resource(t,r,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),a$1.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let t=Date.now(),r=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>t-o<r);if(s.length>=i){let o=Math.ceil((s[0]+r-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${r/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(t),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),t=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<t),this.globalCallWindow.length>=r){let i=Math.ceil((this.globalCallWindow[0]+t-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${t/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e){let t=this.tools.get(e.name);if(!t)throw new Error(`Tool not found: ${e.name}`);let r=this.checkGlobalRateLimit();if(r)return r;let i=this.checkToolCallRateLimit(e.name);if(i)return i;try{let n=t.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(n.__liop_bypass_ast_cache=!0),n&&typeof n.payload=="string"){let o=n.payload,a=this.extractLogic(o);if(a){let c=this.runPreflightPolicy(e.name,a,t.policy);return c?{content:[{type:"text",text:c}],isError:!0}:(n.payload=a,await this.executeInWorkerPool(n,a,e.name))}}return await t.handler(n,{})}catch(n){let s=n;return s instanceof z$1.ZodError?{content:[{type:"text",text:`Validation Error: ${s.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${s.message}`}],isError:true}}}listTools(){return Array.from(this.tools.values()).map(e=>e.tool)}listPrompts(){return Array.from(this.prompts.values()).map(e=>e.prompt)}async getPrompt(e){let t=this.prompts.get(e.name);if(!t)throw new Error(`Prompt not found: ${e.name}`);return await t.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let t=this.resources.get(e);if(!t)throw new Error(`Resource not found: ${e}`);let r="No description provided";return typeof t.content=="function"?r=await t.content():typeof t.content=="string"?r=t.content:t.description&&(r=t.description),{contents:[{uri:t.uri,mimeType:t.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let t=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=e.port??t??50051;this.meshNode=new a$2(e.meshConfig),await this.meshNode.start();let i=this.meshNode;this.meshNode.registerManifestHandler(()=>{let n=this.listTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),s=Array.from(this.resources.values()).map(o=>({name:o.name,uri:o.uri,description:o.description,mimeType:o.mimeType,text:typeof o.content=="string"?o.content:o.description}));return {peerId:i.getPeerId(),grpcPort:r,tools:n,resources:s,serverInfo:this.serverInfo}});for(let n of this.listTools())await this.meshNode.announceCapability(n.name).catch(a$1.info);await this.meshNode.announceManifest().catch(a$1.info),this.rpcServer=new T,this.rpcServer.addService({negotiateIntent:(n,s)=>{let o=n.request;a$1.info(`[LIOP-RPC] Negotiating intent for capability: ${o.capability_hash}`),import('./kyber-2WDOTUQX.js').then(async({Kyber768Wrapper:a})=>{let{publicKey:c,secretKey:p}=await a.generateKeyPair(),u=G.randomUUID();this.sessions.set(u,{capability_hash:o.capability_hash,kyber_sk:p}),s(null,{accepted:true,session_token:u,error_message:"",kyber_public_key:c});});},executeLogic:async n=>{let s=n.request;a$1.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${s.session_token}`);let o=this.sessions.get(s.session_token);if(!o){n.emit("error",{code:W.status.UNAUTHENTICATED,details:"Invalid session token"});return}try{let a=await this.workerPool.run({ciphertext:s.pqc_ciphertext,secretKeyObj:Array.from(o.kyber_sk),wasmBinary:s.wasm_binary,inputs:s.inputs,aesNonce:s.aes_nonce,records:this.sandboxRecords,sessionToken:s.session_token,isEncrypted:!0}),c;try{c=typeof a.output=="string"?a.output:JSON.stringify(a.output);let h=JSON.parse(c);if(h.__liop_proxy_tool){a$1.info(`[LIOP-RPC] Executing Proxied Tool: ${h.__liop_proxy_tool}`);let y=await this.callTool({name:h.__liop_proxy_tool,arguments:h.__liop_proxy_args||{}});c=JSON.stringify(y);}}catch{c=String(a.output);}let p={semantic_evidence:c,cryptographic_proof:Buffer.from(a.image_id||"","hex"),zk_receipt:a.zk_receipt?Buffer.from(a.zk_receipt,"base64"):Buffer.from(""),is_error:!1},u=await this.piiScanner.scan([{type:"text",text:c}]),d=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(c));if(u||d){let h=u||"Aggregation-First Policy Violation";a$1.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${h}`),p.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",p.is_error=!0;}n.write(p,()=>{n.end();});}catch(a){let c=a,p=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",u=c.message||String(a);a$1.error(`[LIOP-RPC] Execution Error: ${u}`);let h={semantic_evidence:p?`Execution Error: ${u}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{n.write(h,()=>{n.end();});}catch{n.end();}}}}),this.boundPort=await this.rpcServer.listen(r),a$1.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,t,r){try{let i=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(t),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1}),s=[{type:"text",text:JSON.stringify({computation_result:i.output,image_id:i.image_id,zk_receipt:i.zk_receipt,status:"Worker Pool Execution Success"})}],o=r?this.tools.get(r)?.policy:void 0,a=this.validateOutputPolicy(r||"unknown_tool",i.output,o);if(a)return a$1.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${a}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?a:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let c=await this.piiScanner.scan(s),p=this.violatesAggregationFirstPolicy(i.output);if(c||p){let u=c||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return a$1.info(`[LIOP-SDK] Secure egress blocked in local execution: ${u}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${u}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:s}}catch(i){let n=i,s=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",o=n.message||String(i);return a$1.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:s?`WorkerPoolError: ${o}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error."}],isError:true}}}async close(){this.workerPool&&await this.workerPool.close({force:true}),this.rpcServer&&await this.rpcServer.stop(),this.meshNode&&await this.meshNode.stop();}};export{T as a,O as b,f as c,H as d,N as e,K as f};//# sourceMappingURL=chunk-X6FJATUE.js.map
29
- //# sourceMappingURL=chunk-X6FJATUE.js.map