@nekzus/liop 2.0.0-alpha.14 → 2.0.0-alpha.15

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.
package/dist/bin/agent.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {f}from'../chunk-YDGVPISC.js';import'../chunk-2MGFSIXN.js';import {g}from'../chunk-7MAGL6ON.js';import'../chunk-UVTEJYHN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-HM77MWB6.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-PPCOS2NU.js';import {a}from'../chunk-S6RJHZV2.js';import'../chunk-4C666HHU.js';import*as l from'fs';import*as _ from'os';import*as d from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let c=t.endsWith("/health")?t:`${t}/health`,u=await fetch(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!u.ok)return null;let e=await u.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(a=>a.includes("/tcp/")&&!a.includes("/ws")&&!a.includes("/ip4/127.0.0.1/"));if(!p)return null;let i=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"?N(p):p;if(!i||i===p){let a=new URL(t).hostname;i=p.replace(/\/ip4\/[^/]+/,`/ip4/${a}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,i):null}catch{return null}}function P(t){let c=t.trim(),u=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(u.test(c)||e.test(c)||p.test(c)){let f="127.0.0.1",i=c.replace(u,`/ip4/${f}`).replace(e,`/ip4/${f}`).replace(p,`/ip4/${f}`);return i!==c&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${i}`),i}return c}function N(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}async function E(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",r=>process.exit(r??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let c=d.join(_.homedir(),".liop"),u=d.join(c,"identity.json");l.existsSync(c)||l.mkdirSync(c,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=d.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let r=l.readFileSync(n,"utf8").trim();r&&e.push(P(r));}}s.push(process.cwd(),d.join(process.cwd(),"tests/infra/nexus-data"),c,d.join(d.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let T=d.join(n,g),I=l.readFileSync(T,"utf8").trim();if(I){let S=P(I);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let r=P(n);e.includes(r)||(e.push(r),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${r}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let f$1=new f({name:"@nekzus/liop",version:"1.0.0"});f$1.enableZeroShotAutonomy();let i=new a$1({identityPath:u,bootstrapNodes:e,addressMapper:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"?N:void 0});await i.start();let a$2=new g(f$1,i);a$2.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
2
+ import {f}from'../chunk-YDGVPISC.js';import'../chunk-2MGFSIXN.js';import {g}from'../chunk-CTB5O4PB.js';import'../chunk-UVTEJYHN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-HM77MWB6.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-PPCOS2NU.js';import {a}from'../chunk-S6RJHZV2.js';import'../chunk-4C666HHU.js';import*as l from'fs';import*as _ from'os';import*as d from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let c=t.endsWith("/health")?t:`${t}/health`,u=await fetch(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!u.ok)return null;let e=await u.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(a=>a.includes("/tcp/")&&!a.includes("/ws")&&!a.includes("/ip4/127.0.0.1/"));if(!p)return null;let i=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"?N(p):p;if(!i||i===p){let a=new URL(t).hostname;i=p.replace(/\/ip4\/[^/]+/,`/ip4/${a}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,i):null}catch{return null}}function P(t){let c=t.trim(),u=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(u.test(c)||e.test(c)||p.test(c)){let f="127.0.0.1",i=c.replace(u,`/ip4/${f}`).replace(e,`/ip4/${f}`).replace(p,`/ip4/${f}`);return i!==c&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${i}`),i}return c}function N(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}async function E(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",r=>process.exit(r??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let c=d.join(_.homedir(),".liop"),u=d.join(c,"identity.json");l.existsSync(c)||l.mkdirSync(c,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=d.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let r=l.readFileSync(n,"utf8").trim();r&&e.push(P(r));}}s.push(process.cwd(),d.join(process.cwd(),"tests/infra/nexus-data"),c,d.join(d.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let T=d.join(n,g),I=l.readFileSync(T,"utf8").trim();if(I){let S=P(I);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let r=P(n);e.includes(r)||(e.push(r),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${r}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let f$1=new f({name:"@nekzus/liop",version:"1.0.0"});f$1.enableZeroShotAutonomy();let i=new a$1({identityPath:u,bootstrapNodes:e,addressMapper:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"?N:void 0});await i.start();let a$2=new g(f$1,i);a$2.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
3
3
  `),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
4
4
  `);},setTimeout(()=>{let s=i.getRoutingTableSize?.()||0;a.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${s}`),a$2.refreshManifestCache(true).catch(()=>{});},2e3);let O=1e4,R=12e4,m=O,v=()=>{setTimeout(async()=>{let s=a$2.getCacheSize();await a$2.refreshManifestCache(true).catch(()=>{});let n=a$2.getCacheSize();n!==s?(m=O,a.info(`[LIOP-Agent] Topology change detected (${s} \u2192 ${n}). Resetting poll to ${O/1e3}s.`)):m=Math.min(Math.round(m*1.5),R),v();},m);};v();let L=(await import('readline')).createInterface({input:process.stdin,terminal:false});process.stdout.on("error",s=>{s.code==="EPIPE"&&process.exit(0);}),L.on("line",async s=>{let n=s.trim();if(n)try{let r=JSON.parse(n);if(r.method){let h=await a$2.dispatch(r);h&&process.stdout.write(`${JSON.stringify(h)}
5
5
  `);}}catch{}}),L.on("close",()=>{process.exit(0);}),a.info("[LIOP-Agent] Guarding Claude Desktop via STDIO."),a.info(`[LIOP-Agent] P2P Mesh: Joined (${e.length} bootstraps)`),a.info("[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0"),process.on("SIGINT",async()=>{await i.stop(),process.exit(0);});}E().catch(t=>{a.error(`[LIOP-Agent] Fatal Error: ${t.message}`),process.exit(1);});//# sourceMappingURL=agent.js.map
@@ -0,0 +1,33 @@
1
+ import {a as a$1}from'./chunk-UVTEJYHN.js';import {a as a$3}from'./chunk-DBXGYHKY.js';import {a as a$2,c}from'./chunk-HM77MWB6.js';import {a}from'./chunk-S6RJHZV2.js';import*as G from'crypto';var H=class{name="o200k_base";countFn;constructor(e,t){this.countFn=e,t&&t(1e4);}countTokens(e){return e.length===0?0:this.countFn(e)}},B=class{name="heuristic (chars/4)";countTokens(e){return e.length===0?0:Math.ceil(e.length/4)}};async function le(){try{let i=await import('gpt-tokenizer'),e=new H(i.countTokens,i.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 B}}function ue(){return new B}var b="1.9.1";var pe=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function ye(i){let e=new Set([i]),t=new Set,r=i.match(pe);if(!r)return ()=>false;let s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(a){return a===i};function o(c){return t.add(c),false}function n(c){return e.add(c),true}return function(a){if(e.has(a))return true;if(t.has(a))return false;let l=a.match(pe);if(!l)return o(a);let m={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return m.prerelease!=null||s.major!==m.major?o(a):s.major===0?s.minor===m.minor&&s.patch<=m.patch?n(a):o(a):s.minor<=m.minor?n(a):o(a)}}var me=ye(b);var ve=b.split(".")[0],L=Symbol.for(`opentelemetry.js.api.${ve}`),x=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function j(i,e,t,r=false){var s;let o=x[L]=(s=x[L])!==null&&s!==void 0?s:{version:b};if(!r&&o[i]){let n=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${i}`);return t.error(n.stack||n.message),false}if(o.version!==b){let n=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${i} does not match previously registered API v${b}`);return t.error(n.stack||n.message),false}return o[i]=e,t.debug(`@opentelemetry/api: Registered a global for ${i} v${b}.`),true}function N(i){var e,t;let r=(e=x[L])===null||e===void 0?void 0:e.version;if(!(!r||!me(r)))return (t=x[L])===null||t===void 0?void 0:t[i]}function U(i,e){e.debug(`@opentelemetry/api: Unregistering a global for ${i} v${b}.`);let t=x[L];t&&delete t[i];}var F=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger";}debug(...e){return $("debug",this._namespace,e)}error(...e){return $("error",this._namespace,e)}info(...e){return $("info",this._namespace,e)}warn(...e){return $("warn",this._namespace,e)}verbose(...e){return $("verbose",this._namespace,e)}};function $(i,e,t){let r=N("diag");if(r)return r[i](e,...t)}var _;(function(i){i[i.NONE=0]="NONE",i[i.ERROR=30]="ERROR",i[i.WARN=50]="WARN",i[i.INFO=60]="INFO",i[i.DEBUG=70]="DEBUG",i[i.VERBOSE=80]="VERBOSE",i[i.ALL=9999]="ALL";})(_||(_={}));function de(i,e){i<_.NONE?i=_.NONE:i>_.ALL&&(i=_.ALL),e=e||{};function t(r,s){let o=e[r];return typeof o=="function"&&i>=s?o.bind(e):function(){}}return {error:t("error",_.ERROR),warn:t("warn",_.WARN),info:t("info",_.INFO),debug:t("debug",_.DEBUG),verbose:t("verbose",_.VERBOSE)}}var Oe="diag",A=class i{static instance(){return this._instance||(this._instance=new i),this._instance}constructor(){function e(s){return function(...o){let n=N("diag");if(n)return n[s](...o)}}let t=this,r=(s,o={logLevel:_.INFO})=>{var n,c,a;if(s===t){let f=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((n=f.stack)!==null&&n!==void 0?n:f.message),false}typeof o=="number"&&(o={logLevel:o});let l=N("diag"),m=de((c=o.logLevel)!==null&&c!==void 0?c:_.INFO,s);if(l&&!o.suppressOverrideMessage){let f=(a=new Error().stack)!==null&&a!==void 0?a:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${f}`),m.warn(`Current logger will overwrite one already registered from ${f}`);}return j("diag",m,t,true)};t.setLogger=r,t.disable=()=>{U(Oe,t);},t.createComponentLogger=s=>new F(s),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error");}};var W=class{constructor(){}createGauge(e,t){return Ie}createHistogram(e,t){return Se}createCounter(e,t){return _e}createUpDownCounter(e,t){return Pe}createObservableGauge(e,t){return ke}createObservableCounter(e,t){return Ee}createObservableUpDownCounter(e,t){return be}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},w=class{},J=class extends w{add(e,t){}},q=class extends w{add(e,t){}},K=class extends w{record(e,t){}},Q=class extends w{record(e,t){}},D=class{addCallback(e){}removeCallback(e){}},X=class extends D{},Y=class extends D{},Z=class extends D{},fe=new W,_e=new J,Ie=new K,Se=new Q,Pe=new q,Ee=new X,ke=new Y,be=new Z;var ee=class{getMeter(e,t,r){return fe}},he=new ee;var te="metrics",V=class i{constructor(){}static getInstance(){return this._instance||(this._instance=new i),this._instance}setGlobalMeterProvider(e){return j(te,e,A.instance())}getMeterProvider(){return N(te)||he}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){U(te,A.instance());}};var oe=V.getInstance();var Re="@nekzus/liop",Ne="1.2.0-alpha.9",we=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],Me=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],z=class{tokenUsage;operationDuration;active=false;constructor(){try{let e=oe.getMeter(Re,Ne);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:we}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:Me}}),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 t={record:()=>{}};this.tokenUsage=t,this.operationDuration=t;}}recordTokens(e,t,r,s){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":r,"gen_ai.token.type":t,"gen_ai.request.model":"liop-mesh",...s?{"liop.tool.name":s}:{}});}recordDuration(e,t,r){this.operationDuration.record(e/1e3,{"gen_ai.system":"liop","gen_ai.operation.name":t,...r?{"error.type":r}:{}});}isActive(){return this.active}};var Ce={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},S=class i{static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=ue(),this.otelBridge=new z,this.initRealEstimator();}initRealEstimator(){le().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return i.instance||(i.instance=new i),i.instance}countTokens(e){try{return this.estimator.countTokens(e)}catch{return Math.ceil(e.length/4)}}record(e){let t={...e,timestamp:Date.now()};this.operations.push(t);try{let r=Ce[e.type]||"chat";e.estimatedInputTokens>0&&this.otelBridge.recordTokens(e.estimatedInputTokens,"input",r,e.toolName),e.estimatedOutputTokens>0&&this.otelBridge.recordTokens(e.estimatedOutputTokens,"output",r,e.toolName),e.durationMs!==void 0&&this.otelBridge.recordDuration(e.durationMs,r);}catch{}}estimateTokens(e){return this.countTokens(e)}getReport(){return {sessionId:this.sessionId,operations:[...this.operations],totalInputTokens:this.operations.reduce((e,t)=>e+t.estimatedInputTokens,0),totalOutputTokens:this.operations.reduce((e,t)=>e+t.estimatedOutputTokens,0),estimatorName:this.estimator.name,sessionUptimeMs:Date.now()-this.startedAt}}getPerToolReport(){let e=new Map;for(let t of this.operations){let r=t.toolName||t.method,s=e.get(r)||{input:0,output:0,calls:0,avgDurationMs:0},o=s.avgDurationMs*s.calls+(t.durationMs||0),n=s.calls+1;e.set(r,{input:s.input+t.estimatedInputTokens,output:s.output+t.estimatedOutputTokens,calls:n,avgDurationMs:n>0?o/n:0});}return e}formatStatusBlock(){let e=this.getReport();if(e.operations.length===0)return "";let t=this.formatUptime(e.sessionUptimeMs),r=e.totalInputTokens+e.totalOutputTokens,s=new Map;for(let d of e.operations){let g=d.type,h=s.get(g)||{count:0,input:0,output:0};s.set(g,{count:h.count+1,input:h.input+d.estimatedInputTokens,output:h.output+d.estimatedOutputTokens});}let o=Array.from(s.entries()),n=o.map(([d,g],h)=>{let k=h===o.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",P=g.output>0?` / ${g.output.toLocaleString()} out`:"";return `${k} ${d} \xD7${g.count} \u2192 ${g.input.toLocaleString()} in${P}`}),c=this.getPerToolReport(),a=Array.from(c.entries()).filter(([d])=>d!=="tools/list"&&d!=="LiopMeshStatus"),l=[];a.length>0&&(l.push("\u251C\u2500 By Tool:"),a.forEach(([d,g],h)=>{let k=h===a.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",P=g.output>0?` / ${g.output.toLocaleString()} out`:"",I=g.avgDurationMs>0?` ~${Math.round(g.avgDurationMs)}ms`:"";l.push(`${k} ${d}: ${g.input.toLocaleString()} in${P} (\xD7${g.calls})${I}`);}));let m=e.operations.filter(d=>d.durationMs!==void 0),f=m.length>0?Math.round(m.reduce((d,g)=>d+(g.durationMs||0),0)/m.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)} (${t})`,`\u251C\u2500 Estimator: ${e.estimatorName}`,`\u251C\u2500 Operations: ${e.operations.length}`,...n,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${r.toLocaleString()} combined)`,...l,...f>0?[`\u251C\u2500 Avg Latency: ${f}ms`]:[],`\u2514\u2500 OTel: ${u}`].join(`
3
+ `)}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return `${t}s`;let r=Math.floor(t/60),s=t%60;if(r<60)return `${r}m ${s}s`;let o=Math.floor(r/60),n=r%60;return `${o}h ${n}m`}reset(){this.operations=[];}static destroy(){i.instance=null;}};function M(){let i=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(i==="0"||i==="false"||i==="no")}function re(i){let e=i,t=[`
4
+
5
+ [LIOP-PROTO-V1:`,`\r
6
+ \r
7
+ [LIOP-PROTO-V1:`,`
8
+ [LIOP-PROTO-V1:`];for(let r of t){let s=e.indexOf(r);if(s!==-1){e=e.slice(0,s);break}}return e.trimEnd()}var ge=300,ne=5,Te=class i{constructor(e,t=null,r=50051){this.liopServer=e;this.meshNode=t;this.defaultRpcPort=r;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let s=this.liopServer.listTools().map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema})),o=this.liopServer.listResources().map(n=>({name:n.name,uri:n.uri,description:n.description,mimeType:n.mimeType}));return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...s],resources:o,serverInfo:this.liopServer.getServerInfo()}}),this.meshNode.announceManifest().catch(s=>{a.info(`[LIOP-Router] Failed to announce manifest: ${s instanceof Error?s.message:String(s)}`);})),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 t=this.manifestFailureState.get(e);if(!t)return false;let r=Date.now();return r>=t.cooldownUntil?false:(r-t.lastSkipLogAt>i.MANIFEST_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Router] Skipping manifest query for ${e} during cooldown (${Math.ceil((t.cooldownUntil-r)/1e3)}s remaining)`),t.lastSkipLogAt=r),true)}recordManifestQuerySuccess(e){this.manifestFailureState.delete(e);}recordManifestQueryFailure(e){let t=Date.now(),s=(this.manifestFailureState.get(e)?.failures||0)+1,o=Math.min(i.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,s-1),i.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:s,cooldownUntil:t+o,lastSkipLogAt:0});}async dispatch(e){let{method:t,params:r,id:s}=e;switch(a.info(`[LIOP-Router] Processing: ${t}`),t){case "initialize":return {jsonrpc:"2.0",id:s,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:s,result:{}};case "tools/list":{let o=this.liopServer.listTools(),n=await this.getRemoteTools(),c=M()?o.map(p=>({...p,description:re(p.description??"")})):o;a.info(`[LIOP-Router] tools/list: ${o.length} local, ${n.length} remote tools found`);let l=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...c,...n],m=S.getInstance(),f=JSON.stringify(l),u=JSON.stringify({tools:l});return m.record({type:"tools_list",method:"tools/list",estimatedInputTokens:m.countTokens(f),estimatedOutputTokens:m.countTokens(u)}),{jsonrpc:"2.0",id:s,result:{tools:l}}}case "tools/call":return this.transcodeMcpToLiop(s,r);case "resources/list":{let o=this.liopServer.listResources(),n=await this.getRemoteResources(),c=[...o,...n],a=S.getInstance(),l=JSON.stringify(c);return a.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:a.countTokens(l)}),{jsonrpc:"2.0",id:s,result:{resources:c}}}case "resources/read":{let o=r;if(!o?.uri)return {jsonrpc:"2.0",id:s,error:{code:-32602,message:"Missing resource uri"}};try{let n=Date.now(),c=await this.liopServer.readResource(o.uri),a=S.getInstance(),l=JSON.stringify(c);return a.record({type:"resource_read",method:"resources/read",toolName:o.uri,estimatedInputTokens:a.countTokens(o.uri),estimatedOutputTokens:a.countTokens(l),durationMs:Date.now()-n}),{jsonrpc:"2.0",id:s,result:c}}catch(n){let c=o.uri;for(let{manifest:a$1}of this.manifestCache.values()){let l=a$1.resources.find(m=>m.uri===c);if(l)return a.info(`[LIOP-Router] Resolved resource ${c} from cache (Peer: ${a$1.peerId})`),{jsonrpc:"2.0",id:s,result:{contents:[{uri:l.uri,mimeType:l.mimeType||"text/plain",text:l.text||l.description||"No content provided"}]}}}return {jsonrpc:"2.0",id:s,error:{code:-32e3,message:n instanceof Error?n.message:String(n)}}}}case "prompts/list":{let o=this.liopServer.listPrompts(),n=S.getInstance(),c=JSON.stringify(o);return n.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:n.countTokens(c)}),{jsonrpc:"2.0",id:s,result:{prompts:o}}}case "prompts/get":{let o=r;if(!o?.name)return {jsonrpc:"2.0",id:s,error:{code:-32602,message:"Missing prompt name"}};try{let n=Date.now(),c=await this.liopServer.getPrompt({name:o.name,arguments:o.arguments||{}}),a=S.getInstance(),l=JSON.stringify({name:o.name,arguments:o.arguments}),m=JSON.stringify(c);return a.record({type:"prompt_get",method:"prompts/get",toolName:o.name,estimatedInputTokens:a.countTokens(l),estimatedOutputTokens:a.countTokens(m),durationMs:Date.now()-n}),{jsonrpc:"2.0",id:s,result:c}}catch(n){return {jsonrpc:"2.0",id:s,error:{code:-32e3,message:n instanceof Error?n.message:String(n)}}}}default:return {jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${t}`}}}}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 t=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:s})=>t-s<ge*1e3))return}return this.currentDiscovery=(async()=>{try{let t=Array.from(this.manifestCache.values()).reduce((u,{manifest:p})=>u+p.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(d=>setTimeout(d,1e3));}let r=[],s=this.manifestCache.size===0?5:1;for(let u=0;u<s;u++){for(let h=0;h<ne;h++){r=await this.meshNode?.discoverManifestProviders()||[];let k=this.meshNode?.getPeerId();if(r.filter(I=>I!==k).length>0)break;h<ne-1&&(a.info(`[LIOP-Router] DHT discovery attempt ${h+1}/${ne}...`),await new Promise(I=>setTimeout(I,1e3)));}let p=this.meshNode.node?.getConnections().map(h=>h.remotePeer.toString())||[];p.length>0&&(r=Array.from(new Set([...r,...p])));let d=this.meshNode?.getPeerId();if(r.filter(h=>h!==d).length>0)break;u<s-1&&(a.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${u+1}/${s})...`),await new Promise(h=>setTimeout(h,1e3)));}if(r.length===0){a.info("[LIOP-Router] No manifest providers found after all attempts.");return}e||a.info(`[LIOP-Router] Discovered ${r.length} candidate manifest providers`);let o=new Set((this.meshNode.node?.getConnections?.()||[]).map(u=>u.remotePeer.toString()));r=[...r].sort((u,p)=>{let d=o.has(u)?1:0;return (o.has(p)?1:0)-d});let n=0,c=0,a$1=!1,l=this.meshNode?.getPeerId(),m=r.filter(u=>{if(!this.meshNode||u===l||this.shouldSkipManifestQuery(u))return !1;let p=this.manifestCache.get(u);return p&&Date.now()-p.cachedAt<ge*1e3?(n++,!1):!0}),f=await Promise.allSettled(m.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 f)if(u.status==="fulfilled"&&u.value?.manifest){let{peerId:p,manifest:d}=u.value;this.manifestCache.set(p,{manifest:d,cachedAt:Date.now()}),this.recordManifestQuerySuccess(p),a$1=!0,n++,a.info(`[LIOP-Router] Manifest received from ${p} (${d.tools.length} tools)`);}else u.status==="fulfilled"&&u.value?(this.recordManifestQueryFailure(u.value.peerId),c++,a.info(`[LIOP-Router] Manifest query returned NULL for ${u.value.peerId}`)):u.status==="rejected"&&(c++,a.info("[LIOP-Router] Fatal error querying manifest:",u.reason instanceof Error?u.reason.message:String(u.reason)));this._discoveryStats={candidates:r.length,success:n,failures:c,lastDiscovery:Date.now()},a$1&&Array.from(this.manifestCache.values()).reduce((p,{manifest:d})=>p+d.tools.length,0)!==t&&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 o=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),n=Number.isFinite(o)&&o>0?o:12e3,c=Date.now()+n,a$1=0,l=-1;for(;Date.now()<c&&!(this.manifestCache.size>=e||(await Promise.race([this.refreshManifestCache(true),new Promise(m=>setTimeout(m,3e3))]).catch(()=>{}),this.manifestCache.size>=e));){if(this.manifestCache.size===l){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,l=this.manifestCache.size;await new Promise(m=>setTimeout(m,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 t=[],r=new Set,s=new Set(this.liopServer.listTools().map(o=>o.name));for(let[o,{manifest:n}]of this.manifestCache.entries())for(let c of n.tools){if(c.name==="LiopMeshStatus")continue;let a=c.name;(r.has(c.name)||s.has(c.name))&&(a=`${c.name}_${o.slice(-4)}`),r.add(a);let l=n.serverInfo?.name||"Unknown Provider",m=c.description||`Remote tool from ${l}`,f={name:a,description:M()?re(m):m,inputSchema:c.inputSchema||{type:"object",properties:{}}};typeof f.inputSchema=="object"&&!f.inputSchema.type&&(f.inputSchema.type="object"),typeof f.inputSchema=="object"&&!f.inputSchema.properties&&(f.inputSchema.properties={});let u="";n.taxonomy&&(u=`
11
+ [LIOP-DOMAIN: ${n.taxonomy.domain}]`);let p=f.inputSchema.properties||{},d="";!M()&&p.payload&&(d=`
12
+ [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!M()&&f.description.includes("STRICT SCHEMA ADHERENCE")&&(f.description=f.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let g=M()?`
13
+ (Peer: ${o.slice(-8)})${u}`:`
14
+ (Origin: ${o.slice(-8)})${u}${d}`;f.description=`${f.description}${g}`,t.push(f);}return t}async getRemoteResources(){this.currentDiscovery||this.refreshManifestCache(true).catch(()=>{});let e=[],t=new Set(this.liopServer.listResources().map(r=>r.uri));for(let[r,{manifest:s}]of this.manifestCache.entries())for(let o of s.resources)if(!t.has(o.uri)){let n={...o},c=s.serverInfo?.name||"Unknown Provider",a="";s.taxonomy&&(a=`
15
+
16
+ [LIOP Zero-Trust Blueprint]
17
+ Domain: ${s.taxonomy.domain}
18
+ Clearance Tier: ${s.taxonomy.clearanceTier}`,s.taxonomy.executionTypes&&s.taxonomy.executionTypes.length>0&&(a+=`
19
+ Execution Types: ${s.taxonomy.executionTypes.join(", ")}`));let l=`
20
+
21
+ [LIOP Zero-Trust Origin]
22
+ Provider: ${c}
23
+ Network ID: ${r}${a}`;n.uri.startsWith("liop://schema/")?(n.name=`[SCHEMA] ${n.name}`,n.description=`[CRITICAL SCHEMA] ${n.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):n.description=n.description?`${n.description}${l}`:l.trim(),e.push(n),t.add(o.uri);}return e}resolveManifestTarget(e){for(let[r,{manifest:s}]of this.manifestCache.entries())if(s.tools.find(n=>n.name===e))return {peerId:r,originalToolName:e};let t=e.split("_");if(t.length>1){let r=t.pop(),s=t.join("_");for(let[o,{manifest:n}]of this.manifestCache.entries())if(o.endsWith(r||"")&&n.tools.find(a=>a.name===s))return {peerId:o,originalToolName:s}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,t){let r=t.name;if(r==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let o=this._discoveryStats||{candidates:0,success:0,failures:0},n=this.manifestCache.size,c=this.meshNode?"Active":"Offline",a=Array.from(this.manifestCache.values()).reduce((O,{manifest:E})=>O+E.tools.length,0),l=this.meshNode?this.meshNode.node?.getConnections().length:0,m=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],f=m.length,p=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",d=p?m.map(O=>{let E=O.split("/"),C=E[E.length-1];return ` \u2022 ${C?C.slice(-8):"Unknown"} (bootstrap)`}).join(`
24
+ `):"",g=this.meshNode?this.meshNode.getRoutingTableSize():0,h=this.meshNode?.getPeerId()||"Offline",k=h==="Offline"?h:this.redactPeerId(h),P=Array.from(this.manifestCache.entries()).flatMap(([O,{manifest:E}])=>E.tools.map(C=>` \u2022 ${C.name} (from origin: ${this.redactPeerId(O)})`)).join(`
25
+ `),I=[`LIOP Mesh Status: ${c==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${k}`,`Network: ${l} Conns | ${g} Mesh Nodes | ${f} Bootstraps`,p&&f>0?`
26
+ Active Bootstraps:
27
+ ${d}
28
+ `:"",`Discovery: ${o.candidates} Candidates | ${o.success} OK | ${o.failures} FAIL`,`Tooling: ${n} Providers | ${a} Total Remote Tools`,a>0?`
29
+ Discovered Remote Tools (Zero-Trust Origins):
30
+ ${P}`:`
31
+ No remote tools discovered yet.`,S.getInstance().formatStatusBlock()].filter(O=>O!=="").join(`
32
+ `),R=S.getInstance();return R.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:R.countTokens(I)}),{jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:I}]}}}let s=this.liopServer.listTools().some(o=>o.name===r);if(!s&&this.meshNode){let o=this.resolveManifestTarget(r);if(o||(await this.refreshManifestCache(),o=this.resolveManifestTarget(r)),o)return a.info(`[LIOP-Router] Resolved ${r} via manifest cache (Peer: ${o.peerId}, Original: ${o.originalToolName})`),this.routeToRemoteProvider(e,o.originalToolName,o.peerId,t);let n=[];for(let c=0;c<3&&(n=await this.meshNode.findProviders(r),!(n.length>0));c++)c<2&&await new Promise(a=>setTimeout(a,1e3));if(n.length>0)return this.routeToRemoteProvider(e,r,n[0],t)}if(s)try{let o=Date.now(),n=await this.liopServer.callTool({name:r,arguments:t.arguments||{}}),c=S.getInstance(),a=JSON.stringify(t.arguments||{}),l=JSON.stringify(n);return c.record({type:"tool_call",method:"tools/call",toolName:r,estimatedInputTokens:c.countTokens(a),estimatedOutputTokens:c.countTokens(l),durationMs:Date.now()-o}),{jsonrpc:"2.0",id:e,result:n}}catch(o){return {jsonrpc:"2.0",id:e,error:{code:-32e3,message:o instanceof Error?o.message:String(o)}}}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,t,r,s){if(!this.meshNode)return {jsonrpc:"2.0",id:e,error:{code:-32603,message:"Mesh Node inactive"}};let o=this.manifestCache.get(r),n=this.defaultRpcPort;if(o)n=o.manifest.grpcPort;else {let p=await this.meshNode.queryManifest(r);p&&(n=p.grpcPort,this.manifestCache.set(r,{manifest:p,cachedAt:Date.now()}),o=this.manifestCache.get(r));}if((process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test")&&o&&process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"){let p=o.manifest.serverInfo?.name?.toLowerCase()||"";p.includes("vault")?n=13011:p.includes("bank")?n=13021:p.includes("oracle")&&(n=13031);}let a$1=await this.meshNode.resolvePeer(r),l=null,m=await import('os'),f=Object.values(m.networkInterfaces()).flat().filter(p=>p?.family==="IPv4").map(p=>p?.address);for(let p of a$1){let d=p.split("/"),g=d.indexOf("ip4");if(g!==-1){let h=d[g+1];if(h==="127.0.0.1"||f.includes(h)){l=`127.0.0.1:${n}`;break}l||(l=`${h}:${n}`);}}l||(l=`127.0.0.1:${n}`),a.info(`[LIOP-Router] Dynamic route: ${t} -> ${l} (PeerID: ${r})`);let u=new a$2.LogicMesh(l,c());return this.performTranscoding(e,u,t,s,r)}async performTranscoding(e,t,r,s,o){let n=r,c=this.meshNode?await this.meshNode.sign(Buffer.from(n)):Buffer.from([]),a=Date.now();return new Promise(l=>{t.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:n,proof_of_intent:c},async(m,f)=>{if(m||!f.accepted)return l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`PQC Handshake Failed: ${m?.message||"Rejected"}`}],isError:true}});let{ciphertext:u,sharedSecret:p}=await a$3.encapsulateAsymmetric(f.kyber_public_key),d=JSON.stringify(s.arguments||{}),g=`return { "__liop_proxy_tool": "${r}", "__liop_proxy_args": ${d} };`,h=G.randomBytes(12),k=this.encryptWithNonce(Buffer.from(g),p,h),P=t.executeLogic({session_token:f.session_token,wasm_binary:new Uint8Array(k),inputs:{},pqc_ciphertext:u,aes_nonce:h}),I="",R=null;P.on("data",O=>{I+=O.semantic_evidence,R=O;}),P.on("end",async()=>{try{if(R&&!await this.verifier.verifyZkReceipt(Buffer.from(g),Buffer.from(R.cryptographic_proof).toString("hex"),Buffer.from(R.zk_receipt)))return l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}});let O=JSON.parse(I),E=S.getInstance();E.record({type:"tool_call",method:"tools/call",toolName:r,peerId:o,estimatedInputTokens:E.countTokens(d),estimatedOutputTokens:E.countTokens(I),durationMs:Date.now()-a}),l({jsonrpc:"2.0",id:e,result:O});}catch{l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:I}]}});}}),P.on("error",O=>l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`LIOP gRPC Error: ${O.message}`}],isError:true}}));});})}encryptWithNonce(e,t,r){let s=G.createCipheriv("aes-256-gcm",t,r),o=Buffer.concat([s.update(e),s.final()]);return Buffer.concat([o,s.getAuthTag()])}};export{H as a,B as b,le as c,ue as d,z as e,S as f,Te as g};//# sourceMappingURL=chunk-CTB5O4PB.js.map
33
+ //# sourceMappingURL=chunk-CTB5O4PB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/economy/estimator.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/version.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/internal/semver.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/internal/global-utils.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/diag/types.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/api/diag.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/metrics/NoopMeter.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/metrics/NoopMeterProvider.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/api/metrics.ts","../../../node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/src/metrics-api.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","VERSION","re","_makeCompatibilityCheck","ownVersion","acceptedVersions","rejectedVersions","myVersionMatch","ownVersionParsed","globalVersion","_reject","v","_accept","globalVersionMatch","globalVersionParsed","isCompatible","major","GLOBAL_OPENTELEMETRY_API_KEY","_global","registerGlobal","type","instance","diag","allowOverride","api","_a","err","getGlobal","_b","unregisterGlobal","DiagComponentLogger","props","args","logProxy","funcName","namespace","logger","DiagLogLevel","createLogLevelDiagLogger","maxLevel","_filterFunc","theLevel","theFunc","API_NAME","DiagAPI","_DiagAPI","_logProxy","self","setLogger","optionsOrLogLevel","oldLogger","newLogger","stack","_c","options","NoopMeter","_name","_options","NOOP_GAUGE_METRIC","NOOP_HISTOGRAM_METRIC","NOOP_COUNTER_METRIC","NOOP_UP_DOWN_COUNTER_METRIC","NOOP_OBSERVABLE_GAUGE_METRIC","NOOP_OBSERVABLE_COUNTER_METRIC","NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC","_callback","_observables","NoopMetric","NoopCounterMetric","_value","_attributes","NoopUpDownCounterMetric","NoopGaugeMetric","NoopHistogramMetric","NoopObservableMetric","NoopObservableCounterMetric","NoopObservableGaugeMetric","NoopObservableUpDownCounterMetric","NOOP_METER","NoopMeterProvider","_version","NOOP_METER_PROVIDER","MetricsAPI","_MetricsAPI","provider","name","version","metrics","METER_NAME","METER_VERSION","TOKEN_USAGE_BUCKETS","DURATION_BUCKETS","LiopOTelBridge","meter","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","data","idx","prefix","outputPart","toolReport","toolEntries","toolLines","durationPart","timedOps","avgLatency","otelStatus","ms","seconds","minutes","remainingSeconds","hours","remainingMinutes","mcpCompactToolDescriptions","stripVerboseLiopToolDescription","description","d","markers","m","i","MANIFEST_CACHE_TTL_S","MANIFEST_DISCOVERY_RETRIES","LiopMcpRouter","_LiopMcpRouter","liopServer","meshNode","defaultRpcPort","remoteTools","t","resources","r","LiopVerifier","peerId","state","now","failures","backoff","request","method","params","id","localTools","listedLocals","allTools","telemetry","toolsPayload","toolsResponsePayload","localResources","remoteResources","allResources","rlTelemetry","rlPayload","typedParams","rrStartTime","result","rrTelemetry","rrOutputPayload","targetUri","manifest","remoteResource","promptsList","plTelemetry","plPayload","pgStartTime","pgTelemetry","pgInputPayload","pgOutputPayload","silent","cachedAt","prevCount","acc","providerIds","MAX_COLD_ATTEMPTS","coldAttempt","attempt","selfId","activePeers","c","selfIdEnd","connectedPeers","a","b","aConnected","successCount","errorCount","cacheUpdated","eligiblePeers","cached","queryResults","EXPECTED_PROVIDERS","initialTimeoutMs","boundedTimeoutMs","deadline","stableCount","lastCacheSize","resolve","tools","seenNames","localToolNames","tool","finalName","providerName","baseDesc","cleanTool","blueprint","properties","envelopeDoc","originStamp","seenUris","resource","augmentedResource","parts","suffix","baseName","stats","providerCount","meshState","cachedTools","connections","bootstrapNodes","bootstrapCount","showBootstraps","bootstrapList","addr","routingTableSize","rawPeerId","localPeerId","cachedToolList","statusText","line","diagTelemetry","isLocal","target","providers","localStartTime","localTelemetry","localInputPayload","localOutputPayload","manifestEntry","grpcPort","addrs","targetAddr","os","localInterfaces","ipIdx","advertisedIp","remoteClient","liopV1","createChannelCredentials","client","capabilityHash","proofOfIntent","transcodingStartTime","response","ciphertext","sharedSecret","Kyber768Wrapper","embeddedArgsJson","proxyLogic","nonce","sealedLogic","call","resultBody","lastResponse","grpcRes","parsedResult","remoteTelemetry","e","payload","cipher","encrypted"],"mappings":"gMA0BO,IAAMA,CAAAA,CAAN,KAAmD,CAChD,IAAA,CAAO,YAAA,CAER,QAER,WAAA,CACCC,CAAAA,CACAC,CAAAA,CACC,CACD,IAAA,CAAK,OAAA,CAAUD,EAEXC,CAAAA,EACHA,CAAAA,CAAoB,GAAM,EAE5B,CAEA,WAAA,CAAYC,CAAAA,CAAsB,CACjC,OAAIA,CAAAA,CAAK,MAAA,GAAW,CAAA,CAAU,CAAA,CACvB,IAAA,CAAK,QAAQA,CAAI,CACzB,CACD,CAAA,CAQaC,CAAAA,CAAN,KAAwD,CACrD,IAAA,CAAO,qBAAA,CAEhB,WAAA,CAAYD,CAAAA,CAAsB,CACjC,OAAIA,EAAK,MAAA,GAAW,CAAA,CAAU,CAAA,CACvB,IAAA,CAAK,IAAA,CAAKA,CAAAA,CAAK,MAAA,CAAS,CAAC,CACjC,CACD,EASA,eAAsBE,EAAAA,EAAgD,CACrE,GAAI,CACH,IAAMC,CAAAA,CAAM,MAAM,OAAO,eAAe,EAClCC,CAAAA,CAAY,IAAIP,CAAAA,CACrBM,CAAAA,CAAI,WAAA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,MAAA,CAAO,MAAA,CAAO,CAACC,CAAAA,CAAWD,EAAO,UAAA,EAAY,CAAC,CACtD,CACD","file":"chunk-CTB5O4PB.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","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.1';\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set<string>([ownVersion]);\n const rejectedVersions = new Set<string>();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { MeterProvider } from '../metrics/MeterProvider';\nimport type { ContextManager } from '../context/types';\nimport type { DiagLogger } from '../diag/types';\nimport type { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\ndeclare const self: unknown;\ndeclare const window: unknown;\ndeclare const global: unknown;\n\nconst _global = (\n typeof globalThis === 'object'\n ? globalThis\n : typeof self === 'object'\n ? self\n : typeof window === 'object'\n ? window\n : typeof global === 'object'\n ? global\n : {}\n) as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport type { ComponentLoggerOptions, DiagLogger } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: unknown[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: unknown[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: unknown[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: unknown[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: unknown[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: unknown[]\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n return logger[funcName](namespace, ...args);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @since 1.0.0\n */\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n *\n * @since 1.0.0\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n *\n * @since 1.0.0\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\n/**\n * @since 1.4.1\n */\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DiagLogFunction, DiagLogger } from '../types';\nimport { DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport type {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n} from '../diag/types';\nimport { DiagLogLevel } from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n *\n * @since 1.0.0\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '<failed to generate stacktrace>';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Meter } from './Meter';\nimport type {\n BatchObservableCallback,\n Counter,\n Gauge,\n Histogram,\n MetricAttributes,\n MetricOptions,\n Observable,\n ObservableCallback,\n ObservableCounter,\n ObservableGauge,\n ObservableUpDownCounter,\n UpDownCounter,\n} from './Metric';\n\n/**\n * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses\n * constant NoopMetrics for all of its methods.\n */\nexport class NoopMeter implements Meter {\n constructor() {}\n\n /**\n * @see {@link Meter.createGauge}\n */\n createGauge(_name: string, _options?: MetricOptions): Gauge {\n return NOOP_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createHistogram}\n */\n createHistogram(_name: string, _options?: MetricOptions): Histogram {\n return NOOP_HISTOGRAM_METRIC;\n }\n\n /**\n * @see {@link Meter.createCounter}\n */\n createCounter(_name: string, _options?: MetricOptions): Counter {\n return NOOP_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createUpDownCounter}\n */\n createUpDownCounter(_name: string, _options?: MetricOptions): UpDownCounter {\n return NOOP_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableGauge}\n */\n createObservableGauge(\n _name: string,\n _options?: MetricOptions\n ): ObservableGauge {\n return NOOP_OBSERVABLE_GAUGE_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableCounter}\n */\n createObservableCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableCounter {\n return NOOP_OBSERVABLE_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.createObservableUpDownCounter}\n */\n createObservableUpDownCounter(\n _name: string,\n _options?: MetricOptions\n ): ObservableUpDownCounter {\n return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;\n }\n\n /**\n * @see {@link Meter.addBatchObservableCallback}\n */\n addBatchObservableCallback(\n _callback: BatchObservableCallback,\n _observables: Observable[]\n ): void {}\n\n /**\n * @see {@link Meter.removeBatchObservableCallback}\n */\n removeBatchObservableCallback(_callback: BatchObservableCallback): void {}\n}\n\nexport class NoopMetric {}\n\nexport class NoopCounterMetric extends NoopMetric implements Counter {\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopUpDownCounterMetric\n extends NoopMetric\n implements UpDownCounter\n{\n add(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopGaugeMetric extends NoopMetric implements Gauge {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopHistogramMetric extends NoopMetric implements Histogram {\n record(_value: number, _attributes: MetricAttributes): void {}\n}\n\nexport class NoopObservableMetric {\n addCallback(_callback: ObservableCallback) {}\n\n removeCallback(_callback: ObservableCallback) {}\n}\n\nexport class NoopObservableCounterMetric\n extends NoopObservableMetric\n implements ObservableCounter {}\n\nexport class NoopObservableGaugeMetric\n extends NoopObservableMetric\n implements ObservableGauge {}\n\nexport class NoopObservableUpDownCounterMetric\n extends NoopObservableMetric\n implements ObservableUpDownCounter {}\n\nexport const NOOP_METER = new NoopMeter();\n\n// Synchronous instruments\nexport const NOOP_COUNTER_METRIC = new NoopCounterMetric();\nexport const NOOP_GAUGE_METRIC = new NoopGaugeMetric();\nexport const NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric();\nexport const NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric();\n\n// Asynchronous instruments\nexport const NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric();\nexport const NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric();\nexport const NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC =\n new NoopObservableUpDownCounterMetric();\n\n/**\n * Create a no-op Meter\n *\n * @since 1.3.0\n */\nexport function createNoopMeter(): Meter {\n return NOOP_METER;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Meter, MeterOptions } from './Meter';\nimport type { MeterProvider } from './MeterProvider';\nimport { NOOP_METER } from './NoopMeter';\n\n/**\n * An implementation of the {@link MeterProvider} which returns an impotent Meter\n * for all calls to `getMeter`\n */\nexport class NoopMeterProvider implements MeterProvider {\n getMeter(_name: string, _version?: string, _options?: MeterOptions): Meter {\n return NOOP_METER;\n }\n}\n\nexport const NOOP_METER_PROVIDER = new NoopMeterProvider();\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { Meter, MeterOptions } from '../metrics/Meter';\nimport type { MeterProvider } from '../metrics/MeterProvider';\nimport { NOOP_METER_PROVIDER } from '../metrics/NoopMeterProvider';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'metrics';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Metrics API\n */\nexport class MetricsAPI {\n private static _instance?: MetricsAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Metrics API */\n public static getInstance(): MetricsAPI {\n if (!this._instance) {\n this._instance = new MetricsAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current global meter provider.\n * Returns true if the meter provider was successfully registered, else false.\n */\n public setGlobalMeterProvider(provider: MeterProvider): boolean {\n return registerGlobal(API_NAME, provider, DiagAPI.instance());\n }\n\n /**\n * Returns the global meter provider.\n */\n public getMeterProvider(): MeterProvider {\n return getGlobal(API_NAME) || NOOP_METER_PROVIDER;\n }\n\n /**\n * Returns a meter from the global meter provider.\n */\n public getMeter(\n name: string,\n version?: string,\n options?: MeterOptions\n ): Meter {\n return this.getMeterProvider().getMeter(name, version, options);\n }\n\n /** Remove the global meter provider */\n public disable(): void {\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { MetricsAPI } from './api/metrics';\n/**\n * Entrypoint for metrics API\n *\n * @since 1.3.0\n */\nexport const metrics = MetricsAPI.getInstance();\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 { LiopVerifier } from \"../crypto/verifier.js\";\nimport { TokenTelemetryEngine } from \"../economy/telemetry.js\";\nimport type { LiopManifest, MeshNode } from \"../mesh/index.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport { liopV1 } from \"../rpc/proto.js\";\nimport { createChannelCredentials } from \"../rpc/tls.js\";\nimport type { IntentResponse, LogicResponse } from \"../rpc/types.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport type { McpRequest, McpResponse } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\nimport {\n\tmcpCompactToolDescriptions,\n\tstripVerboseLiopToolDescription,\n} from \"../utils/mcpCompact.js\";\n\n/**\n * Time-to-live for cached manifests (seconds).\n * Aligned with libp2p Kademlia DHT TABLE_REFRESH_INTERVAL (5 minutes).\n * Provider records in the DHT are valid for 48 hours (PROVIDERS_VALIDITY),\n * so 300s is a conservative, network-friendly value.\n */\nconst MANIFEST_CACHE_TTL_S = 300;\n\n/** Maximum number of DHT query retries for manifest discovery */\nconst MANIFEST_DISCOVERY_RETRIES = 5;\n\n/**\n * LIOP MCP Router\n *\n * Core logic for routing MCP requests to local or remote LIOP providers.\n * Decoupled from transport (HTTP/Stdio).\n *\n * All tool discovery and port resolution is DYNAMIC via the\n * /liop/manifest/1.0.0 protocol stream over Kademlia DHT.\n */\nexport class LiopMcpRouter {\n\t/** Cached manifests from remote peers. Key = PeerID */\n\tprivate manifestCache: Map<\n\t\tstring,\n\t\t{ manifest: LiopManifest; cachedAt: number }\n\t> = new Map();\n\n\t/** Guards against concurrent discovery storms */\n\tprivate currentDiscovery: Promise<void> | null = null;\n\n\t/** Verifier for Tier-0 integrity checks */\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\n\t/** Callback when new remote tools are discovered */\n\tpublic onToolsChanged?: () => void;\n\n\t/** Circuit-breaker state for peers that repeatedly fail manifest queries. */\n\tprivate manifestFailureState: Map<\n\t\tstring,\n\t\t{ failures: number; cooldownUntil: number; lastSkipLogAt: number }\n\t> = new Map();\n\n\tprivate static readonly MANIFEST_FAILURE_BASE_COOLDOWN_MS = 15_000;\n\tprivate static readonly MANIFEST_FAILURE_MAX_COOLDOWN_MS = 5 * 60_000;\n\tprivate static readonly MANIFEST_SKIP_LOG_THROTTLE_MS = 30_000;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\tprivate defaultRpcPort = 50051,\n\t) {\n\t\t// Auto-register manifest handler if mesh node is provided\n\t\tif (this.meshNode) {\n\t\t\tthis.meshNode.registerManifestHandler(() => {\n\t\t\t\tconst remoteTools = this.liopServer.listTools().map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinputSchema: t.inputSchema as Record<string, unknown>,\n\t\t\t\t}));\n\n\t\t\t\tconst resources = this.liopServer.listResources().map((r) => ({\n\t\t\t\t\tname: r.name,\n\t\t\t\t\turi: r.uri,\n\t\t\t\t\tdescription: r.description,\n\t\t\t\t\tmimeType: r.mimeType,\n\t\t\t\t}));\n\n\t\t\t\treturn {\n\t\t\t\t\tpeerId: this.meshNode?.getPeerId() || \"unknown\",\n\t\t\t\t\tgrpcPort: this.defaultRpcPort,\n\t\t\t\t\ttools: [...remoteTools],\n\t\t\t\t\tresources,\n\t\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\t// Proactively announce manifest capability to the mesh\n\t\t\tthis.meshNode.announceManifest().catch((err: unknown) => {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Failed to announce manifest: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\n\t\t// [OWASP-A01] Startup warning when diagnostic level exposes full topology\n\t\tif (process.env.LIOP_DIAGNOSTIC_LEVEL === \"full\") {\n\t\t\tprocess.stderr.write(\n\t\t\t\t\"⚠️ [LIOP-Security] Diagnostic level set to FULL — \" +\n\t\t\t\t\t\"PeerIDs and network topology are exposed. Do NOT use in production.\\n\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate shouldSkipManifestQuery(peerId: string): boolean {\n\t\tconst state = this.manifestFailureState.get(peerId);\n\t\tif (!state) return false;\n\t\tconst now = Date.now();\n\t\tif (now >= state.cooldownUntil) return false;\n\n\t\tif (\n\t\t\tnow - state.lastSkipLogAt >\n\t\t\tLiopMcpRouter.MANIFEST_SKIP_LOG_THROTTLE_MS\n\t\t) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Router] Skipping manifest query for ${peerId} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1000)}s remaining)`,\n\t\t\t);\n\t\t\tstate.lastSkipLogAt = now;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate recordManifestQuerySuccess(peerId: string): void {\n\t\tthis.manifestFailureState.delete(peerId);\n\t}\n\n\tprivate recordManifestQueryFailure(peerId: string): void {\n\t\tconst now = Date.now();\n\t\tconst prev = this.manifestFailureState.get(peerId);\n\t\tconst failures = (prev?.failures || 0) + 1;\n\t\tconst backoff = Math.min(\n\t\t\tLiopMcpRouter.MANIFEST_FAILURE_BASE_COOLDOWN_MS *\n\t\t\t\t2 ** Math.max(0, failures - 1),\n\t\t\tLiopMcpRouter.MANIFEST_FAILURE_MAX_COOLDOWN_MS,\n\t\t);\n\t\tthis.manifestFailureState.set(peerId, {\n\t\t\tfailures,\n\t\t\tcooldownUntil: now + backoff,\n\t\t\tlastSkipLogAt: 0,\n\t\t});\n\t}\n\n\tpublic async dispatch(request: McpRequest): Promise<McpResponse | null> {\n\t\tconst { method, params, id } = request;\n\t\tlog.info(`[LIOP-Router] Processing: ${method}`);\n\n\t\tswitch (method) {\n\t\t\tcase \"initialize\":\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\t\t\tcapabilities: {\n\t\t\t\t\t\t\ttools: { listChanged: true },\n\t\t\t\t\t\t\tresources: { listChanged: true },\n\t\t\t\t\t\t\tprompts: { listChanged: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\tcase \"notifications/initialized\":\n\t\t\t\t// Cloud MCP clients often fire tools/list immediately; kick discovery early\n\t\t\t\t// so manifests populate before (or right after) that call completes.\n\t\t\t\tthis.kickDiscoveryAfterInitialized().catch(() => {});\n\t\t\t\treturn null;\n\t\t\tcase \"notifications/cancelled\":\n\t\t\t\treturn null; // No-op for MCP spec compliance\n\t\t\tcase \"ping\":\n\t\t\t\treturn { jsonrpc: \"2.0\", id, result: {} };\n\t\t\tcase \"tools/list\": {\n\t\t\t\tconst localTools = this.liopServer.listTools();\n\t\t\t\tconst remoteTools = await this.getRemoteTools();\n\n\t\t\t\tconst listedLocals = mcpCompactToolDescriptions()\n\t\t\t\t\t? localTools.map((t) => ({\n\t\t\t\t\t\t\t...t,\n\t\t\t\t\t\t\tdescription: stripVerboseLiopToolDescription(t.description ?? \"\"),\n\t\t\t\t\t\t}))\n\t\t\t\t\t: localTools;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] tools/list: ${localTools.length} local, ${remoteTools.length} remote tools found`,\n\t\t\t\t);\n\n\t\t\t\t// Inject a mandatory static diagnostic tool.\n\t\t\t\t// This ensures that the {tools: []} list is never empty on startup.\n\t\t\t\t// Claude Desktop silently hides the connector if it receives an empty array initially,\n\t\t\t\t// which broke the UX due to the ~3s warm-up time of the Kademlia DHT.\n\t\t\t\tconst diagnosticTool = {\n\t\t\t\t\tname: \"LiopMeshStatus\",\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.\",\n\t\t\t\t\tinputSchema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\t\t\tconst allTools = [diagnosticTool, ...listedLocals, ...remoteTools];\n\n\t\t\t\t// [Token Economy] Record telemetry for the tools/list response\n\t\t\t\tconst telemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst toolsPayload = JSON.stringify(allTools);\n\t\t\t\tconst toolsResponsePayload = JSON.stringify({ tools: allTools });\n\t\t\t\ttelemetry.record({\n\t\t\t\t\ttype: \"tools_list\",\n\t\t\t\t\tmethod: \"tools/list\",\n\t\t\t\t\testimatedInputTokens: telemetry.countTokens(toolsPayload),\n\t\t\t\t\testimatedOutputTokens: telemetry.countTokens(toolsResponsePayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\ttools: allTools,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"tools/call\":\n\t\t\t\treturn this.transcodeMcpToLiop(id, params as Record<string, unknown>);\n\t\t\tcase \"resources/list\": {\n\t\t\t\tconst localResources = this.liopServer.listResources();\n\t\t\t\tconst remoteResources = await this.getRemoteResources();\n\t\t\t\tconst allResources = [...localResources, ...remoteResources];\n\n\t\t\t\t// [Token Economy] Record resources/list telemetry\n\t\t\t\tconst rlTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst rlPayload = JSON.stringify(allResources);\n\t\t\t\trlTelemetry.record({\n\t\t\t\t\ttype: \"resource_list\",\n\t\t\t\t\tmethod: \"resources/list\",\n\t\t\t\t\testimatedInputTokens: 0,\n\t\t\t\t\testimatedOutputTokens: rlTelemetry.countTokens(rlPayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: { resources: allResources },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"resources/read\": {\n\t\t\t\tconst typedParams = params as { uri?: string } | undefined;\n\t\t\t\tif (!typedParams?.uri)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: { code: -32602, message: \"Missing resource uri\" },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst rrStartTime = Date.now();\n\t\t\t\t\tconst result = await this.liopServer.readResource(typedParams.uri);\n\n\t\t\t\t\t// [Token Economy] Record resources/read telemetry\n\t\t\t\t\tconst rrTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\tconst rrOutputPayload = JSON.stringify(result);\n\t\t\t\t\trrTelemetry.record({\n\t\t\t\t\t\ttype: \"resource_read\",\n\t\t\t\t\t\tmethod: \"resources/read\",\n\t\t\t\t\t\ttoolName: typedParams.uri,\n\t\t\t\t\t\testimatedInputTokens: rrTelemetry.countTokens(typedParams.uri),\n\t\t\t\t\t\testimatedOutputTokens: rrTelemetry.countTokens(rrOutputPayload),\n\t\t\t\t\t\tdurationMs: Date.now() - rrStartTime,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\t// Fallback: Resolve remotely from manifest cache\n\t\t\t\t\tconst targetUri = typedParams.uri;\n\t\t\t\t\tfor (const { manifest } of this.manifestCache.values()) {\n\t\t\t\t\t\tconst remoteResource = manifest.resources.find(\n\t\t\t\t\t\t\t(r) => r.uri === targetUri,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (remoteResource) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] Resolved resource ${targetUri} from cache (Peer: ${manifest.peerId})`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\tcontents: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\turi: remoteResource.uri,\n\t\t\t\t\t\t\t\t\t\t\tmimeType: remoteResource.mimeType || \"text/plain\",\n\t\t\t\t\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\t\t\t\t\tremoteResource.text ||\n\t\t\t\t\t\t\t\t\t\t\t\tremoteResource.description ||\n\t\t\t\t\t\t\t\t\t\t\t\t\"No content provided\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase \"prompts/list\": {\n\t\t\t\tconst promptsList = this.liopServer.listPrompts();\n\n\t\t\t\t// [Token Economy] Record prompts/list telemetry\n\t\t\t\tconst plTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst plPayload = JSON.stringify(promptsList);\n\t\t\t\tplTelemetry.record({\n\t\t\t\t\ttype: \"prompt_list\",\n\t\t\t\t\tmethod: \"prompts/list\",\n\t\t\t\t\testimatedInputTokens: 0,\n\t\t\t\t\testimatedOutputTokens: plTelemetry.countTokens(plPayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: { prompts: promptsList },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"prompts/get\": {\n\t\t\t\tconst typedParams = params as\n\t\t\t\t\t| { name?: string; arguments?: Record<string, string> }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (!typedParams?.name)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: { code: -32602, message: \"Missing prompt name\" },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst pgStartTime = Date.now();\n\t\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\t\tname: typedParams.name as string,\n\t\t\t\t\t\targuments: typedParams.arguments || {},\n\t\t\t\t\t});\n\n\t\t\t\t\t// [Token Economy] Record prompts/get telemetry\n\t\t\t\t\tconst pgTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\tconst pgInputPayload = JSON.stringify({\n\t\t\t\t\t\tname: typedParams.name,\n\t\t\t\t\t\targuments: typedParams.arguments,\n\t\t\t\t\t});\n\t\t\t\t\tconst pgOutputPayload = JSON.stringify(result);\n\t\t\t\t\tpgTelemetry.record({\n\t\t\t\t\t\ttype: \"prompt_get\",\n\t\t\t\t\t\tmethod: \"prompts/get\",\n\t\t\t\t\t\ttoolName: typedParams.name,\n\t\t\t\t\t\testimatedInputTokens: pgTelemetry.countTokens(pgInputPayload),\n\t\t\t\t\t\testimatedOutputTokens: pgTelemetry.countTokens(pgOutputPayload),\n\t\t\t\t\t\tdurationMs: Date.now() - pgStartTime,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\terror: { code: -32601, message: `Method not found: ${method}` },\n\t\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * MCP clients often send notifications/initialized then immediately tools/list.\n\t * Start manifest discovery without blocking the notification handler.\n\t */\n\tprivate kickDiscoveryAfterInitialized(): Promise<void> {\n\t\treturn (async () => {\n\t\t\tawait new Promise((r) => setTimeout(r, 250));\n\t\t\tawait Promise.race([\n\t\t\t\tthis.refreshManifestCache(true),\n\t\t\t\tnew Promise<void>((r) => setTimeout(r, 15_000)),\n\t\t\t]).catch(() => {});\n\t\t})();\n\t}\n\n\t/**\n\t * Discovers and caches manifests from all remote LIOP providers in the mesh.\n\t * Uses Kademlia DHT to find \"liop:manifest\" providers, then opens\n\t * /liop/manifest/1.0.0 protocol streams to retrieve their full metadata.\n\t */\n\tpublic async refreshManifestCache(silent = false): Promise<void> {\n\t\tif (!this.meshNode) return;\n\t\tif (this.currentDiscovery) return this.currentDiscovery;\n\n\t\t// Fast-path: Skip DHT query entirely when cache is fresh and populated.\n\t\t// Only background polls (silent=true) should bypass this to detect new nodes.\n\t\t// Foreground requests (tools/list, tools/call) can safely reuse valid cache.\n\t\tif (!silent && this.manifestCache.size > 0) {\n\t\t\tconst now = Date.now();\n\t\t\tconst allFresh = Array.from(this.manifestCache.values()).every(\n\t\t\t\t({ cachedAt }) => now - cachedAt < MANIFEST_CACHE_TTL_S * 1000,\n\t\t\t);\n\t\t\tif (allFresh) return;\n\t\t}\n\n\t\tthis.currentDiscovery = (async () => {\n\t\t\ttry {\n\t\t\t\tconst prevCount = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t\t0,\n\t\t\t\t);\n\n\t\t\t\t// Phase 0: Wait for at least one active connection if mesh is empty (Cold Start)\n\t\t\t\tif (this.manifestCache.size === 0) {\n\t\t\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\t\t\tconst connections =\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal nodes for connection count\n\t\t\t\t\t\t\t(this.meshNode as any).node?.getConnections().length || 0;\n\t\t\t\t\t\tif (connections > 0) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] P2P Connection established. Starting discovery...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Waiting for P2P connections (attempt ${i + 1}/10)...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Phase 1: Try DHT discovery + Fallback loop\n\t\t\t\tlet providerIds: string[] = [];\n\t\t\t\tconst MAX_COLD_ATTEMPTS = this.manifestCache.size === 0 ? 5 : 1;\n\n\t\t\t\tfor (\n\t\t\t\t\tlet coldAttempt = 0;\n\t\t\t\t\tcoldAttempt < MAX_COLD_ATTEMPTS;\n\t\t\t\t\tcoldAttempt++\n\t\t\t\t) {\n\t\t\t\t\t// 1.1 Try DHT discovery\n\t\t\t\t\tfor (\n\t\t\t\t\t\tlet attempt = 0;\n\t\t\t\t\t\tattempt < MANIFEST_DISCOVERY_RETRIES;\n\t\t\t\t\t\tattempt++\n\t\t\t\t\t) {\n\t\t\t\t\t\tproviderIds =\n\t\t\t\t\t\t\t(await this.meshNode?.discoverManifestProviders()) || [];\n\t\t\t\t\t\tconst selfId = this.meshNode?.getPeerId();\n\t\t\t\t\t\tconst remoteIds = providerIds.filter((id) => id !== selfId);\n\t\t\t\t\t\tif (remoteIds.length > 0) break;\n\t\t\t\t\t\tif (attempt < MANIFEST_DISCOVERY_RETRIES - 1) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] DHT discovery attempt ${attempt + 1}/${MANIFEST_DISCOVERY_RETRIES}...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// 1.2 Aggressively merge all active connections to bypass DHT propagation delays\n\t\t\t\t\tconst activePeers =\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t\t(this.meshNode as any).node\n\t\t\t\t\t\t\t?.getConnections()\n\t\t\t\t\t\t\t.map((c: { remotePeer: { toString: () => string } }) =>\n\t\t\t\t\t\t\t\tc.remotePeer.toString(),\n\t\t\t\t\t\t\t) || [];\n\n\t\t\t\t\tif (activePeers.length > 0) {\n\t\t\t\t\t\tproviderIds = Array.from(new Set([...providerIds, ...activePeers]));\n\t\t\t\t\t}\n\n\t\t\t\t\tconst selfIdEnd = this.meshNode?.getPeerId();\n\t\t\t\t\tconst remoteIdsEnd = providerIds.filter((id) => id !== selfIdEnd);\n\t\t\t\t\tif (remoteIdsEnd.length > 0) break;\n\n\t\t\t\t\tif (coldAttempt < MAX_COLD_ATTEMPTS - 1) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${coldAttempt + 1}/${MAX_COLD_ATTEMPTS})...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (providerIds.length === 0) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Router] No manifest providers found after all attempts.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!silent) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Router] Discovered ${providerIds.length} candidate manifest providers`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Prioritize already-connected peers to avoid blocking on stale providers.\n\t\t\t\t// This improves first tools/list latency on Linux/Ubuntu while preserving\n\t\t\t\t// full discovery for slower peers in subsequent refresh cycles.\n\t\t\t\tconst connectedPeers = new Set<string>(\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: internal node access for fast peer ordering\n\t\t\t\t\t((this.meshNode as any).node?.getConnections?.() || []).map(\n\t\t\t\t\t\t(c: { remotePeer: { toString: () => string } }) =>\n\t\t\t\t\t\t\tc.remotePeer.toString(),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tproviderIds = [...providerIds].sort((a, b) => {\n\t\t\t\t\tconst aConnected = connectedPeers.has(a) ? 1 : 0;\n\t\t\t\t\tconst bConnected = connectedPeers.has(b) ? 1 : 0;\n\t\t\t\t\treturn bConnected - aConnected;\n\t\t\t\t});\n\n\t\t\t\tlet successCount = 0;\n\t\t\t\tlet errorCount = 0;\n\t\t\t\tlet cacheUpdated = false;\n\n\t\t\t\t// Filter peers eligible for querying\n\t\t\t\tconst selfId = this.meshNode?.getPeerId();\n\t\t\t\tconst eligiblePeers = providerIds.filter((peerId) => {\n\t\t\t\t\tif (!this.meshNode) return false;\n\t\t\t\t\tif (peerId === selfId) return false;\n\t\t\t\t\tif (this.shouldSkipManifestQuery(peerId)) return false;\n\t\t\t\t\tconst cached = this.manifestCache.get(peerId);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcached &&\n\t\t\t\t\t\tDate.now() - cached.cachedAt < MANIFEST_CACHE_TTL_S * 1000\n\t\t\t\t\t) {\n\t\t\t\t\t\tsuccessCount++;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\t// Parallel manifest queries — eliminates sequential 100ms + retry delays\n\t\t\t\tconst queryResults = await Promise.allSettled(\n\t\t\t\t\teligiblePeers.map(async (peerId) => {\n\t\t\t\t\t\tif (!this.meshNode) return null;\n\t\t\t\t\t\tlog.info(`[LIOP-Router] Querying manifest from: ${peerId}`);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\tmanifest: await this.meshNode.queryManifest(peerId),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\tfor (const result of queryResults) {\n\t\t\t\t\tif (result.status === \"fulfilled\" && result.value?.manifest) {\n\t\t\t\t\t\tconst { peerId, manifest } = result.value;\n\t\t\t\t\t\tthis.manifestCache.set(peerId, {\n\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\tcachedAt: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.recordManifestQuerySuccess(peerId);\n\t\t\t\t\t\tcacheUpdated = true;\n\t\t\t\t\t\tsuccessCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (result.status === \"fulfilled\" && result.value) {\n\t\t\t\t\t\tthis.recordManifestQueryFailure(result.value.peerId);\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Manifest query returned NULL for ${result.value.peerId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (result.status === \"rejected\") {\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Fatal error querying manifest:`,\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason.message\n\t\t\t\t\t\t\t\t: String(result.reason),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Store discovery stats for LiopMeshStatus diagnostics\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: private stats for telemetry\n\t\t\t\t(this as any)._discoveryStats = {\n\t\t\t\t\tcandidates: providerIds.length,\n\t\t\t\t\tsuccess: successCount,\n\t\t\t\t\tfailures: errorCount,\n\t\t\t\t\tlastDiscovery: Date.now(),\n\t\t\t\t};\n\n\t\t\t\tif (cacheUpdated) {\n\t\t\t\t\tconst newCount = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t\t\t0,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (newCount !== prevCount && this.onToolsChanged) {\n\t\t\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t\t\t\"[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\\n\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.onToolsChanged();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis.currentDiscovery = null;\n\t\t\t}\n\t\t})();\n\n\t\treturn this.currentDiscovery;\n\t}\n\n\t/**\n\t * Returns the current manifest cache size for external telemetry.\n\t * Used by the adaptive polling system to detect topology stabilization.\n\t */\n\tpublic getCacheSize(): number {\n\t\treturn this.manifestCache.size;\n\t}\n\n\t/**\n\t * Returns all remote tools discovered via the manifest protocol.\n\t */\n\tprivate async getRemoteTools(): Promise<\n\t\tArray<{\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tinputSchema?: Record<string, unknown>;\n\t\t}>\n\t> {\n\t\tconst EXPECTED_PROVIDERS = Number.parseInt(\n\t\t\tprocess.env.LIOP_EXPECTED_PROVIDERS ?? \"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\t// biome-ignore lint/suspicious/noExplicitAny: MCP JSON-RPC params/id are polymorphic\n\tprivate async transcodeMcpToLiop(id: any, params: any): Promise<any> {\n\t\tconst toolName = params.name;\n\n\t\t// Intercept the static diagnostic tool\n\t\tif (toolName === \"LiopMeshStatus\") {\n\t\t\t// [INDUSTRIAL-FIX] Proactive warm-up: request a refresh when status is called.\n\t\t\t// This ensures that even if the DHT was cold, the next status call (or tools/list)\n\t\t\t// will have data.\n\t\t\tthis.refreshManifestCache(true).catch(() => {});\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: private stats for telemetry\n\t\t\tconst stats = (this as any)._discoveryStats || {\n\t\t\t\tcandidates: 0,\n\t\t\t\tsuccess: 0,\n\t\t\t\tfailures: 0,\n\t\t\t};\n\t\t\tconst providerCount = this.manifestCache.size;\n\t\t\tconst meshState = this.meshNode ? \"Active\" : \"Offline\";\n\t\t\tconst cachedTools = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tconst connections = this.meshNode\n\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t(this.meshNode as any).node?.getConnections().length\n\t\t\t\t: 0;\n\n\t\t\tconst bootstrapNodes: string[] =\n\t\t\t\tthis.meshNode &&\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal config\n\t\t\t\t(this.meshNode as any).config?.bootstrapNodes\n\t\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal config\n\t\t\t\t\t\t(this.meshNode as any).config.bootstrapNodes\n\t\t\t\t\t: [];\n\t\t\tconst bootstrapCount = bootstrapNodes.length;\n\n\t\t\tconst diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || \"redacted\";\n\t\t\tconst showBootstraps = diagLevel !== \"minimal\";\n\n\t\t\tconst bootstrapList = showBootstraps\n\t\t\t\t? bootstrapNodes\n\t\t\t\t\t\t.map((addr) => {\n\t\t\t\t\t\t\tconst parts = addr.split(\"/\");\n\t\t\t\t\t\t\tconst id = parts[parts.length - 1];\n\t\t\t\t\t\t\treturn ` • ${id ? id.slice(-8) : \"Unknown\"} (bootstrap)`;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t: \"\";\n\n\t\t\tconst routingTableSize = this.meshNode\n\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t(this.meshNode as any).getRoutingTableSize()\n\t\t\t\t: 0;\n\n\t\t\tconst rawPeerId = this.meshNode?.getPeerId() || \"Offline\";\n\t\t\tconst localPeerId =\n\t\t\t\trawPeerId === \"Offline\" ? rawPeerId : this.redactPeerId(rawPeerId);\n\n\t\t\tconst cachedToolList = Array.from(this.manifestCache.entries())\n\t\t\t\t.flatMap(([peerId, { manifest }]) =>\n\t\t\t\t\tmanifest.tools.map(\n\t\t\t\t\t\t(t) => ` • ${t.name} (from origin: ${this.redactPeerId(peerId)})`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.join(\"\\n\");\n\n\t\t\tconst statusText = [\n\t\t\t\t`LIOP Mesh Status: ${meshState === \"Active\" ? \"Active\" : \"Offline\"}`,\n\t\t\t\t`Local Agent Identity: ${localPeerId}`,\n\t\t\t\t`Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,\n\t\t\t\tshowBootstraps && bootstrapCount > 0\n\t\t\t\t\t? `\\nActive Bootstraps:\\n${bootstrapList}\\n`\n\t\t\t\t\t: \"\",\n\t\t\t\t`Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,\n\t\t\t\t`Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,\n\t\t\t\tcachedTools > 0\n\t\t\t\t\t? `\\nDiscovered Remote Tools (Zero-Trust Origins):\\n${cachedToolList}`\n\t\t\t\t\t: \"\\nNo remote tools discovered yet.\",\n\t\t\t\t// [Token Economy] Telemetry block (only appears when operations exist)\n\t\t\t\tTokenTelemetryEngine.getInstance().formatStatusBlock(),\n\t\t\t]\n\t\t\t\t.filter((line) => line !== \"\")\n\t\t\t\t.join(\"\\n\");\n\n\t\t\t// [Token Economy] Record diagnostic output telemetry\n\t\t\tconst diagTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\tdiagTelemetry.record({\n\t\t\t\ttype: \"diagnostic\",\n\t\t\t\tmethod: \"tools/call\",\n\t\t\t\ttoolName: \"LiopMeshStatus\",\n\t\t\t\testimatedInputTokens: 0,\n\t\t\t\testimatedOutputTokens: diagTelemetry.countTokens(statusText),\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\tresult: {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: statusText,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst isLocal = this.liopServer\n\t\t\t.listTools()\n\t\t\t.some((t) => t.name === toolName);\n\n\t\tif (!isLocal && this.meshNode) {\n\t\t\t// Phase 1: Cache-first — resolve directly from cached manifests (zero-latency)\n\t\t\t// Per MCP spec, tools don't change between notifications/tools/list_changed.\n\t\t\tlet target = this.resolveManifestTarget(toolName);\n\n\t\t\t// Phase 2: If not cached, trigger DHT refresh and retry\n\t\t\tif (!target) {\n\t\t\t\tawait this.refreshManifestCache();\n\t\t\t\ttarget = this.resolveManifestTarget(toolName);\n\t\t\t}\n\n\t\t\tif (target) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`,\n\t\t\t\t);\n\t\t\t\treturn this.routeToRemoteProvider(\n\t\t\t\t\tid,\n\t\t\t\t\ttarget.originalToolName,\n\t\t\t\t\ttarget.peerId,\n\t\t\t\t\tparams,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Phase 2: Try DHT-based dynamic provider discovery (fallback for unsuffixed names)\n\t\t\tlet providers: string[] = [];\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tproviders = await this.meshNode.findProviders(toolName);\n\t\t\t\tif (providers.length > 0) break;\n\t\t\t\tif (i < 2) await new Promise((r) => setTimeout(r, 1000));\n\t\t\t}\n\n\t\t\tif (providers.length > 0) {\n\t\t\t\treturn this.routeToRemoteProvider(id, toolName, providers[0], params);\n\t\t\t}\n\t\t}\n\n\t\t// If no remote provider found, try local execution\n\t\tif (isLocal) {\n\t\t\ttry {\n\t\t\t\tconst localStartTime = Date.now();\n\t\t\t\tconst result = await this.liopServer.callTool({\n\t\t\t\t\tname: toolName,\n\t\t\t\t\targuments: params.arguments || {},\n\t\t\t\t});\n\n\t\t\t\t// [Token Economy] Record local tool call telemetry\n\t\t\t\tconst localTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst localInputPayload = JSON.stringify(params.arguments || {});\n\t\t\t\tconst localOutputPayload = JSON.stringify(result);\n\t\t\t\tlocalTelemetry.record({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tmethod: \"tools/call\",\n\t\t\t\t\ttoolName,\n\t\t\t\t\testimatedInputTokens: localTelemetry.countTokens(localInputPayload),\n\t\t\t\t\testimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),\n\t\t\t\t\tdurationMs: Date.now() - localStartTime,\n\t\t\t\t});\n\n\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\terror: {\n\t\t\t\tcode: -32002,\n\t\t\t\tmessage: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async routeToRemoteProvider(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tid: any,\n\t\ttoolName: string,\n\t\tpeerId: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tparams: any,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t): Promise<any> {\n\t\tif (!this.meshNode)\n\t\t\treturn {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\terror: { code: -32603, message: \"Mesh Node inactive\" },\n\t\t\t};\n\n\t\t// Dynamic gRPC port resolution from manifest cache\n\t\tlet manifestEntry = this.manifestCache.get(peerId);\n\t\tlet grpcPort = this.defaultRpcPort;\n\n\t\tif (manifestEntry) {\n\t\t\tgrpcPort = manifestEntry.manifest.grpcPort;\n\t\t} else {\n\t\t\t// Try to query the manifest directly\n\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\tif (manifest) {\n\t\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\t\tthis.manifestCache.set(peerId, {\n\t\t\t\t\tmanifest,\n\t\t\t\t\tcachedAt: Date.now(),\n\t\t\t\t});\n\t\t\t\tmanifestEntry = this.manifestCache.get(peerId);\n\t\t\t}\n\t\t}\n\n\t\t// Development-only convenience (opt-in):\n\t\t// Docker Desktop setups publish gRPC ports on the host as 13011/13021/13031.\n\t\t// This mapping is DISABLED in production (NODE_ENV=production) to enforce\n\t\t// dynamic port negotiation via the manifest protocol.\n\t\tconst isDevMode =\n\t\t\tprocess.env.NODE_ENV === \"development\" || process.env.NODE_ENV === \"test\";\n\t\tif (\n\t\t\tisDevMode &&\n\t\t\tmanifestEntry &&\n\t\t\tprocess.env.LIOP_USE_PUBLISHED_GRPC_PORTS === \"1\"\n\t\t) {\n\t\t\tconst providerName =\n\t\t\t\tmanifestEntry.manifest.serverInfo?.name?.toLowerCase() || \"\";\n\t\t\tif (providerName.includes(\"vault\")) grpcPort = 13011;\n\t\t\telse if (providerName.includes(\"bank\")) grpcPort = 13021;\n\t\t\telse if (providerName.includes(\"oracle\")) grpcPort = 13031;\n\t\t}\n\n\t\t// Resolve IP from active connections\n\t\tconst addrs = await this.meshNode.resolvePeer(peerId);\n\t\tlet targetAddr: string | null = null;\n\n\t\t// [LIOP-ALPHA] Check if the peer is running on the same physical machine\n\t\t// by comparing its advertised IPs against our local OS interfaces.\n\t\tconst os = await import(\"node:os\");\n\t\tconst localInterfaces = Object.values(os.networkInterfaces())\n\t\t\t.flat()\n\t\t\t.filter((i) => i?.family === \"IPv4\")\n\t\t\t.map((i) => i?.address);\n\n\t\t// Loop through all advertised addresses to find the optimal target\n\t\tfor (const addr of addrs) {\n\t\t\tconst parts = addr.split(\"/\");\n\t\t\tconst ipIdx = parts.indexOf(\"ip4\");\n\t\t\tif (ipIdx !== -1) {\n\t\t\t\tconst advertisedIp = parts[ipIdx + 1];\n\n\t\t\t\t// Loopback priority or Same-Machine detection\n\t\t\t\tif (\n\t\t\t\t\tadvertisedIp === \"127.0.0.1\" ||\n\t\t\t\t\tlocalInterfaces.includes(advertisedIp)\n\t\t\t\t) {\n\t\t\t\t\ttargetAddr = `127.0.0.1:${grpcPort}`;\n\t\t\t\t\tbreak; // Supreme priority for local execution\n\t\t\t\t}\n\n\t\t\t\t// Default to first discovered valid external IP\n\t\t\t\tif (!targetAddr) {\n\t\t\t\t\ttargetAddr = `${advertisedIp}:${grpcPort}`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!targetAddr) {\n\t\t\t// Fallback to localhost with the dynamically resolved port\n\t\t\ttargetAddr = `127.0.0.1:${grpcPort}`;\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`,\n\t\t);\n\n\t\tconst remoteClient = new liopV1.LogicMesh(\n\t\t\ttargetAddr,\n\t\t\tcreateChannelCredentials(),\n\t\t);\n\t\treturn this.performTranscoding(id, remoteClient, toolName, params, peerId);\n\t}\n\n\tprivate async performTranscoding(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tid: any,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: gRPC client from dynamic proto-loader\n\t\tclient: any,\n\t\ttoolName: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tparams: any,\n\t\tpeerId?: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t): Promise<any> {\n\t\tconst capabilityHash = toolName;\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(Buffer.from(capabilityHash))\n\t\t\t: Buffer.from([]);\n\n\t\tconst transcodingStartTime = Date.now();\n\n\t\treturn new Promise((resolve) => {\n\t\t\tclient.negotiateIntent(\n\t\t\t\t{\n\t\t\t\t\tagent_did: `did:liop:${this.meshNode?.getPeerId() || \"mcp-proxy\"}`,\n\t\t\t\t\tcapability_hash: capabilityHash,\n\t\t\t\t\tproof_of_intent: proofOfIntent,\n\t\t\t\t},\n\t\t\t\tasync (err: Error | null, response: IntentResponse) => {\n\t\t\t\t\tif (err || !response.accepted) {\n\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `PQC Handshake Failed: ${err?.message || \"Rejected\"}`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tconst { ciphertext, sharedSecret } =\n\t\t\t\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(\n\t\t\t\t\t\t\tresponse.kyber_public_key,\n\t\t\t\t\t\t);\n\t\t\t\t\t// SECURITY: Avoid AES-GCM nonce reuse across multiple ciphertexts.\n\t\t\t\t\t// We embed arguments directly into the proxy logic so we only encrypt ONE payload per session/nonce.\n\t\t\t\t\tconst embeddedArgsJson = JSON.stringify(params.arguments || {});\n\t\t\t\t\tconst proxyLogic = `return { \"__liop_proxy_tool\": \"${toolName}\", \"__liop_proxy_args\": ${embeddedArgsJson} };`;\n\t\t\t\t\tconst nonce = crypto.randomBytes(12);\n\n\t\t\t\t\tconst sealedLogic = this.encryptWithNonce(\n\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\tsharedSecret,\n\t\t\t\t\t\tnonce,\n\t\t\t\t\t);\n\n\t\t\t\t\tconst call = client.executeLogic({\n\t\t\t\t\t\tsession_token: response.session_token,\n\t\t\t\t\t\twasm_binary: new Uint8Array(sealedLogic),\n\t\t\t\t\t\tinputs: {},\n\t\t\t\t\t\tpqc_ciphertext: ciphertext,\n\t\t\t\t\t\taes_nonce: nonce,\n\t\t\t\t\t});\n\n\t\t\t\t\tlet resultBody = \"\";\n\t\t\t\t\tlet lastResponse: LogicResponse | null = null;\n\t\t\t\t\tcall.on(\"data\", (grpcRes: LogicResponse) => {\n\t\t\t\t\t\tresultBody += grpcRes.semantic_evidence;\n\t\t\t\t\t\tlastResponse = grpcRes;\n\t\t\t\t\t});\n\t\t\t\t\tcall.on(\"end\", async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (lastResponse) {\n\t\t\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.zk_receipt),\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: \"SECURITY ALERT: Remote response failed cryptographic integrity audit.\",\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst parsedResult = JSON.parse(resultBody);\n\n\t\t\t\t\t\t\t// [Token Economy] Record remote tool call telemetry\n\t\t\t\t\t\t\tconst remoteTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\t\t\tremoteTelemetry.record({\n\t\t\t\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\t\t\t\tmethod: \"tools/call\",\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\t\testimatedInputTokens:\n\t\t\t\t\t\t\t\t\tremoteTelemetry.countTokens(embeddedArgsJson),\n\t\t\t\t\t\t\t\testimatedOutputTokens: remoteTelemetry.countTokens(resultBody),\n\t\t\t\t\t\t\t\tdurationMs: Date.now() - transcodingStartTime,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tresolve({ jsonrpc: \"2.0\", id, result: parsedResult });\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tresult: { content: [{ type: \"text\", text: resultBody }] },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tcall.on(\"error\", (e: Error) =>\n\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{ type: \"text\", text: `LIOP gRPC Error: ${e.message}` },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate encryptWithNonce(\n\t\tpayload: Buffer,\n\t\tkey: Uint8Array,\n\t\tnonce: Buffer,\n\t): Buffer {\n\t\tconst cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce);\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\treturn Buffer.concat([encrypted, cipher.getAuthTag()]);\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import {g}from'./chunk-7MAGL6ON.js';import {a}from'./chunk-S6RJHZV2.js';import*as d from'http';import*as c from'http2';import*as l from'net';var h=class{constructor(e,r=null,o=50051){this.liopServer=e;this.meshNode=r;this.router=new g(this.liopServer,this.meshNode,o),this.h2Server=c.createServer(),this.setupH2Routes(),this.h1Server=d.createServer(),this.setupH1Routes(),this.netServer=l.createServer(t=>{t.once("data",n=>{let s=n.toString().startsWith("PRI * HTTP/2.0");a.info(`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${s?"HTTP/2 (gRPC)":"HTTP/1.1 (MCP)"}`),s?this.h2Server.emit("connection",t):this.h1Server.emit("connection",t),t.unshift(n);}),t.on("error",n=>a.error(`[LIOP-Gateway] NetServer Socket Error: ${n.message}`));}),this.h1Server.on("error",t=>a.error(`[LIOP-Gateway] H1 Server Error: ${t.message}`)),this.h2Server.on("error",t=>a.error(`[LIOP-Gateway] H2 Server Error: ${t.message}`)),a.info("[LIOP-Gateway] Hybrid adapter initialized.");}netServer;h2Server;h1Server;router;setupH2Routes(){this.h2Server.on("stream",(e,r)=>{let o=r["content-type"],t=r[":path"];o==="application/grpc"?this.handleGrpcStream(e):t==="/mcp"&&this.handleMcpH2Stream(e,r);});}setupH1Routes(){this.h1Server.on("request",async(e,r)=>{let o=e.url||"",t=e.method;if(t==="GET"&&(o==="/"||o==="/mcp"||o==="/health")){if(o==="/health"&&e.headers.accept?.includes("application/json")){let n=this.meshNode?{peerId:this.meshNode.getPeerId()?.toString()||"",multiaddrs:this.meshNode.getMultiaddrs().map(s=>s.toString())}:null;r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"healthy",node:this.liopServer.getServerInfo(),mesh:n,tools:this.liopServer.listTools().map(s=>s.name),timestamp:new Date().toISOString()}));return}r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
1
+ import {g}from'./chunk-CTB5O4PB.js';import {a}from'./chunk-S6RJHZV2.js';import*as d from'http';import*as c from'http2';import*as l from'net';var h=class{constructor(e,r=null,o=50051){this.liopServer=e;this.meshNode=r;this.router=new g(this.liopServer,this.meshNode,o),this.h2Server=c.createServer(),this.setupH2Routes(),this.h1Server=d.createServer(),this.setupH1Routes(),this.netServer=l.createServer(t=>{t.once("data",n=>{let s=n.toString().startsWith("PRI * HTTP/2.0");a.info(`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${s?"HTTP/2 (gRPC)":"HTTP/1.1 (MCP)"}`),s?this.h2Server.emit("connection",t):this.h1Server.emit("connection",t),t.unshift(n);}),t.on("error",n=>a.error(`[LIOP-Gateway] NetServer Socket Error: ${n.message}`));}),this.h1Server.on("error",t=>a.error(`[LIOP-Gateway] H1 Server Error: ${t.message}`)),this.h2Server.on("error",t=>a.error(`[LIOP-Gateway] H2 Server Error: ${t.message}`)),a.info("[LIOP-Gateway] Hybrid adapter initialized.");}netServer;h2Server;h1Server;router;setupH2Routes(){this.h2Server.on("stream",(e,r)=>{let o=r["content-type"],t=r[":path"];o==="application/grpc"?this.handleGrpcStream(e):t==="/mcp"&&this.handleMcpH2Stream(e,r);});}setupH1Routes(){this.h1Server.on("request",async(e,r)=>{let o=e.url||"",t=e.method;if(t==="GET"&&(o==="/"||o==="/mcp"||o==="/health")){if(o==="/health"&&e.headers.accept?.includes("application/json")){let n=this.meshNode?{peerId:this.meshNode.getPeerId()?.toString()||"",multiaddrs:this.meshNode.getMultiaddrs().map(s=>s.toString())}:null;r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"healthy",node:this.liopServer.getServerInfo(),mesh:n,tools:this.liopServer.listTools().map(s=>s.name),timestamp:new Date().toISOString()}));return}r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
2
2
  <body style="background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0">
3
3
  <div style="background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)">
4
4
  <h1 style="color:#38bdf8;margin-top:0">LIOP Protocol Transformer</h1>
@@ -9,5 +9,5 @@ import {g}from'./chunk-7MAGL6ON.js';import {a}from'./chunk-S6RJHZV2.js';import*a
9
9
  </div>
10
10
  </div>
11
11
  </body>
12
- `);return}if(o==="/mcp"&&t==="POST"){let n="";e.on("data",s=>n+=s.toString()),e.on("end",async()=>{try{let s=JSON.parse(n),a=await this.router.dispatch(s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify(a));}catch(s){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${s.message}`),r.writeHead(400),r.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else r.writeHead(404),r.end("Not Found");});}handleGrpcStream(e){e.on("data",r=>{let o=r;o&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${o.length} bytes`);}),e.respond({":status":200,"content-type":"application/grpc"}),e.end();}handleMcpH2Stream(e,r){let o="";e.on("data",t=>o+=t.toString()),e.on("end",async()=>{try{let t=await this.router.dispatch(JSON.parse(o));t?(e.respond({":status":200,"content-type":"application/json"}),e.end(JSON.stringify(t))):e.close();}catch{e.respond({":status":400}),e.end();}});}async listen(e,r="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let o=this.liopServer.listTools();for(let t of o)await this.meshNode.announceCapability(t.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${t.name}`);}return new Promise((o,t)=>{this.netServer.on("error",n=>{n.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${e} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${n.message}`),t(n);}),this.netServer.listen(e,r,()=>{let n=this.netServer.address(),s=typeof n=="string"?n:n?.address||r,a$1=typeof n=="string"?e:n?.port||e;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${s}:${a$1}`),o(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{h as a};//# sourceMappingURL=chunk-JBMEAXYU.js.map
13
- //# sourceMappingURL=chunk-JBMEAXYU.js.map
12
+ `);return}if(o==="/mcp"&&t==="POST"){let n="";e.on("data",s=>n+=s.toString()),e.on("end",async()=>{try{let s=JSON.parse(n),a=await this.router.dispatch(s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify(a));}catch(s){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${s.message}`),r.writeHead(400),r.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else r.writeHead(404),r.end("Not Found");});}handleGrpcStream(e){e.on("data",r=>{let o=r;o&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${o.length} bytes`);}),e.respond({":status":200,"content-type":"application/grpc"}),e.end();}handleMcpH2Stream(e,r){let o="";e.on("data",t=>o+=t.toString()),e.on("end",async()=>{try{let t=await this.router.dispatch(JSON.parse(o));t?(e.respond({":status":200,"content-type":"application/json"}),e.end(JSON.stringify(t))):e.close();}catch{e.respond({":status":400}),e.end();}});}async listen(e,r="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let o=this.liopServer.listTools();for(let t of o)await this.meshNode.announceCapability(t.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${t.name}`);}return new Promise((o,t)=>{this.netServer.on("error",n=>{n.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${e} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${n.message}`),t(n);}),this.netServer.listen(e,r,()=>{let n=this.netServer.address(),s=typeof n=="string"?n:n?.address||r,a$1=typeof n=="string"?e:n?.port||e;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${s}:${a$1}`),o(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{h as a};//# sourceMappingURL=chunk-DRCLBOMG.js.map
13
+ //# sourceMappingURL=chunk-DRCLBOMG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/gateway/hybrid.ts"],"names":["LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","meshInfo","m","t","body","chunk","jsonRequest","response","e","data","_headers","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"6IAYO,IAAMA,CAAAA,CAAN,KAAwB,CAM9B,WAAA,CACSC,EACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EAIR,IAAA,CAAK,MAAA,CAAS,IAAIE,CAAAA,CAAc,KAAK,UAAA,CAAY,IAAA,CAAK,QAAA,CAAUD,CAAO,EAGvE,IAAA,CAAK,QAAA,CAAiB,CAAA,CAAA,YAAA,EAAa,CACnC,IAAA,CAAK,aAAA,EAAc,CAGnB,IAAA,CAAK,SAAgB,CAAA,CAAA,YAAA,EAAa,CAClC,IAAA,CAAK,aAAA,EAAc,CAGnB,IAAA,CAAK,SAAA,CAAgB,CAAA,CAAA,YAAA,CAAcE,GAAW,CAC7CA,CAAAA,CAAO,IAAA,CAAK,MAAA,CAASC,CAAAA,EAAW,CAC/B,IAAMC,CAAAA,CAAUD,EAAO,QAAA,EAAS,CAAE,UAAA,CAAW,gBAAgB,EAC7DE,CAAAA,CAAI,IAAA,CACH,CAAA,iDAAA,EAAoDD,C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AA,EAAiCC,EAAI,OAAO,CAAA,CAAE,EAEzDwB,CAAAA,CAAOxB,CAAG,EACX,CAAC,EAED,IAAA,CAAK,SAAA,CAAU,OAAOmB,CAAAA,CAAMC,CAAAA,CAAM,IAAM,CACvC,IAAMK,CAAAA,CAAO,IAAA,CAAK,UAAU,OAAA,EAAQ,CAC9BC,EACL,OAAOD,CAAAA,EAAS,SAAWA,CAAAA,CAAOA,CAAAA,EAAM,OAAA,EAAWL,CAAAA,CAC9CO,IACL,OAAOF,CAAAA,EAAS,SAAWN,CAAAA,CAAOM,CAAAA,EAAM,MAAQN,CAAAA,CAEjDpB,CAAAA,CAAI,IAAA,CACH,CAAA,sEAAA,EAAoE2B,CAAU,CAAA,CAAA,EAAIC,GAAY,EAC/F,CAAA,CACAJ,CAAAA,CAAQI,GAAY,EACrB,CAAC,EACF,CAAC,CACF,CAEA,MAAa,MAAO,CACf,IAAA,CAAK,UACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,GAErB,IAAA,CAAK,SAAA,CAAU,OAAM,CACrB,IAAA,CAAK,SAAS,KAAA,EAAM,CACpB,KAAK,QAAA,CAAS,KAAA,GACf,CAEO,SAAA,EAA2B,CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-JBMEAXYU.js","sourcesContent":["import * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC &harr; gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\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} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\t_headers: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body));\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/gateway/hybrid.ts"],"names":["LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","meshInfo","m","t","body","chunk","jsonRequest","response","e","data","_headers","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"6IAYO,IAAMA,CAAAA,CAAN,KAAwB,CAM9B,WAAA,CACSC,EACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EAIR,IAAA,CAAK,MAAA,CAAS,IAAIE,CAAAA,CAAc,KAAK,UAAA,CAAY,IAAA,CAAK,QAAA,CAAUD,CAAO,EAGvE,IAAA,CAAK,QAAA,CAAiB,CAAA,CAAA,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A,CAAS,mBAAmBC,CAAAA,CAAK,IAAI,EAChDvB,CAAAA,CAAI,IAAA,CACH,0DAAmDuB,CAAAA,CAAK,IAAI,CAAA,CAC7D,EAEF,CACA,OAAO,IAAI,QAAQ,CAACC,CAAAA,CAASC,IAAW,CACvC,IAAA,CAAK,UAAU,EAAA,CAAG,OAAA,CAAUxB,GAAmC,CAC1DA,CAAAA,CAAI,OAAS,YAAA,CAChBD,CAAAA,CAAI,KACH,CAAA,2BAAA,EAA8BoB,CAAI,CAAA,sCAAA,CACnC,CAAA,CAEApB,EAAI,KAAA,CAAM,CAAA,8BAAA,EAAiCC,EAAI,OAAO,CAAA,CAAE,EAEzDwB,CAAAA,CAAOxB,CAAG,EACX,CAAC,EAED,IAAA,CAAK,SAAA,CAAU,OAAOmB,CAAAA,CAAMC,CAAAA,CAAM,IAAM,CACvC,IAAMK,CAAAA,CAAO,IAAA,CAAK,UAAU,OAAA,EAAQ,CAC9BC,EACL,OAAOD,CAAAA,EAAS,SAAWA,CAAAA,CAAOA,CAAAA,EAAM,OAAA,EAAWL,CAAAA,CAC9CO,IACL,OAAOF,CAAAA,EAAS,SAAWN,CAAAA,CAAOM,CAAAA,EAAM,MAAQN,CAAAA,CAEjDpB,CAAAA,CAAI,IAAA,CACH,CAAA,sEAAA,EAAoE2B,CAAU,CAAA,CAAA,EAAIC,GAAY,EAC/F,CAAA,CACAJ,CAAAA,CAAQI,GAAY,EACrB,CAAC,EACF,CAAC,CACF,CAEA,MAAa,MAAO,CACf,IAAA,CAAK,UACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,GAErB,IAAA,CAAK,SAAA,CAAU,OAAM,CACrB,IAAA,CAAK,SAAS,KAAA,EAAM,CACpB,KAAK,QAAA,CAAS,KAAA,GACf,CAEO,SAAA,EAA2B,CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-DRCLBOMG.js","sourcesContent":["import * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC &harr; gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\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} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\t_headers: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body));\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
package/dist/gateway.js CHANGED
@@ -1,2 +1,2 @@
1
- export{a as LiopHybridGateway}from'./chunk-JBMEAXYU.js';import'./chunk-7MAGL6ON.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=gateway.js.map
1
+ export{a as LiopHybridGateway}from'./chunk-DRCLBOMG.js';import'./chunk-CTB5O4PB.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=gateway.js.map
2
2
  //# sourceMappingURL=gateway.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{b as WasiSandbox}from'./chunk-HNDVAKEK.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-P52IE4L6.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TNMS53OP.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-KUCR7DYN.js';export{a as LiopHybridGateway}from'./chunk-JBMEAXYU.js';export{a as LiopRpcServer,f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-YDGVPISC.js';import'./chunk-2MGFSIXN.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-7MAGL6ON.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';export{a as MeshNode}from'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';var u=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(u||{}),n=class extends Error{code;constructor(t,o){super(o),this.name="LiopError",this.code=t;}};var f={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function D(a){let t=f[a],o=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
1
+ export{b as WasiSandbox}from'./chunk-HNDVAKEK.js';export{b as LiopClient,a as LiopRpcClient}from'./chunk-P52IE4L6.js';export{c as PromptSchema,b as ResourceSchema,a as ToolSchema}from'./chunk-TNMS53OP.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-KUCR7DYN.js';export{a as LiopHybridGateway}from'./chunk-DRCLBOMG.js';export{a as LiopRpcServer,f as LiopServer,b as NerScanner,c as PII_PATTERNS,d as PII_PRESETS,e as PiiScanner}from'./chunk-YDGVPISC.js';import'./chunk-2MGFSIXN.js';export{b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-CTB5O4PB.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';export{a as MeshNode}from'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';var u=(e=>(e.CapabilityViolation="CapabilityViolation",e.SandboxEscape="SandboxEscape",e.PiiLeak="PiiLeak",e.InvalidIntent="InvalidIntent",e.Throttled="Throttled",e.ZkVerificationFailed="ZkVerificationFailed",e.MeshUnavailable="MeshUnavailable",e.ConnectionFailed="ConnectionFailed",e))(u||{}),n=class extends Error{code;constructor(t,o){super(o),this.name="LiopError",this.code=t;}};var f={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function D(a){let t=f[a],o=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
2
2
  You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
3
3
  Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nekzus/liop",
3
- "version": "2.0.0-alpha.14",
3
+ "version": "2.0.0-alpha.15",
4
4
  "description": "Official SDK for Logic-Injection-on-Origin Protocol (LIOP). Deploy Logic-on-Origin with WebAssembly at gRPC speed and bidirectional MCP compatibility.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,33 +0,0 @@
1
- import {a as a$1}from'./chunk-UVTEJYHN.js';import {a as a$3}from'./chunk-DBXGYHKY.js';import {a as a$2,c}from'./chunk-HM77MWB6.js';import {a}from'./chunk-S6RJHZV2.js';import {metrics}from'@opentelemetry/api';import*as w from'crypto';var C=class{name="o200k_base";countFn;constructor(e,r){this.countFn=e,r&&r(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 B(){try{let y=await import('gpt-tokenizer'),e=new C(y.countTokens,y.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 U(){return new R}var H="@nekzus/liop",J="1.2.0-alpha.9",q=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],Q=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],N=class{tokenUsage;operationDuration;active=false;constructor(){try{let e=metrics.getMeter(H,J);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:q}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:Q}}),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 r={record:()=>{}};this.tokenUsage=r,this.operationDuration=r;}}recordTokens(e,r,s,n){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":s,"gen_ai.token.type":r,"gen_ai.request.model":"liop-mesh",...n?{"liop.tool.name":n}:{}});}recordDuration(e,r,s){this.operationDuration.record(e/1e3,{"gen_ai.system":"liop","gen_ai.operation.name":r,...s?{"error.type":s}:{}});}isActive(){return this.active}};var W={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},I=class y{static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=U(),this.otelBridge=new N,this.initRealEstimator();}initRealEstimator(){B().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return y.instance||(y.instance=new y),y.instance}countTokens(e){try{return this.estimator.countTokens(e)}catch{return Math.ceil(e.length/4)}}record(e){let r={...e,timestamp:Date.now()};this.operations.push(r);try{let s=W[e.type]||"chat";e.estimatedInputTokens>0&&this.otelBridge.recordTokens(e.estimatedInputTokens,"input",s,e.toolName),e.estimatedOutputTokens>0&&this.otelBridge.recordTokens(e.estimatedOutputTokens,"output",s,e.toolName),e.durationMs!==void 0&&this.otelBridge.recordDuration(e.durationMs,s);}catch{}}estimateTokens(e){return this.countTokens(e)}getReport(){return {sessionId:this.sessionId,operations:[...this.operations],totalInputTokens:this.operations.reduce((e,r)=>e+r.estimatedInputTokens,0),totalOutputTokens:this.operations.reduce((e,r)=>e+r.estimatedOutputTokens,0),estimatorName:this.estimator.name,sessionUptimeMs:Date.now()-this.startedAt}}getPerToolReport(){let e=new Map;for(let r of this.operations){let s=r.toolName||r.method,n=e.get(s)||{input:0,output:0,calls:0,avgDurationMs:0},t=n.avgDurationMs*n.calls+(r.durationMs||0),o=n.calls+1;e.set(s,{input:n.input+r.estimatedInputTokens,output:n.output+r.estimatedOutputTokens,calls:o,avgDurationMs:o>0?t/o:0});}return e}formatStatusBlock(){let e=this.getReport();if(e.operations.length===0)return "";let r=this.formatUptime(e.sessionUptimeMs),s=e.totalInputTokens+e.totalOutputTokens,n=new Map;for(let p of e.operations){let h=p.type,d=n.get(h)||{count:0,input:0,output:0};n.set(h,{count:d.count+1,input:d.input+p.estimatedInputTokens,output:d.output+p.estimatedOutputTokens});}let t=Array.from(n.entries()),o=t.map(([p,h],d)=>{let P=d===t.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",S=h.output>0?` / ${h.output.toLocaleString()} out`:"";return `${P} ${p} \xD7${h.count} \u2192 ${h.input.toLocaleString()} in${S}`}),c=this.getPerToolReport(),u=Array.from(c.entries()).filter(([p])=>p!=="tools/list"&&p!=="LiopMeshStatus"),i=[];u.length>0&&(i.push("\u251C\u2500 By Tool:"),u.forEach(([p,h],d)=>{let P=d===u.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",S=h.output>0?` / ${h.output.toLocaleString()} out`:"",v=h.avgDurationMs>0?` ~${Math.round(h.avgDurationMs)}ms`:"";i.push(`${P} ${p}: ${h.input.toLocaleString()} in${S} (\xD7${h.calls})${v}`);}));let f=e.operations.filter(p=>p.durationMs!==void 0),m=f.length>0?Math.round(f.reduce((p,h)=>p+(h.durationMs||0),0)/f.length):0,a=this.otelBridge.isActive()?"gen_ai.client.token.usage \u2192 active":"disabled";return [`
2
- Token Economy:`,`\u251C\u2500 Session: ${e.sessionId.slice(0,8)} (${r})`,`\u251C\u2500 Estimator: ${e.estimatorName}`,`\u251C\u2500 Operations: ${e.operations.length}`,...o,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${s.toLocaleString()} combined)`,...i,...m>0?[`\u251C\u2500 Avg Latency: ${m}ms`]:[],`\u2514\u2500 OTel: ${a}`].join(`
3
- `)}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return `${r}s`;let s=Math.floor(r/60),n=r%60;if(s<60)return `${s}m ${n}s`;let t=Math.floor(s/60),o=s%60;return `${t}h ${o}m`}reset(){this.operations=[];}static destroy(){y.instance=null;}};function M(){let y=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(y==="0"||y==="false"||y==="no")}function b(y){let e=y,r=[`
4
-
5
- [LIOP-PROTO-V1:`,`\r
6
- \r
7
- [LIOP-PROTO-V1:`,`
8
- [LIOP-PROTO-V1:`];for(let s of r){let n=e.indexOf(s);if(n!==-1){e=e.slice(0,n);break}}return e.trimEnd()}var z=300,$=5,F=class y{constructor(e,r=null,s=50051){this.liopServer=e;this.meshNode=r;this.defaultRpcPort=s;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let n=this.liopServer.listTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),t=this.liopServer.listResources().map(o=>({name:o.name,uri:o.uri,description:o.description,mimeType:o.mimeType}));return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...n],resources:t,serverInfo:this.liopServer.getServerInfo()}}),this.meshNode.announceManifest().catch(n=>{a.info(`[LIOP-Router] Failed to announce manifest: ${n instanceof Error?n.message:String(n)}`);})),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 r=this.manifestFailureState.get(e);if(!r)return false;let s=Date.now();return s>=r.cooldownUntil?false:(s-r.lastSkipLogAt>y.MANIFEST_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Router] Skipping manifest query for ${e} during cooldown (${Math.ceil((r.cooldownUntil-s)/1e3)}s remaining)`),r.lastSkipLogAt=s),true)}recordManifestQuerySuccess(e){this.manifestFailureState.delete(e);}recordManifestQueryFailure(e){let r=Date.now(),n=(this.manifestFailureState.get(e)?.failures||0)+1,t=Math.min(y.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,n-1),y.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:n,cooldownUntil:r+t,lastSkipLogAt:0});}async dispatch(e){let{method:r,params:s,id:n}=e;switch(a.info(`[LIOP-Router] Processing: ${r}`),r){case "initialize":return {jsonrpc:"2.0",id:n,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:n,result:{}};case "tools/list":{let t=this.liopServer.listTools(),o=await this.getRemoteTools(),c=M()?t.map(l=>({...l,description:b(l.description??"")})):t;a.info(`[LIOP-Router] tools/list: ${t.length} local, ${o.length} remote tools found`);let i=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...c,...o],f=I.getInstance(),m=JSON.stringify(i),a$1=JSON.stringify({tools:i});return f.record({type:"tools_list",method:"tools/list",estimatedInputTokens:f.countTokens(m),estimatedOutputTokens:f.countTokens(a$1)}),{jsonrpc:"2.0",id:n,result:{tools:i}}}case "tools/call":return this.transcodeMcpToLiop(n,s);case "resources/list":{let t=this.liopServer.listResources(),o=await this.getRemoteResources(),c=[...t,...o],u=I.getInstance(),i=JSON.stringify(c);return u.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:u.countTokens(i)}),{jsonrpc:"2.0",id:n,result:{resources:c}}}case "resources/read":{let t=s;if(!t?.uri)return {jsonrpc:"2.0",id:n,error:{code:-32602,message:"Missing resource uri"}};try{let o=Date.now(),c=await this.liopServer.readResource(t.uri),u=I.getInstance(),i=JSON.stringify(c);return u.record({type:"resource_read",method:"resources/read",toolName:t.uri,estimatedInputTokens:u.countTokens(t.uri),estimatedOutputTokens:u.countTokens(i),durationMs:Date.now()-o}),{jsonrpc:"2.0",id:n,result:c}}catch(o){let c=t.uri;for(let{manifest:u}of this.manifestCache.values()){let i=u.resources.find(f=>f.uri===c);if(i)return a.info(`[LIOP-Router] Resolved resource ${c} from cache (Peer: ${u.peerId})`),{jsonrpc:"2.0",id:n,result:{contents:[{uri:i.uri,mimeType:i.mimeType||"text/plain",text:i.text||i.description||"No content provided"}]}}}return {jsonrpc:"2.0",id:n,error:{code:-32e3,message:o instanceof Error?o.message:String(o)}}}}case "prompts/list":{let t=this.liopServer.listPrompts(),o=I.getInstance(),c=JSON.stringify(t);return o.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:o.countTokens(c)}),{jsonrpc:"2.0",id:n,result:{prompts:t}}}case "prompts/get":{let t=s;if(!t?.name)return {jsonrpc:"2.0",id:n,error:{code:-32602,message:"Missing prompt name"}};try{let o=Date.now(),c=await this.liopServer.getPrompt({name:t.name,arguments:t.arguments||{}}),u=I.getInstance(),i=JSON.stringify({name:t.name,arguments:t.arguments}),f=JSON.stringify(c);return u.record({type:"prompt_get",method:"prompts/get",toolName:t.name,estimatedInputTokens:u.countTokens(i),estimatedOutputTokens:u.countTokens(f),durationMs:Date.now()-o}),{jsonrpc:"2.0",id:n,result:c}}catch(o){return {jsonrpc:"2.0",id:n,error:{code:-32e3,message:o instanceof Error?o.message:String(o)}}}}default:return {jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${r}`}}}}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 r=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:n})=>r-n<z*1e3))return}return this.currentDiscovery=(async()=>{try{let r=Array.from(this.manifestCache.values()).reduce((a,{manifest:l})=>a+l.tools.length,0);if(this.manifestCache.size===0)for(let a$1=0;a$1<3;a$1++){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 ${a$1+1}/10)...`),await new Promise(p=>setTimeout(p,1e3));}let s=[],n=this.manifestCache.size===0?5:1;for(let a$1=0;a$1<n;a$1++){for(let d=0;d<$;d++){s=await this.meshNode?.discoverManifestProviders()||[];let P=this.meshNode?.getPeerId();if(s.filter(v=>v!==P).length>0)break;d<$-1&&(a.info(`[LIOP-Router] DHT discovery attempt ${d+1}/${$}...`),await new Promise(v=>setTimeout(v,1e3)));}let l=this.meshNode.node?.getConnections().map(d=>d.remotePeer.toString())||[];l.length>0&&(s=Array.from(new Set([...s,...l])));let p=this.meshNode?.getPeerId();if(s.filter(d=>d!==p).length>0)break;a$1<n-1&&(a.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${a$1+1}/${n})...`),await new Promise(d=>setTimeout(d,1e3)));}if(s.length===0){a.info("[LIOP-Router] No manifest providers found after all attempts.");return}e||a.info(`[LIOP-Router] Discovered ${s.length} candidate manifest providers`);let t=new Set((this.meshNode.node?.getConnections?.()||[]).map(a=>a.remotePeer.toString()));s=[...s].sort((a,l)=>{let p=t.has(a)?1:0;return (t.has(l)?1:0)-p});let o=0,c=0,u=!1,i=this.meshNode?.getPeerId(),f=s.filter(a=>{if(!this.meshNode||a===i||this.shouldSkipManifestQuery(a))return !1;let l=this.manifestCache.get(a);return l&&Date.now()-l.cachedAt<z*1e3?(o++,!1):!0}),m=await Promise.allSettled(f.map(async a$1=>this.meshNode?(a.info(`[LIOP-Router] Querying manifest from: ${a$1}`),{peerId:a$1,manifest:await this.meshNode.queryManifest(a$1)}):null));for(let a$1 of m)if(a$1.status==="fulfilled"&&a$1.value?.manifest){let{peerId:l,manifest:p}=a$1.value;this.manifestCache.set(l,{manifest:p,cachedAt:Date.now()}),this.recordManifestQuerySuccess(l),u=!0,o++,a.info(`[LIOP-Router] Manifest received from ${l} (${p.tools.length} tools)`);}else a$1.status==="fulfilled"&&a$1.value?(this.recordManifestQueryFailure(a$1.value.peerId),c++,a.info(`[LIOP-Router] Manifest query returned NULL for ${a$1.value.peerId}`)):a$1.status==="rejected"&&(c++,a.info("[LIOP-Router] Fatal error querying manifest:",a$1.reason instanceof Error?a$1.reason.message:String(a$1.reason)));this._discoveryStats={candidates:s.length,success:o,failures:c,lastDiscovery:Date.now()},u&&Array.from(this.manifestCache.values()).reduce((l,{manifest:p})=>l+p.tools.length,0)!==r&&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 t=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),o=Number.isFinite(t)&&t>0?t:12e3,c=Date.now()+o,u=0,i=-1;for(;Date.now()<c&&!(this.manifestCache.size>=e||(await Promise.race([this.refreshManifestCache(true),new Promise(f=>setTimeout(f,3e3))]).catch(()=>{}),this.manifestCache.size>=e));){if(this.manifestCache.size===i){if(u++,u>=3&&this.manifestCache.size>0){a.info(`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${e}. Proceeding with available mesh.`);break}}else u=0,i=this.manifestCache.size;await new Promise(f=>setTimeout(f,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 r=[],s=new Set,n=new Set(this.liopServer.listTools().map(t=>t.name));for(let[t,{manifest:o}]of this.manifestCache.entries())for(let c of o.tools){if(c.name==="LiopMeshStatus")continue;let u=c.name;(s.has(c.name)||n.has(c.name))&&(u=`${c.name}_${t.slice(-4)}`),s.add(u);let i=o.serverInfo?.name||"Unknown Provider",f=c.description||`Remote tool from ${i}`,m={name:u,description:M()?b(f):f,inputSchema:c.inputSchema||{type:"object",properties:{}}};typeof m.inputSchema=="object"&&!m.inputSchema.type&&(m.inputSchema.type="object"),typeof m.inputSchema=="object"&&!m.inputSchema.properties&&(m.inputSchema.properties={});let a="";o.taxonomy&&(a=`
11
- [LIOP-DOMAIN: ${o.taxonomy.domain}]`);let l=m.inputSchema.properties||{},p="";!M()&&l.payload&&(p=`
12
- [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!M()&&m.description.includes("STRICT SCHEMA ADHERENCE")&&(m.description=m.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let h=M()?`
13
- (Peer: ${t.slice(-8)})${a}`:`
14
- (Origin: ${t.slice(-8)})${a}${p}`;m.description=`${m.description}${h}`,r.push(m);}return r}async getRemoteResources(){this.currentDiscovery||this.refreshManifestCache(true).catch(()=>{});let e=[],r=new Set(this.liopServer.listResources().map(s=>s.uri));for(let[s,{manifest:n}]of this.manifestCache.entries())for(let t of n.resources)if(!r.has(t.uri)){let o={...t},c=n.serverInfo?.name||"Unknown Provider",u="";n.taxonomy&&(u=`
15
-
16
- [LIOP Zero-Trust Blueprint]
17
- Domain: ${n.taxonomy.domain}
18
- Clearance Tier: ${n.taxonomy.clearanceTier}`,n.taxonomy.executionTypes&&n.taxonomy.executionTypes.length>0&&(u+=`
19
- Execution Types: ${n.taxonomy.executionTypes.join(", ")}`));let i=`
20
-
21
- [LIOP Zero-Trust Origin]
22
- Provider: ${c}
23
- Network ID: ${s}${u}`;o.uri.startsWith("liop://schema/")?(o.name=`[SCHEMA] ${o.name}`,o.description=`[CRITICAL SCHEMA] ${o.description||"Data Dictionary for Zero-Shot Autonomy"}${i}`):o.description=o.description?`${o.description}${i}`:i.trim(),e.push(o),r.add(t.uri);}return e}resolveManifestTarget(e){for(let[s,{manifest:n}]of this.manifestCache.entries())if(n.tools.find(o=>o.name===e))return {peerId:s,originalToolName:e};let r=e.split("_");if(r.length>1){let s=r.pop(),n=r.join("_");for(let[t,{manifest:o}]of this.manifestCache.entries())if(t.endsWith(s||"")&&o.tools.find(u=>u.name===n))return {peerId:t,originalToolName:n}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,r){let s=r.name;if(s==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let t=this._discoveryStats||{candidates:0,success:0,failures:0},o=this.manifestCache.size,c=this.meshNode?"Active":"Offline",u=Array.from(this.manifestCache.values()).reduce((T,{manifest:k})=>T+k.tools.length,0),i=this.meshNode?this.meshNode.node?.getConnections().length:0,f=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],m=f.length,l=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",p=l?f.map(T=>{let k=T.split("/"),L=k[k.length-1];return ` \u2022 ${L?L.slice(-8):"Unknown"} (bootstrap)`}).join(`
24
- `):"",h=this.meshNode?this.meshNode.getRoutingTableSize():0,d=this.meshNode?.getPeerId()||"Offline",P=d==="Offline"?d:this.redactPeerId(d),S=Array.from(this.manifestCache.entries()).flatMap(([T,{manifest:k}])=>k.tools.map(L=>` \u2022 ${L.name} (from origin: ${this.redactPeerId(T)})`)).join(`
25
- `),v=[`LIOP Mesh Status: ${c==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${P}`,`Network: ${i} Conns | ${h} Mesh Nodes | ${m} Bootstraps`,l&&m>0?`
26
- Active Bootstraps:
27
- ${p}
28
- `:"",`Discovery: ${t.candidates} Candidates | ${t.success} OK | ${t.failures} FAIL`,`Tooling: ${o} Providers | ${u} Total Remote Tools`,u>0?`
29
- Discovered Remote Tools (Zero-Trust Origins):
30
- ${S}`:`
31
- No remote tools discovered yet.`,I.getInstance().formatStatusBlock()].filter(T=>T!=="").join(`
32
- `),O=I.getInstance();return O.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:O.countTokens(v)}),{jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:v}]}}}let n=this.liopServer.listTools().some(t=>t.name===s);if(!n&&this.meshNode){let t=this.resolveManifestTarget(s);if(t||(await this.refreshManifestCache(),t=this.resolveManifestTarget(s)),t)return a.info(`[LIOP-Router] Resolved ${s} via manifest cache (Peer: ${t.peerId}, Original: ${t.originalToolName})`),this.routeToRemoteProvider(e,t.originalToolName,t.peerId,r);let o=[];for(let c=0;c<3&&(o=await this.meshNode.findProviders(s),!(o.length>0));c++)c<2&&await new Promise(u=>setTimeout(u,1e3));if(o.length>0)return this.routeToRemoteProvider(e,s,o[0],r)}if(n)try{let t=Date.now(),o=await this.liopServer.callTool({name:s,arguments:r.arguments||{}}),c=I.getInstance(),u=JSON.stringify(r.arguments||{}),i=JSON.stringify(o);return c.record({type:"tool_call",method:"tools/call",toolName:s,estimatedInputTokens:c.countTokens(u),estimatedOutputTokens:c.countTokens(i),durationMs:Date.now()-t}),{jsonrpc:"2.0",id:e,result:o}}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: ${s}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(e,r,s,n){if(!this.meshNode)return {jsonrpc:"2.0",id:e,error:{code:-32603,message:"Mesh Node inactive"}};let t=this.manifestCache.get(s),o=this.defaultRpcPort;if(t)o=t.manifest.grpcPort;else {let l=await this.meshNode.queryManifest(s);l&&(o=l.grpcPort,this.manifestCache.set(s,{manifest:l,cachedAt:Date.now()}),t=this.manifestCache.get(s));}if((process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test")&&t&&process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"){let l=t.manifest.serverInfo?.name?.toLowerCase()||"";l.includes("vault")?o=13011:l.includes("bank")?o=13021:l.includes("oracle")&&(o=13031);}let u=await this.meshNode.resolvePeer(s),i=null,f=await import('os'),m=Object.values(f.networkInterfaces()).flat().filter(l=>l?.family==="IPv4").map(l=>l?.address);for(let l of u){let p=l.split("/"),h=p.indexOf("ip4");if(h!==-1){let d=p[h+1];if(d==="127.0.0.1"||m.includes(d)){i=`127.0.0.1:${o}`;break}i||(i=`${d}:${o}`);}}i||(i=`127.0.0.1:${o}`),a.info(`[LIOP-Router] Dynamic route: ${r} -> ${i} (PeerID: ${s})`);let a$1=new a$2.LogicMesh(i,c());return this.performTranscoding(e,a$1,r,n,s)}async performTranscoding(e,r,s,n,t){let o=s,c=this.meshNode?await this.meshNode.sign(Buffer.from(o)):Buffer.from([]),u=Date.now();return new Promise(i=>{r.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:o,proof_of_intent:c},async(f,m)=>{if(f||!m.accepted)return i({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`PQC Handshake Failed: ${f?.message||"Rejected"}`}],isError:true}});let{ciphertext:a,sharedSecret:l}=await a$3.encapsulateAsymmetric(m.kyber_public_key),p=JSON.stringify(n.arguments||{}),h=`return { "__liop_proxy_tool": "${s}", "__liop_proxy_args": ${p} };`,d=w.randomBytes(12),P=this.encryptWithNonce(Buffer.from(h),l,d),S=r.executeLogic({session_token:m.session_token,wasm_binary:new Uint8Array(P),inputs:{},pqc_ciphertext:a,aes_nonce:d}),v="",O=null;S.on("data",T=>{v+=T.semantic_evidence,O=T;}),S.on("end",async()=>{try{if(O&&!await this.verifier.verifyZkReceipt(Buffer.from(h),Buffer.from(O.cryptographic_proof).toString("hex"),Buffer.from(O.zk_receipt)))return i({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}});let T=JSON.parse(v),k=I.getInstance();k.record({type:"tool_call",method:"tools/call",toolName:s,peerId:t,estimatedInputTokens:k.countTokens(p),estimatedOutputTokens:k.countTokens(v),durationMs:Date.now()-u}),i({jsonrpc:"2.0",id:e,result:T});}catch{i({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:v}]}});}}),S.on("error",T=>i({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`LIOP gRPC Error: ${T.message}`}],isError:true}}));});})}encryptWithNonce(e,r,s){let n=w.createCipheriv("aes-256-gcm",r,s),t=Buffer.concat([n.update(e),n.final()]);return Buffer.concat([t,n.getAuthTag()])}};export{C as a,R as b,B as c,U as d,N as e,I as f,F as g};//# sourceMappingURL=chunk-7MAGL6ON.js.map
33
- //# sourceMappingURL=chunk-7MAGL6ON.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","LiopVerifier","peerId","state","now","failures","backoff","request","method","params","id","localTools","listedLocals","allTools","telemetry","toolsPayload","toolsResponsePayload","localResources","remoteResources","allResources","rlTelemetry","rlPayload","typedParams","rrStartTime","result","rrTelemetry","rrOutputPayload","targetUri","manifest","remoteResource","promptsList","plTelemetry","plPayload","pgStartTime","pgTelemetry","pgInputPayload","pgOutputPayload","silent","cachedAt","prevCount","acc","providerIds","MAX_COLD_ATTEMPTS","coldAttempt","attempt","selfId","activePeers","c","selfIdEnd","connectedPeers","b","aConnected","successCount","errorCount","cacheUpdated","eligiblePeers","cached","queryResults","EXPECTED_PROVIDERS","initialTimeoutMs","boundedTimeoutMs","deadline","stableCount","lastCacheSize","resolve","tools","seenNames","localToolNames","tool","finalName","providerName","baseDesc","cleanTool","blueprint","properties","envelopeDoc","originStamp","seenUris","resource","augmentedResource","parts","suffix","baseName","stats","providerCount","meshState","cachedTools","connections","bootstrapNodes","bootstrapCount","showBootstraps","bootstrapList","addr","routingTableSize","rawPeerId","localPeerId","cachedToolList","statusText","line","diagTelemetry","isLocal","target","providers","localStartTime","localTelemetry","localInputPayload","localOutputPayload","manifestEntry","grpcPort","addrs","targetAddr","os","localInterfaces","ipIdx","advertisedIp","remoteClient","liopV1","createChannelCredentials","client","capabilityHash","proofOfIntent","transcodingStartTime","response","ciphertext","sharedSecret","Kyber768Wrapper","embeddedArgsJson","proxyLogic","nonce","sealedLogic","call","resultBody","lastResponse","grpcRes","parsedResult","remoteTelemetry","e","payload","cipher","encryp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AAA,CAAG,CACvD,EACA,OAAA,CAAS,IACV,CACD,CAAC,CACF,EACD,CACD,EACD,CAAC,CACF,CAEQ,gBAAA,CACPC,CAAAA,CACAxL,EACA+K,CAAAA,CACS,CACT,IAAMU,CAAAA,CAAgB,CAAA,CAAA,cAAA,CAAe,aAAA,CAAezL,EAAK+K,CAAK,CAAA,CACxDW,CAAAA,CAAY,MAAA,CAAO,MAAA,CAAO,CAACD,EAAO,MAAA,CAAOD,CAAO,CAAA,CAAGC,CAAAA,CAAO,KAAA,EAAO,CAAC,CAAA,CACxE,OAAO,MAAA,CAAO,MAAA,CAAO,CAACC,CAAAA,CAAWD,EAAO,UAAA,EAAY,CAAC,CACtD,CACD","file":"chunk-7MAGL6ON.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 { LiopVerifier } from \"../crypto/verifier.js\";\nimport { TokenTelemetryEngine } from \"../economy/telemetry.js\";\nimport type { LiopManifest, MeshNode } from \"../mesh/index.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport { liopV1 } from \"../rpc/proto.js\";\nimport { createChannelCredentials } from \"../rpc/tls.js\";\nimport type { IntentResponse, LogicResponse } from \"../rpc/types.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport type { McpRequest, McpResponse } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\nimport {\n\tmcpCompactToolDescriptions,\n\tstripVerboseLiopToolDescription,\n} from \"../utils/mcpCompact.js\";\n\n/**\n * Time-to-live for cached manifests (seconds).\n * Aligned with libp2p Kademlia DHT TABLE_REFRESH_INTERVAL (5 minutes).\n * Provider records in the DHT are valid for 48 hours (PROVIDERS_VALIDITY),\n * so 300s is a conservative, network-friendly value.\n */\nconst MANIFEST_CACHE_TTL_S = 300;\n\n/** Maximum number of DHT query retries for manifest discovery */\nconst MANIFEST_DISCOVERY_RETRIES = 5;\n\n/**\n * LIOP MCP Router\n *\n * Core logic for routing MCP requests to local or remote LIOP providers.\n * Decoupled from transport (HTTP/Stdio).\n *\n * All tool discovery and port resolution is DYNAMIC via the\n * /liop/manifest/1.0.0 protocol stream over Kademlia DHT.\n */\nexport class LiopMcpRouter {\n\t/** Cached manifests from remote peers. Key = PeerID */\n\tprivate manifestCache: Map<\n\t\tstring,\n\t\t{ manifest: LiopManifest; cachedAt: number }\n\t> = new Map();\n\n\t/** Guards against concurrent discovery storms */\n\tprivate currentDiscovery: Promise<void> | null = null;\n\n\t/** Verifier for Tier-0 integrity checks */\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\n\t/** Callback when new remote tools are discovered */\n\tpublic onToolsChanged?: () => void;\n\n\t/** Circuit-breaker state for peers that repeatedly fail manifest queries. */\n\tprivate manifestFailureState: Map<\n\t\tstring,\n\t\t{ failures: number; cooldownUntil: number; lastSkipLogAt: number }\n\t> = new Map();\n\n\tprivate static readonly MANIFEST_FAILURE_BASE_COOLDOWN_MS = 15_000;\n\tprivate static readonly MANIFEST_FAILURE_MAX_COOLDOWN_MS = 5 * 60_000;\n\tprivate static readonly MANIFEST_SKIP_LOG_THROTTLE_MS = 30_000;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\tprivate defaultRpcPort = 50051,\n\t) {\n\t\t// Auto-register manifest handler if mesh node is provided\n\t\tif (this.meshNode) {\n\t\t\tthis.meshNode.registerManifestHandler(() => {\n\t\t\t\tconst remoteTools = this.liopServer.listTools().map((t) => ({\n\t\t\t\t\tname: t.name,\n\t\t\t\t\tdescription: t.description,\n\t\t\t\t\tinputSchema: t.inputSchema as Record<string, unknown>,\n\t\t\t\t}));\n\n\t\t\t\tconst resources = this.liopServer.listResources().map((r) => ({\n\t\t\t\t\tname: r.name,\n\t\t\t\t\turi: r.uri,\n\t\t\t\t\tdescription: r.description,\n\t\t\t\t\tmimeType: r.mimeType,\n\t\t\t\t}));\n\n\t\t\t\treturn {\n\t\t\t\t\tpeerId: this.meshNode?.getPeerId() || \"unknown\",\n\t\t\t\t\tgrpcPort: this.defaultRpcPort,\n\t\t\t\t\ttools: [...remoteTools],\n\t\t\t\t\tresources,\n\t\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t\t};\n\t\t\t});\n\n\t\t\t// Proactively announce manifest capability to the mesh\n\t\t\tthis.meshNode.announceManifest().catch((err: unknown) => {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Failed to announce manifest: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t}\n\n\t\t// [OWASP-A01] Startup warning when diagnostic level exposes full topology\n\t\tif (process.env.LIOP_DIAGNOSTIC_LEVEL === \"full\") {\n\t\t\tprocess.stderr.write(\n\t\t\t\t\"⚠️ [LIOP-Security] Diagnostic level set to FULL — \" +\n\t\t\t\t\t\"PeerIDs and network topology are exposed. Do NOT use in production.\\n\",\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate shouldSkipManifestQuery(peerId: string): boolean {\n\t\tconst state = this.manifestFailureState.get(peerId);\n\t\tif (!state) return false;\n\t\tconst now = Date.now();\n\t\tif (now >= state.cooldownUntil) return false;\n\n\t\tif (\n\t\t\tnow - state.lastSkipLogAt >\n\t\t\tLiopMcpRouter.MANIFEST_SKIP_LOG_THROTTLE_MS\n\t\t) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Router] Skipping manifest query for ${peerId} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1000)}s remaining)`,\n\t\t\t);\n\t\t\tstate.lastSkipLogAt = now;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate recordManifestQuerySuccess(peerId: string): void {\n\t\tthis.manifestFailureState.delete(peerId);\n\t}\n\n\tprivate recordManifestQueryFailure(peerId: string): void {\n\t\tconst now = Date.now();\n\t\tconst prev = this.manifestFailureState.get(peerId);\n\t\tconst failures = (prev?.failures || 0) + 1;\n\t\tconst backoff = Math.min(\n\t\t\tLiopMcpRouter.MANIFEST_FAILURE_BASE_COOLDOWN_MS *\n\t\t\t\t2 ** Math.max(0, failures - 1),\n\t\t\tLiopMcpRouter.MANIFEST_FAILURE_MAX_COOLDOWN_MS,\n\t\t);\n\t\tthis.manifestFailureState.set(peerId, {\n\t\t\tfailures,\n\t\t\tcooldownUntil: now + backoff,\n\t\t\tlastSkipLogAt: 0,\n\t\t});\n\t}\n\n\tpublic async dispatch(request: McpRequest): Promise<McpResponse | null> {\n\t\tconst { method, params, id } = request;\n\t\tlog.info(`[LIOP-Router] Processing: ${method}`);\n\n\t\tswitch (method) {\n\t\t\tcase \"initialize\":\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\t\t\tcapabilities: {\n\t\t\t\t\t\t\ttools: { listChanged: true },\n\t\t\t\t\t\t\tresources: { listChanged: true },\n\t\t\t\t\t\t\tprompts: { listChanged: true },\n\t\t\t\t\t\t},\n\t\t\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\tcase \"notifications/initialized\":\n\t\t\t\t// Cloud MCP clients often fire tools/list immediately; kick discovery early\n\t\t\t\t// so manifests populate before (or right after) that call completes.\n\t\t\t\tthis.kickDiscoveryAfterInitialized().catch(() => {});\n\t\t\t\treturn null;\n\t\t\tcase \"notifications/cancelled\":\n\t\t\t\treturn null; // No-op for MCP spec compliance\n\t\t\tcase \"ping\":\n\t\t\t\treturn { jsonrpc: \"2.0\", id, result: {} };\n\t\t\tcase \"tools/list\": {\n\t\t\t\tconst localTools = this.liopServer.listTools();\n\t\t\t\tconst remoteTools = await this.getRemoteTools();\n\n\t\t\t\tconst listedLocals = mcpCompactToolDescriptions()\n\t\t\t\t\t? localTools.map((t) => ({\n\t\t\t\t\t\t\t...t,\n\t\t\t\t\t\t\tdescription: stripVerboseLiopToolDescription(t.description ?? \"\"),\n\t\t\t\t\t\t}))\n\t\t\t\t\t: localTools;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] tools/list: ${localTools.length} local, ${remoteTools.length} remote tools found`,\n\t\t\t\t);\n\n\t\t\t\t// Inject a mandatory static diagnostic tool.\n\t\t\t\t// This ensures that the {tools: []} list is never empty on startup.\n\t\t\t\t// Claude Desktop silently hides the connector if it receives an empty array initially,\n\t\t\t\t// which broke the UX due to the ~3s warm-up time of the Kademlia DHT.\n\t\t\t\tconst diagnosticTool = {\n\t\t\t\t\tname: \"LiopMeshStatus\",\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.\",\n\t\t\t\t\tinputSchema: {\n\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\tproperties: {},\n\t\t\t\t\t\tadditionalProperties: false,\n\t\t\t\t\t},\n\t\t\t\t};\n\n\t\t\t\tconst allTools = [diagnosticTool, ...listedLocals, ...remoteTools];\n\n\t\t\t\t// [Token Economy] Record telemetry for the tools/list response\n\t\t\t\tconst telemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst toolsPayload = JSON.stringify(allTools);\n\t\t\t\tconst toolsResponsePayload = JSON.stringify({ tools: allTools });\n\t\t\t\ttelemetry.record({\n\t\t\t\t\ttype: \"tools_list\",\n\t\t\t\t\tmethod: \"tools/list\",\n\t\t\t\t\testimatedInputTokens: telemetry.countTokens(toolsPayload),\n\t\t\t\t\testimatedOutputTokens: telemetry.countTokens(toolsResponsePayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: {\n\t\t\t\t\t\ttools: allTools,\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"tools/call\":\n\t\t\t\treturn this.transcodeMcpToLiop(id, params as Record<string, unknown>);\n\t\t\tcase \"resources/list\": {\n\t\t\t\tconst localResources = this.liopServer.listResources();\n\t\t\t\tconst remoteResources = await this.getRemoteResources();\n\t\t\t\tconst allResources = [...localResources, ...remoteResources];\n\n\t\t\t\t// [Token Economy] Record resources/list telemetry\n\t\t\t\tconst rlTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst rlPayload = JSON.stringify(allResources);\n\t\t\t\trlTelemetry.record({\n\t\t\t\t\ttype: \"resource_list\",\n\t\t\t\t\tmethod: \"resources/list\",\n\t\t\t\t\testimatedInputTokens: 0,\n\t\t\t\t\testimatedOutputTokens: rlTelemetry.countTokens(rlPayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: { resources: allResources },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"resources/read\": {\n\t\t\t\tconst typedParams = params as { uri?: string } | undefined;\n\t\t\t\tif (!typedParams?.uri)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: { code: -32602, message: \"Missing resource uri\" },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst rrStartTime = Date.now();\n\t\t\t\t\tconst result = await this.liopServer.readResource(typedParams.uri);\n\n\t\t\t\t\t// [Token Economy] Record resources/read telemetry\n\t\t\t\t\tconst rrTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\tconst rrOutputPayload = JSON.stringify(result);\n\t\t\t\t\trrTelemetry.record({\n\t\t\t\t\t\ttype: \"resource_read\",\n\t\t\t\t\t\tmethod: \"resources/read\",\n\t\t\t\t\t\ttoolName: typedParams.uri,\n\t\t\t\t\t\testimatedInputTokens: rrTelemetry.countTokens(typedParams.uri),\n\t\t\t\t\t\testimatedOutputTokens: rrTelemetry.countTokens(rrOutputPayload),\n\t\t\t\t\t\tdurationMs: Date.now() - rrStartTime,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\t// Fallback: Resolve remotely from manifest cache\n\t\t\t\t\tconst targetUri = typedParams.uri;\n\t\t\t\t\tfor (const { manifest } of this.manifestCache.values()) {\n\t\t\t\t\t\tconst remoteResource = manifest.resources.find(\n\t\t\t\t\t\t\t(r) => r.uri === targetUri,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (remoteResource) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] Resolved resource ${targetUri} from cache (Peer: ${manifest.peerId})`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\tcontents: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\turi: remoteResource.uri,\n\t\t\t\t\t\t\t\t\t\t\tmimeType: remoteResource.mimeType || \"text/plain\",\n\t\t\t\t\t\t\t\t\t\t\ttext:\n\t\t\t\t\t\t\t\t\t\t\t\tremoteResource.text ||\n\t\t\t\t\t\t\t\t\t\t\t\tremoteResource.description ||\n\t\t\t\t\t\t\t\t\t\t\t\t\"No content provided\",\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase \"prompts/list\": {\n\t\t\t\tconst promptsList = this.liopServer.listPrompts();\n\n\t\t\t\t// [Token Economy] Record prompts/list telemetry\n\t\t\t\tconst plTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst plPayload = JSON.stringify(promptsList);\n\t\t\t\tplTelemetry.record({\n\t\t\t\t\ttype: \"prompt_list\",\n\t\t\t\t\tmethod: \"prompts/list\",\n\t\t\t\t\testimatedInputTokens: 0,\n\t\t\t\t\testimatedOutputTokens: plTelemetry.countTokens(plPayload),\n\t\t\t\t});\n\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\tresult: { prompts: promptsList },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcase \"prompts/get\": {\n\t\t\t\tconst typedParams = params as\n\t\t\t\t\t| { name?: string; arguments?: Record<string, string> }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (!typedParams?.name)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: { code: -32602, message: \"Missing prompt name\" },\n\t\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tconst pgStartTime = Date.now();\n\t\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\t\tname: typedParams.name as string,\n\t\t\t\t\t\targuments: typedParams.arguments || {},\n\t\t\t\t\t});\n\n\t\t\t\t\t// [Token Economy] Record prompts/get telemetry\n\t\t\t\t\tconst pgTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\tconst pgInputPayload = JSON.stringify({\n\t\t\t\t\t\tname: typedParams.name,\n\t\t\t\t\t\targuments: typedParams.arguments,\n\t\t\t\t\t});\n\t\t\t\t\tconst pgOutputPayload = JSON.stringify(result);\n\t\t\t\t\tpgTelemetry.record({\n\t\t\t\t\t\ttype: \"prompt_get\",\n\t\t\t\t\t\tmethod: \"prompts/get\",\n\t\t\t\t\t\ttoolName: typedParams.name,\n\t\t\t\t\t\testimatedInputTokens: pgTelemetry.countTokens(pgInputPayload),\n\t\t\t\t\t\testimatedOutputTokens: pgTelemetry.countTokens(pgOutputPayload),\n\t\t\t\t\t\tdurationMs: Date.now() - pgStartTime,\n\t\t\t\t\t});\n\n\t\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\tid,\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t},\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\terror: { code: -32601, message: `Method not found: ${method}` },\n\t\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * MCP clients often send notifications/initialized then immediately tools/list.\n\t * Start manifest discovery without blocking the notification handler.\n\t */\n\tprivate kickDiscoveryAfterInitialized(): Promise<void> {\n\t\treturn (async () => {\n\t\t\tawait new Promise((r) => setTimeout(r, 250));\n\t\t\tawait Promise.race([\n\t\t\t\tthis.refreshManifestCache(true),\n\t\t\t\tnew Promise<void>((r) => setTimeout(r, 15_000)),\n\t\t\t]).catch(() => {});\n\t\t})();\n\t}\n\n\t/**\n\t * Discovers and caches manifests from all remote LIOP providers in the mesh.\n\t * Uses Kademlia DHT to find \"liop:manifest\" providers, then opens\n\t * /liop/manifest/1.0.0 protocol streams to retrieve their full metadata.\n\t */\n\tpublic async refreshManifestCache(silent = false): Promise<void> {\n\t\tif (!this.meshNode) return;\n\t\tif (this.currentDiscovery) return this.currentDiscovery;\n\n\t\t// Fast-path: Skip DHT query entirely when cache is fresh and populated.\n\t\t// Only background polls (silent=true) should bypass this to detect new nodes.\n\t\t// Foreground requests (tools/list, tools/call) can safely reuse valid cache.\n\t\tif (!silent && this.manifestCache.size > 0) {\n\t\t\tconst now = Date.now();\n\t\t\tconst allFresh = Array.from(this.manifestCache.values()).every(\n\t\t\t\t({ cachedAt }) => now - cachedAt < MANIFEST_CACHE_TTL_S * 1000,\n\t\t\t);\n\t\t\tif (allFresh) return;\n\t\t}\n\n\t\tthis.currentDiscovery = (async () => {\n\t\t\ttry {\n\t\t\t\tconst prevCount = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t\t0,\n\t\t\t\t);\n\n\t\t\t\t// Phase 0: Wait for at least one active connection if mesh is empty (Cold Start)\n\t\t\t\tif (this.manifestCache.size === 0) {\n\t\t\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\t\t\tconst connections =\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal nodes for connection count\n\t\t\t\t\t\t\t(this.meshNode as any).node?.getConnections().length || 0;\n\t\t\t\t\t\tif (connections > 0) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] P2P Connection established. Starting discovery...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Waiting for P2P connections (attempt ${i + 1}/10)...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Phase 1: Try DHT discovery + Fallback loop\n\t\t\t\tlet providerIds: string[] = [];\n\t\t\t\tconst MAX_COLD_ATTEMPTS = this.manifestCache.size === 0 ? 5 : 1;\n\n\t\t\t\tfor (\n\t\t\t\t\tlet coldAttempt = 0;\n\t\t\t\t\tcoldAttempt < MAX_COLD_ATTEMPTS;\n\t\t\t\t\tcoldAttempt++\n\t\t\t\t) {\n\t\t\t\t\t// 1.1 Try DHT discovery\n\t\t\t\t\tfor (\n\t\t\t\t\t\tlet attempt = 0;\n\t\t\t\t\t\tattempt < MANIFEST_DISCOVERY_RETRIES;\n\t\t\t\t\t\tattempt++\n\t\t\t\t\t) {\n\t\t\t\t\t\tproviderIds =\n\t\t\t\t\t\t\t(await this.meshNode?.discoverManifestProviders()) || [];\n\t\t\t\t\t\tconst selfId = this.meshNode?.getPeerId();\n\t\t\t\t\t\tconst remoteIds = providerIds.filter((id) => id !== selfId);\n\t\t\t\t\t\tif (remoteIds.length > 0) break;\n\t\t\t\t\t\tif (attempt < MANIFEST_DISCOVERY_RETRIES - 1) {\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Router] DHT discovery attempt ${attempt + 1}/${MANIFEST_DISCOVERY_RETRIES}...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t// 1.2 Aggressively merge all active connections to bypass DHT propagation delays\n\t\t\t\t\tconst activePeers =\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t\t(this.meshNode as any).node\n\t\t\t\t\t\t\t?.getConnections()\n\t\t\t\t\t\t\t.map((c: { remotePeer: { toString: () => string } }) =>\n\t\t\t\t\t\t\t\tc.remotePeer.toString(),\n\t\t\t\t\t\t\t) || [];\n\n\t\t\t\t\tif (activePeers.length > 0) {\n\t\t\t\t\t\tproviderIds = Array.from(new Set([...providerIds, ...activePeers]));\n\t\t\t\t\t}\n\n\t\t\t\t\tconst selfIdEnd = this.meshNode?.getPeerId();\n\t\t\t\t\tconst remoteIdsEnd = providerIds.filter((id) => id !== selfIdEnd);\n\t\t\t\t\tif (remoteIdsEnd.length > 0) break;\n\n\t\t\t\t\tif (coldAttempt < MAX_COLD_ATTEMPTS - 1) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${coldAttempt + 1}/${MAX_COLD_ATTEMPTS})...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait new Promise((r) => setTimeout(r, 1000));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (providerIds.length === 0) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Router] No manifest providers found after all attempts.`,\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!silent) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Router] Discovered ${providerIds.length} candidate manifest providers`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// Prioritize already-connected peers to avoid blocking on stale providers.\n\t\t\t\t// This improves first tools/list latency on Linux/Ubuntu while preserving\n\t\t\t\t// full discovery for slower peers in subsequent refresh cycles.\n\t\t\t\tconst connectedPeers = new Set<string>(\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: internal node access for fast peer ordering\n\t\t\t\t\t((this.meshNode as any).node?.getConnections?.() || []).map(\n\t\t\t\t\t\t(c: { remotePeer: { toString: () => string } }) =>\n\t\t\t\t\t\t\tc.remotePeer.toString(),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tproviderIds = [...providerIds].sort((a, b) => {\n\t\t\t\t\tconst aConnected = connectedPeers.has(a) ? 1 : 0;\n\t\t\t\t\tconst bConnected = connectedPeers.has(b) ? 1 : 0;\n\t\t\t\t\treturn bConnected - aConnected;\n\t\t\t\t});\n\n\t\t\t\tlet successCount = 0;\n\t\t\t\tlet errorCount = 0;\n\t\t\t\tlet cacheUpdated = false;\n\n\t\t\t\t// Filter peers eligible for querying\n\t\t\t\tconst selfId = this.meshNode?.getPeerId();\n\t\t\t\tconst eligiblePeers = providerIds.filter((peerId) => {\n\t\t\t\t\tif (!this.meshNode) return false;\n\t\t\t\t\tif (peerId === selfId) return false;\n\t\t\t\t\tif (this.shouldSkipManifestQuery(peerId)) return false;\n\t\t\t\t\tconst cached = this.manifestCache.get(peerId);\n\t\t\t\t\tif (\n\t\t\t\t\t\tcached &&\n\t\t\t\t\t\tDate.now() - cached.cachedAt < MANIFEST_CACHE_TTL_S * 1000\n\t\t\t\t\t) {\n\t\t\t\t\t\tsuccessCount++;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t});\n\n\t\t\t\t// Parallel manifest queries — eliminates sequential 100ms + retry delays\n\t\t\t\tconst queryResults = await Promise.allSettled(\n\t\t\t\t\teligiblePeers.map(async (peerId) => {\n\t\t\t\t\t\tif (!this.meshNode) return null;\n\t\t\t\t\t\tlog.info(`[LIOP-Router] Querying manifest from: ${peerId}`);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\tmanifest: await this.meshNode.queryManifest(peerId),\n\t\t\t\t\t\t};\n\t\t\t\t\t}),\n\t\t\t\t);\n\n\t\t\t\tfor (const result of queryResults) {\n\t\t\t\t\tif (result.status === \"fulfilled\" && result.value?.manifest) {\n\t\t\t\t\t\tconst { peerId, manifest } = result.value;\n\t\t\t\t\t\tthis.manifestCache.set(peerId, {\n\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\tcachedAt: Date.now(),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.recordManifestQuerySuccess(peerId);\n\t\t\t\t\t\tcacheUpdated = true;\n\t\t\t\t\t\tsuccessCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Manifest received from ${peerId} (${manifest.tools.length} tools)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (result.status === \"fulfilled\" && result.value) {\n\t\t\t\t\t\tthis.recordManifestQueryFailure(result.value.peerId);\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Manifest query returned NULL for ${result.value.peerId}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} else if (result.status === \"rejected\") {\n\t\t\t\t\t\terrorCount++;\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Router] Fatal error querying manifest:`,\n\t\t\t\t\t\t\tresult.reason instanceof Error\n\t\t\t\t\t\t\t\t? result.reason.message\n\t\t\t\t\t\t\t\t: String(result.reason),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Store discovery stats for LiopMeshStatus diagnostics\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: private stats for telemetry\n\t\t\t\t(this as any)._discoveryStats = {\n\t\t\t\t\tcandidates: providerIds.length,\n\t\t\t\t\tsuccess: successCount,\n\t\t\t\t\tfailures: errorCount,\n\t\t\t\t\tlastDiscovery: Date.now(),\n\t\t\t\t};\n\n\t\t\t\tif (cacheUpdated) {\n\t\t\t\t\tconst newCount = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t\t\t0,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (newCount !== prevCount && this.onToolsChanged) {\n\t\t\t\t\t\tprocess.stderr.write(\n\t\t\t\t\t\t\t\"[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.\\n\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.onToolsChanged();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis.currentDiscovery = null;\n\t\t\t}\n\t\t})();\n\n\t\treturn this.currentDiscovery;\n\t}\n\n\t/**\n\t * Returns the current manifest cache size for external telemetry.\n\t * Used by the adaptive polling system to detect topology stabilization.\n\t */\n\tpublic getCacheSize(): number {\n\t\treturn this.manifestCache.size;\n\t}\n\n\t/**\n\t * Returns all remote tools discovered via the manifest protocol.\n\t */\n\tprivate async getRemoteTools(): Promise<\n\t\tArray<{\n\t\t\tname: string;\n\t\t\tdescription?: string;\n\t\t\tinputSchema?: Record<string, unknown>;\n\t\t}>\n\t> {\n\t\tconst EXPECTED_PROVIDERS = Number.parseInt(\n\t\t\tprocess.env.LIOP_EXPECTED_PROVIDERS ?? \"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\t// biome-ignore lint/suspicious/noExplicitAny: MCP JSON-RPC params/id are polymorphic\n\tprivate async transcodeMcpToLiop(id: any, params: any): Promise<any> {\n\t\tconst toolName = params.name;\n\n\t\t// Intercept the static diagnostic tool\n\t\tif (toolName === \"LiopMeshStatus\") {\n\t\t\t// [INDUSTRIAL-FIX] Proactive warm-up: request a refresh when status is called.\n\t\t\t// This ensures that even if the DHT was cold, the next status call (or tools/list)\n\t\t\t// will have data.\n\t\t\tthis.refreshManifestCache(true).catch(() => {});\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: private stats for telemetry\n\t\t\tconst stats = (this as any)._discoveryStats || {\n\t\t\t\tcandidates: 0,\n\t\t\t\tsuccess: 0,\n\t\t\t\tfailures: 0,\n\t\t\t};\n\t\t\tconst providerCount = this.manifestCache.size;\n\t\t\tconst meshState = this.meshNode ? \"Active\" : \"Offline\";\n\t\t\tconst cachedTools = Array.from(this.manifestCache.values()).reduce(\n\t\t\t\t(acc, { manifest }) => acc + manifest.tools.length,\n\t\t\t\t0,\n\t\t\t);\n\t\t\tconst connections = this.meshNode\n\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t(this.meshNode as any).node?.getConnections().length\n\t\t\t\t: 0;\n\n\t\t\tconst bootstrapNodes: string[] =\n\t\t\t\tthis.meshNode &&\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal config\n\t\t\t\t(this.meshNode as any).config?.bootstrapNodes\n\t\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal config\n\t\t\t\t\t\t(this.meshNode as any).config.bootstrapNodes\n\t\t\t\t\t: [];\n\t\t\tconst bootstrapCount = bootstrapNodes.length;\n\n\t\t\tconst diagLevel = process.env.LIOP_DIAGNOSTIC_LEVEL || \"redacted\";\n\t\t\tconst showBootstraps = diagLevel !== \"minimal\";\n\n\t\t\tconst bootstrapList = showBootstraps\n\t\t\t\t? bootstrapNodes\n\t\t\t\t\t\t.map((addr) => {\n\t\t\t\t\t\t\tconst parts = addr.split(\"/\");\n\t\t\t\t\t\t\tconst id = parts[parts.length - 1];\n\t\t\t\t\t\t\treturn ` • ${id ? id.slice(-8) : \"Unknown\"} (bootstrap)`;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t: \"\";\n\n\t\t\tconst routingTableSize = this.meshNode\n\t\t\t\t? // biome-ignore lint/suspicious/noExplicitAny: access internal nodes\n\t\t\t\t\t(this.meshNode as any).getRoutingTableSize()\n\t\t\t\t: 0;\n\n\t\t\tconst rawPeerId = this.meshNode?.getPeerId() || \"Offline\";\n\t\t\tconst localPeerId =\n\t\t\t\trawPeerId === \"Offline\" ? rawPeerId : this.redactPeerId(rawPeerId);\n\n\t\t\tconst cachedToolList = Array.from(this.manifestCache.entries())\n\t\t\t\t.flatMap(([peerId, { manifest }]) =>\n\t\t\t\t\tmanifest.tools.map(\n\t\t\t\t\t\t(t) => ` • ${t.name} (from origin: ${this.redactPeerId(peerId)})`,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.join(\"\\n\");\n\n\t\t\tconst statusText = [\n\t\t\t\t`LIOP Mesh Status: ${meshState === \"Active\" ? \"Active\" : \"Offline\"}`,\n\t\t\t\t`Local Agent Identity: ${localPeerId}`,\n\t\t\t\t`Network: ${connections} Conns | ${routingTableSize} Mesh Nodes | ${bootstrapCount} Bootstraps`,\n\t\t\t\tshowBootstraps && bootstrapCount > 0\n\t\t\t\t\t? `\\nActive Bootstraps:\\n${bootstrapList}\\n`\n\t\t\t\t\t: \"\",\n\t\t\t\t`Discovery: ${stats.candidates} Candidates | ${stats.success} OK | ${stats.failures} FAIL`,\n\t\t\t\t`Tooling: ${providerCount} Providers | ${cachedTools} Total Remote Tools`,\n\t\t\t\tcachedTools > 0\n\t\t\t\t\t? `\\nDiscovered Remote Tools (Zero-Trust Origins):\\n${cachedToolList}`\n\t\t\t\t\t: \"\\nNo remote tools discovered yet.\",\n\t\t\t\t// [Token Economy] Telemetry block (only appears when operations exist)\n\t\t\t\tTokenTelemetryEngine.getInstance().formatStatusBlock(),\n\t\t\t]\n\t\t\t\t.filter((line) => line !== \"\")\n\t\t\t\t.join(\"\\n\");\n\n\t\t\t// [Token Economy] Record diagnostic output telemetry\n\t\t\tconst diagTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\tdiagTelemetry.record({\n\t\t\t\ttype: \"diagnostic\",\n\t\t\t\tmethod: \"tools/call\",\n\t\t\t\ttoolName: \"LiopMeshStatus\",\n\t\t\t\testimatedInputTokens: 0,\n\t\t\t\testimatedOutputTokens: diagTelemetry.countTokens(statusText),\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\tresult: {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: statusText,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\tconst isLocal = this.liopServer\n\t\t\t.listTools()\n\t\t\t.some((t) => t.name === toolName);\n\n\t\tif (!isLocal && this.meshNode) {\n\t\t\t// Phase 1: Cache-first — resolve directly from cached manifests (zero-latency)\n\t\t\t// Per MCP spec, tools don't change between notifications/tools/list_changed.\n\t\t\tlet target = this.resolveManifestTarget(toolName);\n\n\t\t\t// Phase 2: If not cached, trigger DHT refresh and retry\n\t\t\tif (!target) {\n\t\t\t\tawait this.refreshManifestCache();\n\t\t\t\ttarget = this.resolveManifestTarget(toolName);\n\t\t\t}\n\n\t\t\tif (target) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Router] Resolved ${toolName} via manifest cache (Peer: ${target.peerId}, Original: ${target.originalToolName})`,\n\t\t\t\t);\n\t\t\t\treturn this.routeToRemoteProvider(\n\t\t\t\t\tid,\n\t\t\t\t\ttarget.originalToolName,\n\t\t\t\t\ttarget.peerId,\n\t\t\t\t\tparams,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Phase 2: Try DHT-based dynamic provider discovery (fallback for unsuffixed names)\n\t\t\tlet providers: string[] = [];\n\t\t\tfor (let i = 0; i < 3; i++) {\n\t\t\t\tproviders = await this.meshNode.findProviders(toolName);\n\t\t\t\tif (providers.length > 0) break;\n\t\t\t\tif (i < 2) await new Promise((r) => setTimeout(r, 1000));\n\t\t\t}\n\n\t\t\tif (providers.length > 0) {\n\t\t\t\treturn this.routeToRemoteProvider(id, toolName, providers[0], params);\n\t\t\t}\n\t\t}\n\n\t\t// If no remote provider found, try local execution\n\t\tif (isLocal) {\n\t\t\ttry {\n\t\t\t\tconst localStartTime = Date.now();\n\t\t\t\tconst result = await this.liopServer.callTool({\n\t\t\t\t\tname: toolName,\n\t\t\t\t\targuments: params.arguments || {},\n\t\t\t\t});\n\n\t\t\t\t// [Token Economy] Record local tool call telemetry\n\t\t\t\tconst localTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\tconst localInputPayload = JSON.stringify(params.arguments || {});\n\t\t\t\tconst localOutputPayload = JSON.stringify(result);\n\t\t\t\tlocalTelemetry.record({\n\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\tmethod: \"tools/call\",\n\t\t\t\t\ttoolName,\n\t\t\t\t\testimatedInputTokens: localTelemetry.countTokens(localInputPayload),\n\t\t\t\t\testimatedOutputTokens: localTelemetry.countTokens(localOutputPayload),\n\t\t\t\t\tdurationMs: Date.now() - localStartTime,\n\t\t\t\t});\n\n\t\t\t\treturn { jsonrpc: \"2.0\", id, result };\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn {\n\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\tid,\n\t\t\t\t\terror: {\n\t\t\t\t\t\tcode: -32000,\n\t\t\t\t\t\tmessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tjsonrpc: \"2.0\",\n\t\t\tid,\n\t\t\terror: {\n\t\t\t\tcode: -32002,\n\t\t\t\tmessage: `No provider found for tool: ${toolName}. Ensure the provider node is active and connected to the mesh.`,\n\t\t\t},\n\t\t};\n\t}\n\n\tprivate async routeToRemoteProvider(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tid: any,\n\t\ttoolName: string,\n\t\tpeerId: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tparams: any,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t): Promise<any> {\n\t\tif (!this.meshNode)\n\t\t\treturn {\n\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\tid,\n\t\t\t\terror: { code: -32603, message: \"Mesh Node inactive\" },\n\t\t\t};\n\n\t\t// Dynamic gRPC port resolution from manifest cache\n\t\tlet manifestEntry = this.manifestCache.get(peerId);\n\t\tlet grpcPort = this.defaultRpcPort;\n\n\t\tif (manifestEntry) {\n\t\t\tgrpcPort = manifestEntry.manifest.grpcPort;\n\t\t} else {\n\t\t\t// Try to query the manifest directly\n\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\tif (manifest) {\n\t\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\t\tthis.manifestCache.set(peerId, {\n\t\t\t\t\tmanifest,\n\t\t\t\t\tcachedAt: Date.now(),\n\t\t\t\t});\n\t\t\t\tmanifestEntry = this.manifestCache.get(peerId);\n\t\t\t}\n\t\t}\n\n\t\t// Development-only convenience (opt-in):\n\t\t// Docker Desktop setups publish gRPC ports on the host as 13011/13021/13031.\n\t\t// This mapping is DISABLED in production (NODE_ENV=production) to enforce\n\t\t// dynamic port negotiation via the manifest protocol.\n\t\tconst isDevMode =\n\t\t\tprocess.env.NODE_ENV === \"development\" || process.env.NODE_ENV === \"test\";\n\t\tif (\n\t\t\tisDevMode &&\n\t\t\tmanifestEntry &&\n\t\t\tprocess.env.LIOP_USE_PUBLISHED_GRPC_PORTS === \"1\"\n\t\t) {\n\t\t\tconst providerName =\n\t\t\t\tmanifestEntry.manifest.serverInfo?.name?.toLowerCase() || \"\";\n\t\t\tif (providerName.includes(\"vault\")) grpcPort = 13011;\n\t\t\telse if (providerName.includes(\"bank\")) grpcPort = 13021;\n\t\t\telse if (providerName.includes(\"oracle\")) grpcPort = 13031;\n\t\t}\n\n\t\t// Resolve IP from active connections\n\t\tconst addrs = await this.meshNode.resolvePeer(peerId);\n\t\tlet targetAddr: string | null = null;\n\n\t\t// [LIOP-ALPHA] Check if the peer is running on the same physical machine\n\t\t// by comparing its advertised IPs against our local OS interfaces.\n\t\tconst os = await import(\"node:os\");\n\t\tconst localInterfaces = Object.values(os.networkInterfaces())\n\t\t\t.flat()\n\t\t\t.filter((i) => i?.family === \"IPv4\")\n\t\t\t.map((i) => i?.address);\n\n\t\t// Loop through all advertised addresses to find the optimal target\n\t\tfor (const addr of addrs) {\n\t\t\tconst parts = addr.split(\"/\");\n\t\t\tconst ipIdx = parts.indexOf(\"ip4\");\n\t\t\tif (ipIdx !== -1) {\n\t\t\t\tconst advertisedIp = parts[ipIdx + 1];\n\n\t\t\t\t// Loopback priority or Same-Machine detection\n\t\t\t\tif (\n\t\t\t\t\tadvertisedIp === \"127.0.0.1\" ||\n\t\t\t\t\tlocalInterfaces.includes(advertisedIp)\n\t\t\t\t) {\n\t\t\t\t\ttargetAddr = `127.0.0.1:${grpcPort}`;\n\t\t\t\t\tbreak; // Supreme priority for local execution\n\t\t\t\t}\n\n\t\t\t\t// Default to first discovered valid external IP\n\t\t\t\tif (!targetAddr) {\n\t\t\t\t\ttargetAddr = `${advertisedIp}:${grpcPort}`;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!targetAddr) {\n\t\t\t// Fallback to localhost with the dynamically resolved port\n\t\t\ttargetAddr = `127.0.0.1:${grpcPort}`;\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Router] Dynamic route: ${toolName} -> ${targetAddr} (PeerID: ${peerId})`,\n\t\t);\n\n\t\tconst remoteClient = new liopV1.LogicMesh(\n\t\t\ttargetAddr,\n\t\t\tcreateChannelCredentials(),\n\t\t);\n\t\treturn this.performTranscoding(id, remoteClient, toolName, params, peerId);\n\t}\n\n\tprivate async performTranscoding(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tid: any,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: gRPC client from dynamic proto-loader\n\t\tclient: any,\n\t\ttoolName: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t\tparams: any,\n\t\tpeerId?: string,\n\t\t// biome-ignore lint/suspicious/noExplicitAny: MCP polymorphic\n\t): Promise<any> {\n\t\tconst capabilityHash = toolName;\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(Buffer.from(capabilityHash))\n\t\t\t: Buffer.from([]);\n\n\t\tconst transcodingStartTime = Date.now();\n\n\t\treturn new Promise((resolve) => {\n\t\t\tclient.negotiateIntent(\n\t\t\t\t{\n\t\t\t\t\tagent_did: `did:liop:${this.meshNode?.getPeerId() || \"mcp-proxy\"}`,\n\t\t\t\t\tcapability_hash: capabilityHash,\n\t\t\t\t\tproof_of_intent: proofOfIntent,\n\t\t\t\t},\n\t\t\t\tasync (err: Error | null, response: IntentResponse) => {\n\t\t\t\t\tif (err || !response.accepted) {\n\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `PQC Handshake Failed: ${err?.message || \"Rejected\"}`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tconst { ciphertext, sharedSecret } =\n\t\t\t\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(\n\t\t\t\t\t\t\tresponse.kyber_public_key,\n\t\t\t\t\t\t);\n\t\t\t\t\t// SECURITY: Avoid AES-GCM nonce reuse across multiple ciphertexts.\n\t\t\t\t\t// We embed arguments directly into the proxy logic so we only encrypt ONE payload per session/nonce.\n\t\t\t\t\tconst embeddedArgsJson = JSON.stringify(params.arguments || {});\n\t\t\t\t\tconst proxyLogic = `return { \"__liop_proxy_tool\": \"${toolName}\", \"__liop_proxy_args\": ${embeddedArgsJson} };`;\n\t\t\t\t\tconst nonce = crypto.randomBytes(12);\n\n\t\t\t\t\tconst sealedLogic = this.encryptWithNonce(\n\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\tsharedSecret,\n\t\t\t\t\t\tnonce,\n\t\t\t\t\t);\n\n\t\t\t\t\tconst call = client.executeLogic({\n\t\t\t\t\t\tsession_token: response.session_token,\n\t\t\t\t\t\twasm_binary: new Uint8Array(sealedLogic),\n\t\t\t\t\t\tinputs: {},\n\t\t\t\t\t\tpqc_ciphertext: ciphertext,\n\t\t\t\t\t\taes_nonce: nonce,\n\t\t\t\t\t});\n\n\t\t\t\t\tlet resultBody = \"\";\n\t\t\t\t\tlet lastResponse: LogicResponse | null = null;\n\t\t\t\t\tcall.on(\"data\", (grpcRes: LogicResponse) => {\n\t\t\t\t\t\tresultBody += grpcRes.semantic_evidence;\n\t\t\t\t\t\tlastResponse = grpcRes;\n\t\t\t\t\t});\n\t\t\t\t\tcall.on(\"end\", async () => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (lastResponse) {\n\t\t\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t\t\tBuffer.from(proxyLogic),\n\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\t\t\tBuffer.from(lastResponse.zk_receipt),\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\t\t\treturn resolve({\n\t\t\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\t\t\ttext: \"SECURITY ALERT: Remote response failed cryptographic integrity audit.\",\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst parsedResult = JSON.parse(resultBody);\n\n\t\t\t\t\t\t\t// [Token Economy] Record remote tool call telemetry\n\t\t\t\t\t\t\tconst remoteTelemetry = TokenTelemetryEngine.getInstance();\n\t\t\t\t\t\t\tremoteTelemetry.record({\n\t\t\t\t\t\t\t\ttype: \"tool_call\",\n\t\t\t\t\t\t\t\tmethod: \"tools/call\",\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tpeerId,\n\t\t\t\t\t\t\t\testimatedInputTokens:\n\t\t\t\t\t\t\t\t\tremoteTelemetry.countTokens(embeddedArgsJson),\n\t\t\t\t\t\t\t\testimatedOutputTokens: remoteTelemetry.countTokens(resultBody),\n\t\t\t\t\t\t\t\tdurationMs: Date.now() - transcodingStartTime,\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tresolve({ jsonrpc: \"2.0\", id, result: parsedResult });\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\t\tresult: { content: [{ type: \"text\", text: resultBody }] },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tcall.on(\"error\", (e: Error) =>\n\t\t\t\t\t\tresolve({\n\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\tid,\n\t\t\t\t\t\t\tresult: {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{ type: \"text\", text: `LIOP gRPC Error: ${e.message}` },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tprivate encryptWithNonce(\n\t\tpayload: Buffer,\n\t\tkey: Uint8Array,\n\t\tnonce: Buffer,\n\t): Buffer {\n\t\tconst cipher = crypto.createCipheriv(\"aes-256-gcm\", key, nonce);\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\treturn Buffer.concat([encrypted, cipher.getAuthTag()]);\n\t}\n}\n"]}