@nekzus/liop 2.0.0-beta.2 → 2.0.0-beta.4
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 +36 -9
- package/dist/bin/agent.js +2 -2
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.d.ts +4 -2
- package/dist/bridge.js +1 -1
- package/dist/{chunk-7I6YJS3C.js → chunk-DQ6UW6L7.js} +2 -2
- package/dist/chunk-DQ6UW6L7.js.map +1 -0
- package/dist/chunk-L5A64CNT.js +54 -0
- package/dist/chunk-L5A64CNT.js.map +1 -0
- package/dist/chunk-N6FGTZ6A.js +3 -0
- package/dist/chunk-N6FGTZ6A.js.map +1 -0
- package/dist/chunk-RYYRR4N5.js +31 -0
- package/dist/chunk-RYYRR4N5.js.map +1 -0
- package/dist/chunk-SB5XJXKV.js +2 -0
- package/dist/chunk-SB5XJXKV.js.map +1 -0
- package/dist/chunk-SW53FNSN.js +2 -0
- package/dist/chunk-SW53FNSN.js.map +1 -0
- package/dist/{chunk-TNMS53OP.js → chunk-TYVG6TXQ.js} +2 -2
- package/dist/{chunk-TNMS53OP.js.map → chunk-TYVG6TXQ.js.map} +1 -1
- package/dist/chunk-VGXNGTIC.js +33 -0
- package/dist/chunk-VGXNGTIC.js.map +1 -0
- package/dist/chunk-W2QGWRTT.js +3 -0
- package/dist/chunk-W2QGWRTT.js.map +1 -0
- package/dist/chunk-YZVCAJJO.js +13 -0
- package/dist/chunk-YZVCAJJO.js.map +1 -0
- package/dist/client.d.ts +3 -2
- package/dist/client.js +1 -1
- package/dist/gateway.d.ts +14 -3
- package/dist/gateway.js +1 -1
- package/dist/{index-BihN3W-K.d.ts → index-B_Vbrb_I.d.ts} +14 -1
- package/dist/index-CL8m1L1d.d.ts +500 -0
- package/dist/index.d.ts +124 -6
- package/dist/index.js +17 -4
- package/dist/index.js.map +1 -1
- package/dist/mesh.d.ts +3 -0
- package/dist/mesh.js +1 -1
- package/dist/server.d.ts +5 -342
- package/dist/server.js +1 -1
- package/dist/types-DzEXgi4s.d.ts +228 -0
- package/dist/types.d.ts +3 -148
- package/dist/types.js +1 -1
- package/dist/verifier-Z26UC7M4.js +2 -0
- package/dist/{verifier-6M7GY4TW.js.map → verifier-Z26UC7M4.js.map} +1 -1
- package/dist/workers/logic-execution.d.ts +7 -6
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/dist/workers/zk-verifier.d.ts +4 -4
- package/dist/workers/zk-verifier.js +1 -1
- package/dist/workers/zk-verifier.js.map +1 -1
- package/package.json +4 -1
- package/dist/chunk-7I6YJS3C.js.map +0 -1
- package/dist/chunk-C65RM2A3.js +0 -24
- package/dist/chunk-C65RM2A3.js.map +0 -1
- package/dist/chunk-ISKM7EAL.js +0 -2
- package/dist/chunk-ISKM7EAL.js.map +0 -1
- package/dist/chunk-NWZ5KZDN.js +0 -3
- package/dist/chunk-NWZ5KZDN.js.map +0 -1
- package/dist/chunk-SYMZRXI3.js +0 -13
- package/dist/chunk-SYMZRXI3.js.map +0 -1
- package/dist/chunk-UK7OBXGZ.js +0 -33
- package/dist/chunk-UK7OBXGZ.js.map +0 -1
- package/dist/chunk-UVTEJYHN.js +0 -2
- package/dist/chunk-UVTEJYHN.js.map +0 -1
- package/dist/chunk-WG353XMU.js +0 -43
- package/dist/chunk-WG353XMU.js.map +0 -1
- package/dist/verifier-6M7GY4TW.js +0 -2
package/README.md
CHANGED
|
@@ -111,6 +111,8 @@ To integrate LIOP into Claude Desktop, update your `claude_desktop_config.json`
|
|
|
111
111
|
"env": {
|
|
112
112
|
"LIOP_NEXUS_URL": "http://your-nexus-host:3000",
|
|
113
113
|
"LIOP_LOG_LEVEL": "info",
|
|
114
|
+
"LIOP_TOKEN_BANK": "your-secure-bank-token",
|
|
115
|
+
"LIOP_TOKEN_VAULT": "your-secure-vault-token",
|
|
114
116
|
"NODE_OPTIONS": "--use-system-ca"
|
|
115
117
|
}
|
|
116
118
|
}
|
|
@@ -220,27 +222,29 @@ new LiopServer(
|
|
|
220
222
|
capabilities?: Record<string, unknown>;
|
|
221
223
|
workerPool?: {
|
|
222
224
|
enabled?: boolean; // Enable OS-thread sandboxing (default: true)
|
|
225
|
+
minThreads?: number; // Min worker threads (default: CPU count based)
|
|
223
226
|
maxThreads?: number; // Max worker threads (default: CPU count)
|
|
227
|
+
idleTimeout?: number; // Idle timeout in milliseconds for workers
|
|
224
228
|
maxHeapMb?: number; // V8 heap limit per worker (default: 64, env: LIOP_WORKER_MAX_HEAP_MB)
|
|
225
229
|
};
|
|
226
230
|
security?: {
|
|
227
231
|
piiPatterns?: PiiRule[]; // Regex/validator rules for PII detection
|
|
228
232
|
forbiddenKeys?: string[]; // Keys stripped from outgoing responses
|
|
233
|
+
sensitiveKeys?: string[]; // Keys that trigger sensitive query budget
|
|
229
234
|
enableNerScanning?: boolean; // NLP entity detection via compromise (default: false)
|
|
230
|
-
rateLimit?: { // Sliding window rate limiter
|
|
231
|
-
maxPerWindow?: number; // Max calls per window (default: 15)
|
|
232
|
-
|
|
233
|
-
};
|
|
234
|
-
globalRateLimit?: { // Cross-tool aggregate rate limiter
|
|
235
|
-
maxPerWindow?: number; // Max total calls per window (default: 40)
|
|
235
|
+
rateLimit?: { // Sliding window rate limiter configuration
|
|
236
|
+
maxPerWindow?: number; // Max calls per window per tool (default: 15)
|
|
237
|
+
globalMaxPerWindow?: number; // Max total calls across all tools (default: 40)
|
|
236
238
|
windowMs?: number; // Window duration in ms (default: 60000)
|
|
237
239
|
};
|
|
238
240
|
};
|
|
239
241
|
taxonomy?: { // Data domain classification
|
|
240
242
|
domain?: string; // e.g., "finance", "healthcare"
|
|
241
|
-
clearanceTier?:
|
|
243
|
+
clearanceTier?: number; // e.g., 3, 5 (strictly numeric)
|
|
242
244
|
executionTypes?: string[]; // e.g., ["aggregation", "analytics"]
|
|
243
245
|
};
|
|
246
|
+
auth?: LiopAuthConfig; // OAuth 2.1 Hybrid authentication config
|
|
247
|
+
tokenSlug?: string; // Deterministic token resolution slug (e.g., "BANK", "VAULT")
|
|
244
248
|
}
|
|
245
249
|
)
|
|
246
250
|
```
|
|
@@ -300,7 +304,7 @@ await bridge.connect();
|
|
|
300
304
|
│ Layer 2: WASI Sandbox (V8 Isolate) │
|
|
301
305
|
│ 25 poisoned globals (incl. Date, TypedArrays) • │
|
|
302
306
|
│ CPU Fuel limits • 5s timeout • maxHeapMb (64MB default) │
|
|
303
|
-
│ Object.freeze() on
|
|
307
|
+
│ Object.freeze() on 11 core prototypes (strict mode) │
|
|
304
308
|
├───────────────────────────────────────────────────────────┤
|
|
305
309
|
│ Layer 3: Taint Analyzer (IFC — Static) │
|
|
306
310
|
│ Acorn AST 3-pass analysis blocks PII side-channels: │
|
|
@@ -359,6 +363,29 @@ const server = new LiopServer(info, {
|
|
|
359
363
|
|
|
360
364
|
To avoid false positive triggers caused by HMAC-SHA256 ZK-Receipt signatures or transport wrapper frames (such as `{ content: [{ type: "text", text: "..." }] }`), the PII Shield and Aggregation-First engines scan only the unwrapped business data (via `unwrapForAggregationPolicyScan`). Cryptographic seals and protocol routing structures are isolated and excluded from compliance scans.
|
|
361
365
|
|
|
366
|
+
### 📊 3-Tier Query Budget (NIST SP 800-226)
|
|
367
|
+
|
|
368
|
+
To prevent advanced statistical differentiation or database reconstruction attacks, the SDK implements a tiered, session-based budget engine:
|
|
369
|
+
|
|
370
|
+
- **Forbidden Tier** (Limit: `3` queries/session): Applied to highly restricted variables like user IDs, passwords, emails, SSNs (configured via `forbiddenKeys`).
|
|
371
|
+
- **Sensitive Tier** (Limit: `8` queries/session): Applied to moderately sensitive variables like account types, medical diagnoses, blood types, financial tickers (configured via `sensitiveKeys`).
|
|
372
|
+
- **Public Tier** (Limit: `25` queries/session): Default budget for non-sensitive public metadata.
|
|
373
|
+
|
|
374
|
+
If an injected payload queries a field beyond its budget limit, the preflight static analysis immediately blocks execution.
|
|
375
|
+
|
|
376
|
+
### 🛡️ K-Anonymity on Small Datasets
|
|
377
|
+
|
|
378
|
+
When operating on high-privacy datasets, if the source records count is **less than 10**, the SDK forces a strict K-Anonymity restriction:
|
|
379
|
+
- Rejects any output that contains nested objects or arrays.
|
|
380
|
+
- Restricts the returned structure to a maximum of **3 scalar keys** (e.g., simple aggregate counts or statistics).
|
|
381
|
+
- Prevents structural data leakage in low-entropy datasets.
|
|
382
|
+
|
|
383
|
+
### ❄️ Sandbox Poisoned Globals & Date Workaround
|
|
384
|
+
|
|
385
|
+
For maximum host security, the WASI sandbox enforces a poisoned environment that strips dangerous globals and prevents timing side-channels:
|
|
386
|
+
- **Poisoned/Disabled**: `Date` (Date.now, parse, etc. throw an exception to prevent timing analysis), `eval`, `Function`, `setTimeout`, `setInterval`, `Buffer`, `ArrayBuffer`, and all `TypedArrays`.
|
|
387
|
+
- **Date Workaround**: To perform date checks, use lexicographical string comparison on ISO 8601 strings (e.g., `record.date >= "2026-01-01"`).
|
|
388
|
+
|
|
362
389
|
---
|
|
363
390
|
|
|
364
391
|
## Logic-Injection-on-Origin Flow
|
|
@@ -398,7 +425,7 @@ server.enableZeroShotAutonomy(); // Registers the "Blind Analyst" prompt
|
|
|
398
425
|
|
|
399
426
|
Node.js is single-threaded. Heavy operations like Kyber768 decryption, AES-GCM authentication, AST validation, and V8 sandbox instantiation would block the event loop in a standard setup.
|
|
400
427
|
|
|
401
|
-
This SDK dispatches all heavy computation to OS-level threads via [`piscina`](https://github.com/piscinajs/piscina), achieving Rust-like concurrency:
|
|
428
|
+
This SDK dispatches all heavy computation to OS-level threads via [`piscina`](https://github.com/piscinajs/piscina), achieving Rust-like concurrency. On server or verifier initialization, background warmup tasks are automatically dispatched to pre-warm the pool workers, eliminating V8/WASI cold-start overhead (~820k fuel units) for subsequent calls:
|
|
402
429
|
|
|
403
430
|
```typescript
|
|
404
431
|
// Automatic — no configuration needed
|
package/dist/bin/agent.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import {j}from'../chunk-L5A64CNT.js';import'../chunk-2MGFSIXN.js';import {g}from'../chunk-VGXNGTIC.js';import'../chunk-SW53FNSN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-SB5XJXKV.js';import'../chunk-V5MKJT6S.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-DQ6UW6L7.js';import {a}from'../chunk-S6RJHZV2.js';import'../chunk-4C666HHU.js';import*as l from'fs';import*as w from'os';import*as u from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let o=t.endsWith("/health")?t:`${t}/health`,d=await fetch(o,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!d.ok)return null;let e=await d.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(c=>c.includes("/tcp/")&&!c.includes("/ws")&&!c.includes("/ip4/127.0.0.1/"));if(!p)return null;let r=E()?R(p):p;if(!r||r===p){let c=new URL(t).hostname;r=p.replace(/\/ip4\/[^/]+/,`/ip4/${c}`);}return r?(r+=r.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,r):null}catch{return null}}function L(t){let o=t.trim(),d=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(d.test(o)||e.test(o)||p.test(o)){let r="127.0.0.1",c=o.replace(d,`/ip4/${r}`).replace(e,`/ip4/${r}`).replace(p,`/ip4/${r}`);return c!==o&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${c}`),c}return o}function R(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}function D(t){try{let o=new URL(t);return (o.hostname==="127.0.0.1"||o.hostname==="localhost")&&(o.port==="13000"||o.port==="13001")}catch{return false}}function E(){return process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||!!process.env.LIOP_NEXUS_URL&&D(process.env.LIOP_NEXUS_URL)}async function M(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",a=>process.exit(a??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let o=u.join(w.homedir(),".liop"),d=u.join(o,"identity.json");l.existsSync(o)||l.mkdirSync(o,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=u.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let a=l.readFileSync(n,"utf8").trim();a&&e.push(L(a));}}s.push(process.cwd(),u.join(process.cwd(),"tests/infra/nexus-data"),o,u.join(u.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let $=u.join(n,g),v=l.readFileSync($,"utf8").trim();if(v){let S=L(v);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let a$1=L(n);e.includes(a$1)||(e.push(a$1),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${a$1}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let r=new j({name:"@nekzus/liop",version:"1.0.0"});r.enableZeroShotAutonomy();let c=new a$1({identityPath:d,bootstrapNodes:e,addressMapper:E()?R:void 0});await c.start();let f=new g(r,c);f.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
3
3
|
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
4
|
-
`);},setTimeout(()=>{let s=c.getRoutingTableSize?.()||0;a.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${s}`),f
|
|
4
|
+
`);},setTimeout(()=>{let s=c.getRoutingTableSize?.()||0;a.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${s}`),f.refreshManifestCache(true).catch(()=>{});},2e3);let O=1e4,T=12e4,m=O,P=()=>{setTimeout(async()=>{let s=f.getCacheSize();await f.refreshManifestCache(true).catch(()=>{});let n=f.getCacheSize();n!==s?(m=O,a.info(`[LIOP-Agent] Topology change detected (${s} \u2192 ${n}). Resetting poll to ${O/1e3}s.`)):m=Math.min(Math.round(m*1.5),T),P();},m);};P();let I=(await import('readline')).createInterface({input:process.stdin,terminal:false});process.stdout.on("error",s=>{s.code==="EPIPE"&&process.exit(0);}),I.on("line",async s=>{let n=s.trim();if(n)try{let a=JSON.parse(n);if(a.method){let h=await f.dispatch(a);h&&process.stdout.write(`${JSON.stringify(h)}
|
|
5
5
|
`);}}catch{}}),I.on("close",()=>{process.exit(0);}),a.info("[LIOP-Agent] Guarding Claude Desktop via STDIO."),a.info(`[LIOP-Agent] P2P Mesh: Joined (${e.length} bootstraps)`),a.info("[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0"),process.on("SIGINT",async()=>{await c.stop(),process.exit(0);});}M().catch(t=>{a.error(`[LIOP-Agent] Fatal Error: ${t.message}`),process.exit(1);});//# sourceMappingURL=agent.js.map
|
|
6
6
|
//# sourceMappingURL=agent.js.map
|
package/dist/bin/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/agent.ts"],"names":["resolveBootstrapFromUrl","url","healthUrl","response","data","tcpAddr","a","resolved","shouldEnableDockerMap","industrialAddressMapper","urlHost","normalizeBootstrap","addr","trimmed","dockerIpRegex","loopbackRegex","physicalIpRegex","targetIp","normalized","log","isDockerDemoHost","urlStr","u","main","spawn","child","code","buildTime","liopDir","identityPath","bootstrapNodes","args","searchDirs","filePath","dir","multiaddrFiles","f","file","nexusUrl","multiaddr","liopServer","LiopServer","meshNode","MeshNode","router","LiopMcpRouter","rtSize","POLL_BASE_MS","POL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,GAAG,MAAA,CAAQ,MAAOE,CAAAA,EAAS,CAC7B,IAAM1C,CAAAA,CAAU0C,CAAAA,CAAK,IAAA,EAAK,CAC1B,GAAK1C,CAAAA,CAEL,GAAI,CACH,IAAM2C,CAAAA,CAAU,KAAK,KAAA,CAAM3C,CAAO,CAAA,CAClC,GAAI2C,EAAQ,MAAA,CAAQ,CACnB,IAAMrD,CAAAA,CAAW,MAAMyC,IAAO,QAAA,CAASY,CAAO,CAAA,CAC1CrD,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CACD,CAAA,KAAe,CAEf,CACD,CAAC,CAAA,CAEDkD,CAAAA,CAAG,EAAA,CAAG,OAAA,CAAS,IAAM,CACpB,QAAQ,IAAA,CAAK,CAAC,EACf,CAAC,CAAA,CAGDlC,CAAAA,CAAI,IAAA,CAAK,iDAAiD,CAAA,CAC1DA,CAAAA,CAAI,IAAA,CACH,CAAA,+BAAA,EAAkCW,CAAAA,CAAe,MAAM,CAAA,YAAA,CACxD,CAAA,CACAX,EAAI,IAAA,CAAK,+DAA+D,CAAA,CAExE,OAAA,CAAQ,EAAA,CAAG,QAAA,CAAU,SAAY,CAChC,MAAMuB,CAAAA,CAAS,IAAA,EAAK,CACpB,OAAA,CAAQ,IAAA,CAAK,CAAC,EACf,CAAC,EACF,CAEAnB,CAAAA,EAAK,CAAE,KAAA,CAAO+B,CAAAA,EAAQ,CACrBnC,CAAAA,CAAI,MAAM,CAAA,0BAAA,EAA6BmC,CAAAA,CAAI,OAAO,CAAA,CAAE,CAAA,CACpD,OAAA,CAAQ,IAAA,CAAK,CAAC,EACf,CAAC,CAAA","file":"agent.js","sourcesContent":["#!/usr/bin/env node\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { LiopMcpRouter } from \"../gateway/router.js\";\nimport { MeshNode } from \"../mesh/index.js\";\nimport { LiopServer } from \"../server/index.js\";\nimport type { McpRequest } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * Resolves a full libp2p multiaddr (with PeerID) from a LIOP node's\n * HTTP health endpoint. This enables zero-config bootstrap — users\n * only need to provide a URL, not a cryptographic PeerID.\n *\n * @param url - HTTP URL of a LIOP node's health endpoint (e.g. \"http://host:3000\")\n * @returns Full multiaddr string with PeerID, or null if resolution fails\n */\nasync function resolveBootstrapFromUrl(url: string): Promise<string | null> {\n\ttry {\n\t\tconst healthUrl = url.endsWith(\"/health\") ? url : `${url}/health`;\n\t\tconst response = await fetch(healthUrl, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(10000), // Increased to 10s\n\t\t});\n\t\tif (!response.ok) return null;\n\n\t\tconst data = await response.json();\n\t\tif (!data.mesh?.multiaddrs?.length || !data.mesh?.peerId) return null;\n\n\t\t// Find TCP multiaddr (prefer non-websocket for stability)\n\t\tconst tcpAddr = data.mesh.multiaddrs.find(\n\t\t\t(a: string) =>\n\t\t\t\ta.includes(\"/tcp/\") &&\n\t\t\t\t!a.includes(\"/ws\") &&\n\t\t\t\t!a.includes(\"/ip4/127.0.0.1/\"),\n\t\t);\n\t\tif (!tcpAddr) return null;\n\n\t\t// Rewrite internal Docker IP using the address mapper if enabled\n\t\tlet resolved = shouldEnableDockerMap()\n\t\t\t? industrialAddressMapper(tcpAddr)\n\t\t\t: tcpAddr;\n\t\tif (!resolved || resolved === tcpAddr) {\n\t\t\tconst urlHost = new URL(url).hostname;\n\t\t\tresolved = tcpAddr.replace(/\\/ip4\\/[^/]+/, `/ip4/${urlHost}`);\n\t\t}\n\n\t\tif (!resolved) return null;\n\n\t\tresolved += resolved.includes(\"/p2p/\") ? \"\" : `/p2p/${data.mesh.peerId}`;\n\n\t\treturn resolved;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Normalizes a bootstrap multiaddr string.\n * If the address contains a Docker bridge IP (172.16-31.x.x) or Loopback (127.0.0.1),\n * rewrites it to the host accessible via LIOP_NEXUS_URL (e.g. WSL2 IP).\n * This is critical when WSL2 mirror-mode networking is broken.\n */\nfunction normalizeBootstrap(addr: string): string {\n\tconst trimmed = addr.trim();\n\t// Remap Docker bridge IPs and ANY external physical IPs to 127.0.0.1\n\t// because Test-NetConnection confirmed 127.0.0.1 is the only reliable path to Docker ports.\n\tconst dockerIpRegex =\n\t\t/\\/ip4\\/172\\.(1[6-9]|2[0-9]|3[0-1])\\.[0-9]{1,3}\\.[0-9]{1,3}/;\n\tconst loopbackRegex = /\\/ip4\\/127\\.0\\.0\\.1/;\n\tconst physicalIpRegex = /\\/ip4\\/192\\.168\\.[0-9]{1,3}\\.[0-9]{1,3}/;\n\n\tif (\n\t\tdockerIpRegex.test(trimmed) ||\n\t\tloopbackRegex.test(trimmed) ||\n\t\tphysicalIpRegex.test(trimmed)\n\t) {\n\t\tconst targetIp = \"127.0.0.1\";\n\t\tconst normalized = trimmed\n\t\t\t.replace(dockerIpRegex, `/ip4/${targetIp}`)\n\t\t\t.replace(loopbackRegex, `/ip4/${targetIp}`)\n\t\t\t.replace(physicalIpRegex, `/ip4/${targetIp}`);\n\n\t\tif (normalized !== trimmed) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Agent] 🔄 Local Routing Hack → Forced 127.0.0.1: ${normalized}`,\n\t\t\t);\n\t\t}\n\t\treturn normalized;\n\t}\n\n\treturn trimmed;\n}\n\n/**\n * industrialAddressMapper\n *\n * Maps Docker-internal IPs to host-published ports for local demo environments.\n * Activated when any of the following conditions are met:\n * - NODE_ENV is \"development\" or \"test\"\n * - LIOP_DOCKER_MAP=\"true\" or LIOP_DEV_MODE=\"true\" is set\n * - LIOP_NEXUS_URL points to a local Docker demo port (127.0.0.1:13000|13001)\n *\n * Nexus (172.20.0.10) -> 13001\n * Vault (172.20.0.11) -> 13003\n * Bank (172.20.0.12) -> 13004\n * Oracle(172.20.0.13) -> 13005\n */\nfunction industrialAddressMapper(addr: string): string | null {\n\tif (addr.includes(\"/ip4/172.20.0.10\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.10\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13001\",\n\t\t);\n\tif (addr.includes(\"/ip4/172.20.0.11\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.11\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13003\",\n\t\t);\n\tif (addr.includes(\"/ip4/172.20.0.12\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.12\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13004\",\n\t\t);\n\tif (addr.includes(\"/ip4/172.20.0.13\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.13\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13005\",\n\t\t);\n\n\t// Drop container-internal loopbacks to prevent the Host Agent from dialing itself or conflicting ports\n\tif (\n\t\taddr.includes(\"/ip4/127.0.0.1/tcp/4000\") ||\n\t\taddr.includes(\"/ip4/127.0.0.1/tcp/3000\")\n\t) {\n\t\treturn null;\n\t}\n\n\treturn addr;\n}\n\n/**\n * Checks if a URL points to the local Docker demo environment\n * (loopback address on known demo ports).\n */\nfunction isDockerDemoHost(urlStr: string): boolean {\n\ttry {\n\t\tconst u = new URL(urlStr);\n\t\treturn (\n\t\t\t(u.hostname === \"127.0.0.1\" || u.hostname === \"localhost\") &&\n\t\t\t(u.port === \"13000\" || u.port === \"13001\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Determines whether Docker address mapping should be enabled.\n * True when running in development/test mode, when explicitly requested\n * via LIOP_DOCKER_MAP/LIOP_DEV_MODE, or when the Nexus URL points to\n * a local Docker demo port.\n */\nfunction shouldEnableDockerMap(): boolean {\n\treturn (\n\t\tprocess.env.NODE_ENV === \"development\" ||\n\t\tprocess.env.NODE_ENV === \"test\" ||\n\t\tprocess.env.LIOP_DOCKER_MAP === \"true\" ||\n\t\tprocess.env.LIOP_DEV_MODE === \"true\" ||\n\t\t(!!process.env.LIOP_NEXUS_URL &&\n\t\t\tisDockerDemoHost(process.env.LIOP_NEXUS_URL))\n\t);\n}\n\n/**\n * LIOP Agent (Zero-Config CLI)\n *\n * Secure Logic-on-Origin gateway for Claude Desktop.\n * Communicates via STDIO / JSON-RPC.\n *\n * All tool discovery is DYNAMIC via the /liop/manifest/1.0.0 protocol.\n * No hardcoded tools, PeerIDs, or port mappings.\n */\nasync function main() {\n\t// Auto-Relaunch: Ensure system CA certificates are loaded for TLS compatibility.\n\t// Corporate proxies (Cloudflare WARP, Zscaler) inject custom root CAs into the\n\t// OS certificate store. Node.js ignores these by default, causing UNABLE_TO_VERIFY_LEAF_SIGNATURE.\n\t// Pattern: if --use-system-ca is not active, re-spawn with the flag transparently.\n\t// stdio: \"inherit\" ensures Claude Desktop's JSON-RPC pipe is passed through cleanly.\n\tif (\n\t\t(process.platform === \"win32\" || process.platform === \"darwin\") &&\n\t\t!process.execArgv.includes(\"--use-system-ca\") &&\n\t\t!(process.env.NODE_OPTIONS ?? \"\").includes(\"--use-system-ca\")\n\t) {\n\t\tconst { spawn } = await import(\"node:child_process\");\n\t\tconst child = spawn(\n\t\t\tprocess.execPath,\n\t\t\t[\"--use-system-ca\", ...process.argv.slice(1)],\n\t\t\t{ stdio: \"inherit\", env: process.env },\n\t\t);\n\t\tchild.on(\"exit\", (code) => process.exit(code ?? 1));\n\t\tchild.on(\"error\", () => process.exit(1));\n\t\t// Block parent — child handles all I/O from here\n\t\tawait new Promise(() => {});\n\t\treturn;\n\t}\n\n\tconst buildTime = new Date().toISOString();\n\tlog.info(`[LIOP-Agent] 🚀 Version 1.2.0-alpha.9 | Build: ${buildTime}`);\n\n\tconst liopDir = path.join(os.homedir(), \".liop\");\n\tconst identityPath = path.join(liopDir, \"identity.json\");\n\n\tif (!fs.existsSync(liopDir)) {\n\t\tfs.mkdirSync(liopDir, { recursive: true });\n\t}\n\n\t// 1. Determine Bootstrap Nodes (Zero-Config Discovery)\n\tlet bootstrapNodes: string[] = [];\n\n\t// Command line arguments take precedence\n\tconst args = process.argv.slice(2);\n\tif (args.length > 0) {\n\t\tbootstrapNodes = args.filter((a) => a.startsWith(\"/\"));\n\t}\n\n\t// Priority 1: Physical Beacons (Industrial Pattern) - DETERMINISTIC & INSTANT\n\tif (bootstrapNodes.length === 0) {\n\t\tconst searchDirs = [];\n\n\t\t// Priority 1.1: Explicit file from environment variable\n\t\tif (process.env.LIOP_BOOTSTRAP_FILE) {\n\t\t\tlog.warn(\n\t\t\t\t\"LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. \" +\n\t\t\t\t\t\"Use LIOP_NEXUS_URL for Auto-Discovery instead.\",\n\t\t\t);\n\t\t\tconst filePath = path.resolve(process.env.LIOP_BOOTSTRAP_FILE);\n\t\t\tif (fs.existsSync(filePath)) {\n\t\t\t\tconst addr = fs.readFileSync(filePath, \"utf8\").trim();\n\t\t\t\tif (addr) bootstrapNodes.push(normalizeBootstrap(addr));\n\t\t\t}\n\t\t}\n\n\t\t// Priority 1.2: Traditional locations (Scan for all *.multiaddr)\n\t\tsearchDirs.push(\n\t\t\tprocess.cwd(),\n\t\t\tpath.join(process.cwd(), \"tests/infra/nexus-data\"),\n\t\t\tliopDir,\n\t\t\tpath.join(\n\t\t\t\tpath\n\t\t\t\t\t.dirname(new URL(import.meta.url).pathname)\n\t\t\t\t\t.replace(/^\\/([A-Z]:)/, \"$1\"),\n\t\t\t\t\"../../tests/infra/nexus-data\",\n\t\t\t),\n\t\t);\n\n\t\tfor (const dir of searchDirs) {\n\t\t\ttry {\n\t\t\t\tif (fs.existsSync(dir)) {\n\t\t\t\t\tconst files = fs.readdirSync(dir);\n\t\t\t\t\tconst multiaddrFiles = files.filter((f) => f.endsWith(\".multiaddr\"));\n\n\t\t\t\t\tfor (const file of multiaddrFiles) {\n\t\t\t\t\t\tconst filePath = path.join(dir, file);\n\t\t\t\t\t\tconst addr = fs.readFileSync(filePath, \"utf8\").trim();\n\t\t\t\t\t\tif (addr) {\n\t\t\t\t\t\t\tconst normalized = normalizeBootstrap(addr);\n\t\t\t\t\t\t\tif (!bootstrapNodes.includes(normalized)) {\n\t\t\t\t\t\t\t\tbootstrapNodes.push(normalized);\n\t\t\t\t\t\t\t\tlog.info(`[LIOP-Agent] ✅ Loaded beacon: ${file} from ${dir}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we found any beacons in this directory, we consider discovery successful for this layer\n\t\t\t\t\tif (bootstrapNodes.length > 0) break;\n\t\t\t\t}\n\t\t\t} catch (_e) {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t}\n\n\t// Priority 2: Auto-Discovery via NEXUS URL (Aggressive Parallel Discovery)\n\tif (process.env.LIOP_NEXUS_URL) {\n\t\tconst nexusUrl = process.env.LIOP_NEXUS_URL;\n\t\tlog.info(\n\t\t\t`[LIOP-Agent] 🌐 Running parallel discovery from: ${nexusUrl} (Sources Found: ${bootstrapNodes.length})`,\n\t\t);\n\n\t\tconst resolved = await resolveBootstrapFromUrl(nexusUrl);\n\t\tif (resolved) {\n\t\t\tconst normalized = normalizeBootstrap(resolved);\n\t\t\tif (!bootstrapNodes.includes(normalized)) {\n\t\t\t\tbootstrapNodes.push(normalized);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Agent] ✅ Added bootstrap from URL discovery: ${normalized}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Priority 3: Environment variable (direct multiaddr)\n\tif (bootstrapNodes.length === 0 && process.env.LIOP_BOOTSTRAP) {\n\t\tbootstrapNodes.push(process.env.LIOP_BOOTSTRAP.trim());\n\t}\n\n\t// Final fallback: local Nexus bootstrap for demo environments.\n\t// Avoid injecting stale static peer IDs when discovery already found valid peers.\n\tif (bootstrapNodes.length === 0) {\n\t\tbootstrapNodes.push(\n\t\t\t\"/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD\",\n\t\t);\n\t}\n\n\t// Sanitize/validate all candidate multiaddrs so malformed PeerIDs don't crash startup.\n\tbootstrapNodes = bootstrapNodes.filter((addr) => {\n\t\ttry {\n\t\t\tmultiaddr(addr);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\tlog.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${addr}`);\n\t\t\treturn false;\n\t\t}\n\t});\n\n\t// If no bootstrap nodes found, the agent operates in standalone mode.\n\t// It will only serve local tools until peers are discovered.\n\tif (bootstrapNodes.length === 0) {\n\t\tlog.info(\n\t\t\t\"[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode.\",\n\t\t);\n\t\tlog.info(\n\t\t\t\"[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file.\",\n\t\t);\n\t}\n\n\t// Initialize local server node (lightweight, no tools registered locally)\n\tconst liopServer = new LiopServer({\n\t\tname: \"@nekzus/liop\",\n\t\tversion: \"1.0.0\",\n\t});\n\n\t// Enable Zero-Shot Autonomy (Industrial Prompt Injection)\n\tliopServer.enableZeroShotAutonomy();\n\n\t// 2. Mesh Node Configuration\n\tconst meshNode = new MeshNode({\n\t\tidentityPath: identityPath,\n\t\tbootstrapNodes: bootstrapNodes,\n\t\taddressMapper: shouldEnableDockerMap()\n\t\t\t? industrialAddressMapper\n\t\t\t: undefined,\n\t});\n\n\t// Start P2P Mesh\n\tawait meshNode.start();\n\n\t// 3. Initialize the Dynamic Router\n\t// No hardcoded tools — all discovery happens via liop:manifest protocol\n\tconst router = new LiopMcpRouter(liopServer, meshNode);\n\n\t// Proactive Notification to Claude Desktop when tools/resources are discovered dynamically\n\trouter.onToolsChanged = () => {\n\t\tprocess.stdout.write(\n\t\t\t`{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\\n`,\n\t\t);\n\t\tprocess.stdout.write(\n\t\t\t`{\"jsonrpc\":\"2.0\",\"method\":\"notifications/resources/list_changed\"}\\n`,\n\t\t);\n\t};\n\n\t// Initial warming period (2s) then Adaptive Background Discovery\n\t// Polls DHT for new nodes and triggers onToolsChanged when topology shifts.\n\t// Uses exponential backoff to reduce polling load on stable meshes.\n\tsetTimeout(() => {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal for telemetry\n\t\tconst rtSize = (meshNode as any).getRoutingTableSize?.() || 0;\n\t\tlog.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${rtSize}`);\n\t\trouter.refreshManifestCache(true).catch(() => {});\n\t}, 2000);\n\n\tconst POLL_BASE_MS = 10_000;\n\tconst POLL_MAX_MS = 120_000;\n\tlet pollIntervalMs = POLL_BASE_MS;\n\n\tconst scheduleAdaptivePoll = () => {\n\t\tsetTimeout(async () => {\n\t\t\tconst prevSize = router.getCacheSize();\n\t\t\tawait router.refreshManifestCache(true).catch(() => {});\n\t\t\tconst newSize = router.getCacheSize();\n\n\t\t\tif (newSize !== prevSize) {\n\t\t\t\t// Topology changed — reset to aggressive polling\n\t\t\t\tpollIntervalMs = POLL_BASE_MS;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Agent] Topology change detected (${prevSize} → ${newSize}). Resetting poll to ${POLL_BASE_MS / 1000}s.`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Stable — relax polling interval (factor 1.5)\n\t\t\t\tpollIntervalMs = Math.min(\n\t\t\t\t\tMath.round(pollIntervalMs * 1.5),\n\t\t\t\t\tPOLL_MAX_MS,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tscheduleAdaptivePoll();\n\t\t}, pollIntervalMs);\n\t};\n\n\tscheduleAdaptivePoll();\n\n\t// 4. STDIO Transport — Buffered Line Reader\n\t// Uses readline to guarantee complete JSON-RPC messages before parsing.\n\t// Raw stdin.on(\"data\") can fragment large payloads across multiple chunks.\n\tconst readline = await import(\"node:readline\");\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\tterminal: false,\n\t});\n\n\tprocess.stdout.on(\"error\", (err: Error & { code?: string }) => {\n\t\tif (err.code === \"EPIPE\") {\n\t\t\tprocess.exit(0); // Graceful exit when Claude Desktop disconnects\n\t\t}\n\t});\n\n\trl.on(\"line\", async (line) => {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed) return;\n\n\t\ttry {\n\t\t\tconst request = JSON.parse(trimmed) as McpRequest;\n\t\t\tif (request.method) {\n\t\t\t\tconst response = await router.dispatch(request);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (_err) {\n\t\t\t// Silent catch for binary noise or malformed lines\n\t\t}\n\t});\n\n\trl.on(\"close\", () => {\n\t\tprocess.exit(0);\n\t});\n\n\t// Status directed only to stderr\n\tlog.info(`[LIOP-Agent] Guarding Claude Desktop via STDIO.`);\n\tlog.info(\n\t\t`[LIOP-Agent] P2P Mesh: Joined (${bootstrapNodes.length} bootstraps)`,\n\t);\n\tlog.info(\"[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0\");\n\n\tprocess.on(\"SIGINT\", async () => {\n\t\tawait meshNode.stop();\n\t\tprocess.exit(0);\n\t});\n}\n\nmain().catch((err) => {\n\tlog.error(`[LIOP-Agent] Fatal Error: ${err.message}`);\n\tprocess.exit(1);\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/agent.ts"],"names":["resolveBootstrapFromUrl","url","healthUrl","response","data","tcpAddr","a","resolved","shouldEnableDockerMap","industrialAddressMapper","urlHost","normalizeBootstrap","addr","trimmed","dockerIpRegex","loopbackRegex","physicalIpRegex","targetIp","normalized","log","isDockerDemoHost","urlStr","u","main","spawn","child","code","buildTime","liopDir","identityPath","bootstrapNodes","args","searchDirs","filePath","dir","multiaddrFiles","f","file","nexusUrl","multiaddr","liopServer","LiopServer","meshNode","MeshNode","router","LiopMcpRouter","rtSize","POLL_BASE_MS","POLL_MAX_MS","pollIntervalMs","scheduleAdaptivePoll","prevSize","newSize","rl","err","line","request"],"mappings":";ofAmBA,eAAeA,EAAwBC,CAAAA,CAAqC,CAC3E,GAAI,CACH,IAAMC,EAAYD,CAAAA,CAAI,QAAA,CAAS,SAAS,CAAA,CAAIA,CAAAA,CAAM,GAAGA,CAAG,CAAA,OAAA,CAAA,CAClDE,EAAW,MAAM,KAAA,CAAMD,EAAW,CACvC,OAAA,CAAS,CAAE,MAAA,CAAQ,kBAAmB,EACtC,MAAA,CAAQ,WAAA,CAAY,QAAQ,GAAK,CAClC,CAAC,CAAA,CACD,GAAI,CAACC,CAAAA,CAAS,EAAA,CAAI,OAAO,IAAA,CAEzB,IAAMC,EAAO,MAAMD,CAAAA,CAAS,MAAK,CACjC,GAAI,CAACC,CAAAA,CAAK,IAAA,EAAM,YAAY,MAAA,EAAU,CAACA,EAAK,IAAA,EAAM,MAAA,CAAQ,OAAO,IAAA,CAGjE,IAAMC,EAAUD,CAAAA,CAAK,IAAA,CAAK,WAAW,IAAA,CACnCE,CAAAA,EACAA,EAAE,QAAA,CAAS,OAAO,GAClB,CAACA,CAAAA,CAAE,SAAS,KAAK,CAAA,EACjB,CAACA,CAAAA,CAAE,QAAA,CAAS,iBAAiB,CAC/B,CAAA,CACA,GAAI,CAACD,CAAAA,CAAS,OAAO,IAAA,CAGrB,IAAIE,EAAWC,CAAAA,EAAsB,CAClCC,EAAwBJ,CAAO,CAAA,CAC/BA,EACH,GAAI,CAACE,GAAYA,CAAAA,GAAaF,CAAAA,CAAS,CACtC,IAAMK,CAAAA,CAAU,IAAI,GAAA,CAAIT,CAAG,EAAE,QAAA,CAC7BM,CAAAA,CAAWF,EAAQ,OAAA,CAAQ,cAAA,CAAgB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agent.js","sourcesContent":["#!/usr/bin/env node\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { LiopMcpRouter } from \"../gateway/router.js\";\nimport { MeshNode } from \"../mesh/index.js\";\nimport { LiopServer } from \"../server/index.js\";\nimport type { McpRequest } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * Resolves a full libp2p multiaddr (with PeerID) from a LIOP node's\n * HTTP health endpoint. This enables zero-config bootstrap — users\n * only need to provide a URL, not a cryptographic PeerID.\n *\n * @param url - HTTP URL of a LIOP node's health endpoint (e.g. \"http://host:3000\")\n * @returns Full multiaddr string with PeerID, or null if resolution fails\n */\nasync function resolveBootstrapFromUrl(url: string): Promise<string | null> {\n\ttry {\n\t\tconst healthUrl = url.endsWith(\"/health\") ? url : `${url}/health`;\n\t\tconst response = await fetch(healthUrl, {\n\t\t\theaders: { Accept: \"application/json\" },\n\t\t\tsignal: AbortSignal.timeout(10000), // Increased to 10s\n\t\t});\n\t\tif (!response.ok) return null;\n\n\t\tconst data = await response.json();\n\t\tif (!data.mesh?.multiaddrs?.length || !data.mesh?.peerId) return null;\n\n\t\t// Find TCP multiaddr (prefer non-websocket for stability)\n\t\tconst tcpAddr = data.mesh.multiaddrs.find(\n\t\t\t(a: string) =>\n\t\t\t\ta.includes(\"/tcp/\") &&\n\t\t\t\t!a.includes(\"/ws\") &&\n\t\t\t\t!a.includes(\"/ip4/127.0.0.1/\"),\n\t\t);\n\t\tif (!tcpAddr) return null;\n\n\t\t// Rewrite internal Docker IP using the address mapper if enabled\n\t\tlet resolved = shouldEnableDockerMap()\n\t\t\t? industrialAddressMapper(tcpAddr)\n\t\t\t: tcpAddr;\n\t\tif (!resolved || resolved === tcpAddr) {\n\t\t\tconst urlHost = new URL(url).hostname;\n\t\t\tresolved = tcpAddr.replace(/\\/ip4\\/[^/]+/, `/ip4/${urlHost}`);\n\t\t}\n\n\t\tif (!resolved) return null;\n\n\t\tresolved += resolved.includes(\"/p2p/\") ? \"\" : `/p2p/${data.mesh.peerId}`;\n\n\t\treturn resolved;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Normalizes a bootstrap multiaddr string.\n * If the address contains a Docker bridge IP (172.16-31.x.x) or Loopback (127.0.0.1),\n * rewrites it to the host accessible via LIOP_NEXUS_URL (e.g. WSL2 IP).\n * This is critical when WSL2 mirror-mode networking is broken.\n */\nfunction normalizeBootstrap(addr: string): string {\n\tconst trimmed = addr.trim();\n\t// Remap Docker bridge IPs and ANY external physical IPs to 127.0.0.1\n\t// because Test-NetConnection confirmed 127.0.0.1 is the only reliable path to Docker ports.\n\tconst dockerIpRegex =\n\t\t/\\/ip4\\/172\\.(1[6-9]|2[0-9]|3[0-1])\\.[0-9]{1,3}\\.[0-9]{1,3}/;\n\tconst loopbackRegex = /\\/ip4\\/127\\.0\\.0\\.1/;\n\tconst physicalIpRegex = /\\/ip4\\/192\\.168\\.[0-9]{1,3}\\.[0-9]{1,3}/;\n\n\tif (\n\t\tdockerIpRegex.test(trimmed) ||\n\t\tloopbackRegex.test(trimmed) ||\n\t\tphysicalIpRegex.test(trimmed)\n\t) {\n\t\tconst targetIp = \"127.0.0.1\";\n\t\tconst normalized = trimmed\n\t\t\t.replace(dockerIpRegex, `/ip4/${targetIp}`)\n\t\t\t.replace(loopbackRegex, `/ip4/${targetIp}`)\n\t\t\t.replace(physicalIpRegex, `/ip4/${targetIp}`);\n\n\t\tif (normalized !== trimmed) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Agent] 🔄 Local Routing Hack → Forced 127.0.0.1: ${normalized}`,\n\t\t\t);\n\t\t}\n\t\treturn normalized;\n\t}\n\n\treturn trimmed;\n}\n\n/**\n * industrialAddressMapper\n *\n * Maps Docker-internal IPs to host-published ports for local demo environments.\n * Activated when any of the following conditions are met:\n * - NODE_ENV is \"development\" or \"test\"\n * - LIOP_DOCKER_MAP=\"true\" or LIOP_DEV_MODE=\"true\" is set\n * - LIOP_NEXUS_URL points to a local Docker demo port (127.0.0.1:13000|13001)\n *\n * Nexus (172.20.0.10) -> 13001\n * Vault (172.20.0.11) -> 13003\n * Bank (172.20.0.12) -> 13004\n * Oracle(172.20.0.13) -> 13005\n */\nfunction industrialAddressMapper(addr: string): string | null {\n\tif (addr.includes(\"/ip4/172.20.0.10\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.10\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13001\",\n\t\t);\n\tif (addr.includes(\"/ip4/172.20.0.11\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.11\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13003\",\n\t\t);\n\tif (addr.includes(\"/ip4/172.20.0.12\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.12\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13004\",\n\t\t);\n\tif (addr.includes(\"/ip4/172.20.0.13\"))\n\t\treturn addr.replace(\n\t\t\t/\\/ip4\\/172\\.20\\.0\\.13\\/tcp\\/[0-9]+/,\n\t\t\t\"/ip4/127.0.0.1/tcp/13005\",\n\t\t);\n\n\t// Drop container-internal loopbacks to prevent the Host Agent from dialing itself or conflicting ports\n\tif (\n\t\taddr.includes(\"/ip4/127.0.0.1/tcp/4000\") ||\n\t\taddr.includes(\"/ip4/127.0.0.1/tcp/3000\")\n\t) {\n\t\treturn null;\n\t}\n\n\treturn addr;\n}\n\n/**\n * Checks if a URL points to the local Docker demo environment\n * (loopback address on known demo ports).\n */\nfunction isDockerDemoHost(urlStr: string): boolean {\n\ttry {\n\t\tconst u = new URL(urlStr);\n\t\treturn (\n\t\t\t(u.hostname === \"127.0.0.1\" || u.hostname === \"localhost\") &&\n\t\t\t(u.port === \"13000\" || u.port === \"13001\")\n\t\t);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Determines whether Docker address mapping should be enabled.\n * True when running in development/test mode, when explicitly requested\n * via LIOP_DOCKER_MAP/LIOP_DEV_MODE, or when the Nexus URL points to\n * a local Docker demo port.\n */\nfunction shouldEnableDockerMap(): boolean {\n\treturn (\n\t\tprocess.env.NODE_ENV === \"development\" ||\n\t\tprocess.env.NODE_ENV === \"test\" ||\n\t\tprocess.env.LIOP_DOCKER_MAP === \"true\" ||\n\t\tprocess.env.LIOP_DEV_MODE === \"true\" ||\n\t\t(!!process.env.LIOP_NEXUS_URL &&\n\t\t\tisDockerDemoHost(process.env.LIOP_NEXUS_URL))\n\t);\n}\n\n/**\n * LIOP Agent (Zero-Config CLI)\n *\n * Secure Logic-on-Origin gateway for Claude Desktop.\n * Communicates via STDIO / JSON-RPC.\n *\n * All tool discovery is DYNAMIC via the /liop/manifest/1.0.0 protocol.\n * No hardcoded tools, PeerIDs, or port mappings.\n */\nasync function main() {\n\t// Auto-Relaunch: Ensure system CA certificates are loaded for TLS compatibility.\n\t// Corporate proxies (Cloudflare WARP, Zscaler) inject custom root CAs into the\n\t// OS certificate store. Node.js ignores these by default, causing UNABLE_TO_VERIFY_LEAF_SIGNATURE.\n\t// Pattern: if --use-system-ca is not active, re-spawn with the flag transparently.\n\t// stdio: \"inherit\" ensures Claude Desktop's JSON-RPC pipe is passed through cleanly.\n\tif (\n\t\t(process.platform === \"win32\" || process.platform === \"darwin\") &&\n\t\t!process.execArgv.includes(\"--use-system-ca\") &&\n\t\t!(process.env.NODE_OPTIONS ?? \"\").includes(\"--use-system-ca\")\n\t) {\n\t\tconst { spawn } = await import(\"node:child_process\");\n\t\tconst child = spawn(\n\t\t\tprocess.execPath,\n\t\t\t[\"--use-system-ca\", ...process.argv.slice(1)],\n\t\t\t{ stdio: \"inherit\", env: process.env },\n\t\t);\n\t\tchild.on(\"exit\", (code) => process.exit(code ?? 1));\n\t\tchild.on(\"error\", () => process.exit(1));\n\t\t// Block parent — child handles all I/O from here\n\t\tawait new Promise(() => {});\n\t\treturn;\n\t}\n\n\tconst buildTime = new Date().toISOString();\n\tlog.info(`[LIOP-Agent] 🚀 Version 1.2.0-alpha.9 | Build: ${buildTime}`);\n\n\tconst liopDir = path.join(os.homedir(), \".liop\");\n\tconst identityPath = path.join(liopDir, \"identity.json\");\n\n\tif (!fs.existsSync(liopDir)) {\n\t\tfs.mkdirSync(liopDir, { recursive: true });\n\t}\n\n\t// 1. Determine Bootstrap Nodes (Zero-Config Discovery)\n\tlet bootstrapNodes: string[] = [];\n\n\t// Command line arguments take precedence\n\tconst args = process.argv.slice(2);\n\tif (args.length > 0) {\n\t\tbootstrapNodes = args.filter((a) => a.startsWith(\"/\"));\n\t}\n\n\t// Priority 1: Physical Beacons (Industrial Pattern) - DETERMINISTIC & INSTANT\n\tif (bootstrapNodes.length === 0) {\n\t\tconst searchDirs = [];\n\n\t\t// Priority 1.1: Explicit file from environment variable\n\t\tif (process.env.LIOP_BOOTSTRAP_FILE) {\n\t\t\tlog.warn(\n\t\t\t\t\"LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. \" +\n\t\t\t\t\t\"Use LIOP_NEXUS_URL for Auto-Discovery instead.\",\n\t\t\t);\n\t\t\tconst filePath = path.resolve(process.env.LIOP_BOOTSTRAP_FILE);\n\t\t\tif (fs.existsSync(filePath)) {\n\t\t\t\tconst addr = fs.readFileSync(filePath, \"utf8\").trim();\n\t\t\t\tif (addr) bootstrapNodes.push(normalizeBootstrap(addr));\n\t\t\t}\n\t\t}\n\n\t\t// Priority 1.2: Traditional locations (Scan for all *.multiaddr)\n\t\tsearchDirs.push(\n\t\t\tprocess.cwd(),\n\t\t\tpath.join(process.cwd(), \"tests/infra/nexus-data\"),\n\t\t\tliopDir,\n\t\t\tpath.join(\n\t\t\t\tpath\n\t\t\t\t\t.dirname(new URL(import.meta.url).pathname)\n\t\t\t\t\t.replace(/^\\/([A-Z]:)/, \"$1\"),\n\t\t\t\t\"../../tests/infra/nexus-data\",\n\t\t\t),\n\t\t);\n\n\t\tfor (const dir of searchDirs) {\n\t\t\ttry {\n\t\t\t\tif (fs.existsSync(dir)) {\n\t\t\t\t\tconst files = fs.readdirSync(dir);\n\t\t\t\t\tconst multiaddrFiles = files.filter((f) => f.endsWith(\".multiaddr\"));\n\n\t\t\t\t\tfor (const file of multiaddrFiles) {\n\t\t\t\t\t\tconst filePath = path.join(dir, file);\n\t\t\t\t\t\tconst addr = fs.readFileSync(filePath, \"utf8\").trim();\n\t\t\t\t\t\tif (addr) {\n\t\t\t\t\t\t\tconst normalized = normalizeBootstrap(addr);\n\t\t\t\t\t\t\tif (!bootstrapNodes.includes(normalized)) {\n\t\t\t\t\t\t\t\tbootstrapNodes.push(normalized);\n\t\t\t\t\t\t\t\tlog.info(`[LIOP-Agent] ✅ Loaded beacon: ${file} from ${dir}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t// If we found any beacons in this directory, we consider discovery successful for this layer\n\t\t\t\t\tif (bootstrapNodes.length > 0) break;\n\t\t\t\t}\n\t\t\t} catch (_e) {\n\t\t\t\t/* ignore */\n\t\t\t}\n\t\t}\n\t}\n\n\t// Priority 2: Auto-Discovery via NEXUS URL (Aggressive Parallel Discovery)\n\tif (process.env.LIOP_NEXUS_URL) {\n\t\tconst nexusUrl = process.env.LIOP_NEXUS_URL;\n\t\tlog.info(\n\t\t\t`[LIOP-Agent] 🌐 Running parallel discovery from: ${nexusUrl} (Sources Found: ${bootstrapNodes.length})`,\n\t\t);\n\n\t\tconst resolved = await resolveBootstrapFromUrl(nexusUrl);\n\t\tif (resolved) {\n\t\t\tconst normalized = normalizeBootstrap(resolved);\n\t\t\tif (!bootstrapNodes.includes(normalized)) {\n\t\t\t\tbootstrapNodes.push(normalized);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Agent] ✅ Added bootstrap from URL discovery: ${normalized}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Priority 3: Environment variable (direct multiaddr)\n\tif (bootstrapNodes.length === 0 && process.env.LIOP_BOOTSTRAP) {\n\t\tbootstrapNodes.push(process.env.LIOP_BOOTSTRAP.trim());\n\t}\n\n\t// Final fallback: local Nexus bootstrap for demo environments.\n\t// Avoid injecting stale static peer IDs when discovery already found valid peers.\n\tif (bootstrapNodes.length === 0) {\n\t\tbootstrapNodes.push(\n\t\t\t\"/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD\",\n\t\t);\n\t}\n\n\t// Sanitize/validate all candidate multiaddrs so malformed PeerIDs don't crash startup.\n\tbootstrapNodes = bootstrapNodes.filter((addr) => {\n\t\ttry {\n\t\t\tmultiaddr(addr);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\tlog.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${addr}`);\n\t\t\treturn false;\n\t\t}\n\t});\n\n\t// If no bootstrap nodes found, the agent operates in standalone mode.\n\t// It will only serve local tools until peers are discovered.\n\tif (bootstrapNodes.length === 0) {\n\t\tlog.info(\n\t\t\t\"[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode.\",\n\t\t);\n\t\tlog.info(\n\t\t\t\"[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file.\",\n\t\t);\n\t}\n\n\t// Initialize local server node (lightweight, no tools registered locally)\n\tconst liopServer = new LiopServer({\n\t\tname: \"@nekzus/liop\",\n\t\tversion: \"1.0.0\",\n\t});\n\n\t// Enable Zero-Shot Autonomy (Industrial Prompt Injection)\n\tliopServer.enableZeroShotAutonomy();\n\n\t// 2. Mesh Node Configuration\n\tconst meshNode = new MeshNode({\n\t\tidentityPath: identityPath,\n\t\tbootstrapNodes: bootstrapNodes,\n\t\taddressMapper: shouldEnableDockerMap()\n\t\t\t? industrialAddressMapper\n\t\t\t: undefined,\n\t});\n\n\t// Start P2P Mesh\n\tawait meshNode.start();\n\n\t// 3. Initialize the Dynamic Router\n\t// No hardcoded tools — all discovery happens via liop:manifest protocol\n\tconst router = new LiopMcpRouter(liopServer, meshNode);\n\n\t// Proactive Notification to Claude Desktop when tools/resources are discovered dynamically\n\trouter.onToolsChanged = () => {\n\t\tprocess.stdout.write(\n\t\t\t`{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}\\n`,\n\t\t);\n\t\tprocess.stdout.write(\n\t\t\t`{\"jsonrpc\":\"2.0\",\"method\":\"notifications/resources/list_changed\"}\\n`,\n\t\t);\n\t};\n\n\t// Initial warming period (2s) then Adaptive Background Discovery\n\t// Polls DHT for new nodes and triggers onToolsChanged when topology shifts.\n\t// Uses exponential backoff to reduce polling load on stable meshes.\n\tsetTimeout(() => {\n\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal for telemetry\n\t\tconst rtSize = (meshNode as any).getRoutingTableSize?.() || 0;\n\t\tlog.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${rtSize}`);\n\t\trouter.refreshManifestCache(true).catch(() => {});\n\t}, 2000);\n\n\tconst POLL_BASE_MS = 10_000;\n\tconst POLL_MAX_MS = 120_000;\n\tlet pollIntervalMs = POLL_BASE_MS;\n\n\tconst scheduleAdaptivePoll = () => {\n\t\tsetTimeout(async () => {\n\t\t\tconst prevSize = router.getCacheSize();\n\t\t\tawait router.refreshManifestCache(true).catch(() => {});\n\t\t\tconst newSize = router.getCacheSize();\n\n\t\t\tif (newSize !== prevSize) {\n\t\t\t\t// Topology changed — reset to aggressive polling\n\t\t\t\tpollIntervalMs = POLL_BASE_MS;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Agent] Topology change detected (${prevSize} → ${newSize}). Resetting poll to ${POLL_BASE_MS / 1000}s.`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// Stable — relax polling interval (factor 1.5)\n\t\t\t\tpollIntervalMs = Math.min(\n\t\t\t\t\tMath.round(pollIntervalMs * 1.5),\n\t\t\t\t\tPOLL_MAX_MS,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tscheduleAdaptivePoll();\n\t\t}, pollIntervalMs);\n\t};\n\n\tscheduleAdaptivePoll();\n\n\t// 4. STDIO Transport — Buffered Line Reader\n\t// Uses readline to guarantee complete JSON-RPC messages before parsing.\n\t// Raw stdin.on(\"data\") can fragment large payloads across multiple chunks.\n\tconst readline = await import(\"node:readline\");\n\tconst rl = readline.createInterface({\n\t\tinput: process.stdin,\n\t\tterminal: false,\n\t});\n\n\tprocess.stdout.on(\"error\", (err: Error & { code?: string }) => {\n\t\tif (err.code === \"EPIPE\") {\n\t\t\tprocess.exit(0); // Graceful exit when Claude Desktop disconnects\n\t\t}\n\t});\n\n\trl.on(\"line\", async (line) => {\n\t\tconst trimmed = line.trim();\n\t\tif (!trimmed) return;\n\n\t\ttry {\n\t\t\tconst request = JSON.parse(trimmed) as McpRequest;\n\t\t\tif (request.method) {\n\t\t\t\tconst response = await router.dispatch(request);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (_err) {\n\t\t\t// Silent catch for binary noise or malformed lines\n\t\t}\n\t});\n\n\trl.on(\"close\", () => {\n\t\tprocess.exit(0);\n\t});\n\n\t// Status directed only to stderr\n\tlog.info(`[LIOP-Agent] Guarding Claude Desktop via STDIO.`);\n\tlog.info(\n\t\t`[LIOP-Agent] P2P Mesh: Joined (${bootstrapNodes.length} bootstraps)`,\n\t);\n\tlog.info(\"[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0\");\n\n\tprocess.on(\"SIGINT\", async () => {\n\t\tawait meshNode.stop();\n\t\tprocess.exit(0);\n\t});\n}\n\nmain().catch((err) => {\n\tlog.error(`[LIOP-Agent] Fatal Error: ${err.message}`);\n\tprocess.exit(1);\n});\n"]}
|
package/dist/bridge.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
-
import { LiopServer, LiopServerOptions } from './
|
|
2
|
+
import { L as LiopServer, a as LiopServerOptions } from './index-CL8m1L1d.js';
|
|
3
3
|
import 'zod';
|
|
4
4
|
import './mesh.js';
|
|
5
|
-
import './types.js';
|
|
5
|
+
import './types-DzEXgi4s.js';
|
|
6
|
+
import 'jose';
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Configuration options for LiopStreamBridge.
|
|
@@ -98,6 +99,7 @@ declare class LiopMcpBridge {
|
|
|
98
99
|
* Connects the bridge via stdio or Mesh depending on mode.
|
|
99
100
|
*/
|
|
100
101
|
connect(): Promise<void>;
|
|
102
|
+
getServer(): LiopServer | null;
|
|
101
103
|
}
|
|
102
104
|
|
|
103
105
|
export { type LiopBridgeOptions, LiopMcpBridge, LiopStreamBridge, type LiopStreamBridgeOptions };
|
package/dist/bridge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-W2QGWRTT.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=bridge.js.map
|
|
2
2
|
//# sourceMappingURL=bridge.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-S6RJHZV2.js';import*as P from'fs/promises';import*as w from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {bootstrap}from'@libp2p/bootstrap';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var q=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],S="/liop/manifest/1.0.0",O="liop:manifest",E=class b{node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(t={}){this.config={listenAddresses:t.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:t.bootstrapNodes||[],identityPath:t.identityPath,enableWAN:t.enableWAN??false,dhtStoragePath:t.dhtStoragePath,addressMapper:t.addressMapper};}shouldSkipManifestDial(t){let e=this.manifestDialFailureState.get(t);if(!e)return false;let n=Date.now();return n>=e.cooldownUntil?false:(n-e.lastSkipLogAt>b.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Mesh] Skipping manifest dial for ${t} during cooldown (${Math.ceil((e.cooldownUntil-n)/1e3)}s remaining)`),e.lastSkipLogAt=n),true)}recordManifestDialFailure(t){let e=Date.now(),r=(this.manifestDialFailureState.get(t)?.failures||0)+1,o=Math.min(b.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),b.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(t,{failures:r,cooldownUntil:e+o,lastSkipLogAt:0});}clearManifestDialFailure(t){this.manifestDialFailureState.delete(t);}async loadOrCreateIdentity(){try{let{generateKeyPair:t,privateKeyFromProtobuf:e}=await import('@libp2p/crypto/keys'),n=await import('uint8arrays');if(this.config.identityPath){let o=w.resolve(this.config.identityPath);try{let d=await P.readFile(o,"utf-8"),s=JSON.parse(d),l=n.fromString(s.privKey,"base64");try{let a$1=e(l);return a.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a$1,isNew:!1}}catch(a$1){a.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a$1 instanceof Error?a$1.message:String(a$1)}`);}}catch(d){let s=d;s.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Error loading identity: ${s.message}`);}}return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){a.error(`[LIOP-Mesh] Critical error in identity management: ${t}. Falling back to ephemeral identity.`);try{let{generateKeyPair:e}=await import('@libp2p/crypto/keys');return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){throw new Error(`Identity system failure: ${e}`)}}}async saveIdentity(t){if(!(!this.config.identityPath||!this.node))try{let e=w.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),r=await import('uint8arrays'),o=n(t),d=(r.toString||r.default.toString)(o,"base64"),s={id:this.node.peerId.toString(),privKey:d};await P.mkdir(w.dirname(e),{recursive:!0}),await P.writeFile(e,JSON.stringify(s,null,2)),a.info(`[LIOP-Mesh] Identity persisted to ${e}`);}catch(e){a.error(`[LIOP-Mesh] FAILED to persist identity: ${e}`);}}async capabilityToCID(t){let e=await sha256.digest(new TextEncoder().encode(t));return CID.create(1,85,e)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(t=>setTimeout(t,500)),!this.node)return;a.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let t of this.announcedCapabilities)try{let e=await this.capabilityToCID(t);await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Re-announced: ${t}`);}catch(e){a.info(`[LIOP-Mesh] Re-announce failed for ${t}: ${e}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let t=await this.loadOrCreateIdentity();if(!t)throw new Error("Could not initialize P2P Identity");let{privateKey:e,isNew:n}=t;this.localPrivateKey=e;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=q);let o=r.length>0?[bootstrap({list:r})]:void 0,d=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0";if(this.node=await createLibp2p({privateKey:e,addresses:{listen:this.config.listenAddresses},transports:[tcp(),webSockets()],connectionEncrypters:[noise()],streamMuxers:[yamux()],services:{identify:identify(),ping:ping(),dht:kadDHT({protocol:d,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:s=>s})},peerDiscovery:o}),this.node.addEventListener("peer:discovery",s=>{let l=s.detail.id;if(a.info(`[LIOP-Mesh] Discovered peer: ${l.toString()}`),this.node){let a=l;if(this.config.addressMapper&&s.detail.multiaddrs.length>0){let c=s.detail.multiaddrs.map(u=>{let m=this.config.addressMapper(u.toString());return m?multiaddr(m):null}).filter(u=>u!==null).find(u=>u.toString().includes("/tcp/")&&!u.toString().includes("/ws"));c&&(a=c);}this.node.dial(a).catch(()=>{});}}),this.node.addEventListener("peer:connect",s=>{let l=s.detail;if(a.info(`[LIOP-Mesh] Connected to peer: ${l.toString()}`),!this.node)return;let a$1=this.node.services.dht;a$1?.routingTable&&(a.info(`[LIOP-Mesh] Adding ${l.toString()} to DHT Routing Table`),a$1.routingTable.add(l).catch(f=>{a.info(`[LIOP-Mesh] Failed to add peer to routing table: ${f instanceof Error?f.message:String(f)}`);})),this.reannounceAll().catch(f=>{a.info(`[LIOP-Mesh] Re-announce error: ${f instanceof Error?f.message:String(f)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(e),a.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(s=>{a.info(`[LIOP-Mesh] Listening on: ${s.toString()}`);}),r.length>0){a.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let s=5;for(let l of r){let a$1=false,f=1;for(;f<=s&&!a$1;)try{await this.node.dial(multiaddr(l)),a.info(`[LIOP-Mesh] \u2705 Successfully dialed ${l}`),a$1=!0;}catch{let u=Math.min(1e3*2**(f-1),3e3);a.warn(`[LIOP-Mesh] \u26A0\uFE0F Dial attempt ${f}/${s} to ${l} failed. Retrying in ${u/1e3}s...`),f<s?await new Promise(m=>setTimeout(m,u)):a.error(`[LIOP-Mesh] \u274C Could not connect to bootstrap ${l} after ${s} attempts. Continuing...`),f++;}}}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),a.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await P.readFile(t,"utf-8"),n=JSON.parse(e),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let d of n)if(!(!d.id||!d.addresses))try{let s=r(d.id),l=d.addresses.map(f=>multiaddr(f));await this.node.peerStore.save(s,{multiaddrs:l});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(s).catch(()=>{}),o++;}catch{}a.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(t){let e=t;e.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await this.node.peerStore.all(),n=[];for(let r of e)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await P.mkdir(w.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify(n,null,2)),a.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(t){a.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${t}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(O).catch(t=>{a.info(`[LIOP-Mesh] Initial manifest announcement failed: ${t}`);}),this.node.handle(S,async(t,e)=>{let n=t?.stream??t,o=(t?.connection??e)?.remotePeer?.toString()||"unknown";a.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let d=this.manifestProvider?.();if(!d||!n){a.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let s=JSON.stringify(d),l=new TextEncoder().encode(s),a$1=Buffer.alloc(4);a$1.writeUInt32BE(l.length,0);let f=Buffer.concat([a$1,Buffer.from(l)]);a.info(`[LIOP-Mesh] Serving manifest (${f.length} bytes) to ${o} [Tools: ${d.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(f)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(u){a.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${u instanceof Error?u.message:String(u)}`);}}else await pipe([f],n);a.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){a.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(d){a.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${d instanceof Error?d.message:String(d)}`);}}),a.info(`[LIOP-Mesh] Manifest Protocol registered: ${S}`));}registerManifestHandler(t){this.manifestProvider=t,this.node&&this.applyHandlers();}async queryManifest(t){if(!this.node)throw new Error("Mesh Node is not running");if(t===this.node.peerId.toString())return a.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${t}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(t))return null;let e=3;for(let n=1;n<=e;n++)try{let r=null,d=this.node.getConnections().find(h=>h.remotePeer.toString()===t);if(d)r=d.remotePeer;else {let p=(await this.node.peerStore.all()).find(g=>g.id.toString()===t);if(p)r=p.id;else {let{peerIdFromString:g}=await import('@libp2p/peer-id');r=g(t);}}let l=r;if(this.config.addressMapper&&this.node){let h=this.config.addressMapper,p=await this.node.peerStore.get(r);if(p&&p.addresses.length>0){let g=p.addresses.map(y=>{let C=y.multiaddr.toString(),T=h(C);return T?{isCertified:y.isCertified,multiaddr:multiaddr(T)}:null}).filter(y=>y!==null),L=g.find(y=>y.multiaddr.toString().includes("/tcp/")&&!y.multiaddr.toString().includes("/ws"));L&&(l=L.multiaddr,a.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${l.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:g.map(y=>y.multiaddr)});}}let a$1;try{let h=await this.node.dialProtocol(l,S).catch(p=>{throw String(p).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):p});a$1=h.stream||h;}catch(h){if(n===e)return a.info(`[LIOP-Mesh] Dial error for ${t} after ${e} attempts: ${h}`),null;let p=500*2**n;a.info(`[LIOP-Mesh] Dial error for ${t} (Attempt ${n}). Retrying in ${p}ms...`),await new Promise(g=>setTimeout(g,p));continue}let f=a$1.source??(typeof a$1[Symbol.asyncIterator]=="function"?a$1:null);if(!f)throw new Error("Target stream has no AsyncIterable source");let c=[],u=0,m=-1,M,A=new Promise((h,p)=>{M=setTimeout(()=>p(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let h of f){if(!h)continue;let p=typeof h.subarray=="function"?h.subarray():h instanceof Uint8Array?h:new Uint8Array(0),g=Buffer.from(p.buffer,p.byteOffset,p.byteLength);if(g.length>0&&(c.push(g),u+=g.length,m<0&&u>=4&&(m=Buffer.concat(c).readUInt32BE(0)),m>=0&&u>=4+m))break}})(),A]);}catch(h){if(c.length===0)throw h;a.info(`[LIOP-Mesh] Partial manifest read from ${t}: ${h instanceof Error?h.message:String(h)}`);}finally{M&&clearTimeout(M);}let I=Buffer.concat(c);if(I.length<4)throw new Error("Received empty/invalid manifest (too short)");let D=I.readUInt32BE(0),N=I.subarray(4,4+D).toString("utf-8"),$=JSON.parse(N);return a.info(`[LIOP-Mesh] Received manifest from ${t}: ${$.tools.length} tools`),this.clearManifestDialFailure(t),$}catch(r){if(n===e)return this.recordManifestDialFailure(t),a.info(`[LIOP-Mesh] Failed to query manifest from ${t} after ${e} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;a.info(`[LIOP-Mesh] Query error for ${t} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(d=>setTimeout(d,o));}return null}async discoverManifestProviders(){return this.findProviders(O)}async announceManifest(){await this.announceCapability(O);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(t){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(t))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(t=>t.toString())}async announceCapability(t){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(t);try{let e=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Announcing capability: ${t} (CID: ${e.toString()})`),await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Successfully announced capability: ${t}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(e))if(r.id.toString()===n){a.info(`[LIOP-Mesh] Self-verification success: Node is providing ${t}`);break}}catch(e){a.error(`[LIOP-Mesh] Failed to announce capability: ${e}`);}}async findProviders(t){if(!this.node)throw new Error("Mesh Node is not running");let e=[];try{let n=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Querying DHT for ${t} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,d=o>1?1500:3e3;a.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${d}ms (Active connections: ${o})`);let s=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),l=!1;for(;!l;){let a$1=s.next(),f=new Promise(c=>setTimeout(()=>c({timeout:!0}),d));try{let c=await Promise.race([a$1,f]);if(c&&typeof c=="object"&&"timeout"in c){a.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof s.return=="function"&&s.return().catch(()=>{}),l=!0;break}let u=c;if(u.done){l=!0;break}r=!0;let M=u.value.id.toString();a.info(`[LIOP-Mesh] Found provider: ${M}`),e.includes(M)||e.push(M);}catch(c){a.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),l=!0;break}}if(!r){let f=this.node.services.dht?.routingTable?.size||0;a.info(`[LIOP-Mesh] DHT search for ${t} returned zero results (routing table size: ${f})`);}if(this.announcedCapabilities.has(t)){let a$1=this.node.peerId.toString();e.includes(a$1)||(a.info(`[LIOP-Mesh] Including local node (${a$1}) in results for ${t}`),e.push(a$1));}}catch(n){a.info(`[LIOP-Mesh] Error finding providers for ${t}: ${n instanceof Error?n.message:String(n)}`);}return a.info(`[LIOP-Mesh] DHT search for ${t} finished. Found ${e.length} providers.`),e}async resolvePeer(t){if(!this.node)throw new Error("Mesh Node is not running");try{let e=this.node.getConnections();for(let r of e)if(r.remotePeer.toString()===t){let o=r.remoteAddr.toString();return a.info(`[LIOP-Mesh] Resolved peer ${t} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===t&&r.addresses.length>0){let o=r.addresses.map(d=>d.multiaddr.toString());return a.info(`[LIOP-Mesh] Resolved peer ${t} via peerStore: ${o[0]}`),o}a.info(`[LIOP-Mesh] Peer ${t} not found in connections or peerStore`);}catch(e){a.info(`[LIOP-Mesh] Failed to resolve peer ${t}: ${e}`);}return []}};export{E as a};//# sourceMappingURL=chunk-7I6YJS3C.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a}from'./chunk-S6RJHZV2.js';import*as P from'fs/promises';import*as w from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {bootstrap}from'@libp2p/bootstrap';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var q=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],S="/liop/manifest/1.0.0",O="liop:manifest",E=class v{node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(t={}){this.config={listenAddresses:t.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:t.bootstrapNodes||[],identityPath:t.identityPath,enableWAN:t.enableWAN??false,dhtStoragePath:t.dhtStoragePath,addressMapper:t.addressMapper};}shouldSkipManifestDial(t){let e=this.manifestDialFailureState.get(t);if(!e)return false;let n=Date.now();return n>=e.cooldownUntil?false:(n-e.lastSkipLogAt>v.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Mesh] Skipping manifest dial for ${t} during cooldown (${Math.ceil((e.cooldownUntil-n)/1e3)}s remaining)`),e.lastSkipLogAt=n),true)}recordManifestDialFailure(t){let e=Date.now(),r=(this.manifestDialFailureState.get(t)?.failures||0)+1,o=Math.min(v.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),v.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(t,{failures:r,cooldownUntil:e+o,lastSkipLogAt:0});}clearManifestDialFailure(t){this.manifestDialFailureState.delete(t);}async loadOrCreateIdentity(){try{let{generateKeyPair:t,privateKeyFromProtobuf:e}=await import('@libp2p/crypto/keys'),n=await import('uint8arrays');if(this.config.identityPath){let o=w.resolve(this.config.identityPath);try{let d=await P.readFile(o,"utf-8"),s=JSON.parse(d),l=n.fromString(s.privKey,"base64");try{let a$1=e(l);return a.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a$1,isNew:!1}}catch(a$1){a.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a$1 instanceof Error?a$1.message:String(a$1)}`);}}catch(d){let s=d;s.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Error loading identity: ${s.message}`);}}return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){a.error(`[LIOP-Mesh] Critical error in identity management: ${t}. Falling back to ephemeral identity.`);try{let{generateKeyPair:e}=await import('@libp2p/crypto/keys');return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){throw new Error(`Identity system failure: ${e}`)}}}async saveIdentity(t){if(!(!this.config.identityPath||!this.node))try{let e=w.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),r=await import('uint8arrays'),o=n(t),d=(r.toString||r.default.toString)(o,"base64"),s={id:this.node.peerId.toString(),privKey:d};await P.mkdir(w.dirname(e),{recursive:!0}),await P.writeFile(e,JSON.stringify(s,null,2)),a.info(`[LIOP-Mesh] Identity persisted to ${e}`);}catch(e){a.error(`[LIOP-Mesh] FAILED to persist identity: ${e}`);}}async capabilityToCID(t){let e=await sha256.digest(new TextEncoder().encode(t));return CID.create(1,85,e)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(t=>setTimeout(t,500)),!this.node)return;a.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let t of this.announcedCapabilities)try{let e=await this.capabilityToCID(t);await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Re-announced: ${t}`);}catch(e){a.info(`[LIOP-Mesh] Re-announce failed for ${t}: ${e}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let t=await this.loadOrCreateIdentity();if(!t)throw new Error("Could not initialize P2P Identity");let{privateKey:e,isNew:n}=t;this.localPrivateKey=e;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=q);let o=r.length>0?[bootstrap({list:r})]:void 0,d=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0";if(this.node=await createLibp2p({privateKey:e,addresses:{listen:this.config.listenAddresses},transports:[tcp(),webSockets()],connectionEncrypters:[noise()],streamMuxers:[yamux()],services:{identify:identify(),ping:ping(),dht:kadDHT({protocol:d,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:s=>s})},peerDiscovery:o}),this.node.addEventListener("peer:discovery",s=>{let l=s.detail.id;if(a.info(`[LIOP-Mesh] Discovered peer: ${l.toString()}`),this.node){let a=l;if(this.config.addressMapper&&s.detail.multiaddrs.length>0){let c=s.detail.multiaddrs.map(u=>{let m=this.config.addressMapper(u.toString());return m?multiaddr(m):null}).filter(u=>u!==null).find(u=>u.toString().includes("/tcp/")&&!u.toString().includes("/ws"));c&&(a=c);}this.node.dial(a).catch(()=>{});}}),this.node.addEventListener("peer:connect",s=>{let l=s.detail;if(a.info(`[LIOP-Mesh] Connected to peer: ${l.toString()}`),!this.node)return;let a$1=this.node.services.dht;a$1?.routingTable&&(a.info(`[LIOP-Mesh] Adding ${l.toString()} to DHT Routing Table`),a$1.routingTable.add(l).catch(f=>{a.info(`[LIOP-Mesh] Failed to add peer to routing table: ${f instanceof Error?f.message:String(f)}`);})),this.reannounceAll().catch(f=>{a.info(`[LIOP-Mesh] Re-announce error: ${f instanceof Error?f.message:String(f)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(e),a.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(s=>{a.info(`[LIOP-Mesh] Listening on: ${s.toString()}`);}),r.length>0){a.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let s=5;for(let l of r){let a$1=false,f=1;for(;f<=s&&!a$1;)try{await this.node.dial(multiaddr(l)),a.info(`[LIOP-Mesh] \u2705 Successfully dialed ${l}`),a$1=!0;}catch{let u=Math.min(1e3*2**(f-1),3e3);a.warn(`[LIOP-Mesh] \u26A0\uFE0F Dial attempt ${f}/${s} to ${l} failed. Retrying in ${u/1e3}s...`),f<s?await new Promise(m=>setTimeout(m,u)):a.error(`[LIOP-Mesh] \u274C Could not connect to bootstrap ${l} after ${s} attempts. Continuing...`),f++;}}}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),a.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await P.readFile(t,"utf-8"),n=JSON.parse(e),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let d of n)if(!(!d.id||!d.addresses))try{let s=r(d.id),l=d.addresses.map(f=>multiaddr(f));await this.node.peerStore.save(s,{multiaddrs:l});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(s).catch(()=>{}),o++;}catch{}a.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(t){let e=t;e.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await this.node.peerStore.all(),n=[];for(let r of e)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await P.mkdir(w.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify(n,null,2)),a.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(t){a.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${t}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(O).catch(t=>{a.info(`[LIOP-Mesh] Initial manifest announcement failed: ${t}`);}),this.node.handle(S,async(t,e)=>{let n=t?.stream??t,o=(t?.connection??e)?.remotePeer?.toString()||"unknown";a.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let d=this.manifestProvider?.();if(!d||!n){a.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let s=JSON.stringify(d),l=new TextEncoder().encode(s),a$1=Buffer.alloc(4);a$1.writeUInt32BE(l.length,0);let f=Buffer.concat([a$1,Buffer.from(l)]);a.info(`[LIOP-Mesh] Serving manifest (${f.length} bytes) to ${o} [Tools: ${d.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(f)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(u){a.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${u instanceof Error?u.message:String(u)}`);}}else await pipe([f],n);a.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){a.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(d){a.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${d instanceof Error?d.message:String(d)}`);}}),a.info(`[LIOP-Mesh] Manifest Protocol registered: ${S}`));}registerManifestHandler(t){this.manifestProvider=t,this.node&&this.applyHandlers();}async queryManifest(t){if(!this.node)throw new Error("Mesh Node is not running");if(t===this.node.peerId.toString())return a.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${t}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(t))return null;let e=3;for(let n=1;n<=e;n++)try{let r=null,d=this.node.getConnections().find(h=>h.remotePeer.toString()===t);if(d)r=d.remotePeer;else {let p=(await this.node.peerStore.all()).find(g=>g.id.toString()===t);if(p)r=p.id;else {let{peerIdFromString:g}=await import('@libp2p/peer-id');r=g(t);}}let l=r;if(this.config.addressMapper&&this.node){let h=this.config.addressMapper,p=await this.node.peerStore.get(r);if(p&&p.addresses.length>0){let g=p.addresses.map(y=>{let C=y.multiaddr.toString(),T=h(C);return T?{isCertified:y.isCertified,multiaddr:multiaddr(T)}:null}).filter(y=>y!==null),L=g.find(y=>y.multiaddr.toString().includes("/tcp/")&&!y.multiaddr.toString().includes("/ws"));L&&(l=L.multiaddr,a.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${l.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:g.map(y=>y.multiaddr)});}}let a$1;try{let h=await this.node.dialProtocol(l,S).catch(p=>{throw String(p).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):p});a$1=h.stream||h;}catch(h){if(n===e)return a.info(`[LIOP-Mesh] Dial error for ${t} after ${e} attempts: ${h}`),null;let p=500*2**n;a.info(`[LIOP-Mesh] Dial error for ${t} (Attempt ${n}). Retrying in ${p}ms...`),await new Promise(g=>setTimeout(g,p));continue}let f=a$1.source??(typeof a$1[Symbol.asyncIterator]=="function"?a$1:null);if(!f)throw new Error("Target stream has no AsyncIterable source");let c=[],u=0,m=-1,M,A=new Promise((h,p)=>{M=setTimeout(()=>p(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let h of f){if(!h)continue;let p=typeof h.subarray=="function"?h.subarray():h instanceof Uint8Array?h:new Uint8Array(0),g=Buffer.from(p.buffer,p.byteOffset,p.byteLength);if(g.length>0&&(c.push(g),u+=g.length,m<0&&u>=4&&(m=Buffer.concat(c).readUInt32BE(0)),m>=0&&u>=4+m))break}})(),A]);}catch(h){if(c.length===0)throw h;a.info(`[LIOP-Mesh] Partial manifest read from ${t}: ${h instanceof Error?h.message:String(h)}`);}finally{M&&clearTimeout(M);}let I=Buffer.concat(c);if(I.length<4)throw new Error("Received empty/invalid manifest (too short)");let D=I.readUInt32BE(0),N=I.subarray(4,4+D).toString("utf-8"),$=JSON.parse(N);return a.info(`[LIOP-Mesh] Received manifest from ${t}: ${$.tools.length} tools`),this.clearManifestDialFailure(t),$}catch(r){if(n===e)return this.recordManifestDialFailure(t),a.info(`[LIOP-Mesh] Failed to query manifest from ${t} after ${e} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;a.info(`[LIOP-Mesh] Query error for ${t} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(d=>setTimeout(d,o));}return null}async discoverManifestProviders(){return this.findProviders(O)}async announceManifest(){await this.announceCapability(O);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(t){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(t))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(t=>t.toString())}async announceCapability(t){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(t);try{let e=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Announcing capability: ${t} (CID: ${e.toString()})`),await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Successfully announced capability: ${t}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(e))if(r.id.toString()===n){a.info(`[LIOP-Mesh] Self-verification success: Node is providing ${t}`);break}}catch(e){a.error(`[LIOP-Mesh] Failed to announce capability: ${e}`);}}async findProviders(t){if(!this.node)throw new Error("Mesh Node is not running");let e=[];try{let n=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Querying DHT for ${t} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,d=o>1?1500:3e3;a.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${d}ms (Active connections: ${o})`);let s=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),l=!1;for(;!l;){let a$1=s.next(),f=new Promise(c=>setTimeout(()=>c({timeout:!0}),d));try{let c=await Promise.race([a$1,f]);if(c&&typeof c=="object"&&"timeout"in c){a.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof s.return=="function"&&s.return().catch(()=>{}),l=!0;break}let u=c;if(u.done){l=!0;break}r=!0;let M=u.value.id.toString();a.info(`[LIOP-Mesh] Found provider: ${M}`),e.includes(M)||e.push(M);}catch(c){a.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),l=!0;break}}if(!r){let f=this.node.services.dht?.routingTable?.size||0;a.info(`[LIOP-Mesh] DHT search for ${t} returned zero results (routing table size: ${f})`);}if(this.announcedCapabilities.has(t)){let a$1=this.node.peerId.toString();e.includes(a$1)||(a.info(`[LIOP-Mesh] Including local node (${a$1}) in results for ${t}`),e.push(a$1));}}catch(n){a.info(`[LIOP-Mesh] Error finding providers for ${t}: ${n instanceof Error?n.message:String(n)}`);}return a.info(`[LIOP-Mesh] DHT search for ${t} finished. Found ${e.length} providers.`),e}async resolvePeer(t){if(!this.node)throw new Error("Mesh Node is not running");try{let e=this.node.getConnections();for(let r of e)if(r.remotePeer.toString()===t){let o=r.remoteAddr.toString();return a.info(`[LIOP-Mesh] Resolved peer ${t} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===t&&r.addresses.length>0){let o=r.addresses.map(d=>d.multiaddr.toString());return a.info(`[LIOP-Mesh] Resolved peer ${t} via peerStore: ${o[0]}`),o}a.info(`[LIOP-Mesh] Peer ${t} not found in connections or peerStore`);}catch(e){a.info(`[LIOP-Mesh] Failed to resolve peer ${t}: ${e}`);}return []}};export{E as a};//# sourceMappingURL=chunk-DQ6UW6L7.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-DQ6UW6L7.js.map
|
|
@@ -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":"glBA2DA,IAAMA,EAA0B,CAC/B,iFAAA,CACA,iFAAA,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AWA,EAAE,SAAA,CAAU,QAAA,EAAU,CAAA,CACnE,OAAA1D,CAAAA,CAAI,IAAA,CACH,CAAA,0BAAA,EAA6BH,CAAS,mBAAmB4D,CAAAA,CAAM,CAAC,CAAC,CAAA,CAClE,CAAA,CACOA,CACR,CAGDzD,CAAAA,CAAI,IAAA,CACH,CAAA,iBAAA,EAAoBH,CAAS,CAAA,sCAAA,CAC9B,EACD,OAASe,CAAAA,CAAO,CACfZ,EAAI,IAAA,CAAK,CAAA,mCAAA,EAAsCH,CAAS,CAAA,EAAA,EAAKe,CAAK,CAAA,CAAE,EACrE,CACA,OAAO,EACR,CACD","file":"chunk-DQ6UW6L7.js","sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport { noise } from \"@chainsafe/libp2p-noise\";\nimport { yamux } from \"@chainsafe/libp2p-yamux\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { kadDHT } from \"@libp2p/kad-dht\";\nimport { ping } from \"@libp2p/ping\";\nimport { tcp } from \"@libp2p/tcp\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { pipe } from \"it-pipe\";\nimport type { Libp2p } from \"libp2p\";\nimport { createLibp2p } from \"libp2p\";\nimport { CID } from \"multiformats/cid\";\nimport { sha256 } from \"multiformats/hashes/sha2\";\nimport { log } from \"../utils/logger.js\";\n// import { pEvent } from \"p-event\"; // Disabled to avoid ESM conflicts in tests\n\n/**\n * Manifest describing a node's capabilities in the LIOP Mesh.\n * Exchanged via the /liop/manifest/1.0.0 protocol stream.\n */\nexport interface LiopManifest {\n\tpeerId: string;\n\tgrpcPort: number;\n\ttools: Array<{\n\t\tname: string;\n\t\tdescription?: string;\n\t\tinputSchema?: Record<string, unknown>;\n\t}>;\n\tresources: Array<{\n\t\tname: string;\n\t\turi: string;\n\t\tdescription?: string;\n\t\tmimeType?: string;\n\t\ttext?: string;\n\t}>;\n\tserverInfo: { name: string; version: string };\n\ttaxonomy?: {\n\t\tdomain: string;\n\t\tclearanceTier: number;\n\t\texecutionTypes: string[];\n\t};\n\tauthRequired?: boolean;\n\t/** Canonical slug for deterministic token resolution. Agents resolve LIOP_TOKEN_<tokenSlug>. Must match /^[A-Z][A-Z0-9_]*$/. */\n\ttokenSlug?: string;\n}\n\nexport interface MeshNodeConfig {\n\tlistenAddresses?: string[];\n\tbootstrapNodes?: string[];\n\tidentityPath?: string;\n\tenableWAN?: boolean;\n\tdhtStoragePath?: string;\n\t/** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */\n\taddressMapper?: (addr: string) => string | null;\n}\n\nconst DEFAULT_BOOTSTRAP_NODES = [\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt\",\n];\n\nconst LIOP_MANIFEST_PROTOCOL = \"/liop/manifest/1.0.0\";\nconst LIOP_MANIFEST_CAPABILITY = \"liop:manifest\";\n\n/**\n * P2P Mesh Node backed by libp2p + Kademlia DHT.\n *\n * Provides capability advertisement via CID-based content routing\n * and decentralized peer discovery.\n */\nexport class MeshNode {\n\tprivate node: Libp2p | null = null;\n\tprivate config: MeshNodeConfig;\n\tprivate manifestDialFailureState: Map<\n\t\tstring,\n\t\t{ failures: number; cooldownUntil: number; lastSkipLogAt: number }\n\t> = new Map();\n\tprivate static readonly MANIFEST_DIAL_BASE_COOLDOWN_MS = 10_000;\n\tprivate static readonly MANIFEST_DIAL_MAX_COOLDOWN_MS = 2 * 60_000;\n\tprivate static readonly MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS = 30_000;\n\n\t/**\n\t * Buffer of capability hashes that have been announced.\n\t * Used to re-announce capabilities when new peers connect\n\t * (critical for small / isolated clusters where the initial\n\t * provide() finds zero peers in the routing table).\n\t */\n\tprivate announcedCapabilities: Set<string> = new Set();\n\n\t/** Guards against concurrent re-announcement storms. */\n\tprivate reannouncing = false;\n\n\t/** Callback that returns the local node's manifest on request. */\n\tprivate manifestProvider: (() => LiopManifest) | null = null;\n\n\t/** Flag to ensure the manifest protocol is only registered once. */\n\tprivate manifestProtocolRegistered = false;\n\n\t/** Local Ed25519 Private Key for protocol signatures */\n\t// biome-ignore lint/suspicious/noExplicitAny: libp2p keys type\n\tprivate localPrivateKey: any | null = null;\n\n\tconstructor(config: MeshNodeConfig = {}) {\n\t\tthis.config = {\n\t\t\tlistenAddresses: config.listenAddresses || [\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0/ws\",\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0\",\n\t\t\t],\n\t\t\tbootstrapNodes: config.bootstrapNodes || [],\n\t\t\tidentityPath: config.identityPath,\n\t\t\tenableWAN: config.enableWAN ?? false,\n\t\t\tdhtStoragePath: config.dhtStoragePath,\n\t\t\taddressMapper: config.addressMapper,\n\t\t};\n\t}\n\n\tprivate shouldSkipManifestDial(peerIdStr: string): boolean {\n\t\tconst state = this.manifestDialFailureState.get(peerIdStr);\n\t\tif (!state) return false;\n\t\tconst now = Date.now();\n\t\tif (now >= state.cooldownUntil) return false;\n\t\tif (\n\t\t\tnow - state.lastSkipLogAt >\n\t\t\tMeshNode.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS\n\t\t) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Skipping manifest dial for ${peerIdStr} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1000)}s remaining)`,\n\t\t\t);\n\t\t\tstate.lastSkipLogAt = now;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate recordManifestDialFailure(peerIdStr: string): void {\n\t\tconst now = Date.now();\n\t\tconst prev = this.manifestDialFailureState.get(peerIdStr);\n\t\tconst failures = (prev?.failures || 0) + 1;\n\t\tconst backoff = Math.min(\n\t\t\tMeshNode.MANIFEST_DIAL_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),\n\t\t\tMeshNode.MANIFEST_DIAL_MAX_COOLDOWN_MS,\n\t\t);\n\t\tthis.manifestDialFailureState.set(peerIdStr, {\n\t\t\tfailures,\n\t\t\tcooldownUntil: now + backoff,\n\t\t\tlastSkipLogAt: 0,\n\t\t});\n\t}\n\n\tprivate clearManifestDialFailure(peerIdStr: string): void {\n\t\tthis.manifestDialFailureState.delete(peerIdStr);\n\t}\n\n\t/**\n\t * Loads a persistent identity from disk or generates a new Ed25519 keypair.\n\t * Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).\n\t */\n\tprivate async loadOrCreateIdentity() {\n\t\ttry {\n\t\t\tconst { generateKeyPair, privateKeyFromProtobuf } = (await import(\n\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\t)) as any;\n\t\t\t// @ts-expect-error: libp2p ESM dynamic import type conflict\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\tconst uint8arrays = (await import(\"uint8arrays\")) as any;\n\n\t\t\tif (this.config.identityPath) {\n\t\t\t\tconst absolutePath = path.resolve(this.config.identityPath);\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await fs.readFile(absolutePath, \"utf-8\");\n\t\t\t\t\tconst json = JSON.parse(data);\n\t\t\t\t\tconst protobufBytes = uint8arrays.fromString(json.privKey, \"base64\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst privateKey = privateKeyFromProtobuf(protobufBytes);\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Loaded persistent identity from ${absolutePath}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { privateKey, isNew: false };\n\t\t\t\t\t} catch (parseError: unknown) {\n\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Persistent identity at ${absolutePath} is invalid or corrupt. Generating new one. Error: ${\n\t\t\t\t\t\t\t\tparseError instanceof Error\n\t\t\t\t\t\t\t\t\t? parseError.message\n\t\t\t\t\t\t\t\t\t: String(parseError)\n\t\t\t\t\t\t\t}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Fall through to generate new key\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tconst e = error as Error & { code?: string };\n\t\t\t\t\tif (e.code !== \"ENOENT\") {\n\t\t\t\t\t\tlog.error(`[LIOP-Mesh] Error loading identity: ${e.message}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst privateKey = await generateKeyPair(\"Ed25519\");\n\t\t\treturn { privateKey, isNew: true };\n\t\t} catch (error) {\n\t\t\tlog.error(\n\t\t\t\t`[LIOP-Mesh] Critical error in identity management: ${error}. Falling back to ephemeral identity.`,\n\t\t\t);\n\n\t\t\t// EPOCH FALLBACK: In extreme cases (corrupt env), use a volatile in-memory identity\n\t\t\t// to allow the node to start and serve traffic.\n\t\t\ttry {\n\t\t\t\tconst { generateKeyPair } = (await import(\n\t\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p ESM dynamic import type workaround\n\t\t\t\t)) as any;\n\t\t\t\tconst ephemeralKey = await generateKeyPair(\"Ed25519\");\n\t\t\t\treturn { privateKey: ephemeralKey, isNew: true };\n\t\t\t} catch (fallbackError) {\n\t\t\t\tthrow new Error(`Identity system failure: ${fallbackError}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Persists the private key to disk using protobuf serialization (libp2p v3.x).\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: Libp2p private key type is complex for Alpha\n\tprivate async saveIdentity(privateKey: any) {\n\t\tif (!this.config.identityPath || !this.node) return;\n\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.identityPath);\n\t\t\tconst { privateKeyToProtobuf } = (await import(\n\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\t)) as any;\n\t\t\t// @ts-expect-error: libp2p ESM dynamic import type conflict\n\t\t\tconst uint8arrays = await import(\"uint8arrays\");\n\n\t\t\tconst protobufBytes = privateKeyToProtobuf(privateKey);\n\t\t\tconst privKeyEncoded = (\n\t\t\t\tuint8arrays.toString || uint8arrays.default.toString\n\t\t\t)(protobufBytes, \"base64\");\n\n\t\t\tconst json = {\n\t\t\t\tid: this.node.peerId.toString(),\n\t\t\t\tprivKey: privKeyEncoded,\n\t\t\t};\n\n\t\t\tawait fs.mkdir(path.dirname(absolutePath), { recursive: true });\n\t\t\tawait fs.writeFile(absolutePath, JSON.stringify(json, null, 2));\n\t\t\tlog.info(`[LIOP-Mesh] Identity persisted to ${absolutePath}`);\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] FAILED to persist identity: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.\n\t * Required by @libp2p/kad-dht v16+ for provide/findProviders.\n\t */\n\tprivate async capabilityToCID(capability: string): Promise<CID> {\n\t\tconst hash = await sha256.digest(new TextEncoder().encode(capability));\n\t\treturn CID.create(1, 0x55, hash);\n\t}\n\n\t/**\n\t * Re-announces all buffered capabilities after a new peer connects.\n\t * Uses a small delay to allow the DHT protocol handshake to complete.\n\t */\n\tprivate async reannounceAll(): Promise<void> {\n\t\tif (\n\t\t\tthis.reannouncing ||\n\t\t\t!this.node ||\n\t\t\tthis.announcedCapabilities.size === 0\n\t\t)\n\t\t\treturn;\n\n\t\tthis.reannouncing = true;\n\t\ttry {\n\t\t\t// Wait for the DHT protocol handshake to settle\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\n\t\t\tif (!this.node) return;\n\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`,\n\t\t\t);\n\n\t\t\tfor (const hash of this.announcedCapabilities) {\n\t\t\t\ttry {\n\t\t\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\t\t\tawait this.node.contentRouting.provide(cid);\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Re-announced: ${hash}`);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Re-announce failed for ${hash}: ${_e}`);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.reannouncing = false;\n\t\t}\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.node) return;\n\t\tconst result = await this.loadOrCreateIdentity();\n\t\tif (!result) throw new Error(\"Could not initialize P2P Identity\");\n\n\t\tconst { privateKey, isNew } = result;\n\t\tthis.localPrivateKey = privateKey;\n\n\t\tlet bootNodes = this.config.bootstrapNodes || [];\n\t\tif (bootNodes.length === 0 && this.config.enableWAN) {\n\t\t\tbootNodes = DEFAULT_BOOTSTRAP_NODES;\n\t\t}\n\n\t\tconst discovery =\n\t\t\tbootNodes.length > 0\n\t\t\t\t? [\n\t\t\t\t\t\tbootstrap({\n\t\t\t\t\t\t\tlist: bootNodes,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]\n\t\t\t\t: undefined;\n\n\t\tconst dhtProtocol = this.config.enableWAN\n\t\t\t? \"/ipfs/kad/1.0.0\"\n\t\t\t: \"/ipfs/lan/kad/1.0.0\";\n\n\t\tthis.node = await createLibp2p({\n\t\t\tprivateKey,\n\t\t\taddresses: {\n\t\t\t\tlisten: this.config.listenAddresses,\n\t\t\t},\n\t\t\ttransports: [tcp(), webSockets()],\n\t\t\tconnectionEncrypters: [noise()],\n\t\t\tstreamMuxers: [yamux()],\n\t\t\tservices: {\n\t\t\t\tidentify: identify(),\n\t\t\t\tping: ping(),\n\t\t\t\tdht: kadDHT({\n\t\t\t\t\tprotocol: dhtProtocol,\n\t\t\t\t\tclientMode: false,\n\t\t\t\t\t// Allow local/private IPs in the DHT routing table for development/testing\n\t\t\t\t\tallowQueryWithZeroPeers: true,\n\t\t\t\t\t// By default kadDHT drops local IP addresses. Override the mapper to keep them.\n\t\t\t\t\tpeerInfoMapper: (peer) => peer,\n\t\t\t\t}),\n\t\t\t},\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p discovery type mismatch\n\t\t\tpeerDiscovery: discovery as any,\n\t\t});\n\n\t\t// Monitor Connectivity Events\n\t\tthis.node.addEventListener(\"peer:discovery\", (evt) => {\n\t\t\tconst peerId = evt.detail.id;\n\t\t\tlog.info(`[LIOP-Mesh] Discovered peer: ${peerId.toString()}`);\n\t\t\t// [Phase 104] Auto-dial discovered peers to bypass DHT propagation latency\n\t\t\tif (this.node) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: target polymorphic type\n\t\t\t\tlet dialTarget: any = peerId;\n\n\t\t\t\t// Apply port translation if necessary (Docker -> Windows Host)\n\t\t\t\tif (this.config.addressMapper && evt.detail.multiaddrs.length > 0) {\n\t\t\t\t\tconst translated = evt.detail.multiaddrs\n\t\t\t\t\t\t.map((ma) => {\n\t\t\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: mapped conditionally\n\t\t\t\t\t\t\tconst mapped = this.config.addressMapper!(ma.toString());\n\t\t\t\t\t\t\treturn mapped ? multiaddr(mapped) : null;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter((t): t is NonNullable<typeof t> => t !== null);\n\n\t\t\t\t\tconst directTCP = translated.find(\n\t\t\t\t\t\t(ma) =>\n\t\t\t\t\t\t\tma.toString().includes(\"/tcp/\") && !ma.toString().includes(\"/ws\"),\n\t\t\t\t\t);\n\t\t\t\t\tif (directTCP) dialTarget = directTCP;\n\t\t\t\t}\n\n\t\t\t\tthis.node.dial(dialTarget).catch(() => {});\n\t\t\t}\n\t\t});\n\n\t\tthis.node.addEventListener(\"peer:connect\", (evt) => {\n\t\t\tconst peerId = evt.detail;\n\t\t\tlog.info(`[LIOP-Mesh] Connected to peer: ${peerId.toString()}`);\n\n\t\t\tif (!this.node) return;\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal services\n\t\t\tconst dht = (this.node.services as any).dht;\n\t\t\tif (dht?.routingTable) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Adding ${peerId.toString()} to DHT Routing Table`,\n\t\t\t\t);\n\t\t\t\tdht.routingTable.add(peerId).catch((err: unknown) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Failed to add peer to routing table: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Trigger reactive re-announcement of all capabilities\n\t\t\t// so that ADD_PROVIDER messages reach the new peer\n\t\t\tthis.reannounceAll().catch((err: unknown) => {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Re-announce error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t});\n\n\t\tawait this.node.start();\n\n\t\t// Load persisted DHT routing table to enable rapid cold-start reconnections\n\t\tawait this.loadRoutingTable();\n\n\t\t// [LIOP-ALPHA] Protocols and services setup\n\t\tthis.applyHandlers();\n\n\t\tif (isNew && this.config.identityPath) {\n\t\t\tawait this.saveIdentity(privateKey);\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`,\n\t\t);\n\t\tthis.node.getMultiaddrs().forEach((addr) => {\n\t\t\tlog.info(`[LIOP-Mesh] Listening on: ${addr.toString()}`);\n\t\t});\n\n\t\t// Force explicit dialing of Bootstrap nodes with bounded backoff\n\t\tif (bootNodes.length > 0) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Forcing direct P2P dial to ${bootNodes.length} bootstrap nodes...`,\n\t\t\t);\n\n\t\t\tconst maxRetries = 5;\n\t\t\tfor (const addr of bootNodes) {\n\t\t\t\tlet success = false;\n\t\t\t\tlet attempt = 1;\n\n\t\t\t\twhile (attempt <= maxRetries && !success) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.node.dial(multiaddr(addr));\n\t\t\t\t\t\tlog.info(`[LIOP-Mesh] ✅ Successfully dialed ${addr}`);\n\t\t\t\t\t\tsuccess = true;\n\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\tconst delay = Math.min(1000 * 2 ** (attempt - 1), 3000);\n\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t`[LIOP-Mesh] ⚠️ Dial attempt ${attempt}/${maxRetries} to ${addr} failed. Retrying in ${delay / 1000}s...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (attempt < maxRetries) {\n\t\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t\t`[LIOP-Mesh] ❌ Could not connect to bootstrap ${addr} after ${maxRetries} attempts. Continuing...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tattempt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (this.node) {\n\t\t\tawait this.saveRoutingTable();\n\t\t\tawait this.node.stop();\n\t\t\tlog.info(\"[LIOP-Mesh] Node stopped\");\n\t\t}\n\t}\n\n\tprivate async loadRoutingTable() {\n\t\tif (!this.config.dhtStoragePath || !this.node) return;\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.dhtStoragePath);\n\t\t\tconst data = await fs.readFile(absolutePath, \"utf-8\");\n\t\t\tconst peers = JSON.parse(data);\n\t\t\tconst { peerIdFromString } = await import(\"@libp2p/peer-id\");\n\n\t\t\tlet loadedCount = 0;\n\t\t\tfor (const peer of peers) {\n\t\t\t\tif (!peer.id || !peer.addresses) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst peerId = peerIdFromString(peer.id);\n\t\t\t\t\tconst addrs = peer.addresses.map((a: string) => multiaddr(a));\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: bypass libp2p version-drift type mismatch on PeerId\n\t\t\t\t\tawait this.node.peerStore.save(peerId as any, { multiaddrs: addrs });\n\n\t\t\t\t\t// Pre-seed DHT routing table\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal service access\n\t\t\t\t\tconst dht = (this.node.services as any).dht;\n\t\t\t\t\tif (dht?.routingTable) {\n\t\t\t\t\t\tdht.routingTable.add(peerId).catch(() => {});\n\t\t\t\t\t}\n\t\t\t\t\tloadedCount++;\n\t\t\t\t} catch (_e) {}\n\t\t\t}\n\t\t\tlog.info(`[LIOP-Mesh] Loaded ${loadedCount} peers from DHT storage`);\n\t\t} catch (error: unknown) {\n\t\t\tconst e = error as Error & { code?: string };\n\t\t\tif (e.code !== \"ENOENT\") {\n\t\t\t\tlog.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async saveRoutingTable() {\n\t\tif (!this.config.dhtStoragePath || !this.node) return;\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.dhtStoragePath);\n\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\tconst peersToSave = [];\n\t\t\tfor (const peer of allPeers) {\n\t\t\t\tif (peer.addresses.length > 0) {\n\t\t\t\t\tpeersToSave.push({\n\t\t\t\t\t\tid: peer.id.toString(),\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: internal libp2p addr\n\t\t\t\t\t\taddresses: peer.addresses.map((a: any) => a.multiaddr.toString()),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait fs.mkdir(path.dirname(absolutePath), { recursive: true });\n\t\t\tawait fs.writeFile(absolutePath, JSON.stringify(peersToSave, null, 2));\n\t\t\tlog.info(`[LIOP-Mesh] Saved ${peersToSave.length} peers to DHT storage`);\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Internal logic to register protocol handlers against the libp2p node.\n\t * Can be called multiple times; handles idempotent registration.\n\t */\n\tprivate applyHandlers(): void {\n\t\tif (!this.node || this.manifestProtocolRegistered) return;\n\t\tif (!this.manifestProvider) return;\n\n\t\tthis.manifestProtocolRegistered = true;\n\n\t\t// Announce manifest capability to the Mesh DHT for discovery\n\t\tthis.announceCapability(LIOP_MANIFEST_CAPABILITY).catch((err) => {\n\t\t\tlog.info(`[LIOP-Mesh] Initial manifest announcement failed: ${err}`);\n\t\t});\n\n\t\t// libp2p v3.x: handler receives (stream, connection) as separate args\n\t\tthis.node.handle(\n\t\t\tLIOP_MANIFEST_PROTOCOL,\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p v3.x stream/connection types\n\t\t\tasync (streamArg: any, connectionArg?: any) => {\n\t\t\t\t// v3.x passes (stream, connection); v1.x passed ({ stream, connection })\n\t\t\t\tconst stream = streamArg?.stream ?? streamArg;\n\t\t\t\tconst conn = streamArg?.connection ?? connectionArg;\n\t\t\t\tconst remotePeer = conn?.remotePeer?.toString() || \"unknown\";\n\n\t\t\t\tlog.info(`[LIOP-Mesh] Incoming manifest request from ${remotePeer}.`);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst manifest = this.manifestProvider?.();\n\t\t\t\t\tif (!manifest || !stream) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Skipping manifest request (no provider or stream)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (typeof stream?.close === \"function\") await stream.close();\n\t\t\t\t\t\t} catch (_e) {}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst manifestStr = JSON.stringify(manifest);\n\t\t\t\t\tconst payload = new TextEncoder().encode(manifestStr);\n\n\t\t\t\t\t// Write length-prefixed payload (Big Endian 4 bytes)\n\t\t\t\t\tconst lengthBuf = Buffer.alloc(4);\n\t\t\t\t\tlengthBuf.writeUInt32BE(payload.length, 0);\n\t\t\t\t\tconst fullPacket = Buffer.concat([lengthBuf, Buffer.from(payload)]);\n\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Serving manifest (${fullPacket.length} bytes) to ${remotePeer} [Tools: ${manifest.tools.map((t) => t.name).join(\", \")}]`,\n\t\t\t\t\t);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// libp2p v3.x: stream.send() for writing\n\t\t\t\t\t\tif (typeof stream.send === \"function\") {\n\t\t\t\t\t\t\tconst accepted = stream.send(fullPacket);\n\t\t\t\t\t\t\tif (!accepted && typeof stream.onDrain === \"function\") {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait stream.onDrain({ signal: AbortSignal.timeout(5000) });\n\t\t\t\t\t\t\t\t} catch (drainErr) {\n\t\t\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t\t\t`[LIOP-Mesh] WARN: Drain timeout for ${remotePeer}: ${drainErr instanceof Error ? drainErr.message : String(drainErr)}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Fallback for environments where stream.send is not available\n\t\t\t\t\t\t\tawait pipe([fullPacket], stream);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.info(`[LIOP-Mesh] Manifest sent successfully to ${remotePeer}`);\n\t\t\t\t\t} catch (writeErr: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Write error serving manifest to ${remotePeer}: ${writeErr instanceof Error ? writeErr.message : String(writeErr)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (typeof stream.close === \"function\") await stream.close();\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t// Ignore close errors\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Error serving manifest to ${remotePeer}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] Manifest Protocol registered: ${LIOP_MANIFEST_PROTOCOL}`,\n\t\t);\n\t}\n\n\t/**\n\t * Registers a callback as the manifest provider.\n\t * Will be applied immediately if the node is already initialized.\n\t */\n\tregisterManifestHandler(provider: () => LiopManifest): void {\n\t\tthis.manifestProvider = provider;\n\t\tif (this.node) {\n\t\t\tthis.applyHandlers();\n\t\t}\n\t}\n\n\t/**\n\t * Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.\n\t * Returns null if the peer doesn't support the protocol or is unreachable.\n\t */\n\tasync queryManifest(peerIdStr: string): Promise<LiopManifest | null> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\n\t\t// [ALPHA-OPTIMIZATION] Local Loopback Bypass\n\t\t// If we are querying our own manifest, return it directly from the provider.\n\t\tif (peerIdStr === this.node.peerId.toString()) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Loopback: Returning local manifest directly for ${peerIdStr}`,\n\t\t\t);\n\t\t\treturn this.manifestProvider?.() || null;\n\t\t}\n\t\tif (this.shouldSkipManifestDial(peerIdStr)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst MAX_ATTEMPTS = 3;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\ttry {\n\t\t\t\ttype DialTarget = Parameters<Libp2p[\"dialProtocol\"]>[0];\n\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: targetPeer can be from connections or from string\n\t\t\t\tlet targetPeer: any = null;\n\t\t\t\tconst connections = this.node.getConnections();\n\t\t\t\tconst activeConn = connections.find(\n\t\t\t\t\t(c) => c.remotePeer.toString() === peerIdStr,\n\t\t\t\t);\n\n\t\t\t\tif (activeConn) {\n\t\t\t\t\ttargetPeer = activeConn.remotePeer;\n\t\t\t\t} else {\n\t\t\t\t\t// Fallback: search peerStore to find a valid PeerId object that libp2p understands natively\n\t\t\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\t\t\tconst stored = allPeers.find((p) => p.id.toString() === peerIdStr);\n\t\t\t\t\tif (stored) {\n\t\t\t\t\t\ttargetPeer = stored.id;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Final fallback parsing.\n\t\t\t\t\t\t// [LIOP-CAUTION] This is where the toMultihash error usually triggers if libp2p version drift exists.\n\t\t\t\t\t\tconst { peerIdFromString } = await import(\"@libp2p/peer-id\");\n\t\t\t\t\t\ttargetPeer = peerIdFromString(peerIdStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// [LIOP-PORT-TRANSLATION] If an address mapper is configured (e.g. in the Host Agent),\n\t\t\t\t// ensure the targetPeer's addresses are translated before libp2p attempts to dial.\n\t\t\t\tconst dialTargetFromPeer = targetPeer as DialTarget;\n\t\t\t\tlet dialTarget: DialTarget = dialTargetFromPeer;\n\t\t\t\tif (this.config.addressMapper && this.node) {\n\t\t\t\t\tconst mapper = this.config.addressMapper;\n\t\t\t\t\tconst peer = await this.node.peerStore.get(targetPeer);\n\t\t\t\t\tif (peer && peer.addresses.length > 0) {\n\t\t\t\t\t\tconst translated = peer.addresses\n\t\t\t\t\t\t\t.map((oa) => {\n\t\t\t\t\t\t\t\tconst original = oa.multiaddr.toString();\n\t\t\t\t\t\t\t\tconst mapped = mapper(original);\n\t\t\t\t\t\t\t\tif (!mapped) return null;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tisCertified: oa.isCertified,\n\t\t\t\t\t\t\t\t\tmultiaddr: multiaddr(mapped),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.filter((t): t is NonNullable<typeof t> => t !== null);\n\n\t\t\t\t\t\t// Strategy: Force direct dial to the first translated TCP address to bypass DHT routing delays\n\t\t\t\t\t\tconst directTCP = translated.find(\n\t\t\t\t\t\t\t(t) =>\n\t\t\t\t\t\t\t\tt.multiaddr.toString().includes(\"/tcp/\") &&\n\t\t\t\t\t\t\t\t!t.multiaddr.toString().includes(\"/ws\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (directTCP) {\n\t\t\t\t\t\t\tdialTarget = directTCP.multiaddr as DialTarget;\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Mesh] ⚡ Direct dial to translated addr: ${dialTarget.toString()}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update the peerStore so subsequent dials also use the right path\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal peerStore\n\t\t\t\t\t\tawait (this.node as any).peerStore.save(targetPeer, {\n\t\t\t\t\t\t\tmultiaddrs: translated.map((t) => t.multiaddr),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Open a protocol stream using high-level dialProtocol for automated it-stream wrapping\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: stream type varies by transport\n\t\t\t\tlet stream: any;\n\t\t\t\ttry {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p returns polymorphic dialProtocol result\n\t\t\t\t\tconst result: any = await this.node\n\t\t\t\t\t\t.dialProtocol(dialTarget, LIOP_MANIFEST_PROTOCOL)\n\t\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\t\t// Catch specific TypeError that breaks the loop\n\t\t\t\t\t\t\tif (String(e).includes(\"toMultihash\")) {\n\t\t\t\t\t\t\t\tthrow new Error(\"INCOMPATIBLE_PEER_ID_INTERFACE\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t});\n\t\t\t\t\tstream = result.stream || result;\n\t\t\t\t} catch (dialErr) {\n\t\t\t\t\tif (attempt === MAX_ATTEMPTS) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Dial error for ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${dialErr}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tconst delay = 500 * 2 ** attempt;\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Dial error for ${peerIdStr} (Attempt ${attempt}). Retrying in ${delay}ms...`,\n\t\t\t\t\t);\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// libp2p v3.x: stream IS the AsyncIterable<Uint8Array>\n\t\t\t\t// v1.x had stream.source; v3.x has the stream itself as iterable\n\t\t\t\tconst source: AsyncIterable<Uint8Array> =\n\t\t\t\t\tstream.source ??\n\t\t\t\t\t(typeof stream[Symbol.asyncIterator] === \"function\" ? stream : null);\n\n\t\t\t\tif (!source) {\n\t\t\t\t\tthrow new Error(\"Target stream has no AsyncIterable source\");\n\t\t\t\t}\n\n\t\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\t\tlet totalReceived = 0;\n\t\t\t\tlet expectedPayloadLength = -1;\n\n\t\t\t\t// Read length-prefixed manifest: first 4 bytes = payload length (BE)\n\t\t\t\tlet manifestTimeoutId: NodeJS.Timeout | undefined;\n\t\t\t\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\t\t\t\tmanifestTimeoutId = setTimeout(\n\t\t\t\t\t\t() => reject(new Error(\"Manifest read timeout (5.0s)\")),\n\t\t\t\t\t\t5000,\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\tfor await (const chunk of source) {\n\t\t\t\t\t\t\t\tif (!chunk) continue;\n\t\t\t\t\t\t\t\t// libp2p streams yield Uint8ArrayList (from uint8arraylist package)\n\t\t\t\t\t\t\t\t// which reports .length correctly but Buffer.from() produces zeros.\n\t\t\t\t\t\t\t\t// .subarray() returns a flat contiguous Uint8Array with actual data.\n\t\t\t\t\t\t\t\tconst raw =\n\t\t\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Uint8ArrayList type guard\n\t\t\t\t\t\t\t\t\ttypeof (chunk as any).subarray === \"function\"\n\t\t\t\t\t\t\t\t\t\t? (chunk as { subarray: () => Uint8Array }).subarray()\n\t\t\t\t\t\t\t\t\t\t: chunk instanceof Uint8Array\n\t\t\t\t\t\t\t\t\t\t\t? chunk\n\t\t\t\t\t\t\t\t\t\t\t: new Uint8Array(0);\n\t\t\t\t\t\t\t\tconst bytes = Buffer.from(\n\t\t\t\t\t\t\t\t\traw.buffer,\n\t\t\t\t\t\t\t\t\traw.byteOffset,\n\t\t\t\t\t\t\t\t\traw.byteLength,\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (bytes.length > 0) {\n\t\t\t\t\t\t\t\t\tchunks.push(bytes);\n\t\t\t\t\t\t\t\t\ttotalReceived += bytes.length;\n\n\t\t\t\t\t\t\t\t\t// Extract expected length from the first 4 bytes once available\n\t\t\t\t\t\t\t\t\tif (expectedPayloadLength < 0 && totalReceived >= 4) {\n\t\t\t\t\t\t\t\t\t\tconst header = Buffer.concat(chunks);\n\t\t\t\t\t\t\t\t\t\texpectedPayloadLength = header.readUInt32BE(0);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Stop reading once we have the full payload (4 prefix + N payload)\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\texpectedPayloadLength >= 0 &&\n\t\t\t\t\t\t\t\t\t\ttotalReceived >= 4 + expectedPayloadLength\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})(),\n\t\t\t\t\t\ttimeoutPromise,\n\t\t\t\t\t]);\n\t\t\t\t} catch (itErr: unknown) {\n\t\t\t\t\tif (chunks.length === 0) throw itErr;\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Partial manifest read from ${peerIdStr}: ${itErr instanceof Error ? itErr.message : String(itErr)}`,\n\t\t\t\t\t);\n\t\t\t\t} finally {\n\t\t\t\t\tif (manifestTimeoutId) clearTimeout(manifestTimeoutId);\n\t\t\t\t}\n\n\t\t\t\tconst raw = Buffer.concat(chunks);\n\t\t\t\tif (raw.length < 4) {\n\t\t\t\t\tthrow new Error(\"Received empty/invalid manifest (too short)\");\n\t\t\t\t}\n\n\t\t\t\t// Use the length prefix to extract exactly the expected JSON\n\t\t\t\tconst declaredLen = raw.readUInt32BE(0);\n\t\t\t\tconst jsonStr = raw.subarray(4, 4 + declaredLen).toString(\"utf-8\");\n\t\t\t\tconst manifest: LiopManifest = JSON.parse(jsonStr);\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Received manifest from ${peerIdStr}: ${manifest.tools.length} tools`,\n\t\t\t\t);\n\t\t\t\tthis.clearManifestDialFailure(peerIdStr);\n\n\t\t\t\treturn manifest;\n\t\t\t} catch (err: unknown) {\n\t\t\t\tif (attempt === MAX_ATTEMPTS) {\n\t\t\t\t\tthis.recordManifestDialFailure(peerIdStr);\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Failed to query manifest from ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst delay = 500 * 2 ** attempt;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Query error for ${peerIdStr} (Attempt ${attempt}): ${err instanceof Error ? err.message : String(err)}. Retrying in ${delay}ms...`,\n\t\t\t\t);\n\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Discovers all peers in the DHT that have announced \"liop:manifest\".\n\t * Returns their PeerIDs for subsequent manifest queries.\n\t */\n\tasync discoverManifestProviders(): Promise<string[]> {\n\t\treturn this.findProviders(LIOP_MANIFEST_CAPABILITY);\n\t}\n\n\t/**\n\t * Announces this node as a manifest provider in the DHT.\n\t * Should be called after tools/resources have been registered.\n\t */\n\tasync announceManifest(): Promise<void> {\n\t\tawait this.announceCapability(LIOP_MANIFEST_CAPABILITY);\n\t}\n\n\t/**\n\t * Returns the current size of the routing table for diagnostic purposes.\n\t */\n\tgetRoutingTableSize(): number {\n\t\tif (!this.node) return 0;\n\t\t// @ts-expect-error: Accessing internal routing table size for diagnostics\n\t\treturn this.node.services.dht?.routingTable?.size || 0;\n\t}\n\n\tgetPeerId(): string {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\treturn this.node.peerId.toString();\n\t}\n\n\tasync sign(data: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.localPrivateKey) {\n\t\t\tthrow new Error(\"Local identity not loaded or initialized\");\n\t\t}\n\t\t// libp2p private key implementations typically return a Promise<Uint8Array> or Uint8Array\n\t\treturn Buffer.from(await this.localPrivateKey.sign(data));\n\t}\n\n\tgetMultiaddrs(): string[] {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\treturn this.node.getMultiaddrs().map((a) => a.toString());\n\t}\n\n\tasync announceCapability(hash: string): Promise<void> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\n\t\t// Buffer the capability for reactive re-announcement\n\t\tthis.announcedCapabilities.add(hash);\n\n\t\ttry {\n\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Announcing capability: ${hash} (CID: ${cid.toString()})`,\n\t\t\t);\n\n\t\t\t// In libp2p v1.x, contentRouting.provide returns Promise<void>\n\t\t\tawait this.node.contentRouting.provide(cid);\n\t\t\tlog.info(`[LIOP-Mesh] Successfully announced capability: ${hash}`);\n\n\t\t\t// [DEV-ONLY] Self-verification\n\t\t\tconst selfId = this.node.peerId.toString();\n\t\t\tfor await (const peer of this.node.contentRouting.findProviders(cid)) {\n\t\t\t\tif (peer.id.toString() === selfId) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Self-verification success: Node is providing ${hash}`,\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] Failed to announce capability: ${error}`);\n\t\t}\n\t}\n\n\tasync findProviders(hash: string): Promise<string[]> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\tconst providers: string[] = [];\n\t\ttry {\n\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Querying DHT for ${hash} (CID: ${cid.toString()})...`,\n\t\t\t);\n\n\t\t\tlet foundAny = false;\n\n\t\t\t// Phase 103: Adaptive Tail-Wait Polling for DHT Discovery\n\t\t\tconst connections = this.node.getConnections?.()?.length || 0;\n\t\t\tconst idleTimeoutMs = connections > 1 ? 1500 : 3000;\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${idleTimeoutMs}ms (Active connections: ${connections})`,\n\t\t\t);\n\n\t\t\t// We manually iterate the AsyncIterable to abort it via Promise.race\n\t\t\tconst iterator = this.node.contentRouting\n\t\t\t\t.findProviders(cid)\n\t\t\t\t[Symbol.asyncIterator]();\n\t\t\tlet isDone = false;\n\n\t\t\twhile (!isDone) {\n\t\t\t\tconst nextPromise = iterator.next();\n\t\t\t\tconst timeoutPromise = new Promise<{ timeout: true }>((resolve) =>\n\t\t\t\t\tsetTimeout(() => resolve({ timeout: true }), idleTimeoutMs),\n\t\t\t\t);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await Promise.race([nextPromise, timeoutPromise]);\n\n\t\t\t\t\tif (result && typeof result === \"object\" && \"timeout\" in result) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (typeof iterator.return === \"function\") {\n\t\t\t\t\t\t\t// Fire-and-forget: Kademlia iterators can block for 30s on return()\n\t\t\t\t\t\t\titerator.return().catch(() => {});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic Kademlia peer result\n\t\t\t\t\tconst itResult = result as IteratorResult<any>;\n\t\t\t\t\tif (itResult.done) {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tfoundAny = true;\n\t\t\t\t\tconst peer = itResult.value;\n\t\t\t\t\tconst peerId = peer.id.toString();\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Found provider: ${peerId}`);\n\t\t\t\t\tif (!providers.includes(peerId)) {\n\t\t\t\t\t\tproviders.push(peerId);\n\t\t\t\t\t}\n\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t`[LIOP-Mesh] DHT iteration error: ${e instanceof Error ? e.message : String(e)}`,\n\t\t\t\t\t);\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!foundAny) {\n\t\t\t\tconst services = this.node.services as {\n\t\t\t\t\tdht?: { routingTable?: { size: number } };\n\t\t\t\t};\n\t\t\t\tconst dhtSize = services.dht?.routingTable?.size || 0;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] DHT search for ${hash} returned zero results (routing table size: ${dhtSize})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// [DEVELOPER-EXPERIENCE] Local Loopback Discovery\n\t\t\t// If we are providing this capability, ensure we find ourselves even if DHT findProviders doesn't return us.\n\t\t\tif (this.announcedCapabilities.has(hash)) {\n\t\t\t\tconst selfId = this.node.peerId.toString();\n\t\t\t\tif (!providers.includes(selfId)) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Including local node (${selfId}) in results for ${hash}`,\n\t\t\t\t\t);\n\t\t\t\t\tproviders.push(selfId);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Error finding providers for ${hash}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] DHT search for ${hash} finished. Found ${providers.length} providers.`,\n\t\t);\n\t\treturn providers;\n\t}\n\n\tasync resolvePeer(peerIdStr: string): Promise<string[]> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\ttry {\n\t\t\t// Strategy 1: Check active connections for the peer's multiaddrs\n\t\t\tconst connections = this.node.getConnections();\n\t\t\tfor (const conn of connections) {\n\t\t\t\tif (conn.remotePeer.toString() === peerIdStr) {\n\t\t\t\t\tconst remoteAddr = conn.remoteAddr.toString();\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Resolved peer ${peerIdStr} via active connection: ${remoteAddr}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn [remoteAddr];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Strategy 2: Try peerStore (iterate all peers to avoid toMultihash conflict)\n\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\tfor (const peer of allPeers) {\n\t\t\t\tif (peer.id.toString() === peerIdStr && peer.addresses.length > 0) {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal libp2p addr type\n\t\t\t\t\tconst addrs = peer.addresses.map((a: any) => a.multiaddr.toString());\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Resolved peer ${peerIdStr} via peerStore: ${addrs[0]}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn addrs;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Peer ${peerIdStr} not found in connections or peerStore`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlog.info(`[LIOP-Mesh] Failed to resolve peer ${peerIdStr}: ${error}`);\n\t\t}\n\t\treturn [];\n\t}\n}\n"]}
|