@nekzus/liop 2.1.0-alpha.4 → 2.1.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/bin/agent.js +301 -4
  2. package/dist/bin/agent.js.map +1 -1
  3. package/dist/bridge.js +3 -1
  4. package/dist/chunk-32ADSAJS.js +104 -0
  5. package/dist/chunk-32ADSAJS.js.map +1 -0
  6. package/dist/chunk-4KIGYPIQ.js +3298 -0
  7. package/dist/chunk-4KIGYPIQ.js.map +1 -0
  8. package/dist/chunk-72MNYFR6.js +64 -0
  9. package/dist/chunk-72MNYFR6.js.map +1 -0
  10. package/dist/chunk-AL7H7DTW.js +463 -0
  11. package/dist/chunk-AL7H7DTW.js.map +1 -0
  12. package/dist/chunk-CT6NHSYP.js +30 -0
  13. package/dist/chunk-CT6NHSYP.js.map +1 -0
  14. package/dist/chunk-IJHTRIZC.js +56 -0
  15. package/dist/chunk-IJHTRIZC.js.map +1 -0
  16. package/dist/chunk-J3WPBMJ5.js +332 -0
  17. package/dist/chunk-J3WPBMJ5.js.map +1 -0
  18. package/dist/chunk-MMYZR7G7.js +815 -0
  19. package/dist/chunk-MMYZR7G7.js.map +1 -0
  20. package/dist/chunk-ODJT7ZUF.js +300 -0
  21. package/dist/chunk-ODJT7ZUF.js.map +1 -0
  22. package/dist/chunk-OUUTDSOW.js +24 -0
  23. package/dist/chunk-OUUTDSOW.js.map +1 -0
  24. package/dist/chunk-QLCOEP5J.js +68 -0
  25. package/dist/chunk-QLCOEP5J.js.map +1 -0
  26. package/dist/chunk-RDWCGZ2A.js +87 -0
  27. package/dist/chunk-RDWCGZ2A.js.map +1 -0
  28. package/dist/chunk-RWRRBYG4.js +1 -0
  29. package/dist/chunk-SSURAA3I.js +469 -0
  30. package/dist/chunk-SSURAA3I.js.map +1 -0
  31. package/dist/chunk-Y73XGYY7.js +1597 -0
  32. package/dist/chunk-Y73XGYY7.js.map +1 -0
  33. package/dist/client.js +8 -1
  34. package/dist/gateway.js +9 -1
  35. package/dist/index.js +58 -4
  36. package/dist/index.js.map +1 -1
  37. package/dist/kyber-3ULIJSE3.js +3 -0
  38. package/dist/{kyber-2WDOTUQX.js.map → kyber-3ULIJSE3.js.map} +1 -1
  39. package/dist/mesh.js +4 -1
  40. package/dist/server.js +6 -1
  41. package/dist/types.js +2 -1
  42. package/dist/verifier-3FAKCFNN.js +5 -0
  43. package/dist/{verifier-KZ4QYF5M.js.map → verifier-3FAKCFNN.js.map} +1 -1
  44. package/dist/workers/logic-execution.js +255 -1
  45. package/dist/workers/logic-execution.js.map +1 -1
  46. package/dist/workers/zk-verifier.js +173 -1
  47. package/dist/workers/zk-verifier.js.map +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-AEWYQWVZ.js +0 -42
  50. package/dist/chunk-AEWYQWVZ.js.map +0 -1
  51. package/dist/chunk-ANFXJGMP.js +0 -2
  52. package/dist/chunk-ANFXJGMP.js.map +0 -1
  53. package/dist/chunk-CPLE5VZ5.js +0 -33
  54. package/dist/chunk-CPLE5VZ5.js.map +0 -1
  55. package/dist/chunk-DBXGYHKY.js +0 -2
  56. package/dist/chunk-DBXGYHKY.js.map +0 -1
  57. package/dist/chunk-DQ6UW6L7.js +0 -2
  58. package/dist/chunk-DQ6UW6L7.js.map +0 -1
  59. package/dist/chunk-JIUFKRVG.js +0 -13
  60. package/dist/chunk-JIUFKRVG.js.map +0 -1
  61. package/dist/chunk-PWCXZWSE.js +0 -2
  62. package/dist/chunk-PWCXZWSE.js.map +0 -1
  63. package/dist/chunk-RYYRR4N5.js +0 -31
  64. package/dist/chunk-RYYRR4N5.js.map +0 -1
  65. package/dist/chunk-S6RJHZV2.js +0 -2
  66. package/dist/chunk-S6RJHZV2.js.map +0 -1
  67. package/dist/chunk-SB5XJXKV.js +0 -2
  68. package/dist/chunk-SB5XJXKV.js.map +0 -1
  69. package/dist/chunk-T3L6OCM3.js +0 -3
  70. package/dist/chunk-T3L6OCM3.js.map +0 -1
  71. package/dist/chunk-TNBXOZNG.js +0 -2
  72. package/dist/chunk-TNBXOZNG.js.map +0 -1
  73. package/dist/chunk-V5MKJT6S.js +0 -2
  74. package/dist/chunk-V5MKJT6S.js.map +0 -1
  75. package/dist/chunk-VDNV2I4I.js +0 -3
  76. package/dist/chunk-VDNV2I4I.js.map +0 -1
  77. package/dist/kyber-2WDOTUQX.js +0 -2
  78. package/dist/verifier-KZ4QYF5M.js +0 -2
