@nekzus/liop 2.0.0-alpha.9 → 2.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/bin/agent.js +3 -3
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.js +1 -1
- package/dist/chunk-2MGFSIXN.js +2 -0
- package/dist/chunk-2MGFSIXN.js.map +1 -0
- package/dist/chunk-4C666HHU.js +2 -0
- package/dist/chunk-4C666HHU.js.map +1 -0
- package/dist/{chunk-PPCOS2NU.js → chunk-7I6YJS3C.js} +2 -2
- package/dist/{chunk-PPCOS2NU.js.map → chunk-7I6YJS3C.js.map} +1 -1
- package/dist/{chunk-HNDVAKEK.js → chunk-C65RM2A3.js} +6 -6
- package/dist/chunk-C65RM2A3.js.map +1 -0
- package/dist/{chunk-P52IE4L6.js → chunk-ISKM7EAL.js} +2 -2
- package/dist/{chunk-P52IE4L6.js.map → chunk-ISKM7EAL.js.map} +1 -1
- package/dist/{chunk-62YQHKSS.js → chunk-NWZ5KZDN.js} +3 -3
- package/dist/chunk-NWZ5KZDN.js.map +1 -0
- package/dist/{chunk-JBMEAXYU.js → chunk-SYMZRXI3.js} +3 -3
- package/dist/{chunk-JBMEAXYU.js.map → chunk-SYMZRXI3.js.map} +1 -1
- package/dist/chunk-TNMS53OP.js +2 -0
- package/dist/chunk-TNMS53OP.js.map +1 -0
- package/dist/chunk-UK7OBXGZ.js +33 -0
- package/dist/chunk-UK7OBXGZ.js.map +1 -0
- package/dist/chunk-V5MKJT6S.js +2 -0
- package/dist/chunk-V5MKJT6S.js.map +1 -0
- package/dist/chunk-WG353XMU.js +43 -0
- package/dist/chunk-WG353XMU.js.map +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/{index-CyxNLlz7.d.ts → index-BihN3W-K.d.ts} +9 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/kyber-NONMBQNH.js +2 -0
- package/dist/{kyber-2WDOTUQX.js.map → kyber-NONMBQNH.js.map} +1 -1
- package/dist/mesh.js +1 -1
- package/dist/server.js +1 -1
- package/dist/types.js +1 -1
- package/dist/verifier-6M7GY4TW.js +2 -0
- package/dist/{verifier-RQRYXA4C.js.map → verifier-6M7GY4TW.js.map} +1 -1
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/dist/workers/zk-verifier.js +1 -1
- package/dist/workers/zk-verifier.js.map +1 -1
- package/package.json +50 -52
- package/dist/chunk-5OAZNVIU.js +0 -31
- package/dist/chunk-5OAZNVIU.js.map +0 -1
- package/dist/chunk-62YQHKSS.js.map +0 -1
- package/dist/chunk-7MAGL6ON.js +0 -33
- package/dist/chunk-7MAGL6ON.js.map +0 -1
- package/dist/chunk-HM77MWB6.js +0 -2
- package/dist/chunk-HM77MWB6.js.map +0 -1
- package/dist/chunk-HNDVAKEK.js.map +0 -1
- package/dist/chunk-HQZHZM6U.js +0 -2
- package/dist/chunk-HQZHZM6U.js.map +0 -1
- package/dist/kyber-2WDOTUQX.js +0 -2
- package/dist/verifier-RQRYXA4C.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-4C666HHU.js"}
|
|
@@ -1,2 +1,2 @@
|
|
|
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 b{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>b.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(b.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),b.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-PPCOS2NU.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
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 b{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>b.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(b.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),b.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-7I6YJS3C.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-7I6YJS3C.js.map
|
|
@@ -1 +1 @@
|
|
|
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":"glBAwDA,IAAMA,EAA0B,CAC/B,iFAAA,C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oB,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-PPCOS2NU.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}\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// @ts-expect-error: libp2p version drift workaround\n\t\t\t\t\tawait this.node.peerStore.save(peerId, { 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
|
+
{"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":"glBAwDA,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,GAAI,CAACC,CAAAA,CAAO,OAAO,MAAA,CACnB,IAAMC,EAAM,IAAA,CAAK,GAAA,GACjB,OAAIA,CAAAA,EAAOD,CAAAA,CAAM,aAAA,CAAsB,OAEtCC,CAAAA,CAAMD,CAAAA,CAAM,cACZH,CAAAA,CAAS,kCAAA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qB,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-7I6YJS3C.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}\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,5 +1,5 @@
|
|
|
1
|
-
import A from'crypto';import*as n from'fs/promises';import*as b from'os';import*as c from'path';import h from'vm';import {WASI}from'wasi';var f=class extends Error{constructor(t){super(`AST Sec-Policy Violation: ${t}`),this.name="GuardianError";}},w={analyze(d){let t=WebAssembly.Module.imports(d),s=0,l=new Set(["fd_write","fd_read","fd_close","fd_seek","environ_get","environ_sizes_get","args_get","args_sizes_get","clock_time_get","random_get","proc_exit","fd_prestat_get","fd_prestat_dir_name","fd_fdstat_get"]);for(let
|
|
2
|
-
${
|
|
1
|
+
import A from'crypto';import*as n from'fs/promises';import*as b from'os';import*as c from'path';import h from'vm';import {WASI}from'wasi';var f=class extends Error{constructor(t){super(`AST Sec-Policy Violation: ${t}`),this.name="GuardianError";}},w={analyze(d){let t=WebAssembly.Module.imports(d),s=0,l=new Set(["fd_write","fd_read","fd_close","fd_seek","environ_get","environ_sizes_get","args_get","args_sizes_get","clock_time_get","random_get","proc_exit","fd_prestat_get","fd_prestat_dir_name","fd_fdstat_get"]);for(let o of t){if(o.module==="wasi_snapshot_preview1"){if(!l.has(o.name))throw new f(`Banned WASI Import Detected: ${o.module}/${o.name}`)}else throw new f(`Banned Host Import Module Detected: ${o.module}`);if(s++,s>128)throw new f("Import limit exceeded. Possible resource exhaustion attack.")}}};var x=process.emit;process.emit=(d,t,...s)=>d==="warning"&&typeof t=="object"&&t.name==="ExperimentalWarning"&&String(t.message).includes("WASI")||String(t.message).includes("importing WASI")?false:x.call(process,d,t,...s);var y=class{wasi;sandboxId;workingDir;config;stdoutHandle=null;stderrHandle=null;constructor(t={}){this.sandboxId=A.randomUUID(),this.workingDir=c.join(b.tmpdir(),"liop-mesh","sandboxes",this.sandboxId),this.config=t;}async init(){try{await n.mkdir(this.workingDir,{recursive:!0}),this.stdoutHandle=await n.open(c.join(this.workingDir,"stdout.log"),"w+"),this.stderrHandle=await n.open(c.join(this.workingDir,"stderr.log"),"w+"),this.wasi=new WASI({version:"preview1",args:["liop_runtime"],env:this.config.allowEnv?process.env:{NODE_ENV:"production",LIOP_NODE:"true",RUNTIME_ID:this.sandboxId},preopens:{"/sandbox":this.workingDir,...this.config.allowedDirectories},stdout:this.stdoutHandle.fd,stderr:this.stderrHandle.fd});}catch(t){throw new Error(`Sandbox Initialization Failed: ${t instanceof Error?t.message:"FS Error"}`)}}async execute(t,s=[],l={}){let o=performance.now();if(t instanceof Buffer)try{let e=await WebAssembly.compile(new Uint8Array(t));w.analyze(e);let p=await WebAssembly.instantiate(e,this.wasi.getImportObject());this.wasi.start(p);let u=c.join(this.workingDir,"stdout.log"),i=c.join(this.workingDir,"stderr.log"),m=await n.readFile(u,"utf-8"),r=await n.readFile(i,"utf-8"),a=performance.now()-o;return {output:m||(r?`Error: ${r}`:"WASM_EXECUTION_SUCCESS"),fuelConsumed:Math.floor(a*1e3)}}catch(e){throw new Error(`WASM Runtime Error: ${e instanceof Error?e.message:String(e)}`)}else {let e=Object.create(null),p={records:s,...l};e.require=void 0,e.process=void 0,e.global=void 0,e.globalThis=void 0,e.Buffer=void 0,e.setTimeout=void 0,e.setInterval=void 0,e.setImmediate=void 0,e.queueMicrotask=void 0,e.eval=void 0,e.Function=void 0,e.SharedArrayBuffer=void 0,e.Date=void 0,e.ArrayBuffer=void 0,e.Uint8Array=void 0,e.Int8Array=void 0,e.Uint16Array=void 0,e.Int16Array=void 0,e.Uint32Array=void 0,e.Int32Array=void 0,e.Float32Array=void 0,e.Float64Array=void 0,e.BigInt64Array=void 0,e.BigUint64Array=void 0,e.DataView=void 0,e.records=JSON.parse(JSON.stringify(s)),e.env=JSON.parse(JSON.stringify(p));for(let[r,a]of Object.entries(l))e[r]=JSON.parse(JSON.stringify(a));let u=r=>{if(r&&typeof r=="object"&&!Object.isFrozen(r)){Object.freeze(r);for(let a of Object.keys(r))u(r[a]);}return r};u(e.records),u(e.env);for(let r of Object.keys(e))Object.defineProperty(e,r,{writable:false,configurable:false});let i=String(t);(/^\s*return\s/m.test(i)||!i.includes("function liop_main"))&&(i.includes("function liop_main")||(i=`function liop_main(env) {
|
|
2
|
+
${i}
|
|
3
3
|
}`));let m=`
|
|
4
4
|
(function() {
|
|
5
5
|
try {
|
|
@@ -10,7 +10,7 @@ ${o}
|
|
|
10
10
|
Object.freeze(Boolean.prototype);
|
|
11
11
|
Object.freeze(Object.getPrototypeOf(function(){}));
|
|
12
12
|
|
|
13
|
-
${
|
|
13
|
+
${i}
|
|
14
14
|
if (typeof liop_main === 'function') {
|
|
15
15
|
return liop_main(env);
|
|
16
16
|
}
|
|
@@ -19,6 +19,6 @@ ${o}
|
|
|
19
19
|
return "LogicError: " + e.message;
|
|
20
20
|
}
|
|
21
21
|
})();
|
|
22
|
-
`;try{let r=new h.Script(m,{filename:`liop-sandbox-${this.sandboxId.slice(0,8)}.js`}),a=h.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox"}),_=r.runInContext(a,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),S=performance.now()-
|
|
23
|
-
export{w as a,y as b};//# sourceMappingURL=chunk-
|
|
24
|
-
//# sourceMappingURL=chunk-
|
|
22
|
+
`;try{let r=new h.Script(m,{filename:`liop-sandbox-${this.sandboxId.slice(0,8)}.js`}),a=h.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox",microtaskMode:"afterEvaluate"}),_=r.runInContext(a,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),S=performance.now()-o,E=Math.floor(S*1500+100),g=Math.ceil(E/100)*100;if(g>1e6)throw new Error("LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.");return {output:_,fuelConsumed:g}}catch(r){throw new Error(`V8 Isolate Fault: ${r instanceof Error?r.message:"Execution Timeout"}`)}}}async teardown(){try{this.stdoutHandle&&await this.stdoutHandle.close(),this.stderrHandle&&await this.stderrHandle.close(),await n.rm(this.workingDir,{recursive:!0,force:!0});}catch{}}};
|
|
23
|
+
export{w as a,y as b};//# sourceMappingURL=chunk-C65RM2A3.js.map
|
|
24
|
+
//# sourceMappingURL=chunk-C65RM2A3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/guardian.ts","../src/sandbox/wasi.ts"],"names":["GuardianError","message","ASTGuardian","module","imports","_importCount","ALLOWED_WASI_FUNCTIONS","imp","originalEmit","name","data","args","WasiSandbox","config","crypto","WASI","error","compiledLogic","records","inputs","startTime","instance","stdoutPath","stderrPath","stdout","stderr","duration","sandboxEnv","env","key","value","deepFreeze","obj","processedLogic","scriptCode","script","vm","context","output","rawFuel","fuelUsed"],"mappings":"0IAAO,IAAMA,CAAAA,CAAN,cAA4B,KAAM,CACxC,YAAYC,CAAAA,CAAiB,CAC5B,KAAA,CAAM,CAAA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AK,YAAA,EAAc,MAAM,IAAA,CAAK,YAAA,CAAa,KAAA,EAAM,CACjD,IAAA,CAAK,YAAA,EAAc,MAAM,KAAK,YAAA,CAAa,KAAA,EAAM,CACrD,MAAS,CAAA,CAAA,EAAA,CAAG,IAAA,CAAK,UAAA,CAAY,CAAE,SAAA,CAAW,CAAA,CAAA,CAAM,KAAA,CAAO,CAAA,CAAK,CAAC,EAC9D,CAAA,KAAa,CAEb,CACD,CACD","file":"chunk-C65RM2A3.js","sourcesContent":["export class GuardianError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(`AST Sec-Policy Violation: ${message}`);\n\t\tthis.name = \"GuardianError\";\n\t}\n}\n\n/**\n * The Guardian-TS Module\n * Scans the Abstract Syntax Tree (AST) imports of incoming WASM\n * before it reaches the V8 Wasmtime engine to prevent sandbox-escape\n * zero-days, resource exhaustion bombs, and evasive execution.\n */\nexport const ASTGuardian = {\n\t/**\n\t * Analyzes the WebAssembly Module interface proactively.\n\t *\n\t * @param module - The compiled WebAssembly.Module to inspect\n\t * @throws {GuardianError} If illegal imports or capabilities are detected\n\t */\n\tanalyze(module: WebAssembly.Module): void {\n\t\tconst imports = WebAssembly.Module.imports(module);\n\t\tlet _importCount = 0;\n\n\t\tconst ALLOWED_WASI_FUNCTIONS = new Set([\n\t\t\t\"fd_write\",\n\t\t\t\"fd_read\",\n\t\t\t\"fd_close\",\n\t\t\t\"fd_seek\",\n\t\t\t\"environ_get\",\n\t\t\t\"environ_sizes_get\",\n\t\t\t\"args_get\",\n\t\t\t\"args_sizes_get\",\n\t\t\t\"clock_time_get\",\n\t\t\t\"random_get\",\n\t\t\t\"proc_exit\",\n\t\t\t\"fd_prestat_get\",\n\t\t\t\"fd_prestat_dir_name\",\n\t\t\t\"fd_fdstat_get\",\n\t\t]);\n\n\t\tfor (const imp of imports) {\n\t\t\t// Strict Sandbox Validation: Only allow WASI preview 1 specific whitelisted functions.\n\t\t\tif (imp.module === \"wasi_snapshot_preview1\") {\n\t\t\t\tif (!ALLOWED_WASI_FUNCTIONS.has(imp.name)) {\n\t\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\t`Banned WASI Import Detected: ${imp.module}/${imp.name}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t`Banned Host Import Module Detected: ${imp.module}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t_importCount++;\n\n\t\t\tif (_importCount > 128) {\n\t\t\t\tthrow new GuardianError(\n\t\t\t\t\t\"Import limit exceeded. Possible resource exhaustion attack.\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// In Node.js / V8, the maximum module size and function limits\n\t\t// are natively enforced by the engine during compilation.\n\t\t// A successfully compiled WebAssembly.Module already passed structural checks.\n\t},\n};\n","import crypto from \"node:crypto\";\nimport * as fs from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport vm from \"node:vm\";\nimport { WASI } from \"node:wasi\";\nimport { ASTGuardian } from \"./guardian.js\";\n\n// Silence Node.js ExperimentalWarning for WASI (Industrial console parity)\nconst originalEmit = process.emit;\n// @ts-expect-error\nprocess.emit = (name, data, ...args) => {\n\tif (\n\t\t(name === \"warning\" &&\n\t\t\ttypeof data === \"object\" &&\n\t\t\t(data as Record<string, unknown>).name === \"ExperimentalWarning\" &&\n\t\t\tString((data as Record<string, unknown>).message).includes(\"WASI\")) ||\n\t\tString((data as Record<string, unknown>).message).includes(\"importing WASI\")\n\t) {\n\t\treturn false;\n\t}\n\treturn originalEmit.call(process, name, data, ...args);\n};\n\nexport interface SandboxConfig {\n\tallowEnv?: boolean;\n\tallowedDirectories?: Record<string, string>; // guestPath -> hostPath\n\tmemoryLimitMb?: number;\n}\n\n/**\n * LIOP WasiSandbox (Industrial Grade)\n *\n * Provides a production-grade isolated environment for executing untrusted logic.\n * Primarily uses WebAssembly (WASI) for byte-code isolation, with a hardened\n * V8 Isolate fallback for dynamic JS-to-WASM logic injection.\n */\nexport class WasiSandbox {\n\tprivate wasi!: WASI;\n\tprivate sandboxId: string;\n\tprivate workingDir: string;\n\tprivate config: SandboxConfig;\n\tprivate stdoutHandle: fs.FileHandle | null = null;\n\tprivate stderrHandle: fs.FileHandle | null = null;\n\n\tconstructor(config: SandboxConfig = {}) {\n\t\tthis.sandboxId = crypto.randomUUID();\n\t\t// Use a dedicated LIOP directory in the OS temp folder\n\t\tthis.workingDir = path.join(\n\t\t\tos.tmpdir(),\n\t\t\t\"liop-mesh\",\n\t\t\t\"sandboxes\",\n\t\t\tthis.sandboxId,\n\t\t);\n\t\tthis.config = config;\n\t}\n\n\t/**\n\t * Initializes the physical sandbox environment with strict directory lockdown.\n\t */\n\tpublic async init(): Promise<void> {\n\t\ttry {\n\t\t\tawait fs.mkdir(this.workingDir, { recursive: true });\n\n\t\t\t// Initialize WASI with explicit limits\n\t\t\tthis.stdoutHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stdout.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\t\t\tthis.stderrHandle = await fs.open(\n\t\t\t\tpath.join(this.workingDir, \"stderr.log\"),\n\t\t\t\t\"w+\",\n\t\t\t);\n\n\t\t\tthis.wasi = new WASI({\n\t\t\t\tversion: \"preview1\",\n\t\t\t\targs: [\"liop_runtime\"],\n\t\t\t\tenv: this.config.allowEnv\n\t\t\t\t\t? process.env\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tNODE_ENV: \"production\",\n\t\t\t\t\t\t\tLIOP_NODE: \"true\",\n\t\t\t\t\t\t\tRUNTIME_ID: this.sandboxId,\n\t\t\t\t\t\t},\n\t\t\t\tpreopens: {\n\t\t\t\t\t\"/sandbox\": this.workingDir,\n\t\t\t\t\t...this.config.allowedDirectories,\n\t\t\t\t},\n\t\t\t\tstdout: this.stdoutHandle.fd,\n\t\t\t\tstderr: this.stderrHandle.fd,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Sandbox Initialization Failed: ${error instanceof Error ? error.message : \"FS Error\"}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Executes logic (WASM or JS-Wrapped) with hard resource limits.\n\t */\n\tpublic async execute(\n\t\tcompiledLogic: Buffer | string,\n\t\trecords: Record<string, unknown>[] = [],\n\t\tinputs: Record<string, unknown> = {},\n\t): Promise<{ output: unknown; fuelConsumed: number }> {\n\t\tconst startTime = performance.now();\n\n\t\tif (compiledLogic instanceof Buffer) {\n\t\t\t// Path A: Native WebAssembly Isolation\n\t\t\ttry {\n\t\t\t\tconst module = await WebAssembly.compile(new Uint8Array(compiledLogic));\n\n\t\t\t\t// Tier-0 Guardian: Static analysis to prevent sandbox escapes\n\t\t\t\tASTGuardian.analyze(module);\n\n\t\t\t\tconst instance = await WebAssembly.instantiate(\n\t\t\t\t\tmodule,\n\t\t\t\t\tthis.wasi.getImportObject() as WebAssembly.Imports,\n\t\t\t\t);\n\n\t\t\t\t// Standard entry point\n\t\t\t\tthis.wasi.start(instance);\n\n\t\t\t\t// Capture output from the sandbox\n\t\t\t\tconst stdoutPath = path.join(this.workingDir, \"stdout.log\");\n\t\t\t\tconst stderrPath = path.join(this.workingDir, \"stderr.log\");\n\t\t\t\tconst stdout = await fs.readFile(stdoutPath, \"utf-8\");\n\t\t\t\tconst stderr = await fs.readFile(stderrPath, \"utf-8\");\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\treturn {\n\t\t\t\t\toutput:\n\t\t\t\t\t\tstdout || (stderr ? `Error: ${stderr}` : \"WASM_EXECUTION_SUCCESS\"),\n\t\t\t\t\tfuelConsumed: Math.floor(duration * 1000),\n\t\t\t\t};\n\t\t\t} catch (error: unknown) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`WASM Runtime Error: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t} else {\n\t\t\t// Path B: Hardened V8 Isolate Fallback\n\t\t\t// Uses node:vm with zero-prototype objects to prevent prototype pollution escapes.\n\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for Sandbox global poisoning\n\t\t\tconst sandboxEnv: any = Object.create(null); // Isolated global object\n\t\t\tconst env = { records, ...inputs };\n\n\t\t\t// Explicitly poison Node.js escape vectors in the context\n\t\t\tsandboxEnv.require = undefined;\n\t\t\tsandboxEnv.process = undefined;\n\t\t\tsandboxEnv.global = undefined;\n\t\t\tsandboxEnv.globalThis = undefined;\n\t\t\tsandboxEnv.Buffer = undefined;\n\t\t\tsandboxEnv.setTimeout = undefined;\n\t\t\tsandboxEnv.setInterval = undefined;\n\t\t\tsandboxEnv.setImmediate = undefined;\n\t\t\tsandboxEnv.queueMicrotask = undefined;\n\t\t\tsandboxEnv.eval = undefined;\n\t\t\tsandboxEnv.Function = undefined;\n\t\t\tsandboxEnv.SharedArrayBuffer = undefined;\n\t\t\tsandboxEnv.Date = undefined;\n\n\t\t\t// [DoS Defense] Block off-heap memory allocation vectors.\n\t\t\t// Logic-on-Origin operates on JSON data (env.records) — binary buffers\n\t\t\t// serve no legitimate purpose and enable memory exhaustion DoS.\n\t\t\t// (Uint8Array(2GB) bypassed Piscina's maxOldGenerationSizeMb limit)\n\t\t\tsandboxEnv.ArrayBuffer = undefined;\n\t\t\tsandboxEnv.Uint8Array = undefined;\n\t\t\tsandboxEnv.Int8Array = undefined;\n\t\t\tsandboxEnv.Uint16Array = undefined;\n\t\t\tsandboxEnv.Int16Array = undefined;\n\t\t\tsandboxEnv.Uint32Array = undefined;\n\t\t\tsandboxEnv.Int32Array = undefined;\n\t\t\tsandboxEnv.Float32Array = undefined;\n\t\t\tsandboxEnv.Float64Array = undefined;\n\t\t\tsandboxEnv.BigInt64Array = undefined;\n\t\t\tsandboxEnv.BigUint64Array = undefined;\n\t\t\tsandboxEnv.DataView = undefined;\n\n\t\t\t// Inject strictly monitored globals\n\t\t\tsandboxEnv.records = JSON.parse(JSON.stringify(records)); // Deep copy safety\n\t\t\tsandboxEnv.env = JSON.parse(JSON.stringify(env));\n\n\t\t\tfor (const [key, value] of Object.entries(inputs)) {\n\t\t\t\tsandboxEnv[key] = JSON.parse(JSON.stringify(value));\n\t\t\t}\n\n\t\t\t// Freeze the sandbox context to prevent mutation (SEC-GAP-1)\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Required for recursive deep freeze of unknown data\n\t\t\tconst deepFreeze = (obj: any) => {\n\t\t\t\tif (obj && typeof obj === \"object\" && !Object.isFrozen(obj)) {\n\t\t\t\t\tObject.freeze(obj);\n\t\t\t\t\tfor (const key of Object.keys(obj)) {\n\t\t\t\t\t\tdeepFreeze(obj[key]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn obj;\n\t\t\t};\n\n\t\t\tdeepFreeze(sandboxEnv.records);\n\t\t\tdeepFreeze(sandboxEnv.env);\n\n\t\t\t// Prevent property addition/modification on global scope\n\t\t\tfor (const key of Object.keys(sandboxEnv)) {\n\t\t\t\tObject.defineProperty(sandboxEnv, key, {\n\t\t\t\t\twritable: false,\n\t\t\t\t\tconfigurable: false,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// LIOP Execution Wrapper\n\t\t\t// Host-side logic transformation to avoid 'new Function' in sandbox\n\t\t\tlet processedLogic = String(compiledLogic);\n\t\t\tif (\n\t\t\t\t/^\\s*return\\s/m.test(processedLogic) ||\n\t\t\t\t!processedLogic.includes(\"function liop_main\")\n\t\t\t) {\n\t\t\t\tif (!processedLogic.includes(\"function liop_main\")) {\n\t\t\t\t\tprocessedLogic = `function liop_main(env) {\\n${processedLogic}\\n}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst scriptCode = `\n\t\t\t\t(function() {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tObject.freeze(Object.prototype);\n\t\t\t\t\t\tObject.freeze(Array.prototype);\n\t\t\t\t\t\tObject.freeze(String.prototype);\n\t\t\t\t\t\tObject.freeze(Number.prototype);\n\t\t\t\t\t\tObject.freeze(Boolean.prototype);\n\t\t\t\t\t\tObject.freeze(Object.getPrototypeOf(function(){}));\n\n\t\t\t\t\t\t${processedLogic}\n\t\t\t\t\t\tif (typeof liop_main === 'function') {\n\t\t\t\t\t\t\treturn liop_main(env);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn \"ERR_NO_ENTRY_POINT\";\n\t\t\t\t\t} catch(e) {\n\t\t\t\t\t\treturn \"LogicError: \" + e.message;\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t`;\n\n\t\t\ttry {\n\t\t\t\tconst script = new vm.Script(scriptCode, {\n\t\t\t\t\tfilename: `liop-sandbox-${this.sandboxId.slice(0, 8)}.js`,\n\t\t\t\t});\n\n\t\t\t\t// microtaskMode: Ensures Promises created inside the sandbox are\n\t\t\t\t// resolved within the timeout/breakOnSigint scope (Node.js ≥14.6).\n\t\t\t\t// Without this, async microtasks could escape the 5s CPU limit.\n\t\t\t\tconst context = vm.createContext(sandboxEnv, {\n\t\t\t\t\tname: \"LIOP Isolate\",\n\t\t\t\t\torigin: \"liop://sandbox\",\n\t\t\t\t\tmicrotaskMode: \"afterEvaluate\",\n\t\t\t\t});\n\n\t\t\t\t// Execution with hard CPU and Memory limits (Fuel)\n\t\t\t\tconst output = script.runInContext(context, {\n\t\t\t\t\ttimeout: 5000,\n\t\t\t\t\tbreakOnSigint: true,\n\t\t\t\t\tdisplayErrors: true,\n\t\t\t\t});\n\n\t\t\t\tconst duration = performance.now() - startTime;\n\t\t\t\t// SEC: Normalize fuel to buckets of 100 to prevent timing side-channel inference\n\t\t\t\tconst rawFuel = Math.floor(duration * 1500 + 100);\n\t\t\t\tconst fuelUsed = Math.ceil(rawFuel / 100) * 100;\n\n\t\t\t\tif (fuelUsed > 1000000) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.\",\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\treturn { output, fuelConsumed: fuelUsed };\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`V8 Isolate Fault: ${error instanceof Error ? error.message : \"Execution Timeout\"}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Physically cleans up the sandbox and releases resources.\n\t */\n\tpublic async teardown(): Promise<void> {\n\t\ttry {\n\t\t\tif (this.stdoutHandle) await this.stdoutHandle.close();\n\t\t\tif (this.stderrHandle) await this.stderrHandle.close();\n\t\t\tawait fs.rm(this.workingDir, { recursive: true, force: true });\n\t\t} catch (_e) {\n\t\t\t// Silent fail on teardown to prevent process crashes\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-UVTEJYHN.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {c,a}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-UVTEJYHN.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {c,a}from'./chunk-V5MKJT6S.js';import {a as a$2}from'./chunk-7I6YJS3C.js';import {a as a$3}from'./chunk-S6RJHZV2.js';import {createDecipheriv,randomBytes,createCipheriv}from'crypto';var u=class{client;constructor(e,r){let t=c(r);this.client=new a.LogicMesh(e,t);}async negotiateIntent(e){return new Promise((r,t)=>{this.client.NegotiateIntent(e,(i,o)=>{i?t(i):r(o);});})}executeLogic(e){return this.client.ExecuteLogic(e)}close(){this.client.close();}};var $={encryptPayload(l,e){if(e.length!==32)throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");let r=randomBytes(12),t=createCipheriv("aes-256-gcm",e,r),i=Buffer.concat([t.update(l),t.final()]),o=t.getAuthTag();return {ciphertext:Buffer.concat([i,o]),nonce:r}},decryptPayload(l,e,r){if(l.length<16)throw new Error("Invalid GCM Ciphertext; missing authentication tag length");let t=l.subarray(0,-16),i=l.subarray(-16),o=createDecipheriv("aes-256-gcm",r,e);return o.setAuthTag(i),Buffer.concat([o.update(t),o.final()])}};var O=class{meshNode=null;rpcClients=new Map;manifests=new Map;tlsOptions;serverInfo;verifier=new a$1;constructor(e){this.tlsOptions=e;}async connect(e,r){this.meshNode=new a$2(r?.meshConfig),await this.meshNode.start(),a$3.info(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`),e?(this.rpcClients.set("static",new u(e,this.tlsOptions)),this.serverInfo={name:`LiopServer (${e})`,version:"1.0.0"},a$3.info(`[LiopClient] Static gRPC configured for: ${e}`)):this.serverInfo={name:"LiopServer (Mesh Alpha)",version:"1.0.0"};}async resolveCapability(e){if(!this.meshNode)throw new Error("Client must be connected to Mesh to resolve capabilities.");a$3.info(`[LiopClient] Querying Mesh DHT for Provider: ${e}...`);let r=await this.meshNode.findProviders(e);if(r.length===0)throw new Error(`Kademlia DHT found zero providers for capability: ${e}`);let t=r[0];a$3.info(`[LiopClient] Identified Alpha Provider PeerID: ${t}`);let i=50051,o=await this.meshNode.queryManifest(t);o&&(i=o.grpcPort,a$3.info(`[LiopClient] Manifest resolved: gRPC port ${i}`));let s=await this.meshNode.resolvePeer(t);for(let y of s){let a=y.split("/");if(a[1]==="ip4"){let m=`${a[2]}:${i}`;return a$3.info(`[LiopClient] Translated Multiaddr to gRPC Target: ${m}`),m}}return `127.0.0.1:${i}`}async discoverTools(){if(!this.meshNode)throw new Error("Client must be connected before discovering tools.");a$3.info("[LiopClient] Discovery started...");let e=await this.meshNode.discoverManifestProviders(),r=[],t=new Set;for(let i of e)try{a$3.info(`[LiopClient] Querying manifest from: ${i}`);let o=await this.meshNode.queryManifest(i);if(o){this.manifests.set(i,o);for(let s of o.tools)t.has(s.name)||(r.push({name:s.name,description:s.description}),t.add(s.name));}}catch(o){a$3.info(`[LiopClient] Error querying manifest from ${i}:`,o instanceof Error?o.message:String(o));}return a$3.info(`[LiopClient] Discovery finished. Found ${r.length} unique tools.`),r}async callTool(e,r){if(!this.meshNode)throw new Error("Client must be connected before calling tools.");let t=e.name;a$3.info(`[LiopClient] Resolving Tool: ${t}`);let i=this.rpcClients.get("static");if(i)a$3.info(`[LiopClient] Using existing static gRPC connection for ${t}.`);else {let h=await this.resolveCapability(t);i=this.getOrCreateRpcClient(t,h);}a$3.info(`[LiopClient] Negotiating intent for ${t}...`);let o=this.meshNode?`did:liop:${this.meshNode.getPeerId()}`:"did:liop:ephemeral",s=Buffer.from(`${t}:${Date.now()}`),y=this.meshNode?await this.meshNode.sign(s):s,a=await i.negotiateIntent({agent_did:o,capability_hash:t,proof_of_intent:y});if(!a.accepted)throw new Error(`Intent denied by host: ${a.error_message}`);let m=a.kyber_public_key||a.kyberPublicKey,_=a.session_token||a.sessionToken;if(!m)throw a$3.info("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",a),new Error("Handshake failed: Remote host did not provide a valid Kyber Public Key.");a$3.info(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${e.name}...`);let{ciphertext:x,sharedSecret:C}=await a$4.encapsulateAsymmetric(m);a$3.info("[LiopClient] Sealing WASM Payload and Inputs...");let v=r||Buffer.from(""),{ciphertext:k,nonce:A}=$.encryptPayload(v,C),w={},b=await import('crypto');for(let[h,f]of Object.entries(e.arguments||{})){let d=b.randomBytes(12),p=b.createCipheriv("aes-256-gcm",C,d),g=Buffer.concat([p.update(JSON.stringify(f)),p.final()]),c=p.getAuthTag();w[h]=Buffer.concat([d,g,c]);}let B={session_token:_,wasm_binary:k,inputs:w,pqc_ciphertext:x,aes_nonce:A};return new Promise((h,f)=>{let d=i.executeLogic(B);if(!d){f(new Error("RPC Client unavailable or failed to create stream."));return}let p=false,g=false;d.on("data",async c=>{if(!p){g=true,a$3.info("[LiopClient] Logic Executed. Verification in progress...");try{if(!c.is_error&&!await this.verifier.verifyZkReceipt(v,Buffer.from(c.cryptographic_proof).toString("hex"),Buffer.from(c.zk_receipt),Buffer.from(C))){f(new Error("PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."));return}p=!0,h({content:[{type:"text",text:c.semantic_evidence}],isError:c.is_error});}catch(L){f(L);}}}),d.on("error",c=>{p||(a$3.error("[LiopClient] Stream Error:",c),f(c));}),d.on("end",()=>{!g&&!p&&f(new Error("Logic-on-Origin stream closed without results."));});})}getOrCreateRpcClient(e,r){let t=this.rpcClients.get(e);return t||(t=new u(r,this.tlsOptions),this.rpcClients.set(e,t)),t}async readResource(e){if(!this.meshNode)throw new Error("Client must be connected before reading resources.");a$3.info(`[LiopClient] Querying Mesh for Resource: ${e}...`);let r=await this.meshNode.findProviders(e);if(r.length===0)throw new Error(`No mesh providers found for resource: ${e}`);let t=await this.meshNode.queryManifest(r[0]);if(!t)throw new Error("Target peer did not return a valid LIOP Manifest.");let i=t.resources?.find(o=>o.uri===e);if(!i)throw new Error(`Resource ${e} not listed in remote manifest.`);return {contents:[{uri:e,mimeType:i.mimeType||"application/json",text:JSON.stringify(i,null,2)}]}}getServerInfo(){return this.serverInfo}async close(){this.meshNode&&await this.meshNode.stop();}};export{u as a,O as b};//# sourceMappingURL=chunk-ISKM7EAL.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-ISKM7EAL.js.map
|