@nekzus/liop 2.6.0 → 2.7.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 (109) hide show
  1. package/README.md +87 -40
  2. package/dist/bin/agent.js +27 -894
  3. package/dist/bridge.d.ts +4 -3
  4. package/dist/bridge.js +1 -4
  5. package/dist/chunk-2XHSALII.js +3 -0
  6. package/dist/chunk-2ZYX736J.js +2 -0
  7. package/dist/chunk-3WRKTVOF.js +2 -0
  8. package/dist/chunk-6KFKO6ZX.js +2 -0
  9. package/dist/chunk-6VK2XALI.js +2 -0
  10. package/dist/chunk-AYDF3IFZ.js +2 -0
  11. package/dist/chunk-CTTTLCGL.js +31 -0
  12. package/dist/chunk-ECRS6N33.js +4 -0
  13. package/dist/chunk-FDJMH4CB.js +2 -0
  14. package/dist/chunk-FTF6AMF6.js +0 -1
  15. package/dist/chunk-GWVSCZUS.js +2 -0
  16. package/dist/chunk-LEXMMIQI.js +15 -0
  17. package/dist/chunk-LM26HOJ6.js +31 -0
  18. package/dist/chunk-MQ5SU26J.js +2 -0
  19. package/dist/chunk-N35BC62H.js +2 -0
  20. package/dist/chunk-P6IJ3VBD.js +3 -0
  21. package/dist/chunk-TKLRW52V.js +2 -0
  22. package/dist/chunk-V35CXJQN.js +2 -0
  23. package/dist/chunk-WP5ER7RH.js +3 -0
  24. package/dist/chunk-XLVEDKM6.js +2 -0
  25. package/dist/chunk-Y675R34Z.js +2 -0
  26. package/dist/chunk-YD2AF2M6.js +46 -0
  27. package/dist/chunk-YLCNV764.js +3 -0
  28. package/dist/chunk-ZZMSFCJP.js +3 -0
  29. package/dist/client.d.ts +5 -4
  30. package/dist/client.js +1 -11
  31. package/dist/gateway.d.ts +6 -5
  32. package/dist/gateway.js +1 -11
  33. package/dist/{hybrid-DWe1bMoV.d.ts → hybrid-BZpCiUaV.d.ts} +4 -4
  34. package/dist/{index-BuEQtBHD.d.ts → index-BYDtRGue.d.ts} +8 -4
  35. package/dist/{index-CdW8j8Bn.d.ts → index-ByzjpRCk.d.ts} +30 -2
  36. package/dist/index.d.ts +57 -10
  37. package/dist/index.js +4 -317
  38. package/dist/kyber-PULV7PQX.js +2 -0
  39. package/dist/mesh.d.ts +1 -1
  40. package/dist/mesh.js +1 -5
  41. package/dist/{node-B0b2vUFS.d.ts → node-Djzm6UYd.d.ts} +8 -0
  42. package/dist/protocol/liop_core.proto +22 -6
  43. package/dist/server.d.ts +4 -3
  44. package/dist/server.js +1 -8
  45. package/dist/{types-CzRSOlOo.d.ts → types-29zv9X1V.d.ts} +3 -0
  46. package/dist/types.d.ts +2 -1
  47. package/dist/types.js +1 -2
  48. package/dist/verifier-DqZ9MQ9l.d.ts +82 -0
  49. package/dist/verifier-J4NQYZX5.js +2 -0
  50. package/dist/workers/logic-execution.d.ts +7 -0
  51. package/dist/workers/logic-execution.js +1 -271
  52. package/dist/workers/zk-verifier.d.ts +9 -0
  53. package/dist/workers/zk-verifier.js +1 -173
  54. package/dist/zk-DzYNWBgo.d.ts +104 -0
  55. package/package.json +7 -2
  56. package/dist/bin/agent.js.map +0 -1
  57. package/dist/bridge.js.map +0 -1
  58. package/dist/chunk-2KSO3W4A.js +0 -77
  59. package/dist/chunk-2KSO3W4A.js.map +0 -1
  60. package/dist/chunk-2STZHJ24.js +0 -114
  61. package/dist/chunk-2STZHJ24.js.map +0 -1
  62. package/dist/chunk-3QH44NKZ.js +0 -115
  63. package/dist/chunk-3QH44NKZ.js.map +0 -1
  64. package/dist/chunk-5SWHE62F.js +0 -3683
  65. package/dist/chunk-5SWHE62F.js.map +0 -1
  66. package/dist/chunk-7BSCUYUE.js +0 -421
  67. package/dist/chunk-7BSCUYUE.js.map +0 -1
  68. package/dist/chunk-7PITYWOV.js +0 -68
  69. package/dist/chunk-7PITYWOV.js.map +0 -1
  70. package/dist/chunk-EJ426URA.js +0 -818
  71. package/dist/chunk-EJ426URA.js.map +0 -1
  72. package/dist/chunk-FCFTYOAS.js +0 -793
  73. package/dist/chunk-FCFTYOAS.js.map +0 -1
  74. package/dist/chunk-FTF6AMF6.js.map +0 -1
  75. package/dist/chunk-IK7CGWAZ.js +0 -24
  76. package/dist/chunk-IK7CGWAZ.js.map +0 -1
  77. package/dist/chunk-K3DGJLUY.js +0 -106
  78. package/dist/chunk-K3DGJLUY.js.map +0 -1
  79. package/dist/chunk-PAICJCKJ.js +0 -332
  80. package/dist/chunk-PAICJCKJ.js.map +0 -1
  81. package/dist/chunk-PUDETPL4.js +0 -279
  82. package/dist/chunk-PUDETPL4.js.map +0 -1
  83. package/dist/chunk-UJFWPRDM.js +0 -206884
  84. package/dist/chunk-UJFWPRDM.js.map +0 -1
  85. package/dist/chunk-VRB5HUYU.js +0 -1492
  86. package/dist/chunk-VRB5HUYU.js.map +0 -1
  87. package/dist/chunk-VRDZ5IKE.js +0 -558
  88. package/dist/chunk-VRDZ5IKE.js.map +0 -1
  89. package/dist/chunk-WPTOJYN5.js +0 -181
  90. package/dist/chunk-WPTOJYN5.js.map +0 -1
  91. package/dist/chunk-XRDN232O.js +0 -877
  92. package/dist/chunk-XRDN232O.js.map +0 -1
  93. package/dist/chunk-Y62GORQF.js +0 -51
  94. package/dist/chunk-Y62GORQF.js.map +0 -1
  95. package/dist/chunk-ZP3VVXOI.js +0 -66
  96. package/dist/chunk-ZP3VVXOI.js.map +0 -1
  97. package/dist/client.js.map +0 -1
  98. package/dist/gateway.js.map +0 -1
  99. package/dist/index.js.map +0 -1
  100. package/dist/kyber-CGOA7Q6A.js +0 -3
  101. package/dist/kyber-CGOA7Q6A.js.map +0 -1
  102. package/dist/mesh.js.map +0 -1
  103. package/dist/server.js.map +0 -1
  104. package/dist/types.js.map +0 -1
  105. package/dist/verifier-COnid_dg.d.ts +0 -31
  106. package/dist/verifier-XFU7ZB2W.js +0 -6
  107. package/dist/verifier-XFU7ZB2W.js.map +0 -1
  108. package/dist/workers/logic-execution.js.map +0 -1
  109. package/dist/workers/zk-verifier.js.map +0 -1
