@nekzus/liop 2.6.1 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -38
- package/dist/bin/agent.js +27 -894
- 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 +0 -1
- 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 +5 -4
- package/dist/client.js +1 -11
- package/dist/gateway.d.ts +6 -5
- package/dist/gateway.js +1 -11
- package/dist/{hybrid-DWe1bMoV.d.ts → hybrid-BZpCiUaV.d.ts} +4 -4
- package/dist/{index-BuEQtBHD.d.ts → index-BYDtRGue.d.ts} +8 -4
- package/dist/{index-CdW8j8Bn.d.ts → index-ByzjpRCk.d.ts} +30 -2
- package/dist/index.d.ts +57 -10
- package/dist/index.js +4 -317
- package/dist/kyber-PULV7PQX.js +2 -0
- package/dist/mesh.d.ts +1 -1
- package/dist/mesh.js +1 -5
- package/dist/{node-B0b2vUFS.d.ts → node-Djzm6UYd.d.ts} +8 -0
- package/dist/protocol/liop_core.proto +22 -6
- package/dist/server.d.ts +4 -3
- package/dist/server.js +1 -8
- package/dist/{types-CzRSOlOo.d.ts → types-29zv9X1V.d.ts} +3 -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 +7 -2
- package/dist/bin/agent.js.map +0 -1
- package/dist/bridge.js.map +0 -1
- package/dist/chunk-2KSO3W4A.js +0 -77
- package/dist/chunk-2KSO3W4A.js.map +0 -1
- package/dist/chunk-2STZHJ24.js +0 -114
- package/dist/chunk-2STZHJ24.js.map +0 -1
- package/dist/chunk-3QH44NKZ.js +0 -115
- package/dist/chunk-3QH44NKZ.js.map +0 -1
- package/dist/chunk-5SWHE62F.js +0 -3683
- package/dist/chunk-5SWHE62F.js.map +0 -1
- package/dist/chunk-7BSCUYUE.js +0 -421
- package/dist/chunk-7BSCUYUE.js.map +0 -1
- package/dist/chunk-7PITYWOV.js +0 -68
- package/dist/chunk-7PITYWOV.js.map +0 -1
- package/dist/chunk-EJ426URA.js +0 -818
- package/dist/chunk-EJ426URA.js.map +0 -1
- package/dist/chunk-FCFTYOAS.js +0 -793
- package/dist/chunk-FCFTYOAS.js.map +0 -1
- package/dist/chunk-FTF6AMF6.js.map +0 -1
- package/dist/chunk-IK7CGWAZ.js +0 -24
- package/dist/chunk-IK7CGWAZ.js.map +0 -1
- package/dist/chunk-K3DGJLUY.js +0 -106
- package/dist/chunk-K3DGJLUY.js.map +0 -1
- package/dist/chunk-PAICJCKJ.js +0 -332
- package/dist/chunk-PAICJCKJ.js.map +0 -1
- package/dist/chunk-PUDETPL4.js +0 -279
- package/dist/chunk-PUDETPL4.js.map +0 -1
- package/dist/chunk-UJFWPRDM.js +0 -206884
- package/dist/chunk-UJFWPRDM.js.map +0 -1
- package/dist/chunk-VRB5HUYU.js +0 -1492
- package/dist/chunk-VRB5HUYU.js.map +0 -1
- package/dist/chunk-VRDZ5IKE.js +0 -558
- package/dist/chunk-VRDZ5IKE.js.map +0 -1
- package/dist/chunk-WPTOJYN5.js +0 -181
- package/dist/chunk-WPTOJYN5.js.map +0 -1
- package/dist/chunk-XRDN232O.js +0 -877
- package/dist/chunk-XRDN232O.js.map +0 -1
- package/dist/chunk-Y62GORQF.js +0 -51
- package/dist/chunk-Y62GORQF.js.map +0 -1
- package/dist/chunk-ZP3VVXOI.js +0 -66
- package/dist/chunk-ZP3VVXOI.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-CGOA7Q6A.js +0 -3
- package/dist/kyber-CGOA7Q6A.js.map +0 -1
- package/dist/mesh.js.map +0 -1
- package/dist/server.js.map +0 -1
- package/dist/types.js.map +0 -1
- package/dist/verifier-COnid_dg.d.ts +0 -31
- package/dist/verifier-XFU7ZB2W.js +0 -6
- package/dist/verifier-XFU7ZB2W.js.map +0 -1
- package/dist/workers/logic-execution.js.map +0 -1
- package/dist/workers/zk-verifier.js.map +0 -1
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 './node-
|
|
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-2KSO3W4A.js';
|
|
3
|
-
import './chunk-K3DGJLUY.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
|
package/dist/chunk-FTF6AMF6.js
CHANGED
|
@@ -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
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-6KFKO6ZX.js';import {a as a$3}from'./chunk-Y675R34Z.js';import {a as a$2}from'./chunk-XLVEDKM6.js';import {b as b$2}from'./chunk-2ZYX736J.js';import {f,g as g$1,i,j}from'./chunk-ECRS6N33.js';import {f as f$2,g as g$2,u,v,m,w}from'./chunk-ZZMSFCJP.js';import {h,d,e,b as b$1,c,f as f$1,g}from'./chunk-GWVSCZUS.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as D from'crypto';import*as H from'@grpc/grpc-js';function M(){let I=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(I==="0"||I==="false"||I==="no")}a(M,"mcpCompactToolDescriptions");function F(I){let o=I,p=[`
|
|
2
|
+
|
|
3
|
+
[LIOP-PROTO-V1:`,`\r
|
|
4
|
+
\r
|
|
5
|
+
[LIOP-PROTO-V1:`,`
|
|
6
|
+
[LIOP-PROTO-V1:`];for(let n of p){let a=o.indexOf(n);if(a!==-1){o=o.slice(0,a);break}}return o.trimEnd()}a(F,"stripVerboseLiopToolDescription");var ae=300,B=5,ce=class I{constructor(o,p=null,n=50051){this.liopServer=o;this.meshNode=p;this.defaultRpcPort=n;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let a=this.liopServer.listTools().map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),c=this.liopServer.listResources().map(s=>({name:s.name,uri:s.uri,description:s.description,mimeType:s.mimeType})),e=this.liopServer.config;return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...a],resources:c,serverInfo:this.liopServer.getServerInfo(),authRequired:this.liopServer.jwtValidator!==void 0,tokenSlug:e?.tokenSlug,taxonomy:e?.taxonomy?{domain:e.taxonomy.domain||"Unknown Domain",clearanceTier:e.taxonomy.clearanceTier??0,executionTypes:e.taxonomy.executionTypes||[]}:void 0}}),this.meshNode.announceManifest().catch(a=>{b.info(`[LIOP-Router] Failed to announce manifest: ${a instanceof Error?a.message:String(a)}`);})),process.env.LIOP_DIAGNOSTIC_LEVEL==="full"&&process.stderr.write(`\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.
|
|
7
|
+
`);}liopServer;meshNode;defaultRpcPort;static{a(this,"LiopMcpRouter");}manifestCache=new Map;currentDiscovery=null;verifier=new a$1;onToolsChanged;manifestFailureState=new Map;static MANIFEST_FAILURE_BASE_COOLDOWN_MS=15e3;static MANIFEST_FAILURE_MAX_COOLDOWN_MS=5*6e4;static MANIFEST_SKIP_LOG_THROTTLE_MS=3e4;getManifestCacheSize(){return this.manifestCache.size}shouldSkipManifestQuery(o){let p=this.manifestFailureState.get(o);if(!p)return false;let n=Date.now();return n>=p.cooldownUntil?false:(n-p.lastSkipLogAt>I.MANIFEST_SKIP_LOG_THROTTLE_MS&&(b.info(`[LIOP-Router] Skipping manifest query for ${o} during cooldown (${Math.ceil((p.cooldownUntil-n)/1e3)}s remaining)`),p.lastSkipLogAt=n),true)}recordManifestQuerySuccess(o){this.manifestFailureState.delete(o);}recordManifestQueryFailure(o){let p=Date.now(),a=(this.manifestFailureState.get(o)?.failures||0)+1,c=Math.min(I.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,a-1),I.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(o,{failures:a,cooldownUntil:p+c,lastSkipLogAt:0});}detectEra(o){return o.params?._meta?.["io.modelcontextprotocol/protocolVersion"]===h?"modern":d(o)?"legacy":"modern"}async dispatch(o,p){let{method:n,params:a,id:c$1}=o;if(b.info(`[LIOP-Router] Processing: ${n}`),this.liopServer.jwtValidator){let e=a$2(n,p??null);if(!e.allowed)return b.info(`[LIOP-Router] RBAC Access Denied for method '${n}': ${e.reason}`),{jsonrpc:"2.0",id:c$1,error:{code:-32099,message:e.reason||"Access Denied"}}}switch(n){case "initialize":return b.info("[LIOP-Router] \u26A0\uFE0F Legacy MCP client detected (2025-era initialize)."),c(this.liopServer.getServerInfo(),c$1);case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "server/discover":return {jsonrpc:"2.0",id:c$1,result:{resultType:"complete",supportedVersions:[h,b$1],capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "ping":return {jsonrpc:"2.0",id:c$1,result:{}};case "tools/list":{let e$1=this.liopServer.listTools(),s=await this.getRemoteTools(),r=M()?e$1.map(g=>({...g,description:F(g.description??"")})):e$1;b.info(`[LIOP-Router] tools/list: ${e$1.length} local, ${s.length} remote tools found`);let u=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...r,...s].sort((g,y)=>g.name.localeCompare(y.name)),t=f.getInstance(),i=JSON.stringify(u),f$1=JSON.stringify({tools:u});t.record({type:"tools_list",method:"tools/list",estimatedInputTokens:t.countTokens(i),estimatedOutputTokens:t.countTokens(f$1)});let h=this.detectEra(o),m={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:u}};return h==="legacy"&&true&&(m=e(m)),m}case "tools/call":{let e$1=await this.transcodeMcpToLiop(c$1,a,p?.token);if(!e$1)return null;if(this.detectEra(o)==="legacy"&&true)return e(e$1);if(e$1.result&&typeof e$1.result=="object"){let r=e$1.result;r.resultType||(r.resultType="complete");}return e$1}case "resources/list":{let e$1=this.liopServer.listResources(),s=await this.getRemoteResources(),r=[...e$1,...s].sort((f,h)=>f.uri.localeCompare(h.uri)),l=f.getInstance(),u=JSON.stringify(r);l.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:l.countTokens(u)});let t=this.detectEra(o),i={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resources:r}};return t==="legacy"&&true&&(i=e(i)),i}case "resources/read":{let e$1=a;if(!e$1?.uri)return {jsonrpc:"2.0",id:c$1,error:{code:-32602,message:"Missing resource uri"}};try{let s=Date.now(),r=await this.liopServer.readResource(e$1.uri),l=f.getInstance(),u=JSON.stringify(r);l.record({type:"resource_read",method:"resources/read",toolName:e$1.uri,estimatedInputTokens:l.countTokens(e$1.uri),estimatedOutputTokens:l.countTokens(u),durationMs:Date.now()-s});let t=this.detectEra(o),i=typeof r=="object"&&r!==null?{resultType:"complete",ttlMs:6e4,cacheScope:"private",...r}:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:r},f$1={jsonrpc:"2.0",id:c$1,result:i};return t==="legacy"&&!0&&(f$1=e(f$1)),f$1}catch(s){let r=e$1.uri;for(let{manifest:l}of this.manifestCache.values()){let u=l.resources.find(t=>t.uri===r);if(u){b.info(`[LIOP-Router] Resolved resource ${r} from cache (Peer: ${l.peerId})`);let t=this.detectEra(o),i={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:[{uri:u.uri,mimeType:u.mimeType||"text/plain",text:u.text||u.description||"No content provided"}]}};return t==="legacy"&&true&&(i=e(i)),i}}return {jsonrpc:"2.0",id:c$1,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}case "prompts/list":{let e$1=this.liopServer.listPrompts().sort((t,i)=>t.name.localeCompare(i.name)),s=f.getInstance(),r=JSON.stringify(e$1);s.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:s.countTokens(r)});let l=this.detectEra(o),u={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",prompts:e$1}};return l==="legacy"&&true&&(u=e(u)),u}case "prompts/get":{let e$1=a;if(!e$1?.name)return {jsonrpc:"2.0",id:c$1,error:{code:-32602,message:"Missing prompt name"}};try{let s=Date.now(),r=await this.liopServer.getPrompt({name:e$1.name,arguments:e$1.arguments||{}}),l=f.getInstance(),u=JSON.stringify({name:e$1.name,arguments:e$1.arguments}),t=JSON.stringify(r);l.record({type:"prompt_get",method:"prompts/get",toolName:e$1.name,estimatedInputTokens:l.countTokens(u),estimatedOutputTokens:l.countTokens(t),durationMs:Date.now()-s});let i=this.detectEra(o),f$1=typeof r=="object"&&r!==null?{resultType:"complete",...r}:r,h={jsonrpc:"2.0",id:c$1,result:f$1};return i==="legacy"&&!0&&(h=e(h)),h}catch(s){return {jsonrpc:"2.0",id:c$1,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}case "resources/templates/list":{let e$1=this.detectEra(o),s={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resourceTemplates:[]}};return e$1==="legacy"&&true&&(s=e(s)),s}case "subscriptions/listen":{let e$1=this.detectEra(o),s={jsonrpc:"2.0",id:c$1,result:{resultType:"complete"}};return e$1==="legacy"&&true&&(s=e(s)),s}default:return {jsonrpc:"2.0",id:c$1,error:{code:-32601,message:`Method not found: ${n}`}}}}kickDiscoveryAfterInitialized(){return (async()=>{await new Promise(o=>setTimeout(o,250)),await Promise.race([this.refreshManifestCache(true),new Promise(o=>setTimeout(o,15e3))]).catch(()=>{});})()}async refreshManifestCache(o=false){if(this.meshNode){if(this.currentDiscovery)return this.currentDiscovery;if(!o&&this.manifestCache.size>0){let p=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:a})=>p-a<ae*1e3))return}return this.currentDiscovery=(async()=>{try{let p=Array.from(this.manifestCache.values()).reduce((t,{manifest:i})=>t+i.tools.length,0);if(this.manifestCache.size===0)for(let t=0;t<3;t++){if((this.meshNode.node?.getConnections().length||0)>0){b.info("[LIOP-Router] P2P Connection established. Starting discovery...");break}b.info(`[LIOP-Router] Waiting for P2P connections (attempt ${t+1}/10)...`),await new Promise(f=>setTimeout(f,1e3));}let n=[],a=this.manifestCache.size===0?5:1;for(let t=0;t<a;t++){for(let m=0;m<B;m++){n=await this.meshNode?.discoverManifestProviders()||[];let g=this.meshNode?.getPeerId();if(n.filter(v=>v!==g).length>0)break;m<B-1&&(b.info(`[LIOP-Router] DHT discovery attempt ${m+1}/${B}...`),await new Promise(v=>setTimeout(v,1e3)));}let i=this.meshNode.node?.getConnections().map(m=>m.remotePeer.toString())||[];i.length>0&&(n=Array.from(new Set([...n,...i])));let f=this.meshNode?.getPeerId();if(n.filter(m=>m!==f).length>0)break;t<a-1&&(b.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${t+1}/${a})...`),await new Promise(m=>setTimeout(m,1e3)));}if(n.length===0){b.info("[LIOP-Router] No manifest providers found after all attempts.");return}o||b.info(`[LIOP-Router] Discovered ${n.length} candidate manifest providers`);let c=new Set((this.meshNode.node?.getConnections?.()||[]).map(t=>t.remotePeer.toString()));n=[...n].sort((t,i)=>{let f=c.has(t)?1:0;return (c.has(i)?1:0)-f});let e=0,s=0,r=!1,l=this.meshNode?.getPeerId(),u=n.filter(t=>{if(!this.meshNode||t===l||this.shouldSkipManifestQuery(t))return !1;let i=this.manifestCache.get(t);return i&&Date.now()-i.cachedAt<ae*1e3?(e++,!1):!0});await Promise.allSettled(u.map(async t=>{if(this.meshNode){b.info(`[LIOP-Router] Querying manifest from: ${t}`);try{let i=await this.meshNode.queryManifest(t);if(i){if(i.pqcSignature&&i.pqcPublicKey){if(!b$2.verifyManifest(i,i.pqcSignature,i.pqcPublicKey)){b.warn(`[LIOP-Router] \u26A0\uFE0F Tampered manifest rejected for peer ${t} (ML-DSA-65 signature invalid)`),this.recordManifestQueryFailure(t),s++;return}b.info(`[LIOP-Router] \u{1F512} ML-DSA-65 (FIPS 204) Manifest attestation verified for peer ${t}`);}this.manifestCache.set(t,{manifest:i,cachedAt:Date.now()}),this.recordManifestQuerySuccess(t),r=!0,e++,b.info(`[LIOP-Router] Manifest received from ${t} (${i.tools.length} tools)`);}else this.recordManifestQueryFailure(t),s++,b.info(`[LIOP-Router] Manifest query returned NULL for ${t}`);}catch(i){s++,b.info("[LIOP-Router] Fatal error querying manifest:",i instanceof Error?i.message:String(i));}}})),this._discoveryStats={candidates:n.length,success:e,failures:s,lastDiscovery:Date.now()},r&&Array.from(this.manifestCache.values()).reduce((i,{manifest:f})=>i+f.tools.length,0)!==p&&this.onToolsChanged&&(process.stderr.write(`[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.
|
|
8
|
+
`),this.onToolsChanged());}finally{this.currentDiscovery=null;}})(),this.currentDiscovery}}getCacheSize(){return this.manifestCache.size}async getRemoteTools(){let o=Number.parseInt(process.env.LIOP_EXPECTED_PROVIDERS??"1",10);if(this.manifestCache.size<o&&this.meshNode){let c=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),e=Number.isFinite(c)&&c>0?c:12e3,s=Date.now()+e,r=0,l=-1;for(;Date.now()<s&&!(this.manifestCache.size>=o||(await Promise.race([this.refreshManifestCache(true),new Promise(u=>setTimeout(u,3e3))]).catch(()=>{}),this.manifestCache.size>=o));){if(this.manifestCache.size===l){if(r++,r>=3&&this.manifestCache.size>0){b.info(`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${o}. Proceeding with available mesh.`);break}}else r=0,l=this.manifestCache.size;await new Promise(u=>setTimeout(u,1e3));}this.manifestCache.size<o&&(b.info(`[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${o} providers. Some tools may be unavailable. Check Docker containers.`),this.refreshManifestCache(true).catch(()=>{}));}let p=[],n=new Set,a=new Set(this.liopServer.listTools().map(c=>c.name));for(let[c,{manifest:e}]of this.manifestCache.entries())for(let s of e.tools){if(s.name==="LiopMeshStatus")continue;let r=s.name;(n.has(s.name)||a.has(s.name))&&(r=`${s.name}_${c.slice(-4)}`),n.add(r);let l=e.serverInfo?.name||"Unknown Provider",u=s.description||`Remote tool from ${l}`,t={name:r,description:M()?F(u):u,inputSchema:s.inputSchema||{type:"object",properties:{}}};typeof t.inputSchema=="object"&&!t.inputSchema.type&&(t.inputSchema.type="object"),typeof t.inputSchema=="object"&&!t.inputSchema.properties&&(t.inputSchema.properties={});let i="";e.taxonomy&&(i=`
|
|
9
|
+
[LIOP-DOMAIN: ${e.taxonomy.domain}]`);let f=t.inputSchema.properties||{},h="";!M()&&f.payload&&(h=`
|
|
10
|
+
[REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!M()&&t.description.includes("STRICT SCHEMA ADHERENCE")&&(t.description=t.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let m=M()?`
|
|
11
|
+
(Peer: ${c.slice(-8)})${i}`:`
|
|
12
|
+
(Origin: ${c.slice(-8)})${i}${h}`;t.description=`${t.description}${m}`,p.push(t);}return p}async getRemoteResources(){this.currentDiscovery||this.refreshManifestCache(true).catch(()=>{});let o=[],p=new Set(this.liopServer.listResources().map(n=>n.uri));for(let[n,{manifest:a}]of this.manifestCache.entries())for(let c of a.resources)if(!p.has(c.uri)){let e={...c},s=a.serverInfo?.name||"Unknown Provider",r="";a.taxonomy&&(r=`
|
|
13
|
+
|
|
14
|
+
[LIOP Zero-Trust Blueprint]
|
|
15
|
+
Domain: ${a.taxonomy.domain}
|
|
16
|
+
Clearance Tier: ${a.taxonomy.clearanceTier}`,a.taxonomy.executionTypes&&a.taxonomy.executionTypes.length>0&&(r+=`
|
|
17
|
+
Execution Types: ${a.taxonomy.executionTypes.join(", ")}`));let l=`
|
|
18
|
+
|
|
19
|
+
[LIOP Zero-Trust Origin]
|
|
20
|
+
Provider: ${s}
|
|
21
|
+
Network ID: ${n}${r}`;e.uri.startsWith("liop://schema/")?(e.name=`[SCHEMA] ${e.name}`,e.description=`[CRITICAL SCHEMA] ${e.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):e.description=e.description?`${e.description}${l}`:l.trim(),o.push(e),p.add(c.uri);}return o}resolveManifestTarget(o){let p=f$1[o]||o;for(let[a,{manifest:c}]of this.manifestCache.entries()){let e=c.tools.find(s=>s.name===o||s.name===p);if(e)return {peerId:a,originalToolName:e.name}}let n=o.split("_");if(n.length>1){let a=n.pop(),c=n.join("_"),e=f$1[c]||c;for(let[s,{manifest:r}]of this.manifestCache.entries())if(s.endsWith(a||"")){let l=r.tools.find(u=>u.name===c||u.name===e);if(l)return {peerId:s,originalToolName:l.name}}}return null}redactPeerId(o){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?o:`***${o.slice(-8)}`}async transcodeMcpToLiop(o,p,n){p?.arguments&&(p.arguments=g(p.arguments));let a=p.name;if(a==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let e=this._discoveryStats||{candidates:0,success:0,failures:0},s=this.manifestCache.size,r=this.meshNode?"Active":"Offline",l=Array.from(this.manifestCache.values()).reduce((P,{manifest:L})=>P+L.tools.length,0),u=this.meshNode?this.meshNode.node?.getConnections().length:0,t=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],i=t.length,h=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",m=h?t.map(P=>{let L=P.split("/"),C=L[L.length-1];return ` \u2022 ${C?C.slice(-8):"Unknown"} (bootstrap)`}).join(`
|
|
22
|
+
`):"",g=this.meshNode?this.meshNode.getRoutingTableSize():0,y=this.meshNode?.getPeerId()||"Offline",v=y==="Offline"?y:this.redactPeerId(y),E=Array.from(this.manifestCache.entries()).flatMap(([P,{manifest:L}])=>L.tools.map(C=>` \u2022 ${C.name} (from origin: ${this.redactPeerId(P)})`)).join(`
|
|
23
|
+
`),_=[`LIOP Mesh Status: ${r==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${v}`,`Network: ${u} Conns | ${g} Mesh Nodes | ${i} Bootstraps`,h&&i>0?`
|
|
24
|
+
Active Bootstraps:
|
|
25
|
+
${m}
|
|
26
|
+
`:"",`Discovery: ${e.candidates} Candidates | ${e.success} OK | ${e.failures} FAIL`,`Tooling: ${s} Providers | ${l} Total Remote Tools`,l>0?`
|
|
27
|
+
Discovered Remote Tools (Zero-Trust Origins):
|
|
28
|
+
${E}`:`
|
|
29
|
+
No remote tools discovered yet.`,f.getInstance().formatStatusBlock()].filter(P=>P!=="").join(`
|
|
30
|
+
`),w=f.getInstance();return w.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:w.countTokens(_)}),{jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:_}]}}}let c=this.liopServer.listTools().some(e=>e.name===a);if(!c&&this.meshNode){let e=this.resolveManifestTarget(a);if(e||(await this.refreshManifestCache(),e=this.resolveManifestTarget(a)),e){b.info(`[LIOP-Router] Resolved ${a} via manifest cache (Peer: ${e.peerId}, Original: ${e.originalToolName})`);let r=this.manifestCache.get(e.peerId),l=n;if(r?.manifest.authRequired){let u=n||await this.getOrAcquireMeshAgentToken(e.peerId);if(!u){let t=r.manifest.serverInfo?.name?.toLowerCase()||"unknown",i=r.manifest.tokenSlug,f=e.peerId.slice(-8).toUpperCase(),h=i?`LIOP_TOKEN_${i}`:`LIOP_TOKEN_${t.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${t}) requires an access token. Please define the ${h} or LIOP_TOKEN_${f} environment variable on your agent/client host.`}],isError:true}}}l=u;}return this.routeToRemoteProvider(o,e.originalToolName,e.peerId,p,l)}let s=[];for(let r=0;r<3&&(s=await this.meshNode.findProviders(a),!(s.length>0));r++)r<2&&await new Promise(l=>setTimeout(l,1e3));if(s.length>0)return this.routeToRemoteProvider(o,a,s[0],p,n)}if(c)try{let e=Date.now(),s=await this.liopServer.callTool({name:a,arguments:p.arguments||{}}),r=f.getInstance(),l=JSON.stringify(p.arguments||{}),u=JSON.stringify(s),t,i=this.liopServer.getSandboxData();return i&&i.length>0&&(t=r.countTokens(JSON.stringify(i))),r.record({type:"tool_call",method:"tools/call",toolName:a,estimatedInputTokens:r.countTokens(l),estimatedOutputTokens:r.countTokens(u),durationMs:Date.now()-e,originDatasetTokens:t}),f$2.inc({capability:a,tool:a,status:s.isError?"error":"success",role:"executor"}),{jsonrpc:"2.0",id:o,result:s}}catch(e){return {jsonrpc:"2.0",id:o,error:{code:-32e3,message:e instanceof Error?e.message:String(e)}}}return {jsonrpc:"2.0",id:o,error:{code:-32002,message:`No provider found for tool: ${a}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(o,p,n,a,c){if(!this.meshNode)return {jsonrpc:"2.0",id:o,error:{code:-32603,message:"Mesh Node inactive"}};let e=this.manifestCache.get(n),s=this.defaultRpcPort;if(e)s=e.manifest.grpcPort;else {let m=await this.meshNode.queryManifest(n);m&&(s=m.grpcPort,this.manifestCache.set(n,{manifest:m,cachedAt:Date.now()}),e=this.manifestCache.get(n));}let r=await this.meshNode.resolvePeer(n),l=process.env.LIOP_NEXUS_URL||"",u=l.includes("127.0.0.1:13000")||l.includes("localhost:13000")||l.includes("127.0.0.1:13001")||l.includes("localhost:13001"),t=r.some(m=>m.includes("13001")||m.includes("13003")||m.includes("13004")||m.includes("13005")||m.includes("13011")||m.includes("13021")||m.includes("13031")),i$1=process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||u||t;if(i$1){let m=e?.manifest?.serverInfo?.name?.toLowerCase()||"",g=p.toLowerCase();m.includes("vault")||g.includes("medical")?s=13011:m.includes("bank")||g.includes("bank")?s=13021:(m.includes("oracle")||g.includes("hft")||g.includes("market"))&&(s=13031);}let f=null;if(i$1)f=`127.0.0.1:${s}`;else {let m=await import('os'),g=Object.values(m.networkInterfaces()).flat().filter(y=>y?.family==="IPv4").map(y=>y?.address);for(let y of r){let v=y.split("/"),E=v.indexOf("ip4");if(E!==-1){let _=v[E+1];if(_==="127.0.0.1"||g.includes(_)){f=`127.0.0.1:${s}`;break}f||(f=`${_}:${s}`);}}}f||(f=`127.0.0.1:${s}`),b.info(`[LIOP-Router] Dynamic route: ${p} -> ${f} (PeerID: ${n})`);let h=new g$1.LogicMesh(f,i({insecure:true,suppressWarning:true}),j);return this.performTranscoding(o,h,p,a,n,c)}meshAgentToken;async getOrAcquireMeshAgentToken(o){if(o){let s=this.manifestCache.get(o),r=s?.manifest.serverInfo?.name?.toLowerCase()||"",l,u=s?.manifest.tokenSlug;if(u){let t=`LIOP_TOKEN_${u}`;l=process.env[t]||process.env[`LIOP_OAUTH_TOKEN_${u}`],b.info(`[LIOP-Router] Step0 tokenSlug=${u} envKey=${t} found=${!!l} peer=${o.slice(-8)}`);}else b.info(`[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${o.slice(-8)} provider=${r}`);if(!l){let t=o.slice(-8).toUpperCase();l=process.env[`LIOP_TOKEN_${t}`]||process.env[`LIOP_OAUTH_TOKEN_${t}`];}if(!l&&r){let t=r.toUpperCase().replace(/[^A-Z0-9_]/g,"_");l=process.env[`LIOP_TOKEN_${t}`]||process.env[`LIOP_OAUTH_TOKEN_${t}`];}if(l)return b.info(`[LIOP-Router] Resolved node-specific token for peer ${o.slice(-8)} (${r||"unknown"})`),l}if(this.meshAgentToken)return this.meshAgentToken;let p=process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN;if(p)return this.meshAgentToken=p,this.meshAgentToken;let n=process.env.LIOP_NEXUS_URL;if(!n)return;let a=process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID||"liop-mesh-agent",c=process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET||"dev-secret-change-me",e=process.env.LIOP_OAUTH_AUDIENCE||process.env.LIOP_AUDIENCE||"urn:liop:mesh:api";try{let r=`${n.endsWith("/oidc")?n:`${n}/oidc`}/token`;b.info(`[LIOP-Router] Proactively acquiring M2M token from Nexus: ${r}`);let l=new URLSearchParams({grant_type:"client_credentials",scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",resource:e,client_id:a,client_secret:c}),u=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!u.ok){let i=await u.text();b.warn(`[LIOP-Router] M2M Token acquisition failed: ${u.status} ${i}`);return}let t=await u.json();if(t.access_token)return this.meshAgentToken=t.access_token,b.info("[LIOP-Router] M2M Token acquired successfully for router routing."),this.meshAgentToken}catch(s){b.warn(`[LIOP-Router] Failed to acquire M2M token: ${s instanceof Error?s.message:String(s)}`);}}async performTranscoding(o,p,n,a,c,e){let s=n,r=this.meshNode?await this.meshNode.sign(Buffer.from(s)):Buffer.from([]),l=Date.now(),u$1=e;if(u$1||(u$1=await this.getOrAcquireMeshAgentToken(c)),c){let t=this.manifestCache.get(c);if(t?.manifest.authRequired&&!u$1){let i=t.manifest.serverInfo?.name?.toLowerCase()||"unknown",f=t.manifest.tokenSlug,h=c.slice(-8).toUpperCase(),m=f?`LIOP_TOKEN_${f}`:`LIOP_TOKEN_${i.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${i}) requires an access token. Please define the ${m} or LIOP_TOKEN_${h} environment variable on your agent/client host.`}],isError:true}}}}return new Promise(t=>{let i=new H.Metadata;u$1&&i.add("authorization",`Bearer ${u$1}`),p.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:s,proof_of_intent:r},i,async(f$1,h)=>{if(f$1||!h.accepted){try{g$2.inc({capability:n,error_type:"handshake_failed"});}catch{}return t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`PQC Handshake Failed: ${f$1?.message||"Rejected"}`}],isError:true}})}let m$1=performance.now(),{ciphertext:g,sharedSecret:y}=await a$3.encapsulateAsymmetric(h.kyber_public_key),v$1=performance.now()-m$1;try{u.observe({tool:n},v$1),v.inc({algorithm:"ml-kem-768",status:"success"});}catch{}let E=a?.arguments??(a?.payload!==void 0?a:{}),_=JSON.stringify(E),w$1=`return { "__liop_proxy_tool": "${n}", "__liop_proxy_args": ${_} };`,P=D.randomBytes(12),L=this.encryptWithNonce(Buffer.from(w$1),y,P),C=new H.Metadata;u$1&&C.add("authorization",`Bearer ${u$1}`);let x=p.executeLogic({session_token:h.session_token,wasm_binary:new Uint8Array(L),inputs:{},pqc_ciphertext:g,aes_nonce:P},C),k="",N=null;x.on("data",R=>{k+=R.semantic_evidence,N=R;}),x.on("end",async()=>{try{if(N)if(N.is_error)try{g$2.inc({capability:n,error_type:"remote_execution_error"});}catch{}else {let le=Buffer.from(N.cryptographic_proof).toString("hex"),U=Buffer.from(N.zk_receipt),ue=U.length>0&&U[0]===2,q=await this.verifier.verifyZkReceipt(Buffer.from(w$1),le,U,{sessionSecret:Buffer.from(y),expectedOutput:k,zkPolicy:ue?"required":"none"});try{m.inc({status:q?"valid":"invalid"});}catch{}if(!q){try{g$2.inc({capability:n,error_type:"cryptographic_audit_failed"});}catch{}return t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}})}}let R=JSON.parse(k),j=f.getInstance();j.record({type:"tool_call",method:"tools/call",toolName:n,peerId:c,estimatedInputTokens:j.countTokens(_),estimatedOutputTokens:j.countTokens(k),durationMs:Date.now()-l});try{w.inc({capability:n},Buffer.byteLength(k));}catch{}f$2.inc({capability:n,tool:n,status:R.isError?"error":"success",role:"proxy"}),t({jsonrpc:"2.0",id:o,result:R});}catch{t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:k}]}});}}),x.on("error",R=>{try{g$2.inc({capability:n,error_type:"grpc_stream_error"});}catch{}t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`LIOP gRPC Error: ${R.message}`}],isError:true}});});});})}encryptWithNonce(o,p,n){let a=D.createCipheriv("aes-256-gcm",p,n),c=Buffer.concat([a.update(o),a.final()]);return Buffer.concat([c,a.getAuthTag()])}};export{ce as a};//# sourceMappingURL=chunk-LM26HOJ6.js.map
|
|
31
|
+
//# sourceMappingURL=chunk-LM26HOJ6.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';var s={maxDecimalPlaces:4,clampNonNegative:true};function p(c,o){let a$1={...s,...o},u=new WeakSet;function r(t){if(t==null)return t;if(typeof t=="number"){if(!Number.isFinite(t))return t;let e=t;a$1.clampNonNegative&&e<0&&(e=0);let n=10**a$1.maxDecimalPlaces;return e=Math.round(e*n)/n,e}if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="object"){if(u.has(t))return t;if(u.add(t),Array.isArray(t))return t.map(n=>r(n));let e={};for(let[n,f]of Object.entries(t))e[n]=r(f);return e}return t}return a(r,"walk"),r(c)}a(p,"sanitizeOutput");export{p as a};//# sourceMappingURL=chunk-MQ5SU26J.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-MQ5SU26J.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';var c=class s{static{a(this,"TokenManager");}cachedToken=null;expiresAt=0;pendingPromise=null;tokenEndpoint;clientId;clientSecret;audience;scope;staticToken;static REFRESH_BUFFER_MS=3e4;constructor(e){this.tokenEndpoint=e.tokenEndpoint,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.audience=e.audience??"urn:liop:mesh:api",this.scope=Array.isArray(e.scopes)?e.scopes.join(" "):e.scopes??"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",this.staticToken=e.staticToken;}async getToken(){if(this.staticToken)return this.staticToken;let e=Date.now();return this.cachedToken&&e<this.expiresAt-s.REFRESH_BUFFER_MS?this.cachedToken:this.pendingPromise?this.pendingPromise:(this.pendingPromise=(async()=>{try{let t=await this.fetchNewToken();return this.cachedToken=t,t}finally{this.pendingPromise=null;}})(),this.pendingPromise)}invalidate(){this.cachedToken=null,this.expiresAt=0,this.clientId&&this.clientSecret&&(this.staticToken=void 0),b.info("[TokenManager] Cached OAuth access token invalidated.");}isExpired(){return this.staticToken?false:!this.cachedToken||Date.now()>=this.expiresAt-s.REFRESH_BUFFER_MS}getExpiresAt(){return this.expiresAt}async fetchNewToken(){b.info(`[TokenManager] Requesting M2M token from ${this.tokenEndpoint} for client '${this.clientId}'...`);let e=new URLSearchParams({grant_type:"client_credentials",client_id:this.clientId,client_secret:this.clientSecret,resource:this.audience,scope:this.scope}),t=await fetch(this.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e.toString(),signal:AbortSignal.timeout(1e4)});if(!t.ok){let a=await t.text();throw new Error(`OAuth token request failed [HTTP ${t.status}]: ${a}`)}let i=await t.json();if(!i.access_token)throw new Error("OAuth token response did not contain an 'access_token' field.");let r=typeof i.expires_in=="number"?i.expires_in:3600;return this.expiresAt=Date.now()+r*1e3,b.info(`[TokenManager] Acquired access token successfully. Expires in ${r}s.`),i.access_token}};export{c as a};//# sourceMappingURL=chunk-N35BC62H.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-N35BC62H.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {d as d$1,b as b$1,h}from'./chunk-GWVSCZUS.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var O=10,L=1800*1e3,w=60*1e3,g=class{constructor(e,t={}){this.options=t;this.app=new Hono,this.bridgeLogic=new d(e),this.activeSessions=new Map,this.maxSessionsPerIp=t.maxSessionsPerIp??O,this.sessionTimeoutMs=t.sessionTimeoutMs??L,this.setupRoutes();}options;static{a(this,"LiopStreamBridge");}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:t}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new t({sessionIdGenerator:a(()=>randomUUID(),"sessionIdGenerator"),onsessioninitialized:a(i=>{this.activeSessions.set(i,{transport:s,lastActivity:Date.now(),clientIp:e}),b.info(`[LIOP-StreamBridge] Session opened: ${i} (IP: ${e})`);},"onsessioninitialized")});return s.onmessage=async i=>{if(s.sessionId){let r=this.activeSessions.get(s.sessionId);r&&(r.lastActivity=Date.now());}try{let r=await this.bridgeLogic.handleJsonRpcRequest(i);r!==void 0&&await s.send(r);}catch(r){b.info("[LIOP-StreamBridge] JSON-RPC error:",r.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),b.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let t=0;for(let s of this.activeSessions.values())s.clientIp===e&&t++;return t}getClientIp(e){return e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||"unknown"}evictIdleSessions(){let e=Date.now();for(let[t,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(b.info(`[LIOP-StreamBridge] Evicting idle session: ${t}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(t));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),b.info("=".repeat(60)),b.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),b.info("No ZERO_TRUST_TOKEN found in environment."),b.info("A secure ephemeral token has been generated for this session:"),b.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),b.info("=".repeat(60))),this.app.use("/mcp",async(e,t)=>{let s=e.req.header("Authorization");if(!s?.startsWith("Bearer "))return e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);let i=s.slice(7),r=process.env.ZERO_TRUST_TOKEN;if(r&&i===r){await t();return}let o=this.bridgeLogic.getServer()?.jwtValidator;if(o)try{await o.validate(i),await t();return}catch(a){return b.info(`[LIOP-StreamBridge] JWT Validation failed: ${a.message}`),e.json({error:`Unauthorized: JWT Validation failed - ${a.message}`},401)}return b.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401)}),this.app.all("/mcp",async e=>{let t=e.req.header("mcp-session-id");if(t){let a=this.activeSessions.get(t);if(!a)return e.json({error:"Session not found"},404);a.lastActivity=Date.now();let c=await a.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(t),b.info(`[LIOP-StreamBridge] Session closed (DELETE): ${t}`)),c}let s=e.req.header("content-type")||"";if(e.req.method==="POST"&&s.includes("application/json"))try{let a=await e.req.json();if(a.method==="server/discover"||a.params?._meta||!!0){let c=await this.bridgeLogic.handleJsonRpcRequest(a);return c!==void 0?e.json(c):e.body(null,204)}}catch{}let i=this.getClientIp(e),r=this.countSessionsByIp(i);return r>=this.maxSessionsPerIp?(b.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${i} (${r} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(i)).handleRequest(e.req.raw)});}async start(e){let t=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),w),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:t},i=>{b.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${i.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,t]of this.activeSessions)await t.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),b.info("[LIOP-StreamBridge] HTTP ports released."));}};var d=class{constructor(e,t={}){this.options=t;e?.constructor?.name==="LiopServer"?(this.liopServer=e,b.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,b.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,b.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}options;static{a(this,"LiopMcpBridge");}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let t=e.id,s=e.method,i=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(t,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(t,s,i):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(t,s,i):this.errorResponse(t,-32601,"Bridge source not configured")}async handleLiopToMcp(e,t,s){if(!this.liopServer)return null;let i=d$1({method:t,params:s,id:e});if(t==="initialize")return this.successResponse(e,{protocolVersion:b$1,capabilities:{prompts:{listChanged:true},resources:{listChanged:true},tools:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()});if(t==="server/discover")return this.successResponse(e,{resultType:"complete",supportedVersions:[h,b$1],capabilities:{prompts:{listChanged:true},resources:{listChanged:true},tools:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()});if(t!=="notifications/initialized"){if(t==="ping")return this.successResponse(e,{});if(t==="tools/list"){let r=this.liopServer.listTools().sort((o,a)=>o.name.localeCompare(a.name));return this.successResponse(e,i?{tools:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:r})}if(t==="resources/list"){let r=this.liopServer.listResources().sort((o,a)=>o.uri.localeCompare(a.uri));return this.successResponse(e,i?{resources:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resources:r})}if(t==="prompts/list"){let r=this.liopServer.listPrompts().sort((o,a)=>o.name.localeCompare(a.name));return this.successResponse(e,i?{prompts:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",prompts:r})}if(t==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let r=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,i||typeof r!="object"||r===null?r:{resultType:"complete",...r})}catch(r){return this.errorResponse(e,-32e3,r.message)}}if(t==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let r=await this.liopServer.readResource(s.uri);return this.successResponse(e,i?r:typeof r=="object"&&r!==null?{resultType:"complete",ttlMs:6e4,cacheScope:"private",...r}:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:r})}catch(r){return this.errorResponse(e,-32e3,r.message)}}if(t==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let r={name:s.name,arguments:s.arguments||{}};try{let o=await this.liopServer.callTool(r);return (o.isError?!0:await this.verifyZkReceipt(r,o))?this.successResponse(e,i?o:{resultType:"complete",...o}):this.successResponse(e,{content:[{type:"text",text:"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload."}],isError:!0})}catch(o){return this.errorResponse(e,-32e3,o.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,t){return {jsonrpc:"2.0",id:e,result:t}}errorResponse(e,t,s){return {jsonrpc:"2.0",id:e,error:{code:t,message:s}}}async verifyZkReceipt(e,t){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,i=t.content[0]?.text;if(i&&typeof i=="string")try{let r=JSON.parse(i);if(r.image_id||r.zk_receipt){let{LiopVerifier:o}=await import('./verifier-J4NQYZX5.js'),a=new o,c=Buffer.from(r.zk_receipt||"","base64"),u=c.length>0&&c[0]===2;if(!await a.verifyZkReceipt(Buffer.from(s,"utf-8"),r.image_id||"",c,{guestImageIdHex:r.guest_image_id,circuitName:r.circuit_name,expectedOutput:r.computation_result,zkPolicy:u?"required":"none"}))return !1;r.audit_status=u?"VERIFIED: Groth16 Zero-Knowledge Proof Certified by LiopMcpBridge":"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",t.content[0].text=JSON.stringify(r);}}catch{}return !0}catch(s){return b.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:i}=await import('./server.js');if(this.liopServer=new i(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let r=this.legacyMcpServer;if(r._registeredTools)for(let[o,a]of Object.entries(r._registeredTools)){let c=a;this.liopServer.tool(o,c.description||"",c.inputSchema||{},async u=>await c.handler(u));}if(r._registeredResources)for(let[o,a]of Object.entries(r._registeredResources)){let c=a;this.liopServer.resource(c.name,o,c.metadata?.description||"",c.metadata?.mimeType||"application/octet-stream",async()=>(await c.readCallback(new URL(o))).contents[0].text);}}return}let t=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=a(async()=>{b.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);},"shutdown");t.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),t.on("line",async i=>{if(i.trim())try{let r=JSON.parse(i),o=await this.handleJsonRpcRequest(r);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
+
`);}catch(r){b.error(`[LIOP-Bridge] Error: ${r.message}`);}});}getServer(){return this.liopServer}};export{g as a,d as b};//# sourceMappingURL=chunk-P6IJ3VBD.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-P6IJ3VBD.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-AYDF3IFZ.js';import n from'crypto';var f=/^\s*@LIOP\{[^}]+\}[\r\n]+([\s\S]*?)[\r\n]+@END\s*$/;function u(t){let r=t.match(f);return r?.[1]!==void 0?r[1].trim():t.trim()}a$1(u,"normalizeLogicSource");function a(t){if(t[0]===0&&t[1]===97)return n.createHash("sha256").update(t).digest();let s=Buffer.from(t).toString("utf-8"),i=u(s);return n.createHash("sha256").update(Buffer.from(i,"utf-8")).digest()}a$1(a,"deriveLogicImageDigest");export{u as a,a as b};//# sourceMappingURL=chunk-TKLRW52V.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-TKLRW52V.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as S from'fs/promises';import*as I from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {autoNAT}from'@libp2p/autonat';import {bootstrap}from'@libp2p/bootstrap';import {circuitRelayTransport,circuitRelayServer}from'@libp2p/circuit-relay-v2';import {dcutr}from'@libp2p/dcutr';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {mdns}from'@libp2p/mdns';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var Y=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],E="/liop/manifest/1.0.0",N="liop:manifest",k=class T{static{a(this,"MeshNode");}node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(e={}){this.config={listenAddresses:e.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:e.bootstrapNodes||[],identityPath:e.identityPath,enableWAN:e.enableWAN??false,dhtStoragePath:e.dhtStoragePath,addressMapper:e.addressMapper,swarmKey:e.swarmKey};}shouldSkipManifestDial(e){let t=this.manifestDialFailureState.get(e);if(!t)return false;let n=Date.now();return n>=t.cooldownUntil?false:(n-t.lastSkipLogAt>T.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(b.info(`[LIOP-Mesh] Skipping manifest dial for ${e} during cooldown (${Math.ceil((t.cooldownUntil-n)/1e3)}s remaining)`),t.lastSkipLogAt=n),true)}recordManifestDialFailure(e){let t=Date.now(),r=(this.manifestDialFailureState.get(e)?.failures||0)+1,o=Math.min(T.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),T.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(e,{failures:r,cooldownUntil:t+o,lastSkipLogAt:0});}clearManifestDialFailure(e){this.manifestDialFailureState.delete(e);}async loadOrCreateIdentity(){try{let{generateKeyPair:e,privateKeyFromProtobuf:t}=await import('@libp2p/crypto/keys'),{fromString:n}=await import('uint8arrays/from-string');if(this.config.identityPath){let o=I.resolve(this.config.identityPath);try{let s=await S.readFile(o,"utf-8"),f=JSON.parse(s),h=n(f.privKey,"base64");try{let a=t(h);return b.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a,isNew:!1}}catch(a){b.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a instanceof Error?a.message:String(a)}`);}}catch(s){let f=s;f.code!=="ENOENT"&&b.error(`[LIOP-Mesh] Error loading identity: ${f.message}`);}}return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){b.error(`[LIOP-Mesh] Critical error in identity management: ${e}. Falling back to ephemeral identity.`);try{let{generateKeyPair:t}=await import('@libp2p/crypto/keys');return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){throw new Error(`Identity system failure: ${t}`)}}}async saveIdentity(e){if(!(!this.config.identityPath||!this.node))try{let t=I.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),{toString:r}=await import('uint8arrays/to-string'),o=n(e),s=r(o,"base64"),f={id:this.node.peerId.toString(),privKey:s};await S.mkdir(I.dirname(t),{recursive:!0}),await S.writeFile(t,JSON.stringify(f,null,2)),b.info(`[LIOP-Mesh] Identity persisted to ${t}`);}catch(t){b.error(`[LIOP-Mesh] FAILED to persist identity: ${t}`);}}async capabilityToCID(e){let t=await sha256.digest(new TextEncoder().encode(e));return CID.create(1,85,t)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(e=>setTimeout(e,500)),!this.node)return;b.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let e of this.announcedCapabilities)try{let t=await this.capabilityToCID(e);await this.node.contentRouting.provide(t),b.info(`[LIOP-Mesh] Re-announced: ${e}`);}catch(t){b.info(`[LIOP-Mesh] Re-announce failed for ${e}: ${t}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let e=await this.loadOrCreateIdentity();if(!e)throw new Error("Could not initialize P2P Identity");let{privateKey:t,isNew:n}=e;this.localPrivateKey=t;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=Y);let o=this.config.enableAutoNAT??true,s=this.config.enableRelay??true,f=this.config.enableDcutr??true,h=this.config.enableMdns??!this.config.enableWAN,a$1=[];r.length>0&&a$1.push(bootstrap({list:r})),h&&a$1.push(mdns());let g=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0",c=[tcp(),webSockets()];s&&c.push(circuitRelayTransport());let p={identify:identify(),ping:ping(),dht:kadDHT({protocol:g,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:a(l=>l,"peerInfoMapper")})};o&&(p.autoNAT=autoNAT()),s&&(p.relay=circuitRelayServer()),f&&(p.dcutr=dcutr());let M;if(this.config.swarmKey){let{preSharedKey:l}=await import('@libp2p/pnet');M=l({psk:this.config.swarmKey}),b.info("[LIOP-Mesh] \u{1F512} Private Network (pnet) enabled \u2014 transport-layer PSK isolation active");}if(this.node=await createLibp2p({privateKey:t,addresses:{listen:this.config.listenAddresses},transports:c,connectionEncrypters:[noise()],streamMuxers:[yamux()],...M?{connectionProtector:M}:{},services:p,peerDiscovery:a$1.length>0?a$1:void 0}),this.node.addEventListener("peer:discovery",l=>{let P=l.detail.id;if(b.info(`[LIOP-Mesh] Discovered peer: ${P.toString()}`),this.node){let y=P;if(this.config.addressMapper&&l.detail.multiaddrs.length>0){let L=l.detail.multiaddrs.map(b=>{let d=this.config.addressMapper(b.toString());return d?multiaddr(d):null}).filter(b=>b!==null).find(b=>b.toString().includes("/tcp/")&&!b.toString().includes("/ws"));L&&(y=L);}this.node.dial(y).catch(()=>{});}}),this.node.addEventListener("peer:connect",l=>{let P=l.detail;if(b.info(`[LIOP-Mesh] Connected to peer: ${P.toString()}`),!this.node)return;let y=this.node.services.dht;y?.routingTable&&(b.info(`[LIOP-Mesh] Adding ${P.toString()} to DHT Routing Table`),y.routingTable.add(P).catch(m=>{b.info(`[LIOP-Mesh] Failed to add peer to routing table: ${m instanceof Error?m.message:String(m)}`);})),this.reannounceAll().catch(m=>{b.info(`[LIOP-Mesh] Re-announce error: ${m instanceof Error?m.message:String(m)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(t),b.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(l=>{b.info(`[LIOP-Mesh] Listening on: ${l.toString()}`);}),r.length>0){b.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let l=this.node;if(!l)return;let P=2;await Promise.allSettled(r.map(async y=>{for(let m=1;m<=P;m++)try{await l.dial(multiaddr(y),{signal:AbortSignal.timeout(2500)}),b.info(`[LIOP-Mesh] \u2705 Successfully dialed ${y}`);return}catch{m===P?b.warn(`[LIOP-Mesh] \u26A0\uFE0F Could not connect to bootstrap ${y} after ${P} attempts. Continuing...`):await new Promise(b=>setTimeout(b,500));}}));}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),b.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let e=I.resolve(this.config.dhtStoragePath),t=await S.readFile(e,"utf-8"),n=JSON.parse(t),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let s of n)if(!(!s.id||!s.addresses))try{let f=r(s.id),h=s.addresses.map(g=>multiaddr(g));await this.node.peerStore.save(f,{multiaddrs:h});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(f).catch(()=>{}),o++;}catch{}b.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(e){let t=e;t.code!=="ENOENT"&&b.error(`[LIOP-Mesh] Failed to load DHT table: ${t.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let e=I.resolve(this.config.dhtStoragePath),t=await this.node.peerStore.all(),n=[];for(let r of t)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await S.mkdir(I.dirname(e),{recursive:!0}),await S.writeFile(e,JSON.stringify(n,null,2)),b.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(e){b.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${e}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(N).catch(e=>{b.info(`[LIOP-Mesh] Initial manifest announcement failed: ${e}`);}),this.node.handle(E,async(e,t)=>{let n=e?.stream??e,o=(e?.connection??t)?.remotePeer?.toString()||"unknown";b.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let s=this.manifestProvider?.();if(!s||!n){b.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let f=JSON.stringify(s),h=new TextEncoder().encode(f),a=Buffer.alloc(4);a.writeUInt32BE(h.length,0);let g=Buffer.concat([a,Buffer.from(h)]);b.info(`[LIOP-Mesh] Serving manifest (${g.length} bytes) to ${o} [Tools: ${s.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(g)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(p){b.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${p instanceof Error?p.message:String(p)}`);}}else await pipe([g],n);b.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){b.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(s){b.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${s instanceof Error?s.message:String(s)}`);}}),b.info(`[LIOP-Mesh] Manifest Protocol registered: ${E}`));}registerManifestHandler(e){this.manifestProvider=e,this.node&&this.applyHandlers();}async queryManifest(e){if(!this.node)throw new Error("Mesh Node is not running");if(e===this.node.peerId.toString())return b.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${e}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(e))return null;let t=3;for(let n=1;n<=t;n++)try{let r=null,s=this.node.getConnections().find(d=>d.remotePeer.toString()===e);if(s)r=s.remotePeer;else {let u=(await this.node.peerStore.all()).find(w=>w.id.toString()===e);if(u)r=u.id;else {let{peerIdFromString:w}=await import('@libp2p/peer-id');r=w(e);}}let h=r;if(this.config.addressMapper&&this.node){let d=this.config.addressMapper,u=await this.node.peerStore.get(r);if(u&&u.addresses.length>0){let w=u.addresses.map(v=>{let C=v.multiaddr.toString(),D=d(C);return D?{isCertified:v.isCertified,multiaddr:multiaddr(D)}:null}).filter(v=>v!==null),$=w.find(v=>v.multiaddr.toString().includes("/tcp/")&&!v.multiaddr.toString().includes("/ws"));$&&(h=$.multiaddr,b.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${h.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:w.map(v=>v.multiaddr)});}}let a;try{let d=await this.node.dialProtocol(h,E).catch(u=>{throw String(u).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):u});a=d.stream||d;}catch(d){if(n===t)return b.info(`[LIOP-Mesh] Dial error for ${e} after ${t} attempts: ${d}`),null;let u=500*2**n;b.info(`[LIOP-Mesh] Dial error for ${e} (Attempt ${n}). Retrying in ${u}ms...`),await new Promise(w=>setTimeout(w,u));continue}let g=a.source??(typeof a[Symbol.asyncIterator]=="function"?a:null);if(!g)throw new Error("Target stream has no AsyncIterable source");let c=[],p=0,M=-1,l,P=new Promise((d,u)=>{l=setTimeout(()=>u(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let d of g){if(!d)continue;let u=typeof d.subarray=="function"?d.subarray():d instanceof Uint8Array?d:new Uint8Array(0),w=Buffer.from(u.buffer,u.byteOffset,u.byteLength);if(w.length>0&&(c.push(w),p+=w.length,M<0&&p>=4&&(M=Buffer.concat(c).readUInt32BE(0)),M>=0&&p>=4+M))break}})(),P]);}catch(d){if(c.length===0)throw d;b.info(`[LIOP-Mesh] Partial manifest read from ${e}: ${d instanceof Error?d.message:String(d)}`);}finally{l&&clearTimeout(l);}let y=Buffer.concat(c);if(y.length<4)throw new Error("Received empty/invalid manifest (too short)");let m=y.readUInt32BE(0),L=y.subarray(4,4+m).toString("utf-8"),b$1=JSON.parse(L);return b.info(`[LIOP-Mesh] Received manifest from ${e}: ${b$1.tools.length} tools`),this.clearManifestDialFailure(e),b$1}catch(r){if(n===t)return this.recordManifestDialFailure(e),b.info(`[LIOP-Mesh] Failed to query manifest from ${e} after ${t} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;b.info(`[LIOP-Mesh] Query error for ${e} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o));}return null}async discoverManifestProviders(){return this.findProviders(N)}async announceManifest(){await this.announceCapability(N);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(e){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(e))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(e=>e.toString())}async announceCapability(e){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(e);try{let t=await this.capabilityToCID(e);b.info(`[LIOP-Mesh] Announcing capability: ${e} (CID: ${t.toString()})`),await this.node.contentRouting.provide(t),b.info(`[LIOP-Mesh] Successfully announced capability: ${e}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(t))if(r.id.toString()===n){b.info(`[LIOP-Mesh] Self-verification success: Node is providing ${e}`);break}}catch(t){b.error(`[LIOP-Mesh] Failed to announce capability: ${t}`);}}async findProviders(e){if(!this.node)throw new Error("Mesh Node is not running");let t=[];try{let n=await this.capabilityToCID(e);b.info(`[LIOP-Mesh] Querying DHT for ${e} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,s=o>1?1500:3e3;b.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${s}ms (Active connections: ${o})`);let f=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),h=!1;for(;!h;){let a=f.next(),g=new Promise(c=>setTimeout(()=>c({timeout:!0}),s));try{let c=await Promise.race([a,g]);if(c&&typeof c=="object"&&"timeout"in c){b.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof f.return=="function"&&f.return().catch(()=>{}),h=!0;break}let p=c;if(p.done){h=!0;break}r=!0;let l=p.value.id.toString();b.info(`[LIOP-Mesh] Found provider: ${l}`),t.includes(l)||t.push(l);}catch(c){b.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),h=!0;break}}if(!r){let g=this.node.services.dht?.routingTable?.size||0;b.info(`[LIOP-Mesh] DHT search for ${e} returned zero results (routing table size: ${g})`);}if(this.announcedCapabilities.has(e)){let a=this.node.peerId.toString();t.includes(a)||(b.info(`[LIOP-Mesh] Including local node (${a}) in results for ${e}`),t.push(a));}}catch(n){b.info(`[LIOP-Mesh] Error finding providers for ${e}: ${n instanceof Error?n.message:String(n)}`);}return b.info(`[LIOP-Mesh] DHT search for ${e} finished. Found ${t.length} providers.`),t}async resolvePeer(e){if(!this.node)throw new Error("Mesh Node is not running");try{let t=this.node.getConnections();for(let r of t)if(r.remotePeer.toString()===e){let o=r.remoteAddr.toString();return b.info(`[LIOP-Mesh] Resolved peer ${e} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===e&&r.addresses.length>0){let o=r.addresses.map(s=>s.multiaddr.toString());return b.info(`[LIOP-Mesh] Resolved peer ${e} via peerStore: ${o[0]}`),o}b.info(`[LIOP-Mesh] Peer ${e} not found in connections or peerStore`);}catch(t){b.info(`[LIOP-Mesh] Failed to resolve peer ${e}: ${t}`);}return []}isStarted(){return !!this.node&&this.node.status==="started"}getPeers(){return this.node?this.node.getConnections().map(e=>e.remotePeer.toString()):[]}isPrivateNetwork(){return !!this.config.swarmKey}getSwarmKey(){return this.config.swarmKey}};export{k as a};//# sourceMappingURL=chunk-V35CXJQN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-V35CXJQN.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-N35BC62H.js';import {a as a$1}from'./chunk-6KFKO6ZX.js';import {a as a$4}from'./chunk-Y675R34Z.js';import {i,g,j,f}from'./chunk-ECRS6N33.js';import {v,u,g as g$1,m,w as w$1}from'./chunk-ZZMSFCJP.js';import {h,b as b$1}from'./chunk-GWVSCZUS.js';import {a as a$3}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as M from'@grpc/grpc-js';import {createDecipheriv,randomBytes,createCipheriv}from'crypto';var w=class{static{a(this,"LiopRpcClient");}client;token;lastResolvedToken;address;constructor(t,r,i$1){let o=i(r);this.client=new g.LogicMesh(t,o,j),this.token=i$1,typeof i$1=="string"&&(this.lastResolvedToken=i$1),this.address=t;}setToken(t){this.token=t,typeof t=="string"&&(this.lastResolvedToken=t);}async resolveToken(){return typeof this.token=="function"?(this.lastResolvedToken=await this.token(),this.lastResolvedToken):(this.lastResolvedToken=this.token,this.token)}async negotiateIntent(t){let r=await this.resolveToken();return new Promise((i,o)=>{let e=new M.Metadata;r&&e.add("authorization",`Bearer ${r}`),this.client.NegotiateIntent(t,e,(s,n)=>{s?o(s):i(n);});})}executeLogic(t){let r=new M.Metadata,i=this.lastResolvedToken||(typeof this.token=="string"?this.token:void 0);return i&&r.add("authorization",`Bearer ${i}`),this.client.ExecuteLogic(t,r)}close(){this.client.close();}};var F={encryptPayload(y,t){if(t.length!==32)throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");let r=randomBytes(12),i=createCipheriv("aes-256-gcm",t,r),o=Buffer.concat([i.update(y),i.final()]),e=i.getAuthTag();return {ciphertext:Buffer.concat([o,e]),nonce:r}},decryptPayload(y,t,r){if(y.length<16)throw new Error("Invalid GCM Ciphertext; missing authentication tag length");let i=y.subarray(0,-16),o=y.subarray(-16),e=createDecipheriv("aes-256-gcm",r,t);return e.setAuthTag(o),Buffer.concat([e.update(i),e.final()])}};var Q=class{static{a(this,"LiopClient");}meshNode=null;rpcClients=new Map;manifests=new Map;tlsOptions;serverInfo;verifier=new a$1;oauthToken;tokenManager;era="modern";protocolVersion=h;constructor(t){this.tlsOptions=t;}async connect(t,r){let i=r?.auth?.clientId||process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID,o=r?.auth?.clientSecret||process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET,e=r?.auth?.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",s=r?.auth?.audience||process.env.LIOP_OAUTH_AUDIENCE||"urn:liop:mesh:api",n=r?.auth?.scope||process.env.LIOP_OAUTH_SCOPE||"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query";if(this.oauthToken=r?.auth?.token||process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN,i&&o){let v=`${(e).endsWith("/oidc")?e:`${e}/oidc`}/token`;this.tokenManager=new a$2({tokenEndpoint:v,clientId:i,clientSecret:o,audience:s,scopes:n});try{this.oauthToken=await this.tokenManager.getToken(),b.info("[LiopClient] Dynamic TokenManager configured and initial token acquired.");}catch(d){b.error(`[LiopClient] Failed to acquire OAuth M2M Token: ${d instanceof Error?d.message:String(d)}`);}}if(this.meshNode=new a$3(r?.meshConfig),await this.meshNode.start(),b.info(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`),t){let c=a(async()=>this.tokenManager?await this.tokenManager.getToken():this.oauthToken,"tokenResolver");this.rpcClients.set("static",new w(t,this.tlsOptions,c)),this.serverInfo={name:`LiopServer (${t})`,version:"1.0.0"},b.info(`[LiopClient] Static gRPC configured for: ${t}`);}else this.serverInfo={name:"LiopServer (Mesh Alpha)",version:"1.0.0"};}selectOptimalIp(t){for(let r of t){let i=r.split("/"),o=i.indexOf("ip4");if(o!==-1&&o+1<i.length){let e=i[o+1];if(e!=="127.0.0.1"&&!e.startsWith("127.")&&e!=="0.0.0.0"&&e!=="localhost")return e}}for(let r of t){let i=r.split("/"),o=i.indexOf("ip4");if(o!==-1&&o+1<i.length)return i[o+1]}return null}async resolveCapability(t){if(!this.meshNode)throw new Error("Client must be connected to Mesh to resolve capabilities.");b.info(`[LiopClient] Querying Mesh DHT for Provider: ${t}...`);let r=await this.meshNode.findProviders(t);if(r.length===0)throw new Error(`Kademlia DHT found zero providers for capability: ${t}`);let i=r[0];b.info(`[LiopClient] Identified Alpha Provider PeerID: ${i}`);let o=50051,e=await this.meshNode.queryManifest(i);e&&(o=e.grpcPort,this.manifests.set(i,e),b.info(`[LiopClient] Manifest resolved: gRPC port ${o}. Cached manifest for PeerID ${i}`));let s=await this.meshNode.resolvePeer(i),n=this.selectOptimalIp(s);if(n){let c=`${n}:${o}`;return b.info(`[LiopClient] Translated Multiaddr to optimal gRPC Target: ${c}`),c}return `127.0.0.1:${o}`}async probeServerDiscover(t){try{let r={"Content-Type":"application/json","Mcp-Method":"server/discover"};this.oauthToken&&(r.Authorization=`Bearer ${this.oauthToken}`);let i=await fetch(t,{method:"POST",headers:r,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"server/discover",params:{}})});if(i.ok){let e=(await i.json()).result?.supportedVersions||[];if(e.includes(h))return this.era="modern",this.protocolVersion=h,{era:"modern",protocolVersion:h,supportedVersions:e}}}catch{}return this.era="legacy",this.protocolVersion=b$1,{era:"legacy",protocolVersion:b$1,supportedVersions:[b$1]};}async discoverTools(t=false){if(!this.meshNode)throw new Error("Client must be connected before discovering tools.");let r=Date.now();b.info(`[LiopClient] Discovery started (forceRefresh: ${t})...`);let i=await this.meshNode.discoverManifestProviders(),o=[],e=new Set;for(let s of i)try{let n=t?void 0:this.manifests.get(s);if(n?b.info(`[LiopClient] Using cached manifest for: ${s}`):(b.info(`[LiopClient] Querying manifest from: ${s}`),n=await this.meshNode.queryManifest(s),n&&this.manifests.set(s,n)),n)for(let c of n.tools)e.has(c.name)||(o.push({name:c.name,description:c.description}),e.add(c.name));}catch(n){b.info(`[LiopClient] Error querying manifest from ${s}:`,n instanceof Error?n.message:String(n));}b.info(`[LiopClient] Discovery finished. Found ${o.length} unique tools.`);try{let s=f.getInstance(),n=JSON.stringify(o),c=JSON.stringify({tools:o});s.record({type:"tools_list",method:"discoverTools",estimatedInputTokens:s.countTokens(n),estimatedOutputTokens:s.countTokens(c),durationMs:Date.now()-r});}catch{}return o}async callTool(t,r,i){if(!this.meshNode)throw new Error("Client must be connected before calling tools.");let o=Date.now(),e=t.name;b.info(`[LiopClient] Resolving Tool: ${e}`);let s=this.rpcClients.get("static"),n=e;if(s||this.rpcClients.has(e)&&(s=this.rpcClients.get(e),n=e),s)n="static",b.info(`[LiopClient] Using existing static gRPC connection for ${e}.`);else {let p=null;for(let[l,u]of this.manifests.entries())if(u.tools.some(m=>m.name===e)){if(this.rpcClients.has(l)){s=this.rpcClients.get(l),n=l;break}let m=await this.meshNode.resolvePeer(l),T=this.selectOptimalIp(m);if(T){p=`${T}:${u.grpcPort}`,b.info(`[LiopClient] Fast-path: Resolved ${e} from manifest cache to optimal target ${p}`),n=l,s=this.getOrCreateRpcClient(l,p);break}}if(!s){let l=await this.resolveCapability(e);n=e,s=this.getOrCreateRpcClient(e,l);}}b.info(`[LiopClient] Negotiating intent for ${e}...`);let c=this.meshNode?`did:liop:${this.meshNode.getPeerId()}`:"did:liop:ephemeral",v$1=Buffer.from(`${e}:${Date.now()}`),d=this.meshNode?await this.meshNode.sign(v$1):v$1,f$1;try{f$1=await s.negotiateIntent({agent_did:c,capability_hash:e,proof_of_intent:d});}catch(p){let l=p instanceof Error?p.message:String(p);if(this.tokenManager&&(l.includes("UNAUTHENTICATED")||l.includes("Invalid JWT")||l.includes("timestamp check failed")||l.includes("expired"))){b.warn(`[LiopClient] Token expired/unauthenticated for ${e}. Preemptively refreshing OAuth token and retrying negotiateIntent...`),this.tokenManager.invalidate();let u=await this.tokenManager.getToken();this.oauthToken=u,s.setToken(u),f$1=await s.negotiateIntent({agent_did:c,capability_hash:e,proof_of_intent:d});}else throw p}if(!f$1.accepted){if(this.tokenManager&&(f$1.error_message?.includes("token")||f$1.error_message?.includes("UNAUTHENTICATED")||f$1.error_message?.includes("expired")||f$1.error_message?.includes("timestamp check failed"))){b.warn(`[LiopClient] Intent rejected with auth error: "${f$1.error_message}". Refreshing token and retrying...`),this.tokenManager.invalidate();let p=await this.tokenManager.getToken();this.oauthToken=p,s.setToken(p),f$1=await s.negotiateIntent({agent_did:c,capability_hash:e,proof_of_intent:d});}if(!f$1.accepted)throw new Error(`Intent denied by host: ${f$1.error_message}`)}let L=f$1.kyber_public_key||f$1.kyberPublicKey,X=f$1.session_token||f$1.sessionToken;if(!L){b.info("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",f$1);try{v.inc({algorithm:"ml-kem-768",status:"failure"});}catch{}throw new Error("Handshake failed: Remote host did not provide a valid Kyber Public Key.")}b.info(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${t.name}...`);let ee=performance.now(),$,I;try{let p=await a$4.encapsulateAsymmetric(L);$=p.ciphertext,I=p.sharedSecret;let l=performance.now()-ee;u.observe({tool:t.name},l),v.inc({algorithm:"ml-kem-768",status:"success"});}catch(p){try{v.inc({algorithm:"ml-kem-768",status:"failure"});}catch{}throw p}b.info("[LiopClient] Sealing WASM Payload and Inputs...");let S=r||Buffer.from(""),{ciphertext:te,nonce:ie}=F.encryptPayload(S,I),A={},x=await import('crypto');for(let[p,l]of Object.entries(t.arguments||{})){let u=x.randomBytes(12),m=x.createCipheriv("aes-256-gcm",I,u),T=Buffer.concat([m.update(JSON.stringify(l)),m.final()]),h=m.getAuthTag();A[p]=Buffer.concat([u,T,h]);}let ne={session_token:X,wasm_binary:te,inputs:A,pqc_ciphertext:$,aes_nonce:ie};return new Promise((p,l)=>{let u=s.executeLogic(ne);if(!u){l(new Error("RPC Client unavailable or failed to create stream."));return}let m$1=false,T=false;u.on("data",async h=>{if(!m$1){T=true,b.info("[LiopClient] Logic Executed. Verification in progress...");try{let k=!1,U=0;if(h.is_error)try{g$1.inc({capability:e,error_type:"remote_execution_error"});}catch{}else {let g=Buffer.from(h.zk_receipt);k=g.length>0&&g[0]===2,k&&g.length>1&&(U=g[1]);let E=i?.zkPolicy??(k?"required":"none"),O=await this.verifier.verifyZkReceipt(S,Buffer.from(h.cryptographic_proof).toString("hex"),g,{sessionSecret:Buffer.from(I),expectedOutput:h.semantic_evidence,circuitName:i?.circuitName,zkPolicy:E});try{m.inc({status:O?"valid":"invalid"});}catch{}if(!O){try{g$1.inc({capability:e,error_type:"zk_verification_failed"});}catch{}l(new Error("PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."));return}}m$1=!0;try{let g=f.getInstance(),E=JSON.stringify(t.arguments??{});g.record({type:"tool_call",method:"callTool",toolName:e,peerId:n!==e?n:void 0,estimatedInputTokens:g.countTokens(E),estimatedOutputTokens:g.countTokens(h.semantic_evidence),durationMs:Date.now()-o});let O=Buffer.byteLength(h.semantic_evidence||"")+(h.cryptographic_proof?h.cryptographic_proof.length:0)+(h.zk_receipt?h.zk_receipt.length:0);w$1.inc({capability:e},O);}catch{}p({content:[{type:"text",text:h.semantic_evidence}],isError:h.is_error,zkVerified:!h.is_error,zkProofType:k?U:0});}catch(k){try{g$1.inc({capability:e,error_type:"verification_exception"});}catch{}l(k);}}}),u.on("error",h=>{this.rpcClients.delete(n),this.rpcClients.delete(e);try{g$1.inc({capability:e,error_type:"stream_error"});}catch{}m$1||(b.error("[LiopClient] Stream Error:",h),l(h));}),u.on("end",()=>{!T&&!m$1&&l(new Error("Logic-on-Origin stream closed without results."));});})}getOrCreateRpcClient(t,r){let i=this.rpcClients.get(t);if(!i){let o=this.manifests.get(t),e=t;if(!o){b.info(`[LiopClient] PeerID "${t}" not found in manifest cache as PeerID. Searching tools in cached manifests...`);for(let[d,f]of this.manifests.entries())if(f.tools.some(L=>L.name===t)){o=f,e=d,b.info(`[LiopClient] Resolved tool "${t}" to provider PeerID "${d.slice(-8)}" from manifest cache.`);break}}let s=o?.serverInfo?.name?.toLowerCase()||"",n,c=o?.tokenSlug;if(c?(n=process.env[`LIOP_TOKEN_${c}`]||process.env[`LIOP_OAUTH_TOKEN_${c}`],b.info(`[LiopClient] Resolved via tokenSlug "${c}" (LIOP_TOKEN_${c}) -> found: ${!!n}`)):b.info(`[LiopClient] No tokenSlug available for peer ${e.slice(-8)}. Available cache keys: ${Array.from(this.manifests.keys()).map(d=>d.slice(-8)).join(", ")}`),!n&&e){let d=e.slice(-8).toUpperCase();n=process.env[`LIOP_TOKEN_${d}`]||process.env[`LIOP_OAUTH_TOKEN_${d}`];}if(!n&&s){let d=s.toUpperCase().replace(/[^A-Z0-9_]/g,"_");n=process.env[`LIOP_TOKEN_${d}`]||process.env[`LIOP_OAUTH_TOKEN_${d}`];}n&&b.info(`[LiopClient] Resolved node-specific token for peer ${e.slice(-8)} (${s||"unknown"})`);let v=a(async()=>n||(this.tokenManager?await this.tokenManager.getToken():this.oauthToken),"tokenResolver");i=new w(r,this.tlsOptions,v),this.rpcClients.set(t,i);}return i}async readResource(t){if(!this.meshNode)throw new Error("Client must be connected before reading resources.");let r=Date.now();b.info(`[LiopClient] Querying Mesh for Resource: ${t}...`);let i=await this.meshNode.findProviders(t);if(i.length===0)throw new Error(`No mesh providers found for resource: ${t}`);let o=await this.meshNode.queryManifest(i[0]);if(!o)throw new Error("Target peer did not return a valid LIOP Manifest.");let e=o.resources?.find(n=>n.uri===t);if(!e)throw new Error(`Resource ${t} not listed in remote manifest.`);let s={contents:[{uri:t,mimeType:e.mimeType||"application/json",text:JSON.stringify(e,null,2)}]};try{let n=f.getInstance(),c=JSON.stringify(s);n.record({type:"resource_read",method:"readResource",toolName:t,peerId:i[0],estimatedInputTokens:n.countTokens(t),estimatedOutputTokens:n.countTokens(c),durationMs:Date.now()-r});}catch{}return s}get peerId(){return this.meshNode?.getPeerId()??null}get isMeshActive(){return this.meshNode?.isStarted()??false}get connectionCount(){return this.meshNode?.getPeers().length??0}getServerInfo(){return this.serverInfo}async close(){this.meshNode&&await this.meshNode.stop();}};
|
|
2
|
+
export{w as a,F as b,Q as c};//# sourceMappingURL=chunk-WP5ER7RH.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-WP5ER7RH.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';var c={initialize:[],"notifications/initialized":[],"notifications/cancelled":[],ping:[],"server/discover":[],"subscriptions/listen":[],"tools/list":["liop:tools:list"],"tools/call":["liop:tools:call"],"resources/list":["liop:resources:read"],"resources/read":["liop:resources:read"],"resources/templates/list":["liop:resources:read"],"prompts/list":["liop:schema:read"],"prompts/get":["liop:schema:read"]};function u(e,s,l){let o=c[e];if(o!==void 0&&o.length===0)return {allowed:true};if(!s)return {allowed:false,reason:`Authentication required for method: ${e}`};let t=[...o??[],...l??[]];if(t.length===0)return {allowed:false,reason:`Unknown method: ${e}. Access denied (fail-closed).`};let n=new Set(s.scopes),i=t.filter(a=>!n.has(a));return i.length>0?{allowed:false,reason:`Insufficient scopes for ${e}. Missing: ${i.join(", ")}`}:{allowed:true}}a(u,"authorizeRequest");var f=["liop:tools:list","liop:tools:call","liop:resources:read","liop:schema:read","liop:mesh:query"];export{u as a,f as b};//# sourceMappingURL=chunk-XLVEDKM6.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XLVEDKM6.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-AYDF3IFZ.js';import {createMlKem768}from'mlkem';var a=null;async function n(){return a||(a=await createMlKem768()),a}a$1(n,"getKemInstance");var l={importPublicKey(e){if(e.length!==1184)throw new Error(`Kyber768 Public Key must be exactly 1184 bytes (Received: ${e.length})`);return e},async encapsulateAsymmetric(e){try{if(e.length!==1184)throw new Error("Kyber768 Public Key must be exactly 1184 bytes.");let r=await n(),[t,i]=r.encap(e);return {ciphertext:t,sharedSecret:i}}catch(r){throw new Error(`Failed to perform PQC encapsulation: ${r.message}`)}},async generateKeyPair(){let e=await n(),[r,t]=e.generateKeyPair();return {publicKey:r,secretKey:t}},async decapsulateSymmetric(e,r){return (await n()).decap(e,r)}};export{l as a};//# sourceMappingURL=chunk-Y675R34Z.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-Y675R34Z.js.map
|