@nekzus/liop 1.3.0-alpha.1 → 2.0.0-alpha.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 +41 -17
- package/dist/bin/agent.d.ts +0 -1
- package/dist/bin/agent.js +5 -306
- package/dist/bin/agent.js.map +1 -0
- package/dist/{bridge/stream.d.ts → bridge.d.ts} +44 -3
- package/dist/bridge.js +2 -0
- package/dist/bridge.js.map +1 -0
- package/dist/chunk-4ABAFG44.js +33 -0
- package/dist/chunk-4ABAFG44.js.map +1 -0
- package/dist/chunk-ANFXJGMP.js +2 -0
- package/dist/chunk-ANFXJGMP.js.map +1 -0
- package/dist/chunk-DBXGYHKY.js +2 -0
- package/dist/chunk-DBXGYHKY.js.map +1 -0
- package/dist/chunk-HM77MWB6.js +2 -0
- package/dist/chunk-HM77MWB6.js.map +1 -0
- package/dist/chunk-HNDVAKEK.js +24 -0
- package/dist/chunk-HNDVAKEK.js.map +1 -0
- package/dist/chunk-HQZHZM6U.js +2 -0
- package/dist/chunk-HQZHZM6U.js.map +1 -0
- package/dist/chunk-P52IE4L6.js +2 -0
- package/dist/chunk-P52IE4L6.js.map +1 -0
- package/dist/chunk-PIBCW4BD.js +13 -0
- package/dist/chunk-PIBCW4BD.js.map +1 -0
- package/dist/chunk-PPCOS2NU.js +2 -0
- package/dist/chunk-PPCOS2NU.js.map +1 -0
- package/dist/chunk-RWRRBYG4.js +2 -0
- package/dist/chunk-RWRRBYG4.js.map +1 -0
- package/dist/chunk-S6RJHZV2.js +2 -0
- package/dist/chunk-S6RJHZV2.js.map +1 -0
- package/dist/chunk-UVTEJYHN.js +2 -0
- package/dist/chunk-UVTEJYHN.js.map +1 -0
- package/dist/chunk-X6FJATUE.js +29 -0
- package/dist/chunk-X6FJATUE.js.map +1 -0
- package/dist/chunk-XLVRRGOX.js +3 -0
- package/dist/chunk-XLVRRGOX.js.map +1 -0
- package/dist/client.d.ts +5 -0
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -0
- package/dist/{gateway/router.d.ts → gateway.d.ts} +37 -5
- package/dist/gateway.js +2 -0
- package/dist/gateway.js.map +1 -0
- package/dist/{client/index.d.ts → index-CyxNLlz7.d.ts} +24 -5
- package/dist/index.d.ts +313 -12
- package/dist/index.js +31 -12
- package/dist/index.js.map +1 -0
- package/dist/kyber-2WDOTUQX.js +2 -0
- package/dist/kyber-2WDOTUQX.js.map +1 -0
- package/dist/{mesh/node.d.ts → mesh.d.ts} +5 -3
- package/dist/mesh.js +2 -0
- package/dist/mesh.js.map +1 -0
- package/dist/{server/index.d.ts → server.d.ts} +145 -10
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -0
- package/dist/types.d.ts +17 -14
- package/dist/types.js +2 -26
- package/dist/types.js.map +1 -0
- package/dist/{crypto/verifier.d.ts → verifier-DTCD9imJ.d.ts} +3 -1
- package/dist/verifier-RQRYXA4C.js +2 -0
- package/dist/verifier-RQRYXA4C.js.map +1 -0
- package/dist/workers/logic-execution.d.ts +4 -2
- package/dist/workers/logic-execution.js +2 -123
- package/dist/workers/logic-execution.js.map +1 -0
- package/dist/workers/zk-verifier.d.ts +4 -2
- package/dist/workers/zk-verifier.js +2 -98
- package/dist/workers/zk-verifier.js.map +1 -0
- package/package.json +31 -17
- package/dist/bridge/index.d.ts +0 -37
- package/dist/bridge/index.js +0 -249
- package/dist/bridge/stream.js +0 -210
- package/dist/client/index.js +0 -275
- package/dist/crypto/logic-image-id.d.ts +0 -3
- package/dist/crypto/logic-image-id.js +0 -27
- package/dist/crypto/verifier.js +0 -97
- package/dist/economy/estimator.d.ts +0 -53
- package/dist/economy/estimator.js +0 -69
- package/dist/economy/index.d.ts +0 -5
- package/dist/economy/index.js +0 -3
- package/dist/economy/otel.d.ts +0 -38
- package/dist/economy/otel.js +0 -100
- package/dist/economy/telemetry.d.ts +0 -77
- package/dist/economy/telemetry.js +0 -224
- package/dist/errors.d.ts +0 -14
- package/dist/errors.js +0 -19
- package/dist/gateway/hybrid.d.ts +0 -23
- package/dist/gateway/hybrid.js +0 -199
- package/dist/gateway/router.js +0 -1036
- package/dist/mesh/index.d.ts +0 -1
- package/dist/mesh/index.js +0 -1
- package/dist/mesh/node.js +0 -853
- package/dist/prompts/adapters.d.ts +0 -16
- package/dist/prompts/adapters.js +0 -55
- package/dist/rpc/client.d.ts +0 -22
- package/dist/rpc/client.js +0 -40
- package/dist/rpc/codec/lpm.d.ts +0 -20
- package/dist/rpc/codec/lpm.js +0 -36
- package/dist/rpc/crypto/aes.d.ts +0 -22
- package/dist/rpc/crypto/aes.js +0 -47
- package/dist/rpc/crypto/kyber.d.ts +0 -27
- package/dist/rpc/crypto/kyber.js +0 -70
- package/dist/rpc/proto.d.ts +0 -2
- package/dist/rpc/proto.js +0 -33
- package/dist/rpc/server.d.ts +0 -13
- package/dist/rpc/server.js +0 -50
- package/dist/rpc/tls.d.ts +0 -26
- package/dist/rpc/tls.js +0 -54
- package/dist/rpc/types.d.ts +0 -28
- package/dist/rpc/types.js +0 -5
- package/dist/sandbox/guardian.d.ts +0 -18
- package/dist/sandbox/guardian.js +0 -58
- package/dist/sandbox/wasi.d.ts +0 -36
- package/dist/sandbox/wasi.js +0 -209
- package/dist/security/guardian.d.ts +0 -22
- package/dist/security/guardian.js +0 -52
- package/dist/security/zk.d.ts +0 -37
- package/dist/security/zk.js +0 -76
- package/dist/server/index.js +0 -937
- package/dist/server/pii.d.ts +0 -40
- package/dist/server/pii.js +0 -266
- package/dist/utils/logger.d.ts +0 -21
- package/dist/utils/logger.js +0 -70
- package/dist/utils/mcpCompact.d.ts +0 -11
- package/dist/utils/mcpCompact.js +0 -29
|
@@ -0,0 +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-PPCOS2NU.js.map
|
|
@@ -0,0 +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,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,OAA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GDzD,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"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-RWRRBYG4.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var s=class r{static instance;level="info";constructor(){this.setLevelFromEnv();}static getInstance(){return r.instance||(r.instance=new r),r.instance}setLevelFromEnv(){let e=process.env.LIOP_LOG_LEVEL?.toLowerCase();e==="silent"||e==="error"||e==="warn"||e==="info"||e==="debug"?this.level=e:this.level="info";}setLevel(e){this.level=e;}shouldLog(e){let o={silent:0,error:1,warn:2,info:3,debug:4};return o[this.level]>=o[e]}formatMessage(e,o){return `[${new Date().toISOString()}] [${e}] ${o}`}error(e,...o){this.shouldLog("error")&&console.error(this.formatMessage("ERROR",e),...o);}warn(e,...o){this.shouldLog("warn")&&console.error(this.formatMessage("WARN",e),...o);}info(e,...o){this.shouldLog("info")&&console.error(this.formatMessage("INFO",e),...o);}debug(e,...o){this.shouldLog("debug")&&console.error(this.formatMessage("DEBUG",e),...o);}},l=s.getInstance();export{l as a};//# sourceMappingURL=chunk-S6RJHZV2.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-S6RJHZV2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/logger.ts"],"names":["LiopLogger","_LiopLogger","envLevel","level","targetLevel","levels","message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,CAAQ,MAAM,IAAA,CAAK,aAAA,CAAc,OAAQD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE5D,CAEO,IAAA,CAAKD,KAAoBC,CAAAA,CAAiB,CAC5C,KAAK,SAAA,CAAU,MAAM,GACxB,OAAA,CAAQ,KAAA,CAAM,KAAK,aAAA,CAAc,MAAA,CAAQD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE5D,CAEO,MAAMD,CAAAA,CAAAA,GAAoBC,CAAAA,CAAiB,CAC7C,IAAA,CAAK,SAAA,CAAU,OAAO,CAAA,EACzB,OAAA,CAAQ,MAAM,IAAA,CAAK,aAAA,CAAc,QAASD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE7D,CACD,CAAA,CAEaC,CAAAA,CAAMR,EAAW,WAAA","file":"chunk-S6RJHZV2.js","sourcesContent":["export type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\n/**\n * LiopLogger - Structured Logging Abstraction\n * Configurable via `process.env.LIOP_LOG_LEVEL`.\n * Emits strictly to stderr to comply with MCP stdio protocols.\n */\nexport class LiopLogger {\n\tprivate static instance: LiopLogger;\n\tprivate level: LogLevel = \"info\";\n\n\tprivate constructor() {\n\t\tthis.setLevelFromEnv();\n\t}\n\n\tpublic static getInstance(): LiopLogger {\n\t\tif (!LiopLogger.instance) {\n\t\t\tLiopLogger.instance = new LiopLogger();\n\t\t}\n\t\treturn LiopLogger.instance;\n\t}\n\n\tprivate setLevelFromEnv() {\n\t\tconst envLevel = process.env.LIOP_LOG_LEVEL?.toLowerCase();\n\t\tif (\n\t\t\tenvLevel === \"silent\" ||\n\t\t\tenvLevel === \"error\" ||\n\t\t\tenvLevel === \"warn\" ||\n\t\t\tenvLevel === \"info\" ||\n\t\t\tenvLevel === \"debug\"\n\t\t) {\n\t\t\tthis.level = envLevel as LogLevel;\n\t\t} else {\n\t\t\t// Default level: info\n\t\t\tthis.level = \"info\";\n\t\t}\n\t}\n\n\tpublic setLevel(level: LogLevel) {\n\t\tthis.level = level;\n\t}\n\n\tprivate shouldLog(targetLevel: LogLevel): boolean {\n\t\tconst levels: Record<LogLevel, number> = {\n\t\t\tsilent: 0,\n\t\t\terror: 1,\n\t\t\twarn: 2,\n\t\t\tinfo: 3,\n\t\t\tdebug: 4,\n\t\t};\n\t\treturn levels[this.level] >= levels[targetLevel];\n\t}\n\n\tprivate formatMessage(level: string, message: string): string {\n\t\tconst ts = new Date().toISOString();\n\t\treturn `[${ts}] [${level}] ${message}`;\n\t}\n\n\tpublic error(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"ERROR\", message), ...args);\n\t\t}\n\t}\n\n\tpublic warn(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.error(this.formatMessage(\"WARN\", message), ...args);\n\t\t}\n\t}\n\n\tpublic info(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.error(this.formatMessage(\"INFO\", message), ...args);\n\t\t}\n\t}\n\n\tpublic debug(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.error(this.formatMessage(\"DEBUG\", message), ...args);\n\t\t}\n\t}\n}\n\nexport const log = LiopLogger.getInstance();\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-ANFXJGMP.js';import {a}from'./chunk-S6RJHZV2.js';import*as u from'fs';import {createRequire}from'module';import s from'path';import {fileURLToPath,pathToFileURL}from'url';import {Piscina}from'piscina';var P=fileURLToPath(import.meta.url),m=s.dirname(P),c=class f{static zkWorkerPool=null;getZkPool(){if(!f.zkWorkerPool){let e=import.meta.url.endsWith(".ts"),i=e?".ts":".js",o=[];if(e)try{let p=createRequire(import.meta.url).resolve("tsx/package.json");o=["--import",pathToFileURL(s.join(s.dirname(p),"dist","loader.mjs")).href];}catch{o=["--import","tsx"];}let t=[s.resolve(m,`./workers/zk-verifier${i}`),s.resolve(m,`../workers/zk-verifier${i}`)],a=t.find(r=>u.existsSync(r))||t[1];f.zkWorkerPool=new Piscina({filename:a,minThreads:1,maxThreads:2,idleTimeout:3e4,execArgv:o});}return f.zkWorkerPool}async verifyZkReceipt(e,i,o,t){let a$1=this.getZkPool();if(!a$1)throw new Error("Worker pool initialization failed");let r=await a$1.run({action:"verify_receipt",logicPayload:new Uint8Array(e),remoteImageIdHex:i,zkReceipt:new Uint8Array(o),sessionSecret:t?new Uint8Array(t):void 0});return r.verified?(a.info(`[LiopVerifier] ${r.message}`),true):(a.error(`[LiopVerifier] FAILED: ${r.message}`),false)}async verifyTeeAttestation(e){if(e.length===0)return true;try{return a.info("[LiopVerifier] TEE Attestation: Not configured (no-op)."),!0}catch(i){return a.error("[LiopVerifier] TEE Verification Failed:",i),false}}deriveImageId(e){return b(e)}};export{c as a};//# sourceMappingURL=chunk-UVTEJYHN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-UVTEJYHN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crypto/verifier.ts"],"names":["__filename","fileURLToPath","__dirname","path","LiopVerifier","_LiopVerifier","isTS","workerExt","execArgv","tsxPkg","createRequire","pathToFileURL","workerPaths","workerFilename","p","Piscina","logicPayload","remoteImageIdHex","zkReceipt","sessionSecret","pool","result","log","attestationReport","err","deriveLogicImageDigest"],"mappings":"gOAQA,IAAMA,CAAAA,CAAaC,aAAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CAC1CC,CAAAA,CAAYC,CAAAA,CAAK,OAAA,CAAQH,CAAU,CAAA,CAS5BI,CAAAA,CAAN,MAAMC,CAAa,CAEzB,OAAe,YAAA,CAA+B,IAAA,CAEtC,SAAA,EAAY,CACnB,GAAI,CAACA,CAAAA,CAAa,YAAA,CAAc,CAC/B,IAAMC,CAAAA,CAAO,MAAA,CAAA,IAAA,CAAY,GAAA,CAAI,QAAA,CAAS,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CAAmC,CAAA,CAC9D,IAAMC,CAAAA,CAAS,MAAMD,GAAAA,CAAK,GAAA,CAAI,CAC7B,MAAA,CAAQ,gBAAA,CACR,YAAA,CAAc,IAAI,UAAA,CAAWJ,CAAY,CAAA,CACzC,gBAAA,CAAAC,CAAAA,CACA,SAAA,CAAW,IAAI,UAAA,CAAWC,CAAS,CAAA,CACnC,aAAA,CAAeC,CAAAA,CAAgB,IAAI,UAAA,CAAWA,CAAa,CAAA,CAAI,MAChE,CAAC,CAAA,CAED,OAAIE,CAAAA,CAAO,QAAA,EACVC,CAAAA,CAAI,IAAA,CAAK,CAAA,eAAA,EAAkBD,CAAAA,CAAO,OAAO,CAAA,CAAE,CAAA,CACpC,IAAA,GAGRC,CAAAA,CAAI,KAAA,CAAM,CAAA,uBAAA,EAA0BD,CAAAA,CAAO,OAAO,CAAA,CAAE,CAAA,CAC7C,KAAA,CACR,CAOA,MAAa,oBAAA,CACZE,CAAAA,CACmB,CACnB,GAAIA,CAAAA,CAAkB,MAAA,GAAW,CAAA,CAAG,OAAO,KAAA,CAE3C,GAAI,CAKH,OAAAD,CAAAA,CAAI,IAAA,CAAK,yDAAyD,CAAA,CAC3D,CAAA,CACR,CAAA,MAASE,CAAAA,CAAK,CACb,OAAAF,CAAAA,CAAI,KAAA,CAAM,yCAAA,CAA2CE,CAAG,CAAA,CACjD,KACR,CACD,CAKO,aAAA,CAAcR,CAAAA,CAA8B,CAClD,OAAOS,CAAAA,CAAuBT,CAAY,CAC3C,CACD","file":"chunk-UVTEJYHN.js","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { Piscina } from \"piscina\";\nimport { log } from \"../utils/logger.js\";\nimport { deriveLogicImageDigest } from \"./logic-image-id.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n/**\n * LIOP Tier-0 Industrial Verifier\n *\n * This engine is responsible for the trustless verification of remote logic execution.\n * It validates both the integrity of the code (ZkImageID) and the mathematical proof\n * of its execution (ZkSeal), as well as hardware-level attestation (TEE).\n */\nexport class LiopVerifier {\n\t// Singleton Worker Pool for heavy ZK verification\n\tprivate static zkWorkerPool: Piscina | null = null;\n\n\tprivate getZkPool() {\n\t\tif (!LiopVerifier.zkWorkerPool) {\n\t\t\tconst isTS = import.meta.url.endsWith(\".ts\");\n\t\t\tconst workerExt = isTS ? \".ts\" : \".js\";\n\n\t\t\tlet execArgv: string[] = [];\n\t\t\tif (isTS) {\n\t\t\t\ttry {\n\t\t\t\t\tconst req = createRequire(import.meta.url);\n\t\t\t\t\tconst tsxPkg = req.resolve(\"tsx/package.json\");\n\t\t\t\t\tconst absoluteTsx = pathToFileURL(\n\t\t\t\t\t\tpath.join(path.dirname(tsxPkg), \"dist\", \"loader.mjs\"),\n\t\t\t\t\t).href;\n\t\t\t\t\texecArgv = [\"--import\", absoluteTsx];\n\t\t\t\t} catch (_e) {\n\t\t\t\t\texecArgv = [\"--import\", \"tsx\"];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Support both flat dist/ and original src/ structure\n\t\t\tconst workerPaths = [\n\t\t\t\tpath.resolve(__dirname, `./workers/zk-verifier${workerExt}`), // Flat dist/ (tsup)\n\t\t\t\tpath.resolve(__dirname, `../workers/zk-verifier${workerExt}`), // Original src/\n\t\t\t];\n\n\t\t\tconst workerFilename =\n\t\t\t\tworkerPaths.find((p) => fs.existsSync(p)) || workerPaths[1];\n\n\t\t\tLiopVerifier.zkWorkerPool = new Piscina({\n\t\t\t\tfilename: workerFilename,\n\t\t\t\tminThreads: 1,\n\t\t\t\tmaxThreads: 2, // Minimal footprint since verification is fast compared to generation\n\t\t\t\tidleTimeout: 30000,\n\t\t\t\texecArgv,\n\t\t\t});\n\t\t}\n\t\treturn LiopVerifier.zkWorkerPool;\n\t}\n\n\t/**\n\t * Verifies a Zero-Knowledge Receipt from a remote LIOP node via Worker Pool.\n\t *\n\t * @param logicPayload The raw WASM or JS logic that was sent to the provider.\n\t * @param remoteImageIdHex The ImageID reported by the provider (must match our local calculation).\n\t * @param zkReceipt The mathematical proof (Seal + Journal) from the zkVM.\n\t */\n\tpublic async verifyZkReceipt(\n\t\tlogicPayload: Buffer,\n\t\tremoteImageIdHex: string,\n\t\tzkReceipt: Buffer,\n\t\tsessionSecret?: Buffer,\n\t): Promise<boolean> {\n\t\tconst pool = this.getZkPool();\n\t\tif (!pool) throw new Error(\"Worker pool initialization failed\");\n\t\tconst result = await pool.run({\n\t\t\taction: \"verify_receipt\",\n\t\t\tlogicPayload: new Uint8Array(logicPayload),\n\t\t\tremoteImageIdHex,\n\t\t\tzkReceipt: new Uint8Array(zkReceipt),\n\t\t\tsessionSecret: sessionSecret ? new Uint8Array(sessionSecret) : undefined,\n\t\t});\n\n\t\tif (result.verified) {\n\t\t\tlog.info(`[LiopVerifier] ${result.message}`);\n\t\t\treturn true;\n\t\t}\n\n\t\tlog.error(`[LiopVerifier] FAILED: ${result.message}`);\n\t\treturn false;\n\t}\n\n\t/**\n\t * Verifies if a node is running inside an authenticated TEE (e.g. AWS Nitro).\n\t *\n\t * @param attestationReport The COSE-signed attestation document from the hardware.\n\t */\n\tpublic async verifyTeeAttestation(\n\t\tattestationReport: Buffer,\n\t): Promise<boolean> {\n\t\tif (attestationReport.length === 0) return true; // Optional in Mesh Alpha\n\n\t\ttry {\n\t\t\t// Architecture for AWS Nitro Enclaves:\n\t\t\t// 1. Decode CBOR/COSE\n\t\t\t// 2. Verify Signature against AWS Nitro Root CA\n\t\t\t// 3. Compare PCRs\n\t\t\tlog.info(\"[LiopVerifier] TEE Attestation: Not configured (no-op).\");\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tlog.error(\"[LiopVerifier] TEE Verification Failed:\", err);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Derives the ImageID of a logic payload following the LIOP v1 Standard.\n\t */\n\tpublic deriveImageId(logicPayload: Buffer): Buffer {\n\t\treturn deriveLogicImageDigest(logicPayload);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import {a,b}from'./chunk-HM77MWB6.js';import {a as a$2}from'./chunk-PPCOS2NU.js';import {a as a$1}from'./chunk-S6RJHZV2.js';import {Buffer}from'buffer';import G from'crypto';import*as Z from'fs';import {createRequire}from'module';import w from'path';import {fileURLToPath,pathToFileURL}from'url';import*as W from'@grpc/grpc-js';import {Piscina,FixedQueue}from'piscina';import {z as z$1}from'zod';import {zodToJsonSchema}from'zod-to-json-schema';import*as z from'acorn';import {simple}from'acorn-walk';var J={"grpc.keepalive_time_ms":3e4,"grpc.keepalive_timeout_ms":1e4,"grpc.keepalive_permit_without_calls":1,"grpc.max_send_message_length":-1,"grpc.max_receive_message_length":-1,"grpc.enable_retries":1},T=class{server;constructor(){this.server=new W.Server(J);}addService(e){this.server.addService(a.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,t){let r=b(t);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,r,(s,o)=>{if(s){n(s);return}a$1.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async stop(){return new Promise(e=>{this.server.tryShutdown(()=>{a$1.info("[LIOP-RPC] Server shut down"),e();});})}};var A=class l{piiFields;static TAINT_PROPAGATING_METHODS=new Set(["charCodeAt","codePointAt","charAt","at","indexOf","lastIndexOf","search","localeCompare","startsWith","endsWith","includes","substring","slice","substr","split","match","matchAll","replace","replaceAll","normalize","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat"]);static ARRAY_CALLBACK_METHODS=new Set(["map","forEach","filter","find","some","every","flatMap","findIndex"]);static REDUCE_METHODS=new Set(["reduce","reduceRight"]);constructor(e){this.piiFields=new Set(e.map(t=>t.toLowerCase()));}analyze(e){let t;try{let n=`function liop_analysis_wrapper(env) {
|
|
2
|
+
${e}
|
|
3
|
+
}`;t=z.parse(n,{ecmaVersion:2022,sourceType:"script",locations:!0});}catch{return null}let r=new Set,i=new Set;return this.identifyRecordBoundVars(t,r),this.propagateTaint(t,r,i),this.checkReturnStatements(t,r,i)}identifyRecordBoundVars(e,t){simple(e,{CallExpression:n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isEnvRecordsAccess(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(l.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let p=c.params[0];p.type==="Identifier"&&t.add(p.name);}if(l.REDUCE_METHODS.has(o)&&c.params.length>1){let p=c.params[1];p.type==="Identifier"&&t.add(p.name);}}},ForOfStatement:n=>{if(this.isEnvRecordsAccess(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&t.add(s.id.name);}}),simple(e,{VariableDeclarator:n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isEnvRecordsAccess(s.object)&&t.add(n.id.name);}}});}propagateTaint(e,t,r){for(let i=0;i<3;i++){let n=r.size;if(simple(e,{VariableDeclarator:o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,t,r)&&r.add(o.id.name);},AssignmentExpression:o=>{o.left.type==="Identifier"&&this.isExpressionTainted(o.right,t,r)&&r.add(o.left.name);},CallExpression:o=>{if(o.callee.type!=="MemberExpression")return;let a=o.callee;this.getPropertyName(a)==="push"&&a.object.type==="Identifier"&&o.arguments.some(p=>this.isExpressionTainted(p,t,r))&&r.add(a.object.name);}}),r.size===n)break}}checkReturnStatements(e,t,r){let i=null;return simple(e,{ReturnStatement:s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,t,r)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,t,r);i={reason:`PII side-channel detected: output contains values derived from restricted fields. ${a?`Operation: ${a}. `:""}Use only non-PII fields (e.g., numeric/date columns) for aggregations.`,line:o,operation:a};}}}),i}isExpressionTainted(e,t,r){switch(e.type){case "Identifier":return r.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,t,r);case "CallExpression":return this.isCallExprTainted(e,t,r);case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,t,r)||this.isExpressionTainted(i.right,t,r)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,t,r)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,t,r)||this.isExpressionTainted(i.consequent,t,r)||this.isExpressionTainted(i.alternate,t,r)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"&&this.isExpressionTainted(n.value,t,r));case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,t,r));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,t,r));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,t,r)}default:return false}}isMemberExprTainted(e,t,r){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&t.has(e.object.name)&&i&&this.piiFields.has(i.toLowerCase()))return true;if(e.object.type==="MemberExpression"&&i&&this.piiFields.has(i.toLowerCase())){let n=e.object;if(n.computed&&this.isEnvRecordsAccess(n.object))return true}if(this.isExpressionTainted(e.object,t,r))return true;if(e.computed&&e.object.type==="Identifier"&&t.has(e.object.name)&&e.property.type==="Literal"){let n=e.property.value;if(typeof n=="string"&&this.piiFields.has(n.toLowerCase()))return true}return false}isCallExprTainted(e,t,r){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&l.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,t,r))return true;if(this.isEnvRecordsAccess(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,t,r)}if(this.isExpressionTainted(i.object,t,r)||e.arguments.some(s=>this.isExpressionTainted(s,t,r)))return true}if(e.callee.type==="MemberExpression"){let i=e.callee;this.getPropertyName(i)==="push"&&i.object.type==="Identifier"&&e.arguments.some(s=>this.isExpressionTainted(s,t,r))&&r.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,t,r))}return false}doesCallbackProduceTaint(e,t,r,i){let n=new Set(r),s=new Set(i);if(e.params.length>0){let p=t!==null&&l.REDUCE_METHODS.has(t)?1:0;e.params.length>p&&e.params[p].type==="Identifier"&&n.add(e.params[p].name);}if(e.type==="ArrowFunctionExpression"&&e.body.type!=="BlockStatement")return this.isExpressionTainted(e.body,n,s);let o=false,a={ReturnStatement:c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);}};return simple(e.body,a),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let t=e.property.value;if(typeof t=="string")return t}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let t=e;if(this.getPropertyName(t)==="records"&&t.object.type==="Identifier"&&t.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,t,r){if(e.type==="Identifier"){let i=e.name;if(r.has(i))return `variable '${i}' is PII-derived`}if(e.type==="ObjectExpression"){let i=e;for(let n of i.properties)if(n.type==="Property"&&this.isExpressionTainted(n.value,t,r))return `property '${n.key.type==="Identifier"?n.key.name:"unknown"}' contains PII-derived value`}if(e.type==="CallExpression"){let i=e;if(i.callee.type==="MemberExpression"){let n=this.getPropertyName(i.callee);if(n)return `result of .${n}() on PII data`}}}};var B={aspirin:"Medication",lisinopril:"Medication",metformin:"Medication",amlodipine:"Medication",atorvastatin:"Medication",omeprazole:"Medication",losartan:"Medication",simvastatin:"Medication",levothyroxine:"Medication",ibuprofen:"Medication",acetaminophen:"Medication",amoxicillin:"Medication",ciprofloxacin:"Medication",prednisone:"Medication",warfarin:"Medication",insulin:"Medication",hydrochlorothiazide:"Medication",gabapentin:"Medication",albuterol:"Medication",pantoprazole:"Medication",hypertension:"Condition",diabetes:"Condition",bronchitis:"Condition",pneumonia:"Condition",asthma:"Condition"},_=4,V=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,O=class l{static nlp=null;async getNlp(){if(!l.nlp){let e=await import('compromise/three');l.nlp=e.default||e,l.nlp.addWords(B);}return l.nlp}async scan(e){if(e.length<_||V.test(e))return {detected:false,entities:[]};let r=(await this.getNlp())(e),i=[],n=r.people().out("array");for(let a of n){let c=a.trim();c.length>=_&&i.push({type:"person",text:c});}let s=r.places().out("array");for(let a of s){let c=a.trim();c.length>=_&&i.push({type:"place",text:c});}let o=r.organizations().out("array");for(let a of o){let c=a.trim();c.length>=_&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,t=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(t.has(e))return {detected:false,entities:[]};t.add(e);let r=Array.isArray(e)?e:Object.values(e),i=[];for(let n of r){let s=await this.scanDeep(n,t);if(s.detected&&(i.push(...s.entities),s.entities.some(o=>o.type==="person")))return {detected:true,entities:i}}return {detected:i.length>0,entities:i}}return {detected:false,entities:[]}}};function X(l){let e=l.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let t=0,r=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);r&&(n*=2,n>9&&(n-=9)),t+=n,r=!r;}return t%10===0}function Q(l){let e=l.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let t=e.substring(4)+e.substring(0,4),r="";for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n>=65&&n<=90)r+=(n-55).toString();else if(n>=48&&n<=57)r+=t.charAt(i);else return false}try{return BigInt(r)%97n===1n}catch{return false}}var f={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:l=>!l.endsWith("@example.com")&&!l.endsWith("@test.com")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:X},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:l=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(l)?false:l.split(".").map(Number).every(r=>r>=0&&r<=255)},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:l=>{let e=l.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")}},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:l=>{let e=l.replace(/\D/g,"");if(e.length!==9)return false;let t=parseInt(e.substring(0,3),10);return !(t===0||t===666||t>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")}},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Q},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},H={GLOBAL_STRICT:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.PASSPORT_MRZ,f.IBAN],US_COMPLIANT:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.SSN,f.PASSPORT_MRZ],EU_GDPR:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.IBAN,f.PASSPORT_MRZ]},N=class l{patterns;forbiddenKeysSet;nerScanner;static KEY_SAFELIST=new Set(["grid","video","android","identity","provide","override","validate","hidden","widget","guidelines","beside","guideline","outside","inside","collide","decide","divide","aside","ride","side","wide","hide","tide","pride","bride","slide","guide","stride","oxide","dioxide","suicide","homicide","pesticide","valid","invalid","void","avoid","diagnosis","medication","namespace","namesake","rename","filename","hostname","typename","unnamed","renamed","phonetic","phoneme","microphone","headphone","telephone","saxophone","smartphone","streetview","addressable","addressing","cityscape","electricity","capacity","velocity","opacity","timestamp","timezone","image_id","computation_result","zk_receipt","testid","toolid","sessionid","peerid","nodeid","requestid","correlationid","traceid","spanid"]);shortTokenBoundaryPatterns;longForbiddenTokens;constructor(e=[],t=[],r){this.patterns=e,this.forbiddenKeysSet=new Set(t.map(i=>i.toLowerCase())),this.nerScanner=r??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp(`(?:^|[_-])${i}(?:$|[_-])|(?:^|[a-z])${i.charAt(0).toUpperCase()}${i.slice(1)}|^${i}$`,"i")):this.longForbiddenTokens.push(i);}async scan(e,t=new WeakSet){if(e==null)return null;if(typeof e=="string"){let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{let n=JSON.parse(r),s=await this.scan(n,t);if(s)return s}catch{}let i=this.checkString(e);if(i)return i;if(this.nerScanner){let n=await this.nerScanner.scan(e);if(n.detected){let s=n.entities.find(o=>o.type==="person");if(s)return `PII Entity Detected: person name "${s.text}"`}}return null}if(typeof e=="object"){if(t.has(e))return null;if(t.add(e),Array.isArray(e))for(let r of e){let i=await this.scan(r,t);if(i)return i}else for(let[r,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(r.toLowerCase()))return `Forbidden Key: ${r}`;let n=this.checkKeyFuzzy(r);if(n)return n;let s=await this.scan(i,t);if(s)return s}}return null}checkKeyFuzzy(e){let t=e.toLowerCase();if(l.KEY_SAFELIST.has(t))return null;for(let[r,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${r}"`;for(let r of this.longForbiddenTokens)if(t.includes(r))return `Forbidden Key (fuzzy): ${e} contains restricted token "${r}"`;return null}checkString(e){for(let t of this.patterns)if(typeof t=="string"){if(e.toLowerCase().includes(t.toLowerCase()))return t}else if(t instanceof RegExp){if(t.global&&(t.lastIndex=0),t.test(e))return t.source}else if(typeof t=="object"&&t!==null){let r=t;if(typeof r.pattern=="string"){if(e.toLowerCase().includes(r.pattern.toLowerCase())&&(!r.validator||r.validator(r.pattern)))return r.name}else if(r.pattern instanceof RegExp){r.pattern.global&&(r.pattern.lastIndex=0);let i=r.pattern.exec(e);for(;i!==null;){let n=i[0];if(!r.validator||r.validator(n))return r.name;if(!r.pattern.global)break;i=r.pattern.exec(e);}}}return null}};function oe(){let l=process.env.LIOP_RESPECT_PLAIN_TOOL_PAYLOAD?.toLowerCase().trim();return l==="1"||l==="true"||l==="yes"}var U=w.dirname(fileURLToPath(import.meta.url)),K=class l{constructor(e,t){this.serverInfo=e;this.config=t;let r=this.config?.security?.enableNerScanning?new O:null;this.piiScanner=new N(this.config?.security?.piiPatterns??H.GLOBAL_STRICT,this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],r);let i=this.config?.security?.rateLimit;this.toolCallWindowMs=i?.windowMs??Number.parseInt(process.env.LIOP_RATE_LIMIT_WINDOW_MS??"60000",10),this.toolCallMaxPerWindow=i?.maxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_MAX??"15",10),this.globalCallMaxPerWindow=i?.globalMaxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_GLOBAL_MAX??"40",10);let n=this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"];this.taintAnalyzer=new A(n);let s=import.meta.url.endsWith(".ts"),o=s?".ts":".js",a=[];if(s)try{let h=createRequire(import.meta.url).resolve("tsx/package.json");a=["--import",pathToFileURL(w.join(w.dirname(h),"dist","loader.mjs")).href];}catch{a=["--import","tsx"];}let c=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let p=[w.resolve(U,`./workers/logic-execution${o}`),w.resolve(U,`../workers/logic-execution${o}`)],u=p.find(d=>Z.existsSync(d))||p[1];this.workerPool=new Piscina({filename:u,minThreads:this.config?.workerPool?.minThreads??(c?0:2),maxThreads:this.config?.workerPool?.maxThreads??(c?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(c?500:5e3),maxQueue:"auto",taskQueue:new FixedQueue,execArgv:a,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}}),this.resource("LIOP Envelope Specification","liop://protocol/envelope-spec","Complete Logic-on-Origin envelope format, execution rules, and security constraints","text/plain",()=>Promise.resolve(this.buildEnvelopeSpec()));}logicCache=new Map;connectionStats=new Map;CACHE_TTL_MS=1440*60*1e3;THROTTLE_THRESHOLD=5;THROTTLE_COOLDOWN_MS=60*1e3;toolCallWindows=new Map;toolCallMaxPerWindow;toolCallWindowMs;globalCallWindow=[];globalCallMaxPerWindow;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;sessions=new Map;static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,(?<name>[^}]*))?\}\n(?<logic>[\s\S]*?)\n@END/m;extractLogic(e){let t=e.match(l.LIOP_COMPACT_REGEX);return t?.groups?.logic?t.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}runPreflightPolicy(e,t,r){if(r){let n=t.replace(/\s+/g," ");if(r.enforceAggregationFirst&&[/return\s+env\.records(?!\s*\.\s*(?:reduce|length|filter|every|some|find)\b)/i,/return\s*\{[\s\S]*\b(accounts|patients|rows|records)\s*:\s*env\.records(?!\s*\.\s*(?:reduce|length|filter)\b)/i].some(o=>o.test(n)))return "Preflight policy rejected: potential row-level export pattern detected.";if(r.preflightDenyPatterns?.some(s=>s.test(n)))return "Preflight policy rejected: custom deny pattern matched."}let i=this.taintAnalyzer.analyze(t);return i?`Preflight policy rejected: ${i.reason}`:null}validateOutputPolicy(e,t,r){if(!r)return null;let i=this.parseUnknownJson(t);if(r.outputSchema){let s=(()=>{if(!(r.outputSchema instanceof z$1.ZodObject))return r.outputSchema;let o=r.outputSchema;return o._def.catchall instanceof z$1.ZodNever?o.strict():o})().safeParse(i);if(!s.success)return `[LIOP] Output schema violation for ${e}: ${s.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}. HINT: Your output must conform to the declared schema. Use 'env.records' to access the dataset and return only allowed fields.`}return r.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),r.enforceAggregationFirst,this.sandboxRecords.length)?process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?"Aggregation-First Policy Violation: row-level export or K-Anonymity violation blocked. HINT: Use .reduce() to produce a flat {key:value} object. Do NOT use .map() to create arrays of objects. Ensure dataset size > 10 for detailed results.":"Aggregation-First Policy Violation: Output blocked due to privacy constraints.":null}unwrapForAggregationPolicyScan(e){if(typeof e=="string"){let n=e.trim();if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{return this.unwrapForAggregationPolicyScan(JSON.parse(n))}catch{return e}return e}if(!e||typeof e!="object")return e;let t=e;if(!Array.isArray(t.content)||t.content.length===0)return e;let r=[];for(let n of t.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&r.push(s);}if(r.length===0)return e;let i=r.length===1?r[0]:r.join(`
|
|
4
|
+
`);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,t,r){let i=typeof t=="object"&&typeof t.maxOutputRows=="number"?t.maxOutputRows:10,n=typeof t=="object"&&typeof t.allowPrimitiveArrays=="boolean"?t.allowPrimitiveArrays:true;if(typeof e=="string"){let s=e.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(s),t,r)}catch{return false}return false}if(Array.isArray(e))return e.length>0&&e.every(s=>typeof s=="object"&&s!==null)?e.length>i?true:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r));if(e&&typeof e=="object"){let s=Object.keys(e);return r!==void 0&&r>0&&r<10&&(s.length>3||Object.values(e).some(a=>Array.isArray(a)||typeof a=="object"&&a!==null))||s.length>i?true:Object.values(e).some(o=>this.violatesAggregationFirstPolicy(o,t,r))}return false}buildEnvelopeSpec(){let e=["LIOP v1 Envelope Specification","================================","","FORMAT:","","Compact Envelope:"," @LIOP{wasi_v1,TaskName}"," <JavaScript code>"," @END","","RUNTIME ENVIRONMENT:","- env.records: Array of data objects from the origin","- Must use 'return' to output results","- Zero-Trust WASI Sandbox (Node.js Worker Pool)","- Return aggregated objects, NOT raw row-level arrays","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution"];return this.config?.security?.forbiddenKeys?.length&&e.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),e.push("","TAINT TRACKING (Phase 108):","- AST-level analysis blocks PII-derived scalars (charCodeAt, charAt, etc.)","- Operations on restricted fields are tracked through variable assignments","- Boolean inference (field.charCodeAt(0) < N ? 1 : 0) is blocked","- Allowed: aggregations on non-PII fields (balance, amount, date)","","K-ANONYMITY:","- Datasets < 10 records: max 3 scalar output fields, no nesting","- Datasets >= 10 records: max 10 output fields","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)"),e.join(`
|
|
5
|
+
`)}extractSchemaFieldSummary(e,t=0){if(t>3)return "{...}";let r=e.type,i=e.properties,n=e.items;return i?`{${Object.entries(i).map(([o,a])=>{let c=a.type;if(c==="array"&&a.items){let p=this.extractSchemaFieldSummary(a.items,t+1);return `${o}(array of ${p})`}if(c==="object"&&a.properties){let p=this.extractSchemaFieldSummary(a,t+1);return `${o}(${p})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:r==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,t+1)}`:r||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,t,r,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z$1.object(r),o=zodToJsonSchema(s),a=t,c=i;if(r.payload&&r.payload instanceof z$1.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a+=`
|
|
6
|
+
|
|
7
|
+
Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a+=`
|
|
8
|
+
Restricted fields: ${u.join(", ")}.`),this.activeSchema){let d=this.extractSchemaFieldSummary(this.activeSchema);a+=`
|
|
9
|
+
Data structure: ${d}. Full schema: resource liop://schema/global`;}c=async(d,h)=>{let y="global_connection",b=Date.now(),m=this.connectionStats.get(y)||{failures:0,lastAttempt:0};if(m.failures>=this.THROTTLE_THRESHOLD&&b-m.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let M=d.payload,Y=d.__liop_bypass_ast_cache===true,L=G.createHash("sha256").update(M).digest("hex"),S=this.extractLogic(M),C=this.logicCache.get(L);if(!Y&&C&&b-C.timestamp<this.CACHE_TTL_MS&&S){d.payload=S;let v=this.runPreflightPolicy(e,S,n);return v?{content:[{type:"text",text:v}],isError:true}:await this.executeInWorkerPool(d,S,e)}if(!S)return oe()?await i(d,h):(m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:"Error: Malformed payload. Missing @LIOP boundary.\\nYou MUST wrap your logic exactly like this:\\n\\n@LIOP{wasi_v1,DynamicAudit}\\n// Your JS code here\\n@END"}],isError:true});try{let v=this.extractLogic(d.payload);d.payload=v;let R=this.runPreflightPolicy(e,v,n);if(R)return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:R}],isError:!0};let D=await this.executeInWorkerPool(d,v,e);return D.isError?(m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m)):(this.connectionStats.set(y,{failures:0,lastAttempt:b}),this.logicCache.set(L,{hash:L,timestamp:b})),D}catch(v){let R=v;return m.failures++,m.lastAttempt=b,this.connectionStats.set(y,m),{content:[{type:"text",text:`ExecutionRuntimeException: ${R.message}`}],isError:true}}};}let p={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a,inputSchema:p},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{a$1.info(`[LIOP-Mesh] Failed to auto-announce tool ${e}: ${u.message}`);});}prompt(e,t,r,i){if(this.prompts.has(e))throw new Error(`Prompt already registered: ${e}`);this.prompts.set(e,{prompt:{name:e,description:t,arguments:r},handler:i});}enableZeroShotAutonomy(){this.prompt("liop_blind_analyst","The official Logic-Injection-on-Origin Protocol system prompt. Instructs the LLM on how to securely inject Logic-on-Origin without violating PII or safety constraints.",[],e=>({description:"LIOP Blind Analyst Instructions",messages:[{role:"user",content:{type:"text",text:`You are the "Blind Analyst" operating within the Logic-Injection-on-Origin Protocol (LIOP) ecosystem.
|
|
10
|
+
Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
|
|
11
|
+
|
|
12
|
+
INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
|
|
13
|
+
1. DATA PRIVACY: NEVER attempt to export Personally Identifiable Information (PII). The LIOP Egress Shield will block any response containing raw IDs, names, or addresses.
|
|
14
|
+
2. AGGREGATION FIRST: Always prefer returning counts, averages, or anonymized summaries.
|
|
15
|
+
3. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
|
|
16
|
+
Structure:
|
|
17
|
+
@LIOP{wasi_v1,AnalysisTask}
|
|
18
|
+
// Your JS Code Here
|
|
19
|
+
@END
|
|
20
|
+
4. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
|
|
21
|
+
5. LOCALIZATION: Format all JSON response keys in the language used by the user in their query (e.g., use Spanish keys if the query is in Spanish).
|
|
22
|
+
6. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.${this.activeSchema?`
|
|
23
|
+
|
|
24
|
+
CURRENT DATA DICTIONARY (STRICT):
|
|
25
|
+
${JSON.stringify(this.activeSchema,null,2)}`:""}
|
|
26
|
+
|
|
27
|
+
Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,t,r,i,n){if(this.resources.has(t))throw new Error(`Resource URI already registered: ${t}`);this.resources.set(t,{name:e,uri:t,description:r,mimeType:i,content:n});}dataDictionary(e,t="Global Medical Data Dictionary",r="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){this.activeSchema=e;let n=this.extractSchemaFieldSummary(e);for(let[s,o]of this.tools.entries())o.schema.shape.payload&&o.schema.shape.payload instanceof z$1.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
|
|
28
|
+
Data structure: ${n}. Full schema: resource ${r}`,this.tools.set(s,o));this.resource(t,r,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),a$1.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let t=Date.now(),r=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>t-o<r);if(s.length>=i){let o=Math.ceil((s[0]+r-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${r/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(t),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),t=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<t),this.globalCallWindow.length>=r){let i=Math.ceil((this.globalCallWindow[0]+t-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${t/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e){let t=this.tools.get(e.name);if(!t)throw new Error(`Tool not found: ${e.name}`);let r=this.checkGlobalRateLimit();if(r)return r;let i=this.checkToolCallRateLimit(e.name);if(i)return i;try{let n=t.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(n.__liop_bypass_ast_cache=!0),n&&typeof n.payload=="string"){let o=n.payload,a=this.extractLogic(o);if(a){let c=this.runPreflightPolicy(e.name,a,t.policy);return c?{content:[{type:"text",text:c}],isError:!0}:(n.payload=a,await this.executeInWorkerPool(n,a,e.name))}}return await t.handler(n,{})}catch(n){let s=n;return s instanceof z$1.ZodError?{content:[{type:"text",text:`Validation Error: ${s.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${s.message}`}],isError:true}}}listTools(){return Array.from(this.tools.values()).map(e=>e.tool)}listPrompts(){return Array.from(this.prompts.values()).map(e=>e.prompt)}async getPrompt(e){let t=this.prompts.get(e.name);if(!t)throw new Error(`Prompt not found: ${e.name}`);return await t.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let t=this.resources.get(e);if(!t)throw new Error(`Resource not found: ${e}`);let r="No description provided";return typeof t.content=="function"?r=await t.content():typeof t.content=="string"?r=t.content:t.description&&(r=t.description),{contents:[{uri:t.uri,mimeType:t.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let t=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=e.port??t??50051;this.meshNode=new a$2(e.meshConfig),await this.meshNode.start();let i=this.meshNode;this.meshNode.registerManifestHandler(()=>{let n=this.listTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),s=Array.from(this.resources.values()).map(o=>({name:o.name,uri:o.uri,description:o.description,mimeType:o.mimeType,text:typeof o.content=="string"?o.content:o.description}));return {peerId:i.getPeerId(),grpcPort:r,tools:n,resources:s,serverInfo:this.serverInfo}});for(let n of this.listTools())await this.meshNode.announceCapability(n.name).catch(a$1.info);await this.meshNode.announceManifest().catch(a$1.info),this.rpcServer=new T,this.rpcServer.addService({negotiateIntent:(n,s)=>{let o=n.request;a$1.info(`[LIOP-RPC] Negotiating intent for capability: ${o.capability_hash}`),import('./kyber-2WDOTUQX.js').then(async({Kyber768Wrapper:a})=>{let{publicKey:c,secretKey:p}=await a.generateKeyPair(),u=G.randomUUID();this.sessions.set(u,{capability_hash:o.capability_hash,kyber_sk:p}),s(null,{accepted:true,session_token:u,error_message:"",kyber_public_key:c});});},executeLogic:async n=>{let s=n.request;a$1.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${s.session_token}`);let o=this.sessions.get(s.session_token);if(!o){n.emit("error",{code:W.status.UNAUTHENTICATED,details:"Invalid session token"});return}try{let a=await this.workerPool.run({ciphertext:s.pqc_ciphertext,secretKeyObj:Array.from(o.kyber_sk),wasmBinary:s.wasm_binary,inputs:s.inputs,aesNonce:s.aes_nonce,records:this.sandboxRecords,sessionToken:s.session_token,isEncrypted:!0}),c;try{c=typeof a.output=="string"?a.output:JSON.stringify(a.output);let h=JSON.parse(c);if(h.__liop_proxy_tool){a$1.info(`[LIOP-RPC] Executing Proxied Tool: ${h.__liop_proxy_tool}`);let y=await this.callTool({name:h.__liop_proxy_tool,arguments:h.__liop_proxy_args||{}});c=JSON.stringify(y);}}catch{c=String(a.output);}let p={semantic_evidence:c,cryptographic_proof:Buffer.from(a.image_id||"","hex"),zk_receipt:a.zk_receipt?Buffer.from(a.zk_receipt,"base64"):Buffer.from(""),is_error:!1},u=await this.piiScanner.scan([{type:"text",text:c}]),d=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(c));if(u||d){let h=u||"Aggregation-First Policy Violation";a$1.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${h}`),p.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",p.is_error=!0;}n.write(p,()=>{n.end();});}catch(a){let c=a,p=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",u=c.message||String(a);a$1.error(`[LIOP-RPC] Execution Error: ${u}`);let h={semantic_evidence:p?`Execution Error: ${u}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{n.write(h,()=>{n.end();});}catch{n.end();}}}}),this.boundPort=await this.rpcServer.listen(r),a$1.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,t,r){try{let i=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(t),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1}),s=[{type:"text",text:JSON.stringify({computation_result:i.output,image_id:i.image_id,zk_receipt:i.zk_receipt,status:"Worker Pool Execution Success"})}],o=r?this.tools.get(r)?.policy:void 0,a=this.validateOutputPolicy(r||"unknown_tool",i.output,o);if(a)return a$1.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${a}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?a:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let c=await this.piiScanner.scan(s),p=this.violatesAggregationFirstPolicy(i.output);if(c||p){let u=c||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return a$1.info(`[LIOP-SDK] Secure egress blocked in local execution: ${u}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${u}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:s}}catch(i){let n=i,s=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",o=n.message||String(i);return a$1.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:s?`WorkerPoolError: ${o}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error."}],isError:true}}}async close(){this.workerPool&&await this.workerPool.close({force:true}),this.rpcServer&&await this.rpcServer.stop(),this.meshNode&&await this.meshNode.stop();}};export{T as a,O as b,f as c,H as d,N as e,K as f};//# sourceMappingURL=chunk-X6FJATUE.js.map
|
|
29
|
+
//# sourceMappingURL=chunk-X6FJATUE.js.map
|