@nekzus/liop 2.1.0-alpha.4 → 2.1.0-alpha.6

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 (78) hide show
  1. package/dist/bin/agent.js +301 -4
  2. package/dist/bin/agent.js.map +1 -1
  3. package/dist/bridge.js +3 -1
  4. package/dist/chunk-32ADSAJS.js +104 -0
  5. package/dist/chunk-32ADSAJS.js.map +1 -0
  6. package/dist/chunk-4KIGYPIQ.js +3298 -0
  7. package/dist/chunk-4KIGYPIQ.js.map +1 -0
  8. package/dist/chunk-72MNYFR6.js +64 -0
  9. package/dist/chunk-72MNYFR6.js.map +1 -0
  10. package/dist/chunk-AL7H7DTW.js +463 -0
  11. package/dist/chunk-AL7H7DTW.js.map +1 -0
  12. package/dist/chunk-CT6NHSYP.js +30 -0
  13. package/dist/chunk-CT6NHSYP.js.map +1 -0
  14. package/dist/chunk-HB5DXX3Q.js +1976 -0
  15. package/dist/chunk-HB5DXX3Q.js.map +1 -0
  16. package/dist/chunk-IJHTRIZC.js +56 -0
  17. package/dist/chunk-IJHTRIZC.js.map +1 -0
  18. package/dist/chunk-J3WPBMJ5.js +332 -0
  19. package/dist/chunk-J3WPBMJ5.js.map +1 -0
  20. package/dist/chunk-MMYZR7G7.js +815 -0
  21. package/dist/chunk-MMYZR7G7.js.map +1 -0
  22. package/dist/chunk-OUUTDSOW.js +24 -0
  23. package/dist/chunk-OUUTDSOW.js.map +1 -0
  24. package/dist/chunk-PHTWUTY7.js +300 -0
  25. package/dist/chunk-PHTWUTY7.js.map +1 -0
  26. package/dist/chunk-QLCOEP5J.js +68 -0
  27. package/dist/chunk-QLCOEP5J.js.map +1 -0
  28. package/dist/chunk-RDWCGZ2A.js +87 -0
  29. package/dist/chunk-RDWCGZ2A.js.map +1 -0
  30. package/dist/chunk-RWRRBYG4.js +1 -0
  31. package/dist/chunk-SSURAA3I.js +469 -0
  32. package/dist/chunk-SSURAA3I.js.map +1 -0
  33. package/dist/client.js +8 -1
  34. package/dist/gateway.js +9 -1
  35. package/dist/index.js +58 -4
  36. package/dist/index.js.map +1 -1
  37. package/dist/kyber-3ULIJSE3.js +3 -0
  38. package/dist/{kyber-2WDOTUQX.js.map → kyber-3ULIJSE3.js.map} +1 -1
  39. package/dist/mesh.js +4 -1
  40. package/dist/server.js +6 -1
  41. package/dist/types.js +2 -1
  42. package/dist/verifier-3FAKCFNN.js +5 -0
  43. package/dist/{verifier-KZ4QYF5M.js.map → verifier-3FAKCFNN.js.map} +1 -1
  44. package/dist/workers/logic-execution.js +255 -1
  45. package/dist/workers/logic-execution.js.map +1 -1
  46. package/dist/workers/zk-verifier.js +173 -1
  47. package/dist/workers/zk-verifier.js.map +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-AEWYQWVZ.js +0 -42
  50. package/dist/chunk-AEWYQWVZ.js.map +0 -1
  51. package/dist/chunk-ANFXJGMP.js +0 -2
  52. package/dist/chunk-ANFXJGMP.js.map +0 -1
  53. package/dist/chunk-CPLE5VZ5.js +0 -33
  54. package/dist/chunk-CPLE5VZ5.js.map +0 -1
  55. package/dist/chunk-DBXGYHKY.js +0 -2
  56. package/dist/chunk-DBXGYHKY.js.map +0 -1
  57. package/dist/chunk-DQ6UW6L7.js +0 -2
  58. package/dist/chunk-DQ6UW6L7.js.map +0 -1
  59. package/dist/chunk-JIUFKRVG.js +0 -13
  60. package/dist/chunk-JIUFKRVG.js.map +0 -1
  61. package/dist/chunk-PWCXZWSE.js +0 -2
  62. package/dist/chunk-PWCXZWSE.js.map +0 -1
  63. package/dist/chunk-RYYRR4N5.js +0 -31
  64. package/dist/chunk-RYYRR4N5.js.map +0 -1
  65. package/dist/chunk-S6RJHZV2.js +0 -2
  66. package/dist/chunk-S6RJHZV2.js.map +0 -1
  67. package/dist/chunk-SB5XJXKV.js +0 -2
  68. package/dist/chunk-SB5XJXKV.js.map +0 -1
  69. package/dist/chunk-T3L6OCM3.js +0 -3
  70. package/dist/chunk-T3L6OCM3.js.map +0 -1
  71. package/dist/chunk-TNBXOZNG.js +0 -2
  72. package/dist/chunk-TNBXOZNG.js.map +0 -1
  73. package/dist/chunk-V5MKJT6S.js +0 -2
  74. package/dist/chunk-V5MKJT6S.js.map +0 -1
  75. package/dist/chunk-VDNV2I4I.js +0 -3
  76. package/dist/chunk-VDNV2I4I.js.map +0 -1
  77. package/dist/kyber-2WDOTUQX.js +0 -2
  78. package/dist/verifier-KZ4QYF5M.js +0 -2
