@nekzus/liop 2.1.0-beta.3 → 2.1.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +12 -0
  2. package/dist/bin/agent.js +301 -4
  3. package/dist/bin/agent.js.map +1 -1
  4. package/dist/bridge.d.ts +2 -2
  5. package/dist/bridge.js +3 -1
  6. package/dist/chunk-2JLG4DET.js +3354 -0
  7. package/dist/chunk-2JLG4DET.js.map +1 -0
  8. package/dist/chunk-32ADSAJS.js +104 -0
  9. package/dist/chunk-32ADSAJS.js.map +1 -0
  10. package/dist/chunk-72MNYFR6.js +64 -0
  11. package/dist/chunk-72MNYFR6.js.map +1 -0
  12. package/dist/chunk-CT6NHSYP.js +30 -0
  13. package/dist/chunk-CT6NHSYP.js.map +1 -0
  14. package/dist/chunk-E5QBDD5E.js +469 -0
  15. package/dist/chunk-E5QBDD5E.js.map +1 -0
  16. package/dist/chunk-HB5DXX3Q.js +1976 -0
  17. package/dist/chunk-HB5DXX3Q.js.map +1 -0
  18. package/dist/chunk-IJHTRIZC.js +56 -0
  19. package/dist/chunk-IJHTRIZC.js.map +1 -0
  20. package/dist/chunk-J3WPBMJ5.js +332 -0
  21. package/dist/chunk-J3WPBMJ5.js.map +1 -0
  22. package/dist/chunk-NJRSFFD7.js +815 -0
  23. package/dist/chunk-NJRSFFD7.js.map +1 -0
  24. package/dist/chunk-OUUTDSOW.js +24 -0
  25. package/dist/chunk-OUUTDSOW.js.map +1 -0
  26. package/dist/chunk-PHTWUTY7.js +300 -0
  27. package/dist/chunk-PHTWUTY7.js.map +1 -0
  28. package/dist/chunk-QLCOEP5J.js +68 -0
  29. package/dist/chunk-QLCOEP5J.js.map +1 -0
  30. package/dist/chunk-RDWCGZ2A.js +87 -0
  31. package/dist/chunk-RDWCGZ2A.js.map +1 -0
  32. package/dist/chunk-RWRRBYG4.js +1 -0
  33. package/dist/chunk-UVO7DII3.js +463 -0
  34. package/dist/chunk-UVO7DII3.js.map +1 -0
  35. package/dist/client.d.ts +2 -2
  36. package/dist/client.js +8 -1
  37. package/dist/gateway.d.ts +2 -2
  38. package/dist/gateway.js +9 -1
  39. package/dist/{index-DO97j6hP.d.ts → index-BlGc0iym.d.ts} +10 -1
  40. package/dist/{index-Brfvxmdt.d.ts → index-qM8ZH8sC.d.ts} +1 -1
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +58 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/kyber-3ULIJSE3.js +3 -0
  45. package/dist/{kyber-NONMBQNH.js.map → kyber-3ULIJSE3.js.map} +1 -1
  46. package/dist/mesh.js +4 -1
  47. package/dist/server.d.ts +2 -2
  48. package/dist/server.js +6 -1
  49. package/dist/{types-DzEXgi4s.d.ts → types-sKeUxuky.d.ts} +4 -46
  50. package/dist/types.d.ts +1 -1
  51. package/dist/types.js +2 -1
  52. package/dist/verifier-3FAKCFNN.js +5 -0
  53. package/dist/{verifier-XU2DB56Z.js.map → verifier-3FAKCFNN.js.map} +1 -1
  54. package/dist/workers/logic-execution.js +255 -1
  55. package/dist/workers/logic-execution.js.map +1 -1
  56. package/dist/workers/zk-verifier.js +173 -1
  57. package/dist/workers/zk-verifier.js.map +1 -1
  58. package/package.json +74 -45
  59. package/dist/chunk-2MGFSIXN.js +0 -2
  60. package/dist/chunk-2MGFSIXN.js.map +0 -1
  61. package/dist/chunk-4C666HHU.js +0 -2
  62. package/dist/chunk-4C666HHU.js.map +0 -1
  63. package/dist/chunk-ANFXJGMP.js +0 -2
  64. package/dist/chunk-ANFXJGMP.js.map +0 -1
  65. package/dist/chunk-DBXGYHKY.js +0 -2
  66. package/dist/chunk-DBXGYHKY.js.map +0 -1
  67. package/dist/chunk-DQ6UW6L7.js +0 -2
  68. package/dist/chunk-DQ6UW6L7.js.map +0 -1
  69. package/dist/chunk-GI2LSJYZ.js +0 -13
  70. package/dist/chunk-GI2LSJYZ.js.map +0 -1
  71. package/dist/chunk-GJUZGKZW.js +0 -3
  72. package/dist/chunk-GJUZGKZW.js.map +0 -1
  73. package/dist/chunk-I46YEWND.js +0 -33
  74. package/dist/chunk-I46YEWND.js.map +0 -1
  75. package/dist/chunk-PWCXZWSE.js +0 -2
  76. package/dist/chunk-PWCXZWSE.js.map +0 -1
  77. package/dist/chunk-RYYRR4N5.js +0 -31
  78. package/dist/chunk-RYYRR4N5.js.map +0 -1
  79. package/dist/chunk-S6RJHZV2.js +0 -2
  80. package/dist/chunk-S6RJHZV2.js.map +0 -1
  81. package/dist/chunk-SB5XJXKV.js +0 -2
  82. package/dist/chunk-SB5XJXKV.js.map +0 -1
  83. package/dist/chunk-T3L6OCM3.js +0 -3
  84. package/dist/chunk-T3L6OCM3.js.map +0 -1
  85. package/dist/chunk-TYVG6TXQ.js +0 -2
  86. package/dist/chunk-TYVG6TXQ.js.map +0 -1
  87. package/dist/chunk-UCCGDGHE.js +0 -54
  88. package/dist/chunk-UCCGDGHE.js.map +0 -1
  89. package/dist/chunk-V5MKJT6S.js +0 -2
  90. package/dist/chunk-V5MKJT6S.js.map +0 -1
  91. package/dist/kyber-NONMBQNH.js +0 -2
  92. package/dist/verifier-XU2DB56Z.js +0 -2