@@ -1,793 +0,0 @@
1
- import { TokenManager } from './chunk-3QH44NKZ.js';
2
- import { LiopVerifier } from './chunk-2STZHJ24.js';
3
- import { Kyber768Wrapper } from './chunk-7PITYWOV.js';
4
- import { createChannelCredentials, liopV1, GRPC_CHANNEL_OPTIONS, TokenTelemetryEngine } from './chunk-UJFWPRDM.js';
5
- import { pqcHandshakesTotal, pqcHandshakeDurationMs, zkVerificationsTotal, toolCallErrorsTotal, wireEgressBytesTotal } from './chunk-PAICJCKJ.js';
6
- import { MCP_PROTOCOL_VERSION, MCP_LEGACY_SUPPORT_ENABLED, MCP_PROTOCOL_VERSION_LEGACY } from './chunk-2KSO3W4A.js';
7
- import { MeshNode } from './chunk-XRDN232O.js';
8
- import { log } from './chunk-K3DGJLUY.js';
9
- import * as grpc from '@grpc/grpc-js';
10
- import { createDecipheriv, randomBytes, createCipheriv } from 'crypto';
11
-
12
- var LiopRpcClient = class {
13
- // biome-ignore lint/suspicious/noExplicitAny: internal gRPC client type
14
- client;
15
- token;
16
- lastResolvedToken;
17
- address;
18
- constructor(address, tls, token) {
19
- const credentials = createChannelCredentials(tls);
20
- this.client = new liopV1.LogicMesh(
21
- address,
22
- credentials,
23
- GRPC_CHANNEL_OPTIONS
24
- );
25
- this.token = token;
26
- if (typeof token === "string") {
27
- this.lastResolvedToken = token;
28
- }
29
- this.address = address;
30
- }
31
- setToken(token) {
32
- this.token = token;
33
- if (typeof token === "string") {
34
- this.lastResolvedToken = token;
35
- }
36
- }
37
- async resolveToken() {
38
- if (typeof this.token === "function") {
39
- this.lastResolvedToken = await this.token();
40
- return this.lastResolvedToken;
41
- }
42
- this.lastResolvedToken = this.token;
43
- return this.token;
44
- }
45
- /**
46
- * Negotiates intent with the remote host.
47
- * Returns the ephemeral Kyber public key for payload encryption.
48
- */
49
- async negotiateIntent(request) {
50
- const activeToken = await this.resolveToken();
51
- return new Promise((resolve, reject) => {
52
- const metadata = new grpc.Metadata();
53
- if (activeToken) {
54
- metadata.add("authorization", `Bearer ${activeToken}`);
55
- }
56
- this.client.NegotiateIntent(
57
- request,
58
- metadata,
59
- (error, response) => {
60
- if (error) {
61
- reject(error);
62
- } else {
63
- resolve(response);
64
- }
65
- }
66
- );
67
- });
68
- }
69
- /**
70
- * Pushes the encrypted Logic-on-Origin payload to the origin.
71
- * Returns a stream of semantic responses and ZK proofs.
72
- */
73
- executeLogic(request) {
74
- const metadata = new grpc.Metadata();
75
- const activeToken = this.lastResolvedToken || (typeof this.token === "string" ? this.token : void 0);
76
- if (activeToken) {
77
- metadata.add("authorization", `Bearer ${activeToken}`);
78
- }
79
- return this.client.ExecuteLogic(request, metadata);
80
- }
81
- close() {
82
- this.client.close();
83
- }
84
- };
85
- var AesGcmWrapper = {
86
- /**
87
- * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.
88
- *
89
- * @param payload Raw incoming WASM byte array or string.
90
- * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array
91
- * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.
92
- */
93
- encryptPayload(payload, sharedSecret) {
94
- if (sharedSecret.length !== 32) {
95
- throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");
96
- }
97
- const nonce = randomBytes(12);
98
- const cipher = createCipheriv("aes-256-gcm", sharedSecret, nonce);
99
- const encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);
100
- const authTag = cipher.getAuthTag();
101
- const finalCiphertext = Buffer.concat([encrypted, authTag]);
102
- return {
103
- ciphertext: finalCiphertext,
104
- nonce
105
- };
106
- },
107
- /**
108
- * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.
109
- */
110
- decryptPayload(ciphertextBuffer, nonce, sharedSecret) {
111
- if (ciphertextBuffer.length < 16) {
112
- throw new Error(
113
- "Invalid GCM Ciphertext; missing authentication tag length"
114
- );
115
- }
116
- const encryptedData = ciphertextBuffer.subarray(0, -16);
117
- const authTag = ciphertextBuffer.subarray(-16);
118
- const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
119
- decipher.setAuthTag(authTag);
120
- return Buffer.concat([decipher.update(encryptedData), decipher.final()]);
121
- }
122
- };
123
-
124
- // src/client/index.ts
125
- var LiopClient = class {
126
- meshNode = null;
127
- rpcClients = /* @__PURE__ */ new Map();
128
- manifests = /* @__PURE__ */ new Map();
129
- tlsOptions;
130
- serverInfo;
131
- verifier = new LiopVerifier();
132
- oauthToken;
133
- tokenManager;
134
- /** Protocol negotiation era */
135
- era = "modern";
136
- /** Negotiated protocol version */
137
- protocolVersion = MCP_PROTOCOL_VERSION;
138
- constructor(tls) {
139
- this.tlsOptions = tls;
140
- }
141
- /**
142
- * Discovers and connects to the target server or mesh capability.
143
- * If address is omitted, it sets up the MeshNode to act purely dynamically.
144
- */
145
- async connect(address, options) {
146
- const clientId = options?.auth?.clientId || process.env.LIOP_OAUTH_CLIENT_ID || process.env.LIOP_CLIENT_ID;
147
- const clientSecret = options?.auth?.clientSecret || process.env.LIOP_OAUTH_CLIENT_SECRET || process.env.LIOP_CLIENT_SECRET;
148
- const nexusUrl = options?.auth?.nexusUrl || process.env.LIOP_NEXUS_URL || "http://localhost:3000";
149
- const audience = options?.auth?.audience || process.env.LIOP_OAUTH_AUDIENCE || "urn:liop:mesh:api";
150
- 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";
151
- this.oauthToken = options?.auth?.token || process.env.LIOP_OAUTH_TOKEN || process.env.LIOP_TOKEN;
152
- if (clientId && clientSecret) {
153
- const baseUrl = (nexusUrl).endsWith("/oidc") ? nexusUrl : `${nexusUrl}/oidc`;
154
- const tokenEndpoint = `${baseUrl}/token`;
155
- this.tokenManager = new TokenManager({
156
- tokenEndpoint,
157
- clientId,
158
- clientSecret,
159
- audience,
160
- scopes: scope
161
- });
162
- try {
163
- this.oauthToken = await this.tokenManager.getToken();
164
- log.info(
165
- "[LiopClient] Dynamic TokenManager configured and initial token acquired."
166
- );
167
- } catch (err) {
168
- log.error(
169
- `[LiopClient] Failed to acquire OAuth M2M Token: ${err instanceof Error ? err.message : String(err)}`
170
- );
171
- }
172
- }
173
- this.meshNode = new MeshNode(options?.meshConfig);
174
- await this.meshNode.start();
175
- log.info(
176
- `[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`
177
- );
178
- if (address) {
179
- const tokenResolver = async () => {
180
- if (this.tokenManager) {
181
- return await this.tokenManager.getToken();
182
- }
183
- return this.oauthToken;
184
- };
185
- this.rpcClients.set(
186
- "static",
187
- new LiopRpcClient(address, this.tlsOptions, tokenResolver)
188
- );
189
- this.serverInfo = { name: `LiopServer (${address})`, version: "1.0.0" };
190
- log.info(`[LiopClient] Static gRPC configured for: ${address}`);
191
- } else {
192
- this.serverInfo = { name: "LiopServer (Mesh Alpha)", version: "1.0.0" };
193
- }
194
- }
195
- /**
196
- * Selects the optimal IP from an array of multiaddrs.
197
- * Prioritizes routable non-loopback IPv4 addresses (e.g. Docker bridge, LAN, WAN)
198
- * over loopback (127.0.0.1) to prevent inter-container connection failures.
199
- */
200
- selectOptimalIp(addrs) {
201
- for (const maddr of addrs) {
202
- const parts = maddr.split("/");
203
- const ipIdx = parts.indexOf("ip4");
204
- if (ipIdx !== -1 && ipIdx + 1 < parts.length) {
205
- const ip = parts[ipIdx + 1];
206
- if (ip !== "127.0.0.1" && !ip.startsWith("127.") && ip !== "0.0.0.0" && ip !== "localhost") {
207
- return ip;
208
- }
209
- }
210
- }
211
- for (const maddr of addrs) {
212
- const parts = maddr.split("/");
213
- const ipIdx = parts.indexOf("ip4");
214
- if (ipIdx !== -1 && ipIdx + 1 < parts.length) {
215
- return parts[ipIdx + 1];
216
- }
217
- }
218
- return null;
219
- }
220
- /**
221
- * Dynamically queries Kademlia DHT to find the optimal PeerID providing the Capability
222
- * and returns the physical gRPC target (host:port) resolved from the provider's manifest.
223
- */
224
- async resolveCapability(toolName) {
225
- if (!this.meshNode)
226
- throw new Error(
227
- "Client must be connected to Mesh to resolve capabilities."
228
- );
229
- log.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);
230
- const providers = await this.meshNode.findProviders(toolName);
231
- if (providers.length === 0) {
232
- throw new Error(
233
- `Kademlia DHT found zero providers for capability: ${toolName}`
234
- );
235
- }
236
- const providerId = providers[0];
237
- log.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);
238
- let grpcPort = 50051;
239
- const manifest = await this.meshNode.queryManifest(providerId);
240
- if (manifest) {
241
- grpcPort = manifest.grpcPort;
242
- this.manifests.set(providerId, manifest);
243
- log.info(
244
- `[LiopClient] Manifest resolved: gRPC port ${grpcPort}. Cached manifest for PeerID ${providerId}`
245
- );
246
- }
247
- const addrs = await this.meshNode.resolvePeer(providerId);
248
- const optimalIp = this.selectOptimalIp(addrs);
249
- if (optimalIp) {
250
- const grpcHost = `${optimalIp}:${grpcPort}`;
251
- log.info(
252
- `[LiopClient] Translated Multiaddr to optimal gRPC Target: ${grpcHost}`
253
- );
254
- return grpcHost;
255
- }
256
- return `127.0.0.1:${grpcPort}`;
257
- }
258
- /**
259
- * Probes a remote MCP endpoint using 'server/discover' to negotiate protocol era.
260
- * Falls back to legacy initialize handshake if server/discover fails.
261
- */
262
- async probeServerDiscover(mcpUrl) {
263
- try {
264
- const headers = {
265
- "Content-Type": "application/json",
266
- "Mcp-Method": "server/discover"
267
- };
268
- if (this.oauthToken) {
269
- headers.Authorization = `Bearer ${this.oauthToken}`;
270
- }
271
- const res = await fetch(mcpUrl, {
272
- method: "POST",
273
- headers,
274
- body: JSON.stringify({
275
- jsonrpc: "2.0",
276
- id: 1,
277
- method: "server/discover",
278
- params: {}
279
- })
280
- });
281
- if (res.ok) {
282
- const json = await res.json();
283
- const supported = json.result?.supportedVersions || [];
284
- if (supported.includes(MCP_PROTOCOL_VERSION)) {
285
- this.era = "modern";
286
- this.protocolVersion = MCP_PROTOCOL_VERSION;
287
- return {
288
- era: "modern",
289
- protocolVersion: MCP_PROTOCOL_VERSION,
290
- supportedVersions: supported
291
- };
292
- }
293
- }
294
- } catch (_err) {
295
- }
296
- if (MCP_LEGACY_SUPPORT_ENABLED) {
297
- this.era = "legacy";
298
- this.protocolVersion = MCP_PROTOCOL_VERSION_LEGACY;
299
- return {
300
- era: "legacy",
301
- protocolVersion: MCP_PROTOCOL_VERSION_LEGACY,
302
- supportedVersions: [MCP_PROTOCOL_VERSION_LEGACY]
303
- };
304
- }
305
- throw new Error(
306
- "Server does not support MCP 2026-07-28 and legacy support is disabled."
307
- );
308
- }
309
- /**
310
- * Discovers remote capabilities via the LIOP Manifest Protocol.
311
- * Utilizes a memory cache to avoid redundant network dials against live peers.
312
- */
313
- async discoverTools(forceRefresh = false) {
314
- if (!this.meshNode) {
315
- throw new Error("Client must be connected before discovering tools.");
316
- }
317
- const discoveryStartTime = Date.now();
318
- log.info(
319
- `[LiopClient] Discovery started (forceRefresh: ${forceRefresh})...`
320
- );
321
- const providerIds = await this.meshNode.discoverManifestProviders();
322
- const tools = [];
323
- const seenNames = /* @__PURE__ */ new Set();
324
- for (const peerId of providerIds) {
325
- try {
326
- let manifest = !forceRefresh ? this.manifests.get(peerId) : void 0;
327
- if (!manifest) {
328
- log.info(`[LiopClient] Querying manifest from: ${peerId}`);
329
- manifest = await this.meshNode.queryManifest(peerId);
330
- if (manifest) {
331
- this.manifests.set(peerId, manifest);
332
- }
333
- } else {
334
- log.info(`[LiopClient] Using cached manifest for: ${peerId}`);
335
- }
336
- if (manifest) {
337
- for (const tool of manifest.tools) {
338
- if (!seenNames.has(tool.name)) {
339
- tools.push({ name: tool.name, description: tool.description });
340
- seenNames.add(tool.name);
341
- }
342
- }
343
- }
344
- } catch (err) {
345
- log.info(
346
- `[LiopClient] Error querying manifest from ${peerId}:`,
347
- err instanceof Error ? err.message : String(err)
348
- );
349
- }
350
- }
351
- log.info(
352
- `[LiopClient] Discovery finished. Found ${tools.length} unique tools.`
353
- );
354
- try {
355
- const telemetry = TokenTelemetryEngine.getInstance();
356
- const toolsPayload = JSON.stringify(tools);
357
- const toolsResponsePayload = JSON.stringify({ tools });
358
- telemetry.record({
359
- type: "tools_list",
360
- method: "discoverTools",
361
- estimatedInputTokens: telemetry.countTokens(toolsPayload),
362
- estimatedOutputTokens: telemetry.countTokens(toolsResponsePayload),
363
- durationMs: Date.now() - discoveryStartTime
364
- });
365
- } catch {
366
- }
367
- return tools;
368
- }
369
- /**
370
- * Invokes a tool.
371
- */
372
- async callTool(request, _wasmPayload) {
373
- if (!this.meshNode) {
374
- throw new Error("Client must be connected before calling tools.");
375
- }
376
- const callStartTime = Date.now();
377
- const toolName = request.name;
378
- log.info(`[LiopClient] Resolving Tool: ${toolName}`);
379
- let rpcClient = this.rpcClients.get("static");
380
- let targetClientKey = toolName;
381
- if (!rpcClient) {
382
- if (this.rpcClients.has(toolName)) {
383
- rpcClient = this.rpcClients.get(toolName);
384
- targetClientKey = toolName;
385
- }
386
- }
387
- if (!rpcClient) {
388
- let resolvedHost = null;
389
- for (const [peerId, manifest] of this.manifests.entries()) {
390
- if (manifest.tools.some((t) => t.name === toolName)) {
391
- if (this.rpcClients.has(peerId)) {
392
- rpcClient = this.rpcClients.get(peerId);
393
- targetClientKey = peerId;
394
- break;
395
- }
396
- const addrs = await this.meshNode.resolvePeer(peerId);
397
- const optimalIp = this.selectOptimalIp(addrs);
398
- if (optimalIp) {
399
- resolvedHost = `${optimalIp}:${manifest.grpcPort}`;
400
- log.info(
401
- `[LiopClient] Fast-path: Resolved ${toolName} from manifest cache to optimal target ${resolvedHost}`
402
- );
403
- targetClientKey = peerId;
404
- rpcClient = this.getOrCreateRpcClient(peerId, resolvedHost);
405
- break;
406
- }
407
- }
408
- }
409
- if (!rpcClient) {
410
- const dynamicAddress = await this.resolveCapability(toolName);
411
- targetClientKey = toolName;
412
- rpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);
413
- }
414
- } else {
415
- targetClientKey = "static";
416
- log.info(
417
- `[LiopClient] Using existing static gRPC connection for ${toolName}.`
418
- );
419
- }
420
- log.info(`[LiopClient] Negotiating intent for ${toolName}...`);
421
- const agentDid = this.meshNode ? `did:liop:${this.meshNode.getPeerId()}` : "did:liop:ephemeral";
422
- const intentPayload = Buffer.from(`${toolName}:${Date.now()}`);
423
- const proofOfIntent = this.meshNode ? await this.meshNode.sign(intentPayload) : intentPayload;
424
- let intentResponse;
425
- try {
426
- intentResponse = await rpcClient.negotiateIntent({
427
- agent_did: agentDid,
428
- capability_hash: toolName,
429
- proof_of_intent: proofOfIntent
430
- });
431
- } catch (err) {
432
- const errMsg = err instanceof Error ? err.message : String(err);
433
- if (this.tokenManager && (errMsg.includes("UNAUTHENTICATED") || errMsg.includes("Invalid JWT") || errMsg.includes("timestamp check failed") || errMsg.includes("expired"))) {
434
- log.warn(
435
- `[LiopClient] Token expired/unauthenticated for ${toolName}. Preemptively refreshing OAuth token and retrying negotiateIntent...`
436
- );
437
- this.tokenManager.invalidate();
438
- const freshToken = await this.tokenManager.getToken();
439
- this.oauthToken = freshToken;
440
- rpcClient.setToken(freshToken);
441
- intentResponse = await rpcClient.negotiateIntent({
442
- agent_did: agentDid,
443
- capability_hash: toolName,
444
- proof_of_intent: proofOfIntent
445
- });
446
- } else {
447
- throw err;
448
- }
449
- }
450
- if (!intentResponse.accepted) {
451
- if (this.tokenManager && (intentResponse.error_message?.includes("token") || intentResponse.error_message?.includes("UNAUTHENTICATED") || intentResponse.error_message?.includes("expired") || intentResponse.error_message?.includes("timestamp check failed"))) {
452
- log.warn(
453
- `[LiopClient] Intent rejected with auth error: "${intentResponse.error_message}". Refreshing token and retrying...`
454
- );
455
- this.tokenManager.invalidate();
456
- const freshToken = await this.tokenManager.getToken();
457
- this.oauthToken = freshToken;
458
- rpcClient.setToken(freshToken);
459
- intentResponse = await rpcClient.negotiateIntent({
460
- agent_did: agentDid,
461
- capability_hash: toolName,
462
- proof_of_intent: proofOfIntent
463
- });
464
- }
465
- if (!intentResponse.accepted) {
466
- throw new Error(
467
- `Intent denied by host: ${intentResponse.error_message}`
468
- );
469
- }
470
- }
471
- const publicKey = intentResponse.kyber_public_key || intentResponse.kyberPublicKey;
472
- const sessionToken = intentResponse.session_token || intentResponse.sessionToken;
473
- if (!publicKey) {
474
- log.info(
475
- "[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",
476
- intentResponse
477
- );
478
- try {
479
- pqcHandshakesTotal.inc({
480
- algorithm: "ml-kem-768",
481
- status: "failure"
482
- });
483
- } catch {
484
- }
485
- throw new Error(
486
- "Handshake failed: Remote host did not provide a valid Kyber Public Key."
487
- );
488
- }
489
- log.info(
490
- `[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`
491
- );
492
- const pqcStart = performance.now();
493
- let kyberCiphertext;
494
- let sharedSecret;
495
- try {
496
- const res = await Kyber768Wrapper.encapsulateAsymmetric(publicKey);
497
- kyberCiphertext = res.ciphertext;
498
- sharedSecret = res.sharedSecret;
499
- const pqcDuration = performance.now() - pqcStart;
500
- pqcHandshakeDurationMs.observe({ tool: request.name }, pqcDuration);
501
- pqcHandshakesTotal.inc({
502
- algorithm: "ml-kem-768",
503
- status: "success"
504
- });
505
- } catch (encapError) {
506
- try {
507
- pqcHandshakesTotal.inc({
508
- algorithm: "ml-kem-768",
509
- status: "failure"
510
- });
511
- } catch {
512
- }
513
- throw encapError;
514
- }
515
- log.info(`[LiopClient] Sealing WASM Payload and Inputs...`);
516
- const _safePayload = _wasmPayload || Buffer.from("");
517
- const { ciphertext: encryptedWasm, nonce: aesNonce } = AesGcmWrapper.encryptPayload(_safePayload, sharedSecret);
518
- const encryptedInputs = {};
519
- const crypto = await import('crypto');
520
- for (const [key, value] of Object.entries(request.arguments || {})) {
521
- const inputNonce = crypto.randomBytes(12);
522
- const cipher = crypto.createCipheriv(
523
- "aes-256-gcm",
524
- sharedSecret,
525
- inputNonce
526
- );
527
- const encrypted = Buffer.concat([
528
- cipher.update(JSON.stringify(value)),
529
- cipher.final()
530
- ]);
531
- const authTag = cipher.getAuthTag();
532
- encryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);
533
- }
534
- const logicRequest = {
535
- session_token: sessionToken,
536
- wasm_binary: encryptedWasm,
537
- inputs: encryptedInputs,
538
- pqc_ciphertext: kyberCiphertext,
539
- aes_nonce: aesNonce
540
- };
541
- return new Promise((resolve, reject) => {
542
- const stream = rpcClient.executeLogic(logicRequest);
543
- if (!stream) {
544
- reject(new Error("RPC Client unavailable or failed to create stream."));
545
- return;
546
- }
547
- let resultFulfilled = false;
548
- let hasReceivedData = false;
549
- stream.on("data", async (response) => {
550
- if (resultFulfilled) return;
551
- hasReceivedData = true;
552
- log.info("[LiopClient] Logic Executed. Verification in progress...");
553
- try {
554
- if (!response.is_error) {
555
- const isValid = await this.verifier.verifyZkReceipt(
556
- _safePayload,
557
- Buffer.from(response.cryptographic_proof).toString("hex"),
558
- Buffer.from(response.zk_receipt),
559
- Buffer.from(sharedSecret),
560
- response.semantic_evidence
561
- );
562
- try {
563
- zkVerificationsTotal.inc({
564
- status: isValid ? "valid" : "invalid"
565
- });
566
- } catch {
567
- }
568
- if (!isValid) {
569
- try {
570
- toolCallErrorsTotal.inc({
571
- capability: toolName,
572
- error_type: "zk_verification_failed"
573
- });
574
- } catch {
575
- }
576
- reject(
577
- new Error(
578
- "PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."
579
- )
580
- );
581
- return;
582
- }
583
- } else {
584
- try {
585
- toolCallErrorsTotal.inc({
586
- capability: toolName,
587
- error_type: "remote_execution_error"
588
- });
589
- } catch {
590
- }
591
- }
592
- resultFulfilled = true;
593
- try {
594
- const telemetry = TokenTelemetryEngine.getInstance();
595
- const inputPayload = JSON.stringify(request.arguments ?? {});
596
- telemetry.record({
597
- type: "tool_call",
598
- method: "callTool",
599
- toolName,
600
- peerId: targetClientKey !== toolName ? targetClientKey : void 0,
601
- estimatedInputTokens: telemetry.countTokens(inputPayload),
602
- estimatedOutputTokens: telemetry.countTokens(
603
- response.semantic_evidence
604
- ),
605
- durationMs: Date.now() - callStartTime
606
- });
607
- const egressBytes = Buffer.byteLength(response.semantic_evidence || "") + (response.cryptographic_proof ? response.cryptographic_proof.length : 0) + (response.zk_receipt ? response.zk_receipt.length : 0);
608
- wireEgressBytesTotal.inc({ capability: toolName }, egressBytes);
609
- } catch {
610
- }
611
- resolve({
612
- content: [
613
- {
614
- type: "text",
615
- text: response.semantic_evidence
616
- }
617
- ],
618
- isError: response.is_error
619
- });
620
- } catch (err) {
621
- try {
622
- toolCallErrorsTotal.inc({
623
- capability: toolName,
624
- error_type: "verification_exception"
625
- });
626
- } catch {
627
- }
628
- reject(err);
629
- }
630
- });
631
- stream.on("error", (err) => {
632
- this.rpcClients.delete(targetClientKey);
633
- this.rpcClients.delete(toolName);
634
- try {
635
- toolCallErrorsTotal.inc({
636
- capability: toolName,
637
- error_type: "stream_error"
638
- });
639
- } catch {
640
- }
641
- if (resultFulfilled) return;
642
- log.error("[LiopClient] Stream Error:", err);
643
- reject(err);
644
- });
645
- stream.on("end", () => {
646
- if (!hasReceivedData && !resultFulfilled) {
647
- reject(new Error("Logic-on-Origin stream closed without results."));
648
- }
649
- });
650
- });
651
- }
652
- getOrCreateRpcClient(peerId, address) {
653
- let client = this.rpcClients.get(peerId);
654
- if (!client) {
655
- let manifest = this.manifests.get(peerId);
656
- let realPeerId = peerId;
657
- if (!manifest) {
658
- log.info(
659
- `[LiopClient] PeerID "${peerId}" not found in manifest cache as PeerID. Searching tools in cached manifests...`
660
- );
661
- for (const [pId, m] of this.manifests.entries()) {
662
- if (m.tools.some((t) => t.name === peerId)) {
663
- manifest = m;
664
- realPeerId = pId;
665
- log.info(
666
- `[LiopClient] Resolved tool "${peerId}" to provider PeerID "${pId.slice(-8)}" from manifest cache.`
667
- );
668
- break;
669
- }
670
- }
671
- }
672
- const providerName = manifest?.serverInfo?.name?.toLowerCase() || "";
673
- let envToken;
674
- const slug = manifest?.tokenSlug;
675
- if (slug) {
676
- envToken = process.env[`LIOP_TOKEN_${slug}`] || process.env[`LIOP_OAUTH_TOKEN_${slug}`];
677
- log.info(
678
- `[LiopClient] Resolved via tokenSlug "${slug}" (LIOP_TOKEN_${slug}) -> found: ${!!envToken}`
679
- );
680
- } else {
681
- log.info(
682
- `[LiopClient] No tokenSlug available for peer ${realPeerId.slice(-8)}. Available cache keys: ${Array.from(
683
- this.manifests.keys()
684
- ).map((k) => k.slice(-8)).join(", ")}`
685
- );
686
- }
687
- if (!envToken && realPeerId) {
688
- const shortId = realPeerId.slice(-8).toUpperCase();
689
- envToken = process.env[`LIOP_TOKEN_${shortId}`] || process.env[`LIOP_OAUTH_TOKEN_${shortId}`];
690
- }
691
- if (!envToken && providerName) {
692
- const cleanName = providerName.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
693
- envToken = process.env[`LIOP_TOKEN_${cleanName}`] || process.env[`LIOP_OAUTH_TOKEN_${cleanName}`];
694
- }
695
- if (envToken) {
696
- log.info(
697
- `[LiopClient] Resolved node-specific token for peer ${realPeerId.slice(-8)} (${providerName || "unknown"})`
698
- );
699
- }
700
- const tokenResolver = async () => {
701
- if (envToken) return envToken;
702
- if (this.tokenManager) {
703
- return await this.tokenManager.getToken();
704
- }
705
- return this.oauthToken;
706
- };
707
- client = new LiopRpcClient(address, this.tlsOptions, tokenResolver);
708
- this.rpcClients.set(peerId, client);
709
- }
710
- return client;
711
- }
712
- /**
713
- * Reads a specific resource by URI.
714
- * In LIOP, resources can be static definitions or dynamic streams.
715
- */
716
- async readResource(uri) {
717
- if (!this.meshNode) {
718
- throw new Error("Client must be connected before reading resources.");
719
- }
720
- const readStartTime = Date.now();
721
- log.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);
722
- const providers = await this.meshNode.findProviders(uri);
723
- if (providers.length === 0) {
724
- throw new Error(`No mesh providers found for resource: ${uri}`);
725
- }
726
- const manifest = await this.meshNode.queryManifest(providers[0]);
727
- if (!manifest) {
728
- throw new Error("Target peer did not return a valid LIOP Manifest.");
729
- }
730
- const resourceDef = manifest.resources?.find((r) => r.uri === uri);
731
- if (!resourceDef) {
732
- throw new Error(`Resource ${uri} not listed in remote manifest.`);
733
- }
734
- const result = {
735
- contents: [
736
- {
737
- uri,
738
- mimeType: resourceDef.mimeType || "application/json",
739
- text: JSON.stringify(resourceDef, null, 2)
740
- }
741
- ]
742
- };
743
- try {
744
- const telemetry = TokenTelemetryEngine.getInstance();
745
- const outputPayload = JSON.stringify(result);
746
- telemetry.record({
747
- type: "resource_read",
748
- method: "readResource",
749
- toolName: uri,
750
- peerId: providers[0],
751
- estimatedInputTokens: telemetry.countTokens(uri),
752
- estimatedOutputTokens: telemetry.countTokens(outputPayload),
753
- durationMs: Date.now() - readStartTime
754
- });
755
- } catch {
756
- }
757
- return result;
758
- }
759
- /**
760
- * Returns the local PeerId string if the mesh node is active, null otherwise.
761
- * PeerIds are public identifiers by libp2p protocol design (Ed25519 public key hash).
762
- */
763
- get peerId() {
764
- return this.meshNode?.getPeerId() ?? null;
765
- }
766
- /**
767
- * Returns true if the mesh node is initialized and running.
768
- */
769
- get isMeshActive() {
770
- return this.meshNode?.isStarted() ?? false;
771
- }
772
- /**
773
- * Returns the number of active P2P connections, or 0 if the mesh is inactive.
774
- */
775
- get connectionCount() {
776
- return this.meshNode?.getPeers().length ?? 0;
777
- }
778
- getServerInfo() {
779
- return this.serverInfo;
780
- }
781
- /**
782
- * Destroys the active Mesh Node resources.
783
- */
784
- async close() {
785
- if (this.meshNode) {
786
- await this.meshNode.stop();
787
- }
788
- }
789
- };
790
-
791
- export { AesGcmWrapper, LiopClient, LiopRpcClient };
792
- //# sourceMappingURL=chunk-FCFTYOAS.js.map
793
- //# sourceMappingURL=chunk-FCFTYOAS.js.map