@@ -1,2 +0,0 @@
1
- import e from'crypto';var i=/^\s*@LIOP\{[^}]+\}\n?([\s\S]*?)\n?@END\s*$/;function f(t){let r=t.match(i);return r?.[1]!==void 0?r[1].trim():t.trim()}function c(t){if(t[0]===0&&t[1]===97)return e.createHash("sha256").update(t).digest();let n=Buffer.from(t).toString("utf-8"),s=f(n);return e.createHash("sha256").update(Buffer.from(s,"utf-8")).digest()}export{f as a,c as b};//# sourceMappingURL=chunk-ANFXJGMP.js.map
2
- //# sourceMappingURL=chunk-ANFXJGMP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/crypto/logic-image-id.ts"],"names":["TOP_LEVEL_ENVELOPE","normalizeLogicSource","logicUtf8","match","deriveLogicImageDigest","logicPayload","crypto","text","normalized"],"mappings":"sBAOA,IAAMA,CAAAA,CAAqB,4CAAA,CAEpB,SAASC,CAAAA,CAAqBC,CAAAA,CAA2B,CAC/D,IAAMC,EAAQD,CAAAA,CAAU,KAAA,CAAMF,CAAkB,CAAA,CAChD,OAAIG,CAAAA,GAAQ,CAAC,CAAA,GAAM,MAAA,CACXA,EAAM,CAAC,CAAA,CAAE,IAAA,EAAK,CAEfD,EAAU,IAAA,EAClB,CAGO,SAASE,EAAuBC,CAAAA,CAAkC,CAExE,GADeA,CAAAA,CAAa,CAAC,IAAM,CAAA,EAAQA,CAAAA,CAAa,CAAC,CAAA,GAAM,GAE9D,OAAOC,CAAAA,CAAO,UAAA,CAAW,QAAQ,EAAE,MAAA,CAAOD,CAAY,CAAA,CAAE,MAAA,GAEzD,IAAME,CAAAA,CAAO,MAAA,CAAO,IAAA,CAAKF,CAAY,CAAA,CAAE,QAAA,CAAS,OAAO,CAAA,CACjDG,EAAaP,CAAAA,CAAqBM,CAAI,CAAA,CAC5C,OAAOD,EACL,UAAA,CAAW,QAAQ,CAAA,CACnB,MAAA,CAAO,OAAO,IAAA,CAAKE,CAAAA,CAAY,OAAO,CAAC,CAAA,CACvC,QACH","file":"chunk-ANFXJGMP.js","sourcesContent":["import crypto from \"node:crypto\";\n\n/**\n * Top-level LIOP v1 envelope only. Must NOT use multiline (^/$) mode:\n * proxy logic embeds a full envelope inside JSON strings; `^` per line would\n * incorrectly treat that as the document root and desync ImageID vs the worker.\n */\nconst TOP_LEVEL_ENVELOPE = /^\\s*@LIOP\\{[^}]+\\}\\n?([\\s\\S]*?)\\n?@END\\s*$/;\n\nexport function normalizeLogicSource(logicUtf8: string): string {\n\tconst match = logicUtf8.match(TOP_LEVEL_ENVELOPE);\n\tif (match?.[1] !== undefined) {\n\t\treturn match[1].trim();\n\t}\n\treturn logicUtf8.trim();\n}\n\n/** SHA-256 digest of logic bytes (WASM raw; JS UTF-8 after top-level envelope strip). */\nexport function deriveLogicImageDigest(logicPayload: Uint8Array): Buffer {\n\tconst isWasm = logicPayload[0] === 0x00 && logicPayload[1] === 0x61;\n\tif (isWasm) {\n\t\treturn crypto.createHash(\"sha256\").update(logicPayload).digest();\n\t}\n\tconst text = Buffer.from(logicPayload).toString(\"utf-8\");\n\tconst normalized = normalizeLogicSource(text);\n\treturn crypto\n\t\t.createHash(\"sha256\")\n\t\t.update(Buffer.from(normalized, \"utf-8\"))\n\t\t.digest();\n}\n"]}
@@ -1,33 +0,0 @@
1
- import {a as a$1}from'./chunk-PWCXZWSE.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {a as a$2}from'./chunk-SB5XJXKV.js';import {a as a$3,c}from'./chunk-V5MKJT6S.js';import {a}from'./chunk-S6RJHZV2.js';import {metrics}from'@opentelemetry/api';import*as C from'crypto';import*as U from'@grpc/grpc-js';var b=class{name="o200k_base";countFn;constructor(e,s){this.countFn=e,s&&s(1e4);}countTokens(e){return e.length===0?0:this.countFn(e)}},R=class{name="heuristic (chars/4)";countTokens(e){return e.length===0?0:Math.ceil(e.length/4)}};async function V(){try{let T=await import('gpt-tokenizer'),e=new b(T.countTokens,T.setMergeCacheSize);return a.debug("[LIOP-Economy] Token estimator initialized: o200k_base"),e}catch{return a.info("[LIOP-Economy] gpt-tokenizer unavailable, falling back to heuristic estimator"),new R}}function q(){return new R}var Q="@nekzus/liop",Z="1.2.0-alpha.9",X=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],Y=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],$=class{tokenUsage;operationDuration;active=false;constructor(){try{let e=metrics.getMeter(Q,Z);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:X}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:Y}}),this.active=!0,a.debug("[LIOP-OTel] gen_ai.* metrics bridge initialized");}catch(e){a.debug(`[LIOP-OTel] Bridge disabled: ${e instanceof Error?e.message:String(e)}`);let s={record:()=>{}};this.tokenUsage=s,this.operationDuration=s;}}recordTokens(e,s,o,r){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":o,"gen_ai.token.type":s,"gen_ai.request.model":"liop-mesh",...r?{"liop.tool.name":r}:{}});}recordDuration(e,s,o){this.operationDuration.record(e/1e3,{"gen_ai.system":"liop","gen_ai.operation.name":s,...o?{"error.type":o}:{}});}isActive(){return this.active}};var ee={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},I=class T{static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=q(),this.otelBridge=new $,this.initRealEstimator();}initRealEstimator(){V().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return T.instance||(T.instance=new T),T.instance}countTokens(e){try{return this.estimator.countTokens(e)}catch{return Math.ceil(e.length/4)}}record(e){let s={...e,timestamp:Date.now()};this.operations.push(s);try{let o=ee[e.type]||"chat";e.estimatedInputTokens>0&&this.otelBridge.recordTokens(e.estimatedInputTokens,"input",o,e.toolName),e.estimatedOutputTokens>0&&this.otelBridge.recordTokens(e.estimatedOutputTokens,"output",o,e.toolName),e.durationMs!==void 0&&this.otelBridge.recordDuration(e.durationMs,o);}catch{}}estimateTokens(e){return this.countTokens(e)}getReport(){return {sessionId:this.sessionId,operations:[...this.operations],totalInputTokens:this.operations.reduce((e,s)=>e+s.estimatedInputTokens,0),totalOutputTokens:this.operations.reduce((e,s)=>e+s.estimatedOutputTokens,0),estimatorName:this.estimator.name,sessionUptimeMs:Date.now()-this.startedAt}}getPerToolReport(){let e=new Map;for(let s of this.operations){let o=s.toolName||s.method,r=e.get(o)||{input:0,output:0,calls:0,avgDurationMs:0},i=r.avgDurationMs*r.calls+(s.durationMs||0),t=r.calls+1;e.set(o,{input:r.input+s.estimatedInputTokens,output:r.output+s.estimatedOutputTokens,calls:t,avgDurationMs:t>0?i/t:0});}return e}formatStatusBlock(){let e=this.getReport();if(e.operations.length===0)return "";let s=this.formatUptime(e.sessionUptimeMs),o=e.totalInputTokens+e.totalOutputTokens,r=new Map;for(let p of e.operations){let h=p.type,g=r.get(h)||{count:0,input:0,output:0};r.set(h,{count:g.count+1,input:g.input+p.estimatedInputTokens,output:g.output+p.estimatedOutputTokens});}let i=Array.from(r.entries()),t=i.map(([p,h],g)=>{let y=g===i.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",S=h.output>0?` / ${h.output.toLocaleString()} out`:"";return `${y} ${p} \xD7${h.count} \u2192 ${h.input.toLocaleString()} in${S}`}),n=this.getPerToolReport(),a=Array.from(n.entries()).filter(([p])=>p!=="tools/list"&&p!=="LiopMeshStatus"),m=[];a.length>0&&(m.push("\u251C\u2500 By Tool:"),a.forEach(([p,h],g)=>{let y=g===a.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",S=h.output>0?` / ${h.output.toLocaleString()} out`:"",k=h.avgDurationMs>0?` ~${Math.round(h.avgDurationMs)}ms`:"";m.push(`${y} ${p}: ${h.input.toLocaleString()} in${S} (\xD7${h.calls})${k}`);}));let c=e.operations.filter(p=>p.durationMs!==void 0),l=c.length>0?Math.round(c.reduce((p,h)=>p+(h.durationMs||0),0)/c.length):0,u=this.otelBridge.isActive()?"gen_ai.client.token.usage \u2192 active":"disabled";return [`
2
- Token Economy:`,`\u251C\u2500 Session: ${e.sessionId.slice(0,8)} (${s})`,`\u251C\u2500 Estimator: ${e.estimatorName}`,`\u251C\u2500 Operations: ${e.operations.length}`,...t,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${o.toLocaleString()} combined)`,...m,...l>0?[`\u251C\u2500 Avg Latency: ${l}ms`]:[],`\u2514\u2500 OTel: ${u}`].join(`
3
- `)}formatUptime(e){let s=Math.floor(e/1e3);if(s<60)return `${s}s`;let o=Math.floor(s/60),r=s%60;if(o<60)return `${o}m ${r}s`;let i=Math.floor(o/60),t=o%60;return `${i}h ${t}m`}reset(){this.operations=[];}static destroy(){T.instance=null;}};function L(){let T=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(T==="0"||T==="false"||T==="no")}function D(T){let e=T,s=[`
4
-
5
- [LIOP-PROTO-V1:`,`\r
6
- \r
7
- [LIOP-PROTO-V1:`,`
8
- [LIOP-PROTO-V1:`];for(let o of s){let r=e.indexOf(o);if(r!==-1){e=e.slice(0,r);break}}return e.trimEnd()}var K=300,x=5,J=class T{constructor(e,s=null,o=50051){this.liopServer=e;this.meshNode=s;this.defaultRpcPort=o;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let r=this.liopServer.listTools().map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema})),i=this.liopServer.listResources().map(n=>({name:n.name,uri:n.uri,description:n.description,mimeType:n.mimeType})),t=this.liopServer.config;return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...r],resources:i,serverInfo:this.liopServer.getServerInfo(),authRequired:this.liopServer.jwtValidator!==void 0,tokenSlug:t?.tokenSlug,taxonomy:t?.taxonomy?{domain:t.taxonomy.domain||"Unknown Domain",clearanceTier:t.taxonomy.clearanceTier??0,executionTypes:t.taxonomy.executionTypes||[]}:void 0}}),this.meshNode.announceManifest().catch(r=>{a.info(`[LIOP-Router] Failed to announce manifest: ${r instanceof Error?r.message:String(r)}`);})),process.env.LIOP_DIAGNOSTIC_LEVEL==="full"&&process.stderr.write(`\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.
9
- `);}manifestCache=new Map;currentDiscovery=null;verifier=new a$1;onToolsChanged;manifestFailureState=new Map;static MANIFEST_FAILURE_BASE_COOLDOWN_MS=15e3;static MANIFEST_FAILURE_MAX_COOLDOWN_MS=5*6e4;static MANIFEST_SKIP_LOG_THROTTLE_MS=3e4;shouldSkipManifestQuery(e){let s=this.manifestFailureState.get(e);if(!s)return false;let o=Date.now();return o>=s.cooldownUntil?false:(o-s.lastSkipLogAt>T.MANIFEST_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Router] Skipping manifest query for ${e} during cooldown (${Math.ceil((s.cooldownUntil-o)/1e3)}s remaining)`),s.lastSkipLogAt=o),true)}recordManifestQuerySuccess(e){this.manifestFailureState.delete(e);}recordManifestQueryFailure(e){let s=Date.now(),r=(this.manifestFailureState.get(e)?.failures||0)+1,i=Math.min(T.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,r-1),T.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:r,cooldownUntil:s+i,lastSkipLogAt:0});}async dispatch(e,s){let{method:o,params:r,id:i}=e;if(a.info(`[LIOP-Router] Processing: ${o}`),this.liopServer.jwtValidator){let t=a$2(o,s??null);if(!t.allowed)return a.info(`[LIOP-Router] RBAC Access Denied for method '${o}': ${t.reason}`),{jsonrpc:"2.0",id:i,error:{code:-32099,message:t.reason||"Access Denied"}}}switch(o){case "initialize":return {jsonrpc:"2.0",id:i,result:{protocolVersion:"2025-11-25",capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "ping":return {jsonrpc:"2.0",id:i,result:{}};case "tools/list":{let t=this.liopServer.listTools(),n=await this.getRemoteTools(),a$1=L()?t.map(p=>({...p,description:D(p.description??"")})):t;a.info(`[LIOP-Router] tools/list: ${t.length} local, ${n.length} remote tools found`);let c=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...a$1,...n],l=I.getInstance(),u=JSON.stringify(c),f=JSON.stringify({tools:c});return l.record({type:"tools_list",method:"tools/list",estimatedInputTokens:l.countTokens(u),estimatedOutputTokens:l.countTokens(f)}),{jsonrpc:"2.0",id:i,result:{tools:c}}}case "tools/call":return this.transcodeMcpToLiop(i,r,s?.token);case "resources/list":{let t=this.liopServer.listResources(),n=await this.getRemoteResources(),a=[...t,...n],m=I.getInstance(),c=JSON.stringify(a);return m.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:m.countTokens(c)}),{jsonrpc:"2.0",id:i,result:{resources:a}}}case "resources/read":{let t=r;if(!t?.uri)return {jsonrpc:"2.0",id:i,error:{code:-32602,message:"Missing resource uri"}};try{let n=Date.now(),a=await this.liopServer.readResource(t.uri),m=I.getInstance(),c=JSON.stringify(a);return m.record({type:"resource_read",method:"resources/read",toolName:t.uri,estimatedInputTokens:m.countTokens(t.uri),estimatedOutputTokens:m.countTokens(c),durationMs:Date.now()-n}),{jsonrpc:"2.0",id:i,result:a}}catch(n){let a$1=t.uri;for(let{manifest:m}of this.manifestCache.values()){let c=m.resources.find(l=>l.uri===a$1);if(c)return a.info(`[LIOP-Router] Resolved resource ${a$1} from cache (Peer: ${m.peerId})`),{jsonrpc:"2.0",id:i,result:{contents:[{uri:c.uri,mimeType:c.mimeType||"text/plain",text:c.text||c.description||"No content provided"}]}}}return {jsonrpc:"2.0",id:i,error:{code:-32e3,message:n instanceof Error?n.message:String(n)}}}}case "prompts/list":{let t=this.liopServer.listPrompts(),n=I.getInstance(),a=JSON.stringify(t);return n.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:n.countTokens(a)}),{jsonrpc:"2.0",id:i,result:{prompts:t}}}case "prompts/get":{let t=r;if(!t?.name)return {jsonrpc:"2.0",id:i,error:{code:-32602,message:"Missing prompt name"}};try{let n=Date.now(),a=await this.liopServer.getPrompt({name:t.name,arguments:t.arguments||{}}),m=I.getInstance(),c=JSON.stringify({name:t.name,arguments:t.arguments}),l=JSON.stringify(a);return m.record({type:"prompt_get",method:"prompts/get",toolName:t.name,estimatedInputTokens:m.countTokens(c),estimatedOutputTokens:m.countTokens(l),durationMs:Date.now()-n}),{jsonrpc:"2.0",id:i,result:a}}catch(n){return {jsonrpc:"2.0",id:i,error:{code:-32e3,message:n instanceof Error?n.message:String(n)}}}}default:return {jsonrpc:"2.0",id:i,error:{code:-32601,message:`Method not found: ${o}`}}}}kickDiscoveryAfterInitialized(){return (async()=>{await new Promise(e=>setTimeout(e,250)),await Promise.race([this.refreshManifestCache(true),new Promise(e=>setTimeout(e,15e3))]).catch(()=>{});})()}async refreshManifestCache(e=false){if(this.meshNode){if(this.currentDiscovery)return this.currentDiscovery;if(!e&&this.manifestCache.size>0){let s=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:r})=>s-r<K*1e3))return}return this.currentDiscovery=(async()=>{try{let s=Array.from(this.manifestCache.values()).reduce((u,{manifest:f})=>u+f.tools.length,0);if(this.manifestCache.size===0)for(let u=0;u<3;u++){if((this.meshNode.node?.getConnections().length||0)>0){a.info("[LIOP-Router] P2P Connection established. Starting discovery...");break}a.info(`[LIOP-Router] Waiting for P2P connections (attempt ${u+1}/10)...`),await new Promise(p=>setTimeout(p,1e3));}let o=[],r=this.manifestCache.size===0?5:1;for(let u=0;u<r;u++){for(let g=0;g<x;g++){o=await this.meshNode?.discoverManifestProviders()||[];let y=this.meshNode?.getPeerId();if(o.filter(k=>k!==y).length>0)break;g<x-1&&(a.info(`[LIOP-Router] DHT discovery attempt ${g+1}/${x}...`),await new Promise(k=>setTimeout(k,1e3)));}let f=this.meshNode.node?.getConnections().map(g=>g.remotePeer.toString())||[];f.length>0&&(o=Array.from(new Set([...o,...f])));let p=this.meshNode?.getPeerId();if(o.filter(g=>g!==p).length>0)break;u<r-1&&(a.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${u+1}/${r})...`),await new Promise(g=>setTimeout(g,1e3)));}if(o.length===0){a.info("[LIOP-Router] No manifest providers found after all attempts.");return}e||a.info(`[LIOP-Router] Discovered ${o.length} candidate manifest providers`);let i=new Set((this.meshNode.node?.getConnections?.()||[]).map(u=>u.remotePeer.toString()));o=[...o].sort((u,f)=>{let p=i.has(u)?1:0;return (i.has(f)?1:0)-p});let t=0,n=0,a$1=!1,m=this.meshNode?.getPeerId(),c=o.filter(u=>{if(!this.meshNode||u===m||this.shouldSkipManifestQuery(u))return !1;let f=this.manifestCache.get(u);return f&&Date.now()-f.cachedAt<K*1e3?(t++,!1):!0}),l=await Promise.allSettled(c.map(async u=>this.meshNode?(a.info(`[LIOP-Router] Querying manifest from: ${u}`),{peerId:u,manifest:await this.meshNode.queryManifest(u)}):null));for(let u of l)if(u.status==="fulfilled"&&u.value?.manifest){let{peerId:f,manifest:p}=u.value;this.manifestCache.set(f,{manifest:p,cachedAt:Date.now()}),this.recordManifestQuerySuccess(f),a$1=!0,t++,a.info(`[LIOP-Router] Manifest received from ${f} (${p.tools.length} tools)`);}else u.status==="fulfilled"&&u.value?(this.recordManifestQueryFailure(u.value.peerId),n++,a.info(`[LIOP-Router] Manifest query returned NULL for ${u.value.peerId}`)):u.status==="rejected"&&(n++,a.info("[LIOP-Router] Fatal error querying manifest:",u.reason instanceof Error?u.reason.message:String(u.reason)));this._discoveryStats={candidates:o.length,success:t,failures:n,lastDiscovery:Date.now()},a$1&&Array.from(this.manifestCache.values()).reduce((f,{manifest:p})=>f+p.tools.length,0)!==s&&this.onToolsChanged&&(process.stderr.write(`[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.
10
- `),this.onToolsChanged());}finally{this.currentDiscovery=null;}})(),this.currentDiscovery}}getCacheSize(){return this.manifestCache.size}async getRemoteTools(){let e=Number.parseInt(process.env.LIOP_EXPECTED_PROVIDERS??"1",10);if(this.manifestCache.size<e&&this.meshNode){let i=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),t=Number.isFinite(i)&&i>0?i:12e3,n=Date.now()+t,a$1=0,m=-1;for(;Date.now()<n&&!(this.manifestCache.size>=e||(await Promise.race([this.refreshManifestCache(true),new Promise(c=>setTimeout(c,3e3))]).catch(()=>{}),this.manifestCache.size>=e));){if(this.manifestCache.size===m){if(a$1++,a$1>=3&&this.manifestCache.size>0){a.info(`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${e}. Proceeding with available mesh.`);break}}else a$1=0,m=this.manifestCache.size;await new Promise(c=>setTimeout(c,1e3));}this.manifestCache.size<e&&(a.info(`[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${e} providers. Some tools may be unavailable. Check Docker containers.`),this.refreshManifestCache(true).catch(()=>{}));}let s=[],o=new Set,r=new Set(this.liopServer.listTools().map(i=>i.name));for(let[i,{manifest:t}]of this.manifestCache.entries())for(let n of t.tools){if(n.name==="LiopMeshStatus")continue;let a=n.name;(o.has(n.name)||r.has(n.name))&&(a=`${n.name}_${i.slice(-4)}`),o.add(a);let m=t.serverInfo?.name||"Unknown Provider",c=n.description||`Remote tool from ${m}`,l={name:a,description:L()?D(c):c,inputSchema:n.inputSchema||{type:"object",properties:{}}};typeof l.inputSchema=="object"&&!l.inputSchema.type&&(l.inputSchema.type="object"),typeof l.inputSchema=="object"&&!l.inputSchema.properties&&(l.inputSchema.properties={});let u="";t.taxonomy&&(u=`
11
- [LIOP-DOMAIN: ${t.taxonomy.domain}]`);let f=l.inputSchema.properties||{},p="";!L()&&f.payload&&(p=`
12
- [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!L()&&l.description.includes("STRICT SCHEMA ADHERENCE")&&(l.description=l.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let h=L()?`
13
- (Peer: ${i.slice(-8)})${u}`:`
14
- (Origin: ${i.slice(-8)})${u}${p}`;l.description=`${l.description}${h}`,s.push(l);}return s}async getRemoteResources(){this.currentDiscovery||this.refreshManifestCache(true).catch(()=>{});let e=[],s=new Set(this.liopServer.listResources().map(o=>o.uri));for(let[o,{manifest:r}]of this.manifestCache.entries())for(let i of r.resources)if(!s.has(i.uri)){let t={...i},n=r.serverInfo?.name||"Unknown Provider",a="";r.taxonomy&&(a=`
15
-
16
- [LIOP Zero-Trust Blueprint]
17
- Domain: ${r.taxonomy.domain}
18
- Clearance Tier: ${r.taxonomy.clearanceTier}`,r.taxonomy.executionTypes&&r.taxonomy.executionTypes.length>0&&(a+=`
19
- Execution Types: ${r.taxonomy.executionTypes.join(", ")}`));let m=`
20
-
21
- [LIOP Zero-Trust Origin]
22
- Provider: ${n}
23
- Network ID: ${o}${a}`;t.uri.startsWith("liop://schema/")?(t.name=`[SCHEMA] ${t.name}`,t.description=`[CRITICAL SCHEMA] ${t.description||"Data Dictionary for Zero-Shot Autonomy"}${m}`):t.description=t.description?`${t.description}${m}`:m.trim(),e.push(t),s.add(i.uri);}return e}resolveManifestTarget(e){for(let[o,{manifest:r}]of this.manifestCache.entries())if(r.tools.find(t=>t.name===e))return {peerId:o,originalToolName:e};let s=e.split("_");if(s.length>1){let o=s.pop(),r=s.join("_");for(let[i,{manifest:t}]of this.manifestCache.entries())if(i.endsWith(o||"")&&t.tools.find(a=>a.name===r))return {peerId:i,originalToolName:r}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,s,o){let r=s.name;if(r==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let t=this._discoveryStats||{candidates:0,success:0,failures:0},n=this.manifestCache.size,a=this.meshNode?"Active":"Offline",m=Array.from(this.manifestCache.values()).reduce((O,{manifest:v})=>O+v.tools.length,0),c=this.meshNode?this.meshNode.node?.getConnections().length:0,l=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],u=l.length,p=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",h=p?l.map(O=>{let v=O.split("/"),P=v[v.length-1];return ` \u2022 ${P?P.slice(-8):"Unknown"} (bootstrap)`}).join(`
24
- `):"",g=this.meshNode?this.meshNode.getRoutingTableSize():0,y=this.meshNode?.getPeerId()||"Offline",S=y==="Offline"?y:this.redactPeerId(y),k=Array.from(this.manifestCache.entries()).flatMap(([O,{manifest:v}])=>v.tools.map(P=>` \u2022 ${P.name} (from origin: ${this.redactPeerId(O)})`)).join(`
25
- `),M=[`LIOP Mesh Status: ${a==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${S}`,`Network: ${c} Conns | ${g} Mesh Nodes | ${u} Bootstraps`,p&&u>0?`
26
- Active Bootstraps:
27
- ${h}
28
- `:"",`Discovery: ${t.candidates} Candidates | ${t.success} OK | ${t.failures} FAIL`,`Tooling: ${n} Providers | ${m} Total Remote Tools`,m>0?`
29
- Discovered Remote Tools (Zero-Trust Origins):
30
- ${k}`:`
31
- No remote tools discovered yet.`,I.getInstance().formatStatusBlock()].filter(O=>O!=="").join(`
32
- `),E=I.getInstance();return E.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:E.countTokens(M)}),{jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:M}]}}}let i=this.liopServer.listTools().some(t=>t.name===r);if(!i&&this.meshNode){let t=this.resolveManifestTarget(r);if(t||(await this.refreshManifestCache(),t=this.resolveManifestTarget(r)),t){a.info(`[LIOP-Router] Resolved ${r} via manifest cache (Peer: ${t.peerId}, Original: ${t.originalToolName})`);let a$1=this.manifestCache.get(t.peerId),m=o;if(a$1?.manifest.authRequired){let c=o||await this.getOrAcquireMeshAgentToken(t.peerId);if(!c){let l=a$1.manifest.serverInfo?.name?.toLowerCase()||"unknown",u=a$1.manifest.tokenSlug,f=t.peerId.slice(-8).toUpperCase(),p=u?`LIOP_TOKEN_${u}`:`LIOP_TOKEN_${l.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${l}) requires an access token. Please define the ${p} or LIOP_TOKEN_${f} environment variable on your agent/client host.`}],isError:true}}}m=c;}return this.routeToRemoteProvider(e,t.originalToolName,t.peerId,s,m)}let n=[];for(let a=0;a<3&&(n=await this.meshNode.findProviders(r),!(n.length>0));a++)a<2&&await new Promise(m=>setTimeout(m,1e3));if(n.length>0)return this.routeToRemoteProvider(e,r,n[0],s,o)}if(i)try{let t=Date.now(),n=await this.liopServer.callTool({name:r,arguments:s.arguments||{}}),a=I.getInstance(),m=JSON.stringify(s.arguments||{}),c=JSON.stringify(n);return a.record({type:"tool_call",method:"tools/call",toolName:r,estimatedInputTokens:a.countTokens(m),estimatedOutputTokens:a.countTokens(c),durationMs:Date.now()-t}),{jsonrpc:"2.0",id:e,result:n}}catch(t){return {jsonrpc:"2.0",id:e,error:{code:-32e3,message:t instanceof Error?t.message:String(t)}}}return {jsonrpc:"2.0",id:e,error:{code:-32002,message:`No provider found for tool: ${r}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(e,s,o,r,i){if(!this.meshNode)return {jsonrpc:"2.0",id:e,error:{code:-32603,message:"Mesh Node inactive"}};let t=this.manifestCache.get(o),n=this.defaultRpcPort;if(t)n=t.manifest.grpcPort;else {let p=await this.meshNode.queryManifest(o);p&&(n=p.grpcPort,this.manifestCache.set(o,{manifest:p,cachedAt:Date.now()}),t=this.manifestCache.get(o));}if((process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test")&&t){let p=t.manifest.serverInfo?.name?.toLowerCase()||"";p.includes("vault")?n=13011:p.includes("bank")?n=13021:p.includes("oracle")&&(n=13031);}let m=await this.meshNode.resolvePeer(o),c$1=null,l=await import('os'),u=Object.values(l.networkInterfaces()).flat().filter(p=>p?.family==="IPv4").map(p=>p?.address);for(let p of m){let h=p.split("/"),g=h.indexOf("ip4");if(g!==-1){let y=h[g+1];if(y==="127.0.0.1"||u.includes(y)){c$1=`127.0.0.1:${n}`;break}c$1||(c$1=`${y}:${n}`);}}c$1||(c$1=`127.0.0.1:${n}`),a.info(`[LIOP-Router] Dynamic route: ${s} -> ${c$1} (PeerID: ${o})`);let f=new a$3.LogicMesh(c$1,c());return this.performTranscoding(e,f,s,r,o,i)}meshAgentToken;async getOrAcquireMeshAgentToken(e){if(e){let n=this.manifestCache.get(e),a$1=n?.manifest.serverInfo?.name?.toLowerCase()||"",m,c=n?.manifest.tokenSlug;if(c){let l=`LIOP_TOKEN_${c}`;m=process.env[l]||process.env[`LIOP_OAUTH_TOKEN_${c}`],a.info(`[LIOP-Router] Step0 tokenSlug=${c} envKey=${l} found=${!!m} peer=${e.slice(-8)}`);}else a.info(`[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${e.slice(-8)} provider=${a$1}`);if(!m){let l=e.slice(-8).toUpperCase();m=process.env[`LIOP_TOKEN_${l}`]||process.env[`LIOP_OAUTH_TOKEN_${l}`];}if(!m&&a$1){let l=a$1.toUpperCase().replace(/[^A-Z0-9_]/g,"_");m=process.env[`LIOP_TOKEN_${l}`]||process.env[`LIOP_OAUTH_TOKEN_${l}`];}if(m)return a.info(`[LIOP-Router] Resolved node-specific token for peer ${e.slice(-8)} (${a$1||"unknown"})`),m}if(this.meshAgentToken)return this.meshAgentToken;let s=process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN;if(s)return this.meshAgentToken=s,this.meshAgentToken;let o=process.env.LIOP_NEXUS_URL;if(!o)return;let r=process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID||"liop-mesh-agent",i=process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET||"dev-secret-change-me",t=process.env.LIOP_OAUTH_AUDIENCE||process.env.LIOP_AUDIENCE||"urn:liop:mesh:api";try{let a$1=`${o.endsWith("/oidc")?o:`${o}/oidc`}/token`;a.info(`[LIOP-Router] Proactively acquiring M2M token from Nexus: ${a$1}`);let m=new URLSearchParams({grant_type:"client_credentials",scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",resource:t,client_id:r,client_secret:i}),c=await fetch(a$1,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:m.toString()});if(!c.ok){let u=await c.text();a.warn(`[LIOP-Router] M2M Token acquisition failed: ${c.status} ${u}`);return}let l=await c.json();if(l.access_token)return this.meshAgentToken=l.access_token,a.info("[LIOP-Router] M2M Token acquired successfully for router routing."),this.meshAgentToken}catch(n){a.warn(`[LIOP-Router] Failed to acquire M2M token: ${n instanceof Error?n.message:String(n)}`);}}async performTranscoding(e,s,o,r,i,t){let n=o,a=this.meshNode?await this.meshNode.sign(Buffer.from(n)):Buffer.from([]),m=Date.now(),c=t;if(c||(c=await this.getOrAcquireMeshAgentToken(i)),i){let l=this.manifestCache.get(i);if(l?.manifest.authRequired&&!c){let u=l.manifest.serverInfo?.name?.toLowerCase()||"unknown",f=l.manifest.tokenSlug,p=i.slice(-8).toUpperCase(),h=f?`LIOP_TOKEN_${f}`:`LIOP_TOKEN_${u.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${u}) requires an access token. Please define the ${h} or LIOP_TOKEN_${p} environment variable on your agent/client host.`}],isError:true}}}}return new Promise(l=>{let u=new U.Metadata;c&&u.add("authorization",`Bearer ${c}`),s.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:n,proof_of_intent:a},u,async(f,p)=>{if(f||!p.accepted)return l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`PQC Handshake Failed: ${f?.message||"Rejected"}`}],isError:true}});let{ciphertext:h,sharedSecret:g}=await a$4.encapsulateAsymmetric(p.kyber_public_key),y=JSON.stringify(r.arguments||{}),S=`return { "__liop_proxy_tool": "${o}", "__liop_proxy_args": ${y} };`,k=C.randomBytes(12),M=this.encryptWithNonce(Buffer.from(S),g,k),E=new U.Metadata;c&&E.add("authorization",`Bearer ${c}`);let O=s.executeLogic({session_token:p.session_token,wasm_binary:new Uint8Array(M),inputs:{},pqc_ciphertext:h,aes_nonce:k},E),v="",P=null;O.on("data",_=>{v+=_.semantic_evidence,P=_;}),O.on("end",async()=>{try{if(P&&!P.is_error){let W=Buffer.from(P.cryptographic_proof).toString("hex");if(!await this.verifier.verifyZkReceipt(Buffer.from(S),W,Buffer.from(P.zk_receipt),Buffer.from(g),v))return l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}})}let _=JSON.parse(v),A=I.getInstance();A.record({type:"tool_call",method:"tools/call",toolName:o,peerId:i,estimatedInputTokens:A.countTokens(y),estimatedOutputTokens:A.countTokens(v),durationMs:Date.now()-m}),l({jsonrpc:"2.0",id:e,result:_});}catch{l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:v}]}});}}),O.on("error",_=>l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`LIOP gRPC Error: ${_.message}`}],isError:true}}));});})}encryptWithNonce(e,s,o){let r=C.createCipheriv("aes-256-gcm",s,o),i=Buffer.concat([r.update(e),r.final()]);return Buffer.concat([i,r.getAuthTag()])}};export{b as a,R as b,V as c,q as d,$ as e,I as f,J as g};//# sourceMappingURL=chunk-CPLE5VZ5.js.map
33
- //# sourceMappingURL=chunk-CPLE5VZ5.js.map
@@ -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","serverConfig","LiopVerifier","peerId","state","now","failures","backoff","request","authInfo","method","params","id","authResult","authorizeRequest","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","token","stats","providerCount","meshState","cachedTools","connections","bootstrapNodes","bootstrapCount","showBootstraps","bootstrapList","addr","routingTableSize","rawPeerId","localPeerId","cachedToolList","statusText","line","diagTelemetry","isLocal","target","manifestEntry","effectiveToken","resolvedToken","slug","shortId","primaryVar","providers","localStartTime","localTelemetry","localInputPayload","localOutputPayload","grpcPort","addrs","targetAddr","os","localInterfaces","ipIdx","advertisedIp","remoteClient","liopV1","createChannelCredentials","nodeToken","envKey","cleanName","staticToken","nexusUrl","clientId","clientSecret","audience","tokenUrl","response","client","capabilityHash","proofOfIntent","transcodingStartTime","activeToken","metadata","ciphertext","sharedSecret","Kyber768Wrapper","embeddedArgsJson","proxyLogic","nonce","sealedLogic","metadataCall","call","resultBody","lastResponse","grpcRes","proofHex","parsedResult","remoteTelemetry","e","payload","cipher","encrypted"],"mappings":"oTA0BO,IAAMA,CAAAA,CAAN,KAAmD,CAChD,IAAA,CAAO,aAER,OAAA,CAER,WAAA,CACCC,CAAAA,CACAC,CAAAA,CACC,CACD,IAA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CAAC,CAAA,CAEDzE,EAAQ,CAAE,OAAA,CAAS,MAAO,EAAA,CAAAzD,CAAAA,CAAI,OAAQkJ,CAAa,CAAC,EACrD,CAAA,KAAa,CACZzF,EAAQ,CACP,OAAA,CAAS,MACT,EAAA,CAAAzD,CAAAA,CACA,MAAA,CAAQ,CAAE,QAAS,CAAC,CAAE,KAAM,MAAA,CAAQ,IAAA,CAAM8I,CAAW,CAAC,CAAE,CACzD,CAAC,EACF,CACD,CAAC,EACDD,CAAAA,CAAK,EAAA,CAAG,QAAUO,CAAAA,EACjB3F,CAAAA,CAAQ,CACP,OAAA,CAAS,MACT,EAAA,CAAAzD,CAAAA,CACA,OAAQ,CACP,OAAA,CAAS,CACR,CAAE,IAAA,CAAM,MAAA,CAAQ,IAAA,CAAM,oBAAoBoJ,CAAAA,CAAE,OAAO,EAAG,CACvD,CAAA,CACA,QAAS,IACV,CACD,CAAC,CACF,EACD,CACD,EACD,CAAC,CACF,CAEQ,iBACPC,CAAAA,CACAhN,CAAAA,CACAqM,CAAAA,CACS,CACT,IAAMY,CAAAA,CAAgB,CAAA,CAAA,cAAA,CAAe,cAAejN,CAAAA,CAAKqM,CAAK,EACxDa,CAAAA,CAAY,MAAA,CAAO,MAAA,CAAO,CAACD,EAAO,MAAA,CAAOD,CAAO,EAAGC,CAAAA,CAAO,KAAA,EAAO,CAAC,CAAA,CACxE,OAAO,MAAA,CAAO,MAAA,CAAO,CAACC,CAAAA,CAAWD,CAAAA,CAAO,YAAY,CAAC,CACtD,CACD","file":"chunk-CPLE5VZ5.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: compact tool descriptions are ENABLED by default to optimize\n * token consumption for LLM clients (e.g. Claude Desktop).\n *\n * Set LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS=0 to restore verbose descriptions.\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\tif (v === \"0\" || v === \"false\" || v === \"no\") return false;\n\treturn true;\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 * as grpc from \"@grpc/grpc-js\";\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 { AuthInfo } from \"../security/jwt-validator.js\";\nimport { authorizeRequest } from \"../security/rbac.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\t// biome-ignore lint/suspicious/noExplicitAny: access private configuration properties\n\t\t\t\tconst serverConfig = (this.liopServer as any).config;\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\tauthRequired: this.liopServer.jwtValidator !== undefined,\n\t\t\t\t\ttokenSlug: serverConfig?.tokenSlug,\n\t\t\t\t\ttaxonomy: serverConfig?.taxonomy\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tdomain: serverConfig.taxonomy.domain || \"Unknown Domain\",\n\t\t\t\t\t\t\t\tclearanceTier: serverConfig.taxonomy.clearanceTier ?? 0,\n\t\t\t\t\t\t\t\texecutionTypes: serverConfig.taxonomy.executionTypes || [],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\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(\n\t\trequest: McpRequest,\n\t\tauthInfo?: AuthInfo | null,\n\t): Promise<McpResponse | null> {\n\t\tconst { method, params, id } = request;\n\t\tlog.info(`[LIOP-Router] Processing: ${method}`);\n\n\t\t// [SEC] Enforce RBAC scope validation (Least Privilege) only if JWT validation is active\n\t\tif (this.liopServer.jwtValidator) {\n\t\t\tconst authResult = authorizeRequest(method, authInfo ?? null);\n\t\t\tif (!authResult.allowed) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] RBAC Access Denied for method '${method}': ${authResult.reason}`,\n\t\t\t\t);\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: -32099, // Custom authentication/authorization failure code\n\t\t\t\t\t\tmessage: authResult.reason || \"Access Denied\",\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\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(\n\t\t\t\t\tid,\n\t\t\t\t\tparams as { name: string; arguments?: Record<string, unknown> },\n\t\t\t\t\tauthInfo?.token,\n\t\t\t\t);\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 ?? \"1\",\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 ?? \"8000\",\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\tprivate async transcodeMcpToLiop(\n\t\tid: string | number | null | undefined,\n\t\tparams: { name: string; arguments?: Record<string, unknown> },\n\t\ttoken?: string,\n\t): Promise<McpResponse | null> {\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\n\t\t\t\t// Proactive auth check: block locally if the remote node requires authentication\n\t\t\t\t// and no token can be resolved — avoids unnecessary network calls to resolvePeer/gRPC\n\t\t\t\tconst manifestEntry = this.manifestCache.get(target.peerId);\n\t\t\t\tlet effectiveToken = token;\n\t\t\t\tif (manifestEntry?.manifest.authRequired) {\n\t\t\t\t\tconst resolvedToken =\n\t\t\t\t\t\ttoken || (await this.getOrAcquireMeshAgentToken(target.peerId));\n\t\t\t\t\tif (!resolvedToken) {\n\t\t\t\t\t\tconst providerName =\n\t\t\t\t\t\t\tmanifestEntry.manifest.serverInfo?.name?.toLowerCase() ||\n\t\t\t\t\t\t\t\"unknown\";\n\t\t\t\t\t\tconst slug = manifestEntry.manifest.tokenSlug;\n\t\t\t\t\t\tconst shortId = target.peerId.slice(-8).toUpperCase();\n\t\t\t\t\t\tconst primaryVar = slug\n\t\t\t\t\t\t\t? `LIOP_TOKEN_${slug}`\n\t\t\t\t\t\t\t: `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, \"_\")}`;\n\t\t\t\t\t\treturn {\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: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`,\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\t\t\t\t\t// Forward the resolved token instead of the original (potentially undefined) caller token\n\t\t\t\t\teffectiveToken = resolvedToken;\n\t\t\t\t}\n\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\teffectiveToken,\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(\n\t\t\t\t\tid,\n\t\t\t\t\ttoolName,\n\t\t\t\t\tproviders[0],\n\t\t\t\t\tparams,\n\t\t\t\t\ttoken,\n\t\t\t\t);\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\ttoken?: string,\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// Docker Demo convenience (opt-in):\n\t\t// Docker Desktop setups publish gRPC ports on the host as 13011/13021/13031.\n\t\t// Container-internal gRPC ports (50051) are unreachable from the host.\n\t\t// Activated by any Docker-mapping flag: LIOP_DOCKER_MAP, LIOP_DEV_MODE,\n\t\t// LIOP_USE_PUBLISHED_GRPC_PORTS, or NODE_ENV=development/test.\n\t\tconst shouldRemapGrpcPorts =\n\t\t\tprocess.env.LIOP_USE_PUBLISHED_GRPC_PORTS === \"1\" ||\n\t\t\tprocess.env.LIOP_DOCKER_MAP === \"true\" ||\n\t\t\tprocess.env.LIOP_DEV_MODE === \"true\" ||\n\t\t\tprocess.env.NODE_ENV === \"development\" ||\n\t\t\tprocess.env.NODE_ENV === \"test\";\n\t\tif (shouldRemapGrpcPorts && manifestEntry) {\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(\n\t\t\tid,\n\t\t\tremoteClient,\n\t\t\ttoolName,\n\t\t\tparams,\n\t\t\tpeerId,\n\t\t\ttoken,\n\t\t);\n\t}\n\n\t/** Cached M2M token for dynamic gateway-to-node routing */\n\tprivate meshAgentToken?: string;\n\n\t/**\n\t * Dynamically acquires an M2M access token from the Nexus Authorization Server.\n\t * If peerId is provided, checks if there are node-specific environment tokens\n\t * before falling back to the global static token or Nexus acquisition.\n\t */\n\tprivate async getOrAcquireMeshAgentToken(\n\t\tpeerId?: string,\n\t): Promise<string | undefined> {\n\t\tif (peerId) {\n\t\t\tconst manifestEntry = this.manifestCache.get(peerId);\n\t\t\tconst providerName =\n\t\t\t\tmanifestEntry?.manifest.serverInfo?.name?.toLowerCase() || \"\";\n\n\t\t\tlet nodeToken: string | undefined;\n\n\t\t\t// 0. Deterministic tokenSlug resolution (highest priority, zero heuristic)\n\t\t\tconst slug = manifestEntry?.manifest.tokenSlug;\n\t\t\tif (slug) {\n\t\t\t\tconst envKey = `LIOP_TOKEN_${slug}`;\n\t\t\t\tnodeToken =\n\t\t\t\t\tprocess.env[envKey] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Step0 tokenSlug=${slug} envKey=${envKey} found=${!!nodeToken} peer=${peerId.slice(-8)}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${peerId.slice(-8)} provider=${providerName}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// 1. PeerID-specific resolution: LIOP_TOKEN_<last 8 chars of PeerID in uppercase>\n\t\t\tif (!nodeToken) {\n\t\t\t\tconst shortId = peerId.slice(-8).toUpperCase();\n\t\t\t\tnodeToken =\n\t\t\t\t\tprocess.env[`LIOP_TOKEN_${shortId}`] ||\n\t\t\t\t\tprocess.env[`LIOP_OAUTH_TOKEN_${shortId}`];\n\t\t\t}\n\n\t\t\t// 2. Provider-name resolution: LIOP_TOKEN_<CLEAN_PROVIDER_NAME_UPPERCASE>\n\t\t\tif (!nodeToken && providerName) {\n\t\t\t\tconst cleanName = providerName\n\t\t\t\t\t.toUpperCase()\n\t\t\t\t\t.replace(/[^A-Z0-9_]/g, \"_\");\n\t\t\t\tnodeToken =\n\t\t\t\t\tprocess.env[`LIOP_TOKEN_${cleanName}`] ||\n\t\t\t\t\tprocess.env[`LIOP_OAUTH_TOKEN_${cleanName}`];\n\t\t\t}\n\n\t\t\tif (nodeToken) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Resolved node-specific token for peer ${peerId.slice(-8)} (${providerName || \"unknown\"})`,\n\t\t\t\t);\n\t\t\t\treturn nodeToken;\n\t\t\t}\n\t\t}\n\n\t\tif (this.meshAgentToken) return this.meshAgentToken;\n\n\t\t// Support static pre-generated Access Tokens from environment\n\t\tconst staticToken = process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;\n\t\tif (staticToken) {\n\t\t\tthis.meshAgentToken = staticToken;\n\t\t\treturn this.meshAgentToken;\n\t\t}\n\n\t\tconst nexusUrl = process.env.LIOP_NEXUS_URL;\n\t\tif (!nexusUrl) return undefined;\n\n\t\tconst clientId =\n\t\t\tprocess.env.LIOP_OAUTH_CLIENT_ID ||\n\t\t\tprocess.env.LIOP_CLIENT_ID ||\n\t\t\t\"liop-mesh-agent\";\n\t\tconst clientSecret =\n\t\t\tprocess.env.LIOP_OAUTH_CLIENT_SECRET ||\n\t\t\tprocess.env.LIOP_CLIENT_SECRET ||\n\t\t\t\"dev-secret-change-me\";\n\t\tconst audience =\n\t\t\tprocess.env.LIOP_OAUTH_AUDIENCE ||\n\t\t\tprocess.env.LIOP_AUDIENCE ||\n\t\t\t\"urn:liop:mesh:api\";\n\n\t\ttry {\n\t\t\tconst baseUrl = nexusUrl.endsWith(\"/oidc\")\n\t\t\t\t? nexusUrl\n\t\t\t\t: `${nexusUrl}/oidc`;\n\t\t\tconst tokenUrl = `${baseUrl}/token`;\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Router] Proactively acquiring M2M token from Nexus: ${tokenUrl}`,\n\t\t\t);\n\n\t\t\tconst params = new URLSearchParams({\n\t\t\t\tgrant_type: \"client_credentials\",\n\t\t\t\tscope:\n\t\t\t\t\t\"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query\",\n\t\t\t\tresource: audience,\n\t\t\t\tclient_id: clientId,\n\t\t\t\tclient_secret: clientSecret,\n\t\t\t});\n\n\t\t\tconst response = await fetch(tokenUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t},\n\t\t\t\tbody: params.toString(),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst text = await response.text();\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[LIOP-Router] M2M Token acquisition failed: ${response.status} ${text}`,\n\t\t\t\t);\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tconst data = (await response.json()) as { access_token: string };\n\t\t\tif (data.access_token) {\n\t\t\t\tthis.meshAgentToken = data.access_token;\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-Router] M2M Token acquired successfully for router routing.\",\n\t\t\t\t);\n\t\t\t\treturn this.meshAgentToken;\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tlog.warn(\n\t\t\t\t`[LIOP-Router] Failed to acquire M2M token: ${\n\t\t\t\t\terr instanceof Error ? err.message : String(err)\n\t\t\t\t}`,\n\t\t\t);\n\t\t}\n\t\treturn undefined;\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\ttoken?: 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\t// Auto-acquire self-identity M2M token if client did not supply one but a Nexus AS is configured\n\t\tlet activeToken = token;\n\t\tif (!activeToken) {\n\t\t\tactiveToken = await this.getOrAcquireMeshAgentToken(peerId);\n\t\t}\n\n\t\tif (peerId) {\n\t\t\tconst manifestEntry = this.manifestCache.get(peerId);\n\t\t\tif (manifestEntry?.manifest.authRequired && !activeToken) {\n\t\t\t\tconst providerName =\n\t\t\t\t\tmanifestEntry.manifest.serverInfo?.name?.toLowerCase() || \"unknown\";\n\t\t\t\tconst slug = manifestEntry.manifest.tokenSlug;\n\t\t\t\tconst shortId = peerId.slice(-8).toUpperCase();\n\t\t\t\tconst primaryVar = slug\n\t\t\t\t\t? `LIOP_TOKEN_${slug}`\n\t\t\t\t\t: `LIOP_TOKEN_${providerName.toUpperCase().replace(/[^A-Z0-9_]/g, \"_\")}`;\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\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Authentication Required: The restricted node (${providerName}) requires an access token. Please define the ${primaryVar} or LIOP_TOKEN_${shortId} environment variable on your agent/client host.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tconst metadata = new grpc.Metadata();\n\t\t\tif (activeToken) {\n\t\t\t\tmetadata.add(\"authorization\", `Bearer ${activeToken}`);\n\t\t\t}\n\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\tmetadata,\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 metadataCall = new grpc.Metadata();\n\t\t\t\t\tif (activeToken) {\n\t\t\t\t\t\tmetadataCall.add(\"authorization\", `Bearer ${activeToken}`);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst call = client.executeLogic(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsession_token: response.session_token,\n\t\t\t\t\t\t\twasm_binary: new Uint8Array(sealedLogic),\n\t\t\t\t\t\t\tinputs: {},\n\t\t\t\t\t\t\tpqc_ciphertext: ciphertext,\n\t\t\t\t\t\t\taes_nonce: nonce,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmetadataCall,\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\t// Only verify ZK-Receipt if the remote execution succeeded.\n\t\t\t\t\t\t\t\t// If the remote execution failed due to a policy error (e.g. Egress Shield),\n\t\t\t\t\t\t\t\t// the ZK proof is empty and we should bypass validation to propagate the original error.\n\t\t\t\t\t\t\t\tif (!lastResponse.is_error) {\n\t\t\t\t\t\t\t\t\tconst proofHex = Buffer.from(\n\t\t\t\t\t\t\t\t\t\tlastResponse.cryptographic_proof,\n\t\t\t\t\t\t\t\t\t).toString(\"hex\");\n\t\t\t\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\t\t\t\t\tproofHex,\n\t\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.zk_receipt),\n\t\t\t\t\t\t\t\t\t\tBuffer.from(sharedSecret),\n\t\t\t\t\t\t\t\t\t\tresultBody,\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: [\n\t\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\t\ttype: \"text\",\n\t\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\t},\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\tisError: true,\n\t\t\t\t\t\t\t\t\t\t\t},\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 {createMlKem768}from'mlkem';var a=null;async function n(){return a||(a=await createMlKem768()),a}var m={importPublicKey(e){if(e.length!==1184)throw new Error(`Kyber768 Public Key must be exactly 1184 bytes (Received: ${e.length})`);return e},async encapsulateAsymmetric(e){try{if(e.length!==1184)throw new Error("Kyber768 Public Key must be exactly 1184 bytes.");let r=await n(),[t,c]=r.encap(e);return {ciphertext:t,sharedSecret:c}}catch(r){throw new Error(`Failed to perform PQC encapsulation: ${r.message}`)}},async generateKeyPair(){let e=await n(),[r,t]=e.generateKeyPair();return {publicKey:r,secretKey:t}},async decapsulateSymmetric(e,r){return (await n()).decap(e,r)}};export{m as a};//# sourceMappingURL=chunk-DBXGYHKY.js.map
2
- //# sourceMappingURL=chunk-DBXGYHKY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc/crypto/kyber.ts"],"names":["kemInstance","getKemInstance","createMlKem768","Kyber768Wrapper","buffer","publicKey","kem","ct","ss","error","pk","sk","ciphertext","secretKey"],"mappings":"mCAcA,IAAIA,CAAAA,CAAiE,IAAA,CAErE,eAAeC,CAAAA,EAAiB,CAC/B,OAAKD,CAAAA,GACJA,CAAAA,CAAc,MAAME,cAAAA,EAAe,CAAA,CAE7BF,CACR,CAEO,IAAMG,CAAAA,CAAkB,CAK9B,eAAA,CAAgBC,CAAAA,CAAgC,CAC/C,GAAIA,CAAAA,CAAO,MAAA,GAAW,IAAA,CACrB,MAAM,IAAI,KAAA,CACT,CAAA,0DAAA,EAA6DA,CAAAA,CAAO,MAAM,CAAA,CAAA,CAC3E,CAAA,CAED,OAAOA,CACR,CAAA,CAMA,MAAM,qBAAA,CAAsBC,CAAAA,CAGzB,CACF,GAAI,CACH,GAAIA,CAAAA,CAAU,MAAA,GAAW,IAAA,CACxB,MAAM,IAAI,KAAA,CAAM,iDAAiD,CAAA,CAGlE,IAAMC,CAAAA,CAAM,MAAML,CAAAA,EAAe,CAC3B,CAACM,CAAAA,CAAIC,CAAE,EAAIF,CAAAA,CAAI,KAAA,CAAMD,CAAS,CAAA,CAEpC,OAAO,CACN,UAAA,CAAYE,CAAAA,CACZ,YAAA,CAAcC,CACf,CACD,CAAA,MAASC,CAAAA,CAAO,CACf,MAAM,IAAI,KAAA,CACT,CAAA,qCAAA,EAAyCA,CAAAA,CAAgB,OAAO,CAAA,CACjE,CACD,CACD,CAAA,CAKA,MAAM,eAAA,EAGH,CACF,IAAMH,CAAAA,CAAM,MAAML,CAAAA,EAAe,CAC3B,CAACS,CAAAA,CAAIC,CAAE,CAAA,CAAIL,CAAAA,CAAI,eAAA,EAAgB,CACrC,OAAO,CACN,SAAA,CAAWI,CAAAA,CACX,SAAA,CAAWC,CACZ,CACD,CAAA,CAMA,MAAM,oBAAA,CACLC,CAAAA,CACAC,CAAAA,CACsB,CAEtB,OAAA,CADY,MAAMZ,CAAAA,EAAe,EACtB,KAAA,CAAMW,CAAAA,CAAYC,CAAS,CACvC,CACD","file":"chunk-DBXGYHKY.js","sourcesContent":["import { createMlKem768 } from \"mlkem\";\n\n/**\n * LIOP Post-Quantum Cryptography Wrapper\n * Implements ML-KEM-768 (NIST FIPS 203) for Zero-Trust secure key encapsulation\n * directly compatible with `pqcrypto-kyber` on the Mesh-Node Backend.\n *\n * Uses the `mlkem` package which provides:\n * - FIPS 203 compliance (ML-KEM standard)\n * - Constant-time validation (KyberSlash patched)\n * - ~3.5x performance improvement over legacy crystals-kyber\n */\n\n/** Lazy-initialized singleton for the ML-KEM-768 engine */\nlet kemInstance: Awaited<ReturnType<typeof createMlKem768>> | null = null;\n\nasync function getKemInstance() {\n\tif (!kemInstance) {\n\t\tkemInstance = await createMlKem768();\n\t}\n\treturn kemInstance;\n}\n\nexport const Kyber768Wrapper = {\n\t/**\n\t * Extracts and validates the 1184-byte Public Key from the Rust LIOP Data Node\n\t * @param buffer Raw buffer sent via gRPC IntentResponse\n\t */\n\timportPublicKey(buffer: Uint8Array): Uint8Array {\n\t\tif (buffer.length !== 1184) {\n\t\t\tthrow new Error(\n\t\t\t\t`Kyber768 Public Key must be exactly 1184 bytes (Received: ${buffer.length})`,\n\t\t\t);\n\t\t}\n\t\treturn buffer;\n\t},\n\n\t/**\n\t * Encapsulates a shared secret using the server's public key.\n\t * Returns the 1088-byte ciphertext to be sent back, and the 32-byte shared AES secret.\n\t */\n\tasync encapsulateAsymmetric(publicKey: Uint8Array): Promise<{\n\t\tciphertext: Uint8Array;\n\t\tsharedSecret: Uint8Array;\n\t}> {\n\t\ttry {\n\t\t\tif (publicKey.length !== 1184) {\n\t\t\t\tthrow new Error(\"Kyber768 Public Key must be exactly 1184 bytes.\");\n\t\t\t}\n\n\t\t\tconst kem = await getKemInstance();\n\t\t\tconst [ct, ss] = kem.encap(publicKey);\n\n\t\t\treturn {\n\t\t\t\tciphertext: ct,\n\t\t\t\tsharedSecret: ss,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to perform PQC encapsulation: ${(error as Error).message}`,\n\t\t\t);\n\t\t}\n\t},\n\n\t/**\n\t * Generates a Kyber768 KeyPair for the server to accept intents.\n\t */\n\tasync generateKeyPair(): Promise<{\n\t\tpublicKey: Uint8Array;\n\t\tsecretKey: Uint8Array;\n\t}> {\n\t\tconst kem = await getKemInstance();\n\t\tconst [pk, sk] = kem.generateKeyPair();\n\t\treturn {\n\t\t\tpublicKey: pk,\n\t\t\tsecretKey: sk,\n\t\t};\n\t},\n\n\t/**\n\t * Decapsulates the shared secret using the server's secret key.\n\t * Zero-fills the shared secret buffer after extraction for side-channel protection.\n\t */\n\tasync decapsulateSymmetric(\n\t\tciphertext: Uint8Array,\n\t\tsecretKey: Uint8Array,\n\t): Promise<Uint8Array> {\n\t\tconst kem = await getKemInstance();\n\t\treturn kem.decap(ciphertext, secretKey);\n\t},\n};\n"]}
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-S6RJHZV2.js';import*as P from'fs/promises';import*as w from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {bootstrap}from'@libp2p/bootstrap';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var q=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],S="/liop/manifest/1.0.0",O="liop:manifest",E=class v{node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(t={}){this.config={listenAddresses:t.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:t.bootstrapNodes||[],identityPath:t.identityPath,enableWAN:t.enableWAN??false,dhtStoragePath:t.dhtStoragePath,addressMapper:t.addressMapper};}shouldSkipManifestDial(t){let e=this.manifestDialFailureState.get(t);if(!e)return false;let n=Date.now();return n>=e.cooldownUntil?false:(n-e.lastSkipLogAt>v.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Mesh] Skipping manifest dial for ${t} during cooldown (${Math.ceil((e.cooldownUntil-n)/1e3)}s remaining)`),e.lastSkipLogAt=n),true)}recordManifestDialFailure(t){let e=Date.now(),r=(this.manifestDialFailureState.get(t)?.failures||0)+1,o=Math.min(v.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),v.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(t,{failures:r,cooldownUntil:e+o,lastSkipLogAt:0});}clearManifestDialFailure(t){this.manifestDialFailureState.delete(t);}async loadOrCreateIdentity(){try{let{generateKeyPair:t,privateKeyFromProtobuf:e}=await import('@libp2p/crypto/keys'),n=await import('uint8arrays');if(this.config.identityPath){let o=w.resolve(this.config.identityPath);try{let d=await P.readFile(o,"utf-8"),s=JSON.parse(d),l=n.fromString(s.privKey,"base64");try{let a$1=e(l);return a.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a$1,isNew:!1}}catch(a$1){a.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a$1 instanceof Error?a$1.message:String(a$1)}`);}}catch(d){let s=d;s.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Error loading identity: ${s.message}`);}}return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){a.error(`[LIOP-Mesh] Critical error in identity management: ${t}. Falling back to ephemeral identity.`);try{let{generateKeyPair:e}=await import('@libp2p/crypto/keys');return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){throw new Error(`Identity system failure: ${e}`)}}}async saveIdentity(t){if(!(!this.config.identityPath||!this.node))try{let e=w.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),r=await import('uint8arrays'),o=n(t),d=(r.toString||r.default.toString)(o,"base64"),s={id:this.node.peerId.toString(),privKey:d};await P.mkdir(w.dirname(e),{recursive:!0}),await P.writeFile(e,JSON.stringify(s,null,2)),a.info(`[LIOP-Mesh] Identity persisted to ${e}`);}catch(e){a.error(`[LIOP-Mesh] FAILED to persist identity: ${e}`);}}async capabilityToCID(t){let e=await sha256.digest(new TextEncoder().encode(t));return CID.create(1,85,e)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(t=>setTimeout(t,500)),!this.node)return;a.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let t of this.announcedCapabilities)try{let e=await this.capabilityToCID(t);await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Re-announced: ${t}`);}catch(e){a.info(`[LIOP-Mesh] Re-announce failed for ${t}: ${e}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let t=await this.loadOrCreateIdentity();if(!t)throw new Error("Could not initialize P2P Identity");let{privateKey:e,isNew:n}=t;this.localPrivateKey=e;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=q);let o=r.length>0?[bootstrap({list:r})]:void 0,d=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0";if(this.node=await createLibp2p({privateKey:e,addresses:{listen:this.config.listenAddresses},transports:[tcp(),webSockets()],connectionEncrypters:[noise()],streamMuxers:[yamux()],services:{identify:identify(),ping:ping(),dht:kadDHT({protocol:d,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:s=>s})},peerDiscovery:o}),this.node.addEventListener("peer:discovery",s=>{let l=s.detail.id;if(a.info(`[LIOP-Mesh] Discovered peer: ${l.toString()}`),this.node){let a=l;if(this.config.addressMapper&&s.detail.multiaddrs.length>0){let c=s.detail.multiaddrs.map(u=>{let m=this.config.addressMapper(u.toString());return m?multiaddr(m):null}).filter(u=>u!==null).find(u=>u.toString().includes("/tcp/")&&!u.toString().includes("/ws"));c&&(a=c);}this.node.dial(a).catch(()=>{});}}),this.node.addEventListener("peer:connect",s=>{let l=s.detail;if(a.info(`[LIOP-Mesh] Connected to peer: ${l.toString()}`),!this.node)return;let a$1=this.node.services.dht;a$1?.routingTable&&(a.info(`[LIOP-Mesh] Adding ${l.toString()} to DHT Routing Table`),a$1.routingTable.add(l).catch(f=>{a.info(`[LIOP-Mesh] Failed to add peer to routing table: ${f instanceof Error?f.message:String(f)}`);})),this.reannounceAll().catch(f=>{a.info(`[LIOP-Mesh] Re-announce error: ${f instanceof Error?f.message:String(f)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(e),a.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(s=>{a.info(`[LIOP-Mesh] Listening on: ${s.toString()}`);}),r.length>0){a.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let s=5;for(let l of r){let a$1=false,f=1;for(;f<=s&&!a$1;)try{await this.node.dial(multiaddr(l)),a.info(`[LIOP-Mesh] \u2705 Successfully dialed ${l}`),a$1=!0;}catch{let u=Math.min(1e3*2**(f-1),3e3);a.warn(`[LIOP-Mesh] \u26A0\uFE0F Dial attempt ${f}/${s} to ${l} failed. Retrying in ${u/1e3}s...`),f<s?await new Promise(m=>setTimeout(m,u)):a.error(`[LIOP-Mesh] \u274C Could not connect to bootstrap ${l} after ${s} attempts. Continuing...`),f++;}}}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),a.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await P.readFile(t,"utf-8"),n=JSON.parse(e),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let d of n)if(!(!d.id||!d.addresses))try{let s=r(d.id),l=d.addresses.map(f=>multiaddr(f));await this.node.peerStore.save(s,{multiaddrs:l});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(s).catch(()=>{}),o++;}catch{}a.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(t){let e=t;e.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await this.node.peerStore.all(),n=[];for(let r of e)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await P.mkdir(w.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify(n,null,2)),a.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(t){a.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${t}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(O).catch(t=>{a.info(`[LIOP-Mesh] Initial manifest announcement failed: ${t}`);}),this.node.handle(S,async(t,e)=>{let n=t?.stream??t,o=(t?.connection??e)?.remotePeer?.toString()||"unknown";a.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let d=this.manifestProvider?.();if(!d||!n){a.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let s=JSON.stringify(d),l=new TextEncoder().encode(s),a$1=Buffer.alloc(4);a$1.writeUInt32BE(l.length,0);let f=Buffer.concat([a$1,Buffer.from(l)]);a.info(`[LIOP-Mesh] Serving manifest (${f.length} bytes) to ${o} [Tools: ${d.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(f)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(u){a.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${u instanceof Error?u.message:String(u)}`);}}else await pipe([f],n);a.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){a.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(d){a.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${d instanceof Error?d.message:String(d)}`);}}),a.info(`[LIOP-Mesh] Manifest Protocol registered: ${S}`));}registerManifestHandler(t){this.manifestProvider=t,this.node&&this.applyHandlers();}async queryManifest(t){if(!this.node)throw new Error("Mesh Node is not running");if(t===this.node.peerId.toString())return a.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${t}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(t))return null;let e=3;for(let n=1;n<=e;n++)try{let r=null,d=this.node.getConnections().find(h=>h.remotePeer.toString()===t);if(d)r=d.remotePeer;else {let p=(await this.node.peerStore.all()).find(g=>g.id.toString()===t);if(p)r=p.id;else {let{peerIdFromString:g}=await import('@libp2p/peer-id');r=g(t);}}let l=r;if(this.config.addressMapper&&this.node){let h=this.config.addressMapper,p=await this.node.peerStore.get(r);if(p&&p.addresses.length>0){let g=p.addresses.map(y=>{let C=y.multiaddr.toString(),T=h(C);return T?{isCertified:y.isCertified,multiaddr:multiaddr(T)}:null}).filter(y=>y!==null),L=g.find(y=>y.multiaddr.toString().includes("/tcp/")&&!y.multiaddr.toString().includes("/ws"));L&&(l=L.multiaddr,a.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${l.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:g.map(y=>y.multiaddr)});}}let a$1;try{let h=await this.node.dialProtocol(l,S).catch(p=>{throw String(p).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):p});a$1=h.stream||h;}catch(h){if(n===e)return a.info(`[LIOP-Mesh] Dial error for ${t} after ${e} attempts: ${h}`),null;let p=500*2**n;a.info(`[LIOP-Mesh] Dial error for ${t} (Attempt ${n}). Retrying in ${p}ms...`),await new Promise(g=>setTimeout(g,p));continue}let f=a$1.source??(typeof a$1[Symbol.asyncIterator]=="function"?a$1:null);if(!f)throw new Error("Target stream has no AsyncIterable source");let c=[],u=0,m=-1,M,A=new Promise((h,p)=>{M=setTimeout(()=>p(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let h of f){if(!h)continue;let p=typeof h.subarray=="function"?h.subarray():h instanceof Uint8Array?h:new Uint8Array(0),g=Buffer.from(p.buffer,p.byteOffset,p.byteLength);if(g.length>0&&(c.push(g),u+=g.length,m<0&&u>=4&&(m=Buffer.concat(c).readUInt32BE(0)),m>=0&&u>=4+m))break}})(),A]);}catch(h){if(c.length===0)throw h;a.info(`[LIOP-Mesh] Partial manifest read from ${t}: ${h instanceof Error?h.message:String(h)}`);}finally{M&&clearTimeout(M);}let I=Buffer.concat(c);if(I.length<4)throw new Error("Received empty/invalid manifest (too short)");let D=I.readUInt32BE(0),N=I.subarray(4,4+D).toString("utf-8"),$=JSON.parse(N);return a.info(`[LIOP-Mesh] Received manifest from ${t}: ${$.tools.length} tools`),this.clearManifestDialFailure(t),$}catch(r){if(n===e)return this.recordManifestDialFailure(t),a.info(`[LIOP-Mesh] Failed to query manifest from ${t} after ${e} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;a.info(`[LIOP-Mesh] Query error for ${t} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(d=>setTimeout(d,o));}return null}async discoverManifestProviders(){return this.findProviders(O)}async announceManifest(){await this.announceCapability(O);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(t){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(t))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(t=>t.toString())}async announceCapability(t){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(t);try{let e=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Announcing capability: ${t} (CID: ${e.toString()})`),await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Successfully announced capability: ${t}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(e))if(r.id.toString()===n){a.info(`[LIOP-Mesh] Self-verification success: Node is providing ${t}`);break}}catch(e){a.error(`[LIOP-Mesh] Failed to announce capability: ${e}`);}}async findProviders(t){if(!this.node)throw new Error("Mesh Node is not running");let e=[];try{let n=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Querying DHT for ${t} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,d=o>1?1500:3e3;a.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${d}ms (Active connections: ${o})`);let s=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),l=!1;for(;!l;){let a$1=s.next(),f=new Promise(c=>setTimeout(()=>c({timeout:!0}),d));try{let c=await Promise.race([a$1,f]);if(c&&typeof c=="object"&&"timeout"in c){a.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof s.return=="function"&&s.return().catch(()=>{}),l=!0;break}let u=c;if(u.done){l=!0;break}r=!0;let M=u.value.id.toString();a.info(`[LIOP-Mesh] Found provider: ${M}`),e.includes(M)||e.push(M);}catch(c){a.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),l=!0;break}}if(!r){let f=this.node.services.dht?.routingTable?.size||0;a.info(`[LIOP-Mesh] DHT search for ${t} returned zero results (routing table size: ${f})`);}if(this.announcedCapabilities.has(t)){let a$1=this.node.peerId.toString();e.includes(a$1)||(a.info(`[LIOP-Mesh] Including local node (${a$1}) in results for ${t}`),e.push(a$1));}}catch(n){a.info(`[LIOP-Mesh] Error finding providers for ${t}: ${n instanceof Error?n.message:String(n)}`);}return a.info(`[LIOP-Mesh] DHT search for ${t} finished. Found ${e.length} providers.`),e}async resolvePeer(t){if(!this.node)throw new Error("Mesh Node is not running");try{let e=this.node.getConnections();for(let r of e)if(r.remotePeer.toString()===t){let o=r.remoteAddr.toString();return a.info(`[LIOP-Mesh] Resolved peer ${t} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===t&&r.addresses.length>0){let o=r.addresses.map(d=>d.multiaddr.toString());return a.info(`[LIOP-Mesh] Resolved peer ${t} via peerStore: ${o[0]}`),o}a.info(`[LIOP-Mesh] Peer ${t} not found in connections or peerStore`);}catch(e){a.info(`[LIOP-Mesh] Failed to resolve peer ${t}: ${e}`);}return []}};export{E as a};//# sourceMappingURL=chunk-DQ6UW6L7.js.map
2
- //# sourceMappingURL=chunk-DQ6UW6L7.js.map