@nekzus/liop 2.1.0 → 2.3.0

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 (100) hide show
  1. package/LICENSE +201 -21
  2. package/NOTICE +5 -0
  3. package/README.md +73 -5
  4. package/dist/bin/agent.js +303 -4
  5. package/dist/bin/agent.js.map +1 -1
  6. package/dist/bridge.d.ts +2 -2
  7. package/dist/bridge.js +4 -1
  8. package/dist/chunk-32ADSAJS.js +104 -0
  9. package/dist/chunk-32ADSAJS.js.map +1 -0
  10. package/dist/chunk-4LQPDN3W.js +556 -0
  11. package/dist/chunk-4LQPDN3W.js.map +1 -0
  12. package/dist/chunk-72MNYFR6.js +64 -0
  13. package/dist/chunk-72MNYFR6.js.map +1 -0
  14. package/dist/chunk-74CISO2I.js +853 -0
  15. package/dist/chunk-74CISO2I.js.map +1 -0
  16. package/dist/chunk-CRZBVFDV.js +616 -0
  17. package/dist/chunk-CRZBVFDV.js.map +1 -0
  18. package/dist/chunk-GKV6M2PQ.js +208106 -0
  19. package/dist/chunk-GKV6M2PQ.js.map +1 -0
  20. package/dist/chunk-JIJPZFR2.js +51 -0
  21. package/dist/chunk-JIJPZFR2.js.map +1 -0
  22. package/dist/chunk-OIMJZ64E.js +441 -0
  23. package/dist/chunk-OIMJZ64E.js.map +1 -0
  24. package/dist/chunk-OUUTDSOW.js +24 -0
  25. package/dist/chunk-OUUTDSOW.js.map +1 -0
  26. package/dist/chunk-PYKRQAER.js +77 -0
  27. package/dist/chunk-PYKRQAER.js.map +1 -0
  28. package/dist/chunk-QLCOEP5J.js +68 -0
  29. package/dist/chunk-QLCOEP5J.js.map +1 -0
  30. package/dist/chunk-RWRRBYG4.js +1 -0
  31. package/dist/chunk-SONUORBT.js +421 -0
  32. package/dist/chunk-SONUORBT.js.map +1 -0
  33. package/dist/chunk-UBOQZVV5.js +3508 -0
  34. package/dist/chunk-UBOQZVV5.js.map +1 -0
  35. package/dist/chunk-UCJEK75U.js +714 -0
  36. package/dist/chunk-UCJEK75U.js.map +1 -0
  37. package/dist/chunk-WSW6YJNY.js +168 -0
  38. package/dist/chunk-WSW6YJNY.js.map +1 -0
  39. package/dist/client.d.ts +3 -2
  40. package/dist/client.js +9 -1
  41. package/dist/gateway.d.ts +5 -110
  42. package/dist/gateway.js +10 -1
  43. package/dist/hybrid-CF__0YnC.d.ts +170 -0
  44. package/dist/{index-DO97j6hP.d.ts → index-BW95kAL4.d.ts} +72 -2
  45. package/dist/index-cMV0_yD9.d.ts +200 -0
  46. package/dist/index.d.ts +273 -18
  47. package/dist/index.js +311 -4
  48. package/dist/index.js.map +1 -1
  49. package/dist/kyber-3ULIJSE3.js +3 -0
  50. package/dist/{kyber-NONMBQNH.js.map → kyber-3ULIJSE3.js.map} +1 -1
  51. package/dist/mesh.d.ts +14 -0
  52. package/dist/mesh.js +4 -1
  53. package/dist/server.d.ts +2 -2
  54. package/dist/server.js +7 -1
  55. package/dist/{types-DzEXgi4s.d.ts → types-lJIxBlWF.d.ts} +75 -47
  56. package/dist/types.d.ts +1 -1
  57. package/dist/types.js +2 -1
  58. package/dist/verifier-3FAKCFNN.js +5 -0
  59. package/dist/{verifier-XU2DB56Z.js.map → verifier-3FAKCFNN.js.map} +1 -1
  60. package/dist/workers/logic-execution.d.ts +1 -0
  61. package/dist/workers/logic-execution.js +271 -1
  62. package/dist/workers/logic-execution.js.map +1 -1
  63. package/dist/workers/zk-verifier.js +173 -1
  64. package/dist/workers/zk-verifier.js.map +1 -1
  65. package/package.json +98 -49
  66. package/dist/chunk-2MGFSIXN.js +0 -2
  67. package/dist/chunk-2MGFSIXN.js.map +0 -1
  68. package/dist/chunk-4C666HHU.js +0 -2
  69. package/dist/chunk-4C666HHU.js.map +0 -1
  70. package/dist/chunk-ANFXJGMP.js +0 -2
  71. package/dist/chunk-ANFXJGMP.js.map +0 -1
  72. package/dist/chunk-DBXGYHKY.js +0 -2
  73. package/dist/chunk-DBXGYHKY.js.map +0 -1
  74. package/dist/chunk-DQ6UW6L7.js +0 -2
  75. package/dist/chunk-DQ6UW6L7.js.map +0 -1
  76. package/dist/chunk-GI2LSJYZ.js +0 -13
  77. package/dist/chunk-GI2LSJYZ.js.map +0 -1
  78. package/dist/chunk-GJUZGKZW.js +0 -3
  79. package/dist/chunk-GJUZGKZW.js.map +0 -1
  80. package/dist/chunk-I46YEWND.js +0 -33
  81. package/dist/chunk-I46YEWND.js.map +0 -1
  82. package/dist/chunk-PWCXZWSE.js +0 -2
  83. package/dist/chunk-PWCXZWSE.js.map +0 -1
  84. package/dist/chunk-RYYRR4N5.js +0 -31
  85. package/dist/chunk-RYYRR4N5.js.map +0 -1
  86. package/dist/chunk-S6RJHZV2.js +0 -2
  87. package/dist/chunk-S6RJHZV2.js.map +0 -1
  88. package/dist/chunk-SB5XJXKV.js +0 -2
  89. package/dist/chunk-SB5XJXKV.js.map +0 -1
  90. package/dist/chunk-T3L6OCM3.js +0 -3
  91. package/dist/chunk-T3L6OCM3.js.map +0 -1
  92. package/dist/chunk-TYVG6TXQ.js +0 -2
  93. package/dist/chunk-TYVG6TXQ.js.map +0 -1
  94. package/dist/chunk-UCCGDGHE.js +0 -54
  95. package/dist/chunk-UCCGDGHE.js.map +0 -1
  96. package/dist/chunk-V5MKJT6S.js +0 -2
  97. package/dist/chunk-V5MKJT6S.js.map +0 -1
  98. package/dist/index-Brfvxmdt.d.ts +0 -101
  99. package/dist/kyber-NONMBQNH.js +0 -2
  100. package/dist/verifier-XU2DB56Z.js +0 -2