@@ -1,2 +0,0 @@
1
- var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:true});};export{e as a};//# sourceMappingURL=chunk-4C666HHU.js.map
2
- //# sourceMappingURL=chunk-4C666HHU.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-4C666HHU.js"}
@@ -1,2 +0,0 @@
1
- import e from'crypto';var i=/^\s*@LIOP\{[^}]+\}\n?([\s\S]*?)\n?@END\s*$/;function f(t){let r=t.match(i);return r?.[1]!==void 0?r[1].trim():t.trim()}function c(t){if(t[0]===0&&t[1]===97)return e.createHash("sha256").update(t).digest();let n=Buffer.from(t).toString("utf-8"),s=f(n);return e.createHash("sha256").update(Buffer.from(s,"utf-8")).digest()}export{f as a,c as b};//# sourceMappingURL=chunk-ANFXJGMP.js.map
2
- //# sourceMappingURL=chunk-ANFXJGMP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/crypto/logic-image-id.ts"],"names":["TOP_LEVEL_ENVELOPE","normalizeLogicSource","logicUtf8","match","deriveLogicImageDigest","logicPayload","crypto","text","normalized"],"mappings":"sBAOA,IAAMA,CAAAA,CAAqB,4CAAA,CAEpB,SAASC,CAAAA,CAAqBC,CAAAA,CAA2B,CAC/D,IAAMC,EAAQD,CAAAA,CAAU,KAAA,CAAMF,CAAkB,CAAA,CAChD,OAAIG,CAAAA,GAAQ,CAAC,CAAA,GAAM,MAAA,CACXA,EAAM,CAAC,CAAA,CAAE,IAAA,EAAK,CAEfD,EAAU,IAAA,EAClB,CAGO,SAASE,EAAuBC,CAAAA,CAAkC,CAExE,GADeA,CAAAA,CAAa,CAAC,IAAM,CAAA,EAAQA,CAAAA,CAAa,CAAC,CAAA,GAAM,GAE9D,OAAOC,CAAAA,CAAO,UAAA,CAAW,QAAQ,EAAE,MAAA,CAAOD,CAAY,CAAA,CAAE,MAAA,GAEzD,IAAME,CAAAA,CAAO,MAAA,CAAO,IAAA,CAAKF,CAAY,CAAA,CAAE,QAAA,CAAS,OAAO,CAAA,CACjDG,EAAaP,CAAAA,CAAqBM,CAAI,CAAA,CAC5C,OAAOD,EACL,UAAA,CAAW,QAAQ,CAAA,CACnB,MAAA,CAAO,OAAO,IAAA,CAAKE,CAAAA,CAAY,OAAO,CAAC,CAAA,CACvC,QACH","file":"chunk-ANFXJGMP.js","sourcesContent":["import crypto from \"node:crypto\";\n\n/**\n * Top-level LIOP v1 envelope only. Must NOT use multiline (^/$) mode:\n * proxy logic embeds a full envelope inside JSON strings; `^` per line would\n * incorrectly treat that as the document root and desync ImageID vs the worker.\n */\nconst TOP_LEVEL_ENVELOPE = /^\\s*@LIOP\\{[^}]+\\}\\n?([\\s\\S]*?)\\n?@END\\s*$/;\n\nexport function normalizeLogicSource(logicUtf8: string): string {\n\tconst match = logicUtf8.match(TOP_LEVEL_ENVELOPE);\n\tif (match?.[1] !== undefined) {\n\t\treturn match[1].trim();\n\t}\n\treturn logicUtf8.trim();\n}\n\n/** SHA-256 digest of logic bytes (WASM raw; JS UTF-8 after top-level envelope strip). */\nexport function deriveLogicImageDigest(logicPayload: Uint8Array): Buffer {\n\tconst isWasm = logicPayload[0] === 0x00 && logicPayload[1] === 0x61;\n\tif (isWasm) {\n\t\treturn crypto.createHash(\"sha256\").update(logicPayload).digest();\n\t}\n\tconst text = Buffer.from(logicPayload).toString(\"utf-8\");\n\tconst normalized = normalizeLogicSource(text);\n\treturn crypto\n\t\t.createHash(\"sha256\")\n\t\t.update(Buffer.from(normalized, \"utf-8\"))\n\t\t.digest();\n}\n"]}
@@ -1,2 +0,0 @@
1
- import {createMlKem768}from'mlkem';var a=null;async function n(){return a||(a=await createMlKem768()),a}var m={importPublicKey(e){if(e.length!==1184)throw new Error(`Kyber768 Public Key must be exactly 1184 bytes (Received: ${e.length})`);return e},async encapsulateAsymmetric(e){try{if(e.length!==1184)throw new Error("Kyber768 Public Key must be exactly 1184 bytes.");let r=await n(),[t,c]=r.encap(e);return {ciphertext:t,sharedSecret:c}}catch(r){throw new Error(`Failed to perform PQC encapsulation: ${r.message}`)}},async generateKeyPair(){let e=await n(),[r,t]=e.generateKeyPair();return {publicKey:r,secretKey:t}},async decapsulateSymmetric(e,r){return (await n()).decap(e,r)}};export{m as a};//# sourceMappingURL=chunk-DBXGYHKY.js.map
2
- //# sourceMappingURL=chunk-DBXGYHKY.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/rpc/crypto/kyber.ts"],"names":["kemInstance","getKemInstance","createMlKem768","Kyber768Wrapper","buffer","publicKey","kem","ct","ss","error","pk","sk","ciphertext","secretKey"],"mappings":"mCAcA,IAAIA,CAAAA,CAAiE,IAAA,CAErE,eAAeC,CAAAA,EAAiB,CAC/B,OAAKD,CAAAA,GACJA,CAAAA,CAAc,MAAME,cAAAA,EAAe,CAAA,CAE7BF,CACR,CAEO,IAAMG,CAAAA,CAAkB,CAK9B,eAAA,CAAgBC,CAAAA,CAAgC,CAC/C,GAAIA,CAAAA,CAAO,MAAA,GAAW,IAAA,CACrB,MAAM,IAAI,KAAA,CACT,CAAA,0DAAA,EAA6DA,CAAAA,CAAO,MAAM,CAAA,CAAA,CAC3E,CAAA,CAED,OAAOA,CACR,CAAA,CAMA,MAAM,qBAAA,CAAsBC,CAAAA,CAGzB,CACF,GAAI,CACH,GAAIA,CAAAA,CAAU,MAAA,GAAW,IAAA,CACxB,MAAM,IAAI,KAAA,CAAM,iDAAiD,CAAA,CAGlE,IAAMC,CAAAA,CAAM,MAAML,CAAAA,EAAe,CAC3B,CAACM,CAAAA,CAAIC,CAAE,EAAIF,CAAAA,CAAI,KAAA,CAAMD,CAAS,CAAA,CAEpC,OAAO,CACN,UAAA,CAAYE,CAAAA,CACZ,YAAA,CAAcC,CACf,CACD,CAAA,MAASC,CAAAA,CAAO,CACf,MAAM,IAAI,KAAA,CACT,CAAA,qCAAA,EAAyCA,CAAAA,CAAgB,OAAO,CAAA,CACjE,CACD,CACD,CAAA,CAKA,MAAM,eAAA,EAGH,CACF,IAAMH,CAAAA,CAAM,MAAML,CAAAA,EAAe,CAC3B,CAACS,CAAAA,CAAIC,CAAE,CAAA,CAAIL,CAAAA,CAAI,eAAA,EAAgB,CACrC,OAAO,CACN,SAAA,CAAWI,CAAAA,CACX,SAAA,CAAWC,CACZ,CACD,CAAA,CAMA,MAAM,oBAAA,CACLC,CAAAA,CACAC,CAAAA,CACsB,CAEtB,OAAA,CADY,MAAMZ,CAAAA,EAAe,EACtB,KAAA,CAAMW,CAAAA,CAAYC,CAAS,CACvC,CACD","file":"chunk-DBXGYHKY.js","sourcesContent":["import { createMlKem768 } from \"mlkem\";\n\n/**\n * LIOP Post-Quantum Cryptography Wrapper\n * Implements ML-KEM-768 (NIST FIPS 203) for Zero-Trust secure key encapsulation\n * directly compatible with `pqcrypto-kyber` on the Mesh-Node Backend.\n *\n * Uses the `mlkem` package which provides:\n * - FIPS 203 compliance (ML-KEM standard)\n * - Constant-time validation (KyberSlash patched)\n * - ~3.5x performance improvement over legacy crystals-kyber\n */\n\n/** Lazy-initialized singleton for the ML-KEM-768 engine */\nlet kemInstance: Awaited<ReturnType<typeof createMlKem768>> | null = null;\n\nasync function getKemInstance() {\n\tif (!kemInstance) {\n\t\tkemInstance = await createMlKem768();\n\t}\n\treturn kemInstance;\n}\n\nexport const Kyber768Wrapper = {\n\t/**\n\t * Extracts and validates the 1184-byte Public Key from the Rust LIOP Data Node\n\t * @param buffer Raw buffer sent via gRPC IntentResponse\n\t */\n\timportPublicKey(buffer: Uint8Array): Uint8Array {\n\t\tif (buffer.length !== 1184) {\n\t\t\tthrow new Error(\n\t\t\t\t`Kyber768 Public Key must be exactly 1184 bytes (Received: ${buffer.length})`,\n\t\t\t);\n\t\t}\n\t\treturn buffer;\n\t},\n\n\t/**\n\t * Encapsulates a shared secret using the server's public key.\n\t * Returns the 1088-byte ciphertext to be sent back, and the 32-byte shared AES secret.\n\t */\n\tasync encapsulateAsymmetric(publicKey: Uint8Array): Promise<{\n\t\tciphertext: Uint8Array;\n\t\tsharedSecret: Uint8Array;\n\t}> {\n\t\ttry {\n\t\t\tif (publicKey.length !== 1184) {\n\t\t\t\tthrow new Error(\"Kyber768 Public Key must be exactly 1184 bytes.\");\n\t\t\t}\n\n\t\t\tconst kem = await getKemInstance();\n\t\t\tconst [ct, ss] = kem.encap(publicKey);\n\n\t\t\treturn {\n\t\t\t\tciphertext: ct,\n\t\t\t\tsharedSecret: ss,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to perform PQC encapsulation: ${(error as Error).message}`,\n\t\t\t);\n\t\t}\n\t},\n\n\t/**\n\t * Generates a Kyber768 KeyPair for the server to accept intents.\n\t */\n\tasync generateKeyPair(): Promise<{\n\t\tpublicKey: Uint8Array;\n\t\tsecretKey: Uint8Array;\n\t}> {\n\t\tconst kem = await getKemInstance();\n\t\tconst [pk, sk] = kem.generateKeyPair();\n\t\treturn {\n\t\t\tpublicKey: pk,\n\t\t\tsecretKey: sk,\n\t\t};\n\t},\n\n\t/**\n\t * Decapsulates the shared secret using the server's secret key.\n\t * Zero-fills the shared secret buffer after extraction for side-channel protection.\n\t */\n\tasync decapsulateSymmetric(\n\t\tciphertext: Uint8Array,\n\t\tsecretKey: Uint8Array,\n\t): Promise<Uint8Array> {\n\t\tconst kem = await getKemInstance();\n\t\treturn kem.decap(ciphertext, secretKey);\n\t},\n};\n"]}
@@ -1,2 +0,0 @@
1
- import {a}from'./chunk-S6RJHZV2.js';import*as P from'fs/promises';import*as w from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {bootstrap}from'@libp2p/bootstrap';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var q=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],S="/liop/manifest/1.0.0",O="liop:manifest",E=class v{node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(t={}){this.config={listenAddresses:t.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:t.bootstrapNodes||[],identityPath:t.identityPath,enableWAN:t.enableWAN??false,dhtStoragePath:t.dhtStoragePath,addressMapper:t.addressMapper};}shouldSkipManifestDial(t){let e=this.manifestDialFailureState.get(t);if(!e)return false;let n=Date.now();return n>=e.cooldownUntil?false:(n-e.lastSkipLogAt>v.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Mesh] Skipping manifest dial for ${t} during cooldown (${Math.ceil((e.cooldownUntil-n)/1e3)}s remaining)`),e.lastSkipLogAt=n),true)}recordManifestDialFailure(t){let e=Date.now(),r=(this.manifestDialFailureState.get(t)?.failures||0)+1,o=Math.min(v.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),v.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(t,{failures:r,cooldownUntil:e+o,lastSkipLogAt:0});}clearManifestDialFailure(t){this.manifestDialFailureState.delete(t);}async loadOrCreateIdentity(){try{let{generateKeyPair:t,privateKeyFromProtobuf:e}=await import('@libp2p/crypto/keys'),n=await import('uint8arrays');if(this.config.identityPath){let o=w.resolve(this.config.identityPath);try{let d=await P.readFile(o,"utf-8"),s=JSON.parse(d),l=n.fromString(s.privKey,"base64");try{let a$1=e(l);return a.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a$1,isNew:!1}}catch(a$1){a.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a$1 instanceof Error?a$1.message:String(a$1)}`);}}catch(d){let s=d;s.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Error loading identity: ${s.message}`);}}return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){a.error(`[LIOP-Mesh] Critical error in identity management: ${t}. Falling back to ephemeral identity.`);try{let{generateKeyPair:e}=await import('@libp2p/crypto/keys');return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){throw new Error(`Identity system failure: ${e}`)}}}async saveIdentity(t){if(!(!this.config.identityPath||!this.node))try{let e=w.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),r=await import('uint8arrays'),o=n(t),d=(r.toString||r.default.toString)(o,"base64"),s={id:this.node.peerId.toString(),privKey:d};await P.mkdir(w.dirname(e),{recursive:!0}),await P.writeFile(e,JSON.stringify(s,null,2)),a.info(`[LIOP-Mesh] Identity persisted to ${e}`);}catch(e){a.error(`[LIOP-Mesh] FAILED to persist identity: ${e}`);}}async capabilityToCID(t){let e=await sha256.digest(new TextEncoder().encode(t));return CID.create(1,85,e)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(t=>setTimeout(t,500)),!this.node)return;a.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let t of this.announcedCapabilities)try{let e=await this.capabilityToCID(t);await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Re-announced: ${t}`);}catch(e){a.info(`[LIOP-Mesh] Re-announce failed for ${t}: ${e}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let t=await this.loadOrCreateIdentity();if(!t)throw new Error("Could not initialize P2P Identity");let{privateKey:e,isNew:n}=t;this.localPrivateKey=e;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=q);let o=r.length>0?[bootstrap({list:r})]:void 0,d=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0";if(this.node=await createLibp2p({privateKey:e,addresses:{listen:this.config.listenAddresses},transports:[tcp(),webSockets()],connectionEncrypters:[noise()],streamMuxers:[yamux()],services:{identify:identify(),ping:ping(),dht:kadDHT({protocol:d,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:s=>s})},peerDiscovery:o}),this.node.addEventListener("peer:discovery",s=>{let l=s.detail.id;if(a.info(`[LIOP-Mesh] Discovered peer: ${l.toString()}`),this.node){let a=l;if(this.config.addressMapper&&s.detail.multiaddrs.length>0){let c=s.detail.multiaddrs.map(u=>{let m=this.config.addressMapper(u.toString());return m?multiaddr(m):null}).filter(u=>u!==null).find(u=>u.toString().includes("/tcp/")&&!u.toString().includes("/ws"));c&&(a=c);}this.node.dial(a).catch(()=>{});}}),this.node.addEventListener("peer:connect",s=>{let l=s.detail;if(a.info(`[LIOP-Mesh] Connected to peer: ${l.toString()}`),!this.node)return;let a$1=this.node.services.dht;a$1?.routingTable&&(a.info(`[LIOP-Mesh] Adding ${l.toString()} to DHT Routing Table`),a$1.routingTable.add(l).catch(f=>{a.info(`[LIOP-Mesh] Failed to add peer to routing table: ${f instanceof Error?f.message:String(f)}`);})),this.reannounceAll().catch(f=>{a.info(`[LIOP-Mesh] Re-announce error: ${f instanceof Error?f.message:String(f)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(e),a.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(s=>{a.info(`[LIOP-Mesh] Listening on: ${s.toString()}`);}),r.length>0){a.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let s=5;for(let l of r){let a$1=false,f=1;for(;f<=s&&!a$1;)try{await this.node.dial(multiaddr(l)),a.info(`[LIOP-Mesh] \u2705 Successfully dialed ${l}`),a$1=!0;}catch{let u=Math.min(1e3*2**(f-1),3e3);a.warn(`[LIOP-Mesh] \u26A0\uFE0F Dial attempt ${f}/${s} to ${l} failed. Retrying in ${u/1e3}s...`),f<s?await new Promise(m=>setTimeout(m,u)):a.error(`[LIOP-Mesh] \u274C Could not connect to bootstrap ${l} after ${s} attempts. Continuing...`),f++;}}}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),a.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await P.readFile(t,"utf-8"),n=JSON.parse(e),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let d of n)if(!(!d.id||!d.addresses))try{let s=r(d.id),l=d.addresses.map(f=>multiaddr(f));await this.node.peerStore.save(s,{multiaddrs:l});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(s).catch(()=>{}),o++;}catch{}a.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(t){let e=t;e.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await this.node.peerStore.all(),n=[];for(let r of e)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await P.mkdir(w.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify(n,null,2)),a.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(t){a.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${t}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(O).catch(t=>{a.info(`[LIOP-Mesh] Initial manifest announcement failed: ${t}`);}),this.node.handle(S,async(t,e)=>{let n=t?.stream??t,o=(t?.connection??e)?.remotePeer?.toString()||"unknown";a.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let d=this.manifestProvider?.();if(!d||!n){a.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let s=JSON.stringify(d),l=new TextEncoder().encode(s),a$1=Buffer.alloc(4);a$1.writeUInt32BE(l.length,0);let f=Buffer.concat([a$1,Buffer.from(l)]);a.info(`[LIOP-Mesh] Serving manifest (${f.length} bytes) to ${o} [Tools: ${d.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(f)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(u){a.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${u instanceof Error?u.message:String(u)}`);}}else await pipe([f],n);a.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){a.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(d){a.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${d instanceof Error?d.message:String(d)}`);}}),a.info(`[LIOP-Mesh] Manifest Protocol registered: ${S}`));}registerManifestHandler(t){this.manifestProvider=t,this.node&&this.applyHandlers();}async queryManifest(t){if(!this.node)throw new Error("Mesh Node is not running");if(t===this.node.peerId.toString())return a.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${t}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(t))return null;let e=3;for(let n=1;n<=e;n++)try{let r=null,d=this.node.getConnections().find(h=>h.remotePeer.toString()===t);if(d)r=d.remotePeer;else {let p=(await this.node.peerStore.all()).find(g=>g.id.toString()===t);if(p)r=p.id;else {let{peerIdFromString:g}=await import('@libp2p/peer-id');r=g(t);}}let l=r;if(this.config.addressMapper&&this.node){let h=this.config.addressMapper,p=await this.node.peerStore.get(r);if(p&&p.addresses.length>0){let g=p.addresses.map(y=>{let C=y.multiaddr.toString(),T=h(C);return T?{isCertified:y.isCertified,multiaddr:multiaddr(T)}:null}).filter(y=>y!==null),L=g.find(y=>y.multiaddr.toString().includes("/tcp/")&&!y.multiaddr.toString().includes("/ws"));L&&(l=L.multiaddr,a.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${l.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:g.map(y=>y.multiaddr)});}}let a$1;try{let h=await this.node.dialProtocol(l,S).catch(p=>{throw String(p).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):p});a$1=h.stream||h;}catch(h){if(n===e)return a.info(`[LIOP-Mesh] Dial error for ${t} after ${e} attempts: ${h}`),null;let p=500*2**n;a.info(`[LIOP-Mesh] Dial error for ${t} (Attempt ${n}). Retrying in ${p}ms...`),await new Promise(g=>setTimeout(g,p));continue}let f=a$1.source??(typeof a$1[Symbol.asyncIterator]=="function"?a$1:null);if(!f)throw new Error("Target stream has no AsyncIterable source");let c=[],u=0,m=-1,M,A=new Promise((h,p)=>{M=setTimeout(()=>p(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let h of f){if(!h)continue;let p=typeof h.subarray=="function"?h.subarray():h instanceof Uint8Array?h:new Uint8Array(0),g=Buffer.from(p.buffer,p.byteOffset,p.byteLength);if(g.length>0&&(c.push(g),u+=g.length,m<0&&u>=4&&(m=Buffer.concat(c).readUInt32BE(0)),m>=0&&u>=4+m))break}})(),A]);}catch(h){if(c.length===0)throw h;a.info(`[LIOP-Mesh] Partial manifest read from ${t}: ${h instanceof Error?h.message:String(h)}`);}finally{M&&clearTimeout(M);}let I=Buffer.concat(c);if(I.length<4)throw new Error("Received empty/invalid manifest (too short)");let D=I.readUInt32BE(0),N=I.subarray(4,4+D).toString("utf-8"),$=JSON.parse(N);return a.info(`[LIOP-Mesh] Received manifest from ${t}: ${$.tools.length} tools`),this.clearManifestDialFailure(t),$}catch(r){if(n===e)return this.recordManifestDialFailure(t),a.info(`[LIOP-Mesh] Failed to query manifest from ${t} after ${e} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;a.info(`[LIOP-Mesh] Query error for ${t} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(d=>setTimeout(d,o));}return null}async discoverManifestProviders(){return this.findProviders(O)}async announceManifest(){await this.announceCapability(O);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(t){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(t))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(t=>t.toString())}async announceCapability(t){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(t);try{let e=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Announcing capability: ${t} (CID: ${e.toString()})`),await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Successfully announced capability: ${t}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(e))if(r.id.toString()===n){a.info(`[LIOP-Mesh] Self-verification success: Node is providing ${t}`);break}}catch(e){a.error(`[LIOP-Mesh] Failed to announce capability: ${e}`);}}async findProviders(t){if(!this.node)throw new Error("Mesh Node is not running");let e=[];try{let n=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Querying DHT for ${t} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,d=o>1?1500:3e3;a.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${d}ms (Active connections: ${o})`);let s=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),l=!1;for(;!l;){let a$1=s.next(),f=new Promise(c=>setTimeout(()=>c({timeout:!0}),d));try{let c=await Promise.race([a$1,f]);if(c&&typeof c=="object"&&"timeout"in c){a.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof s.return=="function"&&s.return().catch(()=>{}),l=!0;break}let u=c;if(u.done){l=!0;break}r=!0;let M=u.value.id.toString();a.info(`[LIOP-Mesh] Found provider: ${M}`),e.includes(M)||e.push(M);}catch(c){a.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),l=!0;break}}if(!r){let f=this.node.services.dht?.routingTable?.size||0;a.info(`[LIOP-Mesh] DHT search for ${t} returned zero results (routing table size: ${f})`);}if(this.announcedCapabilities.has(t)){let a$1=this.node.peerId.toString();e.includes(a$1)||(a.info(`[LIOP-Mesh] Including local node (${a$1}) in results for ${t}`),e.push(a$1));}}catch(n){a.info(`[LIOP-Mesh] Error finding providers for ${t}: ${n instanceof Error?n.message:String(n)}`);}return a.info(`[LIOP-Mesh] DHT search for ${t} finished. Found ${e.length} providers.`),e}async resolvePeer(t){if(!this.node)throw new Error("Mesh Node is not running");try{let e=this.node.getConnections();for(let r of e)if(r.remotePeer.toString()===t){let o=r.remoteAddr.toString();return a.info(`[LIOP-Mesh] Resolved peer ${t} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===t&&r.addresses.length>0){let o=r.addresses.map(d=>d.multiaddr.toString());return a.info(`[LIOP-Mesh] Resolved peer ${t} via peerStore: ${o[0]}`),o}a.info(`[LIOP-Mesh] Peer ${t} not found in connections or peerStore`);}catch(e){a.info(`[LIOP-Mesh] Failed to resolve peer ${t}: ${e}`);}return []}};export{E as a};//# sourceMappingURL=chunk-DQ6UW6L7.js.map
2
- //# sourceMappingURL=chunk-DQ6UW6L7.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mesh/node.ts"],"names":["DEFAULT_BOOTSTRAP_NODES","LIOP_MANIFEST_PROTOCOL","LIOP_MANIFEST_CAPABILITY","MeshNode","_MeshNode","config","peerIdStr","state","now","log","failures","backoff","generateKeyPair","privateKeyFromProtobuf","uint8arrays","absolutePath","data","json","protobufBytes","privateKey","parseError","error","e","fallbackError","privateKeyToProtobuf","privKeyEncoded","capability","hash","sha256","CID","resolve","cid","_e","result","isNew","bootNodes","discovery","bootstrap","dhtProtocol","createLibp2p","tcp","webSockets","noise","yamux","identify","ping","kadDHT","peer","evt","peerId","dialTarget","directTCP","ma","mapped","multiaddr","t","dht","err","addr","maxRetries","success","attempt","delay","peers","peerIdFromString","loadedCount","addrs","a","allPeers","peersToSave","streamArg","connectionArg","stream","remotePeer","manifest","manifestStr","payload","lengthBuf","fullPacket","drainErr","pipe","writeErr","provider","MAX_ATTEMPTS","targetPeer","activeConn","c","stored","p","mapper","translated","oa","original","dialErr","r","source","chunks","totalReceived","expectedPayloadLength","manifestTimeoutId","timeoutPromise","_","reject","chunk","raw","bytes","itErr","declaredLen","jsonStr","selfId","providers","foundAny","connections","idleTimeoutMs","iterator","isDone","nextPromise","itResult","dhtSize","conn","remoteAddr"],"mappings":"glBA2DA,IAAMA,EAA0B,CAC/B,iFAAA,CACA,iFAAA,CACA,iFAAA,CACA,iFACD,CAAA,CAEMC,CAAAA,CAAyB,uBACzBC,CAAAA,CAA2B,eAAA,CAQpBC,EAAN,MAAMC,CAAS,CACb,IAAA,CAAsB,KACtB,MAAA,CACA,wBAAA,CAGJ,IAAI,GAAA,CACR,OAAwB,+BAAiC,GAAA,CACzD,OAAwB,6BAAA,CAAgC,CAAA,CAAI,IAC5D,OAAwB,kCAAA,CAAqC,GAAA,CAQrD,qBAAA,CAAqC,IAAI,GAAA,CAGzC,YAAA,CAAe,KAAA,CAGf,gBAAA,CAAgD,KAGhD,0BAAA,CAA6B,KAAA,CAI7B,gBAA8B,IAAA,CAEtC,WAAA,CAAYC,EAAyB,EAAC,CAAG,CACxC,IAAA,CAAK,OAAS,CACb,eAAA,CAAiBA,CAAAA,CAAO,eAAA,EAAmB,CAC1C,uBAAA,CACA,oBACD,CAAA,CACA,cAAA,CAAgBA,EAAO,cAAA,EAAkB,GACzC,YAAA,CAAcA,CAAAA,CAAO,aACrB,SAAA,CAAWA,CAAAA,CAAO,SAAA,EAAa,KAAA,CAC/B,eAAgBA,CAAAA,CAAO,cAAA,CACvB,aAAA,CAAeA,CAAAA,CAAO,aACvB,EACD,CAEQ,sBAAA,CAAuBC,CAAAA,CAA4B,CAC1D,IAAMC,CAAAA,CAAQ,KAAK,wBAAA,CAAyB,GAAA,CAAID,CAAS,CAAA,CACzD,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AAI,IAAA,CACH,6BAA6BH,CAAS,CAAA,wBAAA,EAA2BkH,CAAU,CAAA,CAC5E,EACO,CAACA,CAAU,CACnB,CAID,IAAMpD,EAAW,MAAM,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,KAAI,CAC/C,IAAA,IAAWrB,KAAQqB,CAAAA,CAClB,GAAIrB,EAAK,EAAA,CAAG,QAAA,EAAS,GAAMzC,CAAAA,EAAayC,EAAK,SAAA,CAAU,MAAA,CAAS,EAAG,CAElE,IAAMmB,EAAQnB,CAAAA,CAAK,SAAA,CAAU,GAAA,CAAKoB,CAAAA,EAAWA,EAAE,SAAA,CAAU,QAAA,EAAU,CAAA,CACnE,OAAA1D,CAAAA,CAAI,IAAA,CACH,CAAA,0BAAA,EAA6BH,CAAS,mBAAmB4D,CAAAA,CAAM,CAAC,CAAC,CAAA,CAClE,CAAA,CACOA,CACR,CAGDzD,CAAAA,CAAI,IAAA,CACH,CAAA,iBAAA,EAAoBH,CAAS,CAAA,sCAAA,CAC9B,EACD,OAASe,CAAAA,CAAO,CACfZ,EAAI,IAAA,CAAK,CAAA,mCAAA,EAAsCH,CAAS,CAAA,EAAA,EAAKe,CAAK,CAAA,CAAE,EACrE,CACA,OAAO,EACR,CACD","file":"chunk-DQ6UW6L7.js","sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { noise } from \"@chainsafe/libp2p-noise\";\nimport { yamux } from \"@chainsafe/libp2p-yamux\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { kadDHT } from \"@libp2p/kad-dht\";\nimport { ping } from \"@libp2p/ping\";\nimport { tcp } from \"@libp2p/tcp\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { pipe } from \"it-pipe\";\nimport type { Libp2p } from \"libp2p\";\nimport { createLibp2p } from \"libp2p\";\nimport { CID } from \"multiformats/cid\";\nimport { sha256 } from \"multiformats/hashes/sha2\";\nimport { log } from \"../utils/logger.js\";\n// import { pEvent } from \"p-event\"; // Disabled to avoid ESM conflicts in tests\n\n/**\n * Manifest describing a node's capabilities in the LIOP Mesh.\n * Exchanged via the /liop/manifest/1.0.0 protocol stream.\n */\nexport interface LiopManifest {\n\tpeerId: string;\n\tgrpcPort: number;\n\ttools: Array<{\n\t\tname: string;\n\t\tdescription?: string;\n\t\tinputSchema?: Record<string, unknown>;\n\t}>;\n\tresources: Array<{\n\t\tname: string;\n\t\turi: string;\n\t\tdescription?: string;\n\t\tmimeType?: string;\n\t\ttext?: string;\n\t}>;\n\tserverInfo: { name: string; version: string };\n\ttaxonomy?: {\n\t\tdomain: string;\n\t\tclearanceTier: number;\n\t\texecutionTypes: string[];\n\t};\n\tauthRequired?: boolean;\n\t/** Canonical slug for deterministic token resolution. Agents resolve LIOP_TOKEN_<tokenSlug>. Must match /^[A-Z][A-Z0-9_]*$/. */\n\ttokenSlug?: string;\n}\n\nexport interface MeshNodeConfig {\n\tlistenAddresses?: string[];\n\tbootstrapNodes?: string[];\n\tidentityPath?: string;\n\tenableWAN?: boolean;\n\tdhtStoragePath?: string;\n\t/** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */\n\taddressMapper?: (addr: string) => string | null;\n}\n\nconst DEFAULT_BOOTSTRAP_NODES = [\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt\",\n];\n\nconst LIOP_MANIFEST_PROTOCOL = \"/liop/manifest/1.0.0\";\nconst LIOP_MANIFEST_CAPABILITY = \"liop:manifest\";\n\n/**\n * P2P Mesh Node backed by libp2p + Kademlia DHT.\n *\n * Provides capability advertisement via CID-based content routing\n * and decentralized peer discovery.\n */\nexport class MeshNode {\n\tprivate node: Libp2p | null = null;\n\tprivate config: MeshNodeConfig;\n\tprivate manifestDialFailureState: Map<\n\t\tstring,\n\t\t{ failures: number; cooldownUntil: number; lastSkipLogAt: number }\n\t> = new Map();\n\tprivate static readonly MANIFEST_DIAL_BASE_COOLDOWN_MS = 10_000;\n\tprivate static readonly MANIFEST_DIAL_MAX_COOLDOWN_MS = 2 * 60_000;\n\tprivate static readonly MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS = 30_000;\n\n\t/**\n\t * Buffer of capability hashes that have been announced.\n\t * Used to re-announce capabilities when new peers connect\n\t * (critical for small / isolated clusters where the initial\n\t * provide() finds zero peers in the routing table).\n\t */\n\tprivate announcedCapabilities: Set<string> = new Set();\n\n\t/** Guards against concurrent re-announcement storms. */\n\tprivate reannouncing = false;\n\n\t/** Callback that returns the local node's manifest on request. */\n\tprivate manifestProvider: (() => LiopManifest) | null = null;\n\n\t/** Flag to ensure the manifest protocol is only registered once. */\n\tprivate manifestProtocolRegistered = false;\n\n\t/** Local Ed25519 Private Key for protocol signatures */\n\t// biome-ignore lint/suspicious/noExplicitAny: libp2p keys type\n\tprivate localPrivateKey: any | null = null;\n\n\tconstructor(config: MeshNodeConfig = {}) {\n\t\tthis.config = {\n\t\t\tlistenAddresses: config.listenAddresses || [\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0/ws\",\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0\",\n\t\t\t],\n\t\t\tbootstrapNodes: config.bootstrapNodes || [],\n\t\t\tidentityPath: config.identityPath,\n\t\t\tenableWAN: config.enableWAN ?? false,\n\t\t\tdhtStoragePath: config.dhtStoragePath,\n\t\t\taddressMapper: config.addressMapper,\n\t\t};\n\t}\n\n\tprivate shouldSkipManifestDial(peerIdStr: string): boolean {\n\t\tconst state = this.manifestDialFailureState.get(peerIdStr);\n\t\tif (!state) return false;\n\t\tconst now = Date.now();\n\t\tif (now >= state.cooldownUntil) return false;\n\t\tif (\n\t\t\tnow - state.lastSkipLogAt >\n\t\t\tMeshNode.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS\n\t\t) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Skipping manifest dial for ${peerIdStr} 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 recordManifestDialFailure(peerIdStr: string): void {\n\t\tconst now = Date.now();\n\t\tconst prev = this.manifestDialFailureState.get(peerIdStr);\n\t\tconst failures = (prev?.failures || 0) + 1;\n\t\tconst backoff = Math.min(\n\t\t\tMeshNode.MANIFEST_DIAL_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),\n\t\t\tMeshNode.MANIFEST_DIAL_MAX_COOLDOWN_MS,\n\t\t);\n\t\tthis.manifestDialFailureState.set(peerIdStr, {\n\t\t\tfailures,\n\t\t\tcooldownUntil: now + backoff,\n\t\t\tlastSkipLogAt: 0,\n\t\t});\n\t}\n\n\tprivate clearManifestDialFailure(peerIdStr: string): void {\n\t\tthis.manifestDialFailureState.delete(peerIdStr);\n\t}\n\n\t/**\n\t * Loads a persistent identity from disk or generates a new Ed25519 keypair.\n\t * Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).\n\t */\n\tprivate async loadOrCreateIdentity() {\n\t\ttry {\n\t\t\tconst { generateKeyPair, privateKeyFromProtobuf } = (await import(\n\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\t)) as any;\n\t\t\t// @ts-expect-error: libp2p ESM dynamic import type conflict\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\tconst uint8arrays = (await import(\"uint8arrays\")) as any;\n\n\t\t\tif (this.config.identityPath) {\n\t\t\t\tconst absolutePath = path.resolve(this.config.identityPath);\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await fs.readFile(absolutePath, \"utf-8\");\n\t\t\t\t\tconst json = JSON.parse(data);\n\t\t\t\t\tconst protobufBytes = uint8arrays.fromString(json.privKey, \"base64\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst privateKey = privateKeyFromProtobuf(protobufBytes);\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Loaded persistent identity from ${absolutePath}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { privateKey, isNew: false };\n\t\t\t\t\t} catch (parseError: unknown) {\n\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Persistent identity at ${absolutePath} is invalid or corrupt. Generating new one. Error: ${\n\t\t\t\t\t\t\t\tparseError instanceof Error\n\t\t\t\t\t\t\t\t\t? parseError.message\n\t\t\t\t\t\t\t\t\t: String(parseError)\n\t\t\t\t\t\t\t}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Fall through to generate new key\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tconst e = error as Error & { code?: string };\n\t\t\t\t\tif (e.code !== \"ENOENT\") {\n\t\t\t\t\t\tlog.error(`[LIOP-Mesh] Error loading identity: ${e.message}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst privateKey = await generateKeyPair(\"Ed25519\");\n\t\t\treturn { privateKey, isNew: true };\n\t\t} catch (error) {\n\t\t\tlog.error(\n\t\t\t\t`[LIOP-Mesh] Critical error in identity management: ${error}. Falling back to ephemeral identity.`,\n\t\t\t);\n\n\t\t\t// EPOCH FALLBACK: In extreme cases (corrupt env), use a volatile in-memory identity\n\t\t\t// to allow the node to start and serve traffic.\n\t\t\ttry {\n\t\t\t\tconst { generateKeyPair } = (await import(\n\t\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p ESM dynamic import type workaround\n\t\t\t\t)) as any;\n\t\t\t\tconst ephemeralKey = await generateKeyPair(\"Ed25519\");\n\t\t\t\treturn { privateKey: ephemeralKey, isNew: true };\n\t\t\t} catch (fallbackError) {\n\t\t\t\tthrow new Error(`Identity system failure: ${fallbackError}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Persists the private key to disk using protobuf serialization (libp2p v3.x).\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: Libp2p private key type is complex for Alpha\n\tprivate async saveIdentity(privateKey: any) {\n\t\tif (!this.config.identityPath || !this.node) return;\n\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.identityPath);\n\t\t\tconst { privateKeyToProtobuf } = (await import(\n\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\t)) as any;\n\t\t\t// @ts-expect-error: libp2p ESM dynamic import type conflict\n\t\t\tconst uint8arrays = await import(\"uint8arrays\");\n\n\t\t\tconst protobufBytes = privateKeyToProtobuf(privateKey);\n\t\t\tconst privKeyEncoded = (\n\t\t\t\tuint8arrays.toString || uint8arrays.default.toString\n\t\t\t)(protobufBytes, \"base64\");\n\n\t\t\tconst json = {\n\t\t\t\tid: this.node.peerId.toString(),\n\t\t\t\tprivKey: privKeyEncoded,\n\t\t\t};\n\n\t\t\tawait fs.mkdir(path.dirname(absolutePath), { recursive: true });\n\t\t\tawait fs.writeFile(absolutePath, JSON.stringify(json, null, 2));\n\t\t\tlog.info(`[LIOP-Mesh] Identity persisted to ${absolutePath}`);\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] FAILED to persist identity: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.\n\t * Required by @libp2p/kad-dht v16+ for provide/findProviders.\n\t */\n\tprivate async capabilityToCID(capability: string): Promise<CID> {\n\t\tconst hash = await sha256.digest(new TextEncoder().encode(capability));\n\t\treturn CID.create(1, 0x55, hash);\n\t}\n\n\t/**\n\t * Re-announces all buffered capabilities after a new peer connects.\n\t * Uses a small delay to allow the DHT protocol handshake to complete.\n\t */\n\tprivate async reannounceAll(): Promise<void> {\n\t\tif (\n\t\t\tthis.reannouncing ||\n\t\t\t!this.node ||\n\t\t\tthis.announcedCapabilities.size === 0\n\t\t)\n\t\t\treturn;\n\n\t\tthis.reannouncing = true;\n\t\ttry {\n\t\t\t// Wait for the DHT protocol handshake to settle\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\n\t\t\tif (!this.node) return;\n\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`,\n\t\t\t);\n\n\t\t\tfor (const hash of this.announcedCapabilities) {\n\t\t\t\ttry {\n\t\t\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\t\t\tawait this.node.contentRouting.provide(cid);\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Re-announced: ${hash}`);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Re-announce failed for ${hash}: ${_e}`);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.reannouncing = false;\n\t\t}\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.node) return;\n\t\tconst result = await this.loadOrCreateIdentity();\n\t\tif (!result) throw new Error(\"Could not initialize P2P Identity\");\n\n\t\tconst { privateKey, isNew } = result;\n\t\tthis.localPrivateKey = privateKey;\n\n\t\tlet bootNodes = this.config.bootstrapNodes || [];\n\t\tif (bootNodes.length === 0 && this.config.enableWAN) {\n\t\t\tbootNodes = DEFAULT_BOOTSTRAP_NODES;\n\t\t}\n\n\t\tconst discovery =\n\t\t\tbootNodes.length > 0\n\t\t\t\t? [\n\t\t\t\t\t\tbootstrap({\n\t\t\t\t\t\t\tlist: bootNodes,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]\n\t\t\t\t: undefined;\n\n\t\tconst dhtProtocol = this.config.enableWAN\n\t\t\t? \"/ipfs/kad/1.0.0\"\n\t\t\t: \"/ipfs/lan/kad/1.0.0\";\n\n\t\tthis.node = await createLibp2p({\n\t\t\tprivateKey,\n\t\t\taddresses: {\n\t\t\t\tlisten: this.config.listenAddresses,\n\t\t\t},\n\t\t\ttransports: [tcp(), webSockets()],\n\t\t\tconnectionEncrypters: [noise()],\n\t\t\tstreamMuxers: [yamux()],\n\t\t\tservices: {\n\t\t\t\tidentify: identify(),\n\t\t\t\tping: ping(),\n\t\t\t\tdht: kadDHT({\n\t\t\t\t\tprotocol: dhtProtocol,\n\t\t\t\t\tclientMode: false,\n\t\t\t\t\t// Allow local/private IPs in the DHT routing table for development/testing\n\t\t\t\t\tallowQueryWithZeroPeers: true,\n\t\t\t\t\t// By default kadDHT drops local IP addresses. Override the mapper to keep them.\n\t\t\t\t\tpeerInfoMapper: (peer) => peer,\n\t\t\t\t}),\n\t\t\t},\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p discovery type mismatch\n\t\t\tpeerDiscovery: discovery as any,\n\t\t});\n\n\t\t// Monitor Connectivity Events\n\t\tthis.node.addEventListener(\"peer:discovery\", (evt) => {\n\t\t\tconst peerId = evt.detail.id;\n\t\t\tlog.info(`[LIOP-Mesh] Discovered peer: ${peerId.toString()}`);\n\t\t\t// [Phase 104] Auto-dial discovered peers to bypass DHT propagation latency\n\t\t\tif (this.node) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: target polymorphic type\n\t\t\t\tlet dialTarget: any = peerId;\n\n\t\t\t\t// Apply port translation if necessary (Docker -> Windows Host)\n\t\t\t\tif (this.config.addressMapper && evt.detail.multiaddrs.length > 0) {\n\t\t\t\t\tconst translated = evt.detail.multiaddrs\n\t\t\t\t\t\t.map((ma) => {\n\t\t\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: mapped conditionally\n\t\t\t\t\t\t\tconst mapped = this.config.addressMapper!(ma.toString());\n\t\t\t\t\t\t\treturn mapped ? multiaddr(mapped) : null;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter((t): t is NonNullable<typeof t> => t !== null);\n\n\t\t\t\t\tconst directTCP = translated.find(\n\t\t\t\t\t\t(ma) =>\n\t\t\t\t\t\t\tma.toString().includes(\"/tcp/\") && !ma.toString().includes(\"/ws\"),\n\t\t\t\t\t);\n\t\t\t\t\tif (directTCP) dialTarget = directTCP;\n\t\t\t\t}\n\n\t\t\t\tthis.node.dial(dialTarget).catch(() => {});\n\t\t\t}\n\t\t});\n\n\t\tthis.node.addEventListener(\"peer:connect\", (evt) => {\n\t\t\tconst peerId = evt.detail;\n\t\t\tlog.info(`[LIOP-Mesh] Connected to peer: ${peerId.toString()}`);\n\n\t\t\tif (!this.node) return;\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal services\n\t\t\tconst dht = (this.node.services as any).dht;\n\t\t\tif (dht?.routingTable) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Adding ${peerId.toString()} to DHT Routing Table`,\n\t\t\t\t);\n\t\t\t\tdht.routingTable.add(peerId).catch((err: unknown) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Failed to add peer to routing table: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Trigger reactive re-announcement of all capabilities\n\t\t\t// so that ADD_PROVIDER messages reach the new peer\n\t\t\tthis.reannounceAll().catch((err: unknown) => {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Re-announce error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t});\n\n\t\tawait this.node.start();\n\n\t\t// Load persisted DHT routing table to enable rapid cold-start reconnections\n\t\tawait this.loadRoutingTable();\n\n\t\t// [LIOP-ALPHA] Protocols and services setup\n\t\tthis.applyHandlers();\n\n\t\tif (isNew && this.config.identityPath) {\n\t\t\tawait this.saveIdentity(privateKey);\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`,\n\t\t);\n\t\tthis.node.getMultiaddrs().forEach((addr) => {\n\t\t\tlog.info(`[LIOP-Mesh] Listening on: ${addr.toString()}`);\n\t\t});\n\n\t\t// Force explicit dialing of Bootstrap nodes with bounded backoff\n\t\tif (bootNodes.length > 0) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Forcing direct P2P dial to ${bootNodes.length} bootstrap nodes...`,\n\t\t\t);\n\n\t\t\tconst maxRetries = 5;\n\t\t\tfor (const addr of bootNodes) {\n\t\t\t\tlet success = false;\n\t\t\t\tlet attempt = 1;\n\n\t\t\t\twhile (attempt <= maxRetries && !success) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.node.dial(multiaddr(addr));\n\t\t\t\t\t\tlog.info(`[LIOP-Mesh] ✅ Successfully dialed ${addr}`);\n\t\t\t\t\t\tsuccess = true;\n\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\tconst delay = Math.min(1000 * 2 ** (attempt - 1), 3000);\n\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t`[LIOP-Mesh] ⚠️ Dial attempt ${attempt}/${maxRetries} to ${addr} failed. Retrying in ${delay / 1000}s...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (attempt < maxRetries) {\n\t\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t\t`[LIOP-Mesh] ❌ Could not connect to bootstrap ${addr} after ${maxRetries} attempts. Continuing...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tattempt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (this.node) {\n\t\t\tawait this.saveRoutingTable();\n\t\t\tawait this.node.stop();\n\t\t\tlog.info(\"[LIOP-Mesh] Node stopped\");\n\t\t}\n\t}\n\n\tprivate async loadRoutingTable() {\n\t\tif (!this.config.dhtStoragePath || !this.node) return;\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.dhtStoragePath);\n\t\t\tconst data = await fs.readFile(absolutePath, \"utf-8\");\n\t\t\tconst peers = JSON.parse(data);\n\t\t\tconst { peerIdFromString } = await import(\"@libp2p/peer-id\");\n\n\t\t\tlet loadedCount = 0;\n\t\t\tfor (const peer of peers) {\n\t\t\t\tif (!peer.id || !peer.addresses) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst peerId = peerIdFromString(peer.id);\n\t\t\t\t\tconst addrs = peer.addresses.map((a: string) => multiaddr(a));\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: bypass libp2p version-drift type mismatch on PeerId\n\t\t\t\t\tawait this.node.peerStore.save(peerId as any, { multiaddrs: addrs });\n\n\t\t\t\t\t// Pre-seed DHT routing table\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal service access\n\t\t\t\t\tconst dht = (this.node.services as any).dht;\n\t\t\t\t\tif (dht?.routingTable) {\n\t\t\t\t\t\tdht.routingTable.add(peerId).catch(() => {});\n\t\t\t\t\t}\n\t\t\t\t\tloadedCount++;\n\t\t\t\t} catch (_e) {}\n\t\t\t}\n\t\t\tlog.info(`[LIOP-Mesh] Loaded ${loadedCount} peers from DHT storage`);\n\t\t} catch (error: unknown) {\n\t\t\tconst e = error as Error & { code?: string };\n\t\t\tif (e.code !== \"ENOENT\") {\n\t\t\t\tlog.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async saveRoutingTable() {\n\t\tif (!this.config.dhtStoragePath || !this.node) return;\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.dhtStoragePath);\n\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\tconst peersToSave = [];\n\t\t\tfor (const peer of allPeers) {\n\t\t\t\tif (peer.addresses.length > 0) {\n\t\t\t\t\tpeersToSave.push({\n\t\t\t\t\t\tid: peer.id.toString(),\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: internal libp2p addr\n\t\t\t\t\t\taddresses: peer.addresses.map((a: any) => a.multiaddr.toString()),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait fs.mkdir(path.dirname(absolutePath), { recursive: true });\n\t\t\tawait fs.writeFile(absolutePath, JSON.stringify(peersToSave, null, 2));\n\t\t\tlog.info(`[LIOP-Mesh] Saved ${peersToSave.length} peers to DHT storage`);\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Internal logic to register protocol handlers against the libp2p node.\n\t * Can be called multiple times; handles idempotent registration.\n\t */\n\tprivate applyHandlers(): void {\n\t\tif (!this.node || this.manifestProtocolRegistered) return;\n\t\tif (!this.manifestProvider) return;\n\n\t\tthis.manifestProtocolRegistered = true;\n\n\t\t// Announce manifest capability to the Mesh DHT for discovery\n\t\tthis.announceCapability(LIOP_MANIFEST_CAPABILITY).catch((err) => {\n\t\t\tlog.info(`[LIOP-Mesh] Initial manifest announcement failed: ${err}`);\n\t\t});\n\n\t\t// libp2p v3.x: handler receives (stream, connection) as separate args\n\t\tthis.node.handle(\n\t\t\tLIOP_MANIFEST_PROTOCOL,\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p v3.x stream/connection types\n\t\t\tasync (streamArg: any, connectionArg?: any) => {\n\t\t\t\t// v3.x passes (stream, connection); v1.x passed ({ stream, connection })\n\t\t\t\tconst stream = streamArg?.stream ?? streamArg;\n\t\t\t\tconst conn = streamArg?.connection ?? connectionArg;\n\t\t\t\tconst remotePeer = conn?.remotePeer?.toString() || \"unknown\";\n\n\t\t\t\tlog.info(`[LIOP-Mesh] Incoming manifest request from ${remotePeer}.`);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst manifest = this.manifestProvider?.();\n\t\t\t\t\tif (!manifest || !stream) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Skipping manifest request (no provider or stream)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (typeof stream?.close === \"function\") await stream.close();\n\t\t\t\t\t\t} catch (_e) {}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst manifestStr = JSON.stringify(manifest);\n\t\t\t\t\tconst payload = new TextEncoder().encode(manifestStr);\n\n\t\t\t\t\t// Write length-prefixed payload (Big Endian 4 bytes)\n\t\t\t\t\tconst lengthBuf = Buffer.alloc(4);\n\t\t\t\t\tlengthBuf.writeUInt32BE(payload.length, 0);\n\t\t\t\t\tconst fullPacket = Buffer.concat([lengthBuf, Buffer.from(payload)]);\n\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Serving manifest (${fullPacket.length} bytes) to ${remotePeer} [Tools: ${manifest.tools.map((t) => t.name).join(\", \")}]`,\n\t\t\t\t\t);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// libp2p v3.x: stream.send() for writing\n\t\t\t\t\t\tif (typeof stream.send === \"function\") {\n\t\t\t\t\t\t\tconst accepted = stream.send(fullPacket);\n\t\t\t\t\t\t\tif (!accepted && typeof stream.onDrain === \"function\") {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait stream.onDrain({ signal: AbortSignal.timeout(5000) });\n\t\t\t\t\t\t\t\t} catch (drainErr) {\n\t\t\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t\t\t`[LIOP-Mesh] WARN: Drain timeout for ${remotePeer}: ${drainErr instanceof Error ? drainErr.message : String(drainErr)}`,\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} else {\n\t\t\t\t\t\t\t// Fallback for environments where stream.send is not available\n\t\t\t\t\t\t\tawait pipe([fullPacket], stream);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.info(`[LIOP-Mesh] Manifest sent successfully to ${remotePeer}`);\n\t\t\t\t\t} catch (writeErr: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Write error serving manifest to ${remotePeer}: ${writeErr instanceof Error ? writeErr.message : String(writeErr)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (typeof stream.close === \"function\") await stream.close();\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t// Ignore close errors\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Error serving manifest to ${remotePeer}: ${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\tlog.info(\n\t\t\t`[LIOP-Mesh] Manifest Protocol registered: ${LIOP_MANIFEST_PROTOCOL}`,\n\t\t);\n\t}\n\n\t/**\n\t * Registers a callback as the manifest provider.\n\t * Will be applied immediately if the node is already initialized.\n\t */\n\tregisterManifestHandler(provider: () => LiopManifest): void {\n\t\tthis.manifestProvider = provider;\n\t\tif (this.node) {\n\t\t\tthis.applyHandlers();\n\t\t}\n\t}\n\n\t/**\n\t * Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.\n\t * Returns null if the peer doesn't support the protocol or is unreachable.\n\t */\n\tasync queryManifest(peerIdStr: string): Promise<LiopManifest | null> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\n\t\t// [ALPHA-OPTIMIZATION] Local Loopback Bypass\n\t\t// If we are querying our own manifest, return it directly from the provider.\n\t\tif (peerIdStr === this.node.peerId.toString()) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Loopback: Returning local manifest directly for ${peerIdStr}`,\n\t\t\t);\n\t\t\treturn this.manifestProvider?.() || null;\n\t\t}\n\t\tif (this.shouldSkipManifestDial(peerIdStr)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst MAX_ATTEMPTS = 3;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\ttry {\n\t\t\t\ttype DialTarget = Parameters<Libp2p[\"dialProtocol\"]>[0];\n\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: targetPeer can be from connections or from string\n\t\t\t\tlet targetPeer: any = null;\n\t\t\t\tconst connections = this.node.getConnections();\n\t\t\t\tconst activeConn = connections.find(\n\t\t\t\t\t(c) => c.remotePeer.toString() === peerIdStr,\n\t\t\t\t);\n\n\t\t\t\tif (activeConn) {\n\t\t\t\t\ttargetPeer = activeConn.remotePeer;\n\t\t\t\t} else {\n\t\t\t\t\t// Fallback: search peerStore to find a valid PeerId object that libp2p understands natively\n\t\t\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\t\t\tconst stored = allPeers.find((p) => p.id.toString() === peerIdStr);\n\t\t\t\t\tif (stored) {\n\t\t\t\t\t\ttargetPeer = stored.id;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Final fallback parsing.\n\t\t\t\t\t\t// [LIOP-CAUTION] This is where the toMultihash error usually triggers if libp2p version drift exists.\n\t\t\t\t\t\tconst { peerIdFromString } = await import(\"@libp2p/peer-id\");\n\t\t\t\t\t\ttargetPeer = peerIdFromString(peerIdStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// [LIOP-PORT-TRANSLATION] If an address mapper is configured (e.g. in the Host Agent),\n\t\t\t\t// ensure the targetPeer's addresses are translated before libp2p attempts to dial.\n\t\t\t\tconst dialTargetFromPeer = targetPeer as DialTarget;\n\t\t\t\tlet dialTarget: DialTarget = dialTargetFromPeer;\n\t\t\t\tif (this.config.addressMapper && this.node) {\n\t\t\t\t\tconst mapper = this.config.addressMapper;\n\t\t\t\t\tconst peer = await this.node.peerStore.get(targetPeer);\n\t\t\t\t\tif (peer && peer.addresses.length > 0) {\n\t\t\t\t\t\tconst translated = peer.addresses\n\t\t\t\t\t\t\t.map((oa) => {\n\t\t\t\t\t\t\t\tconst original = oa.multiaddr.toString();\n\t\t\t\t\t\t\t\tconst mapped = mapper(original);\n\t\t\t\t\t\t\t\tif (!mapped) return null;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tisCertified: oa.isCertified,\n\t\t\t\t\t\t\t\t\tmultiaddr: multiaddr(mapped),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.filter((t): t is NonNullable<typeof t> => t !== null);\n\n\t\t\t\t\t\t// Strategy: Force direct dial to the first translated TCP address to bypass DHT routing delays\n\t\t\t\t\t\tconst directTCP = translated.find(\n\t\t\t\t\t\t\t(t) =>\n\t\t\t\t\t\t\t\tt.multiaddr.toString().includes(\"/tcp/\") &&\n\t\t\t\t\t\t\t\t!t.multiaddr.toString().includes(\"/ws\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (directTCP) {\n\t\t\t\t\t\t\tdialTarget = directTCP.multiaddr as DialTarget;\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Mesh] ⚡ Direct dial to translated addr: ${dialTarget.toString()}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update the peerStore so subsequent dials also use the right path\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal peerStore\n\t\t\t\t\t\tawait (this.node as any).peerStore.save(targetPeer, {\n\t\t\t\t\t\t\tmultiaddrs: translated.map((t) => t.multiaddr),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Open a protocol stream using high-level dialProtocol for automated it-stream wrapping\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: stream type varies by transport\n\t\t\t\tlet stream: any;\n\t\t\t\ttry {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p returns polymorphic dialProtocol result\n\t\t\t\t\tconst result: any = await this.node\n\t\t\t\t\t\t.dialProtocol(dialTarget, LIOP_MANIFEST_PROTOCOL)\n\t\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\t\t// Catch specific TypeError that breaks the loop\n\t\t\t\t\t\t\tif (String(e).includes(\"toMultihash\")) {\n\t\t\t\t\t\t\t\tthrow new Error(\"INCOMPATIBLE_PEER_ID_INTERFACE\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t});\n\t\t\t\t\tstream = result.stream || result;\n\t\t\t\t} catch (dialErr) {\n\t\t\t\t\tif (attempt === MAX_ATTEMPTS) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Dial error for ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${dialErr}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tconst delay = 500 * 2 ** attempt;\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Dial error for ${peerIdStr} (Attempt ${attempt}). Retrying in ${delay}ms...`,\n\t\t\t\t\t);\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// libp2p v3.x: stream IS the AsyncIterable<Uint8Array>\n\t\t\t\t// v1.x had stream.source; v3.x has the stream itself as iterable\n\t\t\t\tconst source: AsyncIterable<Uint8Array> =\n\t\t\t\t\tstream.source ??\n\t\t\t\t\t(typeof stream[Symbol.asyncIterator] === \"function\" ? stream : null);\n\n\t\t\t\tif (!source) {\n\t\t\t\t\tthrow new Error(\"Target stream has no AsyncIterable source\");\n\t\t\t\t}\n\n\t\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\t\tlet totalReceived = 0;\n\t\t\t\tlet expectedPayloadLength = -1;\n\n\t\t\t\t// Read length-prefixed manifest: first 4 bytes = payload length (BE)\n\t\t\t\tlet manifestTimeoutId: NodeJS.Timeout | undefined;\n\t\t\t\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\t\t\t\tmanifestTimeoutId = setTimeout(\n\t\t\t\t\t\t() => reject(new Error(\"Manifest read timeout (5.0s)\")),\n\t\t\t\t\t\t5000,\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\tfor await (const chunk of source) {\n\t\t\t\t\t\t\t\tif (!chunk) continue;\n\t\t\t\t\t\t\t\t// libp2p streams yield Uint8ArrayList (from uint8arraylist package)\n\t\t\t\t\t\t\t\t// which reports .length correctly but Buffer.from() produces zeros.\n\t\t\t\t\t\t\t\t// .subarray() returns a flat contiguous Uint8Array with actual data.\n\t\t\t\t\t\t\t\tconst raw =\n\t\t\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Uint8ArrayList type guard\n\t\t\t\t\t\t\t\t\ttypeof (chunk as any).subarray === \"function\"\n\t\t\t\t\t\t\t\t\t\t? (chunk as { subarray: () => Uint8Array }).subarray()\n\t\t\t\t\t\t\t\t\t\t: chunk instanceof Uint8Array\n\t\t\t\t\t\t\t\t\t\t\t? chunk\n\t\t\t\t\t\t\t\t\t\t\t: new Uint8Array(0);\n\t\t\t\t\t\t\t\tconst bytes = Buffer.from(\n\t\t\t\t\t\t\t\t\traw.buffer,\n\t\t\t\t\t\t\t\t\traw.byteOffset,\n\t\t\t\t\t\t\t\t\traw.byteLength,\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (bytes.length > 0) {\n\t\t\t\t\t\t\t\t\tchunks.push(bytes);\n\t\t\t\t\t\t\t\t\ttotalReceived += bytes.length;\n\n\t\t\t\t\t\t\t\t\t// Extract expected length from the first 4 bytes once available\n\t\t\t\t\t\t\t\t\tif (expectedPayloadLength < 0 && totalReceived >= 4) {\n\t\t\t\t\t\t\t\t\t\tconst header = Buffer.concat(chunks);\n\t\t\t\t\t\t\t\t\t\texpectedPayloadLength = header.readUInt32BE(0);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Stop reading once we have the full payload (4 prefix + N payload)\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\texpectedPayloadLength >= 0 &&\n\t\t\t\t\t\t\t\t\t\ttotalReceived >= 4 + expectedPayloadLength\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tbreak;\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\ttimeoutPromise,\n\t\t\t\t\t]);\n\t\t\t\t} catch (itErr: unknown) {\n\t\t\t\t\tif (chunks.length === 0) throw itErr;\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Partial manifest read from ${peerIdStr}: ${itErr instanceof Error ? itErr.message : String(itErr)}`,\n\t\t\t\t\t);\n\t\t\t\t} finally {\n\t\t\t\t\tif (manifestTimeoutId) clearTimeout(manifestTimeoutId);\n\t\t\t\t}\n\n\t\t\t\tconst raw = Buffer.concat(chunks);\n\t\t\t\tif (raw.length < 4) {\n\t\t\t\t\tthrow new Error(\"Received empty/invalid manifest (too short)\");\n\t\t\t\t}\n\n\t\t\t\t// Use the length prefix to extract exactly the expected JSON\n\t\t\t\tconst declaredLen = raw.readUInt32BE(0);\n\t\t\t\tconst jsonStr = raw.subarray(4, 4 + declaredLen).toString(\"utf-8\");\n\t\t\t\tconst manifest: LiopManifest = JSON.parse(jsonStr);\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Received manifest from ${peerIdStr}: ${manifest.tools.length} tools`,\n\t\t\t\t);\n\t\t\t\tthis.clearManifestDialFailure(peerIdStr);\n\n\t\t\t\treturn manifest;\n\t\t\t} catch (err: unknown) {\n\t\t\t\tif (attempt === MAX_ATTEMPTS) {\n\t\t\t\t\tthis.recordManifestDialFailure(peerIdStr);\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Failed to query manifest from ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst delay = 500 * 2 ** attempt;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Query error for ${peerIdStr} (Attempt ${attempt}): ${err instanceof Error ? err.message : String(err)}. Retrying in ${delay}ms...`,\n\t\t\t\t);\n\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Discovers all peers in the DHT that have announced \"liop:manifest\".\n\t * Returns their PeerIDs for subsequent manifest queries.\n\t */\n\tasync discoverManifestProviders(): Promise<string[]> {\n\t\treturn this.findProviders(LIOP_MANIFEST_CAPABILITY);\n\t}\n\n\t/**\n\t * Announces this node as a manifest provider in the DHT.\n\t * Should be called after tools/resources have been registered.\n\t */\n\tasync announceManifest(): Promise<void> {\n\t\tawait this.announceCapability(LIOP_MANIFEST_CAPABILITY);\n\t}\n\n\t/**\n\t * Returns the current size of the routing table for diagnostic purposes.\n\t */\n\tgetRoutingTableSize(): number {\n\t\tif (!this.node) return 0;\n\t\t// @ts-expect-error: Accessing internal routing table size for diagnostics\n\t\treturn this.node.services.dht?.routingTable?.size || 0;\n\t}\n\n\tgetPeerId(): string {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\treturn this.node.peerId.toString();\n\t}\n\n\tasync sign(data: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.localPrivateKey) {\n\t\t\tthrow new Error(\"Local identity not loaded or initialized\");\n\t\t}\n\t\t// libp2p private key implementations typically return a Promise<Uint8Array> or Uint8Array\n\t\treturn Buffer.from(await this.localPrivateKey.sign(data));\n\t}\n\n\tgetMultiaddrs(): string[] {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\treturn this.node.getMultiaddrs().map((a) => a.toString());\n\t}\n\n\tasync announceCapability(hash: string): Promise<void> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\n\t\t// Buffer the capability for reactive re-announcement\n\t\tthis.announcedCapabilities.add(hash);\n\n\t\ttry {\n\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Announcing capability: ${hash} (CID: ${cid.toString()})`,\n\t\t\t);\n\n\t\t\t// In libp2p v1.x, contentRouting.provide returns Promise<void>\n\t\t\tawait this.node.contentRouting.provide(cid);\n\t\t\tlog.info(`[LIOP-Mesh] Successfully announced capability: ${hash}`);\n\n\t\t\t// [DEV-ONLY] Self-verification\n\t\t\tconst selfId = this.node.peerId.toString();\n\t\t\tfor await (const peer of this.node.contentRouting.findProviders(cid)) {\n\t\t\t\tif (peer.id.toString() === selfId) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Self-verification success: Node is providing ${hash}`,\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] Failed to announce capability: ${error}`);\n\t\t}\n\t}\n\n\tasync findProviders(hash: string): Promise<string[]> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\tconst providers: string[] = [];\n\t\ttry {\n\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Querying DHT for ${hash} (CID: ${cid.toString()})...`,\n\t\t\t);\n\n\t\t\tlet foundAny = false;\n\n\t\t\t// Phase 103: Adaptive Tail-Wait Polling for DHT Discovery\n\t\t\tconst connections = this.node.getConnections?.()?.length || 0;\n\t\t\tconst idleTimeoutMs = connections > 1 ? 1500 : 3000;\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${idleTimeoutMs}ms (Active connections: ${connections})`,\n\t\t\t);\n\n\t\t\t// We manually iterate the AsyncIterable to abort it via Promise.race\n\t\t\tconst iterator = this.node.contentRouting\n\t\t\t\t.findProviders(cid)\n\t\t\t\t[Symbol.asyncIterator]();\n\t\t\tlet isDone = false;\n\n\t\t\twhile (!isDone) {\n\t\t\t\tconst nextPromise = iterator.next();\n\t\t\t\tconst timeoutPromise = new Promise<{ timeout: true }>((resolve) =>\n\t\t\t\t\tsetTimeout(() => resolve({ timeout: true }), idleTimeoutMs),\n\t\t\t\t);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await Promise.race([nextPromise, timeoutPromise]);\n\n\t\t\t\t\tif (result && typeof result === \"object\" && \"timeout\" in result) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (typeof iterator.return === \"function\") {\n\t\t\t\t\t\t\t// Fire-and-forget: Kademlia iterators can block for 30s on return()\n\t\t\t\t\t\t\titerator.return().catch(() => {});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic Kademlia peer result\n\t\t\t\t\tconst itResult = result as IteratorResult<any>;\n\t\t\t\t\tif (itResult.done) {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tfoundAny = true;\n\t\t\t\t\tconst peer = itResult.value;\n\t\t\t\t\tconst peerId = peer.id.toString();\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Found provider: ${peerId}`);\n\t\t\t\t\tif (!providers.includes(peerId)) {\n\t\t\t\t\t\tproviders.push(peerId);\n\t\t\t\t\t}\n\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t`[LIOP-Mesh] DHT iteration error: ${e instanceof Error ? e.message : String(e)}`,\n\t\t\t\t\t);\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!foundAny) {\n\t\t\t\tconst services = this.node.services as {\n\t\t\t\t\tdht?: { routingTable?: { size: number } };\n\t\t\t\t};\n\t\t\t\tconst dhtSize = services.dht?.routingTable?.size || 0;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] DHT search for ${hash} returned zero results (routing table size: ${dhtSize})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// [DEVELOPER-EXPERIENCE] Local Loopback Discovery\n\t\t\t// If we are providing this capability, ensure we find ourselves even if DHT findProviders doesn't return us.\n\t\t\tif (this.announcedCapabilities.has(hash)) {\n\t\t\t\tconst selfId = this.node.peerId.toString();\n\t\t\t\tif (!providers.includes(selfId)) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Including local node (${selfId}) in results for ${hash}`,\n\t\t\t\t\t);\n\t\t\t\t\tproviders.push(selfId);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Error finding providers for ${hash}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] DHT search for ${hash} finished. Found ${providers.length} providers.`,\n\t\t);\n\t\treturn providers;\n\t}\n\n\tasync resolvePeer(peerIdStr: string): Promise<string[]> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\ttry {\n\t\t\t// Strategy 1: Check active connections for the peer's multiaddrs\n\t\t\tconst connections = this.node.getConnections();\n\t\t\tfor (const conn of connections) {\n\t\t\t\tif (conn.remotePeer.toString() === peerIdStr) {\n\t\t\t\t\tconst remoteAddr = conn.remoteAddr.toString();\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Resolved peer ${peerIdStr} via active connection: ${remoteAddr}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn [remoteAddr];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Strategy 2: Try peerStore (iterate all peers to avoid toMultihash conflict)\n\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\tfor (const peer of allPeers) {\n\t\t\t\tif (peer.id.toString() === peerIdStr && peer.addresses.length > 0) {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal libp2p addr type\n\t\t\t\t\tconst addrs = peer.addresses.map((a: any) => a.multiaddr.toString());\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Resolved peer ${peerIdStr} via peerStore: ${addrs[0]}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn addrs;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Peer ${peerIdStr} not found in connections or peerStore`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlog.info(`[LIOP-Mesh] Failed to resolve peer ${peerIdStr}: ${error}`);\n\t\t}\n\t\treturn [];\n\t}\n}\n"]}
@@ -1,13 +0,0 @@
1
- import {g}from'./chunk-I46YEWND.js';import {b}from'./chunk-SB5XJXKV.js';import {a}from'./chunk-S6RJHZV2.js';import*as v from'http';import*as m from'http2';import*as y from'net';function u(h,t){return {resource:t,authorization_servers:[h],scopes_supported:b,bearer_methods_supported:["header"],resource_documentation:"https://github.com/nekzus/liop"}}var f=class{constructor(t,e=null,i=50051){this.liopServer=t;this.meshNode=e;this.jwtValidator=this.liopServer.jwtValidator,this.oauthProvider=this.liopServer.oauthProvider,this.router=new g(this.liopServer,this.meshNode,i),this.h2Server=m.createServer(),this.setupH2Routes(),this.h1Server=v.createServer(),this.setupH1Routes(),this.netServer=y.createServer(r=>{r.once("data",o=>{let n=o.toString().startsWith("PRI * HTTP/2.0");a.info(`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${n?"HTTP/2 (gRPC)":"HTTP/1.1 (MCP)"}`),n?this.h2Server.emit("connection",r):this.h1Server.emit("connection",r),r.unshift(o);}),r.on("error",o=>a.error(`[LIOP-Gateway] NetServer Socket Error: ${o.message}`));}),this.h1Server.on("error",r=>a.error(`[LIOP-Gateway] H1 Server Error: ${r.message}`)),this.h2Server.on("error",r=>a.error(`[LIOP-Gateway] H2 Server Error: ${r.message}`)),a.info("[LIOP-Gateway] Hybrid adapter initialized.");}netServer;h2Server;h1Server;router;jwtValidator;oauthProvider;setupH2Routes(){this.h2Server.on("stream",(t,e)=>{let i=e["content-type"],r=e[":path"];i==="application/grpc"?this.handleGrpcStream(t):r==="/mcp"&&this.handleMcpH2Stream(t,e);});}setupH1Routes(){this.h1Server.on("request",async(t,e)=>{let i=t.url||"",r=t.method;if(i.startsWith("/oidc")&&this.oauthProvider){let o=typeof this.oauthProvider.callback=="function"?this.oauthProvider.callback():this.oauthProvider,n=t.url;t.url=(n||"").slice(5)||"/";try{return o(t,e)}finally{t.url=n;}}if(r==="GET"&&i==="/.well-known/oauth-protected-resource"){if(this.jwtValidator){let o=u(this.jwtValidator.getIssuer(),this.jwtValidator.getAudience());e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(o));return}e.writeHead(404),e.end("Not Found");return}if(r==="GET"&&(i==="/"||i==="/mcp"||i==="/health")){if(i==="/health"&&t.headers.accept?.includes("application/json")){let o=this.meshNode?{peerId:this.meshNode.getPeerId()?.toString()||"",multiaddrs:this.meshNode.getMultiaddrs().map(p=>p.toString())}:null,n=this.jwtValidator?.getIssuer(),a=n?n.endsWith("/oidc")?n:`${n}/oidc`:"",d=this.jwtValidator&&n?{issuer:n,jwks_uri:`${a}/jwks`,...this.oauthProvider?{token_endpoint:`${a}/token`}:{}}:void 0;e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify({status:"healthy",node:this.liopServer.getServerInfo(),mesh:o,tools:this.liopServer.listTools().map(p=>p.name),auth:d,timestamp:new Date().toISOString()}));return}e.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),e.end(`
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
- <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
- <h1 style="color:#38bdf8;margin-top:0">LIOP Protocol Transformer</h1>
5
- <p style="opacity:0.8;font-weight:600">L4/L7 Transcoding: JSON-RPC &harr; gRPC</p>
6
- <p style="opacity:0.6;font-size:14px">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>
7
- <div style="background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155">
8
- <code style="color:#10b981">Endpoint: http://localhost:3000/mcp</code>
9
- </div>
10
- </div>
11
- </body>
12
- `);return}if(i==="/mcp"&&r==="POST"){let o=null;if(this.jwtValidator){let a=t.headers.authorization;if(!a?.startsWith("Bearer ")){e.writeHead(401,{"WWW-Authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Unauthorized"}));return}try{o=await this.jwtValidator.validate(a.slice(7));}catch(d){e.writeHead(401,{"WWW-Authenticate":`Bearer error="invalid_token", error_description="${d.message}"`,"Content-Type":"application/json"}),e.end(JSON.stringify({error:"Invalid token"}));return}}let n="";t.on("data",a=>n+=a.toString()),t.on("end",async()=>{try{let a=JSON.parse(n),d=await this.router.dispatch(a,o);e.writeHead(200,{"Content-Type":"application/json"}),e.end(JSON.stringify(d));}catch(a$1){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${a$1.message}`),e.writeHead(400),e.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else e.writeHead(404),e.end("Not Found");});}handleGrpcStream(t){t.on("data",e=>{let i=e;i&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${i.length} bytes`);}),t.respond({":status":200,"content-type":"application/grpc"}),t.end();}handleMcpH2Stream(t,e){let i="";t.on("data",r=>i+=r.toString()),t.on("end",async()=>{try{let r=null;if(this.jwtValidator){let n=e.authorization;if(!n?.startsWith("Bearer ")){t.respond({":status":401,"www-authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"content-type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}try{r=await this.jwtValidator.validate(n.slice(7));}catch(a){t.respond({":status":401,"www-authenticate":`Bearer error="invalid_token", error_description="${a.message}"`,"content-type":"application/json"}),t.end(JSON.stringify({error:"Invalid token"}));return}}let o=await this.router.dispatch(JSON.parse(i),r);o?(t.respond({":status":200,"content-type":"application/json"}),t.end(JSON.stringify(o))):t.close();}catch{t.respond({":status":400}),t.end();}});}async listen(t,e="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let i=this.liopServer.listTools();for(let r of i)await this.meshNode.announceCapability(r.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${r.name}`);}return new Promise((i,r)=>{this.netServer.on("error",o=>{o.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${t} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${o.message}`),r(o);}),this.netServer.listen(t,e,()=>{let o=this.netServer.address(),n=typeof o=="string"?o:o?.address||e,a$1=typeof o=="string"?t:o?.port||t;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${n}:${a$1}`),i(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{u as a,f as b};//# sourceMappingURL=chunk-GI2LSJYZ.js.map
13
- //# sourceMappingURL=chunk-GI2LSJYZ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/security/prm.ts","../src/gateway/hybrid.ts"],"names":["buildProtectedResourceMetadata","issuer","audience","LIOP_SCOPES","LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","callback","originalUrl","prm","meshInfo","m","baseUrl","authInfoResponse","t","authInfo","authHeader","e","body","chunk","jsonRequest","response","data","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"iLAoCO,SAASA,CAAAA,CACfC,CAAAA,CACAC,CAAAA,CAC4B,CAC5B,OAAO,CACN,QAAA,CAAUA,CAAAA,CACV,qBAAA,CAAuB,CAACD,CAAM,CAAA,CAC9B,gBAAA,CAAkBE,CAAAA,CAClB,wBAAA,CAA0B,CAAC,QAAQ,CAAA,CACnC,uBAAwB,gCACzB,CACD,CCjCO,IAAMC,CAAAA,CAAN,KAAwB,CAS9B,WAAA,CACSC,CAAAA,CACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,CAAAA,CAGR,IAAA,CAAK,YAAA,CAAe,IAAA,CAAK,UAAA,CAAW,YAAA,CACpC,IAAA,CAAK,aAAA,CAAgB,IAAA,CAAK,UAAA,CAAW,aAAA,CAGrC,KAAK,MAAA,CAAS,IAAIE,CAAAA,CAAc,IAAA,CAAK,UAAA,CAAY,IAAA,CAAK,SAAUD,CAAO,CAAA,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C,IAAA,CAAK,SAAA,CAAU,EAAA,CAAG,OAAA,CAAU9B,CAAAA,EAAmC,CAC1DA,CAAAA,CAAI,IAAA,GAAS,YAAA,CAChBD,CAAAA,CAAI,IAAA,CACH,CAAA,2BAAA,EAA8B0B,CAAI,CAAA,sCAAA,CACnC,CAAA,CAEA1B,CAAAA,CAAI,KAAA,CAAM,CAAA,8BAAA,EAAiCC,CAAAA,CAAI,OAAO,CAAA,CAAE,CAAA,CAEzD8B,CAAAA,CAAO9B,CAAG,EACX,CAAC,CAAA,CAED,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOyB,CAAAA,CAAMC,CAAAA,CAAM,IAAM,CACvC,IAAMK,CAAAA,CAAO,IAAA,CAAK,SAAA,CAAU,OAAA,EAAQ,CAC9BC,CAAAA,CACL,OAAOD,CAAAA,EAAS,QAAA,CAAWA,CAAAA,CAAOA,CAAAA,EAAM,OAAA,EAAWL,CAAAA,CAC9CO,GAAAA,CACL,OAAOF,CAAAA,EAAS,QAAA,CAAWN,CAAAA,CAAOM,CAAAA,EAAM,IAAA,EAAQN,CAAAA,CAEjD1B,CAAAA,CAAI,IAAA,CACH,CAAA,sEAAA,EAAoEiC,CAAU,CAAA,CAAA,EAAIC,GAAY,CAAA,CAC/F,CAAA,CACAJ,CAAAA,CAAQI,GAAY,EACrB,CAAC,EACF,CAAC,CACF,CAEA,MAAa,IAAA,EAAO,CACf,IAAA,CAAK,QAAA,EACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,EAAK,CAE1B,IAAA,CAAK,SAAA,CAAU,KAAA,EAAM,CACrB,IAAA,CAAK,QAAA,CAAS,KAAA,EAAM,CACpB,IAAA,CAAK,QAAA,CAAS,KAAA,GACf,CAEO,SAAA,EAA2B,CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-GI2LSJYZ.js","sourcesContent":["/**\n * LIOP Protected Resource Metadata — RFC 9728\n *\n * Builds the JSON document served at /.well-known/oauth-protected-resource.\n * This enables MCP clients to discover the authorization server and\n * required scopes for accessing LIOP tools and resources.\n *\n * Standards: RFC 9728, MCP Spec 2025-11-25\n */\n\nimport { LIOP_SCOPES } from \"./rbac.js\";\n\n/**\n * RFC 9728 Protected Resource Metadata response.\n *\n * @see https://datatracker.ietf.org/doc/rfc9728\n */\nexport interface ProtectedResourceMetadata {\n\t/** Identifier for the protected resource. */\n\tresource: string;\n\t/** Array of authorization server issuer URLs that can issue tokens for this resource. */\n\tauthorization_servers: string[];\n\t/** OAuth scopes accepted by this resource. */\n\tscopes_supported: readonly string[];\n\t/** Methods of presenting the bearer token (always \"header\" for LIOP). */\n\tbearer_methods_supported: string[];\n\t/** URL to the resource documentation. */\n\tresource_documentation: string;\n}\n\n/**\n * Builds the Protected Resource Metadata document (RFC 9728).\n *\n * @param issuer - OIDC issuer URL of the Nexus authorization server\n * @param audience - JWT audience claim (resource identifier)\n */\nexport function buildProtectedResourceMetadata(\n\tissuer: string,\n\taudience: string,\n): ProtectedResourceMetadata {\n\treturn {\n\t\tresource: audience,\n\t\tauthorization_servers: [issuer],\n\t\tscopes_supported: LIOP_SCOPES,\n\t\tbearer_methods_supported: [\"header\"],\n\t\tresource_documentation: \"https://github.com/nekzus/liop\",\n\t};\n}\n","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 { AuthInfo, JwtValidator } from \"../security/jwt-validator.js\";\nimport { buildProtectedResourceMetadata } from \"../security/prm.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\tprivate jwtValidator?: JwtValidator;\n\t// biome-ignore lint/suspicious/noExplicitAny: oidc-provider is loaded in Phase C\n\tprivate oauthProvider?: any;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\tthis.jwtValidator = this.liopServer.jwtValidator;\n\t\tthis.oauthProvider = this.liopServer.oauthProvider;\n\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\t// [SEC] M2M OAuth 2.1 OIDC Authorization Server Router (Phase C proxy)\n\t\t\tif (url.startsWith(\"/oidc\") && this.oauthProvider) {\n\t\t\t\tconst callback =\n\t\t\t\t\ttypeof this.oauthProvider.callback === \"function\"\n\t\t\t\t\t\t? this.oauthProvider.callback()\n\t\t\t\t\t\t: this.oauthProvider;\n\t\t\t\t// Rewrite req.url to strip the '/oidc' prefix before delegating to oidc-provider\n\t\t\t\tconst originalUrl = req.url;\n\t\t\t\treq.url = (originalUrl || \"\").slice(5) || \"/\";\n\t\t\t\ttry {\n\t\t\t\t\treturn callback(req, res);\n\t\t\t\t} finally {\n\t\t\t\t\treq.url = originalUrl;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// [SEC] RFC 9728 Protected Resource Metadata (PRM) Endpoint\n\t\t\tif (method === \"GET\" && url === \"/.well-known/oauth-protected-resource\") {\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst prm = buildProtectedResourceMetadata(\n\t\t\t\t\t\tthis.jwtValidator.getIssuer(),\n\t\t\t\t\t\tthis.jwtValidator.getAudience(),\n\t\t\t\t\t);\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(JSON.stringify(prm));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t\treturn;\n\t\t\t}\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\tconst issuer = this.jwtValidator?.getIssuer();\n\t\t\t\t\tconst baseUrl = issuer\n\t\t\t\t\t\t? issuer.endsWith(\"/oidc\")\n\t\t\t\t\t\t\t? issuer\n\t\t\t\t\t\t\t: `${issuer}/oidc`\n\t\t\t\t\t\t: \"\";\n\t\t\t\t\tconst authInfoResponse =\n\t\t\t\t\t\tthis.jwtValidator && issuer\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tissuer,\n\t\t\t\t\t\t\t\t\tjwks_uri: `${baseUrl}/jwks`,\n\t\t\t\t\t\t\t\t\t...(this.oauthProvider\n\t\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\t\ttoken_endpoint: `${baseUrl}/token`,\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: undefined;\n\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\tauth: authInfoResponse,\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 authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = req.headers.authorization;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tres.writeHead(401, {\n\t\t\t\t\t\t\t\"WWW-Authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tres.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\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, authInfo);\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\theaders: 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\tlet authInfo: AuthInfo | null = null;\n\n\t\t\t\t// [SEC] Continuous verification of Bearer token over HTTP/2 (NIST SP 800-207)\n\t\t\t\tif (this.jwtValidator) {\n\t\t\t\t\tconst authHeader = headers.authorization as string;\n\t\t\t\t\tif (!authHeader?.startsWith(\"Bearer \")) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\":\n\t\t\t\t\t\t\t\t'Bearer error=\"invalid_token\", error_description=\"Missing or malformed Authorization header\"',\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Unauthorized\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tauthInfo = await this.jwtValidator.validate(authHeader.slice(7));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\t\":status\": 401,\n\t\t\t\t\t\t\t\"www-authenticate\": `Bearer error=\"invalid_token\", error_description=\"${(e as Error).message}\"`,\n\t\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end(JSON.stringify({ error: \"Invalid token\" }));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body), authInfo);\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,3 +0,0 @@
1
- import {a}from'./chunk-S6RJHZV2.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var T=10,y=1800*1e3,R=60*1e3,d=class{constructor(e,r={}){this.options=r;this.app=new Hono,this.bridgeLogic=new p(e),this.activeSessions=new Map,this.maxSessionsPerIp=r.maxSessionsPerIp??T,this.sessionTimeoutMs=r.sessionTimeoutMs??y,this.setupRoutes();}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:r}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new r({sessionIdGenerator:()=>randomUUID(),onsessioninitialized:t=>{this.activeSessions.set(t,{transport:s,lastActivity:Date.now(),clientIp:e}),a.info(`[LIOP-StreamBridge] Session opened: ${t} (IP: ${e})`);}});return s.onmessage=async t=>{if(s.sessionId){let i=this.activeSessions.get(s.sessionId);i&&(i.lastActivity=Date.now());}try{let i=await this.bridgeLogic.handleJsonRpcRequest(t);i!==void 0&&await s.send(i);}catch(i){a.info("[LIOP-StreamBridge] JSON-RPC error:",i.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),a.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let r=0;for(let s of this.activeSessions.values())s.clientIp===e&&r++;return r}getClientIp(e){return e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||"unknown"}evictIdleSessions(){let e=Date.now();for(let[r,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(a.info(`[LIOP-StreamBridge] Evicting idle session: ${r}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(r));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),a.info("=".repeat(60)),a.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),a.info("No ZERO_TRUST_TOKEN found in environment."),a.info("A secure ephemeral token has been generated for this session:"),a.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),a.info("=".repeat(60))),this.app.use("/mcp",async(e,r)=>{let s=e.req.header("Authorization");if(!s?.startsWith("Bearer "))return e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);let t=s.slice(7),i=process.env.ZERO_TRUST_TOKEN;if(i&&t===i){await r();return}let n=this.bridgeLogic.getServer()?.jwtValidator;if(n)try{await n.validate(t),await r();return}catch(a$1){return a.info(`[LIOP-StreamBridge] JWT Validation failed: ${a$1.message}`),e.json({error:`Unauthorized: JWT Validation failed - ${a$1.message}`},401)}return a.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401)}),this.app.all("/mcp",async e=>{let r=e.req.header("mcp-session-id");if(r){let n=this.activeSessions.get(r);if(!n)return e.json({error:"Session not found"},404);n.lastActivity=Date.now();let a$1=await n.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(r),a.info(`[LIOP-StreamBridge] Session closed (DELETE): ${r}`)),a$1}let s=this.getClientIp(e),t=this.countSessionsByIp(s);return t>=this.maxSessionsPerIp?(a.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${s} (${t} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(s)).handleRequest(e.req.raw)});}async start(e){let r=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),R),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:r},t=>{a.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${t.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,r]of this.activeSessions)await r.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),a.info("[LIOP-StreamBridge] HTTP ports released."));}};var p=class{constructor(e,r={}){this.options=r;e?.constructor?.name==="LiopServer"?(this.liopServer=e,a.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let r=e.id,s=e.method,t=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(r,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(r,s,t):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(r,s,t):this.errorResponse(r,-32601,"Bridge source not configured")}async handleLiopToMcp(e,r,s){if(!this.liopServer)return null;if(r==="initialize")return this.successResponse(e,{protocolVersion:"2025-11-25",capabilities:{prompts:{},resources:{},tools:{}},serverInfo:this.liopServer.getServerInfo()});if(r!=="notifications/initialized"){if(r==="ping")return this.successResponse(e,{});if(r==="tools/list"){let t=this.liopServer.listTools();return this.successResponse(e,{tools:t})}if(r==="resources/list"){let t=this.liopServer.listResources();return this.successResponse(e,{resources:t})}if(r==="prompts/list"){let t=this.liopServer.listPrompts();return this.successResponse(e,{prompts:t})}if(r==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let t=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let t=await this.liopServer.readResource(s.uri);return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let t={name:s.name,arguments:s.arguments||{}};try{let i=await this.liopServer.callTool(t);return (i.isError?!0:await this.verifyZkReceipt(t,i))?this.successResponse(e,i):this.successResponse(e,{content:[{type:"text",text:"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload."}],isError:!0})}catch(i){return this.errorResponse(e,-32e3,i.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,r){return {jsonrpc:"2.0",id:e,result:r}}errorResponse(e,r,s){return {jsonrpc:"2.0",id:e,error:{code:r,message:s}}}async verifyZkReceipt(e,r){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,t=r.content[0]?.text;if(t&&typeof t=="string")try{let i=JSON.parse(t);if(i.image_id||i.zk_receipt){let{LiopVerifier:n}=await import('./verifier-XU2DB56Z.js');if(!await new n().verifyZkReceipt(Buffer.from(s,"utf-8"),i.image_id,Buffer.from(i.zk_receipt||"","base64"),void 0,i.computation_result))return !1;i.audit_status="VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",r.content[0].text=JSON.stringify(i);}}catch{}return !0}catch(s){return a.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:t}=await import('./server.js');if(this.liopServer=new t(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let i=this.legacyMcpServer;if(i._registeredTools)for(let[n,a]of Object.entries(i._registeredTools)){let c=a;this.liopServer.tool(n,c.description||"",c.inputSchema||{},async l=>await c.handler(l));}if(i._registeredResources)for(let[n,a]of Object.entries(i._registeredResources)){let c=a;this.liopServer.resource(c.name,n,c.metadata?.description||"",c.metadata?.mimeType||"application/octet-stream",async()=>(await c.readCallback(new URL(n))).contents[0].text);}}return}let r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=async()=>{a.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);};r.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),r.on("line",async t=>{if(t.trim())try{let i=JSON.parse(t),n=await this.handleJsonRpcRequest(i);n&&process.stdout.write(`${JSON.stringify(n)}
2
- `);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}getServer(){return this.liopServer}};export{d as a,p as b};//# sourceMappingURL=chunk-GJUZGKZW.js.map
3
- //# sourceMappingURL=chunk-GJUZGKZW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","token","expectedToken","jwtValidator","e","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,CAAAA,CAA8B,GAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,CAAAA,CAAuB,GAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CAC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AAQ,MACf,MAAA,CAAQ,OAAA,CAAQ,OAChB,QAAA,CAAU,KACX,CAAC,CAAA,CAEKC,CAAAA,CAAW,SAAY,CAC5B/C,EAAI,IAAA,CAAK,wCAAwC,EAC7C,IAAA,CAAK,UAAA,EAAY,MAAM,IAAA,CAAK,UAAA,CAAW,KAAA,EAAM,CACjD,QAAQ,IAAA,CAAK,CAAC,EACf,CAAA,CAEA8C,CAAAA,CAAG,GAAG,OAAA,CAASC,CAAQ,CAAA,CACvB,OAAA,CAAQ,GAAG,QAAA,CAAUA,CAAQ,EAC7B,OAAA,CAAQ,EAAA,CAAG,UAAWA,CAAQ,CAAA,CAE9BD,CAAAA,CAAG,EAAA,CAAG,OAAQ,MAAOE,CAAAA,EAAS,CAC7B,GAAKA,CAAAA,CAAK,MAAK,CACf,GAAI,CACH,IAAMtB,EAAU,IAAA,CAAK,KAAA,CAAMsB,CAAI,CAAA,CACzB/B,CAAAA,CAAW,MAAM,IAAA,CAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,OAASF,CAAAA,CAAY,CACpBf,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBe,EAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CAEO,SAAA,EAA+B,CACrC,OAAO,IAAA,CAAK,UACb,CACD","file":"chunk-GJUZGKZW.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\t\t\tif (!auth?.startsWith(\"Bearer \")) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst token = auth.slice(7);\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\n\t\t\t// Check static token fallback first (retrocompatibility)\n\t\t\tif (expectedToken && token === expectedToken) {\n\t\t\t\tawait next();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Validate with JWT Validator if configured on the server\n\t\t\tconst jwtValidator = this.bridgeLogic.getServer()?.jwtValidator;\n\t\t\tif (jwtValidator) {\n\t\t\t\ttry {\n\t\t\t\t\tawait jwtValidator.validate(token);\n\t\t\t\t\tawait next();\n\t\t\t\t\treturn;\n\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] JWT Validation failed: ${(e as Error).message}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: `Unauthorized: JWT Validation failed - ${(e as Error).message}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t401,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.info(\n\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t);\n\t\t\treturn c.json(\n\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t401,\n\t\t\t);\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\t// If the tool execution returned an error (e.g. policy violation), we bypass\n\t\t\t\t// ZK-Receipt verification because no cryptographic proof is generated for errors.\n\t\t\t\tconst isVerified = result.isError\n\t\t\t\t\t? true\n\t\t\t\t\t: await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tdata.computation_result,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\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\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\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\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic getServer(): LiopServer | null {\n\t\treturn this.liopServer;\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
@@ -1,33 +0,0 @@
1
- import {a as a$1}from'./chunk-PWCXZWSE.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {a as a$2}from'./chunk-SB5XJXKV.js';import {a as a$3,c}from'./chunk-V5MKJT6S.js';import {a}from'./chunk-S6RJHZV2.js';import*as K from'crypto';import*as ce from'@grpc/grpc-js';var W=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 fe(){try{let c=await import('gpt-tokenizer'),e=new W(c.countTokens,c.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 he(){return new B}var N="1.9.1";var ge=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ee(c){let e=new Set([c]),t=new Set,r=c.match(ge);if(!r)return ()=>false;let n={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(n.prerelease!=null)return function(a){return a===c};function i(s){return t.add(s),false}function o(s){return e.add(s),true}return function(a){if(e.has(a))return true;if(t.has(a))return false;let l=a.match(ge);if(!l)return i(a);let u={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return u.prerelease!=null||n.major!==u.major?i(a):n.major===0?n.minor===u.minor&&n.patch<=u.patch?o(a):i(a):n.minor<=u.minor?o(a):i(a)}}var Te=Ee(N);var ke=N.split(".")[0],$=Symbol.for(`opentelemetry.js.api.${ke}`),A=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function V(c,e,t,r=false){var n;let i=A[$]=(n=A[$])!==null&&n!==void 0?n:{version:N};if(!r&&i[c]){let o=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${c}`);return t.error(o.stack||o.message),false}if(i.version!==N){let o=new Error(`@opentelemetry/api: Registration of version v${i.version} for ${c} does not match previously registered API v${N}`);return t.error(o.stack||o.message),false}return i[c]=e,t.debug(`@opentelemetry/api: Registered a global for ${c} v${N}.`),true}function b(c){var e,t;let r=(e=A[$])===null||e===void 0?void 0:e.version;if(!(!r||!Te(r)))return (t=A[$])===null||t===void 0?void 0:t[c]}function F(c,e){e.debug(`@opentelemetry/api: Unregistering a global for ${c} v${N}.`);let t=A[$];t&&delete t[c];}var z=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger";}debug(...e){return x("debug",this._namespace,e)}error(...e){return x("error",this._namespace,e)}info(...e){return x("info",this._namespace,e)}warn(...e){return x("warn",this._namespace,e)}verbose(...e){return x("verbose",this._namespace,e)}};function x(c,e,t){let r=b("diag");if(r)return r[c](e,...t)}var v;(function(c){c[c.NONE=0]="NONE",c[c.ERROR=30]="ERROR",c[c.WARN=50]="WARN",c[c.INFO=60]="INFO",c[c.DEBUG=70]="DEBUG",c[c.VERBOSE=80]="VERBOSE",c[c.ALL=9999]="ALL";})(v||(v={}));function ye(c,e){c<v.NONE?c=v.NONE:c>v.ALL&&(c=v.ALL),e=e||{};function t(r,n){let i=e[r];return typeof i=="function"&&c>=n?i.bind(e):function(){}}return {error:t("error",v.ERROR),warn:t("warn",v.WARN),info:t("info",v.INFO),debug:t("debug",v.DEBUG),verbose:t("verbose",v.VERBOSE)}}var Se="diag",D=class c{static instance(){return this._instance||(this._instance=new c),this._instance}constructor(){function e(n){return function(...i){let o=b("diag");if(o)return o[n](...i)}}let t=this,r=(n,i={logLevel:v.INFO})=>{var o,s,a;if(n===t){let p=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((o=p.stack)!==null&&o!==void 0?o:p.message),false}typeof i=="number"&&(i={logLevel:i});let l=b("diag"),u=ye((s=i.logLevel)!==null&&s!==void 0?s:v.INFO,n);if(l&&!i.suppressOverrideMessage){let p=(a=new Error().stack)!==null&&a!==void 0?a:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${p}`),u.warn(`Current logger will overwrite one already registered from ${p}`);}return V("diag",u,t,true)};t.setLogger=r,t.disable=()=>{F(Se,t);},t.createComponentLogger=n=>new z(n),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error");}};var J=class{constructor(){}createGauge(e,t){return Ne}createHistogram(e,t){return we}createCounter(e,t){return Re}createUpDownCounter(e,t){return be}createObservableGauge(e,t){return Le}createObservableCounter(e,t){return Ce}createObservableUpDownCounter(e,t){return Me}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},C=class{},Q=class extends C{add(e,t){}},Z=class extends C{add(e,t){}},X=class extends C{record(e,t){}},Y=class extends C{record(e,t){}},U=class{addCallback(e){}removeCallback(e){}},ee=class extends U{},te=class extends U{},oe=class extends U{},_e=new J,Re=new Q,Ne=new X,we=new Y,be=new Z,Ce=new ee,Le=new te,Me=new oe;var re=class{getMeter(e,t,r){return _e}},Oe=new re;var ne="metrics",G=class c{constructor(){}static getInstance(){return this._instance||(this._instance=new c),this._instance}setGlobalMeterProvider(e){return V(ne,e,D.instance())}getMeterProvider(){return b(ne)||Oe}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){F(ne,D.instance());}};var se=G.getInstance();var $e="@nekzus/liop",Ae="1.2.0-alpha.9",xe=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],De=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],H=class{tokenUsage;operationDuration;active=false;constructor(){try{let e=se.getMeter($e,Ae);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:xe}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:De}}),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,n){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":r,"gen_ai.token.type":t,"gen_ai.request.model":"liop-mesh",...n?{"liop.tool.name":n}:{}});}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 Ue={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},P=class c{static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=he(),this.otelBridge=new H,this.initRealEstimator();}initRealEstimator(){fe().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return c.instance||(c.instance=new c),c.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=Ue[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,n=e.get(r)||{input:0,output:0,calls:0,avgDurationMs:0},i=n.avgDurationMs*n.calls+(t.durationMs||0),o=n.calls+1;e.set(r,{input:n.input+t.estimatedInputTokens,output:n.output+t.estimatedOutputTokens,calls:o,avgDurationMs:o>0?i/o: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,n=new Map;for(let d of e.operations){let g=d.type,T=n.get(g)||{count:0,input:0,output:0};n.set(g,{count:T.count+1,input:T.input+d.estimatedInputTokens,output:T.output+d.estimatedOutputTokens});}let i=Array.from(n.entries()),o=i.map(([d,g],T)=>{let y=T===i.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",R=g.output>0?` / ${g.output.toLocaleString()} out`:"";return `${y} ${d} \xD7${g.count} \u2192 ${g.input.toLocaleString()} in${R}`}),s=this.getPerToolReport(),a=Array.from(s.entries()).filter(([d])=>d!=="tools/list"&&d!=="LiopMeshStatus"),l=[];a.length>0&&(l.push("\u251C\u2500 By Tool:"),a.forEach(([d,g],T)=>{let y=T===a.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",R=g.output>0?` / ${g.output.toLocaleString()} out`:"",k=g.avgDurationMs>0?` ~${Math.round(g.avgDurationMs)}ms`:"";l.push(`${y} ${d}: ${g.input.toLocaleString()} in${R} (\xD7${g.calls})${k}`);}));let u=e.operations.filter(d=>d.durationMs!==void 0),p=u.length>0?Math.round(u.reduce((d,g)=>d+(g.durationMs||0),0)/u.length):0,m=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}`,...o,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${r.toLocaleString()} combined)`,...l,...p>0?[`\u251C\u2500 Avg Latency: ${p}ms`]:[],`\u2514\u2500 OTel: ${m}`].join(`
3
- `)}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return `${t}s`;let r=Math.floor(t/60),n=t%60;if(r<60)return `${r}m ${n}s`;let i=Math.floor(r/60),o=r%60;return `${i}h ${o}m`}reset(){this.operations=[];}static destroy(){c.instance=null;}};function L(){let c=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(c==="0"||c==="false"||c==="no")}function ie(c){let e=c,t=[`
4
-
5
- [LIOP-PROTO-V1:`,`\r
6
- \r
7
- [LIOP-PROTO-V1:`,`
8
- [LIOP-PROTO-V1:`];for(let r of t){let n=e.indexOf(r);if(n!==-1){e=e.slice(0,n);break}}return e.trimEnd()}var ve=300,ae=5,Ie=class c$1{constructor(e,t=null,r=50051){this.liopServer=e;this.meshNode=t;this.defaultRpcPort=r;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let n=this.liopServer.listTools().map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),i=this.liopServer.listResources().map(s=>({name:s.name,uri:s.uri,description:s.description,mimeType:s.mimeType})),o=this.liopServer.config;return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...n],resources:i,serverInfo:this.liopServer.getServerInfo(),authRequired:this.liopServer.jwtValidator!==void 0,tokenSlug:o?.tokenSlug,taxonomy:o?.taxonomy?{domain:o.taxonomy.domain||"Unknown Domain",clearanceTier:o.taxonomy.clearanceTier??0,executionTypes:o.taxonomy.executionTypes||[]}:void 0}}),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 t=this.manifestFailureState.get(e);if(!t)return false;let r=Date.now();return r>=t.cooldownUntil?false:(r-t.lastSkipLogAt>c$1.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(),n=(this.manifestFailureState.get(e)?.failures||0)+1,i=Math.min(c$1.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,n-1),c$1.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:n,cooldownUntil:t+i,lastSkipLogAt:0});}async dispatch(e,t){let{method:r,params:n,id:i}=e;if(a.info(`[LIOP-Router] Processing: ${r}`),this.liopServer.jwtValidator){let o=a$2(r,t??null);if(!o.allowed)return a.info(`[LIOP-Router] RBAC Access Denied for method '${r}': ${o.reason}`),{jsonrpc:"2.0",id:i,error:{code:-32099,message:o.reason||"Access Denied"}}}switch(r){case "initialize":return {jsonrpc:"2.0",id:i,result:{protocolVersion:"2025-11-25",capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "ping":return {jsonrpc:"2.0",id:i,result:{}};case "tools/list":{let o=this.liopServer.listTools(),s=await this.getRemoteTools(),a$1=L()?o.map(d=>({...d,description:ie(d.description??"")})):o;a.info(`[LIOP-Router] tools/list: ${o.length} local, ${s.length} remote tools found`);let u=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...a$1,...s],p=P.getInstance(),m=JSON.stringify(u),h=JSON.stringify({tools:u});return p.record({type:"tools_list",method:"tools/list",estimatedInputTokens:p.countTokens(m),estimatedOutputTokens:p.countTokens(h)}),{jsonrpc:"2.0",id:i,result:{tools:u}}}case "tools/call":return this.transcodeMcpToLiop(i,n,t?.token);case "resources/list":{let o=this.liopServer.listResources(),s=await this.getRemoteResources(),a=[...o,...s],l=P.getInstance(),u=JSON.stringify(a);return l.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:l.countTokens(u)}),{jsonrpc:"2.0",id:i,result:{resources:a}}}case "resources/read":{let o=n;if(!o?.uri)return {jsonrpc:"2.0",id:i,error:{code:-32602,message:"Missing resource uri"}};try{let s=Date.now(),a=await this.liopServer.readResource(o.uri),l=P.getInstance(),u=JSON.stringify(a);return l.record({type:"resource_read",method:"resources/read",toolName:o.uri,estimatedInputTokens:l.countTokens(o.uri),estimatedOutputTokens:l.countTokens(u),durationMs:Date.now()-s}),{jsonrpc:"2.0",id:i,result:a}}catch(s){let a$1=o.uri;for(let{manifest:l}of this.manifestCache.values()){let u=l.resources.find(p=>p.uri===a$1);if(u)return a.info(`[LIOP-Router] Resolved resource ${a$1} from cache (Peer: ${l.peerId})`),{jsonrpc:"2.0",id:i,result:{contents:[{uri:u.uri,mimeType:u.mimeType||"text/plain",text:u.text||u.description||"No content provided"}]}}}return {jsonrpc:"2.0",id:i,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}case "prompts/list":{let o=this.liopServer.listPrompts(),s=P.getInstance(),a=JSON.stringify(o);return s.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:s.countTokens(a)}),{jsonrpc:"2.0",id:i,result:{prompts:o}}}case "prompts/get":{let o=n;if(!o?.name)return {jsonrpc:"2.0",id:i,error:{code:-32602,message:"Missing prompt name"}};try{let s=Date.now(),a=await this.liopServer.getPrompt({name:o.name,arguments:o.arguments||{}}),l=P.getInstance(),u=JSON.stringify({name:o.name,arguments:o.arguments}),p=JSON.stringify(a);return l.record({type:"prompt_get",method:"prompts/get",toolName:o.name,estimatedInputTokens:l.countTokens(u),estimatedOutputTokens:l.countTokens(p),durationMs:Date.now()-s}),{jsonrpc:"2.0",id:i,result:a}}catch(s){return {jsonrpc:"2.0",id:i,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}default:return {jsonrpc:"2.0",id:i,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 t=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:n})=>t-n<ve*1e3))return}return this.currentDiscovery=(async()=>{try{let t=Array.from(this.manifestCache.values()).reduce((m,{manifest:h})=>m+h.tools.length,0);if(this.manifestCache.size===0)for(let m=0;m<3;m++){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 ${m+1}/10)...`),await new Promise(d=>setTimeout(d,1e3));}let r=[],n=this.manifestCache.size===0?5:1;for(let m=0;m<n;m++){for(let T=0;T<ae;T++){r=await this.meshNode?.discoverManifestProviders()||[];let y=this.meshNode?.getPeerId();if(r.filter(k=>k!==y).length>0)break;T<ae-1&&(a.info(`[LIOP-Router] DHT discovery attempt ${T+1}/${ae}...`),await new Promise(k=>setTimeout(k,1e3)));}let h=this.meshNode.node?.getConnections().map(T=>T.remotePeer.toString())||[];h.length>0&&(r=Array.from(new Set([...r,...h])));let d=this.meshNode?.getPeerId();if(r.filter(T=>T!==d).length>0)break;m<n-1&&(a.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${m+1}/${n})...`),await new Promise(T=>setTimeout(T,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 i=new Set((this.meshNode.node?.getConnections?.()||[]).map(m=>m.remotePeer.toString()));r=[...r].sort((m,h)=>{let d=i.has(m)?1:0;return (i.has(h)?1:0)-d});let o=0,s=0,a$1=!1,l=this.meshNode?.getPeerId(),u=r.filter(m=>{if(!this.meshNode||m===l||this.shouldSkipManifestQuery(m))return !1;let h=this.manifestCache.get(m);return h&&Date.now()-h.cachedAt<ve*1e3?(o++,!1):!0}),p=await Promise.allSettled(u.map(async m=>this.meshNode?(a.info(`[LIOP-Router] Querying manifest from: ${m}`),{peerId:m,manifest:await this.meshNode.queryManifest(m)}):null));for(let m of p)if(m.status==="fulfilled"&&m.value?.manifest){let{peerId:h,manifest:d}=m.value;this.manifestCache.set(h,{manifest:d,cachedAt:Date.now()}),this.recordManifestQuerySuccess(h),a$1=!0,o++,a.info(`[LIOP-Router] Manifest received from ${h} (${d.tools.length} tools)`);}else m.status==="fulfilled"&&m.value?(this.recordManifestQueryFailure(m.value.peerId),s++,a.info(`[LIOP-Router] Manifest query returned NULL for ${m.value.peerId}`)):m.status==="rejected"&&(s++,a.info("[LIOP-Router] Fatal error querying manifest:",m.reason instanceof Error?m.reason.message:String(m.reason)));this._discoveryStats={candidates:r.length,success:o,failures:s,lastDiscovery:Date.now()},a$1&&Array.from(this.manifestCache.values()).reduce((h,{manifest:d})=>h+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 i=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),o=Number.isFinite(i)&&i>0?i:12e3,s=Date.now()+o,a$1=0,l=-1;for(;Date.now()<s&&!(this.manifestCache.size>=e||(await Promise.race([this.refreshManifestCache(true),new Promise(u=>setTimeout(u,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(u=>setTimeout(u,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,n=new Set(this.liopServer.listTools().map(i=>i.name));for(let[i,{manifest:o}]of this.manifestCache.entries())for(let s of o.tools){if(s.name==="LiopMeshStatus")continue;let a=s.name;(r.has(s.name)||n.has(s.name))&&(a=`${s.name}_${i.slice(-4)}`),r.add(a);let l=o.serverInfo?.name||"Unknown Provider",u=s.description||`Remote tool from ${l}`,p={name:a,description:L()?ie(u):u,inputSchema:s.inputSchema||{type:"object",properties:{}}};typeof p.inputSchema=="object"&&!p.inputSchema.type&&(p.inputSchema.type="object"),typeof p.inputSchema=="object"&&!p.inputSchema.properties&&(p.inputSchema.properties={});let m="";o.taxonomy&&(m=`
11
- [LIOP-DOMAIN: ${o.taxonomy.domain}]`);let h=p.inputSchema.properties||{},d="";!L()&&h.payload&&(d=`
12
- [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!L()&&p.description.includes("STRICT SCHEMA ADHERENCE")&&(p.description=p.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let g=L()?`
13
- (Peer: ${i.slice(-8)})${m}`:`
14
- (Origin: ${i.slice(-8)})${m}${d}`;p.description=`${p.description}${g}`,t.push(p);}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:n}]of this.manifestCache.entries())for(let i of n.resources)if(!t.has(i.uri)){let o={...i},s=n.serverInfo?.name||"Unknown Provider",a="";n.taxonomy&&(a=`
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&&(a+=`
19
- Execution Types: ${n.taxonomy.executionTypes.join(", ")}`));let l=`
20
-
21
- [LIOP Zero-Trust Origin]
22
- Provider: ${s}
23
- Network ID: ${r}${a}`;o.uri.startsWith("liop://schema/")?(o.name=`[SCHEMA] ${o.name}`,o.description=`[CRITICAL SCHEMA] ${o.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):o.description=o.description?`${o.description}${l}`:l.trim(),e.push(o),t.add(i.uri);}return e}resolveManifestTarget(e){for(let[r,{manifest:n}]of this.manifestCache.entries())if(n.tools.find(o=>o.name===e))return {peerId:r,originalToolName:e};let t=e.split("_");if(t.length>1){let r=t.pop(),n=t.join("_");for(let[i,{manifest:o}]of this.manifestCache.entries())if(i.endsWith(r||"")&&o.tools.find(a=>a.name===n))return {peerId:i,originalToolName:n}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,t,r){let n=t.name;if(n==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let o=this._discoveryStats||{candidates:0,success:0,failures:0},s=this.manifestCache.size,a=this.meshNode?"Active":"Offline",l=Array.from(this.manifestCache.values()).reduce((E,{manifest:I})=>E+I.tools.length,0),u=this.meshNode?this.meshNode.node?.getConnections().length:0,p=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],m=p.length,d=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",g=d?p.map(E=>{let I=E.split("/"),S=I[I.length-1];return ` \u2022 ${S?S.slice(-8):"Unknown"} (bootstrap)`}).join(`
24
- `):"",T=this.meshNode?this.meshNode.getRoutingTableSize():0,y=this.meshNode?.getPeerId()||"Offline",R=y==="Offline"?y:this.redactPeerId(y),k=Array.from(this.manifestCache.entries()).flatMap(([E,{manifest:I}])=>I.tools.map(S=>` \u2022 ${S.name} (from origin: ${this.redactPeerId(E)})`)).join(`
25
- `),j=[`LIOP Mesh Status: ${a==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${R}`,`Network: ${u} Conns | ${T} Mesh Nodes | ${m} Bootstraps`,d&&m>0?`
26
- Active Bootstraps:
27
- ${g}
28
- `:"",`Discovery: ${o.candidates} Candidates | ${o.success} OK | ${o.failures} FAIL`,`Tooling: ${s} Providers | ${l} Total Remote Tools`,l>0?`
29
- Discovered Remote Tools (Zero-Trust Origins):
30
- ${k}`:`
31
- No remote tools discovered yet.`,P.getInstance().formatStatusBlock()].filter(E=>E!=="").join(`
32
- `),M=P.getInstance();return M.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:M.countTokens(j)}),{jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:j}]}}}let i=this.liopServer.listTools().some(o=>o.name===n);if(!i&&this.meshNode){let o=this.resolveManifestTarget(n);if(o||(await this.refreshManifestCache(),o=this.resolveManifestTarget(n)),o){a.info(`[LIOP-Router] Resolved ${n} via manifest cache (Peer: ${o.peerId}, Original: ${o.originalToolName})`);let a$1=this.manifestCache.get(o.peerId),l=r;if(a$1?.manifest.authRequired){let u=r||await this.getOrAcquireMeshAgentToken(o.peerId);if(!u){let p=a$1.manifest.serverInfo?.name?.toLowerCase()||"unknown",m=a$1.manifest.tokenSlug,h=o.peerId.slice(-8).toUpperCase(),d=m?`LIOP_TOKEN_${m}`:`LIOP_TOKEN_${p.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${p}) requires an access token. Please define the ${d} or LIOP_TOKEN_${h} environment variable on your agent/client host.`}],isError:true}}}l=u;}return this.routeToRemoteProvider(e,o.originalToolName,o.peerId,t,l)}let s=[];for(let a=0;a<3&&(s=await this.meshNode.findProviders(n),!(s.length>0));a++)a<2&&await new Promise(l=>setTimeout(l,1e3));if(s.length>0)return this.routeToRemoteProvider(e,n,s[0],t,r)}if(i)try{let o=Date.now(),s=await this.liopServer.callTool({name:n,arguments:t.arguments||{}}),a=P.getInstance(),l=JSON.stringify(t.arguments||{}),u=JSON.stringify(s);return a.record({type:"tool_call",method:"tools/call",toolName:n,estimatedInputTokens:a.countTokens(l),estimatedOutputTokens:a.countTokens(u),durationMs:Date.now()-o}),{jsonrpc:"2.0",id:e,result:s}}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: ${n}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(e,t,r,n,i){if(!this.meshNode)return {jsonrpc:"2.0",id:e,error:{code:-32603,message:"Mesh Node inactive"}};let o=this.manifestCache.get(r),s=this.defaultRpcPort;if(o)s=o.manifest.grpcPort;else {let d=await this.meshNode.queryManifest(r);d&&(s=d.grpcPort,this.manifestCache.set(r,{manifest:d,cachedAt:Date.now()}),o=this.manifestCache.get(r));}if((process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test")&&o){let d=o.manifest.serverInfo?.name?.toLowerCase()||"";d.includes("vault")?s=13011:d.includes("bank")?s=13021:d.includes("oracle")&&(s=13031);}let l=await this.meshNode.resolvePeer(r),u=null,p=await import('os'),m=Object.values(p.networkInterfaces()).flat().filter(d=>d?.family==="IPv4").map(d=>d?.address);for(let d of l){let g=d.split("/"),T=g.indexOf("ip4");if(T!==-1){let y=g[T+1];if(y==="127.0.0.1"||m.includes(y)){u=`127.0.0.1:${s}`;break}u||(u=`${y}:${s}`);}}u||(u=`127.0.0.1:${s}`),a.info(`[LIOP-Router] Dynamic route: ${t} -> ${u} (PeerID: ${r})`);let h=new a$3.LogicMesh(u,c());return this.performTranscoding(e,h,t,n,r,i)}meshAgentToken;async getOrAcquireMeshAgentToken(e){if(e){let s=this.manifestCache.get(e),a$1=s?.manifest.serverInfo?.name?.toLowerCase()||"",l,u=s?.manifest.tokenSlug;if(u){let p=`LIOP_TOKEN_${u}`;l=process.env[p]||process.env[`LIOP_OAUTH_TOKEN_${u}`],a.info(`[LIOP-Router] Step0 tokenSlug=${u} envKey=${p} found=${!!l} peer=${e.slice(-8)}`);}else a.info(`[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${e.slice(-8)} provider=${a$1}`);if(!l){let p=e.slice(-8).toUpperCase();l=process.env[`LIOP_TOKEN_${p}`]||process.env[`LIOP_OAUTH_TOKEN_${p}`];}if(!l&&a$1){let p=a$1.toUpperCase().replace(/[^A-Z0-9_]/g,"_");l=process.env[`LIOP_TOKEN_${p}`]||process.env[`LIOP_OAUTH_TOKEN_${p}`];}if(l)return a.info(`[LIOP-Router] Resolved node-specific token for peer ${e.slice(-8)} (${a$1||"unknown"})`),l}if(this.meshAgentToken)return this.meshAgentToken;let t=process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN;if(t)return this.meshAgentToken=t,this.meshAgentToken;let r=process.env.LIOP_NEXUS_URL;if(!r)return;let n=process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID||"liop-mesh-agent",i=process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET||"dev-secret-change-me",o=process.env.LIOP_OAUTH_AUDIENCE||process.env.LIOP_AUDIENCE||"urn:liop:mesh:api";try{let a$1=`${r.endsWith("/oidc")?r:`${r}/oidc`}/token`;a.info(`[LIOP-Router] Proactively acquiring M2M token from Nexus: ${a$1}`);let l=new URLSearchParams({grant_type:"client_credentials",scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",resource:o,client_id:n,client_secret:i}),u=await fetch(a$1,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!u.ok){let m=await u.text();a.warn(`[LIOP-Router] M2M Token acquisition failed: ${u.status} ${m}`);return}let p=await u.json();if(p.access_token)return this.meshAgentToken=p.access_token,a.info("[LIOP-Router] M2M Token acquired successfully for router routing."),this.meshAgentToken}catch(s){a.warn(`[LIOP-Router] Failed to acquire M2M token: ${s instanceof Error?s.message:String(s)}`);}}async performTranscoding(e,t,r,n,i,o){let s=r,a=this.meshNode?await this.meshNode.sign(Buffer.from(s)):Buffer.from([]),l=Date.now(),u=o;if(u||(u=await this.getOrAcquireMeshAgentToken(i)),i){let p=this.manifestCache.get(i);if(p?.manifest.authRequired&&!u){let m=p.manifest.serverInfo?.name?.toLowerCase()||"unknown",h=p.manifest.tokenSlug,d=i.slice(-8).toUpperCase(),g=h?`LIOP_TOKEN_${h}`:`LIOP_TOKEN_${m.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${m}) requires an access token. Please define the ${g} or LIOP_TOKEN_${d} environment variable on your agent/client host.`}],isError:true}}}}return new Promise(p=>{let m=new ce.Metadata;u&&m.add("authorization",`Bearer ${u}`),t.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:s,proof_of_intent:a},m,async(h,d)=>{if(h||!d.accepted)return p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`PQC Handshake Failed: ${h?.message||"Rejected"}`}],isError:true}});let{ciphertext:g,sharedSecret:T}=await a$4.encapsulateAsymmetric(d.kyber_public_key),y=JSON.stringify(n.arguments||{}),R=`return { "__liop_proxy_tool": "${r}", "__liop_proxy_args": ${y} };`,k=K.randomBytes(12),j=this.encryptWithNonce(Buffer.from(R),T,k),M=new ce.Metadata;u&&M.add("authorization",`Bearer ${u}`);let E=t.executeLogic({session_token:d.session_token,wasm_binary:new Uint8Array(j),inputs:{},pqc_ciphertext:g,aes_nonce:k},M),I="",S=null;E.on("data",w=>{I+=w.semantic_evidence,S=w;}),E.on("end",async()=>{try{if(S&&!S.is_error){let Pe=Buffer.from(S.cryptographic_proof).toString("hex");if(!await this.verifier.verifyZkReceipt(Buffer.from(R),Pe,Buffer.from(S.zk_receipt),Buffer.from(T),I))return p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}})}let w=JSON.parse(I),q=P.getInstance();q.record({type:"tool_call",method:"tools/call",toolName:r,peerId:i,estimatedInputTokens:q.countTokens(y),estimatedOutputTokens:q.countTokens(I),durationMs:Date.now()-l}),p({jsonrpc:"2.0",id:e,result:w});}catch{p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:I}]}});}}),E.on("error",w=>p({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`LIOP gRPC Error: ${w.message}`}],isError:true}}));});})}encryptWithNonce(e,t,r){let n=K.createCipheriv("aes-256-gcm",t,r),i=Buffer.concat([n.update(e),n.final()]);return Buffer.concat([i,n.getAuthTag()])}};export{W as a,B as b,fe as c,he as d,H as e,P as f,Ie as g};//# sourceMappingURL=chunk-I46YEWND.js.map
33
- //# sourceMappingURL=chunk-I46YEWND.js.map