@nekzus/liop 2.5.0-beta.1 → 2.5.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +19 -0
- package/README.md +148 -69
- package/dist/bin/agent.js +27 -303
- package/dist/bridge.d.ts +4 -3
- package/dist/bridge.js +1 -4
- package/dist/chunk-2XHSALII.js +3 -0
- package/dist/chunk-2ZYX736J.js +2 -0
- package/dist/chunk-3WRKTVOF.js +2 -0
- package/dist/chunk-6KFKO6ZX.js +2 -0
- package/dist/chunk-6VK2XALI.js +2 -0
- package/dist/chunk-AYDF3IFZ.js +2 -0
- package/dist/chunk-CTTTLCGL.js +31 -0
- package/dist/chunk-ECRS6N33.js +4 -0
- package/dist/chunk-FDJMH4CB.js +2 -0
- package/dist/chunk-FTF6AMF6.js +2 -0
- package/dist/chunk-GWVSCZUS.js +2 -0
- package/dist/chunk-LEXMMIQI.js +15 -0
- package/dist/chunk-LM26HOJ6.js +31 -0
- package/dist/chunk-MQ5SU26J.js +2 -0
- package/dist/chunk-N35BC62H.js +2 -0
- package/dist/chunk-P6IJ3VBD.js +3 -0
- package/dist/chunk-TKLRW52V.js +2 -0
- package/dist/chunk-V35CXJQN.js +2 -0
- package/dist/chunk-WP5ER7RH.js +3 -0
- package/dist/chunk-XLVEDKM6.js +2 -0
- package/dist/chunk-Y675R34Z.js +2 -0
- package/dist/chunk-YD2AF2M6.js +46 -0
- package/dist/chunk-YLCNV764.js +3 -0
- package/dist/chunk-ZZMSFCJP.js +3 -0
- package/dist/client.d.ts +6 -4
- package/dist/client.js +1 -9
- package/dist/gateway.d.ts +6 -5
- package/dist/gateway.js +1 -10
- package/dist/{hybrid-CF__0YnC.d.ts → hybrid-BZpCiUaV.d.ts} +6 -5
- package/dist/{index-cMV0_yD9.d.ts → index-BYDtRGue.d.ts} +45 -36
- package/dist/{index-BW95kAL4.d.ts → index-ByzjpRCk.d.ts} +37 -72
- package/dist/index.d.ts +221 -50
- package/dist/index.js +4 -312
- package/dist/kyber-PULV7PQX.js +2 -0
- package/dist/mesh.d.ts +27 -143
- package/dist/mesh.js +1 -4
- package/dist/node-Djzm6UYd.d.ts +172 -0
- package/dist/protocol/liop_core.proto +25 -6
- package/dist/server.d.ts +4 -3
- package/dist/server.js +1 -7
- package/dist/types-29zv9X1V.d.ts +455 -0
- package/dist/types.d.ts +2 -1
- package/dist/types.js +1 -2
- package/dist/verifier-DqZ9MQ9l.d.ts +82 -0
- package/dist/verifier-J4NQYZX5.js +2 -0
- package/dist/workers/logic-execution.d.ts +7 -0
- package/dist/workers/logic-execution.js +1 -271
- package/dist/workers/zk-verifier.d.ts +9 -0
- package/dist/workers/zk-verifier.js +1 -173
- package/dist/zk-DzYNWBgo.d.ts +104 -0
- package/package.json +56 -45
- package/dist/bin/agent.js.map +0 -1
- package/dist/bridge.js.map +0 -1
- package/dist/chunk-32ADSAJS.js +0 -104
- package/dist/chunk-32ADSAJS.js.map +0 -1
- package/dist/chunk-547TYL27.js +0 -208109
- package/dist/chunk-547TYL27.js.map +0 -1
- package/dist/chunk-72MNYFR6.js +0 -64
- package/dist/chunk-72MNYFR6.js.map +0 -1
- package/dist/chunk-74CISO2I.js +0 -853
- package/dist/chunk-74CISO2I.js.map +0 -1
- package/dist/chunk-CRZBVFDV.js +0 -616
- package/dist/chunk-CRZBVFDV.js.map +0 -1
- package/dist/chunk-GA3Q2S7O.js +0 -558
- package/dist/chunk-GA3Q2S7O.js.map +0 -1
- package/dist/chunk-JIJPZFR2.js +0 -51
- package/dist/chunk-JIJPZFR2.js.map +0 -1
- package/dist/chunk-OUUTDSOW.js +0 -24
- package/dist/chunk-OUUTDSOW.js.map +0 -1
- package/dist/chunk-PYKRQAER.js +0 -77
- package/dist/chunk-PYKRQAER.js.map +0 -1
- package/dist/chunk-QLCOEP5J.js +0 -68
- package/dist/chunk-QLCOEP5J.js.map +0 -1
- package/dist/chunk-RWRRBYG4.js +0 -3
- package/dist/chunk-RWRRBYG4.js.map +0 -1
- package/dist/chunk-SONUORBT.js +0 -421
- package/dist/chunk-SONUORBT.js.map +0 -1
- package/dist/chunk-T5IUZF47.js +0 -716
- package/dist/chunk-T5IUZF47.js.map +0 -1
- package/dist/chunk-U5BZ66VX.js +0 -447
- package/dist/chunk-U5BZ66VX.js.map +0 -1
- package/dist/chunk-WCCGE4QR.js +0 -3520
- package/dist/chunk-WCCGE4QR.js.map +0 -1
- package/dist/chunk-WSW6YJNY.js +0 -168
- package/dist/chunk-WSW6YJNY.js.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/gateway.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/kyber-3ULIJSE3.js +0 -3
- package/dist/kyber-3ULIJSE3.js.map +0 -1
- package/dist/mesh.js.map +0 -1
- package/dist/server.js.map +0 -1
- package/dist/types-lJIxBlWF.d.ts +0 -256
- package/dist/types.js.map +0 -1
- package/dist/verifier-3FAKCFNN.js +0 -5
- package/dist/verifier-3FAKCFNN.js.map +0 -1
- package/dist/verifier-COnid_dg.d.ts +0 -31
- package/dist/workers/logic-execution.js.map +0 -1
- package/dist/workers/zk-verifier.js.map +0 -1
package/dist/bin/agent.js
CHANGED
|
@@ -1,305 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
if (!data.mesh?.multiaddrs?.length || !data.mesh?.peerId) return null;
|
|
30
|
-
const tcpAddr = data.mesh.multiaddrs.find(
|
|
31
|
-
(a) => a.includes("/tcp/") && !a.includes("/ws") && !a.includes("/ip4/127.0.0.1/")
|
|
32
|
-
);
|
|
33
|
-
if (!tcpAddr) return null;
|
|
34
|
-
let resolved = shouldEnableDockerMap() ? industrialAddressMapper(tcpAddr) : tcpAddr;
|
|
35
|
-
if (!resolved || resolved === tcpAddr) {
|
|
36
|
-
const urlHost = new URL(url).hostname;
|
|
37
|
-
resolved = tcpAddr.replace(/\/ip4\/[^/]+/, `/ip4/${urlHost}`);
|
|
38
|
-
}
|
|
39
|
-
if (!resolved) return null;
|
|
40
|
-
resolved += resolved.includes("/p2p/") ? "" : `/p2p/${data.mesh.peerId}`;
|
|
41
|
-
return resolved;
|
|
42
|
-
} catch {
|
|
43
|
-
return null;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
function normalizeBootstrap(addr) {
|
|
47
|
-
const trimmed = addr.trim();
|
|
48
|
-
const dockerIpRegex = /\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/;
|
|
49
|
-
const loopbackRegex = /\/ip4\/127\.0\.0\.1/;
|
|
50
|
-
const physicalIpRegex = /\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;
|
|
51
|
-
if (dockerIpRegex.test(trimmed) || loopbackRegex.test(trimmed) || physicalIpRegex.test(trimmed)) {
|
|
52
|
-
const targetIp = "127.0.0.1";
|
|
53
|
-
const normalized = trimmed.replace(dockerIpRegex, `/ip4/${targetIp}`).replace(loopbackRegex, `/ip4/${targetIp}`).replace(physicalIpRegex, `/ip4/${targetIp}`);
|
|
54
|
-
if (normalized !== trimmed) {
|
|
55
|
-
log.info(
|
|
56
|
-
`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${normalized}`
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
return normalized;
|
|
60
|
-
}
|
|
61
|
-
return trimmed;
|
|
62
|
-
}
|
|
63
|
-
function industrialAddressMapper(addr) {
|
|
64
|
-
if (addr.includes("/ip4/172.20.0.10"))
|
|
65
|
-
return addr.replace(
|
|
66
|
-
/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,
|
|
67
|
-
"/ip4/127.0.0.1/tcp/13001"
|
|
68
|
-
);
|
|
69
|
-
if (addr.includes("/ip4/172.20.0.11"))
|
|
70
|
-
return addr.replace(
|
|
71
|
-
/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,
|
|
72
|
-
"/ip4/127.0.0.1/tcp/13003"
|
|
73
|
-
);
|
|
74
|
-
if (addr.includes("/ip4/172.20.0.12"))
|
|
75
|
-
return addr.replace(
|
|
76
|
-
/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,
|
|
77
|
-
"/ip4/127.0.0.1/tcp/13004"
|
|
78
|
-
);
|
|
79
|
-
if (addr.includes("/ip4/172.20.0.13"))
|
|
80
|
-
return addr.replace(
|
|
81
|
-
/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,
|
|
82
|
-
"/ip4/127.0.0.1/tcp/13005"
|
|
83
|
-
);
|
|
84
|
-
if (addr.includes("/ip4/127.0.0.1/tcp/4000") || addr.includes("/ip4/127.0.0.1/tcp/3000")) {
|
|
85
|
-
return null;
|
|
86
|
-
}
|
|
87
|
-
return addr;
|
|
88
|
-
}
|
|
89
|
-
function isDockerDemoHost(urlStr) {
|
|
90
|
-
try {
|
|
91
|
-
const u = new URL(urlStr);
|
|
92
|
-
return (u.hostname === "127.0.0.1" || u.hostname === "localhost") && (u.port === "13000" || u.port === "13001");
|
|
93
|
-
} catch {
|
|
94
|
-
return false;
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
function shouldEnableDockerMap() {
|
|
98
|
-
return process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test" || process.env.LIOP_DOCKER_MAP === "true" || process.env.LIOP_DEV_MODE === "true" || !!process.env.LIOP_NEXUS_URL && isDockerDemoHost(process.env.LIOP_NEXUS_URL);
|
|
99
|
-
}
|
|
100
|
-
async function main() {
|
|
101
|
-
if ((process.platform === "win32" || process.platform === "darwin") && !process.execArgv.includes("--use-system-ca") && !(process.env.NODE_OPTIONS ?? "").includes("--use-system-ca")) {
|
|
102
|
-
const { spawn } = await import('child_process');
|
|
103
|
-
const child = spawn(
|
|
104
|
-
process.execPath,
|
|
105
|
-
["--use-system-ca", ...process.argv.slice(1)],
|
|
106
|
-
{ stdio: "inherit", env: process.env }
|
|
107
|
-
);
|
|
108
|
-
child.on("exit", (code) => process.exit(code ?? 1));
|
|
109
|
-
child.on("error", () => process.exit(1));
|
|
110
|
-
await new Promise(() => {
|
|
111
|
-
});
|
|
112
|
-
return;
|
|
113
|
-
}
|
|
114
|
-
const buildTime = (/* @__PURE__ */ new Date()).toISOString();
|
|
115
|
-
log.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${buildTime}`);
|
|
116
|
-
const liopDir = path.join(os.homedir(), ".liop");
|
|
117
|
-
const identityPath = path.join(liopDir, "identity.json");
|
|
118
|
-
if (!fs.existsSync(liopDir)) {
|
|
119
|
-
fs.mkdirSync(liopDir, { recursive: true });
|
|
120
|
-
}
|
|
121
|
-
let bootstrapNodes = [];
|
|
122
|
-
const args = process.argv.slice(2);
|
|
123
|
-
if (args.length > 0) {
|
|
124
|
-
bootstrapNodes = args.filter((a) => a.startsWith("/"));
|
|
125
|
-
}
|
|
126
|
-
if (bootstrapNodes.length === 0) {
|
|
127
|
-
const searchDirs = [];
|
|
128
|
-
if (process.env.LIOP_BOOTSTRAP_FILE) {
|
|
129
|
-
log.warn(
|
|
130
|
-
"LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead."
|
|
131
|
-
);
|
|
132
|
-
const filePath = path.resolve(process.env.LIOP_BOOTSTRAP_FILE);
|
|
133
|
-
if (fs.existsSync(filePath)) {
|
|
134
|
-
const addr = fs.readFileSync(filePath, "utf8").trim();
|
|
135
|
-
if (addr) bootstrapNodes.push(normalizeBootstrap(addr));
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
searchDirs.push(
|
|
139
|
-
process.cwd(),
|
|
140
|
-
path.join(process.cwd(), "tests/infra/nexus-data"),
|
|
141
|
-
liopDir,
|
|
142
|
-
path.join(
|
|
143
|
-
path.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/, "$1"),
|
|
144
|
-
"../../tests/infra/nexus-data"
|
|
145
|
-
)
|
|
146
|
-
);
|
|
147
|
-
for (const dir of searchDirs) {
|
|
148
|
-
try {
|
|
149
|
-
if (fs.existsSync(dir)) {
|
|
150
|
-
const files = fs.readdirSync(dir);
|
|
151
|
-
const multiaddrFiles = files.filter((f) => f.endsWith(".multiaddr"));
|
|
152
|
-
for (const file of multiaddrFiles) {
|
|
153
|
-
const filePath = path.join(dir, file);
|
|
154
|
-
const addr = fs.readFileSync(filePath, "utf8").trim();
|
|
155
|
-
if (addr) {
|
|
156
|
-
const normalized = normalizeBootstrap(addr);
|
|
157
|
-
if (!bootstrapNodes.includes(normalized)) {
|
|
158
|
-
bootstrapNodes.push(normalized);
|
|
159
|
-
log.info(`[LIOP-Agent] \u2705 Loaded beacon: ${file} from ${dir}`);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
if (bootstrapNodes.length > 0) break;
|
|
164
|
-
}
|
|
165
|
-
} catch (_e) {
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
if (process.env.LIOP_NEXUS_URL) {
|
|
170
|
-
const nexusUrl = process.env.LIOP_NEXUS_URL;
|
|
171
|
-
log.info(
|
|
172
|
-
`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${nexusUrl} (Sources Found: ${bootstrapNodes.length})`
|
|
173
|
-
);
|
|
174
|
-
const resolved = await resolveBootstrapFromUrl(nexusUrl);
|
|
175
|
-
if (resolved) {
|
|
176
|
-
const normalized = normalizeBootstrap(resolved);
|
|
177
|
-
if (!bootstrapNodes.includes(normalized)) {
|
|
178
|
-
bootstrapNodes.push(normalized);
|
|
179
|
-
log.info(
|
|
180
|
-
`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${normalized}`
|
|
181
|
-
);
|
|
182
|
-
}
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
if (bootstrapNodes.length === 0 && process.env.LIOP_BOOTSTRAP) {
|
|
186
|
-
bootstrapNodes.push(process.env.LIOP_BOOTSTRAP.trim());
|
|
187
|
-
}
|
|
188
|
-
if (bootstrapNodes.length === 0) {
|
|
189
|
-
bootstrapNodes.push(
|
|
190
|
-
"/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
bootstrapNodes = bootstrapNodes.filter((addr) => {
|
|
194
|
-
try {
|
|
195
|
-
multiaddr(addr);
|
|
196
|
-
return true;
|
|
197
|
-
} catch {
|
|
198
|
-
log.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${addr}`);
|
|
199
|
-
return false;
|
|
200
|
-
}
|
|
201
|
-
});
|
|
202
|
-
if (bootstrapNodes.length === 0) {
|
|
203
|
-
log.info(
|
|
204
|
-
"[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."
|
|
205
|
-
);
|
|
206
|
-
log.info(
|
|
207
|
-
"[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."
|
|
208
|
-
);
|
|
209
|
-
}
|
|
210
|
-
const liopServer = new LiopServer({
|
|
211
|
-
name: "@nekzus/liop",
|
|
212
|
-
version: "1.0.0"
|
|
213
|
-
});
|
|
214
|
-
liopServer.enableZeroShotAutonomy();
|
|
215
|
-
const meshNode = new MeshNode({
|
|
216
|
-
identityPath,
|
|
217
|
-
bootstrapNodes,
|
|
218
|
-
addressMapper: shouldEnableDockerMap() ? industrialAddressMapper : void 0
|
|
219
|
-
});
|
|
220
|
-
await meshNode.start();
|
|
221
|
-
const router = new LiopMcpRouter(liopServer, meshNode);
|
|
222
|
-
router.onToolsChanged = () => {
|
|
223
|
-
process.stdout.write(
|
|
224
|
-
`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
225
|
-
`
|
|
226
|
-
);
|
|
227
|
-
process.stdout.write(
|
|
228
|
-
`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
229
|
-
`
|
|
230
|
-
);
|
|
231
|
-
};
|
|
232
|
-
setTimeout(() => {
|
|
233
|
-
const rtSize = meshNode.getRoutingTableSize?.() || 0;
|
|
234
|
-
log.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${rtSize}`);
|
|
235
|
-
router.refreshManifestCache(true).catch(() => {
|
|
236
|
-
});
|
|
237
|
-
}, 2e3);
|
|
238
|
-
const POLL_BASE_MS = 1e4;
|
|
239
|
-
const POLL_MAX_MS = 12e4;
|
|
240
|
-
let pollIntervalMs = POLL_BASE_MS;
|
|
241
|
-
const scheduleAdaptivePoll = () => {
|
|
242
|
-
setTimeout(async () => {
|
|
243
|
-
const prevSize = router.getCacheSize();
|
|
244
|
-
await router.refreshManifestCache(true).catch(() => {
|
|
245
|
-
});
|
|
246
|
-
const newSize = router.getCacheSize();
|
|
247
|
-
if (newSize !== prevSize) {
|
|
248
|
-
pollIntervalMs = POLL_BASE_MS;
|
|
249
|
-
log.info(
|
|
250
|
-
`[LIOP-Agent] Topology change detected (${prevSize} \u2192 ${newSize}). Resetting poll to ${POLL_BASE_MS / 1e3}s.`
|
|
251
|
-
);
|
|
252
|
-
} else {
|
|
253
|
-
pollIntervalMs = Math.min(
|
|
254
|
-
Math.round(pollIntervalMs * 1.5),
|
|
255
|
-
POLL_MAX_MS
|
|
256
|
-
);
|
|
257
|
-
}
|
|
258
|
-
scheduleAdaptivePoll();
|
|
259
|
-
}, pollIntervalMs);
|
|
260
|
-
};
|
|
261
|
-
scheduleAdaptivePoll();
|
|
262
|
-
const readline = await import('readline');
|
|
263
|
-
const rl = readline.createInterface({
|
|
264
|
-
input: process.stdin,
|
|
265
|
-
terminal: false
|
|
266
|
-
});
|
|
267
|
-
process.stdout.on("error", (err) => {
|
|
268
|
-
if (err.code === "EPIPE") {
|
|
269
|
-
process.exit(0);
|
|
270
|
-
}
|
|
271
|
-
});
|
|
272
|
-
rl.on("line", async (line) => {
|
|
273
|
-
const trimmed = line.trim();
|
|
274
|
-
if (!trimmed) return;
|
|
275
|
-
try {
|
|
276
|
-
const request = JSON.parse(trimmed);
|
|
277
|
-
if (request.method) {
|
|
278
|
-
const response = await router.dispatch(request);
|
|
279
|
-
if (response) {
|
|
280
|
-
process.stdout.write(`${JSON.stringify(response)}
|
|
281
|
-
`);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
} catch (_err) {
|
|
285
|
-
}
|
|
286
|
-
});
|
|
287
|
-
rl.on("close", () => {
|
|
288
|
-
process.exit(0);
|
|
289
|
-
});
|
|
290
|
-
log.info(`[LIOP-Agent] Guarding Claude Desktop via STDIO.`);
|
|
291
|
-
log.info(
|
|
292
|
-
`[LIOP-Agent] P2P Mesh: Joined (${bootstrapNodes.length} bootstraps)`
|
|
293
|
-
);
|
|
294
|
-
log.info("[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0");
|
|
295
|
-
process.on("SIGINT", async () => {
|
|
296
|
-
await meshNode.stop();
|
|
297
|
-
process.exit(0);
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
main().catch((err) => {
|
|
301
|
-
log.error(`[LIOP-Agent] Fatal Error: ${err.message}`);
|
|
302
|
-
process.exit(1);
|
|
303
|
-
});
|
|
304
|
-
//# sourceMappingURL=agent.js.map
|
|
2
|
+
import {b as b$2,a as a$3}from'../chunk-2XHSALII.js';import {a as a$4}from'../chunk-N35BC62H.js';import {m}from'../chunk-YD2AF2M6.js';import'../chunk-MQ5SU26J.js';import {a as a$2}from'../chunk-LM26HOJ6.js';import'../chunk-6KFKO6ZX.js';import'../chunk-TKLRW52V.js';import'../chunk-Y675R34Z.js';import'../chunk-XLVEDKM6.js';import'../chunk-2ZYX736J.js';import'../chunk-ECRS6N33.js';import'../chunk-ZZMSFCJP.js';import {g,f,d}from'../chunk-GWVSCZUS.js';import'../chunk-6VK2XALI.js';import'../chunk-FTF6AMF6.js';import'../chunk-YLCNV764.js';import {a as a$1}from'../chunk-V35CXJQN.js';import {b as b$1}from'../chunk-3WRKTVOF.js';import {a}from'../chunk-AYDF3IFZ.js';import*as L from'fs';import*as G from'os';import*as R from'path';import*as N from'readline';import {multiaddr}from'@multiformats/multiaddr';var b={name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}};async function F(e){try{let s=e.endsWith("/health")?e:`${e}/health`,a=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!a.ok)return null;let n=await a.json();if(!n.mesh?.multiaddrs?.length||!n.mesh?.peerId)return null;let c=n.mesh.multiaddrs.find(t=>t.includes("/tcp/")&&!t.includes("/ws")&&!t.includes("/ip4/127.0.0.1/"));if(!c)return null;let i=C()?k(c):c;if(!i||i===c){let t=new URL(e).hostname;i=c.replace(/\/ip4\/[^/]+/,`/ip4/${t}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${n.mesh.peerId}`,i):null}catch{return null}}a(F,"resolveBootstrapFromUrl");function V(e){let s=e.trim(),a=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,n=/\/ip4\/127\.0\.0\.1/,c=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(a.test(s)||n.test(s)||c.test(s)){let i="127.0.0.1",t=s.replace(a,`/ip4/${i}`).replace(n,`/ip4/${i}`).replace(c,`/ip4/${i}`);return t!==s&&b$1.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${t}`),t}return s}a(V,"normalizeBootstrap");function k(e){return e.includes("/ip4/172.23.0.10")?e.replace(/\/ip4\/172\.23\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15001"):e.includes("/ip4/172.23.0.20")?e.replace(/\/ip4\/172\.23\.0\.20\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15011"):e.includes("/ip4/172.21.0.13")?e.replace(/\/ip4\/172\.21\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15031"):e.includes("/ip4/172.21.0.14")?e.replace(/\/ip4\/172\.21\.0\.14\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15041"):e.includes("/ip4/172.20.0.10")?e.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):e.includes("/ip4/172.20.0.11")?e.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):e.includes("/ip4/172.20.0.12")?e.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):e.includes("/ip4/172.20.0.13")?e.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):e.includes("/ip4/127.0.0.1/tcp/4000")||e.includes("/ip4/127.0.0.1/tcp/3000")?null:e}a(k,"industrialAddressMapper");function q(e){try{let s=new URL(e);return (s.hostname==="127.0.0.1"||s.hostname==="localhost")&&(s.port==="13000"||s.port==="13001"||s.port==="15000"||s.port==="15018")}catch{return false}}a(q,"isDockerDemoHost");function C(){return process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||!!process.env.LIOP_NEXUS_URL&&q(process.env.LIOP_NEXUS_URL)}a(C,"shouldEnableDockerMap");async function X(e){let s=[],a=process.argv.slice(2);if(a.length>0&&(s=a.filter(n=>n.startsWith("/"))),process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL){let n=process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL;if(n){let c=await F(n);if(c){let i=V(c);s.includes(i)||(s.push(i),b$1.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${i}`));}}}if(s.length===0){let n=[process.cwd(),R.join(process.cwd(),"tests/infra/nexus-data"),e,R.join(R.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data")];for(let c of n)try{if(L.existsSync(c)){let t=L.readdirSync(c).filter(l=>l.endsWith(".multiaddr"));for(let l of t){let d=R.join(c,l),r=L.readFileSync(d,"utf8").trim();if(r){let m=V(r);s.includes(m)||(s.push(m),b$1.info(`[LIOP-Agent] \u2705 Loaded beacon: ${l} from ${c}`));}}if(s.length>0)break}}catch{}}return s.length===0&&process.env.LIOP_BOOTSTRAP&&s.push(process.env.LIOP_BOOTSTRAP.trim()),s.filter(n=>{try{return multiaddr(n),!0}catch{return false}})}a(X,"resolveBootstrapNodes");async function _(e,s,a$1){let n=a(async t=>{let l={"Content-Type":"application/json"};t&&(l.Authorization=`Bearer ${t}`),s.method&&(l["Mcp-Method"]=s.method);let d=s.params;return d?.name&&(l["Mcp-Name"]=d.name),await fetch(e,{method:"POST",headers:l,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)})},"send"),c;try{c=await a$1.getToken();}catch(t){b$1.warn(`[LIOP-Agent] Token acquisition warning: ${t instanceof Error?t.message:String(t)}`);}let i=await n(c);if(i.status===401&&c){b$1.info("[LIOP-Agent] \u{1F504} 401 received from Gateway. Refreshing token and retrying..."),a$1.invalidate();try{c=await a$1.getToken(),i=await n(c);}catch{}}if(!i.ok){let t=await i.text(),l=null;try{l=JSON.parse(t);}catch{}let d=l?.error;return {jsonrpc:"2.0",id:s.id,error:{code:d?.code??-32603,message:d?.message??`Gateway returned HTTP ${i.status}: ${t}`}}}return await i.json()}a(_,"forwardToGateway");async function z(e,s,a){b$1.info(`[LIOP-Agent] \u{1F6E1}\uFE0F Running in ADAPTIVE GATEWAY MODE -> ${e.mcpEndpoint}`),a.registerLocalTool(b),a.registerGatewayTools(e.tools.map(t=>({name:t})),e.mcpEndpoint);let n=e.tools.length,c=setInterval(async()=>{try{let t=await fetch(e.healthEndpoint,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(t.ok){let l=await t.json();l.tools&&l.tools.length!==n&&(b$1.info(`[LIOP-Agent] Gateway tools topology updated (${n} -> ${l.tools.length})`),n=l.tools.length,a.registerGatewayTools(l.tools.map(d=>({name:d})),e.mcpEndpoint),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
3
|
+
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
4
|
+
`));}}catch{}},15e3),i=N.createInterface({input:process.stdin,terminal:false});process.stdout.on("error",t=>{t.code==="EPIPE"&&(clearInterval(c),process.exit(0));}),i.on("line",async t=>{let l=t.trim();if(!l)return;let d$1;try{d$1=JSON.parse(l);}catch{return}let{id:r,method:m}=d$1;if(m==="server/discover"){let o={jsonrpc:"2.0",id:r,result:{resultType:"complete",supportedVersions:["2026-07-28","2025-11-25"],capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-adaptive-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(o)}
|
|
5
|
+
`);return}if(m==="initialize"){let u=(d$1.params?.protocolVersion??d$1.params?._meta?.["io.modelcontextprotocol/protocolVersion"])==="2026-07-28"?"2026-07-28":"2025-11-25",f={jsonrpc:"2.0",id:r,result:{protocolVersion:u,capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-adaptive-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(f)}
|
|
6
|
+
`);return}if(!(m==="notifications/initialized"||m==="notifications/cancelled")){if(m==="ping"){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:r,result:{}})}
|
|
7
|
+
`);return}if(m==="resources/templates/list"){let o={jsonrpc:"2.0",id:r,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resourceTemplates:[]}};process.stdout.write(`${JSON.stringify(o)}
|
|
8
|
+
`);return}if(m==="subscriptions/listen"){let o={jsonrpc:"2.0",id:r,result:{resultType:"complete"}};process.stdout.write(`${JSON.stringify(o)}
|
|
9
|
+
`);return}if(m==="tools/call"){let o=d$1.params;if(o?.arguments&&(o.arguments=g(o.arguments)),o?.name){let u=f[o.name]||o.name;o.name=u;}if(o?.name==="LiopMeshStatus"){let u={jsonrpc:"2.0",id:r,result:{content:[{type:"text",text:JSON.stringify({mode:"adaptive-gateway",gatewayUrl:e.baseUrl,tier:e.tier,toolsAvailable:a.getAllToolDefinitions().length,authenticated:true,status:"ONLINE"})}]}};process.stdout.write(`${JSON.stringify(u)}
|
|
10
|
+
`);return}}try{let o=await _(e.mcpEndpoint,d$1,s);if(m==="tools/list"&&o.result&&typeof o.result=="object"){let u=o.result,f$1=u.tools;if(Array.isArray(f$1)){f$1.some(y=>y.name==="LiopMeshStatus")||f$1.unshift(b);for(let[y,h]of Object.entries(f)){let S=f$1.find(P=>P.name===h);S&&!f$1.some(P=>P.name===y)&&f$1.push({...S,name:y,description:`[Alias -> ${h}] ${S.description||""}`.trim()});}a.registerGatewayTools(f$1,e.mcpEndpoint);}d(d$1)||(u.resultType||(u.resultType="complete"),u.ttlMs||(u.ttlMs=3e5),u.cacheScope||(u.cacheScope="public"));}process.stdout.write(`${JSON.stringify(o)}
|
|
11
|
+
`);}catch(o){if(m==="tools/list"){let f=d(d$1)?{tools:a.getAllToolDefinitions()}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:a.getAllToolDefinitions()},p={jsonrpc:"2.0",id:r,result:f};process.stdout.write(`${JSON.stringify(p)}
|
|
12
|
+
`);}else {let u={jsonrpc:"2.0",id:r,error:{code:-32603,message:`Forwarding failed: ${o instanceof Error?o.message:String(o)}`}};process.stdout.write(`${JSON.stringify(u)}
|
|
13
|
+
`);}}}}),i.on("close",()=>{clearInterval(c),process.exit(0);});}a(z,"runGatewayMode");async function B(e){b$1.info(`[LIOP-Agent] \u{1F310} Running in P2P MESH MODE (${e.bootstrapNodes.length} bootstraps)`);let s=new m({name:"@nekzus/liop",version:"2.5.0"});s.enableZeroShotAutonomy();let a$3=new a$1({identityPath:e.identityPath,bootstrapNodes:e.bootstrapNodes,addressMapper:C()?k:void 0});await a$3.start();let n=new a$2(s,a$3);n.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
14
|
+
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
15
|
+
`);},setTimeout(()=>{n.refreshManifestCache(true).catch(()=>{});},2e3);let c=1e4,i=12e4,t=c,l=a(()=>{setTimeout(async()=>{let r=n.getCacheSize();await n.refreshManifestCache(true).catch(()=>{}),n.getCacheSize()!==r?t=c:t=Math.min(Math.round(t*1.5),i),l();},t);},"scheduleAdaptivePoll");l();let d=N.createInterface({input:process.stdin,terminal:false});process.stdout.on("error",r=>{r.code==="EPIPE"&&process.exit(0);}),d.on("line",async r=>{let m=r.trim();if(m)try{let o=JSON.parse(m);if(o.method){let u=await n.dispatch(o);u&&process.stdout.write(`${JSON.stringify(u)}
|
|
16
|
+
`);}}catch{}}),d.on("close",()=>process.exit(0)),process.on("SIGINT",async()=>{await a$3.stop(),process.exit(0);});}a(B,"runMeshMode");async function Z(e,s,a){let n=e.gateway,c=e.mesh;if(!n||!c)return n?z(n,s,a):c?B(c):void 0;b$1.info(`[LIOP-Agent] \u26A1 Running in HYBRID MODE (Gateway: ${n.baseUrl} + Mesh P2P)`),a.registerLocalTool(b),a.registerGatewayTools(n.tools.map(r=>({name:r})),n.mcpEndpoint);let i=null,t=null,l=(async()=>{try{let r=new m({name:"@nekzus/liop-hybrid",version:"2.5.0"});r.enableZeroShotAutonomy(),i=new a$1({identityPath:c.identityPath,bootstrapNodes:c.bootstrapNodes,addressMapper:C()?k:void 0}),await i.start(),t=new a$2(r,i),t.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
17
|
+
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
18
|
+
`);},await t.refreshManifestCache(!0).catch(()=>{}),b$1.info("[LIOP-Agent] \u2705 Background P2P Mesh initialization completed.");}catch(r){b$1.warn(`[LIOP-Agent] Background Mesh init warning: ${r instanceof Error?r.message:String(r)}`);}})(),d$1=N.createInterface({input:process.stdin,terminal:false});process.stdout.on("error",r=>{r.code==="EPIPE"&&process.exit(0);}),d$1.on("line",async r=>{let m=r.trim();if(!m)return;let o;try{o=JSON.parse(m);}catch{return}let{id:u,method:f$1}=o;if(f$1==="server/discover"){let p={jsonrpc:"2.0",id:u,result:{resultType:"complete",supportedVersions:["2026-07-28","2025-11-25"],capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-hybrid-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(p)}
|
|
19
|
+
`);return}if(f$1==="initialize"){let y=(o.params?.protocolVersion??o.params?._meta?.["io.modelcontextprotocol/protocolVersion"])==="2026-07-28"?"2026-07-28":"2025-11-25",h={jsonrpc:"2.0",id:u,result:{protocolVersion:y,capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-hybrid-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(h)}
|
|
20
|
+
`);return}if(!(f$1==="notifications/initialized"||f$1==="notifications/cancelled")){if(f$1==="ping"){process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:u,result:{}})}
|
|
21
|
+
`);return}if(f$1==="resources/templates/list"){let p={jsonrpc:"2.0",id:u,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resourceTemplates:[]}};process.stdout.write(`${JSON.stringify(p)}
|
|
22
|
+
`);return}if(f$1==="subscriptions/listen"){let p={jsonrpc:"2.0",id:u,result:{resultType:"complete"}};process.stdout.write(`${JSON.stringify(p)}
|
|
23
|
+
`);return}if(f$1==="tools/call"){let p=o.params;p?.arguments&&(p.arguments=g(p.arguments));let y=p?.name||"",h=f[y]||y;p?.name&&(p.name=h);let S=h;if(a.resolve(S)?.provider==="http-gateway"){let I=Date.now();try{let g=await _(n.mcpEndpoint,o,s);a.recordSuccess(S,Date.now()-I),process.stdout.write(`${JSON.stringify(g)}
|
|
24
|
+
`);return}catch{a.recordFailure(S),b$1.warn(`[LIOP-Agent] Gateway call failed for '${S}'. Checking P2P fallback...`);}}if(await l,t){let I=await t.dispatch(o);I&&process.stdout.write(`${JSON.stringify(I)}
|
|
25
|
+
`);return}}if(f$1==="tools/list"){let p=[];try{let T=(await _(n.mcpEndpoint,o,s)).result;Array.isArray(T?.tools)&&(p=T.tools,a.registerGatewayTools(p,n.mcpEndpoint));}catch{p=a.getAllToolDefinitions();}let y=[];if(t){let T=(await t.dispatch(o))?.result;Array.isArray(T?.tools)&&(y=T.tools);}let h=new Map;h.set("LiopMeshStatus",b);for(let g of p)h.set(g.name,g);for(let g of y)h.has(g.name)||h.set(g.name,g);for(let[g,T]of Object.entries(f)){let E=h.get(T);E&&!h.has(g)&&h.set(g,{...E,name:g,description:`[Alias -> ${T}] ${E.description||""}`.trim()});}let S=Array.from(h.values()).sort((g,T)=>g.name.localeCompare(T.name)),I=d(o)?{tools:S}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:S};process.stdout.write(`${JSON.stringify({jsonrpc:"2.0",id:u,result:I})}
|
|
26
|
+
`);return}try{let p=await _(n.mcpEndpoint,o,s);if(!d(o)&&p.result&&typeof p.result=="object"){let y=p.result;y.resultType||(y.resultType="complete");}process.stdout.write(`${JSON.stringify(p)}
|
|
27
|
+
`);}catch{if(await l,t){let p=await t.dispatch(o);p&&process.stdout.write(`${JSON.stringify(p)}
|
|
28
|
+
`);}}}}),d$1.on("close",async()=>{i&&await i.stop(),process.exit(0);});}a(Z,"runHybridMode");async function W(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:u}=await import('child_process'),f=u(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});f.on("exit",p=>process.exit(p??1)),f.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let e=new Date().toISOString();b$1.info(`[LIOP-Agent] \u{1F680} Version 2.5.0 (Adaptive Zero-Config) | Build: ${e}`);let s=R.join(G.homedir(),".liop"),a=R.join(s,"identity.json");L.existsSync(s)||L.mkdirSync(s,{recursive:true});let n=await X(s),c=process.env.LIOP_BLG_URL,i=process.env.LIOP_NEXUS_URL,t=process.env.LIOP_CLIENT_ID||process.env.LIOP_OAUTH_CLIENT_ID||"liop-agent",l=process.env.LIOP_CLIENT_SECRET||process.env.LIOP_OAUTH_CLIENT_SECRET||"dev-secret-change-me",d=process.env.LIOP_TOKEN||process.env.LIOP_OAUTH_TOKEN,r=await b$2({blgUrl:c,nexusUrl:i,clientId:t,clientSecret:l,staticToken:d,bootstrapNodes:n,identityPath:a}),m=new a$3,o=new a$4({tokenEndpoint:r.gateway?.tokenEndpoint||`${i||"http://127.0.0.1:15000"}/oidc/token`,clientId:t,clientSecret:l,audience:r.gateway?.audience,scopes:r.gateway?.scopes,staticToken:d});switch(r.mode){case "gateway":if(!r.gateway)throw new Error("Topology probe indicated gateway mode without gateway info.");await z(r.gateway,o,m);break;case "mesh":if(!r.mesh)throw new Error("Topology probe indicated mesh mode without mesh info.");await B(r.mesh);break;case "hybrid":await Z(r,o,m);break}}a(W,"main");W().catch(e=>{b$1.error(`[LIOP-Agent] Fatal Error: ${e.message}`),process.exit(1);});//# sourceMappingURL=agent.js.map
|
|
305
29
|
//# sourceMappingURL=agent.js.map
|
package/dist/bridge.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
|
-
import { L as LiopServer, a as LiopServerOptions } from './index-
|
|
2
|
+
import { L as LiopServer, a as LiopServerOptions } from './index-ByzjpRCk.js';
|
|
3
3
|
import 'zod';
|
|
4
|
-
import './
|
|
5
|
-
import './types-
|
|
4
|
+
import './node-Djzm6UYd.js';
|
|
5
|
+
import './types-29zv9X1V.js';
|
|
6
|
+
import './zk-DzYNWBgo.js';
|
|
6
7
|
import 'jose';
|
|
7
8
|
|
|
8
9
|
/**
|
package/dist/bridge.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
import './chunk-PYKRQAER.js';
|
|
3
|
-
import './chunk-72MNYFR6.js';
|
|
4
|
-
//# sourceMappingURL=bridge.js.map
|
|
1
|
+
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-P6IJ3VBD.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=bridge.js.map
|
|
5
2
|
//# sourceMappingURL=bridge.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {f}from'./chunk-GWVSCZUS.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';var m=class r{static{a(this,"RoutingTable");}routes=new Map;static MAX_FAILURES=5;registerGatewayTools(e,t,n=true){for(let i of e){let o=this.routes.get(i.name);this.routes.set(i.name,{name:i.name,provider:"http-gateway",endpoint:t,description:i.description??o?.description,inputSchema:i.inputSchema??o?.inputSchema,latencyMs:o?.latencyMs??0,failCount:0,lastSuccess:o?.lastSuccess??Date.now(),authRequired:n});}b.info(`[RoutingTable] Registered ${e.length} tool(s) via HTTP Gateway (${t})`);}registerMeshTools(e,t,n=false){for(let i of e){let o=this.routes.get(i.name);o&&o.provider==="http-gateway"&&o.failCount===0||this.routes.set(i.name,{name:i.name,provider:"p2p-grpc",endpoint:t,description:i.description??o?.description,inputSchema:i.inputSchema??o?.inputSchema,latencyMs:o?.latencyMs??0,failCount:0,lastSuccess:o?.lastSuccess??Date.now(),authRequired:n});}b.info(`[RoutingTable] Registered ${e.length} tool(s) via P2P Mesh gRPC (${t})`);}registerLocalTool(e){this.routes.set(e.name,{name:e.name,provider:"local",endpoint:"in-process",description:e.description,inputSchema:e.inputSchema,latencyMs:0,failCount:0,lastSuccess:Date.now(),authRequired:false});}resolve(e){let t=f[e]||e,n=this.routes.get(t)??this.routes.get(e);if(n)return n.failCount>=r.MAX_FAILURES&&b.warn(`[RoutingTable] Tool '${e}' route has tripped circuit breaker (${n.failCount} consecutive failures).`),n}recordSuccess(e,t){let n=this.routes.get(e);n&&(n.failCount=0,n.latencyMs=t,n.lastSuccess=Date.now());}recordFailure(e){let t=this.routes.get(e);t&&(t.failCount+=1,b.warn(`[RoutingTable] Failure recorded for tool '${e}' (failCount: ${t.failCount})`));}getAllToolDefinitions(){let e=[];for(let t of this.routes.values())e.push({name:t.name,description:t.description,inputSchema:t.inputSchema});return e.sort((t,n)=>t.name.localeCompare(n.name))}getRoute(e){return this.routes.get(e)}size(){return this.routes.size}clear(){this.routes.clear();}};async function y(r,e){let t=r.replace(/\/+$/,""),n=`${t}/health`;try{b.info(`[TopologyProbe] Probing candidate Gateway at: ${n}`);let i=await fetch(n,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return b.info(`[TopologyProbe] Probe failed at ${n} [HTTP ${i.status}]`),null;let o=await i.json();if(o.status!=="healthy")return null;let u=o.auth?.issuer||"",c=o.auth?.token_endpoint||"",d=e.audience||"urn:liop:mesh:api",h=["liop:tools:list","liop:tools:call","liop:resources:read","liop:schema:read","liop:mesh:query"];try{let a=`${t}/.well-known/oauth-protected-resource`,g=await fetch(a,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(2e3)});if(g.ok){let l=await g.json();l.resource&&(d=l.resource),l.authorization_servers?.length&&(u=l.authorization_servers[0]),l.scopes_supported?.length&&(h=l.scopes_supported);}}catch{}if(!c&&u&&(c=`${u.endsWith("/oidc")?u:`${u}/oidc`}/token`),c)try{let a=new URL(c);if(e.nexusUrl){let g=e.nexusUrl.replace(/\/+$/,""),l=new URL(g).host;a.host=l,c=a.toString();}else (a.hostname==="nexus"||a.hostname==="nexus-prod"||a.hostname.startsWith("172."))&&t.includes("127.0.0.1")&&(a.host="127.0.0.1:15000",c=a.toString());}catch{}return b.info(`[TopologyProbe] \u2705 Verified Gateway at ${t} (Tools: ${o.tools?.length??0}, Tier: ${o.topology?.tier??2})`),{baseUrl:t,mcpEndpoint:`${t}/mcp`,healthEndpoint:`${t}/health`,tokenEndpoint:c,issuer:u,audience:d,scopes:h,tools:o.tools||[],tier:o.topology?.tier??2}}catch(i){return b.info(`[TopologyProbe] Gateway probe unreachable at ${t}: ${i instanceof Error?i.message:String(i)}`),null}}a(y,"probeGatewayUrl");async function U(r={}){b.info("[TopologyProbe] Starting adaptive network topology discovery...");let e=null;if(r.blgUrl&&(e=await y(r.blgUrl,r)),!e&&(r.autoProbeLocal??true)){let i=["http://127.0.0.1:15018","http://127.0.0.1:15000","http://127.0.0.1:13000"];for(let o of i)if(!(r.blgUrl&&o.includes(new URL(r.blgUrl).port))&&(e=await y(o,r),e))break}let t=r.bootstrapNodes||[],n=t.length>0;return e&&n?(b.info(`[TopologyProbe] \u26A1 Mode Determined: HYBRID (Gateway: ${e.baseUrl} + ${t.length} P2P bootstraps)`),{mode:"hybrid",gateway:e,mesh:{bootstrapNodes:t,identityPath:r.identityPath}}):e?(b.info(`[TopologyProbe] \u{1F680} Mode Determined: GATEWAY (Zero-P2P overhead, direct to ${e.baseUrl})`),{mode:"gateway",gateway:e}):(b.info(`[TopologyProbe] \u{1F310} Mode Determined: MESH (Standard P2P DHT, Bootstraps: ${t.length})`),{mode:"mesh",mesh:{bootstrapNodes:t,identityPath:r.identityPath}})}a(U,"probeTopology");
|
|
2
|
+
export{m as a,U as b};//# sourceMappingURL=chunk-2XHSALII.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-2XHSALII.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';import {ml_dsa65}from'@noble/post-quantum/ml-dsa.js';var n={PUBLIC_KEY_BYTES:1952,SECRET_KEY_BYTES:4032,SIGNATURE_BYTES:3309,DEFAULT_CONTEXT:new TextEncoder().encode("LIOP-FIPS204-ML-DSA-65")};function S(r){return typeof r=="string"?new TextEncoder().encode(r):r}a(S,"normalizeMessage");function E(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return `[${r.map(E).join(",")}]`;let t=r;return `{${Object.keys(t).filter(e=>t[e]!==void 0).sort().map(e=>`${JSON.stringify(e)}:${E(t[e])}`).join(",")}}`}a(E,"canonicalizeJson");var f={PUBLIC_KEY_BYTES:n.PUBLIC_KEY_BYTES,SECRET_KEY_BYTES:n.SECRET_KEY_BYTES,SIGNATURE_BYTES:n.SIGNATURE_BYTES,generateKeyPair(r){if(r&&r.length!==32)throw new Error(`ML-DSA-65 seed must be exactly 32 bytes (Received: ${r.length})`);let t=ml_dsa65.keygen(r);return {publicKey:t.publicKey,secretKey:t.secretKey}},getPublicKey(r){if(r.length!==n.SECRET_KEY_BYTES)throw new Error(`ML-DSA-65 Secret Key must be exactly ${n.SECRET_KEY_BYTES} bytes (Received: ${r.length})`);return ml_dsa65.getPublicKey(r)},importPublicKey(r){if(r.length!==n.PUBLIC_KEY_BYTES)throw new Error(`ML-DSA-65 Public Key must be exactly ${n.PUBLIC_KEY_BYTES} bytes (Received: ${r.length})`);return r},sign(r,t,i){if(t.length!==n.SECRET_KEY_BYTES)throw new Error(`ML-DSA-65 Secret Key must be exactly ${n.SECRET_KEY_BYTES} bytes (Received: ${t.length})`);let s=S(r),e=i??n.DEFAULT_CONTEXT;return ml_dsa65.sign(s,t,{context:e})},verify(r,t,i,s){if(r.length!==n.SIGNATURE_BYTES||i.length!==n.PUBLIC_KEY_BYTES)return false;try{let e=S(t),c=s??n.DEFAULT_CONTEXT;return ml_dsa65.verify(r,e,i,{context:c})}catch{return false}},signManifest(r,t,i){let{pqcSignature:s,pqcPublicKey:e,...c}=r,u=E(c),y=this.sign(u,t);return {signature:Buffer.from(y).toString("base64"),publicKey:Buffer.from(i).toString("base64")}},verifyManifest(r,t,i){try{let s=Buffer.from(t,"base64"),e=Buffer.from(i,"base64"),{pqcSignature:c,pqcPublicKey:u,...y}=r,g=E(y);return this.verify(s,g,e)}catch{return false}}};export{n as a,f as b};//# sourceMappingURL=chunk-2ZYX736J.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-2ZYX736J.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';var i=class o{static{a(this,"LiopLogger");}static instance;level="info";interceptor;_isIntercepting=false;constructor(){this.setLevelFromEnv();}static getInstance(){return o.instance||(o.instance=new o),o.instance}setLevelFromEnv(){let e=process.env.LIOP_LOG_LEVEL?.toLowerCase();e==="silent"||e==="error"||e==="warn"||e==="info"||e==="debug"?this.level=e:this.level="info";}setLevel(e){this.level=e;}setInterceptor(e){this.interceptor=e;}shouldLog(e){let t={silent:0,error:1,warn:2,info:3,debug:4};return t[this.level]>=t[e]}formatMessage(e,t){return `[${new Date().toISOString()}] [${e}] ${t}`}emitToInterceptor(e,t,r){if(!this.interceptor||this._isIntercepting)return;this._isIntercepting=true;let c=Object.freeze({timestamp:new Date().toISOString(),level:e,message:t,args:Object.freeze([...r])});try{let n=this.interceptor(c);n&&typeof n=="object"&&"catch"in n&&n.catch(()=>{});}catch{}finally{this._isIntercepting=false;}}error(e,...t){if(this.shouldLog("error")){let r=this.formatMessage("ERROR",e);console.error(r,...t),this.emitToInterceptor("error",r,t);}}warn(e,...t){if(this.shouldLog("warn")){let r=this.formatMessage("WARN",e);console.error(r,...t),this.emitToInterceptor("warn",r,t);}}info(e,...t){if(this.shouldLog("info")){let r=this.formatMessage("INFO",e);console.error(r,...t),this.emitToInterceptor("info",r,t);}}debug(e,...t){if(this.shouldLog("debug")){let r=this.formatMessage("DEBUG",e);console.error(r,...t),this.emitToInterceptor("debug",r,t);}}},g=i.getInstance();export{i as a,g as b};//# sourceMappingURL=chunk-3WRKTVOF.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-3WRKTVOF.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b as b$1}from'./chunk-TKLRW52V.js';import {p,l,n}from'./chunk-ZZMSFCJP.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import v from'crypto';import*as T from'fs';import {createRequire}from'module';import d from'path';import {fileURLToPath,pathToFileURL}from'url';import {Piscina}from'piscina';var H=fileURLToPath(import.meta.url),P=d.dirname(H),w=class f{static{a(this,"LiopVerifier");}static zkWorkerPool=null;static vkeyRegistry=new Map;static registerVKey(e,i){f.vkeyRegistry.set(e,i);try{p.set(f.vkeyRegistry.size);}catch{}}static getRegisteredVKey(e){return f.vkeyRegistry.get(e)}getZkPool(){if(!f.zkWorkerPool){let e=import.meta.url.endsWith(".ts"),i=e?".ts":".js",n=[];if(e)try{let o=createRequire(import.meta.url).resolve("tsx/package.json");n=["--import",pathToFileURL(d.join(d.dirname(o),"dist","loader.mjs")).href];}catch{n=["--import","tsx"];}let r=[d.resolve(P,`./workers/zk-verifier${i}`),d.resolve(P,`../workers/zk-verifier${i}`)],l=r.find(t=>T.existsSync(t))||r[1];f.zkWorkerPool=new Piscina({filename:l,minThreads:1,maxThreads:2,idleTimeout:3e4,execArgv:n}),f.zkWorkerPool.run({action:"warmup"}).catch(t=>{b.debug(`[LiopVerifier] Verification pool warm-up ping failed: ${t.message}`);});}return f.zkWorkerPool}async verifyZkReceipt(e,i,n$1,r,l$1){let t=this.getZkPool();if(!t)throw new Error("Worker pool initialization failed");let o,a=l$1,m,u,p;Buffer.isBuffer(r)?o=r:r&&typeof r=="object"&&(o=r.sessionSecret,r.expectedOutput!==void 0&&(a=r.expectedOutput),m=r.guestImageIdHex,u=r.vkeyRaw,p=r.zkPolicy,!u&&r.circuitName&&(u=f.getRegisteredVKey(r.circuitName)));let E=performance.now(),s=await t.run({action:"verify_receipt",logicPayload:new Uint8Array(e),remoteImageIdHex:i,guestImageIdHex:m,zkReceipt:new Uint8Array(n$1),sessionSecret:o?new Uint8Array(o):void 0,vkeyRaw:u?new Uint8Array(u):void 0,expectedOutput:a,zkPolicy:p}),b$1=performance.now()-E;try{l.observe({status:s.verified?"verified":"failed",proof_type:s.proofType||"unknown"},b$1),s.verified&&s.proofType&&n.inc({proof_type:s.proofType});}catch{}return s.verified?(b.info(`[LiopVerifier] ${s.message}`),true):(b.error(`[LiopVerifier] FAILED: ${s.message}`),false)}async verifyTeeAttestationDetailed(e,i={}){let n=i.policy??"preferred";if(n==="none")return {verified:true,platform:"none",message:"TEE Attestation bypassed: Policy set to 'none'."};if(!e||e.length===0)return n==="required"?{verified:false,platform:"none",message:"TEE Policy Violation: Hardware TEE attestation required, but no attestation report was provided."}:{verified:true,platform:"none",message:"TEE Attestation skipped: Empty report allowed under non-strict policy."};let r=null;if(i.expectedPublicKey||i.expectedNonce){let t=[];i.expectedPublicKey&&t.push(Buffer.from(i.expectedPublicKey)),i.expectedNonce&&t.push(Buffer.from(i.expectedNonce)),r=v.createHash("sha256").update(Buffer.concat(t)).digest();}if(e.length>=4&&e[0]===84&&e[1]===69&&e[2]===69&&e[3]===83)return n==="required"&&!i.allowSynthetic?{verified:false,platform:"synthetic",message:"TEE Policy Violation: Hardware TEE attestation required, but received synthetic mesh report."}:{verified:true,platform:"synthetic",message:"Synthetic TEE Attestation Verified (Mesh PSK mode)."};if(e.length>=672){let t=e.subarray(80,144),o=e.subarray(144,192),a=e.length>=480?e.subarray(416,480):void 0;if(r){let m=t.subarray(0,r.length);if(!v.timingSafeEqual(m,r))return {verified:false,platform:"amd-sev-snp",message:"AMD SEV-SNP Attestation Failed: REPORT_DATA binding mismatch (public key / nonce forged or altered).",measurements:{reportDataHex:t.toString("hex"),measurementHex:o.toString("hex"),chipIdHex:a?.toString("hex")}}}return {verified:true,platform:"amd-sev-snp",message:"AMD SEV-SNP Hardware TEE Attestation Certified: Cryptographic measurement & REPORT_DATA verified.",measurements:{reportDataHex:t.toString("hex"),measurementHex:o.toString("hex"),chipIdHex:a?.toString("hex")}}}if(e.length>=2&&e[0]===210&&e[1]===132||e.includes(Buffer.from("pcrs"))){if(i.expectedPcrs)for(let[t,o]of Object.entries(i.expectedPcrs)){let a=Buffer.from(o,"hex");if(a.length>0&&!e.includes(a))return {verified:false,platform:"aws-nitro",message:`AWS Nitro Attestation Failed: PCR${t} measurement mismatch.`}}return r&&!e.includes(r)?{verified:false,platform:"aws-nitro",message:"AWS Nitro Attestation Failed: user_data binding mismatch (public key / nonce forged or altered)."}:{verified:true,platform:"aws-nitro",message:"AWS Nitro Enclave Hardware TEE Attestation Certified: PCR measurements & user_data verified."}}return n==="required"?{verified:false,platform:"none",message:`TEE Verification Failed: Unrecognized hardware attestation report format (${e.length} bytes).`}:{verified:true,platform:"none",message:"Non-critical TEE report accepted under relaxed policy."}}async verifyTeeAttestation(e,i={}){let n=await this.verifyTeeAttestationDetailed(e,i);return n.verified?(b.info(`[LiopVerifier] ${n.message}`),true):(b.error(`[LiopVerifier] TEE FAILED: ${n.message}`),false)}deriveImageId(e){return b$1(e)}};export{w as a};//# sourceMappingURL=chunk-6KFKO6ZX.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-6KFKO6ZX.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';import s from'crypto';var b=(t=>(t[t.HMAC_LEGACY=0]="HMAC_LEGACY",t[t.GROTH16=2]="GROTH16",t[t.GROTH16_PQC_HYBRID=3]="GROTH16_PQC_HYBRID",t))(b||{}),m=1,g=2,B=144,r=class extends Error{static{a(this,"ZkVerificationError");}constructor(o){super(`ZK Verification Failed: ${o}`),this.name="ZkVerificationError";}};function v(e){if(e.guestImageId.length!==32)throw new r(`Invalid guestImageId size: expected 32 bytes, got ${e.guestImageId.length}`);if(e.logicDigest.length!==32)throw new r(`Invalid logicDigest size: expected 32 bytes, got ${e.logicDigest.length}`);if(e.datasetDigest.length!==32)throw new r(`Invalid datasetDigest size: expected 32 bytes, got ${e.datasetDigest.length}`);if(e.outputDigest.length!==32)throw new r(`Invalid outputDigest size: expected 32 bytes, got ${e.outputDigest.length}`);let o=Buffer.alloc(B);return e.guestImageId.copy(o,0),e.logicDigest.copy(o,32),e.datasetDigest.copy(o,64),e.outputDigest.copy(o,96),o.writeBigUInt64BE(BigInt(e.fuelConsumed),128),o.writeBigUInt64BE(BigInt(e.executionTimestamp),136),o}a(v,"encodeJournalV2");function U(e){if(e.length!==B)throw new r(`Invalid ZkJournalV2 size: expected ${B} bytes, got ${e.length}`);return {guestImageId:Buffer.from(e.subarray(0,32)),logicDigest:Buffer.from(e.subarray(32,64)),datasetDigest:Buffer.from(e.subarray(64,96)),outputDigest:Buffer.from(e.subarray(96,128)),fuelConsumed:e.readBigUInt64BE(128),executionTimestamp:e.readBigUInt64BE(136)}}a(U,"decodeJournalV2");var H={encodeV2(e,o,n){let t=Buffer.alloc(6);t.writeUInt8(g,0),t.writeUInt8(e,1),t.writeUInt32BE(o.length,2);let f=Buffer.concat([t,o,n]),i=s.createHash("sha256").update(f).digest();return Buffer.concat([f,i])},encodeHybridV2(e,o,n,t){let f=Buffer.alloc(6);f.writeUInt8(g,0),f.writeUInt8(3,1),f.writeUInt32BE(e.length,2);let i=Buffer.alloc(2);i.writeUInt16BE(o.length,0);let c=Buffer.alloc(2);c.writeUInt16BE(n.length,0);let u=Buffer.concat([f,e,i,o,c,n,t]),d=s.createHash("sha256").update(u).digest();return Buffer.concat([u,d])},decode(e){if(!e||e.length===0)throw new r("Empty or malformed zero-knowledge proof array.");let o=e[0];if(o===m){if(e.length<35)throw new r("Malformed receipt: invalid header or length.");let n=e.readUInt16BE(1);if(e.length<3+n+32)throw new r("Malformed receipt: truncated journal or seal.");let t=Buffer.from(e.subarray(3,3+n)),f=Buffer.from(e.subarray(3+n,3+n+32));return {version:m,proofType:0,journal:t,proof:f,raw:e}}if(o===g){if(e.length<38)throw new r("Malformed receipt v2: buffer too short (< 38 bytes).");let n=e[1],t=e.readUInt32BE(2);if(e.length<6+t+32)throw new r("Malformed receipt v2: truncated payload.");let f=e.subarray(0,e.length-32),i=e.subarray(e.length-32),c=s.createHash("sha256").update(f).digest();if(!s.timingSafeEqual(i,c))throw new r("Receipt checksum verification failed.");let u=Buffer.from(e.subarray(6,6+t));if(n===3){let a=6+t;if(e.length<a+2+32)throw new r("Malformed hybrid receipt: missing proof length header.");let p=e.readUInt16BE(a);if(a+=2,e.length<a+p+2+32)throw new r("Malformed hybrid receipt: truncated Groth16 proof.");let I=Buffer.from(e.subarray(a,a+p));a+=p;let h=e.readUInt16BE(a);if(a+=2,e.length<a+h+32)throw new r("Malformed hybrid receipt: truncated ML-DSA-65 signature.");let y=Buffer.from(e.subarray(a,a+h));a+=h;let x=Buffer.from(e.subarray(a,e.length-32));return {version:g,proofType:n,journal:u,proof:I,pqcSignature:y,pqcPublicKey:x,raw:e}}let d=Buffer.from(e.subarray(6+t,e.length-32));return {version:g,proofType:n,journal:u,proof:d,raw:e}}throw new r(`Unsupported receipt version: 0x${o.toString(16)}`)}},C={verify(e,o,n){if(!e.imageId.equals(o))throw new r("ImageID mismatch. The remote origin executed a different WASM payload.");if(e.proof.length===0)throw new r("Empty or malformed zero-knowledge proof array.");let t=Buffer.from(e.proof);if(t.length<35||t[0]!==1)throw new r("Malformed receipt: invalid header or length.");let f=t.readUInt16BE(1),i=t.subarray(3,3+f),c=t.subarray(3+f);if(c.length!==32)throw new r("Invalid seal: expected 32-byte HMAC-SHA256.");try{if(JSON.parse(i.toString()).image_id!==e.imageId.toString("hex"))throw new r("Journal imageId does not match receipt header.")}catch{throw new r("Failed to parse journal data.")}if(n&&n.length>0){let u=s.createHmac("sha256",n).update(i).digest();if(!s.timingSafeEqual(c,u))throw new r("Invalid seal: HMAC verification failed.")}return true},deriveImageId(e){return s.createHash("sha256").update(e).digest()}};export{b as a,m as b,g as c,B as d,r as e,v as f,U as g,H as h,C as i};//# sourceMappingURL=chunk-6VK2XALI.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-6VK2XALI.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';import j from'crypto';import*as s from'fs/promises';import*as A from'os';import*as p from'path';import h from'vm';import {WASI}from'wasi';import*as I from'acorn';import {simple}from'acorn-walk';var m=class extends Error{static{a(this,"GuardianError");}constructor(r){super(`AST Sec-Policy Violation: ${r}`),this.name="GuardianError";}},w={analyze(a){let r=WebAssembly.Module.imports(a),t=0,o=new Set(["fd_write","fd_read","fd_close","fd_seek","environ_get","environ_sizes_get","args_get","args_sizes_get","clock_time_get","random_get","proc_exit","fd_prestat_get","fd_prestat_dir_name","fd_fdstat_get"]);for(let i of r){if(i.module==="wasi_snapshot_preview1"){if(!o.has(i.name))throw new m(`Banned WASI Import Detected: ${i.module}/${i.name}`)}else throw new m(`Banned Host Import Module Detected: ${i.module}`);if(t++,t>128)throw new m("Import limit exceeded. Possible resource exhaustion attack.")}}};var D=process.emit;process.emit=(a,r,...t)=>a==="warning"&&typeof r=="object"&&r.name==="ExperimentalWarning"&&String(r.message).includes("WASI")||String(r.message).includes("importing WASI")?false:D.call(process,a,r,...t);function z(){let r=process.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"],t={NODE_ENV:"production",LIOP_NODE:"true"};for(let o of r){let i=process.env[o];i!==void 0&&!i.startsWith("()")&&(t[o]=i);}return t}a(z,"getDefaultEnvironment");function k(a){try{let r=I.parse(a,{ecmaVersion:2022,sourceType:"script",allowReturnOutsideFunction:!0}),t=100;return simple(r,{Identifier(){t+=1;},Literal(){t+=1;},BinaryExpression(){t+=2;},UnaryExpression(){t+=2;},LogicalExpression(){t+=2;},VariableDeclaration(o){t+=5*(o.declarations?.length||1);},AssignmentExpression(){t+=3;},MemberExpression(){t+=3;},ObjectExpression(o){t+=5+(o.properties?.length||0)*2;},ArrayExpression(o){t+=5+(o.elements?.length||0)*2;},CallExpression(o){t+=10+(o.arguments?.length||0)*2;},FunctionDeclaration(){t+=20;},FunctionExpression(){t+=15;},ArrowFunctionExpression(){t+=15;},IfStatement(){t+=5;},SwitchStatement(){t+=10;},ForStatement(){t+=50;},ForInStatement(){t+=50;},ForOfStatement(){t+=50;},WhileStatement(){t+=50;},DoWhileStatement(){t+=50;},TryStatement(){t+=15;},ReturnStatement(){t+=2;}}),Math.ceil(t/100)*100}catch{return 500}}a(k,"calculateAstInstructionFuel");var S=class{static{a(this,"WasiSandbox");}wasi;sandboxId;workingDir;config;stdoutHandle=null;stderrHandle=null;constructor(r={}){this.sandboxId=j.randomUUID(),this.workingDir=p.join(A.tmpdir(),"liop-mesh","sandboxes",this.sandboxId),this.config=r;}async init(){try{await s.mkdir(this.workingDir,{recursive:!0}),this.stdoutHandle=await s.open(p.join(this.workingDir,"stdout.log"),"w+"),this.stderrHandle=await s.open(p.join(this.workingDir,"stderr.log"),"w+"),this.wasi=new WASI({version:"preview1",args:["liop_runtime"],env:this.config.allowEnv?{...z(),RUNTIME_ID:this.sandboxId}:{NODE_ENV:"production",LIOP_NODE:"true",RUNTIME_ID:this.sandboxId},preopens:{"/sandbox":this.workingDir,...this.config.allowedDirectories},stdout:this.stdoutHandle.fd,stderr:this.stderrHandle.fd});}catch(r){throw new Error(`Sandbox Initialization Failed: ${r instanceof Error?r.message:"FS Error"}`)}}async execute(r,t=[],o={}){let i=performance.now();if(r instanceof Buffer)try{let e=await WebAssembly.compile(new Uint8Array(r));w.analyze(e);let g=await WebAssembly.instantiate(e,this.wasi.getImportObject());this.wasi.start(g);let u=p.join(this.workingDir,"stdout.log"),l=p.join(this.workingDir,"stderr.log"),c=await s.readFile(u,"utf-8"),y=await s.readFile(l,"utf-8"),n=performance.now()-i;return {output:c||(y?`Error: ${y}`:"WASM_EXECUTION_SUCCESS"),fuelConsumed:Math.max(100,Math.ceil(Math.floor(n*1e3)/100)*100)}}catch(e){throw new Error(`WASM Runtime Error: ${e instanceof Error?e.message:String(e)}`)}else {let e=Object.create(null),g={records:t,...o};e.require=void 0,e.process=void 0,e.global=void 0,e.globalThis=void 0,e.Buffer=void 0,e.setTimeout=void 0,e.setInterval=void 0,e.setImmediate=void 0,e.queueMicrotask=void 0,e.eval=void 0,e.Function=void 0,e.SharedArrayBuffer=void 0,e.Date=void 0,e.performance=void 0,e.Intl=void 0,e.ArrayBuffer=void 0,e.Uint8Array=void 0,e.Int8Array=void 0,e.Uint16Array=void 0,e.Int16Array=void 0,e.Uint32Array=void 0,e.Int32Array=void 0,e.Float32Array=void 0,e.Float64Array=void 0,e.BigInt64Array=void 0,e.BigUint64Array=void 0,e.DataView=void 0;let u=a(n=>{if(!n||typeof n!="object")return n;if(Array.isArray(n))return n.map(u);let d=Object.create(null);for(let[E,b]of Object.entries(n))d[E]=u(b);return d},"toNullPrototype");e.records=u(JSON.parse(JSON.stringify(t))),e.env=u(JSON.parse(JSON.stringify(g)));for(let[n,d]of Object.entries(o))e[n]=u(JSON.parse(JSON.stringify(d)));let l=a(n=>{if(n&&typeof n=="object"&&!Object.isFrozen(n)){Object.freeze(n);for(let d of Object.keys(n))l(n[d]);}return n},"deepFreeze");l(e.records),l(e.env);for(let n of Object.keys(e))Object.defineProperty(e,n,{writable:false,configurable:false});let c=String(r);(/^\s*return\s/m.test(c)||!c.includes("function liop_main"))&&(c.includes("function liop_main")||(c=`function liop_main(env) {
|
|
2
|
+
${c}
|
|
3
|
+
}`));let y=`
|
|
4
|
+
(function() {
|
|
5
|
+
"use strict";
|
|
6
|
+
try {
|
|
7
|
+
// Pre-execution prototype freezing (PCI-DSS Compliance)
|
|
8
|
+
Object.freeze(Object.prototype);
|
|
9
|
+
Object.freeze(Array.prototype);
|
|
10
|
+
Object.freeze(String.prototype);
|
|
11
|
+
Object.freeze(Number.prototype);
|
|
12
|
+
Object.freeze(Boolean.prototype);
|
|
13
|
+
Object.freeze(RegExp.prototype);
|
|
14
|
+
Object.freeze(Map.prototype);
|
|
15
|
+
Object.freeze(Set.prototype);
|
|
16
|
+
Object.freeze(Promise.prototype);
|
|
17
|
+
Object.freeze(Error.prototype);
|
|
18
|
+
Object.freeze(Object.getPrototypeOf(function(){}));
|
|
19
|
+
|
|
20
|
+
${c}
|
|
21
|
+
if (typeof liop_main === 'function') {
|
|
22
|
+
return liop_main(env);
|
|
23
|
+
}
|
|
24
|
+
return "ERR_NO_ENTRY_POINT";
|
|
25
|
+
} catch(e) {
|
|
26
|
+
return "LogicError: " + e.message;
|
|
27
|
+
}
|
|
28
|
+
})();
|
|
29
|
+
`;try{let n=new h.Script(y,{filename:`liop-sandbox-${this.sandboxId.slice(0,8)}.js`});!process.env.VITEST&&typeof Object.prototype=="object"&&!Object.isFrozen(Object.prototype)&&(Object.freeze(Object.prototype),Object.freeze(Array.prototype),Object.freeze(String.prototype),Object.freeze(Number.prototype),Object.freeze(Boolean.prototype),Object.freeze(RegExp.prototype),Object.freeze(Map.prototype),Object.freeze(Set.prototype),Object.freeze(Promise.prototype),Object.freeze(Error.prototype));let d=h.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox",microtaskMode:"afterEvaluate"}),E=n.runInContext(d,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),b=typeof r=="string"?r:r.toString("utf-8"),O=k(b);if(O>1e6)throw new Error("LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.");return {output:E,fuelConsumed:O}}catch(n){throw new Error(`V8 Isolate Fault: ${n instanceof Error?n.message:"Execution Timeout"}`)}}}async teardown(){try{this.stdoutHandle&&await this.stdoutHandle.close(),this.stderrHandle&&await this.stderrHandle.close(),await s.rm(this.workingDir,{recursive:!0,force:!0});}catch{}}};
|
|
30
|
+
export{w as a,z as b,k as c,S as d};//# sourceMappingURL=chunk-CTTTLCGL.js.map
|
|
31
|
+
//# sourceMappingURL=chunk-CTTTLCGL.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {q as q$1,r,s,t}from'./chunk-ZZMSFCJP.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {countTokens,setMergeCacheSize}from'gpt-tokenizer/model/gpt-4o';import*as v from'fs';import*as h from'@grpc/grpc-js';import B from'path';import {fileURLToPath}from'url';import*as Oe from'@grpc/proto-loader';var P=class{static{a(this,"RealTokenEstimator");}name="o200k_base";countFn;constructor(e,r){if(this.countFn=e,r)try{r(1e4);}catch{}}countTokens(e){return e.length===0?0:this.countFn(e)}},w=class{static{a(this,"HeuristicTokenEstimator");}name="heuristic (chars/4)";countTokens(e){return e.length===0?0:Math.ceil(e.length/4)}};async function se(){try{let t=new P(countTokens,setMergeCacheSize);return b.debug("[LIOP-Economy] Token estimator initialized: o200k_base"),t}catch{return b.info("[LIOP-Economy] Inlined tokenizer initialization error, falling back to heuristic estimator"),new w}}a(se,"createTokenEstimator");function ce(){try{return new P(countTokens,setMergeCacheSize)}catch{return new w}}a(ce,"createSyncTokenEstimator");var O="1.9.1";var ue=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ee(t){let e=new Set([t]),r=new Set,o=t.match(ue);if(!o)return ()=>false;let i={major:+o[1],minor:+o[2],patch:+o[3],prerelease:o[4]};if(i.prerelease!=null)return a(function(c){return c===t},"isExactmatch");function a$1(_){return r.add(_),false}a(a$1,"_reject");function s(_){return e.add(_),true}return a(s,"_accept"),a(function(c){if(e.has(c))return true;if(r.has(c))return false;let g=c.match(ue);if(!g)return a$1(c);let T={major:+g[1],minor:+g[2],patch:+g[3],prerelease:g[4]};return T.prerelease!=null||i.major!==T.major?a$1(c):i.major===0?i.minor===T.minor&&i.patch<=T.patch?s(c):a$1(c):i.minor<=T.minor?s(c):a$1(c)},"isCompatible")}a(Ee,"_makeCompatibilityCheck");var pe=Ee(O);var ve=O.split(".")[0],I=Symbol.for(`opentelemetry.js.api.${ve}`),C=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function R(t,e,r,o=false){var i;let a=C[I]=(i=C[I])!==null&&i!==void 0?i:{version:O};if(!o&&a[t]){let s=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${t}`);return r.error(s.stack||s.message),false}if(a.version!==O){let s=new Error(`@opentelemetry/api: Registration of version v${a.version} for ${t} does not match previously registered API v${O}`);return r.error(s.stack||s.message),false}return a[t]=e,r.debug(`@opentelemetry/api: Registered a global for ${t} v${O}.`),true}a(R,"registerGlobal");function E(t){var e,r;let o=(e=C[I])===null||e===void 0?void 0:e.version;if(!(!o||!pe(o)))return (r=C[I])===null||r===void 0?void 0:r[t]}a(E,"getGlobal");function A(t,e){e.debug(`@opentelemetry/api: Unregistering a global for ${t} v${O}.`);let r=C[I];r&&delete r[t];}a(A,"unregisterGlobal");var N=class{static{a(this,"DiagComponentLogger");}constructor(e){this._namespace=e.namespace||"DiagComponentLogger";}debug(...e){return L("debug",this._namespace,e)}error(...e){return L("error",this._namespace,e)}info(...e){return L("info",this._namespace,e)}warn(...e){return L("warn",this._namespace,e)}verbose(...e){return L("verbose",this._namespace,e)}};function L(t,e,r){let o=E("diag");if(o)return o[t](e,...r)}a(L,"logProxy");var d;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL";})(d||(d={}));function le(t,e){t<d.NONE?t=d.NONE:t>d.ALL&&(t=d.ALL),e=e||{};function r(o,i){let a=e[o];return typeof a=="function"&&t>=i?a.bind(e):function(){}}return a(r,"_filterFunc"),{error:r("error",d.ERROR),warn:r("warn",d.WARN),info:r("info",d.INFO),debug:r("debug",d.DEBUG),verbose:r("verbose",d.VERBOSE)}}a(le,"createLogLevelDiagLogger");var ye="diag",x=class t{static{a(this,"DiagAPI");}static instance(){return this._instance||(this._instance=new t),this._instance}constructor(){function e(i){return function(...a){let s=E("diag");if(s)return s[i](...a)}}a(e,"_logProxy");let r=this,o=a((i,a={logLevel:d.INFO})=>{var s,_,c;if(i===r){let b=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((s=b.stack)!==null&&s!==void 0?s:b.message),false}typeof a=="number"&&(a={logLevel:a});let g=E("diag"),T=le((_=a.logLevel)!==null&&_!==void 0?_:d.INFO,i);if(g&&!a.suppressOverrideMessage){let b=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";g.warn(`Current logger will be overwritten from ${b}`),T.warn(`Current logger will overwrite one already registered from ${b}`);}return R("diag",T,r,true)},"setLogger");r.setLogger=o,r.disable=()=>{A(ye,r);},r.createComponentLogger=i=>new N(i),r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error");}};var G=class{static{a(this,"NoopMeter");}constructor(){}createGauge(e,r){return Ie}createHistogram(e,r){return Ce}createCounter(e,r){return Se}createUpDownCounter(e,r){return Le}createObservableGauge(e,r){return Me}createObservableCounter(e,r){return xe}createObservableUpDownCounter(e,r){return Pe}addBatchObservableCallback(e,r){}removeBatchObservableCallback(e){}},y=class{static{a(this,"NoopMetric");}},V=class extends y{static{a(this,"NoopCounterMetric");}add(e,r){}},K=class extends y{static{a(this,"NoopUpDownCounterMetric");}add(e,r){}},j=class extends y{static{a(this,"NoopGaugeMetric");}record(e,r){}},H=class extends y{static{a(this,"NoopHistogramMetric");}record(e,r){}},M=class{static{a(this,"NoopObservableMetric");}addCallback(e){}removeCallback(e){}},W=class extends M{static{a(this,"NoopObservableCounterMetric");}},z=class extends M{static{a(this,"NoopObservableGaugeMetric");}},q=class extends M{static{a(this,"NoopObservableUpDownCounterMetric");}},me=new G,Se=new V,Ie=new j,Ce=new H,Le=new K,xe=new W,Me=new z,Pe=new q;var X=class{static{a(this,"NoopMeterProvider");}getMeter(e,r,o){return me}},de=new X;var Y="metrics",$=class t{static{a(this,"MetricsAPI");}constructor(){}static getInstance(){return this._instance||(this._instance=new t),this._instance}setGlobalMeterProvider(e){return R(Y,e,x.instance())}getMeterProvider(){return E(Y)||de}getMeter(e,r,o){return this.getMeterProvider().getMeter(e,r,o)}disable(){A(Y,x.instance());}};var J=$.getInstance();var we="@nekzus/liop",Re="1.2.0-alpha.9",Ae=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],Ne=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],D=class{static{a(this,"LiopOTelBridge");}tokenUsage;operationDuration;active=false;constructor(){try{let e=J.getMeter(we,Re);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:Ae}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:Ne}}),this.active=!0,b.debug("[LIOP-OTel] gen_ai.* metrics bridge initialized");}catch(e){b.debug(`[LIOP-OTel] Bridge disabled: ${e instanceof Error?e.message:String(e)}`);let r={record:a(()=>{},"record")};this.tokenUsage=r,this.operationDuration=r;}}recordTokens(e,r,o,i){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":o,"gen_ai.token.type":r,"gen_ai.request.model":"liop-mesh",...i?{"liop.tool.name":i}:{}});}recordDuration(e,r,o){this.operationDuration.record(e/1e3,{"gen_ai.system":"liop","gen_ai.operation.name":r,...o?{"error.type":o}:{}});}isActive(){return this.active}};var $e={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},fe=class t$1{static{a(this,"TokenTelemetryEngine");}static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=ce(),this.otelBridge=new D,this.initRealEstimator();}initRealEstimator(){se().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return t$1.instance||(t$1.instance=new t$1),t$1.instance}countTokens(e){try{return this.estimator.countTokens(e)}catch{return Math.ceil(e.length/4)}}record(e){let r$1={...e,timestamp:Date.now()};this.operations.push(r$1);try{let o=$e[e.type]||"chat";e.estimatedInputTokens>0&&this.otelBridge.recordTokens(e.estimatedInputTokens,"input",o,e.toolName),e.estimatedOutputTokens>0&&this.otelBridge.recordTokens(e.estimatedOutputTokens,"output",o,e.toolName),e.durationMs!==void 0&&this.otelBridge.recordDuration(e.durationMs,o);}catch{}try{let o={type:e.type,method:e.method,tool:e.toolName||"none"};if(e.estimatedInputTokens>0&&q$1.inc(o,e.estimatedInputTokens),e.estimatedOutputTokens>0&&r.inc(o,e.estimatedOutputTokens),e.originDatasetTokens!==void 0&&e.originDatasetTokens>e.estimatedOutputTokens){let i=e.originDatasetTokens-e.estimatedOutputTokens;s.inc({tool:e.toolName||"none"},i);}e.durationMs!==void 0&&e.durationMs>=0&&t.observe(o,e.durationMs);}catch{}}estimateTokens(e){return this.countTokens(e)}getReport(){return {sessionId:this.sessionId,operations:[...this.operations],totalInputTokens:this.operations.reduce((e,r)=>e+r.estimatedInputTokens,0),totalOutputTokens:this.operations.reduce((e,r)=>e+r.estimatedOutputTokens,0),estimatorName:this.estimator.name,sessionUptimeMs:Date.now()-this.startedAt}}getPerToolReport(){let e=new Map;for(let r of this.operations){let o=r.toolName||r.method,i=e.get(o)||{input:0,output:0,calls:0,avgDurationMs:0},a=i.avgDurationMs*i.calls+(r.durationMs||0),s=i.calls+1;e.set(o,{input:i.input+r.estimatedInputTokens,output:i.output+r.estimatedOutputTokens,calls:s,avgDurationMs:s>0?a/s:0});}return e}formatStatusBlock(){let e=this.getReport();if(e.operations.length===0)return "";let r=this.formatUptime(e.sessionUptimeMs),o=e.totalInputTokens+e.totalOutputTokens,i=new Map;for(let f of e.operations){let u=f.type,k=i.get(u)||{count:0,input:0,output:0};i.set(u,{count:k.count+1,input:k.input+f.estimatedInputTokens,output:k.output+f.estimatedOutputTokens});}let a=Array.from(i.entries()),s=a.map(([f,u],k)=>{let F=k===a.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",U=u.output>0?` / ${u.output.toLocaleString()} out`:"";return `${F} ${f} \xD7${u.count} \u2192 ${u.input.toLocaleString()} in${U}`}),_=this.getPerToolReport(),c=Array.from(_.entries()).filter(([f])=>f!=="tools/list"&&f!=="LiopMeshStatus"),g=[];c.length>0&&(g.push("\u251C\u2500 By Tool:"),c.forEach(([f,u],k)=>{let F=k===c.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",U=u.output>0?` / ${u.output.toLocaleString()} out`:"",ke=u.avgDurationMs>0?` ~${Math.round(u.avgDurationMs)}ms`:"";g.push(`${F} ${f}: ${u.input.toLocaleString()} in${U} (\xD7${u.calls})${ke}`);}));let T=e.operations.filter(f=>f.durationMs!==void 0),b=T.length>0?Math.round(T.reduce((f,u)=>f+(u.durationMs||0),0)/T.length):0,be=this.otelBridge.isActive()?"gen_ai.client.token.usage \u2192 active":"disabled";return [`
|
|
2
|
+
Token Economy:`,`\u251C\u2500 Session: ${e.sessionId.slice(0,8)} (${r})`,`\u251C\u2500 Estimator: ${e.estimatorName}`,`\u251C\u2500 Operations: ${e.operations.length}`,...s,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${o.toLocaleString()} combined)`,...g,...b>0?[`\u251C\u2500 Avg Latency: ${b}ms`]:[],`\u2514\u2500 OTel: ${be}`].join(`
|
|
3
|
+
`)}formatUptime(e){let r=Math.floor(e/1e3);if(r<60)return `${r}s`;let o=Math.floor(r/60),i=r%60;if(o<60)return `${o}m ${i}s`;let a=Math.floor(o/60),s=o%60;return `${a}h ${s}m`}reset(){this.operations=[];}static destroy(){t$1.instance=null;}};var S=a(()=>process.env.NODE_ENV==="production"||process.env.LIOP_ENFORCE_TLS==="true","isTlsEnforced"),he=a(t=>t?.insecure===true||t?.suppressWarning===true||process.env.LIOP_SUPPRESS_TLS_WARNING==="true","isTlsWarningSuppressed"),ge=false,Te=false;function er(t){if(t?.mutualTls&&!t.rootCert&&!t.certManager?.getRootCert())throw new Error("[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates.");if(t?.certManager)try{let e=t.certManager.getCertChain(),r=t.certManager.getPrivateKey(),o=t.certManager.getRootCert();if(t.mutualTls&&!o)throw new Error("[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but CertManager has no root CA certificate loaded.");return h.ServerCredentials.createSsl(o,[{cert_chain:e,private_key:r}],!!t.mutualTls)}catch(e){if(S())throw new Error(`[LIOP-TLS] FATAL: CertManager server credential creation failed in enforced mode: ${e}`);return b.warn(`[LIOP-TLS] CertManager failed, falling back to insecure: ${e}`),h.ServerCredentials.createInsecure()}if(!t?.certChain||!t?.privateKey){if(S())throw new Error("[LIOP-TLS] FATAL: TLS certificates required in production or when LIOP_ENFORCE_TLS=true.");return !he(t)&&!ge&&(ge=true,b.debug("[LIOP-TLS] No TLS certificates configured \u2014 using insecure server credentials")),h.ServerCredentials.createInsecure()}try{let e=t.rootCert?v.readFileSync(t.rootCert):null,r=v.readFileSync(t.certChain),o=v.readFileSync(t.privateKey);if(t.mutualTls&&!e)throw new Error("[LIOP-TLS] FATAL: Mutual TLS (mTLS) enabled but no root CA certificate (rootCert) provided to verify client certificates.");return h.ServerCredentials.createSsl(e,[{cert_chain:r,private_key:o}],!!t.mutualTls)}catch(e){if(S())throw new Error(`[LIOP-TLS] FATAL: Server certificate loading failed in production or enforced mode. Refusing insecure fallback to prevent MITM/eavesdropping: ${e}`);return b.warn(`[LIOP-TLS] Server certificate loading failed, falling back to insecure (dev mode): ${e}`),h.ServerCredentials.createInsecure()}}a(er,"createServerCredentials");function tr(t){if(t?.certManager)try{let e=t.certManager.getRootCert();if(!e)throw new Error("[LIOP-TLS] FATAL: Channel TLS requires a root CA certificate in CertManager.");let r=t.certManager.getCertChain(),o=t.certManager.getPrivateKey();return h.credentials.createSsl(e,o,r)}catch(e){if(S())throw new Error(`[LIOP-TLS] FATAL: Channel certificate loading failed in enforced mode: ${e}`);return b.warn(`[LIOP-TLS] Channel CertManager failed, falling back to insecure: ${e}`),h.credentials.createInsecure()}if(!t?.rootCert){if(S())throw new Error("[LIOP-TLS] FATAL: TLS root certificate required in production or when LIOP_ENFORCE_TLS=true.");return !he(t)&&!Te&&(Te=true,b.debug("[LIOP-TLS] No TLS root certificate configured \u2014 using insecure channel credentials")),h.credentials.createInsecure()}try{let e=v.readFileSync(t.rootCert),r=t.certChain?v.readFileSync(t.certChain):void 0,o=t.privateKey?v.readFileSync(t.privateKey):void 0;return h.credentials.createSsl(e,o,r)}catch(e){if(S())throw new Error(`[LIOP-TLS] FATAL: Channel certificate loading failed in production or enforced mode. Refusing insecure fallback to prevent MITM/eavesdropping: ${e}`);return b.warn(`[LIOP-TLS] Channel certificate loading failed, falling back to insecure (dev mode): ${e}`),h.credentials.createInsecure()}}a(tr,"createChannelCredentials");var ir={"grpc.keepalive_time_ms":3e4,"grpc.keepalive_timeout_ms":1e4,"grpc.keepalive_permit_without_calls":1,"grpc.max_send_message_length":-1,"grpc.max_receive_message_length":-1,"grpc.enable_retries":1};var Be=fileURLToPath(import.meta.url),Q=B.dirname(Be),Fe=[B.resolve(Q,"./protocol/liop_core.proto"),B.resolve(Q,"../protocol/liop_core.proto")],Ue=B.resolve(Q,"../../../../protocol/proto/liop_core.proto"),Z=Fe.find(t=>v.existsSync(t))||Ue;v.existsSync(Z)||b.error(`[LIOP-Proto] CRITICAL: Proto file not found at ${Z}`);var Ge=Oe.loadSync(Z,{keepCase:true,longs:String,enums:String,defaults:true,oneofs:true}),Ve=h.loadPackageDefinition(Ge),lr=Ve.liop.v1;export{P as a,w as b,se as c,ce as d,D as e,fe as f,lr as g,er as h,tr as i,ir as j};//# sourceMappingURL=chunk-ECRS6N33.js.map
|
|
4
|
+
//# sourceMappingURL=chunk-ECRS6N33.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {e}from'./chunk-6VK2XALI.js';import {a}from'./chunk-AYDF3IFZ.js';import {bn254,stringBigints}from'micro-zk-proofs';var y=250;function d(e,r){if(!e||!r?.proof)return false;try{return bn254.groth.verifyProof(e,r)}catch{return false}}a(d,"verifyGroth16Proof");function g(e$1){try{let r=stringBigints.encode(e$1);return Buffer.from(JSON.stringify(r),"utf-8")}catch(r){throw new e(`Failed to serialize VerificationKey: ${r instanceof Error?r.message:String(r)}`)}}a(g,"serializeVKey");function h(e$1){try{let r=JSON.parse(e$1.toString("utf-8"));return stringBigints.decode(r)}catch(r){throw new e(`Failed to deserialize VerificationKey: ${r instanceof Error?r.message:String(r)}`)}}a(h,"deserializeVKey");function l(e$1){try{let r=stringBigints.encode(e$1);return Buffer.from(JSON.stringify(r),"utf-8")}catch(r){throw new e(`Failed to serialize GrothProof: ${r instanceof Error?r.message:String(r)}`)}}a(l,"serializeGrothProof");function p(e$1){try{let r=JSON.parse(e$1.toString("utf-8"));return stringBigints.decode(r)}catch(r){throw new e(`Failed to deserialize GrothProof: ${r instanceof Error?r.message:String(r)}`)}}a(p,"deserializeGrothProof");export{y as a,d as b,g as c,h as d,l as e,p as f};//# sourceMappingURL=chunk-FDJMH4CB.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-FDJMH4CB.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';import {z}from'zod';var p=true,o="2025-11-25";function l(r,t){return {jsonrpc:"2.0",id:t??null,result:{protocolVersion:o,capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:r}}}a(l,"buildLegacyInitializeResponse");function u(r){if(r.method==="initialize"||r.method==="notifications/initialized")return true;let i=r.params?._meta?.["io.modelcontextprotocol/protocolVersion"];return !i||i===o}a(u,"isLegacyRequest");function g(r){if(!r.result||typeof r.result!="object")return r;let t={...r.result};return delete t.resultType,delete t.ttlMs,delete t.cacheScope,{...r,result:t}}a(g,"adaptResponseForLegacyClient");var d={bank_tool:"Analyze_Synthetic_Bank_Transactions",bank_tool_XDwd:"Analyze_Synthetic_Bank_Transactions",vault_tool:"Analyze_Synthetic_Medical_Records",vault_tool_E8wP:"Analyze_Synthetic_Medical_Records",oracle_tool:"Analyze_HFT_Market_Data",compute_aggregate:"Analyze_Synthetic_Bank_Transactions"};function m(r){if(!r)return {};let t={...r};return t.data!==void 0&&(t.payload===void 0&&(t.payload=t.data),t.envelope===void 0&&(t.envelope=t.data)),t}a(m,"normalizeToolArguments");var I="2026-07-28",T=z.object({name:z.string(),description:z.string().optional(),inputSchema:z.record(z.string(),z.unknown())}),h=z.object({uri:z.string(),name:z.string(),description:z.string().optional(),mimeType:z.string().optional()}),C=z.object({name:z.string(),description:z.string().optional(),arguments:z.array(z.object({name:z.string(),description:z.string().optional(),required:z.boolean().optional()})).optional()});export{p as a,o as b,l as c,u as d,g as e,d as f,m as g,I as h,T as i,h as j,C as k};//# sourceMappingURL=chunk-GWVSCZUS.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-GWVSCZUS.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-LM26HOJ6.js';import {b as b$1}from'./chunk-XLVEDKM6.js';import {i,j as j$1,e}from'./chunk-ZZMSFCJP.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as L from'http';import*as j from'http2';import*as H from'net';function A(c,e){return {resource:e,authorization_servers:[c],scopes_supported:b$1,bearer_methods_supported:["header"],resource_documentation:"https://github.com/nekzus/liop"}}a(A,"buildProtectedResourceMetadata");var m={FLAG_DATA:0,FLAG_TRAILERS:128,HEADER_LENGTH:5,CONTENT_TYPE_PREFIX:"application/grpc-web",STATUS_OK:0,STATUS_CANCELLED:1,STATUS_UNKNOWN:2,STATUS_INVALID_ARGUMENT:3,STATUS_DEADLINE_EXCEEDED:4,STATUS_NOT_FOUND:5,STATUS_PERMISSION_DENIED:7,STATUS_UNAUTHENTICATED:16,STATUS_INTERNAL:13};function G(c){if(!c)return false;let e=c.toLowerCase();return e.startsWith("application/grpc-web")||e.startsWith("application/grpc-web+proto")||e.startsWith("application/grpc-web+json")}a(G,"isGrpcWebRequest");function D(c){let e=Buffer.isBuffer(c)?c:Buffer.from(c),t=Buffer.alloc(m.HEADER_LENGTH);return t.writeUInt8(m.FLAG_DATA,0),t.writeUInt32BE(e.length,1),Buffer.concat([t,e])}a(D,"encodeDataFrame");function x(c=m.STATUS_OK,e="",t={}){let o=[`grpc-status:${c}`,`grpc-message:${encodeURIComponent(e)}`];for(let[i,s]of Object.entries(t))o.push(`${i}:${s}`);let n=`${o.join(`\r
|
|
2
|
+
`)}\r
|
|
3
|
+
`,r=Buffer.from(n,"utf-8"),a=Buffer.alloc(m.HEADER_LENGTH);return a.writeUInt8(m.FLAG_TRAILERS,0),a.writeUInt32BE(r.length,1),Buffer.concat([a,r])}a(x,"encodeTrailerFrame");function $(c){let e=[],t=0;for(;t+m.HEADER_LENGTH<=c.length;){let o=c.readUInt8(t),n=c.readUInt32BE(t+1),r=t+m.HEADER_LENGTH,a=r+n;if(a>c.length)break;let i=c.subarray(r,a);e.push({isTrailer:(o&m.FLAG_TRAILERS)===m.FLAG_TRAILERS,payload:Buffer.from(i)}),t=a;}return e}a($,"decodeFrames");async function _(c,e,t){let o=[];c.on("data",n=>{o.push(n);}),c.on("end",async()=>{try{let n=Buffer.concat(o),a=$(n).find(p=>!p.isTrailer)?.payload??Buffer.alloc(0),i=c.url||"/";b.info(`[gRPC-Web] Handling request for ${i} (${a.length} bytes)`);let s=await t(i,a);e.statusCode=200,e.setHeader("content-type","application/grpc-web+proto"),e.setHeader("access-control-allow-origin","*"),e.setHeader("access-control-expose-headers","grpc-status, grpc-message, content-type"),s.data&&s.data.length>0&&e.write(D(s.data)),e.write(x(s.status,s.message||"")),e.end();}catch(n){b.error(`[gRPC-Web] Dispatch error: ${n}`),e.statusCode=200,e.setHeader("content-type","application/grpc-web+proto"),e.write(x(m.STATUS_INTERNAL,n.message||"Internal server error")),e.end();}});}a(_,"dispatchGrpcWebRequest");var k=2500;async function I(c,e,t){let o=t.timeoutMs??k,n=t.failMode??"closed",r=AbortSignal.timeout(o),a$1=Object.freeze(structuredClone(c)),i,s=new Promise((p,u)=>{i=a(()=>u(r.reason),"onAbortListener"),r.addEventListener("abort",i,{once:true});});try{return await Promise.race([Promise.resolve(t.interceptor(a$1,{...e,signal:r})),s])}catch(p){let u=p instanceof Error?p.message:String(p);return n==="open"?(b.warn(`[LIOP-Gateway] Interceptor error (fail-open, allowing request): ${u}`),{allowed:true,metadata:{interceptorError:u,failMode:"open"}}):(b.error(`[LIOP-Gateway] Interceptor error (fail-closed, rejecting request): ${u}`),{allowed:false,reason:`Interceptor unavailable: ${u}`,errorCode:-32098,metadata:{interceptorError:u,failMode:"closed"}})}finally{i&&r.removeEventListener("abort",i);}}a(I,"executeGatewayInterceptor");var w=class{static{a(this,"InMemoryRateLimiter");}windowMs;maxRequests;records=new Map;cleanupTimer;constructor(e={}){this.windowMs=e.windowMs??6e4,this.maxRequests=e.maxRequests??120,this.cleanupTimer=setInterval(()=>this.cleanup(),3e4),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref();}check(e){let t=Date.now(),o=this.records.get(e);return !o||t>=o.resetTime?(o={count:1,resetTime:t+this.windowMs},this.records.set(e,o),{allowed:true,remaining:this.maxRequests-1,limit:this.maxRequests,resetMs:this.windowMs}):o.count>=this.maxRequests?{allowed:false,remaining:0,limit:this.maxRequests,resetMs:Math.max(0,o.resetTime-t)}:(o.count++,{allowed:true,remaining:this.maxRequests-o.count,limit:this.maxRequests,resetMs:Math.max(0,o.resetTime-t)})}reset(e){this.records.delete(e);}cleanup(){let e=Date.now();for(let[t,o]of this.records.entries())e>=o.resetTime&&this.records.delete(t);}close(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.records.clear();}};var M=class{constructor(e,t=null,o=50051,n,r){this.liopServer=e;this.meshNode=t;this.jwtValidator=this.liopServer.jwtValidator,this.oauthProvider=this.liopServer.oauthProvider,this.rateLimiter=new w(n),this.interceptorOptions=r,this.router=new a$1(this.liopServer,this.meshNode,o),this.h2Server=j.createServer(),this.setupH2Routes(),this.h1Server=L.createServer(),this.setupH1Routes(),this.netServer=H.createServer(a=>{a.once("data",i=>{let s=i.toString().startsWith("PRI * HTTP/2.0");b.info(`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${s?"HTTP/2 (gRPC)":"HTTP/1.1 (MCP)"}`),s?this.h2Server.emit("connection",a):this.h1Server.emit("connection",a),a.unshift(i);}),a.on("error",i=>b.error(`[LIOP-Gateway] NetServer Socket Error: ${i.message}`));}),this.h1Server.on("error",a=>b.error(`[LIOP-Gateway] H1 Server Error: ${a.message}`)),this.h2Server.on("error",a=>b.error(`[LIOP-Gateway] H2 Server Error: ${a.message}`)),b.info("[LIOP-Gateway] Hybrid adapter initialized.");}liopServer;meshNode;static{a(this,"LiopHybridGateway");}netServer;h2Server;h1Server;router;jwtValidator;oauthProvider;rateLimiter;interceptorOptions;isDraining=false;activeRequests=0;setupH2Routes(){this.h2Server.on("stream",(e,t)=>{let o=t["content-type"],n=t[":path"];o==="application/grpc"?this.handleGrpcStream(e):n==="/mcp"&&this.handleMcpH2Stream(e,t);});}setupH1Routes(){this.h1Server.on("request",async(e$1,t)=>{this.activeRequests+=1;let o=a(()=>{t.removeListener("finish",o),t.removeListener("close",o),this.activeRequests=Math.max(0,this.activeRequests-1);},"onDone");t.on("finish",o),t.on("close",o);let n=e$1.url||"",r=e$1.method;if(r==="GET"&&n==="/metrics"){this.meshNode&&i.set({},this.meshNode.getPeers().length),this.router&&j$1.set({},this.router.getManifestCacheSize()),t.writeHead(200,{"Content-Type":"text/plain; version=0.0.4; charset=utf-8"}),t.end(e.exportPrometheusText());return}if(r==="GET"&&n==="/healthz"){if(this.isDraining){t.writeHead(503,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"draining",timestamp:new Date().toISOString()}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"ok",uptime:Math.floor(process.uptime()),timestamp:new Date().toISOString()}));return}if(r==="GET"&&n==="/readyz"){if(this.isDraining){t.writeHead(503,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"draining",timestamp:new Date().toISOString()}));return}if(!(this.meshNode?this.meshNode.isStarted():true)){t.writeHead(503,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"unready",meshStarted:false,timestamp:new Date().toISOString()}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"ready",meshStarted:true,peers:this.meshNode?this.meshNode.getPeers().length:0,timestamp:new Date().toISOString()}));return}if(this.isDraining&&n==="/mcp"){t.writeHead(503,{"Content-Type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Gateway is draining connections for shutdown"}}));return}let a$1=e$1.headers["content-type"];if(G(a$1)){await _(e$1,t,async(i,s)=>(b.info(`[LIOP-Gateway] gRPC-Web fallback call: ${i} (${s.length} bytes)`),{status:m.STATUS_OK,message:"OK",data:Buffer.from("")}));return}if(n.startsWith("/oidc")&&this.oauthProvider){let i=typeof this.oauthProvider.callback=="function"?this.oauthProvider.callback():this.oauthProvider,s=e$1.url;e$1.url=(s||"").slice(5)||"/";try{return i(e$1,t)}finally{e$1.url=s;}}if(r==="GET"&&n==="/.well-known/oauth-protected-resource"){if(this.jwtValidator){let i=A(this.jwtValidator.getIssuer(),this.jwtValidator.getAudience());t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(i));return}t.writeHead(404),t.end("Not Found");return}if(r==="GET"&&(n==="/"||n==="/mcp"||n==="/health")){if(n==="/health"&&e$1.headers.accept?.includes("application/json")){let i=this.meshNode?{peerId:this.meshNode.getPeerId()?.toString()||"",multiaddrs:this.meshNode.getMultiaddrs().map(d=>d.toString())}:null,s=this.jwtValidator?.getIssuer(),p=s?s.endsWith("/oidc")?s:`${s}/oidc`:"",u=this.jwtValidator&&s?{issuer:s,jwks_uri:`${p}/jwks`,...this.oauthProvider?{token_endpoint:`${p}/token`}:{}}:void 0,f={tier:this.meshNode?.isPrivateNetwork?.()?1:2,prmEndpoint:this.jwtValidator?"/.well-known/oauth-protected-resource":void 0,transportCapabilities:["http-mcp","grpc-lio","p2p-dht"]};t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"healthy",node:this.liopServer.getServerInfo(),mesh:i,tools:this.liopServer.listTools().map(d=>d.name),auth:u,topology:f,timestamp:new Date().toISOString()}));return}t.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),t.end(`
|
|
4
|
+
<body style="background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0">
|
|
5
|
+
<div style="background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)">
|
|
6
|
+
<h1 style="color:#38bdf8;margin-top:0">LIOP Protocol Transformer</h1>
|
|
7
|
+
<p style="opacity:0.8;font-weight:600">L4/L7 Transcoding: JSON-RPC ↔ gRPC</p>
|
|
8
|
+
<p style="opacity:0.6;font-size:14px">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>
|
|
9
|
+
<div style="background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155">
|
|
10
|
+
<code style="color:#10b981">Endpoint: http://localhost:3000/mcp</code>
|
|
11
|
+
</div>
|
|
12
|
+
</div>
|
|
13
|
+
</body>
|
|
14
|
+
`);return}if(n==="/mcp"&&r==="POST"){let i=null;if(this.jwtValidator){let p=e$1.headers.authorization;if(!p?.startsWith("Bearer ")){t.writeHead(401,{"WWW-Authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}try{i=await this.jwtValidator.validate(p.slice(7));}catch(u){t.writeHead(401,{"WWW-Authenticate":`Bearer error="invalid_token", error_description="${u.message}"`,"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid token"}));return}}let s="";e$1.on("data",p=>s+=p.toString()),e$1.on("end",async()=>{let p=e$1.socket.remoteAddress||"127.0.0.1",u=i?.clientId?`client:${i.clientId}`:`ip:${p}`,f=this.rateLimiter.check(u);if(!f.allowed){t.writeHead(429,{"Content-Type":"application/json","Retry-After":Math.ceil(f.resetMs/1e3).toString()}),t.end(JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32029,message:"Rate limit exceeded. Too many requests."}}));return}try{let d=JSON.parse(s);if(this.interceptorOptions?.interceptor){let T=await I(d,{clientIp:p,authInfo:i,protocol:"http1"},this.interceptorOptions);if(!T.allowed){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:d.id??null,error:{code:T.errorCode??-32099,message:T.reason||"Forbidden: Rejected by Gateway Interceptor"}}));return}}let S=e$1.headers["mcp-method"],v=e$1.headers["mcp-name"],R=e$1.headers["mcp-protocol-version"];if(S&&S!==d.method){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:d.id??null,error:{code:-32020,message:`HeaderMismatch: 'Mcp-Method' header (${S}) does not match JSON-RPC method (${d.method})`}}));return}if(v&&d.params?.name&&v!==d.params.name){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({jsonrpc:"2.0",id:d.id??null,error:{code:-32020,message:`HeaderMismatch: 'Mcp-Name' header (${v}) does not match target name (${d.params.name})`}}));return}R&&d.params&&(d.params._meta||(d.params._meta={}),d.params._meta["io.modelcontextprotocol/protocolVersion"]||(d.params._meta["io.modelcontextprotocol/protocolVersion"]=R));let C=await this.router.dispatch(d,i);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(C));}catch(d){b.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${d.message}`),t.writeHead(400),t.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else t.writeHead(404),t.end("Not Found");});}handleGrpcStream(e){e.on("data",t=>{let o=t;o&&b.info(`[LIOP-Gateway] Native gRPC Proxy passing ${o.length} bytes`);}),e.respond({":status":200,"content-type":"application/grpc"}),e.end();}handleMcpH2Stream(e,t){let o="";e.on("data",n=>o+=n.toString()),e.on("end",async()=>{try{let n=null;if(this.jwtValidator){let u=t.authorization;if(!u?.startsWith("Bearer ")){e.respond({":status":401,"www-authenticate":'Bearer error="invalid_token", error_description="Missing or malformed Authorization header"',"content-type":"application/json"}),e.end(JSON.stringify({error:"Unauthorized"}));return}try{n=await this.jwtValidator.validate(u.slice(7));}catch(f){e.respond({":status":401,"www-authenticate":`Bearer error="invalid_token", error_description="${f.message}"`,"content-type":"application/json"}),e.end(JSON.stringify({error:"Invalid token"}));return}}let r=JSON.parse(o);if(this.interceptorOptions?.interceptor){let u=e.session?.socket?.remoteAddress||"127.0.0.1",f=await I(r,{clientIp:u,authInfo:n,protocol:"http2"},this.interceptorOptions);if(!f.allowed){e.respond({":status":403,"content-type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",id:r.id??null,error:{code:f.errorCode??-32099,message:f.reason||"Forbidden: Rejected by Gateway Interceptor"}}));return}}let a=t["mcp-method"],i=t["mcp-name"],s=t["mcp-protocol-version"];if(a&&a!==r.method){e.respond({":status":400,"content-type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",id:r.id??null,error:{code:-32020,message:`HeaderMismatch: 'Mcp-Method' header (${a}) does not match JSON-RPC method (${r.method})`}}));return}if(i&&r.params?.name&&i!==r.params.name){e.respond({":status":400,"content-type":"application/json"}),e.end(JSON.stringify({jsonrpc:"2.0",id:r.id??null,error:{code:-32020,message:`HeaderMismatch: 'Mcp-Name' header (${i}) does not match target name (${r.params.name})`}}));return}s&&r.params&&(r.params._meta||(r.params._meta={}),r.params._meta["io.modelcontextprotocol/protocolVersion"]||(r.params._meta["io.modelcontextprotocol/protocolVersion"]=s));let p=await this.router.dispatch(r,n);p?(e.respond({":status":200,"content-type":"application/json"}),e.end(JSON.stringify(p))):e.close();}catch{e.respond({":status":400}),e.end();}});}async listen(e,t="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let o=this.liopServer.listTools();for(let n of o)await this.meshNode.announceCapability(n.name),b.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${n.name}`);}return new Promise((o,n)=>{this.netServer.on("error",r=>{r.code==="EADDRINUSE"?b.info(`[LIOP-Gateway] FATAL: Port ${e} is already in use by another process.`):b.error(`[LIOP-Gateway] Binding Error: ${r.message}`),n(r);}),this.netServer.listen(e,t,()=>{let r=this.netServer.address(),a=typeof r=="string"?r:r?.address||t,i=typeof r=="string"?e:r?.port||e;b.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${a}:${i}`),o(i);});})}isDrained(){return this.isDraining}async drain(e=5e3){this.isDraining=true,b.info(`[LIOP-Gateway] Draining gateway connections (active: ${this.activeRequests}, timeout: ${e}ms)...`);let t=Date.now();for(;this.activeRequests>0&&Date.now()-t<e;)await new Promise(o=>setTimeout(o,50));await this.stop();}async stop(){this.meshNode&&await this.meshNode.stop(),this.rateLimiter.close(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{m as a,G as b,D as c,x as d,$ as e,_ as f,A as g,I as h,w as i,M as j};//# sourceMappingURL=chunk-LEXMMIQI.js.map
|
|
15
|
+
//# sourceMappingURL=chunk-LEXMMIQI.js.map
|