@@ -0,0 +1,616 @@
1
+ import { LiopVerifier } from './chunk-32ADSAJS.js';
2
+ import { Kyber768Wrapper } from './chunk-QLCOEP5J.js';
3
+ import { createChannelCredentials, liopV1, GRPC_CHANNEL_OPTIONS } from './chunk-WSW6YJNY.js';
4
+ import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION_LEGACY } from './chunk-PYKRQAER.js';
5
+ import { MeshNode } from './chunk-74CISO2I.js';
6
+ import { log } from './chunk-72MNYFR6.js';
7
+ import * as grpc from '@grpc/grpc-js';
8
+ import { createDecipheriv, randomBytes, createCipheriv } from 'crypto';
9
+
10
+ var LiopRpcClient = class {
11
+ // biome-ignore lint/suspicious/noExplicitAny: internal gRPC client type
12
+ client;
13
+ token;
14
+ address;
15
+ constructor(address, tls, token) {
16
+ const credentials = createChannelCredentials(tls);
17
+ this.client = new liopV1.LogicMesh(
18
+ address,
19
+ credentials,
20
+ GRPC_CHANNEL_OPTIONS
21
+ );
22
+ this.token = token;
23
+ this.address = address;
24
+ }
25
+ /**
26
+ * Negotiates intent with the remote host.
27
+ * Returns the ephemeral Kyber public key for payload encryption.
28
+ */
29
+ async negotiateIntent(request) {
30
+ return new Promise((resolve, reject) => {
31
+ const metadata = new grpc.Metadata();
32
+ if (this.token) {
33
+ metadata.add("authorization", `Bearer ${this.token}`);
34
+ }
35
+ this.client.NegotiateIntent(
36
+ request,
37
+ metadata,
38
+ (error, response) => {
39
+ if (error) {
40
+ reject(error);
41
+ } else {
42
+ resolve(response);
43
+ }
44
+ }
45
+ );
46
+ });
47
+ }
48
+ /**
49
+ * Pushes the encrypted Logic-on-Origin payload to the origin.
50
+ * Returns a stream of semantic responses and ZK proofs.
51
+ */
52
+ executeLogic(request) {
53
+ const metadata = new grpc.Metadata();
54
+ if (this.token) {
55
+ metadata.add("authorization", `Bearer ${this.token}`);
56
+ }
57
+ return this.client.ExecuteLogic(request, metadata);
58
+ }
59
+ close() {
60
+ this.client.close();
61
+ }
62
+ };
63
+ var AesGcmWrapper = {
64
+ /**
65
+ * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.
66
+ *
67
+ * @param payload Raw incoming WASM byte array or string.
68
+ * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array
69
+ * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.
70
+ */
71
+ encryptPayload(payload, sharedSecret) {
72
+ if (sharedSecret.length !== 32) {
73
+ throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");
74
+ }
75
+ const nonce = randomBytes(12);
76
+ const cipher = createCipheriv("aes-256-gcm", sharedSecret, nonce);
77
+ const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
78
+ const authTag = cipher.getAuthTag();
79
+ const finalCiphertext = Buffer.concat([encrypted, authTag]);
80
+ return {
81
+ ciphertext: finalCiphertext,
82
+ nonce
83
+ };
84
+ },
85
+ /**
86
+ * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.
87
+ */
88
+ decryptPayload(ciphertextBuffer, nonce, sharedSecret) {
89
+ if (ciphertextBuffer.length < 16) {
90
+ throw new Error(
91
+ "Invalid GCM Ciphertext; missing authentication tag length"
92
+ );
93
+ }
94
+ const encryptedData = ciphertextBuffer.subarray(0, -16);
95
+ const authTag = ciphertextBuffer.subarray(-16);
96
+ const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
97
+ decipher.setAuthTag(authTag);
98
+ return Buffer.concat([decipher.update(encryptedData), decipher.final()]);
99
+ }
100
+ };
101
+
102
+ // src/client/index.ts
103
+ var LiopClient = class {
104
+ meshNode = null;
105
+ rpcClients = /* @__PURE__ */ new Map();
106
+ manifests = /* @__PURE__ */ new Map();
107
+ tlsOptions;
108
+ serverInfo;
109
+ verifier = new LiopVerifier();
110
+ oauthToken;
111
+ /** Protocol negotiation era */
112
+ era = "modern";
113
+ /** Negotiated protocol version */
114
+ protocolVersion = MCP_PROTOCOL_VERSION;
115
+ constructor(tls) {
116
+ this.tlsOptions = tls;
117
+ }
118
+ /**
119
+ * Requests an M2M access token from the Nexus Authorization Server using Client Credentials.
120
+ */
121
+ async acquireM2MToken(authOpts) {
122
+ const baseUrl = authOpts.nexusUrl.endsWith("/oidc") ? authOpts.nexusUrl : `${authOpts.nexusUrl}/oidc`;
123
+ const tokenUrl = `${baseUrl}/token`;
124
+ log.info(`[LiopClient] Requesting M2M Token from Nexus AS: ${tokenUrl}`);
125
+ const params = new URLSearchParams({
126
+ grant_type: "client_credentials",
127
+ scope: authOpts.scope || "liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",
128
+ resource: authOpts.audience,
129
+ client_id: authOpts.clientId,
130
+ client_secret: authOpts.clientSecret
131
+ });
132
+ const response = await fetch(tokenUrl, {
133
+ method: "POST",
134
+ headers: {
135
+ "Content-Type": "application/x-www-form-urlencoded"
136
+ },
137
+ body: params.toString()
138
+ });
139
+ if (!response.ok) {
140
+ const text = await response.text();
141
+ throw new Error(
142
+ `OAuth token request failed with status ${response.status}: ${text}`
143
+ );
144
+ }
145
+ const data = await response.json();
146
+ if (!data.access_token) {
147
+ throw new Error("OAuth token response did not contain an access_token.");
148
+ }
149
+ log.info("[LiopClient] M2M Token acquired successfully.");
150
+ return data.access_token;
151
+ }
152
+ /**
153
+ * Discovers and connects to the target server or mesh capability.
154
+ * If address is omitted, it sets up the MeshNode to act purely dynamically.
155
+ */
156
+ async connect(address, options) {
157
+ const clientId = options?.auth?.clientId || process.env.LIOP_OAUTH_CLIENT_ID || process.env.LIOP_CLIENT_ID;
158
+ const clientSecret = options?.auth?.clientSecret || process.env.LIOP_OAUTH_CLIENT_SECRET || process.env.LIOP_CLIENT_SECRET;
159
+ const nexusUrl = options?.auth?.nexusUrl || process.env.LIOP_NEXUS_URL || "http://localhost:3000";
160
+ const audience = options?.auth?.audience || process.env.LIOP_OAUTH_AUDIENCE || "urn:liop:mesh:api";
161
+ const scope = options?.auth?.scope || process.env.LIOP_OAUTH_SCOPE || "liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query";
162
+ this.oauthToken = options?.auth?.token || process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;
163
+ if (clientId && clientSecret) {
164
+ try {
165
+ this.oauthToken = await this.acquireM2MToken({
166
+ clientId,
167
+ clientSecret,
168
+ nexusUrl,
169
+ audience,
170
+ scope
171
+ });
172
+ } catch (err) {
173
+ log.error(
174
+ `[LiopClient] Failed to acquire OAuth M2M Token: ${err instanceof Error ? err.message : String(err)}`
175
+ );
176
+ }
177
+ }
178
+ this.meshNode = new MeshNode(options?.meshConfig);
179
+ await this.meshNode.start();
180
+ log.info(
181
+ `[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`
182
+ );
183
+ if (address) {
184
+ this.rpcClients.set(
185
+ "static",
186
+ new LiopRpcClient(address, this.tlsOptions, this.oauthToken)
187
+ );
188
+ this.serverInfo = { name: `LiopServer (${address})`, version: "1.0.0" };
189
+ log.info(`[LiopClient] Static gRPC configured for: ${address}`);
190
+ } else {
191
+ this.serverInfo = { name: "LiopServer (Mesh Alpha)", version: "1.0.0" };
192
+ }
193
+ }
194
+ /**
195
+ * Selects the optimal IP from an array of multiaddrs.
196
+ * Prioritizes routable non-loopback IPv4 addresses (e.g. Docker bridge, LAN, WAN)
197
+ * over loopback (127.0.0.1) to prevent inter-container connection failures.
198
+ */
199
+ selectOptimalIp(addrs) {
200
+ for (const maddr of addrs) {
201
+ const parts = maddr.split("/");
202
+ const ipIdx = parts.indexOf("ip4");
203
+ if (ipIdx !== -1 && ipIdx + 1 < parts.length) {
204
+ const ip = parts[ipIdx + 1];
205
+ if (ip !== "127.0.0.1" && !ip.startsWith("127.") && ip !== "0.0.0.0" && ip !== "localhost") {
206
+ return ip;
207
+ }
208
+ }
209
+ }
210
+ for (const maddr of addrs) {
211
+ const parts = maddr.split("/");
212
+ const ipIdx = parts.indexOf("ip4");
213
+ if (ipIdx !== -1 && ipIdx + 1 < parts.length) {
214
+ return parts[ipIdx + 1];
215
+ }
216
+ }
217
+ return null;
218
+ }
219
+ /**
220
+ * Dynamically queries Kademlia DHT to find the optimal PeerID providing the Capability
221
+ * and returns the physical gRPC target (host:port) resolved from the provider's manifest.
222
+ */
223
+ async resolveCapability(toolName) {
224
+ if (!this.meshNode)
225
+ throw new Error(
226
+ "Client must be connected to Mesh to resolve capabilities."
227
+ );
228
+ log.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);
229
+ const providers = await this.meshNode.findProviders(toolName);
230
+ if (providers.length === 0) {
231
+ throw new Error(
232
+ `Kademlia DHT found zero providers for capability: ${toolName}`
233
+ );
234
+ }
235
+ const providerId = providers[0];
236
+ log.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);
237
+ let grpcPort = 50051;
238
+ const manifest = await this.meshNode.queryManifest(providerId);
239
+ if (manifest) {
240
+ grpcPort = manifest.grpcPort;
241
+ this.manifests.set(providerId, manifest);
242
+ log.info(
243
+ `[LiopClient] Manifest resolved: gRPC port ${grpcPort}. Cached manifest for PeerID ${providerId}`
244
+ );
245
+ }
246
+ const addrs = await this.meshNode.resolvePeer(providerId);
247
+ const optimalIp = this.selectOptimalIp(addrs);
248
+ if (optimalIp) {
249
+ const grpcHost = `${optimalIp}:${grpcPort}`;
250
+ log.info(
251
+ `[LiopClient] Translated Multiaddr to optimal gRPC Target: ${grpcHost}`
252
+ );
253
+ return grpcHost;
254
+ }
255
+ return `127.0.0.1:${grpcPort}`;
256
+ }
257
+ /**
258
+ * Probes a remote MCP endpoint using 'server/discover' to negotiate protocol era.
259
+ * Falls back to legacy initialize handshake if server/discover fails.
260
+ */
261
+ async probeServerDiscover(mcpUrl) {
262
+ try {
263
+ const headers = {
264
+ "Content-Type": "application/json",
265
+ "Mcp-Method": "server/discover"
266
+ };
267
+ if (this.oauthToken) {
268
+ headers.Authorization = `Bearer ${this.oauthToken}`;
269
+ }
270
+ const res = await fetch(mcpUrl, {
271
+ method: "POST",
272
+ headers,
273
+ body: JSON.stringify({
274
+ jsonrpc: "2.0",
275
+ id: 1,
276
+ method: "server/discover",
277
+ params: {}
278
+ })
279
+ });
280
+ if (res.ok) {
281
+ const json = await res.json();
282
+ const supported = json.result?.supportedVersions || [];
283
+ if (supported.includes(MCP_PROTOCOL_VERSION)) {
284
+ this.era = "modern";
285
+ this.protocolVersion = MCP_PROTOCOL_VERSION;
286
+ return {
287
+ era: "modern",
288
+ protocolVersion: MCP_PROTOCOL_VERSION,
289
+ supportedVersions: supported
290
+ };
291
+ }
292
+ }
293
+ } catch (_err) {
294
+ }
295
+ if (MCP_LEGACY_SUPPORT_ENABLED) {
296
+ this.era = "legacy";
297
+ this.protocolVersion = MCP_PROTOCOL_VERSION_LEGACY;
298
+ return {
299
+ era: "legacy",
300
+ protocolVersion: MCP_PROTOCOL_VERSION_LEGACY,
301
+ supportedVersions: [MCP_PROTOCOL_VERSION_LEGACY]
302
+ };
303
+ }
304
+ throw new Error(
305
+ "Server does not support MCP 2026-07-28 and legacy support is disabled."
306
+ );
307
+ }
308
+ /**
309
+ * Discovers remote capabilities via the LIOP Manifest Protocol.
310
+ * Utilizes a memory cache to avoid redundant network dials against live peers.
311
+ */
312
+ async discoverTools(forceRefresh = false) {
313
+ if (!this.meshNode) {
314
+ throw new Error("Client must be connected before discovering tools.");
315
+ }
316
+ log.info(
317
+ `[LiopClient] Discovery started (forceRefresh: ${forceRefresh})...`
318
+ );
319
+ const providerIds = await this.meshNode.discoverManifestProviders();
320
+ const tools = [];
321
+ const seenNames = /* @__PURE__ */ new Set();
322
+ for (const peerId of providerIds) {
323
+ try {
324
+ let manifest = !forceRefresh ? this.manifests.get(peerId) : void 0;
325
+ if (!manifest) {
326
+ log.info(`[LiopClient] Querying manifest from: ${peerId}`);
327
+ manifest = await this.meshNode.queryManifest(peerId);
328
+ if (manifest) {
329
+ this.manifests.set(peerId, manifest);
330
+ }
331
+ } else {
332
+ log.info(`[LiopClient] Using cached manifest for: ${peerId}`);
333
+ }
334
+ if (manifest) {
335
+ for (const tool of manifest.tools) {
336
+ if (!seenNames.has(tool.name)) {
337
+ tools.push({ name: tool.name, description: tool.description });
338
+ seenNames.add(tool.name);
339
+ }
340
+ }
341
+ }
342
+ } catch (err) {
343
+ log.info(
344
+ `[LiopClient] Error querying manifest from ${peerId}:`,
345
+ err instanceof Error ? err.message : String(err)
346
+ );
347
+ }
348
+ }
349
+ log.info(
350
+ `[LiopClient] Discovery finished. Found ${tools.length} unique tools.`
351
+ );
352
+ return tools;
353
+ }
354
+ /**
355
+ * Invokes a tool.
356
+ */
357
+ async callTool(request, _wasmPayload) {
358
+ if (!this.meshNode) {
359
+ throw new Error("Client must be connected before calling tools.");
360
+ }
361
+ const toolName = request.name;
362
+ log.info(`[LiopClient] Resolving Tool: ${toolName}`);
363
+ let rpcClient = this.rpcClients.get("static");
364
+ let targetClientKey = toolName;
365
+ if (!rpcClient) {
366
+ if (this.rpcClients.has(toolName)) {
367
+ rpcClient = this.rpcClients.get(toolName);
368
+ targetClientKey = toolName;
369
+ }
370
+ }
371
+ if (!rpcClient) {
372
+ let resolvedHost = null;
373
+ for (const [peerId, manifest] of this.manifests.entries()) {
374
+ if (manifest.tools.some((t) => t.name === toolName)) {
375
+ if (this.rpcClients.has(peerId)) {
376
+ rpcClient = this.rpcClients.get(peerId);
377
+ targetClientKey = peerId;
378
+ break;
379
+ }
380
+ const addrs = await this.meshNode.resolvePeer(peerId);
381
+ const optimalIp = this.selectOptimalIp(addrs);
382
+ if (optimalIp) {
383
+ resolvedHost = `${optimalIp}:${manifest.grpcPort}`;
384
+ log.info(
385
+ `[LiopClient] Fast-path: Resolved ${toolName} from manifest cache to optimal target ${resolvedHost}`
386
+ );
387
+ targetClientKey = peerId;
388
+ rpcClient = this.getOrCreateRpcClient(peerId, resolvedHost);
389
+ break;
390
+ }
391
+ }
392
+ }
393
+ if (!rpcClient) {
394
+ const dynamicAddress = await this.resolveCapability(toolName);
395
+ targetClientKey = toolName;
396
+ rpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);
397
+ }
398
+ } else {
399
+ targetClientKey = "static";
400
+ log.info(
401
+ `[LiopClient] Using existing static gRPC connection for ${toolName}.`
402
+ );
403
+ }
404
+ log.info(`[LiopClient] Negotiating intent for ${toolName}...`);
405
+ const agentDid = this.meshNode ? `did:liop:${this.meshNode.getPeerId()}` : "did:liop:ephemeral";
406
+ const intentPayload = Buffer.from(`${toolName}:${Date.now()}`);
407
+ const proofOfIntent = this.meshNode ? await this.meshNode.sign(intentPayload) : intentPayload;
408
+ const intentResponse = await rpcClient.negotiateIntent({
409
+ agent_did: agentDid,
410
+ capability_hash: toolName,
411
+ proof_of_intent: proofOfIntent
412
+ });
413
+ if (!intentResponse.accepted) {
414
+ throw new Error(`Intent denied by host: ${intentResponse.error_message}`);
415
+ }
416
+ const publicKey = intentResponse.kyber_public_key || intentResponse.kyberPublicKey;
417
+ const sessionToken = intentResponse.session_token || intentResponse.sessionToken;
418
+ if (!publicKey) {
419
+ log.info(
420
+ "[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",
421
+ intentResponse
422
+ );
423
+ throw new Error(
424
+ "Handshake failed: Remote host did not provide a valid Kyber Public Key."
425
+ );
426
+ }
427
+ log.info(
428
+ `[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`
429
+ );
430
+ const { ciphertext: kyberCiphertext, sharedSecret } = await Kyber768Wrapper.encapsulateAsymmetric(publicKey);
431
+ log.info(`[LiopClient] Sealing WASM Payload and Inputs...`);
432
+ const _safePayload = _wasmPayload || Buffer.from("");
433
+ const { ciphertext: encryptedWasm, nonce: aesNonce } = AesGcmWrapper.encryptPayload(_safePayload, sharedSecret);
434
+ const encryptedInputs = {};
435
+ const crypto = await import('crypto');
436
+ for (const [key, value] of Object.entries(request.arguments || {})) {
437
+ const inputNonce = crypto.randomBytes(12);
438
+ const cipher = crypto.createCipheriv(
439
+ "aes-256-gcm",
440
+ sharedSecret,
441
+ inputNonce
442
+ );
443
+ const encrypted = Buffer.concat([
444
+ cipher.update(JSON.stringify(value)),
445
+ cipher.final()
446
+ ]);
447
+ const authTag = cipher.getAuthTag();
448
+ encryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);
449
+ }
450
+ const logicRequest = {
451
+ session_token: sessionToken,
452
+ wasm_binary: encryptedWasm,
453
+ inputs: encryptedInputs,
454
+ pqc_ciphertext: kyberCiphertext,
455
+ aes_nonce: aesNonce
456
+ };
457
+ return new Promise((resolve, reject) => {
458
+ const stream = rpcClient.executeLogic(logicRequest);
459
+ if (!stream) {
460
+ reject(new Error("RPC Client unavailable or failed to create stream."));
461
+ return;
462
+ }
463
+ let resultFulfilled = false;
464
+ let hasReceivedData = false;
465
+ stream.on("data", async (response) => {
466
+ if (resultFulfilled) return;
467
+ hasReceivedData = true;
468
+ log.info("[LiopClient] Logic Executed. Verification in progress...");
469
+ try {
470
+ if (!response.is_error) {
471
+ const isValid = await this.verifier.verifyZkReceipt(
472
+ _safePayload,
473
+ Buffer.from(response.cryptographic_proof).toString("hex"),
474
+ Buffer.from(response.zk_receipt),
475
+ Buffer.from(sharedSecret),
476
+ response.semantic_evidence
477
+ );
478
+ if (!isValid) {
479
+ reject(
480
+ new Error(
481
+ "PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."
482
+ )
483
+ );
484
+ return;
485
+ }
486
+ }
487
+ resultFulfilled = true;
488
+ resolve({
489
+ content: [
490
+ {
491
+ type: "text",
492
+ text: response.semantic_evidence
493
+ }
494
+ ],
495
+ isError: response.is_error
496
+ });
497
+ } catch (err) {
498
+ reject(err);
499
+ }
500
+ });
501
+ stream.on("error", (err) => {
502
+ this.rpcClients.delete(targetClientKey);
503
+ this.rpcClients.delete(toolName);
504
+ if (resultFulfilled) return;
505
+ log.error("[LiopClient] Stream Error:", err);
506
+ reject(err);
507
+ });
508
+ stream.on("end", () => {
509
+ if (!hasReceivedData && !resultFulfilled) {
510
+ reject(new Error("Logic-on-Origin stream closed without results."));
511
+ }
512
+ });
513
+ });
514
+ }
515
+ getOrCreateRpcClient(peerId, address) {
516
+ let client = this.rpcClients.get(peerId);
517
+ if (!client) {
518
+ let nodeToken = this.oauthToken;
519
+ let manifest = this.manifests.get(peerId);
520
+ let realPeerId = peerId;
521
+ if (!manifest) {
522
+ log.info(
523
+ `[LiopClient] PeerID "${peerId}" not found in manifest cache as PeerID. Searching tools in cached manifests...`
524
+ );
525
+ for (const [pId, m] of this.manifests.entries()) {
526
+ if (m.tools.some((t) => t.name === peerId)) {
527
+ manifest = m;
528
+ realPeerId = pId;
529
+ log.info(
530
+ `[LiopClient] Resolved tool "${peerId}" to provider PeerID "${pId.slice(-8)}" from manifest cache.`
531
+ );
532
+ break;
533
+ }
534
+ }
535
+ }
536
+ const providerName = manifest?.serverInfo?.name?.toLowerCase() || "";
537
+ let envToken;
538
+ const slug = manifest?.tokenSlug;
539
+ if (slug) {
540
+ envToken = process.env[`LIOP_TOKEN_${slug}`] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];
541
+ log.info(
542
+ `[LiopClient] Resolved via tokenSlug "${slug}" (LIOP_TOKEN_${slug}) -> found: ${!!envToken}`
543
+ );
544
+ } else {
545
+ log.info(
546
+ `[LiopClient] No tokenSlug available for peer ${realPeerId.slice(-8)}. Available cache keys: ${Array.from(
547
+ this.manifests.keys()
548
+ ).map((k) => k.slice(-8)).join(", ")}`
549
+ );
550
+ }
551
+ if (!envToken && realPeerId) {
552
+ const shortId = realPeerId.slice(-8).toUpperCase();
553
+ envToken = process.env[`LIOP_TOKEN_${shortId}`] || process.env[`LIOP_OAUTH_TOKEN_${shortId}`];
554
+ }
555
+ if (!envToken && providerName) {
556
+ const cleanName = providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
557
+ envToken = process.env[`LIOP_TOKEN_${cleanName}`] || process.env[`LIOP_OAUTH_TOKEN_${cleanName}`];
558
+ }
559
+ if (envToken) {
560
+ log.info(
561
+ `[LiopClient] Resolved node-specific token for peer ${realPeerId.slice(-8)} (${providerName || "unknown"})`
562
+ );
563
+ nodeToken = envToken;
564
+ }
565
+ client = new LiopRpcClient(address, this.tlsOptions, nodeToken);
566
+ this.rpcClients.set(peerId, client);
567
+ }
568
+ return client;
569
+ }
570
+ /**
571
+ * Reads a specific resource by URI.
572
+ * In LIOP, resources can be static definitions or dynamic streams.
573
+ */
574
+ async readResource(uri) {
575
+ if (!this.meshNode) {
576
+ throw new Error("Client must be connected before reading resources.");
577
+ }
578
+ log.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);
579
+ const providers = await this.meshNode.findProviders(uri);
580
+ if (providers.length === 0) {
581
+ throw new Error(`No mesh providers found for resource: ${uri}`);
582
+ }
583
+ const manifest = await this.meshNode.queryManifest(providers[0]);
584
+ if (!manifest) {
585
+ throw new Error("Target peer did not return a valid LIOP Manifest.");
586
+ }
587
+ const resourceDef = manifest.resources?.find((r) => r.uri === uri);
588
+ if (!resourceDef) {
589
+ throw new Error(`Resource ${uri} not listed in remote manifest.`);
590
+ }
591
+ return {
592
+ contents: [
593
+ {
594
+ uri,
595
+ mimeType: resourceDef.mimeType || "application/json",
596
+ text: JSON.stringify(resourceDef, null, 2)
597
+ }
598
+ ]
599
+ };
600
+ }
601
+ getServerInfo() {
602
+ return this.serverInfo;
603
+ }
604
+ /**
605
+ * Destroys the active Mesh Node resources.
606
+ */
607
+ async close() {
608
+ if (this.meshNode) {
609
+ await this.meshNode.stop();
610
+ }
611
+ }
612
+ };
613
+
614
+ export { LiopClient, LiopRpcClient };
615
+ //# sourceMappingURL=chunk-CRZBVFDV.js.map
616
+ //# sourceMappingURL=chunk-CRZBVFDV.js.map