@@ -0,0 +1,815 @@
1
+ import { log } from './chunk-72MNYFR6.js';
2
+ import * as fs from 'fs/promises';
3
+ import * as path from 'path';
4
+ import { noise } from '@chainsafe/libp2p-noise';
5
+ import { yamux } from '@chainsafe/libp2p-yamux';
6
+ import { bootstrap } from '@libp2p/bootstrap';
7
+ import { identify } from '@libp2p/identify';
8
+ import { kadDHT } from '@libp2p/kad-dht';
9
+ import { ping } from '@libp2p/ping';
10
+ import { tcp } from '@libp2p/tcp';
11
+ import { webSockets } from '@libp2p/websockets';
12
+ import { multiaddr } from '@multiformats/multiaddr';
13
+ import { pipe } from 'it-pipe';
14
+ import { createLibp2p } from 'libp2p';
15
+ import { CID } from 'multiformats/cid';
16
+ import { sha256 } from 'multiformats/hashes/sha2';
17
+
18
+ var DEFAULT_BOOTSTRAP_NODES = [
19
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR",
20
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
21
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb",
22
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"
23
+ ];
24
+ var LIOP_MANIFEST_PROTOCOL = "/liop/manifest/1.0.0";
25
+ var LIOP_MANIFEST_CAPABILITY = "liop:manifest";
26
+ var MeshNode = class _MeshNode {
27
+ node = null;
28
+ config;
29
+ manifestDialFailureState = /* @__PURE__ */ new Map();
30
+ static MANIFEST_DIAL_BASE_COOLDOWN_MS = 1e4;
31
+ static MANIFEST_DIAL_MAX_COOLDOWN_MS = 2 * 6e4;
32
+ static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS = 3e4;
33
+ /**
34
+ * Buffer of capability hashes that have been announced.
35
+ * Used to re-announce capabilities when new peers connect
36
+ * (critical for small / isolated clusters where the initial
37
+ * provide() finds zero peers in the routing table).
38
+ */
39
+ announcedCapabilities = /* @__PURE__ */ new Set();
40
+ /** Guards against concurrent re-announcement storms. */
41
+ reannouncing = false;
42
+ /** Callback that returns the local node's manifest on request. */
43
+ manifestProvider = null;
44
+ /** Flag to ensure the manifest protocol is only registered once. */
45
+ manifestProtocolRegistered = false;
46
+ /** Local Ed25519 Private Key for protocol signatures */
47
+ // biome-ignore lint/suspicious/noExplicitAny: libp2p keys type
48
+ localPrivateKey = null;
49
+ constructor(config = {}) {
50
+ this.config = {
51
+ listenAddresses: config.listenAddresses || [
52
+ "/ip4/0.0.0.0/tcp/0/ws",
53
+ "/ip4/0.0.0.0/tcp/0"
54
+ ],
55
+ bootstrapNodes: config.bootstrapNodes || [],
56
+ identityPath: config.identityPath,
57
+ enableWAN: config.enableWAN ?? false,
58
+ dhtStoragePath: config.dhtStoragePath,
59
+ addressMapper: config.addressMapper
60
+ };
61
+ }
62
+ shouldSkipManifestDial(peerIdStr) {
63
+ const state = this.manifestDialFailureState.get(peerIdStr);
64
+ if (!state) return false;
65
+ const now = Date.now();
66
+ if (now >= state.cooldownUntil) return false;
67
+ if (now - state.lastSkipLogAt > _MeshNode.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS) {
68
+ log.info(
69
+ `[LIOP-Mesh] Skipping manifest dial for ${peerIdStr} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1e3)}s remaining)`
70
+ );
71
+ state.lastSkipLogAt = now;
72
+ }
73
+ return true;
74
+ }
75
+ recordManifestDialFailure(peerIdStr) {
76
+ const now = Date.now();
77
+ const prev = this.manifestDialFailureState.get(peerIdStr);
78
+ const failures = (prev?.failures || 0) + 1;
79
+ const backoff = Math.min(
80
+ _MeshNode.MANIFEST_DIAL_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),
81
+ _MeshNode.MANIFEST_DIAL_MAX_COOLDOWN_MS
82
+ );
83
+ this.manifestDialFailureState.set(peerIdStr, {
84
+ failures,
85
+ cooldownUntil: now + backoff,
86
+ lastSkipLogAt: 0
87
+ });
88
+ }
89
+ clearManifestDialFailure(peerIdStr) {
90
+ this.manifestDialFailureState.delete(peerIdStr);
91
+ }
92
+ /**
93
+ * Loads a persistent identity from disk or generates a new Ed25519 keypair.
94
+ * Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).
95
+ */
96
+ async loadOrCreateIdentity() {
97
+ try {
98
+ const { generateKeyPair, privateKeyFromProtobuf } = await import(
99
+ '@libp2p/crypto/keys'
100
+ // biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>
101
+ );
102
+ const uint8arrays = await import('uint8arrays');
103
+ if (this.config.identityPath) {
104
+ const absolutePath = path.resolve(this.config.identityPath);
105
+ try {
106
+ const data = await fs.readFile(absolutePath, "utf-8");
107
+ const json = JSON.parse(data);
108
+ const protobufBytes = uint8arrays.fromString(json.privKey, "base64");
109
+ try {
110
+ const privateKey2 = privateKeyFromProtobuf(protobufBytes);
111
+ log.info(
112
+ `[LIOP-Mesh] Loaded persistent identity from ${absolutePath}`
113
+ );
114
+ return { privateKey: privateKey2, isNew: false };
115
+ } catch (parseError) {
116
+ log.error(
117
+ `[LIOP-Mesh] Persistent identity at ${absolutePath} is invalid or corrupt. Generating new one. Error: ${parseError instanceof Error ? parseError.message : String(parseError)}`
118
+ );
119
+ }
120
+ } catch (error) {
121
+ const e = error;
122
+ if (e.code !== "ENOENT") {
123
+ log.error(`[LIOP-Mesh] Error loading identity: ${e.message}`);
124
+ }
125
+ }
126
+ }
127
+ const privateKey = await generateKeyPair("Ed25519");
128
+ return { privateKey, isNew: true };
129
+ } catch (error) {
130
+ log.error(
131
+ `[LIOP-Mesh] Critical error in identity management: ${error}. Falling back to ephemeral identity.`
132
+ );
133
+ try {
134
+ const { generateKeyPair } = await import(
135
+ '@libp2p/crypto/keys'
136
+ // biome-ignore lint/suspicious/noExplicitAny: libp2p ESM dynamic import type workaround
137
+ );
138
+ const ephemeralKey = await generateKeyPair("Ed25519");
139
+ return { privateKey: ephemeralKey, isNew: true };
140
+ } catch (fallbackError) {
141
+ throw new Error(`Identity system failure: ${fallbackError}`);
142
+ }
143
+ }
144
+ }
145
+ /**
146
+ * Persists the private key to disk using protobuf serialization (libp2p v3.x).
147
+ */
148
+ // biome-ignore lint/suspicious/noExplicitAny: Libp2p private key type is complex for Alpha
149
+ async saveIdentity(privateKey) {
150
+ if (!this.config.identityPath || !this.node) return;
151
+ try {
152
+ const absolutePath = path.resolve(this.config.identityPath);
153
+ const { privateKeyToProtobuf } = await import(
154
+ '@libp2p/crypto/keys'
155
+ // biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>
156
+ );
157
+ const uint8arrays = await import('uint8arrays');
158
+ const protobufBytes = privateKeyToProtobuf(privateKey);
159
+ const privKeyEncoded = (uint8arrays.toString || uint8arrays.default.toString)(protobufBytes, "base64");
160
+ const json = {
161
+ id: this.node.peerId.toString(),
162
+ privKey: privKeyEncoded
163
+ };
164
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
165
+ await fs.writeFile(absolutePath, JSON.stringify(json, null, 2));
166
+ log.info(`[LIOP-Mesh] Identity persisted to ${absolutePath}`);
167
+ } catch (error) {
168
+ log.error(`[LIOP-Mesh] FAILED to persist identity: ${error}`);
169
+ }
170
+ }
171
+ /**
172
+ * Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.
173
+ * Required by @libp2p/kad-dht v16+ for provide/findProviders.
174
+ */
175
+ async capabilityToCID(capability) {
176
+ const hash = await sha256.digest(new TextEncoder().encode(capability));
177
+ return CID.create(1, 85, hash);
178
+ }
179
+ /**
180
+ * Re-announces all buffered capabilities after a new peer connects.
181
+ * Uses a small delay to allow the DHT protocol handshake to complete.
182
+ */
183
+ async reannounceAll() {
184
+ if (this.reannouncing || !this.node || this.announcedCapabilities.size === 0)
185
+ return;
186
+ this.reannouncing = true;
187
+ try {
188
+ await new Promise((resolve2) => setTimeout(resolve2, 500));
189
+ if (!this.node) return;
190
+ log.info(
191
+ `[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`
192
+ );
193
+ for (const hash of this.announcedCapabilities) {
194
+ try {
195
+ const cid = await this.capabilityToCID(hash);
196
+ await this.node.contentRouting.provide(cid);
197
+ log.info(`[LIOP-Mesh] Re-announced: ${hash}`);
198
+ } catch (_e) {
199
+ log.info(`[LIOP-Mesh] Re-announce failed for ${hash}: ${_e}`);
200
+ }
201
+ }
202
+ } finally {
203
+ this.reannouncing = false;
204
+ }
205
+ }
206
+ async start() {
207
+ if (this.node) return;
208
+ const result = await this.loadOrCreateIdentity();
209
+ if (!result) throw new Error("Could not initialize P2P Identity");
210
+ const { privateKey, isNew } = result;
211
+ this.localPrivateKey = privateKey;
212
+ let bootNodes = this.config.bootstrapNodes || [];
213
+ if (bootNodes.length === 0 && this.config.enableWAN) {
214
+ bootNodes = DEFAULT_BOOTSTRAP_NODES;
215
+ }
216
+ const discovery = bootNodes.length > 0 ? [
217
+ bootstrap({
218
+ list: bootNodes
219
+ })
220
+ ] : void 0;
221
+ const dhtProtocol = this.config.enableWAN ? "/ipfs/kad/1.0.0" : "/ipfs/lan/kad/1.0.0";
222
+ this.node = await createLibp2p({
223
+ privateKey,
224
+ addresses: {
225
+ listen: this.config.listenAddresses
226
+ },
227
+ transports: [tcp(), webSockets()],
228
+ connectionEncrypters: [noise()],
229
+ streamMuxers: [yamux()],
230
+ services: {
231
+ identify: identify(),
232
+ ping: ping(),
233
+ dht: kadDHT({
234
+ protocol: dhtProtocol,
235
+ clientMode: false,
236
+ // Allow local/private IPs in the DHT routing table for development/testing
237
+ allowQueryWithZeroPeers: true,
238
+ // By default kadDHT drops local IP addresses. Override the mapper to keep them.
239
+ peerInfoMapper: (peer) => peer
240
+ })
241
+ },
242
+ // biome-ignore lint/suspicious/noExplicitAny: libp2p discovery type mismatch
243
+ peerDiscovery: discovery
244
+ });
245
+ this.node.addEventListener("peer:discovery", (evt) => {
246
+ const peerId = evt.detail.id;
247
+ log.info(`[LIOP-Mesh] Discovered peer: ${peerId.toString()}`);
248
+ if (this.node) {
249
+ let dialTarget = peerId;
250
+ if (this.config.addressMapper && evt.detail.multiaddrs.length > 0) {
251
+ const translated = evt.detail.multiaddrs.map((ma) => {
252
+ const mapped = this.config.addressMapper(ma.toString());
253
+ return mapped ? multiaddr(mapped) : null;
254
+ }).filter((t) => t !== null);
255
+ const directTCP = translated.find(
256
+ (ma) => ma.toString().includes("/tcp/") && !ma.toString().includes("/ws")
257
+ );
258
+ if (directTCP) dialTarget = directTCP;
259
+ }
260
+ this.node.dial(dialTarget).catch(() => {
261
+ });
262
+ }
263
+ });
264
+ this.node.addEventListener("peer:connect", (evt) => {
265
+ const peerId = evt.detail;
266
+ log.info(`[LIOP-Mesh] Connected to peer: ${peerId.toString()}`);
267
+ if (!this.node) return;
268
+ const dht = this.node.services.dht;
269
+ if (dht?.routingTable) {
270
+ log.info(
271
+ `[LIOP-Mesh] Adding ${peerId.toString()} to DHT Routing Table`
272
+ );
273
+ dht.routingTable.add(peerId).catch((err) => {
274
+ log.info(
275
+ `[LIOP-Mesh] Failed to add peer to routing table: ${err instanceof Error ? err.message : String(err)}`
276
+ );
277
+ });
278
+ }
279
+ this.reannounceAll().catch((err) => {
280
+ log.info(
281
+ `[LIOP-Mesh] Re-announce error: ${err instanceof Error ? err.message : String(err)}`
282
+ );
283
+ });
284
+ });
285
+ await this.node.start();
286
+ await this.loadRoutingTable();
287
+ this.applyHandlers();
288
+ if (isNew && this.config.identityPath) {
289
+ await this.saveIdentity(privateKey);
290
+ }
291
+ log.info(
292
+ `[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`
293
+ );
294
+ this.node.getMultiaddrs().forEach((addr) => {
295
+ log.info(`[LIOP-Mesh] Listening on: ${addr.toString()}`);
296
+ });
297
+ if (bootNodes.length > 0) {
298
+ log.info(
299
+ `[LIOP-Mesh] Forcing direct P2P dial to ${bootNodes.length} bootstrap nodes...`
300
+ );
301
+ const maxRetries = 5;
302
+ for (const addr of bootNodes) {
303
+ let success = false;
304
+ let attempt = 1;
305
+ while (attempt <= maxRetries && !success) {
306
+ try {
307
+ await this.node.dial(multiaddr(addr));
308
+ log.info(`[LIOP-Mesh] \u2705 Successfully dialed ${addr}`);
309
+ success = true;
310
+ } catch (_e) {
311
+ const delay = Math.min(1e3 * 2 ** (attempt - 1), 3e3);
312
+ log.warn(
313
+ `[LIOP-Mesh] \u26A0\uFE0F Dial attempt ${attempt}/${maxRetries} to ${addr} failed. Retrying in ${delay / 1e3}s...`
314
+ );
315
+ if (attempt < maxRetries) {
316
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
317
+ } else {
318
+ log.error(
319
+ `[LIOP-Mesh] \u274C Could not connect to bootstrap ${addr} after ${maxRetries} attempts. Continuing...`
320
+ );
321
+ }
322
+ attempt++;
323
+ }
324
+ }
325
+ }
326
+ }
327
+ }
328
+ async stop() {
329
+ if (this.node) {
330
+ await this.saveRoutingTable();
331
+ await this.node.stop();
332
+ log.info("[LIOP-Mesh] Node stopped");
333
+ }
334
+ }
335
+ async loadRoutingTable() {
336
+ if (!this.config.dhtStoragePath || !this.node) return;
337
+ try {
338
+ const absolutePath = path.resolve(this.config.dhtStoragePath);
339
+ const data = await fs.readFile(absolutePath, "utf-8");
340
+ const peers = JSON.parse(data);
341
+ const { peerIdFromString } = await import('@libp2p/peer-id');
342
+ let loadedCount = 0;
343
+ for (const peer of peers) {
344
+ if (!peer.id || !peer.addresses) continue;
345
+ try {
346
+ const peerId = peerIdFromString(peer.id);
347
+ const addrs = peer.addresses.map((a) => multiaddr(a));
348
+ await this.node.peerStore.save(peerId, { multiaddrs: addrs });
349
+ const dht = this.node.services.dht;
350
+ if (dht?.routingTable) {
351
+ dht.routingTable.add(peerId).catch(() => {
352
+ });
353
+ }
354
+ loadedCount++;
355
+ } catch (_e) {
356
+ }
357
+ }
358
+ log.info(`[LIOP-Mesh] Loaded ${loadedCount} peers from DHT storage`);
359
+ } catch (error) {
360
+ const e = error;
361
+ if (e.code !== "ENOENT") {
362
+ log.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);
363
+ }
364
+ }
365
+ }
366
+ async saveRoutingTable() {
367
+ if (!this.config.dhtStoragePath || !this.node) return;
368
+ try {
369
+ const absolutePath = path.resolve(this.config.dhtStoragePath);
370
+ const allPeers = await this.node.peerStore.all();
371
+ const peersToSave = [];
372
+ for (const peer of allPeers) {
373
+ if (peer.addresses.length > 0) {
374
+ peersToSave.push({
375
+ id: peer.id.toString(),
376
+ // biome-ignore lint/suspicious/noExplicitAny: internal libp2p addr
377
+ addresses: peer.addresses.map((a) => a.multiaddr.toString())
378
+ });
379
+ }
380
+ }
381
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
382
+ await fs.writeFile(absolutePath, JSON.stringify(peersToSave, null, 2));
383
+ log.info(`[LIOP-Mesh] Saved ${peersToSave.length} peers to DHT storage`);
384
+ } catch (error) {
385
+ log.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${error}`);
386
+ }
387
+ }
388
+ /**
389
+ * Internal logic to register protocol handlers against the libp2p node.
390
+ * Can be called multiple times; handles idempotent registration.
391
+ */
392
+ applyHandlers() {
393
+ if (!this.node || this.manifestProtocolRegistered) return;
394
+ if (!this.manifestProvider) return;
395
+ this.manifestProtocolRegistered = true;
396
+ this.announceCapability(LIOP_MANIFEST_CAPABILITY).catch((err) => {
397
+ log.info(`[LIOP-Mesh] Initial manifest announcement failed: ${err}`);
398
+ });
399
+ this.node.handle(
400
+ LIOP_MANIFEST_PROTOCOL,
401
+ // biome-ignore lint/suspicious/noExplicitAny: libp2p v3.x stream/connection types
402
+ async (streamArg, connectionArg) => {
403
+ const stream = streamArg?.stream ?? streamArg;
404
+ const conn = streamArg?.connection ?? connectionArg;
405
+ const remotePeer = conn?.remotePeer?.toString() || "unknown";
406
+ log.info(`[LIOP-Mesh] Incoming manifest request from ${remotePeer}.`);
407
+ try {
408
+ const manifest = this.manifestProvider?.();
409
+ if (!manifest || !stream) {
410
+ log.info(
411
+ `[LIOP-Mesh] Skipping manifest request (no provider or stream)`
412
+ );
413
+ try {
414
+ if (typeof stream?.close === "function") await stream.close();
415
+ } catch (_e) {
416
+ }
417
+ return;
418
+ }
419
+ const manifestStr = JSON.stringify(manifest);
420
+ const payload = new TextEncoder().encode(manifestStr);
421
+ const lengthBuf = Buffer.alloc(4);
422
+ lengthBuf.writeUInt32BE(payload.length, 0);
423
+ const fullPacket = Buffer.concat([lengthBuf, Buffer.from(payload)]);
424
+ log.info(
425
+ `[LIOP-Mesh] Serving manifest (${fullPacket.length} bytes) to ${remotePeer} [Tools: ${manifest.tools.map((t) => t.name).join(", ")}]`
426
+ );
427
+ try {
428
+ if (typeof stream.send === "function") {
429
+ const accepted = stream.send(fullPacket);
430
+ if (!accepted && typeof stream.onDrain === "function") {
431
+ try {
432
+ await stream.onDrain({ signal: AbortSignal.timeout(5e3) });
433
+ } catch (drainErr) {
434
+ log.info(
435
+ `[LIOP-Mesh] WARN: Drain timeout for ${remotePeer}: ${drainErr instanceof Error ? drainErr.message : String(drainErr)}`
436
+ );
437
+ }
438
+ }
439
+ } else {
440
+ await pipe([fullPacket], stream);
441
+ }
442
+ log.info(`[LIOP-Mesh] Manifest sent successfully to ${remotePeer}`);
443
+ } catch (writeErr) {
444
+ log.info(
445
+ `[LIOP-Mesh] Write error serving manifest to ${remotePeer}: ${writeErr instanceof Error ? writeErr.message : String(writeErr)}`
446
+ );
447
+ } finally {
448
+ try {
449
+ if (typeof stream.close === "function") await stream.close();
450
+ } catch (_e) {
451
+ }
452
+ }
453
+ return;
454
+ } catch (err) {
455
+ log.info(
456
+ `[LIOP-Mesh] Error serving manifest to ${remotePeer}: ${err instanceof Error ? err.message : String(err)}`
457
+ );
458
+ }
459
+ }
460
+ );
461
+ log.info(
462
+ `[LIOP-Mesh] Manifest Protocol registered: ${LIOP_MANIFEST_PROTOCOL}`
463
+ );
464
+ }
465
+ /**
466
+ * Registers a callback as the manifest provider.
467
+ * Will be applied immediately if the node is already initialized.
468
+ */
469
+ registerManifestHandler(provider) {
470
+ this.manifestProvider = provider;
471
+ if (this.node) {
472
+ this.applyHandlers();
473
+ }
474
+ }
475
+ /**
476
+ * Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.
477
+ * Returns null if the peer doesn't support the protocol or is unreachable.
478
+ */
479
+ async queryManifest(peerIdStr) {
480
+ if (!this.node) throw new Error("Mesh Node is not running");
481
+ if (peerIdStr === this.node.peerId.toString()) {
482
+ log.info(
483
+ `[LIOP-Mesh] Loopback: Returning local manifest directly for ${peerIdStr}`
484
+ );
485
+ return this.manifestProvider?.() || null;
486
+ }
487
+ if (this.shouldSkipManifestDial(peerIdStr)) {
488
+ return null;
489
+ }
490
+ const MAX_ATTEMPTS = 3;
491
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
492
+ try {
493
+ let targetPeer = null;
494
+ const connections = this.node.getConnections();
495
+ const activeConn = connections.find(
496
+ (c) => c.remotePeer.toString() === peerIdStr
497
+ );
498
+ if (activeConn) {
499
+ targetPeer = activeConn.remotePeer;
500
+ } else {
501
+ const allPeers = await this.node.peerStore.all();
502
+ const stored = allPeers.find((p) => p.id.toString() === peerIdStr);
503
+ if (stored) {
504
+ targetPeer = stored.id;
505
+ } else {
506
+ const { peerIdFromString } = await import('@libp2p/peer-id');
507
+ targetPeer = peerIdFromString(peerIdStr);
508
+ }
509
+ }
510
+ const dialTargetFromPeer = targetPeer;
511
+ let dialTarget = dialTargetFromPeer;
512
+ if (this.config.addressMapper && this.node) {
513
+ const mapper = this.config.addressMapper;
514
+ const peer = await this.node.peerStore.get(targetPeer);
515
+ if (peer && peer.addresses.length > 0) {
516
+ const translated = peer.addresses.map((oa) => {
517
+ const original = oa.multiaddr.toString();
518
+ const mapped = mapper(original);
519
+ if (!mapped) return null;
520
+ return {
521
+ isCertified: oa.isCertified,
522
+ multiaddr: multiaddr(mapped)
523
+ };
524
+ }).filter((t) => t !== null);
525
+ const directTCP = translated.find(
526
+ (t) => t.multiaddr.toString().includes("/tcp/") && !t.multiaddr.toString().includes("/ws")
527
+ );
528
+ if (directTCP) {
529
+ dialTarget = directTCP.multiaddr;
530
+ log.info(
531
+ `[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${dialTarget.toString()}`
532
+ );
533
+ }
534
+ await this.node.peerStore.save(targetPeer, {
535
+ multiaddrs: translated.map((t) => t.multiaddr)
536
+ });
537
+ }
538
+ }
539
+ let stream;
540
+ try {
541
+ const result = await this.node.dialProtocol(dialTarget, LIOP_MANIFEST_PROTOCOL).catch((e) => {
542
+ if (String(e).includes("toMultihash")) {
543
+ throw new Error("INCOMPATIBLE_PEER_ID_INTERFACE");
544
+ }
545
+ throw e;
546
+ });
547
+ stream = result.stream || result;
548
+ } catch (dialErr) {
549
+ if (attempt === MAX_ATTEMPTS) {
550
+ log.info(
551
+ `[LIOP-Mesh] Dial error for ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${dialErr}`
552
+ );
553
+ return null;
554
+ }
555
+ const delay = 500 * 2 ** attempt;
556
+ log.info(
557
+ `[LIOP-Mesh] Dial error for ${peerIdStr} (Attempt ${attempt}). Retrying in ${delay}ms...`
558
+ );
559
+ await new Promise((r) => setTimeout(r, delay));
560
+ continue;
561
+ }
562
+ const source = stream.source ?? (typeof stream[Symbol.asyncIterator] === "function" ? stream : null);
563
+ if (!source) {
564
+ throw new Error("Target stream has no AsyncIterable source");
565
+ }
566
+ const chunks = [];
567
+ let totalReceived = 0;
568
+ let expectedPayloadLength = -1;
569
+ let manifestTimeoutId;
570
+ const timeoutPromise = new Promise((_, reject) => {
571
+ manifestTimeoutId = setTimeout(
572
+ () => reject(new Error("Manifest read timeout (5.0s)")),
573
+ 5e3
574
+ );
575
+ });
576
+ try {
577
+ await Promise.race([
578
+ (async () => {
579
+ for await (const chunk of source) {
580
+ if (!chunk) continue;
581
+ const raw2 = (
582
+ // biome-ignore lint/suspicious/noExplicitAny: Uint8ArrayList type guard
583
+ typeof chunk.subarray === "function" ? chunk.subarray() : chunk instanceof Uint8Array ? chunk : new Uint8Array(0)
584
+ );
585
+ const bytes = Buffer.from(
586
+ raw2.buffer,
587
+ raw2.byteOffset,
588
+ raw2.byteLength
589
+ );
590
+ if (bytes.length > 0) {
591
+ chunks.push(bytes);
592
+ totalReceived += bytes.length;
593
+ if (expectedPayloadLength < 0 && totalReceived >= 4) {
594
+ const header = Buffer.concat(chunks);
595
+ expectedPayloadLength = header.readUInt32BE(0);
596
+ }
597
+ if (expectedPayloadLength >= 0 && totalReceived >= 4 + expectedPayloadLength) {
598
+ break;
599
+ }
600
+ }
601
+ }
602
+ })(),
603
+ timeoutPromise
604
+ ]);
605
+ } catch (itErr) {
606
+ if (chunks.length === 0) throw itErr;
607
+ log.info(
608
+ `[LIOP-Mesh] Partial manifest read from ${peerIdStr}: ${itErr instanceof Error ? itErr.message : String(itErr)}`
609
+ );
610
+ } finally {
611
+ if (manifestTimeoutId) clearTimeout(manifestTimeoutId);
612
+ }
613
+ const raw = Buffer.concat(chunks);
614
+ if (raw.length < 4) {
615
+ throw new Error("Received empty/invalid manifest (too short)");
616
+ }
617
+ const declaredLen = raw.readUInt32BE(0);
618
+ const jsonStr = raw.subarray(4, 4 + declaredLen).toString("utf-8");
619
+ const manifest = JSON.parse(jsonStr);
620
+ log.info(
621
+ `[LIOP-Mesh] Received manifest from ${peerIdStr}: ${manifest.tools.length} tools`
622
+ );
623
+ this.clearManifestDialFailure(peerIdStr);
624
+ return manifest;
625
+ } catch (err) {
626
+ if (attempt === MAX_ATTEMPTS) {
627
+ this.recordManifestDialFailure(peerIdStr);
628
+ log.info(
629
+ `[LIOP-Mesh] Failed to query manifest from ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)}`
630
+ );
631
+ return null;
632
+ }
633
+ const delay = 500 * 2 ** attempt;
634
+ log.info(
635
+ `[LIOP-Mesh] Query error for ${peerIdStr} (Attempt ${attempt}): ${err instanceof Error ? err.message : String(err)}. Retrying in ${delay}ms...`
636
+ );
637
+ await new Promise((r) => setTimeout(r, delay));
638
+ }
639
+ }
640
+ return null;
641
+ }
642
+ /**
643
+ * Discovers all peers in the DHT that have announced "liop:manifest".
644
+ * Returns their PeerIDs for subsequent manifest queries.
645
+ */
646
+ async discoverManifestProviders() {
647
+ return this.findProviders(LIOP_MANIFEST_CAPABILITY);
648
+ }
649
+ /**
650
+ * Announces this node as a manifest provider in the DHT.
651
+ * Should be called after tools/resources have been registered.
652
+ */
653
+ async announceManifest() {
654
+ await this.announceCapability(LIOP_MANIFEST_CAPABILITY);
655
+ }
656
+ /**
657
+ * Returns the current size of the routing table for diagnostic purposes.
658
+ */
659
+ getRoutingTableSize() {
660
+ if (!this.node) return 0;
661
+ return this.node.services.dht?.routingTable?.size || 0;
662
+ }
663
+ getPeerId() {
664
+ if (!this.node) throw new Error("Mesh Node is not running");
665
+ return this.node.peerId.toString();
666
+ }
667
+ async sign(data) {
668
+ if (!this.localPrivateKey) {
669
+ throw new Error("Local identity not loaded or initialized");
670
+ }
671
+ return Buffer.from(await this.localPrivateKey.sign(data));
672
+ }
673
+ getMultiaddrs() {
674
+ if (!this.node) throw new Error("Mesh Node is not running");
675
+ return this.node.getMultiaddrs().map((a) => a.toString());
676
+ }
677
+ async announceCapability(hash) {
678
+ if (!this.node) throw new Error("Mesh Node is not running");
679
+ this.announcedCapabilities.add(hash);
680
+ try {
681
+ const cid = await this.capabilityToCID(hash);
682
+ log.info(
683
+ `[LIOP-Mesh] Announcing capability: ${hash} (CID: ${cid.toString()})`
684
+ );
685
+ await this.node.contentRouting.provide(cid);
686
+ log.info(`[LIOP-Mesh] Successfully announced capability: ${hash}`);
687
+ const selfId = this.node.peerId.toString();
688
+ for await (const peer of this.node.contentRouting.findProviders(cid)) {
689
+ if (peer.id.toString() === selfId) {
690
+ log.info(
691
+ `[LIOP-Mesh] Self-verification success: Node is providing ${hash}`
692
+ );
693
+ break;
694
+ }
695
+ }
696
+ } catch (error) {
697
+ log.error(`[LIOP-Mesh] Failed to announce capability: ${error}`);
698
+ }
699
+ }
700
+ async findProviders(hash) {
701
+ if (!this.node) throw new Error("Mesh Node is not running");
702
+ const providers = [];
703
+ try {
704
+ const cid = await this.capabilityToCID(hash);
705
+ log.info(
706
+ `[LIOP-Mesh] Querying DHT for ${hash} (CID: ${cid.toString()})...`
707
+ );
708
+ let foundAny = false;
709
+ const connections = this.node.getConnections?.()?.length || 0;
710
+ const idleTimeoutMs = connections > 1 ? 1500 : 3e3;
711
+ log.info(
712
+ `[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${idleTimeoutMs}ms (Active connections: ${connections})`
713
+ );
714
+ const iterator = this.node.contentRouting.findProviders(cid)[Symbol.asyncIterator]();
715
+ let isDone = false;
716
+ while (!isDone) {
717
+ const nextPromise = iterator.next();
718
+ const timeoutPromise = new Promise(
719
+ (resolve2) => setTimeout(() => resolve2({ timeout: true }), idleTimeoutMs)
720
+ );
721
+ try {
722
+ const result = await Promise.race([nextPromise, timeoutPromise]);
723
+ if (result && typeof result === "object" && "timeout" in result) {
724
+ log.info(
725
+ `[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early.`
726
+ );
727
+ if (typeof iterator.return === "function") {
728
+ iterator.return().catch(() => {
729
+ });
730
+ }
731
+ isDone = true;
732
+ break;
733
+ }
734
+ const itResult = result;
735
+ if (itResult.done) {
736
+ isDone = true;
737
+ break;
738
+ }
739
+ foundAny = true;
740
+ const peer = itResult.value;
741
+ const peerId = peer.id.toString();
742
+ log.info(`[LIOP-Mesh] Found provider: ${peerId}`);
743
+ if (!providers.includes(peerId)) {
744
+ providers.push(peerId);
745
+ }
746
+ } catch (e) {
747
+ log.warn(
748
+ `[LIOP-Mesh] DHT iteration error: ${e instanceof Error ? e.message : String(e)}`
749
+ );
750
+ isDone = true;
751
+ break;
752
+ }
753
+ }
754
+ if (!foundAny) {
755
+ const services = this.node.services;
756
+ const dhtSize = services.dht?.routingTable?.size || 0;
757
+ log.info(
758
+ `[LIOP-Mesh] DHT search for ${hash} returned zero results (routing table size: ${dhtSize})`
759
+ );
760
+ }
761
+ if (this.announcedCapabilities.has(hash)) {
762
+ const selfId = this.node.peerId.toString();
763
+ if (!providers.includes(selfId)) {
764
+ log.info(
765
+ `[LIOP-Mesh] Including local node (${selfId}) in results for ${hash}`
766
+ );
767
+ providers.push(selfId);
768
+ }
769
+ }
770
+ } catch (error) {
771
+ log.info(
772
+ `[LIOP-Mesh] Error finding providers for ${hash}: ${error instanceof Error ? error.message : String(error)}`
773
+ );
774
+ }
775
+ log.info(
776
+ `[LIOP-Mesh] DHT search for ${hash} finished. Found ${providers.length} providers.`
777
+ );
778
+ return providers;
779
+ }
780
+ async resolvePeer(peerIdStr) {
781
+ if (!this.node) throw new Error("Mesh Node is not running");
782
+ try {
783
+ const connections = this.node.getConnections();
784
+ for (const conn of connections) {
785
+ if (conn.remotePeer.toString() === peerIdStr) {
786
+ const remoteAddr = conn.remoteAddr.toString();
787
+ log.info(
788
+ `[LIOP-Mesh] Resolved peer ${peerIdStr} via active connection: ${remoteAddr}`
789
+ );
790
+ return [remoteAddr];
791
+ }
792
+ }
793
+ const allPeers = await this.node.peerStore.all();
794
+ for (const peer of allPeers) {
795
+ if (peer.id.toString() === peerIdStr && peer.addresses.length > 0) {
796
+ const addrs = peer.addresses.map((a) => a.multiaddr.toString());
797
+ log.info(
798
+ `[LIOP-Mesh] Resolved peer ${peerIdStr} via peerStore: ${addrs[0]}`
799
+ );
800
+ return addrs;
801
+ }
802
+ }
803
+ log.info(
804
+ `[LIOP-Mesh] Peer ${peerIdStr} not found in connections or peerStore`
805
+ );
806
+ } catch (error) {
807
+ log.info(`[LIOP-Mesh] Failed to resolve peer ${peerIdStr}: ${error}`);
808
+ }
809
+ return [];
810
+ }
811
+ };
812
+
813
+ export { MeshNode };
814
+ //# sourceMappingURL=chunk-MMYZR7G7.js.map
815
+ //# sourceMappingURL=chunk-MMYZR7G7.js.map