@nekzus/liop 2.4.0-alpha.26 → 2.4.0-alpha.28

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/dist/bin/agent.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {b as b$2,a as a$3}from'../chunk-2XHSALII.js';import {a as a$4}from'../chunk-N35BC62H.js';import {m}from'../chunk-YD2AF2M6.js';import'../chunk-MQ5SU26J.js';import {a as a$2}from'../chunk-LM26HOJ6.js';import'../chunk-6KFKO6ZX.js';import'../chunk-TKLRW52V.js';import'../chunk-Y675R34Z.js';import'../chunk-XLVEDKM6.js';import'../chunk-2ZYX736J.js';import'../chunk-ECRS6N33.js';import'../chunk-ZZMSFCJP.js';import {g,f,d}from'../chunk-GWVSCZUS.js';import'../chunk-6VK2XALI.js';import'../chunk-FTF6AMF6.js';import'../chunk-YLCNV764.js';import {a as a$1}from'../chunk-V35CXJQN.js';import {b as b$1}from'../chunk-3WRKTVOF.js';import {a}from'../chunk-AYDF3IFZ.js';import*as L from'fs';import*as G from'os';import*as R from'path';import*as N from'readline';import {multiaddr}from'@multiformats/multiaddr';var b={name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}};async function F(e){try{let s=e.endsWith("/health")?e:`${e}/health`,a=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!a.ok)return null;let n=await a.json();if(!n.mesh?.multiaddrs?.length||!n.mesh?.peerId)return null;let c=n.mesh.multiaddrs.find(t=>t.includes("/tcp/")&&!t.includes("/ws")&&!t.includes("/ip4/127.0.0.1/"));if(!c)return null;let i=C()?k(c):c;if(!i||i===c){let t=new URL(e).hostname;i=c.replace(/\/ip4\/[^/]+/,`/ip4/${t}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${n.mesh.peerId}`,i):null}catch{return null}}a(F,"resolveBootstrapFromUrl");function V(e){let s=e.trim(),a=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,n=/\/ip4\/127\.0\.0\.1/,c=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(a.test(s)||n.test(s)||c.test(s)){let i="127.0.0.1",t=s.replace(a,`/ip4/${i}`).replace(n,`/ip4/${i}`).replace(c,`/ip4/${i}`);return t!==s&&b$1.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${t}`),t}return s}a(V,"normalizeBootstrap");function k(e){return e.includes("/ip4/172.23.0.10")?e.replace(/\/ip4\/172\.23\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15001"):e.includes("/ip4/172.23.0.20")?e.replace(/\/ip4\/172\.23\.0\.20\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15011"):e.includes("/ip4/172.21.0.13")?e.replace(/\/ip4\/172\.21\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15031"):e.includes("/ip4/172.21.0.14")?e.replace(/\/ip4\/172\.21\.0\.14\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15041"):e.includes("/ip4/172.20.0.10")?e.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):e.includes("/ip4/172.20.0.11")?e.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):e.includes("/ip4/172.20.0.12")?e.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):e.includes("/ip4/172.20.0.13")?e.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):e.includes("/ip4/127.0.0.1/tcp/4000")||e.includes("/ip4/127.0.0.1/tcp/3000")?null:e}a(k,"industrialAddressMapper");function q(e){try{let s=new URL(e);return (s.hostname==="127.0.0.1"||s.hostname==="localhost")&&(s.port==="13000"||s.port==="13001"||s.port==="15000"||s.port==="15018")}catch{return false}}a(q,"isDockerDemoHost");function C(){return process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||!!process.env.LIOP_NEXUS_URL&&q(process.env.LIOP_NEXUS_URL)}a(C,"shouldEnableDockerMap");async function X(e){let s=[],a=process.argv.slice(2);if(a.length>0&&(s=a.filter(n=>n.startsWith("/"))),process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL){let n=process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL;if(n){let c=await F(n);if(c){let i=V(c);s.includes(i)||(s.push(i),b$1.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${i}`));}}}if(s.length===0){let n=[process.cwd(),R.join(process.cwd(),"tests/infra/nexus-data"),e,R.join(R.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data")];for(let c of n)try{if(L.existsSync(c)){let t=L.readdirSync(c).filter(l=>l.endsWith(".multiaddr"));for(let l of t){let d=R.join(c,l),r=L.readFileSync(d,"utf8").trim();if(r){let m=V(r);s.includes(m)||(s.push(m),b$1.info(`[LIOP-Agent] \u2705 Loaded beacon: ${l} from ${c}`));}}if(s.length>0)break}}catch{}}return s.length===0&&process.env.LIOP_BOOTSTRAP&&s.push(process.env.LIOP_BOOTSTRAP.trim()),s.filter(n=>{try{return multiaddr(n),!0}catch{return false}})}a(X,"resolveBootstrapNodes");async function _(e,s,a$1){let n=a(async t=>{let l={"Content-Type":"application/json"};t&&(l.Authorization=`Bearer ${t}`),s.method&&(l["Mcp-Method"]=s.method);let d=s.params;return d?.name&&(l["Mcp-Name"]=d.name),await fetch(e,{method:"POST",headers:l,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)})},"send"),c;try{c=await a$1.getToken();}catch(t){b$1.warn(`[LIOP-Agent] Token acquisition warning: ${t instanceof Error?t.message:String(t)}`);}let i=await n(c);if(i.status===401&&c){b$1.info("[LIOP-Agent] \u{1F504} 401 received from Gateway. Refreshing token and retrying..."),a$1.invalidate();try{c=await a$1.getToken(),i=await n(c);}catch{}}if(!i.ok){let t=await i.text(),l=null;try{l=JSON.parse(t);}catch{}let d=l?.error;return {jsonrpc:"2.0",id:s.id,error:{code:d?.code??-32603,message:d?.message??`Gateway returned HTTP ${i.status}: ${t}`}}}return await i.json()}a(_,"forwardToGateway");async function z(e,s,a){b$1.info(`[LIOP-Agent] \u{1F6E1}\uFE0F Running in ADAPTIVE GATEWAY MODE -> ${e.mcpEndpoint}`),a.registerLocalTool(b),a.registerGatewayTools(e.tools.map(t=>({name:t})),e.mcpEndpoint);let n=e.tools.length,c=setInterval(async()=>{try{let t=await fetch(e.healthEndpoint,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(t.ok){let l=await t.json();l.tools&&l.tools.length!==n&&(b$1.info(`[LIOP-Agent] Gateway tools topology updated (${n} -> ${l.tools.length})`),n=l.tools.length,a.registerGatewayTools(l.tools.map(d=>({name:d})),e.mcpEndpoint),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
2
+ import {b as b$2,a as a$3}from'../chunk-2XHSALII.js';import {a as a$4}from'../chunk-N35BC62H.js';import {m}from'../chunk-CQ2VNVSP.js';import'../chunk-MQ5SU26J.js';import {a as a$2}from'../chunk-AN5NODTN.js';import'../chunk-6KFKO6ZX.js';import'../chunk-TKLRW52V.js';import'../chunk-Y675R34Z.js';import'../chunk-XLVEDKM6.js';import'../chunk-2ZYX736J.js';import'../chunk-ECRS6N33.js';import'../chunk-ZZMSFCJP.js';import {g,f,d}from'../chunk-GWVSCZUS.js';import'../chunk-6VK2XALI.js';import'../chunk-FTF6AMF6.js';import'../chunk-YLCNV764.js';import {a as a$1}from'../chunk-V35CXJQN.js';import {b as b$1}from'../chunk-3WRKTVOF.js';import {a}from'../chunk-AYDF3IFZ.js';import*as L from'fs';import*as G from'os';import*as R from'path';import*as N from'readline';import {multiaddr}from'@multiformats/multiaddr';var b={name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}};async function F(e){try{let s=e.endsWith("/health")?e:`${e}/health`,a=await fetch(s,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!a.ok)return null;let n=await a.json();if(!n.mesh?.multiaddrs?.length||!n.mesh?.peerId)return null;let c=n.mesh.multiaddrs.find(t=>t.includes("/tcp/")&&!t.includes("/ws")&&!t.includes("/ip4/127.0.0.1/"));if(!c)return null;let i=C()?k(c):c;if(!i||i===c){let t=new URL(e).hostname;i=c.replace(/\/ip4\/[^/]+/,`/ip4/${t}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${n.mesh.peerId}`,i):null}catch{return null}}a(F,"resolveBootstrapFromUrl");function V(e){let s=e.trim(),a=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,n=/\/ip4\/127\.0\.0\.1/,c=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(a.test(s)||n.test(s)||c.test(s)){let i="127.0.0.1",t=s.replace(a,`/ip4/${i}`).replace(n,`/ip4/${i}`).replace(c,`/ip4/${i}`);return t!==s&&b$1.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${t}`),t}return s}a(V,"normalizeBootstrap");function k(e){return e.includes("/ip4/172.23.0.10")?e.replace(/\/ip4\/172\.23\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15001"):e.includes("/ip4/172.23.0.20")?e.replace(/\/ip4\/172\.23\.0\.20\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15011"):e.includes("/ip4/172.21.0.13")?e.replace(/\/ip4\/172\.21\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15031"):e.includes("/ip4/172.21.0.14")?e.replace(/\/ip4\/172\.21\.0\.14\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/15041"):e.includes("/ip4/172.20.0.10")?e.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):e.includes("/ip4/172.20.0.11")?e.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):e.includes("/ip4/172.20.0.12")?e.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):e.includes("/ip4/172.20.0.13")?e.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):e.includes("/ip4/127.0.0.1/tcp/4000")||e.includes("/ip4/127.0.0.1/tcp/3000")?null:e}a(k,"industrialAddressMapper");function q(e){try{let s=new URL(e);return (s.hostname==="127.0.0.1"||s.hostname==="localhost")&&(s.port==="13000"||s.port==="13001"||s.port==="15000"||s.port==="15018")}catch{return false}}a(q,"isDockerDemoHost");function C(){return process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||!!process.env.LIOP_NEXUS_URL&&q(process.env.LIOP_NEXUS_URL)}a(C,"shouldEnableDockerMap");async function X(e){let s=[],a=process.argv.slice(2);if(a.length>0&&(s=a.filter(n=>n.startsWith("/"))),process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL){let n=process.env.LIOP_NEXUS_URL||process.env.LIOP_BLG_URL;if(n){let c=await F(n);if(c){let i=V(c);s.includes(i)||(s.push(i),b$1.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${i}`));}}}if(s.length===0){let n=[process.cwd(),R.join(process.cwd(),"tests/infra/nexus-data"),e,R.join(R.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data")];for(let c of n)try{if(L.existsSync(c)){let t=L.readdirSync(c).filter(l=>l.endsWith(".multiaddr"));for(let l of t){let d=R.join(c,l),r=L.readFileSync(d,"utf8").trim();if(r){let m=V(r);s.includes(m)||(s.push(m),b$1.info(`[LIOP-Agent] \u2705 Loaded beacon: ${l} from ${c}`));}}if(s.length>0)break}}catch{}}return s.length===0&&process.env.LIOP_BOOTSTRAP&&s.push(process.env.LIOP_BOOTSTRAP.trim()),s.filter(n=>{try{return multiaddr(n),!0}catch{return false}})}a(X,"resolveBootstrapNodes");async function _(e,s,a$1){let n=a(async t=>{let l={"Content-Type":"application/json"};t&&(l.Authorization=`Bearer ${t}`),s.method&&(l["Mcp-Method"]=s.method);let d=s.params;return d?.name&&(l["Mcp-Name"]=d.name),await fetch(e,{method:"POST",headers:l,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)})},"send"),c;try{c=await a$1.getToken();}catch(t){b$1.warn(`[LIOP-Agent] Token acquisition warning: ${t instanceof Error?t.message:String(t)}`);}let i=await n(c);if(i.status===401&&c){b$1.info("[LIOP-Agent] \u{1F504} 401 received from Gateway. Refreshing token and retrying..."),a$1.invalidate();try{c=await a$1.getToken(),i=await n(c);}catch{}}if(!i.ok){let t=await i.text(),l=null;try{l=JSON.parse(t);}catch{}let d=l?.error;return {jsonrpc:"2.0",id:s.id,error:{code:d?.code??-32603,message:d?.message??`Gateway returned HTTP ${i.status}: ${t}`}}}return await i.json()}a(_,"forwardToGateway");async function z(e,s,a){b$1.info(`[LIOP-Agent] \u{1F6E1}\uFE0F Running in ADAPTIVE GATEWAY MODE -> ${e.mcpEndpoint}`),a.registerLocalTool(b),a.registerGatewayTools(e.tools.map(t=>({name:t})),e.mcpEndpoint);let n=e.tools.length,c=setInterval(async()=>{try{let t=await fetch(e.healthEndpoint,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(4e3)});if(t.ok){let l=await t.json();l.tools&&l.tools.length!==n&&(b$1.info(`[LIOP-Agent] Gateway tools topology updated (${n} -> ${l.tools.length})`),n=l.tools.length,a.registerGatewayTools(l.tools.map(d=>({name:d})),e.mcpEndpoint),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
3
3
  `),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
4
4
  `));}}catch{}},15e3),i=N.createInterface({input:process.stdin,terminal:false});process.stdout.on("error",t=>{t.code==="EPIPE"&&(clearInterval(c),process.exit(0));}),i.on("line",async t=>{let l=t.trim();if(!l)return;let d$1;try{d$1=JSON.parse(l);}catch{return}let{id:r,method:m}=d$1;if(m==="server/discover"){let o={jsonrpc:"2.0",id:r,result:{resultType:"complete",supportedVersions:["2026-07-28","2025-11-25"],capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-adaptive-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(o)}
5
5
  `);return}if(m==="initialize"){let u=(d$1.params?.protocolVersion??d$1.params?._meta?.["io.modelcontextprotocol/protocolVersion"])==="2026-07-28"?"2026-07-28":"2025-11-25",f={jsonrpc:"2.0",id:r,result:{protocolVersion:u,capabilities:{tools:{listChanged:true},resources:{listChanged:true,subscribe:true},prompts:{listChanged:true}},serverInfo:{name:"liop-adaptive-agent",version:"2.5.0"}}};process.stdout.write(`${JSON.stringify(f)}
package/dist/bridge.js CHANGED
@@ -1,2 +1,2 @@
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
1
+ export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-YMR3PMO3.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=bridge.js.map
2
2
  //# sourceMappingURL=bridge.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 as w$1}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 w(){let I=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(I==="0"||I==="false"||I==="no")}a(w,"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=w()?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),m=JSON.stringify({tools:u});t.record({type:"tools_list",method:"tools/list",estimatedInputTokens:t.countTokens(i),estimatedOutputTokens:t.countTokens(m)});let h=this.detectEra(o),d={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:u}};return h==="legacy"&&true&&(d=e(d)),d}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((m,h)=>m.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},m={jsonrpc:"2.0",id:c$1,result:i};return t==="legacy"&&!0&&(m=e(m)),m}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),m=typeof r=="object"&&r!==null?{resultType:"complete",...r}:r,h={jsonrpc:"2.0",id:c$1,result:m};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(m=>setTimeout(m,1e3));}let n=[],a=this.manifestCache.size===0?5:1;for(let t=0;t<a;t++){for(let d=0;d<B;d++){n=await this.meshNode?.discoverManifestProviders()||[];let g=this.meshNode?.getPeerId();if(n.filter(v=>v!==g).length>0)break;d<B-1&&(b.info(`[LIOP-Router] DHT discovery attempt ${d+1}/${B}...`),await new Promise(v=>setTimeout(v,1e3)));}let i=this.meshNode.node?.getConnections().map(d=>d.remotePeer.toString())||[];i.length>0&&(n=Array.from(new Set([...n,...i])));let m=this.meshNode?.getPeerId();if(n.filter(d=>d!==m).length>0)break;t<a-1&&(b.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${t+1}/${a})...`),await new Promise(d=>setTimeout(d,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 m=c.has(t)?1:0;return (c.has(i)?1:0)-m});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:m})=>i+m.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:w()?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 m=t.inputSchema.properties||{},h="";!w()&&m.payload&&(h=`
10
+ [REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!w()&&t.description.includes("STRICT SCHEMA ADHERENCE")&&(t.description=t.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let d=w()?`
11
+ (Peer: ${c.slice(-8)})${i}`:`
12
+ (Origin: ${c.slice(-8)})${i}${h}`;t.description=`${t.description}${d}`,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",d=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
+ ${d}
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
+ `),M=f.getInstance();return M.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:M.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,m=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_${m} 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=p?.arguments??(p?.payload!==void 0?p:{}),r=await this.liopServer.callTool({name:a,arguments:s}),l=f.getInstance(),u=JSON.stringify(s),t=JSON.stringify(r),i,m=this.liopServer.getSandboxData();return m&&m.length>0&&(i=l.countTokens(JSON.stringify(m))),l.record({type:"tool_call",method:"tools/call",toolName:a,estimatedInputTokens:l.countTokens(u),estimatedOutputTokens:l.countTokens(t),durationMs:Date.now()-e,originDatasetTokens:i}),f$2.inc({capability:a,tool:a,status:r.isError?"error":"success",role:"executor"}),{jsonrpc:"2.0",id:o,result:r}}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 d=await this.meshNode.queryManifest(n);d&&(s=d.grpcPort,this.manifestCache.set(n,{manifest:d,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(d=>d.includes("13001")||d.includes("13003")||d.includes("13004")||d.includes("13005")||d.includes("13011")||d.includes("13021")||d.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 d=e?.manifest?.serverInfo?.name?.toLowerCase()||"",g=p.toLowerCase();d.includes("vault")||g.includes("medical")?s=13011:d.includes("bank")||g.includes("bank")?s=13021:(d.includes("oracle")||g.includes("hft")||g.includes("market"))&&(s=13031);}let m=null;if(i$1)m=`127.0.0.1:${s}`;else {let d=await import('os'),g=Object.values(d.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(_)){m=`127.0.0.1:${s}`;break}m||(m=`${_}:${s}`);}}}m||(m=`127.0.0.1:${s}`),b.info(`[LIOP-Router] Dynamic route: ${p} -> ${m} (PeerID: ${n})`);let h=new g$1.LogicMesh(m,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",m=t.manifest.tokenSlug,h=c.slice(-8).toUpperCase(),d=m?`LIOP_TOKEN_${m}`:`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 ${d} 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(m$1,h)=>{if(m$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: ${m$1?.message||"Rejected"}`}],isError:true}})}let d=performance.now(),{ciphertext:g,sharedSecret:y}=await a$3.encapsulateAsymmetric(h.kyber_public_key),v$1=performance.now()-d;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),M=`return { "__liop_proxy_tool": "${n}", "__liop_proxy_args": ${_} };`,P=D.randomBytes(12),L=this.encryptWithNonce(Buffer.from(M),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(M),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$1.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-AN5NODTN.js.map
31
+ //# sourceMappingURL=chunk-AN5NODTN.js.map
@@ -0,0 +1,46 @@
1
+ import {a as a$2}from'./chunk-MQ5SU26J.js';import {a as a$3,b as b$2}from'./chunk-XLVEDKM6.js';import {b as b$1}from'./chunk-2ZYX736J.js';import {j,g,h,f as f$1}from'./chunk-ECRS6N33.js';import {k,f,h as h$1,w,x,g as g$1}from'./chunk-ZZMSFCJP.js';import {a as a$1}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import*as O from'crypto';import O__default from'crypto';import*as S from'fs';import {createRequire}from'module';import L from'path';import {fileURLToPath,pathToFileURL}from'url';import*as _ from'@grpc/grpc-js';import {createMlKem768}from'mlkem';import {Piscina,FixedQueue}from'piscina';import {z}from'zod';import*as B from'jose';import Ae from'oidc-provider';import*as ne from'acorn';import {simple}from'acorn-walk';var J=class{static{a(this,"LiopRpcServer");}server;constructor(){this.server=new _.Server(j);}addService(e){this.server.addService(g.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,r){let t=h(r);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,t,(s,o)=>{if(s){n(s);return}b.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async gracefulShutdown(e=5e3){return new Promise(r=>{let t=false,i=setTimeout(()=>{t||(t=true,b.warn(`[LIOP-RPC] tryShutdown timed out after ${e}ms \u2014 forcing shutdown`),this.server.forceShutdown(),r());},e);this.server.tryShutdown(()=>{t||(t=true,clearTimeout(i),b.info("[LIOP-RPC] Server gracefully shut down"),r());});})}async stop(){return this.gracefulShutdown(5e3)}};var ve="0".repeat(64);function _e(h){let e=Object.keys(h).sort(),r={};for(let t of e)r[t]=h[t];return JSON.stringify(r)}a(_e,"canonicalize");function Ee(h){let e=_e(h);return O.createHash("sha256").update(e).digest("hex")}a(Ee,"computeEntryHash");var ie=class{static{a(this,"AuditLogger");}entries=[];lastEntryHash=ve;filePath;interceptor;constructor(e){this.filePath=e,this.filePath&&S.existsSync(this.filePath)&&this.loadFromFile(this.filePath);}setInterceptor(e){this.interceptor=e;}recordExecution(e){let r=O.randomUUID(),t=e.timestamp||new Date().toISOString(),i=e.traceId||O.randomBytes(16).toString("hex"),n=e.datasetHash||O.createHash("sha256").update("").digest("hex"),s=e.outputHash||O.createHash("sha256").update("").digest("hex"),o=e.zkReceiptSig||"",a={id:r,timestamp:t,traceId:i,agentDid:e.agentDid,peerId:e.peerId,toolName:e.toolName,datasetHash:n,fuelConsumed:e.fuelConsumed,outputHash:s,zkReceiptSig:o,status:e.status,prevEntryHash:this.lastEntryHash},c=Ee(a),l={...a,entryHash:c};if(this.entries.push(l),this.lastEntryHash=c,this.filePath&&S.appendFileSync(this.filePath,`${JSON.stringify(l)}
2
+ `,"utf8"),this.interceptor){let u=Object.freeze(structuredClone(l));try{let y=this.interceptor(u);y&&typeof y=="object"&&"catch"in y&&y.catch(()=>{});}catch{}}return l}getEntries(){return [...this.entries]}getEntryCount(){return this.entries.length}verifyIntegrity(){let e=ve;for(let r=0;r<this.entries.length;r++){let t=this.entries[r];if(t.prevEntryHash!==e)return {valid:false,totalEntries:this.entries.length,brokenIndex:r,reason:`Broken hash chain at index ${r}: expected prevHash ${e}, got ${t.prevEntryHash}`};let{entryHash:i,...n}=t,s=Ee(n);if(s!==i)return {valid:false,totalEntries:this.entries.length,brokenIndex:r,reason:`Tampered entry at index ${r}: hash mismatch (expected ${s}, stored ${i})`};e=i;}return {valid:true,totalEntries:this.entries.length}}exportJsonl(){return this.entries.map(e=>JSON.stringify(e)).join(`
3
+ `)}loadFromFile(e){let t=S.readFileSync(e,"utf8").split(`
4
+ `).filter(i=>i.trim().length>0);for(let i of t){let n=JSON.parse(i);this.entries.push(n),this.lastEntryHash=n.entryHash;}}},Se=new ie;var H={audience:"urn:liop:mesh:api",tokenTtlSeconds:3600,jwksCacheTtlMs:6e5,jwksCooldownMs:3e4,clockToleranceSec:5,signingAlgorithm:"EdDSA"};var q=class{static{a(this,"JwtValidator");}jwksResolver;issuer;audience;constructor(e,r,t){this.issuer=e,this.audience=r,t instanceof URL?this.jwksResolver=B.createRemoteJWKSet(t,{cacheMaxAge:H.jwksCacheTtlMs,cooldownDuration:H.jwksCooldownMs}):this.jwksResolver=B.createLocalJWKSet(t);}async validate(e){let r=this.buildIssuerAliases(),{payload:t}=await B.jwtVerify(e,this.jwksResolver,{issuer:r.length>1?r:this.issuer,audience:this.audience,algorithms:[H.signingAlgorithm,"ES256"],clockTolerance:H.clockToleranceSec,requiredClaims:["sub","scope"]});return {token:e,clientId:t.sub??"unknown",scopes:typeof t.scope=="string"?t.scope.split(" "):[],expiresAt:t.exp}}buildIssuerAliases(){let e=[this.issuer],r=this.issuer.endsWith("/")?this.issuer.slice(0,-1):this.issuer,t=["nexus:3000","liop-nexus:3000","127.0.0.1:3000","localhost:3000","127.0.0.1:13000","localhost:13000","127.0.0.1:13001","localhost:13001","127.0.0.1:15000","localhost:15000"],i="";try{let o=new URL(r);i=`${o.hostname}:${o.port||"3000"}`;}catch{return e}if(!t.some(o=>i===o))return e;let s=r.replace(/^https?:\/\/[^/]+/,"");for(let o of t){let a=`http://${o}${s}`;e.includes(a)||e.push(a);}if(s)for(let o of t){let a=`http://${o}`;e.includes(a)||e.push(a);}else for(let o of t){let a=`http://${o}/oidc`;e.includes(a)||e.push(a);}return e}getIssuer(){return this.issuer}getAudience(){return this.audience}};function be(h){let{privateKey:e,publicKey:r}=O__default.generateKeyPairSync("ed25519"),t=e.export({format:"jwk"}),i=r.export({format:"jwk"}),n=O__default.createHash("sha256").update(i.x||"").digest("hex").slice(0,16),s={...t,kid:n,use:"sig",alg:"EdDSA"},o={...i,kid:n,use:"sig",alg:"EdDSA"},a$1={keys:[s]},c={keys:[o]},l={scopes:["openid","offline_access",...b$2],clients:h.clients.map(v=>({client_id:v.client_id,client_secret:v.client_secret,grant_types:["client_credentials"],response_types:[],redirect_uris:[],scope:v.scope,token_endpoint_auth_method:"client_secret_post",id_token_signed_response_alg:"EdDSA"})),features:{clientCredentials:{enabled:true},devInteractions:{enabled:false},resourceIndicators:{enabled:true,useGrantedResource:a(()=>true,"useGrantedResource"),getResourceServerInfo:a((v,p,f)=>({scope:f.scope||"",accessTokenFormat:"jwt",jwt:{sign:{alg:"EdDSA"}}}),"getResourceServerInfo")}},formats:{AccessToken:"jwt"},interactions:{url:a(()=>{throw new Error("InteractionsNotSupportedException: This Authorization Server is strictly configured for Machine-to-Machine flows.")},"url")},jwks:a$1,ttl:{ClientCredentials:3600},cookies:{keys:[O__default.randomBytes(32).toString("hex")]},extraTokenClaims:a((v,p)=>p.kind==="AccessToken"?{scope:p.scope}:{},"extraTokenClaims")},u=h.issuer.endsWith("/")?h.issuer.slice(0,-1):h.issuer,y=new Ae(u,l);return y.proxy=true,{provider:y,jwks:c}}a(be,"createOAuthServer");var V=class h{static{a(this,"TaintAnalyzer");}piiFields;sensitiveKeys;static TAINT_PROPAGATING_METHODS=new Set(["charCodeAt","codePointAt","charAt","at","indexOf","lastIndexOf","search","localeCompare","startsWith","endsWith","includes","substring","slice","substr","split","match","matchAll","replace","replaceAll","normalize","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat"]);static ARRAY_CALLBACK_METHODS=new Set(["map","forEach","filter","find","some","every","flatMap","findIndex"]);static REDUCE_METHODS=new Set(["reduce","reduceRight"]);currentRecordCollections=new Set;constructor(e,r=[]){this.piiFields=new Set(e.map(t=>t.toLowerCase())),this.sensitiveKeys=new Set(r.map(t=>t.toLowerCase()));}classifyField(e,r=[]){let t=e.toLowerCase();if(this.piiFields.has(t))return "forbidden";let i=new Set(r.map(n=>n.toLowerCase()));return this.sensitiveKeys.has(t)||i.has(t)?"sensitive":"public"}analyze(e,r,t=50){let i;try{let a=`function liop_analysis_wrapper(env) {
5
+ ${e}
6
+ }`;i=ne.parse(a,{ecmaVersion:"latest",sourceType:"script",locations:!0,allowReturnOutsideFunction:!0});}catch{return null}let n=new Set,s=new Set;this.identifyRecordBoundVars(i,n),this.propagateTaint(i,n,s);let o=this.checkReturnStatements(i,n,s);if(o)return o;if(r!==void 0&&r>0&&r<t){let a=this.detectCorrelatedAggregations(i);if(a)return a.reason=a.reason.replace("50 records",`${t} records`),a}if(r!==void 0&&r>0&&r<t){let a=this.detectMinMaxExtraction(i);if(a)return a.reason=a.reason.replace("50 records",`${t} records`),a}return null}extractQueriedFields(e){let r;try{r=ne.parse(`function w(env) {
7
+ ${e}
8
+ }`,{ecmaVersion:"latest",sourceType:"script",allowReturnOutsideFunction:!0});}catch{return []}let t=new Set;this.identifyRecordBoundVars(r,t);let i=new Set;return simple(r,{MemberExpression:a(s=>{let o=this.getPropertyName(s);if(!(!o||o==="length")&&(s.object.type==="Identifier"&&t.has(s.object.name)&&i.add(o),s.object.type==="MemberExpression")){let a=s.object;a.computed&&this.isEnvRecordsAccess(a.object)&&i.add(o);}},"MemberExpression")}),Array.from(i)}detectCorrelatedAggregations(e){let r=new Map;simple(e,{CallExpression:a(i=>{if(i.callee.type!=="MemberExpression")return;let n=i.callee,s=this.getPropertyName(n);if(!s||!h.REDUCE_METHODS.has(s)||!this.isEnvRecordsChain(n.object))return;let o=i.arguments[0];if(!o||o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return;let a=o,c=a.params.length>1?a.params[1]:a.params[0];if(c?.type!=="Identifier")return;let l=c.name,u=this.extractFieldsFromBody(a.body,l);for(let y of u){let v=r.get(y)??0;r.set(y,v+1);}},"CallExpression")});for(let[i,n]of r)if(n>=2)return {reason:`Correlation guard: ${n} aggregations detected on field '${i}'. Multiple correlated aggregations on the same field can enable differencing attacks. Use a single aggregation per numeric field, or increase dataset size above 50 records.`};return null}isEnvRecordsChain(e){if(this.isEnvRecordsAccess(e))return true;if(e.type==="CallExpression"){let r=e;if(r.callee.type==="MemberExpression"){let t=r.callee,i=this.getPropertyName(t);if(i&&(i==="slice"||i==="filter"||i==="toSorted"))return this.isEnvRecordsChain(t.object)}}return false}isRecordsSource(e){if(this.isEnvRecordsAccess(e)||e.type==="Identifier"&&this.currentRecordCollections.has(e.name))return true;if(e.type==="CallExpression"){let r=e;if(r.callee.type==="MemberExpression"){let t=r.callee,i=this.getPropertyName(t);if(i&&(i==="slice"||i==="filter"||i==="toSorted"||i==="map"||i==="concat"))return this.isRecordsSource(t.object)}}return false}identifyRecordCollections(e){this.currentRecordCollections.clear();for(let r=0;r<3;r++)simple(e,{VariableDeclarator:a(i=>{!i.init||i.id.type!=="Identifier"||this.isRecordsSource(i.init)&&this.currentRecordCollections.add(i.id.name);},"VariableDeclarator"),AssignmentExpression:a(i=>{i.left.type==="Identifier"&&this.isRecordsSource(i.right)&&this.currentRecordCollections.add(i.left.name);},"AssignmentExpression")});}extractFieldsFromBody(e,r){let t=[];return simple(e,{MemberExpression:a(n=>{if(n.object.type==="Identifier"&&n.object.name===r){let s=this.getPropertyName(n);s&&s!=="length"&&t.push(s);}},"MemberExpression")}),t}detectMinMaxExtraction(e){let r=null;return simple(e,{CallExpression:a(i=>{if(!r&&i.callee.type==="MemberExpression"){let n=i.callee;if(n.object.type==="Identifier"&&n.object.name==="Math"){let s=this.getPropertyName(n);(s==="min"||s==="max")&&i.arguments.some(o=>o.type==="SpreadElement"&&this.isRecordsMapCall(o.argument))&&(r={reason:`Min/Max gate: Math.${s}() on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations.`});}}},"CallExpression"),MemberExpression:a(i=>{if(!r&&i.computed&&i.object.type==="CallExpression"){let n=i.object;if(n.callee.type==="MemberExpression"){let s=this.getPropertyName(n.callee);if(s==="sort"||s==="toSorted"){let o=n.callee.object;this.isEnvRecordsChain(o)&&(r={reason:"Min/Max gate: .sort()[index] on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations."});}}}},"MemberExpression")}),r}isRecordsMapCall(e){if(e.type!=="CallExpression")return false;let r=e;if(r.callee.type!=="MemberExpression")return false;let t=r.callee;return this.getPropertyName(t)==="map"&&this.isRecordsSource(t.object)}identifyRecordBoundVars(e,r){this.identifyRecordCollections(e),simple(e,{CallExpression:a(n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isRecordsSource(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(h.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&r.add(l.name);}if(h.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&r.add(l.name);}}},"CallExpression"),ForOfStatement:a(n=>{if(this.isRecordsSource(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&r.add(s.id.name);},"ForOfStatement")}),simple(e,{VariableDeclarator:a(n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isRecordsSource(s.object)&&r.add(n.id.name);}},"VariableDeclarator")});}propagateTaint(e,r,t){for(let i=0;i<3;i++){let n=t.size;if(simple(e,{VariableDeclarator:a(o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,r,t)&&t.add(o.id.name);},"VariableDeclarator"),AssignmentExpression:a(o=>{if(o.left.type==="MemberExpression"){let a=o.left;a.computed&&this.isExpressionTainted(a.property,r,t)&&a.object.type==="Identifier"&&t.add(a.object.name);}o.left.type==="Identifier"&&this.isExpressionTainted(o.right,r,t)&&t.add(o.left.name);},"AssignmentExpression"),FunctionDeclaration:a(o=>{o.id&&o.id.type==="Identifier"&&this.doesCallbackProduceTaint(o,null,r,t)&&t.add(o.id.name);},"FunctionDeclaration"),CallExpression:a(o=>{if(o.callee.type!=="MemberExpression")return;let a=o.callee;this.getPropertyName(a)==="push"&&a.object.type==="Identifier"&&o.arguments.some(l=>this.isExpressionTainted(l,r,t))&&t.add(a.object.name);},"CallExpression")}),t.size===n)break}}checkReturnStatements(e,r,t){let i=null;return simple(e,{ReturnStatement:a(s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,r,t)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,r,t);i={reason:`PII side-channel detected: output contains values derived from restricted fields. ${a?`Operation: ${a}. `:""}Use only non-PII fields (e.g., numeric/date columns) for aggregations.`,line:o,operation:a};}},"ReturnStatement")}),i}isExpressionTainted(e,r,t){switch(e.type){case "Identifier":return t.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,r,t);case "CallExpression":return this.isCallExprTainted(e,r,t);case "YieldExpression":{let i=e;return i.argument?this.isExpressionTainted(i.argument,r,t):false}case "FunctionExpression":case "ArrowFunctionExpression":{let i=e;return this.doesCallbackProduceTaint(i,null,r,t)}case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,r,t)||this.isExpressionTainted(i.right,r,t)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,r,t)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,r,t)||this.isExpressionTainted(i.consequent,r,t)||this.isExpressionTainted(i.alternate,r,t)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"?n.computed&&this.isExpressionTainted(n.key,r,t)?true:this.isExpressionTainted(n.value,r,t):n.type==="SpreadElement"?this.isExpressionTainted(n.argument,r,t):false);case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,r,t));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,r,t));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,r,t)}default:return false}}isMemberExprTainted(e,r,t){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&r.has(e.object.name)&&i&&this.piiFields.has(i.toLowerCase()))return true;if(e.object.type==="MemberExpression"&&i&&this.piiFields.has(i.toLowerCase())){let n=e.object;if(n.computed&&this.isRecordsSource(n.object))return true}if(this.isExpressionTainted(e.object,r,t))return true;if(e.computed&&e.object.type==="Identifier"&&r.has(e.object.name)&&e.property.type==="Literal"){let n=e.property.value;if(typeof n=="string"&&this.piiFields.has(n.toLowerCase()))return true}return false}isCallExprTainted(e,r,t){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&h.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,r,t))return true;if(this.isRecordsSource(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,r,t)}if(this.isExpressionTainted(i.object,r,t)||e.arguments.some(s=>this.isExpressionTainted(s,r,t)))return true}if(e.callee.type==="MemberExpression"){let i=e.callee;this.getPropertyName(i)==="push"&&i.object.type==="Identifier"&&e.arguments.some(s=>this.isExpressionTainted(s,r,t))&&t.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(t.has(i))return true;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,r,t))}return false}doesCallbackProduceTaint(e,r,t,i){let n=new Set(t),s=new Set(i);if(e.params.length>0){let l=r!==null&&h.REDUCE_METHODS.has(r)?1:0;e.params.length>l&&e.params[l].type==="Identifier"&&n.add(e.params[l].name);}if(e.type==="ArrowFunctionExpression"&&e.body.type!=="BlockStatement")return this.isExpressionTainted(e.body,n,s);this.propagateTaint(e.body,n,s);let o=false,a$1={ReturnStatement:a(c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);},"ReturnStatement"),YieldExpression:a(c=>{let l=c;l.argument&&this.isExpressionTainted(l.argument,n,s)&&(o=true);},"YieldExpression")};return simple(e.body,a$1),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let r=e.property.value;if(typeof r=="string")return r}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let r=e;if(this.getPropertyName(r)==="records"&&r.object.type==="Identifier"&&r.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,r,t){if(e.type==="Identifier"){let i=e.name;if(t.has(i))return `variable '${i}' is PII-derived`}if(e.type==="ObjectExpression"){let i=e;for(let n of i.properties)if(n.type==="Property"&&this.isExpressionTainted(n.value,r,t))return `property '${n.key.type==="Identifier"?n.key.name:"unknown"}' contains PII-derived value`}if(e.type==="CallExpression"){let i=e;if(i.callee.type==="MemberExpression"){let n=this.getPropertyName(i.callee);if(n)return `result of .${n}() on PII data`}}}};var ke={aspirin:"Medication",lisinopril:"Medication",metformin:"Medication",amlodipine:"Medication",atorvastatin:"Medication",omeprazole:"Medication",losartan:"Medication",simvastatin:"Medication",levothyroxine:"Medication",ibuprofen:"Medication",acetaminophen:"Medication",amoxicillin:"Medication",ciprofloxacin:"Medication",prednisone:"Medication",warfarin:"Medication",insulin:"Medication",hydrochlorothiazide:"Medication",gabapentin:"Medication",albuterol:"Medication",pantoprazole:"Medication",hypertension:"Condition",diabetes:"Condition",bronchitis:"Condition",pneumonia:"Condition",asthma:"Condition"},Q=4,Oe=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,X=class h{static{a(this,"NerScanner");}static nlp=null;async getNlp(){if(!h.nlp){let e=await import('compromise/three');h.nlp=e.default||e,h.nlp.addWords(ke);}return h.nlp}async scan(e){if(e.length<Q||Oe.test(e))return {detected:false,entities:[]};let t=(await this.getNlp())(e),i=[],n=t.people().out("array");for(let a of n){let c=a.trim();c.length>=Q&&i.push({type:"person",text:c});}let s=t.places().out("array");for(let a of s){let c=a.trim();c.length>=Q&&i.push({type:"place",text:c});}let o=t.organizations().out("array");for(let a of o){let c=a.trim();c.length>=Q&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,r=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(r.has(e))return {detected:false,entities:[]};r.add(e);let t=Array.isArray(e)?e:Object.values(e),i=[];for(let n of t){let s=await this.scanDeep(n,r);if(s.detected&&(i.push(...s.entities),s.entities.some(o=>o.type==="person")))return {detected:true,entities:i}}return {detected:i.length>0,entities:i}}return {detected:false,entities:[]}}};function Ne(h){let e=h.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let r=0,t=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);t&&(n*=2,n>9&&(n-=9)),r+=n,t=!t;}return r%10===0}a(Ne,"isLuhnValid");function Ce(h){let e=h.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let r=e.substring(4)+e.substring(0,4),t="";for(let i=0;i<r.length;i++){let n=r.charCodeAt(i);if(n>=65&&n<=90)t+=(n-55).toString();else if(n>=48&&n<=57)t+=r.charAt(i);else return false}try{return BigInt(t)%97n===1n}catch{return false}}a(Ce,"isIbanValid");var R={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:a(h=>!h.endsWith("@example.com")&&!h.endsWith("@test.com"),"validator")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:Ne},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:a(h=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(h)?false:h.split(".").map(Number).every(t=>t>=0&&t<=255),"validator")},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")},"validator")},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");if(e.length!==9)return false;let r=parseInt(e.substring(0,3),10);return !(r===0||r===666||r>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")},"validator")},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Ce},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},Te={GLOBAL_STRICT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.PASSPORT_MRZ,R.IBAN],US_COMPLIANT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.SSN,R.PASSPORT_MRZ],EU_GDPR:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.IBAN,R.PASSPORT_MRZ]},ee=class h{static{a(this,"PiiScanner");}patterns;forbiddenKeysSet;nerScanner;static KEY_SAFELIST=new Set(["grid","video","android","identity","provide","override","validate","hidden","widget","guidelines","beside","guideline","outside","inside","collide","decide","divide","aside","ride","side","wide","hide","tide","pride","bride","slide","guide","stride","oxide","dioxide","suicide","homicide","pesticide","valid","invalid","void","avoid","diagnosis","medication","namespace","namesake","rename","filename","hostname","typename","unnamed","renamed","phonetic","phoneme","microphone","headphone","telephone","saxophone","smartphone","streetview","addressable","addressing","cityscape","electricity","capacity","velocity","opacity","timestamp","timezone","image_id","computation_result","zk_receipt","testid","toolid","sessionid","peerid","nodeid","requestid","correlationid","traceid","spanid"]);shortTokenBoundaryPatterns;longForbiddenTokens;constructor(e=[],r=[],t){this.patterns=e,this.forbiddenKeysSet=new Set(r.map(i=>i.toLowerCase())),this.nerScanner=t??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp((()=>{let n=i.split("").map(o=>`[${o.toLowerCase()}${o.toUpperCase()}]`).join(""),s=`[a-z]${i.charAt(0).toUpperCase()}${i.slice(1)}`;return `(?:^|[_-])${n}(?:$|[_-])|${s}(?:$|[A-Z_-])|^${n}$`})())):this.longForbiddenTokens.push(i);}async scan(e,r=new WeakSet){if(e==null)return null;if(typeof e=="string"){let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{let n=JSON.parse(t),s=await this.scan(n,r);if(s)return s}catch{}let i=this.checkString(e);if(i)return i;if(this.nerScanner){let n=await this.nerScanner.scan(e);if(n.detected){let s=n.entities.find(o=>o.type==="person");if(s)return `PII Entity Detected: person name "${s.text}"`}}return null}if(typeof e=="number"||typeof e=="bigint"){let t=e.toString();if(t.length>=7){let i=this.checkString(t);if(i)return i}return null}if(typeof e=="object"){if(r.has(e))return null;if(r.add(e),Array.isArray(e))for(let t of e){let i=await this.scan(t,r);if(i)return i}else for(let[t,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(t.toLowerCase()))return `Forbidden Key: ${t}`;let n=this.checkKeyFuzzy(t);if(n)return n;let s=await this.scan(i,r);if(s)return s}}return null}checkKeyFuzzy(e){let r=e.toLowerCase();if(h.KEY_SAFELIST.has(r))return null;for(let[t,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${t}"`;for(let t of this.longForbiddenTokens)if(r.includes(t))return `Forbidden Key (fuzzy): ${e} contains restricted token "${t}"`;return null}checkString(e){for(let r of this.patterns)if(typeof r=="string"){if(e.toLowerCase().includes(r.toLowerCase()))return r}else if(r instanceof RegExp){if(r.global&&(r.lastIndex=0),r.test(e))return r.source}else if(typeof r=="object"&&r!==null){let t=r;if(typeof t.pattern=="string"){if(e.toLowerCase().includes(t.pattern.toLowerCase())&&(!t.validator||t.validator(t.pattern)))return t.name}else if(t.pattern instanceof RegExp){t.pattern.global&&(t.pattern.lastIndex=0);let i=t.pattern.exec(e);for(;i!==null;){let n=i[0];if(!t.validator||t.validator(n))return t.name;if(!t.pattern.global)break;i=t.pattern.exec(e);}}}return null}};var Pe=L.dirname(fileURLToPath(import.meta.url)),Re=class h{constructor(e,r){this.serverInfo=e;this.config=r;let t=this.config?.security?.enableNerScanning?new X:null;this.piiScanner=new ee(this.config?.security?.piiPatterns??Te.GLOBAL_STRICT,this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],t);let i=this.config?.security?.rateLimit;this.toolCallWindowMs=i?.windowMs??Number.parseInt(process.env.LIOP_RATE_LIMIT_WINDOW_MS??"60000",10),this.toolCallMaxPerWindow=i?.maxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_MAX??"15",10),this.globalCallMaxPerWindow=i?.globalMaxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_GLOBAL_MAX??"40",10);let n=this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],s=this.config?.security?.sensitiveKeys??[];this.taintAnalyzer=new V(n,s),this.auditLogger=this.config?.auditLogger||Se;let o=import.meta.url.endsWith(".ts"),a=o?".ts":".js",c=[];if(o)try{let f=createRequire(import.meta.url).resolve("tsx/package.json"),d=pathToFileURL(L.join(L.dirname(f),"dist","loader.mjs")).href;c.push("--import",d);}catch{c.push("--import","tsx");}let l=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let u=[L.resolve(Pe,`./workers/logic-execution${a}`),L.resolve(Pe,`../workers/logic-execution${a}`)],y=u.find(p=>S.existsSync(p))||u[1];this.workerPool=new Piscina({filename:y,minThreads:this.config?.workerPool?.minThreads??(l?0:2),maxThreads:this.config?.workerPool?.maxThreads??(l?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(l?500:5e3),maxQueue:this.config?.workerPool?.maxQueue??"auto",taskQueue:new FixedQueue,execArgv:c,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}});let v=this.config?.workerPool?.minThreads??(l?0:2);if(this.workerPool&&v>0)for(let p=0;p<v;p++)this.workerPool.run({isWarmup:true}).catch(f=>{b.debug(`[LiopServer] Worker pool warm-up ping failed: ${f.message}`);});try{this.enclavePqcKeypair=b$1.generateKeyPair();}catch{this.enclavePqcKeypair=void 0;}if(this.config?.auth?.role==="nexus"){let p=this.config.auth.issuer||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=this.config.auth.clients||[{client_id:process.env.LIOP_OAUTH_CLIENT_ID||"liop-mesh-agent",client_secret:process.env.LIOP_OAUTH_CLIENT_SECRET||"dev-secret-change-me",grant_types:["client_credentials"],scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query"}],{provider:m,jwks:b}=be({issuer:p,clients:d});this.oauthProvider=m,this.jwtValidator=new q(p,f,b);}else if(this.config?.auth?.role==="node"){let p=this.config.auth.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=p.endsWith("/oidc")?p:`${p}/oidc`,m=new URL(`${d}/jwks`);this.jwtValidator=new q(p,f,m);}this.resource("LIOP Envelope Specification","liop://protocol/envelope-spec","Complete Logic-on-Origin envelope format, execution rules, and security constraints","text/plain",()=>Promise.resolve(this.buildEnvelopeSpec())),this.config?.auth?.revocationPath&&this.loadRevocationList();}serverInfo;config;static{a(this,"LiopServer");}logicCache=new Map;connectionStats=new Map;CACHE_TTL_MS=1440*60*1e3;THROTTLE_THRESHOLD=5;THROTTLE_COOLDOWN_MS=60*1e3;toolCallWindows=new Map;toolCallMaxPerWindow;toolCallWindowMs;globalCallWindow=[];globalCallMaxPerWindow;fieldQueryBudget=new Map;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;enclavePqcKeypair;jwtValidator;oauthProvider;sessions=new Map;revokedTokenHashes=new Set;lastRevocationLoadTime=0;pqcKeyPair=b$1.generateKeyPair();auditLogger;getDatasetHash(){return O__default.createHash("sha256").update(JSON.stringify(this.sandboxRecords||[])).digest("hex")}static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,\s*(?<name>[^}]*))?\}[\r\n]+(?<logic>[\s\S]*?)[\r\n]+@END/m;extractLogic(e){if(!e||typeof e!="string")return null;let r=e.trim().match(h.LIOP_COMPACT_REGEX);return r?.groups?.logic?r.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r)}catch{return e}return e}runPreflightPolicy(e,r,t,i="local-client"){if(t){let a=r.replace(/\s+/g," ");if(t.enforceAggregationFirst&&[/return\s+env\.records(?!\s*\.\s*(?:reduce|length|filter|every|some|find)\b)/i,/return\s*\{[\s\S]*\b(accounts|patients|rows|records)\s*:\s*env\.records(?!\s*\.\s*(?:reduce|length|filter)\b)/i].some(l=>l.test(a)))return "Preflight policy rejected: potential row-level export pattern detected.";if(t.preflightDenyPatterns?.some(c=>c.test(a)))return "Preflight policy rejected: custom deny pattern matched."}let n=50;typeof t?.enforceAggregationFirst=="object"&&(n=t.enforceAggregationFirst.minMaxBlockThreshold??50);let s=this.taintAnalyzer.analyze(r,this.sandboxRecords.length,n);if(s)return `Preflight policy rejected: ${s.reason}`;let o=this.taintAnalyzer.extractQueriedFields(r);if(o.length>0){if(i==="__proto__"||i==="constructor"||i==="prototype"||e==="__proto__"||e==="constructor"||e==="prototype")return "Preflight policy rejected: invalid property key names (prototype pollution guard).";let a=t?.budgetStorePath||this.config?.budgetStorePath;if(a)try{let c=this.executeWithBudgetLock(a,l=>{let u=l[i]||{},y=u[e]||{};for(let d of o){let m=this.taintAnalyzer.classifyField(d,t?.sensitiveKeys),b=25,T="public";if(t?.queryBudgetPerField!==void 0?(b=t.queryBudgetPerField,T="override"):m==="forbidden"?(b=3,T="forbidden"):m==="sensitive"&&(b=8,T="sensitive"),(y[d]??0)>=b)return {result:`Preflight policy rejected: Query budget exceeded for field '${d}' (max ${b} per session for ${T} fields). Rotate PQC session to reset budget.`}}let v={...y};for(let d of o)v[d]=(v[d]??0)+1;let p={...u};p[e]=v;let f={...l};return f[i]=p,{result:null,updatedBudget:f}});if(c)return c}catch(c){let l=c instanceof Error?c.message:String(c);b.error(`[LIOP-Server] Error applying persistent query budget: ${l}. Falling back to in-memory.`);let u=this.applyInMemoryBudget(i,e,o,t);if(u)return u}else {let c=this.applyInMemoryBudget(i,e,o,t);if(c)return c}}return null}validateOutputPolicy(e,r,t){if(!t)return null;let i=this.parseUnknownJson(r);if(i&&typeof i=="object"&&i.isError===true)return null;if(t.outputSchema){let s=(()=>{if(!(t.outputSchema instanceof z.ZodObject))return t.outputSchema;let o=t.outputSchema,a=o.def||o._def;return a&&a.catchall!==void 0&&!(a.catchall instanceof z.ZodNever)?o:o.strict()})().safeParse(i);if(!s.success)return `[LIOP] Output schema violation for ${e}: ${s.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}. HINT: Your output must conform to the declared schema. Use 'env.records' to access the dataset and return only allowed fields.`}return t.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),t.enforceAggregationFirst,this.sandboxRecords.length)?process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?"Aggregation-First Policy Violation: row-level export or K-Anonymity violation blocked. HINT: Use .reduce() to produce a flat {key:value} object. Do NOT use .map() to create arrays of objects. Ensure dataset size > 10 for detailed results.":"Aggregation-First Policy Violation: Output blocked due to privacy constraints.":null}unwrapForAggregationPolicyScan(e){if(typeof e=="string"){let n=e.trim();if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{return this.unwrapForAggregationPolicyScan(JSON.parse(n))}catch{return e}return e}if(!e||typeof e!="object")return e;let r=e;if(r.computation_result!==void 0)return this.unwrapForAggregationPolicyScan(r.computation_result);if(!Array.isArray(r.content)||r.content.length===0)return e;let t=[];for(let n of r.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&t.push(s);}if(t.length===0)return e;let i=t.length===1?t[0]:t.join(`
9
+ `);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,r,t){if(!r)return false;let i=typeof r=="object"&&typeof r.maxOutputRows=="number"?r.maxOutputRows:10,n=typeof r=="object"&&typeof r.allowPrimitiveArrays=="boolean"?r.allowPrimitiveArrays:true;if(typeof e=="string"){let s=e.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(s),r,t)}catch{return false}return false}if(Array.isArray(e))return e.length>0&&e.every(s=>typeof s=="object"&&s!==null)?e.length>i?true:e.some(s=>this.violatesAggregationFirstPolicy(s,r,t)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,r,t));if(e&&typeof e=="object"){let s=Object.keys(e);return t!==void 0&&t>0&&t<10&&(s.length>3||Object.values(e).some(a=>Array.isArray(a)||typeof a=="object"&&a!==null))||s.length>i?true:Object.values(e).some(o=>this.violatesAggregationFirstPolicy(o,r,t))}return false}buildEnvelopeSpec(){let e=["LIOP v1 Envelope Specification","================================","","FORMAT:","","Compact Envelope:"," @LIOP{wasi_v1,TaskName}"," <JavaScript code>"," @END","","RUNTIME ENVIRONMENT:","- env.records: Array of data objects from the origin","- Must use 'return' to output results","- Zero-Trust WASI Sandbox (Node.js Worker Pool)","- Return aggregated objects, NOT raw row-level arrays","","SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS:","- Date is poisoned: The 'Date' class/constructor is undefined (Date.now(), Date.parse(), etc. will throw)."," Workaround: Use lexicographical string comparison on ISO 8601 date strings (e.g., record.date >= '2024-01-01').","- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.","- Frozen prototypes: Any modifications to Object.prototype, Array.prototype, etc., are blocked.","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution","","DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism):","- Default field noise scale is derived from node global sensitivity.","- COUNT / LENGTH Optimization: To obtain EXACT counts without noise (sensitivity=1),"," the return keys MUST contain 'count', 'length', 'size', 'num', 'positive', 'negative',"," or start with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count').","- AVERAGE Optimization: Keys containing 'avg', 'mean' or 'average' scale noise"," down automatically by dividing sensitivity by dataset size (sensitivity / n).","- SUM / OTHER queries: Receive full Laplace noise based on global node sensitivity"," (e.g., Sensitivity=100,000 in Bank to protect balances)."];return this.config?.security?.forbiddenKeys?.length&&e.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),e.push("","TAINT TRACKING (Phase 108):","- AST-level analysis blocks PII-derived scalars (charCodeAt, charAt, etc.)","- Operations on restricted fields are tracked through variable assignments","- Boolean inference (field.charCodeAt(0) < N ? 1 : 0) is blocked","- Allowed: aggregations on non-PII fields (balance, amount, date)","","K-ANONYMITY THRESHOLDS:","- Small Datasets (< 10 records): Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.","- Large Datasets (>= 10 records): Maximum of 10 output fields.","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)","","QUERY BUDGET TIERS (NIST SP 800-226):","- FORBIDDEN (PII fields like name, accountHolder): Blocked in AST preflight. Never executed, does not consume budget.","- SENSITIVE (fields marked via sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override).","- PUBLIC (all other fields): 25 queries per agent identity.","- PERSISTENCE: The budget is tracked by agent DID and persisted to disk, NOT by MCP session."," Reconnecting or starting a new session does NOT reset the budget."," Reset requires: administrator calling resetFieldBudget() or manual deletion of the budget store file.","","AUTHENTICATION (tokenSlug Convention):","- Restricted nodes declare authRequired: true in their manifest.","- Token resolution: LIOP_TOKEN_<tokenSlug> (deterministic) > LIOP_TOKEN_<PeerID> > LIOP_TOKEN_<ProviderName>","- Format: tokenSlug must match SCREAMING_SNAKE_CASE /^[A-Z][A-Z0-9_]*$/ (e.g., BANK, VAULT, HFT_ORACLE)."),e.join(`
10
+ `)}extractSchemaFieldSummary(e,r=0){if(r>3)return "{...}";let t=e.type,i=e.properties,n=e.items;return i?`{${Object.entries(i).map(([o,a])=>{let c=a.type;if(c==="array"&&a.items){let l=this.extractSchemaFieldSummary(a.items,r+1);return `${o}(array of ${l})`}if(c==="object"&&a.properties){let l=this.extractSchemaFieldSummary(a,r+1);return `${o}(${l})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:t==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,r+1)}`:t||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,r,t,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z.object(t),o=z.toJSONSchema(s,{target:"draft-07"}),a$1=r,c=i;if(t.payload&&t.payload instanceof z.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a$1+=`
11
+
12
+ Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. Note: If dataset size < 10 (synthetic demo), Egress K-Anonymity blocks output if it has >3 keys or any array/nested object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a$1+=`
13
+ Restricted fields: ${u.join(", ")}.`),this.activeSchema){let y=this.extractSchemaFieldSummary(this.activeSchema);a$1+=`
14
+ Data structure: ${y}. Full schema: resource liop://schema/global`;}c=a(async(y,v)=>{let p="global_connection",f=Date.now(),d=this.connectionStats.get(p)||{failures:0,lastAttempt:0};if(d.failures>=this.THROTTLE_THRESHOLD&&f-d.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let m=y&&typeof y=="object"?y:{},b=m.payload??m.envelope??m.code,T=m.__liop_bypass_ast_cache===true,A=O__default.createHash("sha256").update(b||"").digest("hex"),w=this.extractLogic(b),x=this.logicCache.get(A);if(!T&&x&&f-x.timestamp<this.CACHE_TTL_MS&&w){m.payload=w,m.envelope!==void 0&&(m.envelope=w);let I=this.runPreflightPolicy(e,w,n,"mcp-client");return I?{content:[{type:"text",text:I}],isError:true}:await this.executeInWorkerPool(y,w,e)}if(!w)return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:"Error: Malformed payload. Missing @LIOP boundary.\\nYou MUST wrap your logic exactly like this:\\n\\n@LIOP{wasi_v1,DynamicAudit}\\n// Your JS code here\\n@END"}],isError:true};try{let I=this.extractLogic(b);m.payload=I,m.envelope!==void 0&&(m.envelope=I);let N=this.runPreflightPolicy(e,I,n,"mcp-client");if(N)return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:N}],isError:!0};let M=await this.executeInWorkerPool(y,I,e);return M.isError?(d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d)):(this.connectionStats.set(p,{failures:0,lastAttempt:f}),this.logicCache.set(A,{hash:A,timestamp:f})),M}catch(I){let N=I;return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:`ExecutionRuntimeException: ${N.message}`}],isError:true}}},"finalHandler");}let l={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a$1,inputSchema:l},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{b.info(`[LIOP-Mesh] Failed to auto-announce tool ${e}: ${u.message}`);});}prompt(e,r,t,i){if(this.prompts.has(e))throw new Error(`Prompt already registered: ${e}`);this.prompts.set(e,{prompt:{name:e,description:r,arguments:t},handler:i});}enableZeroShotAutonomy(){this.prompt("liop_blind_analyst","The official Logic-Injection-on-Origin Protocol system prompt. Instructs the LLM on how to securely inject Logic-on-Origin without violating PII or safety constraints.",[],e=>({description:"LIOP Blind Analyst Instructions",messages:[{role:"user",content:{type:"text",text:`You are the "Blind Analyst" operating within the Logic-Injection-on-Origin Protocol (LIOP) ecosystem.
15
+ Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
16
+
17
+ INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
18
+ 1. DATA PRIVACY: NEVER attempt to export Personally Identifiable Information (PII). The LIOP Egress Shield will block any response containing raw IDs, names, or addresses.
19
+ 2. AGGREGATION FIRST & K-ANONYMITY THRESHOLDS: Always prefer returning counts, averages, or anonymized summaries.
20
+ - Dataset < 10 records: Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.
21
+ - Dataset >= 10 records: Maximum of 10 output fields.
22
+ 3. LAPLACE DIFFERENTIAL PRIVACY (DP) COMPLIANCE:
23
+ - Legitimate COUNT queries: To obtain EXACT, un-noised counts, you MUST name your return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.
24
+ - Legitimate AVERAGE queries: Use 'avg_', '_average' or 'mean_' keys to automatically scale down Laplace noise by dividing sensitivity by the dataset size (sensitivity / n).
25
+ - Legitimate SUM queries: Return keys without count/average suffixes will receive full Laplacian noise scaled by the node's global sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.
26
+ 4. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
27
+ Structure:
28
+ @LIOP{wasi_v1,AnalysisTask}
29
+ // Your JS Code Here
30
+ @END
31
+ 5. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
32
+ 6. LOCALIZATION: Format all JSON response keys in the language used by the user in their query (e.g., use Spanish keys if the query is in Spanish).
33
+ 7. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.
34
+ 8. SANDBOX RUNTIME: The 'Date' class/constructor is poisoned and set to undefined. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw exceptions.
35
+ Workaround: Perform chronological operations and filtering using lexicographical string comparisons on ISO 8601 date strings (e.g., 'record.date >= "2024-01-01"').
36
+ Additionally, standard globals like 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', ArrayBuffer, and TypedArrays are also undefined.
37
+ 9. QUERY BUDGET PERSISTENCE: The per-field query budget is tracked by your agent DID and persisted to disk. Reconnecting or starting a new MCP session does NOT reset the budget. If you receive "Query budget exceeded", you must use a different field or request an administrator to invoke resetFieldBudget().${this.activeSchema?`
38
+
39
+ CURRENT DATA DICTIONARY (STRICT):
40
+ ${JSON.stringify(this.activeSchema,null,2)}`:""}
41
+
42
+ Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,r,t,i,n){if(this.resources.has(r))throw new Error(`Resource URI already registered: ${r}`);this.resources.set(r,{name:e,uri:r,description:t,mimeType:i,content:n});}buildExecutionGuidelines(){return ["LIOP Sandbox Execution Guidelines","=================================","","1. DATE POISONING & FILTERING WORKAROUND:"," The global 'Date' class is set to undefined inside the sandbox. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw a ReferenceError."," - Workaround: Perform chronological filtering using lexicographical string comparisons on ISO 8601 strings."," Example: const filtered = env.records.filter(r => r.date >= '2024-01-01' && r.date <= '2024-12-31');","","2. K-ANONYMITY CONSTRAINTS:"," - Datasets with LESS than 10 records: The returned object must contain at most 3 scalar fields, and must NOT contain any arrays or nested objects."," - Datasets with 10 or MORE records: The returned object can contain up to 10 fields.","","3. DIFFERENTIAL PRIVACY SUFFIXES:"," To avoid Laplacian noise adding random perturbations to your counts or averages, you must name your object keys using specific terms:"," - Counts (Exact, no noise): Key names must contain 'count', 'length', 'size', 'num', 'positive', 'negative', or start with 'total_' or 'num_'."," - Averages (Reduced noise): Key names must contain 'avg', 'mean', or 'average'."," - Sums/Other: Will receive full Laplace noise.","","4. GENERAL RESTRICTIONS:"," - Do not use 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', 'ArrayBuffer', or TypedArrays."," - Do not attempt to modify prototypes (Object.prototype, Array.prototype).","","5. QUERY BUDGET TIERS (NIST SP 800-226):"," The per-field query budget is tracked by agent DID and persisted to disk (not per MCP session)."," - FORBIDDEN (PII fields): Always blocked in AST preflight. Does not consume budget."," - SENSITIVE (sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override)."," - PUBLIC (other fields): 25 queries per agent identity."," - Reset requires administrator intervention via resetFieldBudget()."].join(`
43
+ `)}dataDictionary(e,r="Global Medical Data Dictionary",t="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){e.$comment="LIOP DIRECTIVES: 1. Date is undefined (Date.now(), new Date() throw). Workaround: use lexicographical string comparison on ISO 8601 string dates (e.g. record.date >= '2024-01-01'). 2. Small datasets (<10 records) limit outputs to max 3 scalar keys with NO nesting. 3. DP counts must contain count/length/size/num/total_ prefix/suffix.",this.activeSchema=e;let n=this.extractSchemaFieldSummary(e);for(let[s,o]of this.tools.entries())o.schema.shape.payload&&o.schema.shape.payload instanceof z.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
44
+ Data structure: ${n}. Full schema: resource ${t}. Guidelines: resource liop://schema/guidelines`,this.tools.set(s,o));this.resources.has("liop://schema/guidelines")||this.resource("LIOP Execution Guidelines","liop://schema/guidelines","Directives for generating compliant JavaScript code for the LIOP Sandbox runtime","text/plain",()=>Promise.resolve(this.buildExecutionGuidelines())),this.resource(r,t,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),b.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let r=Date.now(),t=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>r-o<t);if(s.length>=i){let o=Math.ceil((s[0]+t-r)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${t/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(r),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),r=this.toolCallWindowMs,t=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<r),this.globalCallWindow.length>=t){let i=Math.ceil((this.globalCallWindow[0]+r-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${t} total calls per ${r/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e,r="local-client"){let t=this.tools.get(e.name);if(!t)throw new Error(`Tool not found: ${e.name}`);let i=this.checkGlobalRateLimit();if(i)return i;let n=this.checkToolCallRateLimit(e.name);if(n)return n;try{let s=t.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(s.__liop_bypass_ast_cache=!0),s&&typeof s.payload=="string"){let a=s.payload,c=this.extractLogic(a);if(c){let l=this.runPreflightPolicy(e.name,c,t.policy,r);return l?{content:[{type:"text",text:l}],isError:!0}:(s.payload=c,await this.executeInWorkerPool(s,c,e.name))}}return await t.handler(s,{})}catch(s){let o=s;return o instanceof z.ZodError?{content:[{type:"text",text:`Validation Error: ${o.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${o.message}`}],isError:true}}}listTools(){return Array.from(this.tools.values()).map(e=>e.tool)}listPrompts(){return Array.from(this.prompts.values()).map(e=>e.prompt)}async getPrompt(e){let r=this.prompts.get(e.name);if(!r)throw new Error(`Prompt not found: ${e.name}`);return await r.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let r=this.resources.get(e);if(!r)throw new Error(`Resource not found: ${e}`);let t="No description provided";return typeof r.content=="function"?t=await r.content():typeof r.content=="string"?t=r.content:r.description&&(t=r.description),{contents:[{uri:r.uri,mimeType:r.mimeType||"text/plain",text:t}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getSandboxData(){return this.sandboxRecords}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let r=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,t=e.port??r??50051,i=/^[A-Z][A-Z0-9_]*$/;if(this.config?.tokenSlug&&!i.test(this.config.tokenSlug))throw new Error(`Invalid tokenSlug "${this.config.tokenSlug}". Must match SCREAMING_SNAKE_CASE: /^[A-Z][A-Z0-9_]*$/ (e.g., "BANK", "VAULT", "HFT_ORACLE").`);this.meshNode=new a$1(e.meshConfig),await this.meshNode.start();let n=this.meshNode;this.meshNode.registerManifestHandler(()=>{let s=this.listTools().map(l=>{let u=this.tools.get(l.name);return {name:l.name,description:l.description,inputSchema:l.inputSchema,zkMode:u?.policy?.zkMode,guestImageId:u?.policy?.guestImageId??this.config?.guestImageId,circuitName:u?.policy?.circuitName,vkey:u?.policy?.vkey}}),o=Array.from(this.resources.values()).map(l=>({name:l.name,uri:l.uri,description:l.description,mimeType:l.mimeType,text:typeof l.content=="string"?l.content:l.description})),a={peerId:n.getPeerId(),grpcPort:t,tools:s,resources:o,serverInfo:this.serverInfo,authRequired:this.jwtValidator!==void 0,tokenSlug:this.config?.tokenSlug,guestImageId:this.config?.guestImageId,vkeys:this.config?.zkVkeys,taxonomy:this.config?.taxonomy?{domain:this.config.taxonomy.domain||"Unknown Domain",clearanceTier:this.config.taxonomy.clearanceTier??0,executionTypes:this.config.taxonomy.executionTypes||[]}:void 0},c=b$1.signManifest(a,this.pqcKeyPair.secretKey,this.pqcKeyPair.publicKey);return {...a,pqcSignature:c.signature,pqcPublicKey:c.publicKey}});for(let s of this.listTools())await this.meshNode.announceCapability(s.name).catch(b.info);await this.meshNode.announceManifest().catch(b.info),this.rpcServer=new J,this.rpcServer.addService({negotiateIntent:a((s,o)=>{let a=s.request;if(b.info(`[LIOP-RPC] Negotiating intent for capability: ${a.capability_hash}`),this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){o({code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){o({code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info("[LIOP-RPC] Bypass authentication for matching localTestToken: [REDACTED]"),import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:p})=>{let{publicKey:f,secretKey:d}=await p.generateKeyPair(),m=O__default.randomUUID();this.sessions.set(m,{capability_hash:a.capability_hash,kyber_sk:d,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:m,error_message:"",kyber_public_key:f});});return}o({code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}this.jwtValidator.validate(l).then(p=>{let f=a$3("tools/call",p);if(!f.allowed){o({code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:d})=>{let{publicKey:m,secretKey:b}=await d.generateKeyPair(),T=O__default.randomUUID();this.sessions.set(T,{capability_hash:a.capability_hash,kyber_sk:b,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:T,error_message:"",kyber_public_key:m});});}).catch(p=>{o({code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p.message}`});});}else import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:c})=>{let{publicKey:l,secretKey:u}=await c.generateKeyPair(),y=O__default.randomUUID();this.sessions.set(y,{capability_hash:a.capability_hash,kyber_sk:u,agent_did:a.agent_did,createdAt:Date.now()}),o(null,{accepted:true,session_token:y,error_message:"",kyber_public_key:l});});},"negotiateIntent"),executeLogic:a(async s=>{let o=s.request;b.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${o.session_token}`);let a$1=a(async()=>{let c=this.sessions.get(o.session_token);if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Invalid session token"});return}let l=3600*1e3;if(c.createdAt){let f=Date.now()-c.createdAt;if(f>l){this.sessions.delete(o.session_token),s.emit("error",{code:_.status.UNAUTHENTICATED,details:`[LIOP-PQC] Session secret expired: Age (${Math.round(f/1e3)}s) exceeds 3600s TTL limit. Re-handshake required.`});return}}if(c.tokenHash&&(this.loadRevocationList(),this.revokedTokenHashes.has(c.tokenHash))){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let u=c.capability_hash,v=(u?this.tools.get(u):void 0)?.policy,p="";try{let d=(await createMlKem768()).decap(new Uint8Array(o.pqc_ciphertext),c.kyber_sk),m=Buffer.from(d),b$1=Buffer.from(o.wasm_binary),T=b$1.subarray(-16),A=b$1.subarray(0,-16),w=O__default.createDecipheriv("aes-256-gcm",m,Buffer.from(o.aes_nonce||new Uint8Array(12)));w.setAuthTag(T);let x=w.update(A);x=Buffer.concat([x,w.final()]),p=x.toString("utf-8");let I=this.extractLogic(p)||p.trim(),N=this.runPreflightPolicy(u||"unknown_tool",I,v,c.agent_did||o.session_token);if(N){b.info(`[LIOP-RPC] Preflight blocked: ${N}`);let M={semantic_evidence:N,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(M,()=>{s.end();});return}}catch(f){let d=f instanceof Error?f.message:String(f);b.error(`[LIOP-RPC] Preflight decryption failed: ${d}`),s.emit("error",{code:_.status.INTERNAL,details:`Preflight logic analysis failed: ${d}`});return}try{let f$2=v?{epsilon:v.dpEpsilon??1,sensitivity:v.dpSensitivity??1,smallDatasetThreshold:v.dpSmallDatasetThreshold??50}:void 0,d=o.requested_proof_mode;(d===void 0||d===0)&&(v?.zkMode==="required"?d=2:v?.zkMode==="optimistic"?d=1:d=0);let m=await this.workerPool.run({ciphertext:o.pqc_ciphertext,secretKeyObj:Array.from(c.kyber_sk),wasmBinary:o.wasm_binary,inputs:o.inputs,aesNonce:o.aes_nonce,records:this.sandboxRecords,sessionToken:o.session_token,sessionTimestamp:c.createdAt,isEncrypted:!0,proofMode:d,guestImageId:v?.guestImageId??this.config?.guestImageId,pqcSigningKey:v?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:f$2});if(d===2&&m.proof_type!==2&&m.proof_type!==3){b.error(`[LIOP-RPC] Enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable for ${u||"tool"}`);let k={semantic_evidence:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0,proof_type:0};s.write(k,()=>{s.end();});return}let b$1=a$2(m.output),T,A=b$1;try{T=typeof b$1=="string"?b$1:JSON.stringify(b$1);let k=JSON.parse(T);if(k.__liop_proxy_tool){b.info(`[LIOP-RPC] Executing Proxied Tool: ${k.__liop_proxy_tool}`);let W=c.agent_did||"unknown-client",D=await this.callTool({name:k.__liop_proxy_tool,arguments:k.__liop_proxy_args||{}},W);if(D.isError){b.info(`[LIOP-RPC] Proxy tool execution failed: ${D.content[0].text}`);let U={semantic_evidence:D.content[0].text||"Unknown error",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(U,()=>{s.end();});return}let G=a$2(D);T=JSON.stringify(G),A=this.unwrapForAggregationPolicyScan(G);}}catch{T=String(b$1);}let w$1=this.validateOutputPolicy(u||"unknown_tool",A,v);if(w$1){b.info(`[LIOP-RPC] Output policy blocked for ${u||"unknown_tool"}: ${w$1}`);let D={semantic_evidence:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?w$1:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(D,()=>{s.end();});return}let x$1={semantic_evidence:T,cryptographic_proof:Buffer.from(m.image_id||"","hex"),zk_receipt:m.zk_receipt?Buffer.from(m.zk_receipt,"base64"):Buffer.from(""),is_error:!1,proof_type:m.proof_type===3?3:m.proof_type===2?2:0,guest_image_id:m.guest_image_id||v?.guestImageId||this.config?.guestImageId||""},I=await this.piiScanner.scan(A),N=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(A),v?.enforceAggregationFirst,this.sandboxRecords?.length),M=!!(I||N);if(M){let k$1=I||"Aggregation-First Policy Violation";b.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${k$1}`),x$1.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",x$1.is_error=!0,k.inc({reason:I?"pii_scanner":"aggregation_policy"});}this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:m.fuel_consumed||0,outputHash:O__default.createHash("sha256").update(x$1.semantic_evidence).digest("hex"),zkReceiptSig:m.zk_receipt||"",status:M?"BLOCKED_EGRESS":"SUCCESS"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:M?"blocked_egress":"success",role:"executor"}),h$1.observe({capability:u||"unknown",tool:u||"unknown"},m.fuel_consumed||0);try{let k=Buffer.byteLength(x$1.semantic_evidence||"")+(x$1.cryptographic_proof?x$1.cryptographic_proof.length:0)+(x$1.zk_receipt?x$1.zk_receipt.length:0);if(w.inc({capability:u||"unknown"},k),this.sandboxRecords&&this.sandboxRecords.length>0){let W=JSON.stringify(this.sandboxRecords),D=Buffer.byteLength(W),G=Math.max(0,D-k);G>0&&x.inc({capability:u||"unknown"},G);try{let U=f$1.getInstance(),xe=U.countTokens(W),we=U.countTokens(x$1.semantic_evidence||""),Ie=U.countTokens(p||"");U.record({type:"tool_call",method:"ExecuteLogic",toolName:u||"unknown",estimatedInputTokens:Ie,estimatedOutputTokens:we,originDatasetTokens:xe});}catch{}}}catch{}s.write(x$1,()=>{s.end();});}catch(f$1){let d=f$1,m=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",b$1=d.message||String(f$1);b.error(`[LIOP-RPC] Execution Error: ${b$1}`);let T=m?`Execution Error: ${b$1}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.";this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:0,outputHash:O__default.createHash("sha256").update(T).digest("hex"),zkReceiptSig:"",status:"ERROR"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:"error",role:"executor"}),g$1.inc({capability:u||"unknown",error_type:"runtime_error"});let A={semantic_evidence:T,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{s.write(A,()=>{s.end();});}catch{s.end();}}},"proceed");if(this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info("[LIOP-RPC] Bypass authentication in executeLogic for matching localTestToken: [REDACTED]"),await a$1();return}s.emit("error",{code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}try{let p=await this.jwtValidator.validate(l),f=a$3("tools/call",p);if(!f.allowed){s.emit("error",{code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}await a$1();}catch(p){s.emit("error",{code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p instanceof Error?p.message:String(p)}`});}}else await a$1();},"executeLogic")}),this.boundPort=await this.rpcServer.listen(t),b.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,r,t){try{let i=t?this.tools.get(t)?.policy:void 0,n=i?{epsilon:i.dpEpsilon??1,sensitivity:i.dpSensitivity??1,smallDatasetThreshold:i.dpSmallDatasetThreshold??50}:void 0,s=0;i?.zkMode==="required"?s=2:i?.zkMode==="optimistic"&&(s=1);let o=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(r),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1,proofMode:s,guestImageId:i?.guestImageId??this.config?.guestImageId,pqcSigningKey:i?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:n});if(s===2&&o.proof_type!==2&&o.proof_type!==3)return {content:[{type:"text",text:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable."}],isError:!0};let a=o.output,c=a$2(a),u=[{type:"text",text:JSON.stringify({computation_result:c,image_id:o.image_id,zk_receipt:o.zk_receipt,proof_type:o.proof_type===3?"GROTH16_PQC_HYBRID":o.proof_type===2?"GROTH16":"HMAC_LEGACY",guest_image_id:o.guest_image_id,status:"Worker Pool Execution Success"})}],y=t?this.tools.get(t)?.policy:void 0,v=this.validateOutputPolicy(t||"unknown_tool",c,y);if(v)return b.info(`[LIOP-SDK] Output policy blocked for ${t||"unknown_tool"}: ${v}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?v:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let p=await this.piiScanner.scan(c),f=this.violatesAggregationFirstPolicy(c,y?.enforceAggregationFirst,this.sandboxRecords?.length);if(p||f){let d=p||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return b.info(`[LIOP-SDK] Secure egress blocked in local execution: ${d}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${d}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:u}}catch(i){let n=i,s=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",o=n.message||String(i);return b.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:o.includes("worker_thread_exited")||o.includes("ERR_WORKER_OUT_OF_MEMORY")||o.includes("terminated")||o.includes("heap limit")?"[LIOP] Execution terminated: memory limit exceeded (64MB heap). Reduce data processing volume.":s?`WorkerPoolError: ${o}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error."}],isError:true}}}async close(){this.workerPool&&await this.workerPool.close({force:true}),this.rpcServer&&await this.rpcServer.stop(),this.meshNode&&await this.meshNode.stop();}loadRevocationList(){let e=this.config?.auth?.revocationPath;if(e)try{if(S.existsSync(e)){let r=S.statSync(e);if(r.mtimeMs<=this.lastRevocationLoadTime)return;let t=S.readFileSync(e,"utf-8"),i=JSON.parse(t);if(Array.isArray(i)){this.revokedTokenHashes.clear();for(let n of i)typeof n=="string"&&this.revokedTokenHashes.add(n.trim().toLowerCase());this.lastRevocationLoadTime=r.mtimeMs,b.info(`[LiopServer] Loaded ${this.revokedTokenHashes.size} revoked token hashes from ${e}`);}}else {let r=L.dirname(e);S.existsSync(r)||S.mkdirSync(r,{recursive:!0}),S.writeFileSync(e,JSON.stringify([],null,2),"utf-8"),this.lastRevocationLoadTime=Date.now(),b.info(`[LiopServer] Created empty local revocation list at ${e}`);}}catch(r){b.error(`[LiopServer] Failed to load revocation list: ${r instanceof Error?r.message:String(r)}`);}}revokeToken(e){if(!e)return;let r=O__default.createHash("sha256").update(e).digest("hex").toLowerCase();this.revokeTokenHash(r);}revokeTokenHash(e){if(!e)return;let r=e.toLowerCase();this.loadRevocationList(),this.revokedTokenHashes.add(r);let t=this.config?.auth?.revocationPath;if(t)try{let i=L.dirname(t);S.existsSync(i)||S.mkdirSync(i,{recursive:!0});let n=Array.from(this.revokedTokenHashes);S.writeFileSync(t,JSON.stringify(n,null,2),"utf-8");let s=S.statSync(t);this.lastRevocationLoadTime=s.mtimeMs,b.info(`[LiopServer] Persisted revocation for hash ${r} to ${t}`);}catch(i){b.error(`[LiopServer] Failed to persist revocation: ${i instanceof Error?i.message:String(i)}`);}}resetFieldBudget(e,r){if(e==="__proto__"||e==="constructor"||e==="prototype"||r&&(r==="__proto__"||r==="constructor"||r==="prototype")){b.warn(`[LiopServer] Rejected resetFieldBudget for unsafe clientId/toolName: ${e}`);return}if(r){let i=this.fieldQueryBudget.get(e);i&&i.delete(r);}else this.fieldQueryBudget.delete(e);let t=this.config?.budgetStorePath;if(t)try{this.executeWithBudgetLock(t,i=>(r?Object.hasOwn(i,e)&&i[e]&&delete i[e][r]:Object.hasOwn(i,e)&&delete i[e],{result:void 0,updatedBudget:i})),b.info(`[LiopServer] Reset query budget for client ${e}${r?` / tool ${r}`:""}`);}catch(i){b.error(`[LiopServer] Failed to reset persistent budget: ${i instanceof Error?i.message:String(i)}`);}}getPersistentBudget(e){try{if(!S.existsSync(e))return Object.create(null);let r=S.readFileSync(e,"utf-8"),t=JSON.parse(r||"{}");if(t&&typeof t=="object"){let i=Object.create(null);for(let[n,s]of Object.entries(t))n!=="__proto__"&&n!=="constructor"&&n!=="prototype"&&(i[n]=s);return i}return Object.create(null)}catch{return Object.create(null)}}savePersistentBudget(e,r){let t=`${e}.tmp`,i=L.dirname(e);S.existsSync(i)||S.mkdirSync(i,{recursive:true}),S.writeFileSync(t,JSON.stringify(r,null,2),"utf-8"),S.renameSync(t,e);}executeWithBudgetLock(e,r){let t=`${e}.lock`,i=100,s=0,o=L.dirname(e);if(!S.existsSync(o))try{S.mkdirSync(o,{recursive:!0});}catch{}for(;s<i;)try{S.writeFileSync(t,process.pid.toString(),{flag:"wx"});break}catch(a){if(a&&typeof a=="object"&&"code"in a&&a.code==="EEXIST"){s++;}else throw a}if(s>=i)throw new Error("Timeout acquiring lock for persistent query budget database");try{let a=this.getPersistentBudget(e),{result:c,updatedBudget:l}=r(a);return l&&this.savePersistentBudget(e,l),c}finally{try{S.existsSync(t)&&S.unlinkSync(t);}catch{}}}applyInMemoryBudget(e,r,t,i){let n=this.fieldQueryBudget.get(e);n||(n=new Map,this.fieldQueryBudget.set(e,n));let s=n.get(r);s||(s=new Map,n.set(r,s));for(let o of t){let a=this.taintAnalyzer.classifyField(o,i?.sensitiveKeys),c=25,l="public";if(i?.queryBudgetPerField!==void 0?(c=i.queryBudgetPerField,l="override"):a==="forbidden"?(c=3,l="forbidden"):a==="sensitive"&&(c=8,l="sensitive"),(s.get(o)??0)>=c)return `Preflight policy rejected: Query budget exceeded for field '${o}' (max ${c} per session for ${l} fields). Rotate PQC session to reset budget.`}for(let o of t){let a=s.get(o)??0;s.set(o,a+1);}return null}};
45
+ export{J as a,ve as b,Ee as c,ie as d,Se as e,H as f,q as g,be as h,X as i,R as j,Te as k,ee as l,Re as m};//# sourceMappingURL=chunk-CQ2VNVSP.js.map
46
+ //# sourceMappingURL=chunk-CQ2VNVSP.js.map
@@ -0,0 +1,57 @@
1
+ import {a}from'./chunk-AYDF3IFZ.js';import j from'crypto';import*as s from'fs/promises';import*as S from'os';import*as u from'path';import g from'vm';import {WASI}from'wasi';import*as A from'acorn';import {simple}from'acorn-walk';var y=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 y(`Banned WASI Import Detected: ${i.module}/${i.name}`)}else throw new y(`Banned Host Import Module Detected: ${i.module}`);if(t++,t>128)throw new y("Import limit exceeded. Possible resource exhaustion attack.")}}};var P=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:P.call(process,a,r,...t);function R(){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(R,"getDefaultEnvironment");function D(a){try{let r=A.parse(a,{ecmaVersion:"latest",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(D,"calculateAstInstructionFuel");var h=class{static{a(this,"WasiSandbox");}wasi;sandboxId;workingDir;config;stdoutHandle=null;stderrHandle=null;constructor(r={}){this.sandboxId=j.randomUUID(),this.workingDir=u.join(S.tmpdir(),"liop-mesh","sandboxes",this.sandboxId),this.config=r;}async init(){try{await s.mkdir(this.workingDir,{recursive:!0}),this.stdoutHandle=await s.open(u.join(this.workingDir,"stdout.log"),"w+"),this.stderrHandle=await s.open(u.join(this.workingDir,"stderr.log"),"w+"),this.wasi=new WASI({version:"preview1",args:["liop_runtime"],env:this.config.allowEnv?{...R(),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 b=await WebAssembly.instantiate(e,this.wasi.getImportObject());this.wasi.start(b);let p=u.join(this.workingDir,"stdout.log"),l=u.join(this.workingDir,"stderr.log"),d=await s.readFile(p,"utf-8"),c=await s.readFile(l,"utf-8"),O=performance.now()-i;return {output:d||(c?`Error: ${c}`:"WASM_EXECUTION_SUCCESS"),fuelConsumed:Math.max(100,Math.ceil(Math.floor(O*1e3)/100)*100)}}catch(e){throw new Error(`WASM Runtime Error: ${e instanceof Error?e.message:String(e)}`)}else {let e=Object.create(null),b={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 p=g.createContext(e,{name:"LIOP Isolate",origin:"liop://sandbox",microtaskMode:"afterEvaluate"});g.runInContext(`for (const proto of [
2
+ Object.getPrototypeOf(function(){}),
3
+ Object.getPrototypeOf(async function(){}),
4
+ Object.getPrototypeOf(function*(){})
5
+ ]) {
6
+ if (proto) {
7
+ try {
8
+ Object.defineProperty(proto, "constructor", {
9
+ value: undefined,
10
+ writable: false,
11
+ configurable: false,
12
+ });
13
+ Object.freeze(proto);
14
+ } catch (_) {}
15
+ }
16
+ }`,p);let l=g.runInContext(`(function(raw) {
17
+ const parsed = JSON.parse(raw);
18
+ function sanitize(val) {
19
+ if (!val || typeof val !== "object") return val;
20
+ if (Array.isArray(val)) return val.map(sanitize);
21
+ const clone = Object.create(null);
22
+ for (const [k, v] of Object.entries(val)) {
23
+ clone[k] = sanitize(v);
24
+ }
25
+ return clone;
26
+ }
27
+ return sanitize(parsed);
28
+ })`,p),d=a(n=>{if(n&&typeof n=="object"&&!Object.isFrozen(n)){Object.freeze(n);for(let m of Object.keys(n))d(n[m]);}return n},"deepFreeze");e.records=d(l(JSON.stringify(t))),e.env=d(l(JSON.stringify(b)));for(let[n,m]of Object.entries(o))e[n]=d(l(JSON.stringify(m)));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) {
29
+ ${c}
30
+ }`));let O=`
31
+ (function() {
32
+ "use strict";
33
+ try {
34
+ // Pre-execution prototype freezing (PCI-DSS Compliance)
35
+ Object.freeze(Object.prototype);
36
+ Object.freeze(Array.prototype);
37
+ Object.freeze(String.prototype);
38
+ Object.freeze(Number.prototype);
39
+ Object.freeze(Boolean.prototype);
40
+ Object.freeze(RegExp.prototype);
41
+ Object.freeze(Map.prototype);
42
+ Object.freeze(Set.prototype);
43
+ Object.freeze(Promise.prototype);
44
+ Object.freeze(Error.prototype);
45
+ Object.freeze(Object.getPrototypeOf(function(){}));
46
+
47
+ ${c}
48
+ if (typeof liop_main === 'function') {
49
+ return liop_main(env);
50
+ }
51
+ return "ERR_NO_ENTRY_POINT";
52
+ } catch(e) {
53
+ return "LogicError: " + e.message;
54
+ }
55
+ })();
56
+ `;try{let n=new g.Script(O,{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 m=n.runInContext(p,{timeout:5e3,breakOnSigint:!0,displayErrors:!0}),I=typeof r=="string"?r:r.toString("utf-8"),E=D(I);if(E>1e6)throw new Error("LIOP_RESOURCE_EXHAUSTED: Execution fuel limit exceeded.");return {output:m,fuelConsumed:E}}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{}}};export{w as a,R as b,D as c,h as d};//# sourceMappingURL=chunk-HLAQ3HVD.js.map
57
+ //# sourceMappingURL=chunk-HLAQ3HVD.js.map
@@ -0,0 +1,15 @@
1
+ import {a as a$1}from'./chunk-AN5NODTN.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 x(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(x,"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 _(c=m.STATUS_OK,e="",t={}){let o=[`grpc-status:${c}`,`grpc-message:${encodeURIComponent(e)}`];for(let[n,s]of Object.entries(t))o.push(`${n}:${s}`);let i=`${o.join(`\r
2
+ `)}\r
3
+ `,r=Buffer.from(i,"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(_,"encodeTrailerFrame");function $(c){let e=[],t=0;for(;t+m.HEADER_LENGTH<=c.length;){let o=c.readUInt8(t),i=c.readUInt32BE(t+1),r=t+m.HEADER_LENGTH,a=r+i;if(a>c.length)break;let n=c.subarray(r,a);e.push({isTrailer:(o&m.FLAG_TRAILERS)===m.FLAG_TRAILERS,payload:Buffer.from(n)}),t=a;}return e}a($,"decodeFrames");async function G(c,e,t){let o=[];c.on("data",i=>{o.push(i);}),c.on("end",async()=>{try{let i=Buffer.concat(o),a=$(i).find(p=>!p.isTrailer)?.payload??Buffer.alloc(0),n=c.url||"/";b.info(`[gRPC-Web] Handling request for ${n} (${a.length} bytes)`);let s=await t(n,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(_(s.status,s.message||"")),e.end();}catch(i){b.error(`[gRPC-Web] Dispatch error: ${i}`),e.statusCode=200,e.setHeader("content-type","application/grpc-web+proto"),e.write(_(m.STATUS_INTERNAL,i.message||"Internal server error")),e.end();}});}a(G,"dispatchGrpcWebRequest");var k=2500;async function I(c,e,t){let o=t.timeoutMs??k,i=t.failMode??"closed",r=AbortSignal.timeout(o),a$1=Object.freeze(structuredClone(c)),n,s=new Promise((p,u)=>{n=a(()=>u(r.reason),"onAbortListener"),r.addEventListener("abort",n,{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 i==="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{n&&r.removeEventListener("abort",n);}}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,i,r){this.liopServer=e;this.meshNode=t;this.jwtValidator=this.liopServer.jwtValidator,this.oauthProvider=this.liopServer.oauthProvider,this.rateLimiter=new w(i),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",n=>{let s=n.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(n);}),a.on("error",n=>b.error(`[LIOP-Gateway] NetServer Socket Error: ${n.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"],i=t[":path"];o==="application/grpc"?this.handleGrpcStream(e):i==="/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 i$1=e$1.url||"",r=e$1.method;if(r==="GET"&&i$1==="/metrics"){let n=process.env.LIOP_METRICS_TOKEN;if(n&&e$1.headers.authorization!==`Bearer ${n}`){t.writeHead(401,{"Content-Type":"application/json; charset=utf-8"}),t.end(JSON.stringify({error:"Unauthorized: Invalid metrics token"}));return}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"&&i$1==="/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"&&i$1==="/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&&i$1==="/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(x(a$1)){await G(e$1,t,async(n,s)=>(b.info(`[LIOP-Gateway] gRPC-Web fallback call: ${n} (${s.length} bytes)`),{status:m.STATUS_OK,message:"OK",data:Buffer.from("")}));return}if(i$1.startsWith("/oidc")&&this.oauthProvider){let n=typeof this.oauthProvider.callback=="function"?this.oauthProvider.callback():this.oauthProvider,s=e$1.url;e$1.url=(s||"").slice(5)||"/";try{return n(e$1,t)}finally{e$1.url=s;}}if(r==="GET"&&i$1==="/.well-known/oauth-protected-resource"){if(this.jwtValidator){let n=A(this.jwtValidator.getIssuer(),this.jwtValidator.getAudience());t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(n));return}t.writeHead(404),t.end("Not Found");return}if(r==="GET"&&(i$1==="/"||i$1==="/mcp"||i$1==="/health")){if(i$1==="/health"&&e$1.headers.accept?.includes("application/json")){let n=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:n,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 &harr; 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(i$1==="/mcp"&&r==="POST"){let n=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{n=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=n?.clientId?`client:${n.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:n,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,n);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",i=>o+=i.toString()),e.on("end",async()=>{try{let i=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{i=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:i,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"],n=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(n&&r.params?.name&&n!==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 (${n}) 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,i);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 i of o)await this.meshNode.announceCapability(i.name),b.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${i.name}`);}return new Promise((o,i)=>{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}`),i(r);}),this.netServer.listen(e,t,()=>{let r=this.netServer.address(),a=typeof r=="string"?r:r?.address||t,n=typeof r=="string"?e:r?.port||e;b.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${a}:${n}`),o(n);});})}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,x as b,D as c,_ as d,$ as e,G as f,A as g,I as h,w as i,M as j};//# sourceMappingURL=chunk-LZIEMSYZ.js.map
15
+ //# sourceMappingURL=chunk-LZIEMSYZ.js.map
@@ -1,3 +1,3 @@
1
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
2
+ `);}catch(r){b.error(`[LIOP-Bridge] Error: ${r.message}`);}});}getServer(){return this.liopServer}};export{g as a,d as b};//# sourceMappingURL=chunk-YMR3PMO3.js.map
3
+ //# sourceMappingURL=chunk-YMR3PMO3.js.map
package/dist/gateway.js CHANGED
@@ -1,2 +1,2 @@
1
- export{j as LiopHybridGateway}from'./chunk-LEXMMIQI.js';import'./chunk-LM26HOJ6.js';import'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';import'./chunk-Y675R34Z.js';import'./chunk-XLVEDKM6.js';import'./chunk-2ZYX736J.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=gateway.js.map
1
+ export{j as LiopHybridGateway}from'./chunk-LZIEMSYZ.js';import'./chunk-AN5NODTN.js';import'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';import'./chunk-Y675R34Z.js';import'./chunk-XLVEDKM6.js';import'./chunk-2ZYX736J.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=gateway.js.map
2
2
  //# sourceMappingURL=gateway.js.map
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export{d as WasiSandbox,c as calculateAstInstructionFuel,b as getDefaultEnvironment}from'./chunk-CTTTLCGL.js';export{a as VERIFICATION_LATENCY_BUDGET_MS,f as deserializeGrothProof,d as deserializeVKey,e as serializeGrothProof,c as serializeVKey,b as verifyGroth16Proof}from'./chunk-FDJMH4CB.js';export{b as AesGcmWrapper,c as LiopClient,a as LiopRpcClient}from'./chunk-WP5ER7RH.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-P6IJ3VBD.js';export{a as GRPC_WEB_CONSTANTS,i as InMemoryRateLimiter,j as LiopHybridGateway,g as buildProtectedResourceMetadata,e as decodeFrames,f as dispatchGrpcWebRequest,c as encodeDataFrame,d as encodeTrailerFrame,h as executeGatewayInterceptor,b as isGrpcWebRequest}from'./chunk-LEXMMIQI.js';export{a as RoutingTable,b as probeTopology}from'./chunk-2XHSALII.js';export{a as TokenManager}from'./chunk-N35BC62H.js';export{f as AUTH_DEFAULTS,d as AuditLogger,b as GENESIS_HASH,g as JwtValidator,a as LiopRpcServer,m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner,c as computeEntryHash,h as createOAuthServer,e as globalAuditLogger}from'./chunk-YD2AF2M6.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';export{a as LiopMcpRouter}from'./chunk-LM26HOJ6.js';export{a as LiopVerifier}from'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';export{a as Kyber768Wrapper}from'./chunk-Y675R34Z.js';export{b as LIOP_SCOPES,a as authorizeRequest}from'./chunk-XLVEDKM6.js';export{a as DILITHIUM65_CONSTANTS,b as Dilithium65Wrapper}from'./chunk-2ZYX736J.js';export{j as GRPC_CHANNEL_OPTIONS,b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,i as createChannelCredentials,h as createServerCredentials,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-ECRS6N33.js';export{a as Counter,b as Gauge,c as Histogram,d as MetricsRegistry,k as egressBlocksTotal,h as fuelConsumed,j as manifestCacheSize,i as meshPeersConnected,t as operationDurationMs,u as pqcHandshakeDurationMs,v as pqcHandshakesTotal,e as protocolMetrics,q as tokensInputTotal,r as tokensOutputTotal,s as tokensSavedTotal,g as toolCallErrorsTotal,f as toolCallsTotal,w as wireEgressBytesTotal,x as wireSavedBytesTotal,n as zkProofsByTypeTotal,o as zkProvingDurationMs,l as zkVerificationDurationMs,m as zkVerificationsTotal,p as zkVkeyCacheSize}from'./chunk-ZZMSFCJP.js';export{a as MCP_LEGACY_SUPPORT_ENABLED,h as MCP_PROTOCOL_VERSION,b as MCP_PROTOCOL_VERSION_LEGACY,k as PromptSchema,j as ResourceSchema,i as ToolSchema}from'./chunk-GWVSCZUS.js';export{a as ProofType,b as RECEIPT_VERSION_V1,c as RECEIPT_VERSION_V2,d as ZK_JOURNAL_V2_SIZE,e as ZkVerificationError,i as ZkVerifier,g as decodeJournalV2,f as encodeJournalV2,h as receiptCodec}from'./chunk-6VK2XALI.js';export{a as SWARM_KEY_BYTE_LENGTH,b as createSwarmKey,d as deserializeSwarmKey,g as loadSwarmKey,e as parseSwarmKey,f as saveSwarmKey,c as serializeSwarmKey}from'./chunk-YLCNV764.js';export{a as MeshNode}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';export{a as LiopLogger,b as log}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as h from'crypto';import {EventEmitter}from'events';import*as i from'fs';var A=(o=>(o.CapabilityViolation="CapabilityViolation",o.SandboxEscape="SandboxEscape",o.PiiLeak="PiiLeak",o.InvalidIntent="InvalidIntent",o.Throttled="Throttled",o.ZkVerificationFailed="ZkVerificationFailed",o.MeshUnavailable="MeshUnavailable",o.ConnectionFailed="ConnectionFailed",o))(A||{}),y=class extends Error{static{a(this,"LiopError");}code;constructor(t,e){super(e),this.name="LiopError",this.code=t;}};var D=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,g=class n{static{a(this,"LiopTracer");}static generateTraceId(){let t;do t=h.randomBytes(16).toString("hex");while(t==="0".repeat(32));return t}static generateSpanId(){let t;do t=h.randomBytes(8).toString("hex");while(t==="0".repeat(16));return t}static formatTraceparent(t,e,r=true){return `00-${t}-${e}-${r?"01":"00"}`}static parseTraceparent(t){if(!t||typeof t!="string")return null;let e=t.trim(),r=D.exec(e);if(!r)return null;let[,a,c,l,m]=r;if(a==="00"&&(c==="0".repeat(32)||l==="0".repeat(16)))return null;let o=(Number.parseInt(m,16)&1)===1;return {traceId:c,spanId:l,sampled:o}}static injectTraceparent(t,e){t.traceparent=n.formatTraceparent(e.traceId,e.spanId,e.sampled);}static extractTraceparent(t){let e=t.traceparent||t.Traceparent;return Array.isArray(e)?n.parseTraceparent(e[0]):n.parseTraceparent(e)}startSpan(t,e,r={}){let a=e?.traceId||n.generateTraceId(),c=n.generateSpanId(),l=e?e.sampled:true;return {name:t,context:{traceId:a,spanId:c,sampled:l},startTime:Date.now(),attributes:{...r},status:"OK",setAttribute(d,T){return this.attributes[d]=T,this},recordException(d){return this.status="ERROR",this.error=typeof d=="string"?d:d.message,this},end(){this.endTime=Date.now();}}}},Mt=new g;var k={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function Bt(n){let t=k[n],e=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
1
+ export{d as WasiSandbox,c as calculateAstInstructionFuel,b as getDefaultEnvironment}from'./chunk-HLAQ3HVD.js';export{a as VERIFICATION_LATENCY_BUDGET_MS,f as deserializeGrothProof,d as deserializeVKey,e as serializeGrothProof,c as serializeVKey,b as verifyGroth16Proof}from'./chunk-FDJMH4CB.js';export{b as AesGcmWrapper,c as LiopClient,a as LiopRpcClient}from'./chunk-WP5ER7RH.js';export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-YMR3PMO3.js';export{a as GRPC_WEB_CONSTANTS,i as InMemoryRateLimiter,j as LiopHybridGateway,g as buildProtectedResourceMetadata,e as decodeFrames,f as dispatchGrpcWebRequest,c as encodeDataFrame,d as encodeTrailerFrame,h as executeGatewayInterceptor,b as isGrpcWebRequest}from'./chunk-LZIEMSYZ.js';export{a as RoutingTable,b as probeTopology}from'./chunk-2XHSALII.js';export{a as TokenManager}from'./chunk-N35BC62H.js';export{f as AUTH_DEFAULTS,d as AuditLogger,b as GENESIS_HASH,g as JwtValidator,a as LiopRpcServer,m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner,c as computeEntryHash,h as createOAuthServer,e as globalAuditLogger}from'./chunk-CQ2VNVSP.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';export{a as LiopMcpRouter}from'./chunk-AN5NODTN.js';export{a as LiopVerifier}from'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';export{a as Kyber768Wrapper}from'./chunk-Y675R34Z.js';export{b as LIOP_SCOPES,a as authorizeRequest}from'./chunk-XLVEDKM6.js';export{a as DILITHIUM65_CONSTANTS,b as Dilithium65Wrapper}from'./chunk-2ZYX736J.js';export{j as GRPC_CHANNEL_OPTIONS,b as HeuristicTokenEstimator,e as LiopOTelBridge,a as RealTokenEstimator,f as TokenTelemetryEngine,i as createChannelCredentials,h as createServerCredentials,d as createSyncTokenEstimator,c as createTokenEstimator}from'./chunk-ECRS6N33.js';export{a as Counter,b as Gauge,c as Histogram,d as MetricsRegistry,k as egressBlocksTotal,h as fuelConsumed,j as manifestCacheSize,i as meshPeersConnected,t as operationDurationMs,u as pqcHandshakeDurationMs,v as pqcHandshakesTotal,e as protocolMetrics,q as tokensInputTotal,r as tokensOutputTotal,s as tokensSavedTotal,g as toolCallErrorsTotal,f as toolCallsTotal,w as wireEgressBytesTotal,x as wireSavedBytesTotal,n as zkProofsByTypeTotal,o as zkProvingDurationMs,l as zkVerificationDurationMs,m as zkVerificationsTotal,p as zkVkeyCacheSize}from'./chunk-ZZMSFCJP.js';export{a as MCP_LEGACY_SUPPORT_ENABLED,h as MCP_PROTOCOL_VERSION,b as MCP_PROTOCOL_VERSION_LEGACY,k as PromptSchema,j as ResourceSchema,i as ToolSchema}from'./chunk-GWVSCZUS.js';export{a as ProofType,b as RECEIPT_VERSION_V1,c as RECEIPT_VERSION_V2,d as ZK_JOURNAL_V2_SIZE,e as ZkVerificationError,i as ZkVerifier,g as decodeJournalV2,f as encodeJournalV2,h as receiptCodec}from'./chunk-6VK2XALI.js';export{a as SWARM_KEY_BYTE_LENGTH,b as createSwarmKey,d as deserializeSwarmKey,g as loadSwarmKey,e as parseSwarmKey,f as saveSwarmKey,c as serializeSwarmKey}from'./chunk-YLCNV764.js';export{a as MeshNode}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';export{a as LiopLogger,b as log}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as h from'crypto';import {EventEmitter}from'events';import*as i from'fs';var A=(o=>(o.CapabilityViolation="CapabilityViolation",o.SandboxEscape="SandboxEscape",o.PiiLeak="PiiLeak",o.InvalidIntent="InvalidIntent",o.Throttled="Throttled",o.ZkVerificationFailed="ZkVerificationFailed",o.MeshUnavailable="MeshUnavailable",o.ConnectionFailed="ConnectionFailed",o))(A||{}),y=class extends Error{static{a(this,"LiopError");}code;constructor(t,e){super(e),this.name="LiopError",this.code=t;}};var D=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,g=class n{static{a(this,"LiopTracer");}static generateTraceId(){let t;do t=h.randomBytes(16).toString("hex");while(t==="0".repeat(32));return t}static generateSpanId(){let t;do t=h.randomBytes(8).toString("hex");while(t==="0".repeat(16));return t}static formatTraceparent(t,e,r=true){return `00-${t}-${e}-${r?"01":"00"}`}static parseTraceparent(t){if(!t||typeof t!="string")return null;let e=t.trim(),r=D.exec(e);if(!r)return null;let[,a,c,l,m]=r;if(a==="00"&&(c==="0".repeat(32)||l==="0".repeat(16)))return null;let o=(Number.parseInt(m,16)&1)===1;return {traceId:c,spanId:l,sampled:o}}static injectTraceparent(t,e){t.traceparent=n.formatTraceparent(e.traceId,e.spanId,e.sampled);}static extractTraceparent(t){let e=t.traceparent||t.Traceparent;return Array.isArray(e)?n.parseTraceparent(e[0]):n.parseTraceparent(e)}startSpan(t,e,r={}){let a=e?.traceId||n.generateTraceId(),c=n.generateSpanId(),l=e?e.sampled:true;return {name:t,context:{traceId:a,spanId:c,sampled:l},startTime:Date.now(),attributes:{...r},status:"OK",setAttribute(d,T){return this.attributes[d]=T,this},recordException(d){return this.status="ERROR",this.error=typeof d=="string"?d:d.message,this},end(){this.endTime=Date.now();}}}},Mt=new g;var k={claude:{xmlStandard:true,jsonSchemaPreferred:false},openai:{xmlStandard:false,jsonSchemaPreferred:true},gemini:{xmlStandard:false,jsonSchemaPreferred:true}};function Bt(n){let t=k[n],e=`[LIOP-PROTO-V1: LOGIC-ON-ORIGIN SPECIFICATION]
2
2
  You are interacting with a Logic-Injection-on-Origin Protocol (LIOP) Mesh Network.
3
3
  Unlike standard MCP where you pull context to evaluate it remotely, in LIOP you WRITE code that executes on the data's origin.
4
4
 
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- export{m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner}from'./chunk-YD2AF2M6.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';import'./chunk-XLVEDKM6.js';import'./chunk-2ZYX736J.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-6VK2XALI.js';import'./chunk-V35CXJQN.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=server.js.map
1
+ export{m as LiopServer,i as NerScanner,j as PII_PATTERNS,k as PII_PRESETS,l as PiiScanner}from'./chunk-CQ2VNVSP.js';export{a as sanitizeOutput}from'./chunk-MQ5SU26J.js';import'./chunk-XLVEDKM6.js';import'./chunk-2ZYX736J.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-6VK2XALI.js';import'./chunk-V35CXJQN.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=server.js.map
2
2
  //# sourceMappingURL=server.js.map
@@ -1,2 +1,2 @@
1
- import {a as a$1,d}from'../chunk-CTTTLCGL.js';import {a as a$3}from'../chunk-MQ5SU26J.js';import {a as a$2,b}from'../chunk-TKLRW52V.js';import {b as b$1}from'../chunk-2ZYX736J.js';import {f,h}from'../chunk-6VK2XALI.js';import {a}from'../chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import m from'crypto';import {createMlKem768}from'mlkem';var Y={epsilon:1,sensitivity:1,smallDatasetThreshold:50},J=1,ee=10;function te(e,i){let o;do if(i)o=m.createHash("sha256").update(`${i.seed}:${i.counter++}`).digest().readUInt32BE(0)/4294967296-.5;else {let t=m.randomBytes(4),a=t[0]<<24|t[1]<<16|t[2]<<8|t[3];o=Number.parseInt(a.toString(10),10)/4294967296;}while(o===0||o===-0.5);return -e*Math.sign(o)*Math.log(1-2*Math.abs(o))}a(te,"laplaceSample");function re(e,i={},o){let t={...Y,...i},a=t.sensitivity/t.epsilon,c=e+te(a,o);return Math.round(c*1e4)/1e4}a(re,"addLaplaceNoise");function $(e,i,o){if(!e)return i;let t=e.toLowerCase(),a=/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(t),c=t==="total"||t==="n"||t==="total_records"||t.startsWith("total_")||t.startsWith("num_")||/total.*(count|items|entries|rows|records|tickers)/i.test(t);return a||c?1:/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(t)&&o>0?i/o:i}a($,"deriveFieldSensitivity");function Z(e,i={},o){let t={...Y,...i};if(o>=t.smallDatasetThreshold)return e;o<ee&&t.epsilon<J&&(t.epsilon=J);let a;return t.seed&&(a={seed:t.seed,counter:0}),R(e,t,o,void 0,a)}a(Z,"applyDpToOutput");function R(e,i,o,t,a){if(typeof e=="number"&&Number.isFinite(e)){let c=$(t,i.sensitivity,o),u=re(e,{...i,sensitivity:c},a),w=t!=null&&$(t,i.sensitivity,o)===1;return (Number.isInteger(e)||w)&&(u=Math.round(u)),e>=0&&(u=Math.max(0,u)),u}if(Array.isArray(e))return e.map(c=>R(c,i,o,t,a));if(e!==null&&typeof e=="object"){let c={};for(let[u,w]of Object.entries(e))c[u]=R(w,i,o,u,a);return c}return e}a(R,"walkAndNoise");async function oe(e){if(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)),e.isWarmup)return {image_id:"",output:"warm",fuel_consumed:0};if(e.sessionTimestamp!==void 0){let n=Date.now()-e.sessionTimestamp;if(n>36e5)throw new Error(`[LIOP-PQC] Session secret expired: Age (${Math.round(n/1e3)}s) exceeds 3600s TTL limit.`);if(e.sessionTimestamp>Date.now()+6e4)throw new Error("[LIOP-PQC] Session secret invalid: Timestamp is in the future.")}let{ciphertext:i,secretKeyObj:o,wasmBinary:t,inputs:a,aesNonce:c,records:u,isEncrypted:w=true,dpConfig:z}=e,s,D={},C=Buffer.alloc(32);if(w){let p=new Uint8Array(o),n=new Uint8Array(i),g=(await createMlKem768()).decap(n,p),d=Buffer.from(g);C=d;let _=Buffer.from(t),k=_.subarray(-16),T=_.subarray(0,-16),A=m.createDecipheriv("aes-256-gcm",d,Buffer.from(c||new Uint8Array(12)));A.setAuthTag(k);let S=A.update(T);S=Buffer.concat([S,A.final()]),s=S;for(let[E,B]of Object.entries(a||{})){let y=Buffer.from(B),f=y.subarray(0,12),h=y.subarray(-16),x=y.subarray(12,-16),O=m.createDecipheriv("aes-256-gcm",d,f);O.setAuthTag(h);let v=O.update(x);v=Buffer.concat([v,O.final()]),D[E]=JSON.parse(v.toString("utf-8"));}}else t[0]===0&&t[1]===97&&t[2]===115&&t[3]===109?s=Buffer.from(t):s=Buffer.from(t).toString("utf-8");let K=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&K){let p=new Uint8Array(s),n=await WebAssembly.compile(p);a$1.analyze(n);}else s instanceof Buffer&&!K&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$2(s));let N=new d;await N.init();try{let p=await N.execute(s,u,D),n=p.output,I;typeof s=="string"?I=Buffer.from(s,"utf-8"):I=new Uint8Array(s);let g=b(I).toString("hex"),d=m.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");if(z&&(n=Z(n,{...z,seed:`${d}:${g}`},u?.length||0)),n=a$3(n),e.proofMode===1||e.proofMode===2){let E=e.guestImageId?Buffer.from(e.guestImageId,"hex"):m.createHash("sha256").update("liop-default-guest-v2").digest(),B=typeof n=="string"?n:n===void 0?"undefined":JSON.stringify(n),y=f({guestImageId:E,logicDigest:Buffer.from(g,"hex"),datasetDigest:Buffer.from(d,"hex"),outputDigest:m.createHash("sha256").update(B).digest(),fuelConsumed:BigInt(p.fuelConsumed),executionTimestamp:BigInt(Date.now())}),f$1,h$1=null;try{h$1=await import('@nekzus/liop-zk-native');}catch{h$1=null;}if(h$1&&typeof h$1.prove_analytical_query=="function")try{let b=typeof D?.operation=="string"?D.operation:"sum",M=JSON.stringify({records:Array.isArray(u)?u.map(P=>Number(P.amount??P.value??1)):[1],expected_sum:typeof n=="number"?n:void 0});f$1=await h$1.prove_analytical_query(b,M);}catch(b){if(e.proofMode===2)throw new Error(`ZK PROOF GENERATION FAILED: Native Groth16 prover execution error: ${b instanceof Error?b.message:String(b)}`);f$1=Buffer.alloc(128,66);}else {if(e.proofMode===2)throw new Error("ZK PROOF GENERATION FAILED: Native Groth16 prover module unavailable for required policy.");f$1=Buffer.alloc(128,66);}let x,O=2;if(e.pqcSigningKey&&e.pqcSigningKey.length>0){O=3;let b=m.createHash("sha256").update(Buffer.concat([y,f$1])).digest(),M=b$1.sign(b,e.pqcSigningKey),P=b$1.getPublicKey(e.pqcSigningKey);x=h.encodeHybridV2(y,f$1,Buffer.from(M),Buffer.from(P));}else x=h.encodeV2(2,y,f$1);let v=x.toString("base64");return {image_id:g,zk_receipt:v,output:n,fuel_consumed:p.fuelConsumed,proof_type:O,guest_image_id:E.toString("hex")}}let _=Buffer.from(JSON.stringify({image_id:g,dataset_hash:d,output_hash:m.createHash("sha256").update(typeof n=="string"?n:n===void 0?"undefined":JSON.stringify(n)).digest("hex"),fuel:p.fuelConsumed,ts:Date.now()})),k=m.createHmac("sha256",C).update(_).digest(),T=Buffer.alloc(2);T.writeUInt16BE(_.length);let S=Buffer.concat([Buffer.from([1]),T,_,k]).toString("base64");return {image_id:g,zk_receipt:S,output:n,fuel_consumed:p.fuelConsumed,proof_type:0}}finally{await N.teardown();}}a(oe,"processLogicExecution");export{oe as default};//# sourceMappingURL=logic-execution.js.map
1
+ import {a as a$1,d}from'../chunk-HLAQ3HVD.js';import {a as a$3}from'../chunk-MQ5SU26J.js';import {a as a$2,b}from'../chunk-TKLRW52V.js';import {b as b$1}from'../chunk-2ZYX736J.js';import {f,h}from'../chunk-6VK2XALI.js';import {a}from'../chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import m from'crypto';import {createMlKem768}from'mlkem';var Y={epsilon:1,sensitivity:1,smallDatasetThreshold:50},J=1,ee=10;function te(e,i){let o;do if(i)o=m.createHash("sha256").update(`${i.seed}:${i.counter++}`).digest().readUInt32BE(0)/4294967296-.5;else {let t=m.randomBytes(4),a=t[0]<<24|t[1]<<16|t[2]<<8|t[3];o=Number.parseInt(a.toString(10),10)/4294967296;}while(o===0||o===-0.5);return -e*Math.sign(o)*Math.log(1-2*Math.abs(o))}a(te,"laplaceSample");function re(e,i={},o){let t={...Y,...i},a=t.sensitivity/t.epsilon,c=e+te(a,o);return Math.round(c*1e4)/1e4}a(re,"addLaplaceNoise");function $(e,i,o){if(!e)return i;let t=e.toLowerCase(),a=/count|length|size|num|gainer|loser|positive|negative|nan_|null_|empty_|finite_|non_finite_|instruments|tickers|users|records/i.test(t),c=t==="total"||t==="n"||t==="total_records"||t.startsWith("total_")||t.startsWith("num_")||/total.*(count|items|entries|rows|records|tickers)/i.test(t);return a||c?1:/avg|mean|average|var|variance|std|stddev|ratio|bps|drift|pct|percent|imbalance/i.test(t)&&o>0?i/o:i}a($,"deriveFieldSensitivity");function Z(e,i={},o){let t={...Y,...i};if(o>=t.smallDatasetThreshold)return e;o<ee&&t.epsilon<J&&(t.epsilon=J);let a;return t.seed&&(a={seed:t.seed,counter:0}),R(e,t,o,void 0,a)}a(Z,"applyDpToOutput");function R(e,i,o,t,a){if(typeof e=="number"&&Number.isFinite(e)){let c=$(t,i.sensitivity,o),u=re(e,{...i,sensitivity:c},a),w=t!=null&&$(t,i.sensitivity,o)===1;return (Number.isInteger(e)||w)&&(u=Math.round(u)),e>=0&&(u=Math.max(0,u)),u}if(Array.isArray(e))return e.map(c=>R(c,i,o,t,a));if(e!==null&&typeof e=="object"){let c={};for(let[u,w]of Object.entries(e))c[u]=R(w,i,o,u,a);return c}return e}a(R,"walkAndNoise");async function oe(e){if(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)),e.isWarmup)return {image_id:"",output:"warm",fuel_consumed:0};if(e.sessionTimestamp!==void 0){let n=Date.now()-e.sessionTimestamp;if(n>36e5)throw new Error(`[LIOP-PQC] Session secret expired: Age (${Math.round(n/1e3)}s) exceeds 3600s TTL limit.`);if(e.sessionTimestamp>Date.now()+6e4)throw new Error("[LIOP-PQC] Session secret invalid: Timestamp is in the future.")}let{ciphertext:i,secretKeyObj:o,wasmBinary:t,inputs:a,aesNonce:c,records:u,isEncrypted:w=true,dpConfig:z}=e,s,D={},C=Buffer.alloc(32);if(w){let p=new Uint8Array(o),n=new Uint8Array(i),g=(await createMlKem768()).decap(n,p),d=Buffer.from(g);C=d;let _=Buffer.from(t),k=_.subarray(-16),T=_.subarray(0,-16),A=m.createDecipheriv("aes-256-gcm",d,Buffer.from(c||new Uint8Array(12)));A.setAuthTag(k);let S=A.update(T);S=Buffer.concat([S,A.final()]),s=S;for(let[E,B]of Object.entries(a||{})){let y=Buffer.from(B),f=y.subarray(0,12),h=y.subarray(-16),x=y.subarray(12,-16),O=m.createDecipheriv("aes-256-gcm",d,f);O.setAuthTag(h);let v=O.update(x);v=Buffer.concat([v,O.final()]),D[E]=JSON.parse(v.toString("utf-8"));}}else t[0]===0&&t[1]===97&&t[2]===115&&t[3]===109?s=Buffer.from(t):s=Buffer.from(t).toString("utf-8");let K=s[0]===0&&s[1]===97&&s[2]===115&&s[3]===109;if(s instanceof Buffer&&K){let p=new Uint8Array(s),n=await WebAssembly.compile(p);a$1.analyze(n);}else s instanceof Buffer&&!K&&(s=s.toString("utf-8"));typeof s=="string"&&(s=a$2(s));let N=new d;await N.init();try{let p=await N.execute(s,u,D),n=p.output,I;typeof s=="string"?I=Buffer.from(s,"utf-8"):I=new Uint8Array(s);let g=b(I).toString("hex"),d=m.createHash("sha256").update(JSON.stringify(u||[])).digest("hex");if(z&&(n=Z(n,{...z,seed:`${d}:${g}`},u?.length||0)),n=a$3(n),e.proofMode===1||e.proofMode===2){let E=e.guestImageId?Buffer.from(e.guestImageId,"hex"):m.createHash("sha256").update("liop-default-guest-v2").digest(),B=typeof n=="string"?n:n===void 0?"undefined":JSON.stringify(n),y=f({guestImageId:E,logicDigest:Buffer.from(g,"hex"),datasetDigest:Buffer.from(d,"hex"),outputDigest:m.createHash("sha256").update(B).digest(),fuelConsumed:BigInt(p.fuelConsumed),executionTimestamp:BigInt(Date.now())}),f$1,h$1=null;try{h$1=await import('@nekzus/liop-zk-native');}catch{h$1=null;}if(h$1&&typeof h$1.prove_analytical_query=="function")try{let b=typeof D?.operation=="string"?D.operation:"sum",M=JSON.stringify({records:Array.isArray(u)?u.map(P=>Number(P.amount??P.value??1)):[1],expected_sum:typeof n=="number"?n:void 0});f$1=await h$1.prove_analytical_query(b,M);}catch(b){if(e.proofMode===2)throw new Error(`ZK PROOF GENERATION FAILED: Native Groth16 prover execution error: ${b instanceof Error?b.message:String(b)}`);f$1=Buffer.alloc(128,66);}else {if(e.proofMode===2)throw new Error("ZK PROOF GENERATION FAILED: Native Groth16 prover module unavailable for required policy.");f$1=Buffer.alloc(128,66);}let x,O=2;if(e.pqcSigningKey&&e.pqcSigningKey.length>0){O=3;let b=m.createHash("sha256").update(Buffer.concat([y,f$1])).digest(),M=b$1.sign(b,e.pqcSigningKey),P=b$1.getPublicKey(e.pqcSigningKey);x=h.encodeHybridV2(y,f$1,Buffer.from(M),Buffer.from(P));}else x=h.encodeV2(2,y,f$1);let v=x.toString("base64");return {image_id:g,zk_receipt:v,output:n,fuel_consumed:p.fuelConsumed,proof_type:O,guest_image_id:E.toString("hex")}}let _=Buffer.from(JSON.stringify({image_id:g,dataset_hash:d,output_hash:m.createHash("sha256").update(typeof n=="string"?n:n===void 0?"undefined":JSON.stringify(n)).digest("hex"),fuel:p.fuelConsumed,ts:Date.now()})),k=m.createHmac("sha256",C).update(_).digest(),T=Buffer.alloc(2);T.writeUInt16BE(_.length);let S=Buffer.concat([Buffer.from([1]),T,_,k]).toString("base64");return {image_id:g,zk_receipt:S,output:n,fuel_consumed:p.fuelConsumed,proof_type:0}}finally{await N.teardown();}}a(oe,"processLogicExecution");export{oe as default};//# sourceMappingURL=logic-execution.js.map
2
2
  //# sourceMappingURL=logic-execution.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nekzus/liop",
3
- "version": "2.4.0-alpha.26",
3
+ "version": "2.4.0-alpha.28",
4
4
  "description": "Official SDK for Logic-Injection-on-Origin Protocol (LIOP). Deploy Logic-on-Origin with WebAssembly at gRPC speed and bidirectional MCP compatibility.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -101,7 +101,7 @@
101
101
  "dependencies": {
102
102
  "@chainsafe/libp2p-noise": "17.0.0",
103
103
  "@chainsafe/libp2p-yamux": "8.0.1",
104
- "@grpc/grpc-js": "1.14.4",
104
+ "@grpc/grpc-js": "1.14.5",
105
105
  "@grpc/proto-loader": "0.8.1",
106
106
  "@hono/node-server": "2.1.1",
107
107
  "@libp2p/autonat": "^3.0.27",
@@ -151,50 +151,6 @@
151
151
  "optional": true
152
152
  }
153
153
  },
154
- "overrides": {
155
- "content-type": "1.0.5",
156
- "protobufjs": "^7.6.1",
157
- "piscina": "5.3.2",
158
- "ws": "^8.21.0",
159
- "hono": "4.13.8",
160
- "fast-uri": "^3.1.5",
161
- "brace-expansion": "^1.1.18",
162
- "ip-address": "^10.3.1",
163
- "js-yaml": "^4.3.1",
164
- "nanoid": "^3.3.18",
165
- "postcss": "^8.5.18",
166
- "type-is": "2.0.1",
167
- "uint8arrays": "6.1.1",
168
- "aggregate-error": "npm:@socketregistry/aggregate-error@^1",
169
- "array-buffer-byte-length": "npm:@socketregistry/array-buffer-byte-length@^1",
170
- "deep-equal": "npm:@socketregistry/deep-equal@^1",
171
- "es-define-property": "npm:@socketregistry/es-define-property@^1",
172
- "es-get-iterator": "npm:@socketregistry/es-get-iterator@^1",
173
- "function-bind": "npm:@socketregistry/function-bind@^1",
174
- "gopd": "npm:@socketregistry/gopd@^1",
175
- "has-symbols": "npm:@socketregistry/has-symbols@^1",
176
- "hasown": "npm:@socketregistry/hasown@^1",
177
- "indent-string": "npm:@socketregistry/indent-string@^1",
178
- "is-arguments": "npm:@socketregistry/is-arguments@^1",
179
- "is-array-buffer": "npm:@socketregistry/is-array-buffer@^1",
180
- "is-date-object": "npm:@socketregistry/is-date-object@^1",
181
- "is-interactive": "npm:@socketregistry/is-interactive@^1",
182
- "is-regex": "npm:@socketregistry/is-regex@^1",
183
- "is-shared-array-buffer": "npm:@socketregistry/is-shared-array-buffer@^1",
184
- "is-unicode-supported": "npm:@socketregistry/is-unicode-supported@^1",
185
- "isarray": "npm:@socketregistry/isarray@^1",
186
- "object-assign": "npm:@socketregistry/object-assign@^1",
187
- "object-is": "npm:@socketregistry/object-is@^1",
188
- "object-keys": "npm:@socketregistry/object-keys@^1",
189
- "object.assign": "npm:@socketregistry/object.assign@^1",
190
- "regexp.prototype.flags": "npm:@socketregistry/regexp.prototype.flags@^1",
191
- "safe-buffer": "npm:@socketregistry/safe-buffer@^1",
192
- "safer-buffer": "npm:@socketregistry/safer-buffer@^1",
193
- "side-channel": "npm:@socketregistry/side-channel@^1",
194
- "which-boxed-primitive": "npm:@socketregistry/which-boxed-primitive@^1",
195
- "which-collection": "npm:@socketregistry/which-collection@^1",
196
- "which-typed-array": "npm:@socketregistry/which-typed-array@^1"
197
- },
198
154
  "scripts": {
199
155
  "build": "tsup && npx tsx scripts/copy-protos.ts",
200
156
  "test": "vitest run --fileParallelism=false",
@@ -1,31 +0,0 @@
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
@@ -1,15 +0,0 @@
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 &harr; 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
@@ -1,31 +0,0 @@
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
@@ -1,46 +0,0 @@
1
- import {a as a$2}from'./chunk-MQ5SU26J.js';import {a as a$3,b as b$2}from'./chunk-XLVEDKM6.js';import {b as b$1}from'./chunk-2ZYX736J.js';import {j,g,h,f as f$1}from'./chunk-ECRS6N33.js';import {k,f,h as h$1,w,x,g as g$1}from'./chunk-ZZMSFCJP.js';import {a as a$1}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import*as O from'crypto';import O__default from'crypto';import*as S from'fs';import {createRequire}from'module';import L from'path';import {fileURLToPath,pathToFileURL}from'url';import*as _ from'@grpc/grpc-js';import {createMlKem768}from'mlkem';import {Piscina,FixedQueue}from'piscina';import {z}from'zod';import*as B from'jose';import Ae from'oidc-provider';import*as ne from'acorn';import {simple}from'acorn-walk';var J=class{static{a(this,"LiopRpcServer");}server;constructor(){this.server=new _.Server(j);}addService(e){this.server.addService(g.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,t){let r=h(t);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,r,(s,o)=>{if(s){n(s);return}b.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async gracefulShutdown(e=5e3){return new Promise(t=>{let r=false,i=setTimeout(()=>{r||(r=true,b.warn(`[LIOP-RPC] tryShutdown timed out after ${e}ms \u2014 forcing shutdown`),this.server.forceShutdown(),t());},e);this.server.tryShutdown(()=>{r||(r=true,clearTimeout(i),b.info("[LIOP-RPC] Server gracefully shut down"),t());});})}async stop(){return this.gracefulShutdown(5e3)}};var ve="0".repeat(64);function _e(h){let e=Object.keys(h).sort(),t={};for(let r of e)t[r]=h[r];return JSON.stringify(t)}a(_e,"canonicalize");function Ee(h){let e=_e(h);return O.createHash("sha256").update(e).digest("hex")}a(Ee,"computeEntryHash");var ie=class{static{a(this,"AuditLogger");}entries=[];lastEntryHash=ve;filePath;interceptor;constructor(e){this.filePath=e,this.filePath&&S.existsSync(this.filePath)&&this.loadFromFile(this.filePath);}setInterceptor(e){this.interceptor=e;}recordExecution(e){let t=O.randomUUID(),r=e.timestamp||new Date().toISOString(),i=e.traceId||O.randomBytes(16).toString("hex"),n=e.datasetHash||O.createHash("sha256").update("").digest("hex"),s=e.outputHash||O.createHash("sha256").update("").digest("hex"),o=e.zkReceiptSig||"",a={id:t,timestamp:r,traceId:i,agentDid:e.agentDid,peerId:e.peerId,toolName:e.toolName,datasetHash:n,fuelConsumed:e.fuelConsumed,outputHash:s,zkReceiptSig:o,status:e.status,prevEntryHash:this.lastEntryHash},c=Ee(a),l={...a,entryHash:c};if(this.entries.push(l),this.lastEntryHash=c,this.filePath&&S.appendFileSync(this.filePath,`${JSON.stringify(l)}
2
- `,"utf8"),this.interceptor){let u=Object.freeze(structuredClone(l));try{let y=this.interceptor(u);y&&typeof y=="object"&&"catch"in y&&y.catch(()=>{});}catch{}}return l}getEntries(){return [...this.entries]}getEntryCount(){return this.entries.length}verifyIntegrity(){let e=ve;for(let t=0;t<this.entries.length;t++){let r=this.entries[t];if(r.prevEntryHash!==e)return {valid:false,totalEntries:this.entries.length,brokenIndex:t,reason:`Broken hash chain at index ${t}: expected prevHash ${e}, got ${r.prevEntryHash}`};let{entryHash:i,...n}=r,s=Ee(n);if(s!==i)return {valid:false,totalEntries:this.entries.length,brokenIndex:t,reason:`Tampered entry at index ${t}: hash mismatch (expected ${s}, stored ${i})`};e=i;}return {valid:true,totalEntries:this.entries.length}}exportJsonl(){return this.entries.map(e=>JSON.stringify(e)).join(`
3
- `)}loadFromFile(e){let r=S.readFileSync(e,"utf8").split(`
4
- `).filter(i=>i.trim().length>0);for(let i of r){let n=JSON.parse(i);this.entries.push(n),this.lastEntryHash=n.entryHash;}}},Se=new ie;var H={audience:"urn:liop:mesh:api",tokenTtlSeconds:3600,jwksCacheTtlMs:6e5,jwksCooldownMs:3e4,clockToleranceSec:5,signingAlgorithm:"EdDSA"};var q=class{static{a(this,"JwtValidator");}jwksResolver;issuer;audience;constructor(e,t,r){this.issuer=e,this.audience=t,r instanceof URL?this.jwksResolver=B.createRemoteJWKSet(r,{cacheMaxAge:H.jwksCacheTtlMs,cooldownDuration:H.jwksCooldownMs}):this.jwksResolver=B.createLocalJWKSet(r);}async validate(e){let t=this.buildIssuerAliases(),{payload:r}=await B.jwtVerify(e,this.jwksResolver,{issuer:t.length>1?t:this.issuer,audience:this.audience,algorithms:[H.signingAlgorithm,"ES256"],clockTolerance:H.clockToleranceSec,requiredClaims:["sub","scope"]});return {token:e,clientId:r.sub??"unknown",scopes:typeof r.scope=="string"?r.scope.split(" "):[],expiresAt:r.exp}}buildIssuerAliases(){let e=[this.issuer],t=this.issuer.endsWith("/")?this.issuer.slice(0,-1):this.issuer,r=["nexus:3000","liop-nexus:3000","127.0.0.1:3000","localhost:3000","127.0.0.1:13000","localhost:13000","127.0.0.1:13001","localhost:13001","127.0.0.1:15000","localhost:15000"],i="";try{let o=new URL(t);i=`${o.hostname}:${o.port||"3000"}`;}catch{return e}if(!r.some(o=>i===o))return e;let s=t.replace(/^https?:\/\/[^/]+/,"");for(let o of r){let a=`http://${o}${s}`;e.includes(a)||e.push(a);}if(s)for(let o of r){let a=`http://${o}`;e.includes(a)||e.push(a);}else for(let o of r){let a=`http://${o}/oidc`;e.includes(a)||e.push(a);}return e}getIssuer(){return this.issuer}getAudience(){return this.audience}};function be(h){let{privateKey:e,publicKey:t}=O__default.generateKeyPairSync("ed25519"),r=e.export({format:"jwk"}),i=t.export({format:"jwk"}),n=O__default.createHash("sha256").update(i.x||"").digest("hex").slice(0,16),s={...r,kid:n,use:"sig",alg:"EdDSA"},o={...i,kid:n,use:"sig",alg:"EdDSA"},a$1={keys:[s]},c={keys:[o]},l={scopes:["openid","offline_access",...b$2],clients:h.clients.map(v=>({client_id:v.client_id,client_secret:v.client_secret,grant_types:["client_credentials"],response_types:[],redirect_uris:[],scope:v.scope,token_endpoint_auth_method:"client_secret_post",id_token_signed_response_alg:"EdDSA"})),features:{clientCredentials:{enabled:true},devInteractions:{enabled:false},resourceIndicators:{enabled:true,useGrantedResource:a(()=>true,"useGrantedResource"),getResourceServerInfo:a((v,p,f)=>({scope:f.scope||"",accessTokenFormat:"jwt",jwt:{sign:{alg:"EdDSA"}}}),"getResourceServerInfo")}},formats:{AccessToken:"jwt"},interactions:{url:a(()=>{throw new Error("InteractionsNotSupportedException: This Authorization Server is strictly configured for Machine-to-Machine flows.")},"url")},jwks:a$1,ttl:{ClientCredentials:3600},cookies:{keys:[O__default.randomBytes(32).toString("hex")]},extraTokenClaims:a((v,p)=>p.kind==="AccessToken"?{scope:p.scope}:{},"extraTokenClaims")},u=h.issuer.endsWith("/")?h.issuer.slice(0,-1):h.issuer,y=new Ae(u,l);return y.proxy=true,{provider:y,jwks:c}}a(be,"createOAuthServer");var V=class h{static{a(this,"TaintAnalyzer");}piiFields;sensitiveKeys;static TAINT_PROPAGATING_METHODS=new Set(["charCodeAt","codePointAt","charAt","at","indexOf","lastIndexOf","search","localeCompare","startsWith","endsWith","includes","substring","slice","substr","split","match","matchAll","replace","replaceAll","normalize","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat"]);static ARRAY_CALLBACK_METHODS=new Set(["map","forEach","filter","find","some","every","flatMap","findIndex"]);static REDUCE_METHODS=new Set(["reduce","reduceRight"]);currentRecordCollections=new Set;constructor(e,t=[]){this.piiFields=new Set(e.map(r=>r.toLowerCase())),this.sensitiveKeys=new Set(t.map(r=>r.toLowerCase()));}classifyField(e,t=[]){let r=e.toLowerCase();if(this.piiFields.has(r))return "forbidden";let i=new Set(t.map(n=>n.toLowerCase()));return this.sensitiveKeys.has(r)||i.has(r)?"sensitive":"public"}analyze(e,t,r=50){let i;try{let a=`function liop_analysis_wrapper(env) {
5
- ${e}
6
- }`;i=ne.parse(a,{ecmaVersion:2022,sourceType:"script",locations:!0});}catch{return null}let n=new Set,s=new Set;this.identifyRecordBoundVars(i,n),this.propagateTaint(i,n,s);let o=this.checkReturnStatements(i,n,s);if(o)return o;if(t!==void 0&&t>0&&t<r){let a=this.detectCorrelatedAggregations(i);if(a)return a.reason=a.reason.replace("50 records",`${r} records`),a}if(t!==void 0&&t>0&&t<r){let a=this.detectMinMaxExtraction(i);if(a)return a.reason=a.reason.replace("50 records",`${r} records`),a}return null}extractQueriedFields(e){let t;try{t=ne.parse(`function w(env) {
7
- ${e}
8
- }`,{ecmaVersion:2022,sourceType:"script"});}catch{return []}let r=new Set;this.identifyRecordBoundVars(t,r);let i=new Set;return simple(t,{MemberExpression:a(s=>{let o=this.getPropertyName(s);if(!(!o||o==="length")&&(s.object.type==="Identifier"&&r.has(s.object.name)&&i.add(o),s.object.type==="MemberExpression")){let a=s.object;a.computed&&this.isEnvRecordsAccess(a.object)&&i.add(o);}},"MemberExpression")}),Array.from(i)}detectCorrelatedAggregations(e){let t=new Map;simple(e,{CallExpression:a(i=>{if(i.callee.type!=="MemberExpression")return;let n=i.callee,s=this.getPropertyName(n);if(!s||!h.REDUCE_METHODS.has(s)||!this.isEnvRecordsChain(n.object))return;let o=i.arguments[0];if(!o||o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return;let a=o,c=a.params.length>1?a.params[1]:a.params[0];if(c?.type!=="Identifier")return;let l=c.name,u=this.extractFieldsFromBody(a.body,l);for(let y of u){let v=t.get(y)??0;t.set(y,v+1);}},"CallExpression")});for(let[i,n]of t)if(n>=2)return {reason:`Correlation guard: ${n} aggregations detected on field '${i}'. Multiple correlated aggregations on the same field can enable differencing attacks. Use a single aggregation per numeric field, or increase dataset size above 50 records.`};return null}isEnvRecordsChain(e){if(this.isEnvRecordsAccess(e))return true;if(e.type==="CallExpression"){let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,i=this.getPropertyName(r);if(i&&(i==="slice"||i==="filter"||i==="toSorted"))return this.isEnvRecordsChain(r.object)}}return false}isRecordsSource(e){if(this.isEnvRecordsAccess(e)||e.type==="Identifier"&&this.currentRecordCollections.has(e.name))return true;if(e.type==="CallExpression"){let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,i=this.getPropertyName(r);if(i&&(i==="slice"||i==="filter"||i==="toSorted"||i==="map"||i==="concat"))return this.isRecordsSource(r.object)}}return false}identifyRecordCollections(e){this.currentRecordCollections.clear();for(let t=0;t<3;t++)simple(e,{VariableDeclarator:a(i=>{!i.init||i.id.type!=="Identifier"||this.isRecordsSource(i.init)&&this.currentRecordCollections.add(i.id.name);},"VariableDeclarator"),AssignmentExpression:a(i=>{i.left.type==="Identifier"&&this.isRecordsSource(i.right)&&this.currentRecordCollections.add(i.left.name);},"AssignmentExpression")});}extractFieldsFromBody(e,t){let r=[];return simple(e,{MemberExpression:a(n=>{if(n.object.type==="Identifier"&&n.object.name===t){let s=this.getPropertyName(n);s&&s!=="length"&&r.push(s);}},"MemberExpression")}),r}detectMinMaxExtraction(e){let t=null;return simple(e,{CallExpression:a(i=>{if(!t&&i.callee.type==="MemberExpression"){let n=i.callee;if(n.object.type==="Identifier"&&n.object.name==="Math"){let s=this.getPropertyName(n);(s==="min"||s==="max")&&i.arguments.some(o=>o.type==="SpreadElement"&&this.isRecordsMapCall(o.argument))&&(t={reason:`Min/Max gate: Math.${s}() on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations.`});}}},"CallExpression"),MemberExpression:a(i=>{if(!t&&i.computed&&i.object.type==="CallExpression"){let n=i.object;if(n.callee.type==="MemberExpression"){let s=this.getPropertyName(n.callee);if(s==="sort"||s==="toSorted"){let o=n.callee.object;this.isEnvRecordsChain(o)&&(t={reason:"Min/Max gate: .sort()[index] on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations."});}}}},"MemberExpression")}),t}isRecordsMapCall(e){if(e.type!=="CallExpression")return false;let t=e;if(t.callee.type!=="MemberExpression")return false;let r=t.callee;return this.getPropertyName(r)==="map"&&this.isRecordsSource(r.object)}identifyRecordBoundVars(e,t){this.identifyRecordCollections(e),simple(e,{CallExpression:a(n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isRecordsSource(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(h.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&t.add(l.name);}if(h.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&t.add(l.name);}}},"CallExpression"),ForOfStatement:a(n=>{if(this.isRecordsSource(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&t.add(s.id.name);},"ForOfStatement")}),simple(e,{VariableDeclarator:a(n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isRecordsSource(s.object)&&t.add(n.id.name);}},"VariableDeclarator")});}propagateTaint(e,t,r){for(let i=0;i<3;i++){let n=r.size;if(simple(e,{VariableDeclarator:a(o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,t,r)&&r.add(o.id.name);},"VariableDeclarator"),AssignmentExpression:a(o=>{if(o.left.type==="MemberExpression"){let a=o.left;a.computed&&this.isExpressionTainted(a.property,t,r)&&a.object.type==="Identifier"&&r.add(a.object.name);}o.left.type==="Identifier"&&this.isExpressionTainted(o.right,t,r)&&r.add(o.left.name);},"AssignmentExpression"),FunctionDeclaration:a(o=>{o.id&&o.id.type==="Identifier"&&this.doesCallbackProduceTaint(o,null,t,r)&&r.add(o.id.name);},"FunctionDeclaration"),CallExpression:a(o=>{if(o.callee.type!=="MemberExpression")return;let a=o.callee;this.getPropertyName(a)==="push"&&a.object.type==="Identifier"&&o.arguments.some(l=>this.isExpressionTainted(l,t,r))&&r.add(a.object.name);},"CallExpression")}),r.size===n)break}}checkReturnStatements(e,t,r){let i=null;return simple(e,{ReturnStatement:a(s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,t,r)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,t,r);i={reason:`PII side-channel detected: output contains values derived from restricted fields. ${a?`Operation: ${a}. `:""}Use only non-PII fields (e.g., numeric/date columns) for aggregations.`,line:o,operation:a};}},"ReturnStatement")}),i}isExpressionTainted(e,t,r){switch(e.type){case "Identifier":return r.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,t,r);case "CallExpression":return this.isCallExprTainted(e,t,r);case "YieldExpression":{let i=e;return i.argument?this.isExpressionTainted(i.argument,t,r):false}case "FunctionExpression":case "ArrowFunctionExpression":{let i=e;return this.doesCallbackProduceTaint(i,null,t,r)}case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,t,r)||this.isExpressionTainted(i.right,t,r)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,t,r)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,t,r)||this.isExpressionTainted(i.consequent,t,r)||this.isExpressionTainted(i.alternate,t,r)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"?n.computed&&this.isExpressionTainted(n.key,t,r)?true:this.isExpressionTainted(n.value,t,r):n.type==="SpreadElement"?this.isExpressionTainted(n.argument,t,r):false);case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,t,r));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,t,r));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,t,r)}default:return false}}isMemberExprTainted(e,t,r){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&t.has(e.object.name)&&i&&this.piiFields.has(i.toLowerCase()))return true;if(e.object.type==="MemberExpression"&&i&&this.piiFields.has(i.toLowerCase())){let n=e.object;if(n.computed&&this.isRecordsSource(n.object))return true}if(this.isExpressionTainted(e.object,t,r))return true;if(e.computed&&e.object.type==="Identifier"&&t.has(e.object.name)&&e.property.type==="Literal"){let n=e.property.value;if(typeof n=="string"&&this.piiFields.has(n.toLowerCase()))return true}return false}isCallExprTainted(e,t,r){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&h.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,t,r))return true;if(this.isRecordsSource(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,t,r)}if(this.isExpressionTainted(i.object,t,r)||e.arguments.some(s=>this.isExpressionTainted(s,t,r)))return true}if(e.callee.type==="MemberExpression"){let i=e.callee;this.getPropertyName(i)==="push"&&i.object.type==="Identifier"&&e.arguments.some(s=>this.isExpressionTainted(s,t,r))&&r.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(r.has(i))return true;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,t,r))}return false}doesCallbackProduceTaint(e,t,r,i){let n=new Set(r),s=new Set(i);if(e.params.length>0){let l=t!==null&&h.REDUCE_METHODS.has(t)?1:0;e.params.length>l&&e.params[l].type==="Identifier"&&n.add(e.params[l].name);}if(e.type==="ArrowFunctionExpression"&&e.body.type!=="BlockStatement")return this.isExpressionTainted(e.body,n,s);this.propagateTaint(e.body,n,s);let o=false,a$1={ReturnStatement:a(c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);},"ReturnStatement"),YieldExpression:a(c=>{let l=c;l.argument&&this.isExpressionTainted(l.argument,n,s)&&(o=true);},"YieldExpression")};return simple(e.body,a$1),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let t=e.property.value;if(typeof t=="string")return t}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let t=e;if(this.getPropertyName(t)==="records"&&t.object.type==="Identifier"&&t.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,t,r){if(e.type==="Identifier"){let i=e.name;if(r.has(i))return `variable '${i}' is PII-derived`}if(e.type==="ObjectExpression"){let i=e;for(let n of i.properties)if(n.type==="Property"&&this.isExpressionTainted(n.value,t,r))return `property '${n.key.type==="Identifier"?n.key.name:"unknown"}' contains PII-derived value`}if(e.type==="CallExpression"){let i=e;if(i.callee.type==="MemberExpression"){let n=this.getPropertyName(i.callee);if(n)return `result of .${n}() on PII data`}}}};var ke={aspirin:"Medication",lisinopril:"Medication",metformin:"Medication",amlodipine:"Medication",atorvastatin:"Medication",omeprazole:"Medication",losartan:"Medication",simvastatin:"Medication",levothyroxine:"Medication",ibuprofen:"Medication",acetaminophen:"Medication",amoxicillin:"Medication",ciprofloxacin:"Medication",prednisone:"Medication",warfarin:"Medication",insulin:"Medication",hydrochlorothiazide:"Medication",gabapentin:"Medication",albuterol:"Medication",pantoprazole:"Medication",hypertension:"Condition",diabetes:"Condition",bronchitis:"Condition",pneumonia:"Condition",asthma:"Condition"},Q=4,Oe=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,X=class h{static{a(this,"NerScanner");}static nlp=null;async getNlp(){if(!h.nlp){let e=await import('compromise/three');h.nlp=e.default||e,h.nlp.addWords(ke);}return h.nlp}async scan(e){if(e.length<Q||Oe.test(e))return {detected:false,entities:[]};let r=(await this.getNlp())(e),i=[],n=r.people().out("array");for(let a of n){let c=a.trim();c.length>=Q&&i.push({type:"person",text:c});}let s=r.places().out("array");for(let a of s){let c=a.trim();c.length>=Q&&i.push({type:"place",text:c});}let o=r.organizations().out("array");for(let a of o){let c=a.trim();c.length>=Q&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,t=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(t.has(e))return {detected:false,entities:[]};t.add(e);let r=Array.isArray(e)?e:Object.values(e),i=[];for(let n of r){let s=await this.scanDeep(n,t);if(s.detected&&(i.push(...s.entities),s.entities.some(o=>o.type==="person")))return {detected:true,entities:i}}return {detected:i.length>0,entities:i}}return {detected:false,entities:[]}}};function Ne(h){let e=h.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let t=0,r=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);r&&(n*=2,n>9&&(n-=9)),t+=n,r=!r;}return t%10===0}a(Ne,"isLuhnValid");function Ce(h){let e=h.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let t=e.substring(4)+e.substring(0,4),r="";for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n>=65&&n<=90)r+=(n-55).toString();else if(n>=48&&n<=57)r+=t.charAt(i);else return false}try{return BigInt(r)%97n===1n}catch{return false}}a(Ce,"isIbanValid");var R={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:a(h=>!h.endsWith("@example.com")&&!h.endsWith("@test.com"),"validator")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:Ne},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:a(h=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(h)?false:h.split(".").map(Number).every(r=>r>=0&&r<=255),"validator")},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")},"validator")},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");if(e.length!==9)return false;let t=parseInt(e.substring(0,3),10);return !(t===0||t===666||t>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")},"validator")},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Ce},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},Te={GLOBAL_STRICT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.PASSPORT_MRZ,R.IBAN],US_COMPLIANT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.SSN,R.PASSPORT_MRZ],EU_GDPR:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.IBAN,R.PASSPORT_MRZ]},ee=class h{static{a(this,"PiiScanner");}patterns;forbiddenKeysSet;nerScanner;static KEY_SAFELIST=new Set(["grid","video","android","identity","provide","override","validate","hidden","widget","guidelines","beside","guideline","outside","inside","collide","decide","divide","aside","ride","side","wide","hide","tide","pride","bride","slide","guide","stride","oxide","dioxide","suicide","homicide","pesticide","valid","invalid","void","avoid","diagnosis","medication","namespace","namesake","rename","filename","hostname","typename","unnamed","renamed","phonetic","phoneme","microphone","headphone","telephone","saxophone","smartphone","streetview","addressable","addressing","cityscape","electricity","capacity","velocity","opacity","timestamp","timezone","image_id","computation_result","zk_receipt","testid","toolid","sessionid","peerid","nodeid","requestid","correlationid","traceid","spanid"]);shortTokenBoundaryPatterns;longForbiddenTokens;constructor(e=[],t=[],r){this.patterns=e,this.forbiddenKeysSet=new Set(t.map(i=>i.toLowerCase())),this.nerScanner=r??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp((()=>{let n=i.split("").map(o=>`[${o.toLowerCase()}${o.toUpperCase()}]`).join(""),s=`[a-z]${i.charAt(0).toUpperCase()}${i.slice(1)}`;return `(?:^|[_-])${n}(?:$|[_-])|${s}(?:$|[A-Z_-])|^${n}$`})())):this.longForbiddenTokens.push(i);}async scan(e,t=new WeakSet){if(e==null)return null;if(typeof e=="string"){let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{let n=JSON.parse(r),s=await this.scan(n,t);if(s)return s}catch{}let i=this.checkString(e);if(i)return i;if(this.nerScanner){let n=await this.nerScanner.scan(e);if(n.detected){let s=n.entities.find(o=>o.type==="person");if(s)return `PII Entity Detected: person name "${s.text}"`}}return null}if(typeof e=="object"){if(t.has(e))return null;if(t.add(e),Array.isArray(e))for(let r of e){let i=await this.scan(r,t);if(i)return i}else for(let[r,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(r.toLowerCase()))return `Forbidden Key: ${r}`;let n=this.checkKeyFuzzy(r);if(n)return n;let s=await this.scan(i,t);if(s)return s}}return null}checkKeyFuzzy(e){let t=e.toLowerCase();if(h.KEY_SAFELIST.has(t))return null;for(let[r,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${r}"`;for(let r of this.longForbiddenTokens)if(t.includes(r))return `Forbidden Key (fuzzy): ${e} contains restricted token "${r}"`;return null}checkString(e){for(let t of this.patterns)if(typeof t=="string"){if(e.toLowerCase().includes(t.toLowerCase()))return t}else if(t instanceof RegExp){if(t.global&&(t.lastIndex=0),t.test(e))return t.source}else if(typeof t=="object"&&t!==null){let r=t;if(typeof r.pattern=="string"){if(e.toLowerCase().includes(r.pattern.toLowerCase())&&(!r.validator||r.validator(r.pattern)))return r.name}else if(r.pattern instanceof RegExp){r.pattern.global&&(r.pattern.lastIndex=0);let i=r.pattern.exec(e);for(;i!==null;){let n=i[0];if(!r.validator||r.validator(n))return r.name;if(!r.pattern.global)break;i=r.pattern.exec(e);}}}return null}};var Pe=L.dirname(fileURLToPath(import.meta.url)),Re=class h{constructor(e,t){this.serverInfo=e;this.config=t;let r=this.config?.security?.enableNerScanning?new X:null;this.piiScanner=new ee(this.config?.security?.piiPatterns??Te.GLOBAL_STRICT,this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],r);let i=this.config?.security?.rateLimit;this.toolCallWindowMs=i?.windowMs??Number.parseInt(process.env.LIOP_RATE_LIMIT_WINDOW_MS??"60000",10),this.toolCallMaxPerWindow=i?.maxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_MAX??"15",10),this.globalCallMaxPerWindow=i?.globalMaxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_GLOBAL_MAX??"40",10);let n=this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],s=this.config?.security?.sensitiveKeys??[];this.taintAnalyzer=new V(n,s),this.auditLogger=this.config?.auditLogger||Se;let o=import.meta.url.endsWith(".ts"),a=o?".ts":".js",c=[];if(o)try{let f=createRequire(import.meta.url).resolve("tsx/package.json"),d=pathToFileURL(L.join(L.dirname(f),"dist","loader.mjs")).href;c.push("--import",d);}catch{c.push("--import","tsx");}let l=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let u=[L.resolve(Pe,`./workers/logic-execution${a}`),L.resolve(Pe,`../workers/logic-execution${a}`)],y=u.find(p=>S.existsSync(p))||u[1];this.workerPool=new Piscina({filename:y,minThreads:this.config?.workerPool?.minThreads??(l?0:2),maxThreads:this.config?.workerPool?.maxThreads??(l?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(l?500:5e3),maxQueue:this.config?.workerPool?.maxQueue??"auto",taskQueue:new FixedQueue,execArgv:c,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}});let v=this.config?.workerPool?.minThreads??(l?0:2);if(this.workerPool&&v>0)for(let p=0;p<v;p++)this.workerPool.run({isWarmup:true}).catch(f=>{b.debug(`[LiopServer] Worker pool warm-up ping failed: ${f.message}`);});try{this.enclavePqcKeypair=b$1.generateKeyPair();}catch{this.enclavePqcKeypair=void 0;}if(this.config?.auth?.role==="nexus"){let p=this.config.auth.issuer||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=this.config.auth.clients||[{client_id:process.env.LIOP_OAUTH_CLIENT_ID||"liop-mesh-agent",client_secret:process.env.LIOP_OAUTH_CLIENT_SECRET||"dev-secret-change-me",grant_types:["client_credentials"],scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query"}],{provider:m,jwks:b}=be({issuer:p,clients:d});this.oauthProvider=m,this.jwtValidator=new q(p,f,b);}else if(this.config?.auth?.role==="node"){let p=this.config.auth.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=p.endsWith("/oidc")?p:`${p}/oidc`,m=new URL(`${d}/jwks`);this.jwtValidator=new q(p,f,m);}this.resource("LIOP Envelope Specification","liop://protocol/envelope-spec","Complete Logic-on-Origin envelope format, execution rules, and security constraints","text/plain",()=>Promise.resolve(this.buildEnvelopeSpec())),this.config?.auth?.revocationPath&&this.loadRevocationList();}serverInfo;config;static{a(this,"LiopServer");}logicCache=new Map;connectionStats=new Map;CACHE_TTL_MS=1440*60*1e3;THROTTLE_THRESHOLD=5;THROTTLE_COOLDOWN_MS=60*1e3;toolCallWindows=new Map;toolCallMaxPerWindow;toolCallWindowMs;globalCallWindow=[];globalCallMaxPerWindow;fieldQueryBudget=new Map;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;enclavePqcKeypair;jwtValidator;oauthProvider;sessions=new Map;revokedTokenHashes=new Set;lastRevocationLoadTime=0;pqcKeyPair=b$1.generateKeyPair();auditLogger;getDatasetHash(){return O__default.createHash("sha256").update(JSON.stringify(this.sandboxRecords||[])).digest("hex")}static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,\s*(?<name>[^}]*))?\}[\r\n]+(?<logic>[\s\S]*?)[\r\n]+@END/m;extractLogic(e){if(!e||typeof e!="string")return null;let t=e.trim().match(h.LIOP_COMPACT_REGEX);return t?.groups?.logic?t.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}runPreflightPolicy(e,t,r,i="local-client"){if(r){let a=t.replace(/\s+/g," ");if(r.enforceAggregationFirst&&[/return\s+env\.records(?!\s*\.\s*(?:reduce|length|filter|every|some|find)\b)/i,/return\s*\{[\s\S]*\b(accounts|patients|rows|records)\s*:\s*env\.records(?!\s*\.\s*(?:reduce|length|filter)\b)/i].some(l=>l.test(a)))return "Preflight policy rejected: potential row-level export pattern detected.";if(r.preflightDenyPatterns?.some(c=>c.test(a)))return "Preflight policy rejected: custom deny pattern matched."}let n=50;typeof r?.enforceAggregationFirst=="object"&&(n=r.enforceAggregationFirst.minMaxBlockThreshold??50);let s=this.taintAnalyzer.analyze(t,this.sandboxRecords.length,n);if(s)return `Preflight policy rejected: ${s.reason}`;let o=this.taintAnalyzer.extractQueriedFields(t);if(o.length>0){if(i==="__proto__"||i==="constructor"||i==="prototype"||e==="__proto__"||e==="constructor"||e==="prototype")return "Preflight policy rejected: invalid property key names (prototype pollution guard).";let a=r?.budgetStorePath||this.config?.budgetStorePath;if(a)try{let c=this.executeWithBudgetLock(a,l=>{let u=l[i]||{},y=u[e]||{};for(let d of o){let m=this.taintAnalyzer.classifyField(d,r?.sensitiveKeys),b=25,T="public";if(r?.queryBudgetPerField!==void 0?(b=r.queryBudgetPerField,T="override"):m==="forbidden"?(b=3,T="forbidden"):m==="sensitive"&&(b=8,T="sensitive"),(y[d]??0)>=b)return {result:`Preflight policy rejected: Query budget exceeded for field '${d}' (max ${b} per session for ${T} fields). Rotate PQC session to reset budget.`}}let v={...y};for(let d of o)v[d]=(v[d]??0)+1;let p={...u};p[e]=v;let f={...l};return f[i]=p,{result:null,updatedBudget:f}});if(c)return c}catch(c){let l=c instanceof Error?c.message:String(c);b.error(`[LIOP-Server] Error applying persistent query budget: ${l}. Falling back to in-memory.`);let u=this.applyInMemoryBudget(i,e,o,r);if(u)return u}else {let c=this.applyInMemoryBudget(i,e,o,r);if(c)return c}}return null}validateOutputPolicy(e,t,r){if(!r)return null;let i=this.parseUnknownJson(t);if(i&&typeof i=="object"&&i.isError===true)return null;if(r.outputSchema){let s=(()=>{if(!(r.outputSchema instanceof z.ZodObject))return r.outputSchema;let o=r.outputSchema,a=o.def||o._def;return a&&a.catchall!==void 0&&!(a.catchall instanceof z.ZodNever)?o:o.strict()})().safeParse(i);if(!s.success)return `[LIOP] Output schema violation for ${e}: ${s.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}. HINT: Your output must conform to the declared schema. Use 'env.records' to access the dataset and return only allowed fields.`}return r.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),r.enforceAggregationFirst,this.sandboxRecords.length)?process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?"Aggregation-First Policy Violation: row-level export or K-Anonymity violation blocked. HINT: Use .reduce() to produce a flat {key:value} object. Do NOT use .map() to create arrays of objects. Ensure dataset size > 10 for detailed results.":"Aggregation-First Policy Violation: Output blocked due to privacy constraints.":null}unwrapForAggregationPolicyScan(e){if(typeof e=="string"){let n=e.trim();if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{return this.unwrapForAggregationPolicyScan(JSON.parse(n))}catch{return e}return e}if(!e||typeof e!="object")return e;let t=e;if(t.computation_result!==void 0)return this.unwrapForAggregationPolicyScan(t.computation_result);if(!Array.isArray(t.content)||t.content.length===0)return e;let r=[];for(let n of t.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&r.push(s);}if(r.length===0)return e;let i=r.length===1?r[0]:r.join(`
9
- `);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,t,r){if(!t)return false;let i=typeof t=="object"&&typeof t.maxOutputRows=="number"?t.maxOutputRows:10,n=typeof t=="object"&&typeof t.allowPrimitiveArrays=="boolean"?t.allowPrimitiveArrays:true;if(typeof e=="string"){let s=e.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(s),t,r)}catch{return false}return false}if(Array.isArray(e))return e.length>0&&e.every(s=>typeof s=="object"&&s!==null)?e.length>i?true:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r));if(e&&typeof e=="object"){let s=Object.keys(e);return r!==void 0&&r>0&&r<10&&(s.length>3||Object.values(e).some(a=>Array.isArray(a)||typeof a=="object"&&a!==null))||s.length>i?true:Object.values(e).some(o=>this.violatesAggregationFirstPolicy(o,t,r))}return false}buildEnvelopeSpec(){let e=["LIOP v1 Envelope Specification","================================","","FORMAT:","","Compact Envelope:"," @LIOP{wasi_v1,TaskName}"," <JavaScript code>"," @END","","RUNTIME ENVIRONMENT:","- env.records: Array of data objects from the origin","- Must use 'return' to output results","- Zero-Trust WASI Sandbox (Node.js Worker Pool)","- Return aggregated objects, NOT raw row-level arrays","","SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS:","- Date is poisoned: The 'Date' class/constructor is undefined (Date.now(), Date.parse(), etc. will throw)."," Workaround: Use lexicographical string comparison on ISO 8601 date strings (e.g., record.date >= '2024-01-01').","- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.","- Frozen prototypes: Any modifications to Object.prototype, Array.prototype, etc., are blocked.","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution","","DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism):","- Default field noise scale is derived from node global sensitivity.","- COUNT / LENGTH Optimization: To obtain EXACT counts without noise (sensitivity=1),"," the return keys MUST contain 'count', 'length', 'size', 'num', 'positive', 'negative',"," or start with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count').","- AVERAGE Optimization: Keys containing 'avg', 'mean' or 'average' scale noise"," down automatically by dividing sensitivity by dataset size (sensitivity / n).","- SUM / OTHER queries: Receive full Laplace noise based on global node sensitivity"," (e.g., Sensitivity=100,000 in Bank to protect balances)."];return this.config?.security?.forbiddenKeys?.length&&e.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),e.push("","TAINT TRACKING (Phase 108):","- AST-level analysis blocks PII-derived scalars (charCodeAt, charAt, etc.)","- Operations on restricted fields are tracked through variable assignments","- Boolean inference (field.charCodeAt(0) < N ? 1 : 0) is blocked","- Allowed: aggregations on non-PII fields (balance, amount, date)","","K-ANONYMITY THRESHOLDS:","- Small Datasets (< 10 records): Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.","- Large Datasets (>= 10 records): Maximum of 10 output fields.","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)","","QUERY BUDGET TIERS (NIST SP 800-226):","- FORBIDDEN (PII fields like name, accountHolder): Blocked in AST preflight. Never executed, does not consume budget.","- SENSITIVE (fields marked via sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override).","- PUBLIC (all other fields): 25 queries per agent identity.","- PERSISTENCE: The budget is tracked by agent DID and persisted to disk, NOT by MCP session."," Reconnecting or starting a new session does NOT reset the budget."," Reset requires: administrator calling resetFieldBudget() or manual deletion of the budget store file.","","AUTHENTICATION (tokenSlug Convention):","- Restricted nodes declare authRequired: true in their manifest.","- Token resolution: LIOP_TOKEN_<tokenSlug> (deterministic) > LIOP_TOKEN_<PeerID> > LIOP_TOKEN_<ProviderName>","- Format: tokenSlug must match SCREAMING_SNAKE_CASE /^[A-Z][A-Z0-9_]*$/ (e.g., BANK, VAULT, HFT_ORACLE)."),e.join(`
10
- `)}extractSchemaFieldSummary(e,t=0){if(t>3)return "{...}";let r=e.type,i=e.properties,n=e.items;return i?`{${Object.entries(i).map(([o,a])=>{let c=a.type;if(c==="array"&&a.items){let l=this.extractSchemaFieldSummary(a.items,t+1);return `${o}(array of ${l})`}if(c==="object"&&a.properties){let l=this.extractSchemaFieldSummary(a,t+1);return `${o}(${l})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:r==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,t+1)}`:r||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,t,r,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z.object(r),o=z.toJSONSchema(s,{target:"draft-07"}),a$1=t,c=i;if(r.payload&&r.payload instanceof z.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a$1+=`
11
-
12
- Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. Note: If dataset size < 10 (synthetic demo), Egress K-Anonymity blocks output if it has >3 keys or any array/nested object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a$1+=`
13
- Restricted fields: ${u.join(", ")}.`),this.activeSchema){let y=this.extractSchemaFieldSummary(this.activeSchema);a$1+=`
14
- Data structure: ${y}. Full schema: resource liop://schema/global`;}c=a(async(y,v)=>{let p="global_connection",f=Date.now(),d=this.connectionStats.get(p)||{failures:0,lastAttempt:0};if(d.failures>=this.THROTTLE_THRESHOLD&&f-d.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let m=y&&typeof y=="object"?y:{},b=m.payload??m.envelope??m.code,T=m.__liop_bypass_ast_cache===true,A=O__default.createHash("sha256").update(b||"").digest("hex"),w=this.extractLogic(b),x=this.logicCache.get(A);if(!T&&x&&f-x.timestamp<this.CACHE_TTL_MS&&w){m.payload=w,m.envelope!==void 0&&(m.envelope=w);let I=this.runPreflightPolicy(e,w,n,"mcp-client");return I?{content:[{type:"text",text:I}],isError:true}:await this.executeInWorkerPool(y,w,e)}if(!w)return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:"Error: Malformed payload. Missing @LIOP boundary.\\nYou MUST wrap your logic exactly like this:\\n\\n@LIOP{wasi_v1,DynamicAudit}\\n// Your JS code here\\n@END"}],isError:true};try{let I=this.extractLogic(b);m.payload=I,m.envelope!==void 0&&(m.envelope=I);let N=this.runPreflightPolicy(e,I,n,"mcp-client");if(N)return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:N}],isError:!0};let M=await this.executeInWorkerPool(y,I,e);return M.isError?(d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d)):(this.connectionStats.set(p,{failures:0,lastAttempt:f}),this.logicCache.set(A,{hash:A,timestamp:f})),M}catch(I){let N=I;return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:`ExecutionRuntimeException: ${N.message}`}],isError:true}}},"finalHandler");}let l={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a$1,inputSchema:l},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{b.info(`[LIOP-Mesh] Failed to auto-announce tool ${e}: ${u.message}`);});}prompt(e,t,r,i){if(this.prompts.has(e))throw new Error(`Prompt already registered: ${e}`);this.prompts.set(e,{prompt:{name:e,description:t,arguments:r},handler:i});}enableZeroShotAutonomy(){this.prompt("liop_blind_analyst","The official Logic-Injection-on-Origin Protocol system prompt. Instructs the LLM on how to securely inject Logic-on-Origin without violating PII or safety constraints.",[],e=>({description:"LIOP Blind Analyst Instructions",messages:[{role:"user",content:{type:"text",text:`You are the "Blind Analyst" operating within the Logic-Injection-on-Origin Protocol (LIOP) ecosystem.
15
- Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
16
-
17
- INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
18
- 1. DATA PRIVACY: NEVER attempt to export Personally Identifiable Information (PII). The LIOP Egress Shield will block any response containing raw IDs, names, or addresses.
19
- 2. AGGREGATION FIRST & K-ANONYMITY THRESHOLDS: Always prefer returning counts, averages, or anonymized summaries.
20
- - Dataset < 10 records: Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.
21
- - Dataset >= 10 records: Maximum of 10 output fields.
22
- 3. LAPLACE DIFFERENTIAL PRIVACY (DP) COMPLIANCE:
23
- - Legitimate COUNT queries: To obtain EXACT, un-noised counts, you MUST name your return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.
24
- - Legitimate AVERAGE queries: Use 'avg_', '_average' or 'mean_' keys to automatically scale down Laplace noise by dividing sensitivity by the dataset size (sensitivity / n).
25
- - Legitimate SUM queries: Return keys without count/average suffixes will receive full Laplacian noise scaled by the node's global sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.
26
- 4. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
27
- Structure:
28
- @LIOP{wasi_v1,AnalysisTask}
29
- // Your JS Code Here
30
- @END
31
- 5. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
32
- 6. LOCALIZATION: Format all JSON response keys in the language used by the user in their query (e.g., use Spanish keys if the query is in Spanish).
33
- 7. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.
34
- 8. SANDBOX RUNTIME: The 'Date' class/constructor is poisoned and set to undefined. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw exceptions.
35
- Workaround: Perform chronological operations and filtering using lexicographical string comparisons on ISO 8601 date strings (e.g., 'record.date >= "2024-01-01"').
36
- Additionally, standard globals like 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', ArrayBuffer, and TypedArrays are also undefined.
37
- 9. QUERY BUDGET PERSISTENCE: The per-field query budget is tracked by your agent DID and persisted to disk. Reconnecting or starting a new MCP session does NOT reset the budget. If you receive "Query budget exceeded", you must use a different field or request an administrator to invoke resetFieldBudget().${this.activeSchema?`
38
-
39
- CURRENT DATA DICTIONARY (STRICT):
40
- ${JSON.stringify(this.activeSchema,null,2)}`:""}
41
-
42
- Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,t,r,i,n){if(this.resources.has(t))throw new Error(`Resource URI already registered: ${t}`);this.resources.set(t,{name:e,uri:t,description:r,mimeType:i,content:n});}buildExecutionGuidelines(){return ["LIOP Sandbox Execution Guidelines","=================================","","1. DATE POISONING & FILTERING WORKAROUND:"," The global 'Date' class is set to undefined inside the sandbox. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw a ReferenceError."," - Workaround: Perform chronological filtering using lexicographical string comparisons on ISO 8601 strings."," Example: const filtered = env.records.filter(r => r.date >= '2024-01-01' && r.date <= '2024-12-31');","","2. K-ANONYMITY CONSTRAINTS:"," - Datasets with LESS than 10 records: The returned object must contain at most 3 scalar fields, and must NOT contain any arrays or nested objects."," - Datasets with 10 or MORE records: The returned object can contain up to 10 fields.","","3. DIFFERENTIAL PRIVACY SUFFIXES:"," To avoid Laplacian noise adding random perturbations to your counts or averages, you must name your object keys using specific terms:"," - Counts (Exact, no noise): Key names must contain 'count', 'length', 'size', 'num', 'positive', 'negative', or start with 'total_' or 'num_'."," - Averages (Reduced noise): Key names must contain 'avg', 'mean', or 'average'."," - Sums/Other: Will receive full Laplace noise.","","4. GENERAL RESTRICTIONS:"," - Do not use 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', 'ArrayBuffer', or TypedArrays."," - Do not attempt to modify prototypes (Object.prototype, Array.prototype).","","5. QUERY BUDGET TIERS (NIST SP 800-226):"," The per-field query budget is tracked by agent DID and persisted to disk (not per MCP session)."," - FORBIDDEN (PII fields): Always blocked in AST preflight. Does not consume budget."," - SENSITIVE (sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override)."," - PUBLIC (other fields): 25 queries per agent identity."," - Reset requires administrator intervention via resetFieldBudget()."].join(`
43
- `)}dataDictionary(e,t="Global Medical Data Dictionary",r="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){e.$comment="LIOP DIRECTIVES: 1. Date is undefined (Date.now(), new Date() throw). Workaround: use lexicographical string comparison on ISO 8601 string dates (e.g. record.date >= '2024-01-01'). 2. Small datasets (<10 records) limit outputs to max 3 scalar keys with NO nesting. 3. DP counts must contain count/length/size/num/total_ prefix/suffix.",this.activeSchema=e;let n=this.extractSchemaFieldSummary(e);for(let[s,o]of this.tools.entries())o.schema.shape.payload&&o.schema.shape.payload instanceof z.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
44
- Data structure: ${n}. Full schema: resource ${r}. Guidelines: resource liop://schema/guidelines`,this.tools.set(s,o));this.resources.has("liop://schema/guidelines")||this.resource("LIOP Execution Guidelines","liop://schema/guidelines","Directives for generating compliant JavaScript code for the LIOP Sandbox runtime","text/plain",()=>Promise.resolve(this.buildExecutionGuidelines())),this.resource(t,r,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),b.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let t=Date.now(),r=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>t-o<r);if(s.length>=i){let o=Math.ceil((s[0]+r-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${r/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(t),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),t=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<t),this.globalCallWindow.length>=r){let i=Math.ceil((this.globalCallWindow[0]+t-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${t/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e,t="local-client"){let r=this.tools.get(e.name);if(!r)throw new Error(`Tool not found: ${e.name}`);let i=this.checkGlobalRateLimit();if(i)return i;let n=this.checkToolCallRateLimit(e.name);if(n)return n;try{let s=r.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(s.__liop_bypass_ast_cache=!0),s&&typeof s.payload=="string"){let a=s.payload,c=this.extractLogic(a);if(c){let l=this.runPreflightPolicy(e.name,c,r.policy,t);return l?{content:[{type:"text",text:l}],isError:!0}:(s.payload=c,await this.executeInWorkerPool(s,c,e.name))}}return await r.handler(s,{})}catch(s){let o=s;return o instanceof z.ZodError?{content:[{type:"text",text:`Validation Error: ${o.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${o.message}`}],isError:true}}}listTools(){return Array.from(this.tools.values()).map(e=>e.tool)}listPrompts(){return Array.from(this.prompts.values()).map(e=>e.prompt)}async getPrompt(e){let t=this.prompts.get(e.name);if(!t)throw new Error(`Prompt not found: ${e.name}`);return await t.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let t=this.resources.get(e);if(!t)throw new Error(`Resource not found: ${e}`);let r="No description provided";return typeof t.content=="function"?r=await t.content():typeof t.content=="string"?r=t.content:t.description&&(r=t.description),{contents:[{uri:t.uri,mimeType:t.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getSandboxData(){return this.sandboxRecords}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let t=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=e.port??t??50051,i=/^[A-Z][A-Z0-9_]*$/;if(this.config?.tokenSlug&&!i.test(this.config.tokenSlug))throw new Error(`Invalid tokenSlug "${this.config.tokenSlug}". Must match SCREAMING_SNAKE_CASE: /^[A-Z][A-Z0-9_]*$/ (e.g., "BANK", "VAULT", "HFT_ORACLE").`);this.meshNode=new a$1(e.meshConfig),await this.meshNode.start();let n=this.meshNode;this.meshNode.registerManifestHandler(()=>{let s=this.listTools().map(l=>{let u=this.tools.get(l.name);return {name:l.name,description:l.description,inputSchema:l.inputSchema,zkMode:u?.policy?.zkMode,guestImageId:u?.policy?.guestImageId??this.config?.guestImageId,circuitName:u?.policy?.circuitName,vkey:u?.policy?.vkey}}),o=Array.from(this.resources.values()).map(l=>({name:l.name,uri:l.uri,description:l.description,mimeType:l.mimeType,text:typeof l.content=="string"?l.content:l.description})),a={peerId:n.getPeerId(),grpcPort:r,tools:s,resources:o,serverInfo:this.serverInfo,authRequired:this.jwtValidator!==void 0,tokenSlug:this.config?.tokenSlug,guestImageId:this.config?.guestImageId,vkeys:this.config?.zkVkeys,taxonomy:this.config?.taxonomy?{domain:this.config.taxonomy.domain||"Unknown Domain",clearanceTier:this.config.taxonomy.clearanceTier??0,executionTypes:this.config.taxonomy.executionTypes||[]}:void 0},c=b$1.signManifest(a,this.pqcKeyPair.secretKey,this.pqcKeyPair.publicKey);return {...a,pqcSignature:c.signature,pqcPublicKey:c.publicKey}});for(let s of this.listTools())await this.meshNode.announceCapability(s.name).catch(b.info);await this.meshNode.announceManifest().catch(b.info),this.rpcServer=new J,this.rpcServer.addService({negotiateIntent:a((s,o)=>{let a=s.request;if(b.info(`[LIOP-RPC] Negotiating intent for capability: ${a.capability_hash}`),this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){o({code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){o({code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info(`[LIOP-RPC] Bypass authentication for matching localTestToken: ${y}`),import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:p})=>{let{publicKey:f,secretKey:d}=await p.generateKeyPair(),m=O__default.randomUUID();this.sessions.set(m,{capability_hash:a.capability_hash,kyber_sk:d,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:m,error_message:"",kyber_public_key:f});});return}o({code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}this.jwtValidator.validate(l).then(p=>{let f=a$3("tools/call",p);if(!f.allowed){o({code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:d})=>{let{publicKey:m,secretKey:b}=await d.generateKeyPair(),T=O__default.randomUUID();this.sessions.set(T,{capability_hash:a.capability_hash,kyber_sk:b,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:T,error_message:"",kyber_public_key:m});});}).catch(p=>{o({code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p.message}`});});}else import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:c})=>{let{publicKey:l,secretKey:u}=await c.generateKeyPair(),y=O__default.randomUUID();this.sessions.set(y,{capability_hash:a.capability_hash,kyber_sk:u,agent_did:a.agent_did,createdAt:Date.now()}),o(null,{accepted:true,session_token:y,error_message:"",kyber_public_key:l});});},"negotiateIntent"),executeLogic:a(async s=>{let o=s.request;b.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${o.session_token}`);let a$1=a(async()=>{let c=this.sessions.get(o.session_token);if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Invalid session token"});return}let l=3600*1e3;if(c.createdAt){let f=Date.now()-c.createdAt;if(f>l){this.sessions.delete(o.session_token),s.emit("error",{code:_.status.UNAUTHENTICATED,details:`[LIOP-PQC] Session secret expired: Age (${Math.round(f/1e3)}s) exceeds 3600s TTL limit. Re-handshake required.`});return}}if(c.tokenHash&&(this.loadRevocationList(),this.revokedTokenHashes.has(c.tokenHash))){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let u=c.capability_hash,v=(u?this.tools.get(u):void 0)?.policy,p="";try{let d=(await createMlKem768()).decap(new Uint8Array(o.pqc_ciphertext),c.kyber_sk),m=Buffer.from(d),b$1=Buffer.from(o.wasm_binary),T=b$1.subarray(-16),A=b$1.subarray(0,-16),w=O__default.createDecipheriv("aes-256-gcm",m,Buffer.from(o.aes_nonce||new Uint8Array(12)));w.setAuthTag(T);let x=w.update(A);x=Buffer.concat([x,w.final()]),p=x.toString("utf-8");let I=this.extractLogic(p)||p.trim(),N=this.runPreflightPolicy(u||"unknown_tool",I,v,c.agent_did||o.session_token);if(N){b.info(`[LIOP-RPC] Preflight blocked: ${N}`);let M={semantic_evidence:N,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(M,()=>{s.end();});return}}catch(f){let d=f instanceof Error?f.message:String(f);b.error(`[LIOP-RPC] Preflight decryption failed: ${d}`),s.emit("error",{code:_.status.INTERNAL,details:`Preflight logic analysis failed: ${d}`});return}try{let f$2=v?{epsilon:v.dpEpsilon??1,sensitivity:v.dpSensitivity??1,smallDatasetThreshold:v.dpSmallDatasetThreshold??50}:void 0,d=o.requested_proof_mode;(d===void 0||d===0)&&(v?.zkMode==="required"?d=2:v?.zkMode==="optimistic"?d=1:d=0);let m=await this.workerPool.run({ciphertext:o.pqc_ciphertext,secretKeyObj:Array.from(c.kyber_sk),wasmBinary:o.wasm_binary,inputs:o.inputs,aesNonce:o.aes_nonce,records:this.sandboxRecords,sessionToken:o.session_token,sessionTimestamp:c.createdAt,isEncrypted:!0,proofMode:d,guestImageId:v?.guestImageId??this.config?.guestImageId,pqcSigningKey:v?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:f$2});if(d===2&&m.proof_type!==2&&m.proof_type!==3){b.error(`[LIOP-RPC] Enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable for ${u||"tool"}`);let k={semantic_evidence:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0,proof_type:0};s.write(k,()=>{s.end();});return}let b$1=a$2(m.output),T,A=b$1;try{T=typeof b$1=="string"?b$1:JSON.stringify(b$1);let k=JSON.parse(T);if(k.__liop_proxy_tool){b.info(`[LIOP-RPC] Executing Proxied Tool: ${k.__liop_proxy_tool}`);let W=c.agent_did||"unknown-client",D=await this.callTool({name:k.__liop_proxy_tool,arguments:k.__liop_proxy_args||{}},W);if(D.isError){b.info(`[LIOP-RPC] Proxy tool execution failed: ${D.content[0].text}`);let U={semantic_evidence:D.content[0].text||"Unknown error",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(U,()=>{s.end();});return}let G=a$2(D);T=JSON.stringify(G),A=this.unwrapForAggregationPolicyScan(G);}}catch{T=String(b$1);}let w$1=this.validateOutputPolicy(u||"unknown_tool",A,v);if(w$1){b.info(`[LIOP-RPC] Output policy blocked for ${u||"unknown_tool"}: ${w$1}`);let D={semantic_evidence:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?w$1:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(D,()=>{s.end();});return}let x$1={semantic_evidence:T,cryptographic_proof:Buffer.from(m.image_id||"","hex"),zk_receipt:m.zk_receipt?Buffer.from(m.zk_receipt,"base64"):Buffer.from(""),is_error:!1,proof_type:m.proof_type===3?3:m.proof_type===2?2:0,guest_image_id:m.guest_image_id||v?.guestImageId||this.config?.guestImageId||""},I=await this.piiScanner.scan(A),N=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(A),v?.enforceAggregationFirst,this.sandboxRecords?.length),M=!!(I||N);if(M){let k$1=I||"Aggregation-First Policy Violation";b.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${k$1}`),x$1.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",x$1.is_error=!0,k.inc({reason:I?"pii_scanner":"aggregation_policy"});}this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:m.fuel_consumed||0,outputHash:O__default.createHash("sha256").update(x$1.semantic_evidence).digest("hex"),zkReceiptSig:m.zk_receipt||"",status:M?"BLOCKED_EGRESS":"SUCCESS"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:M?"blocked_egress":"success",role:"executor"}),h$1.observe({capability:u||"unknown",tool:u||"unknown"},m.fuel_consumed||0);try{let k=Buffer.byteLength(x$1.semantic_evidence||"")+(x$1.cryptographic_proof?x$1.cryptographic_proof.length:0)+(x$1.zk_receipt?x$1.zk_receipt.length:0);if(w.inc({capability:u||"unknown"},k),this.sandboxRecords&&this.sandboxRecords.length>0){let W=JSON.stringify(this.sandboxRecords),D=Buffer.byteLength(W),G=Math.max(0,D-k);G>0&&x.inc({capability:u||"unknown"},G);try{let U=f$1.getInstance(),xe=U.countTokens(W),we=U.countTokens(x$1.semantic_evidence||""),Ie=U.countTokens(p||"");U.record({type:"tool_call",method:"ExecuteLogic",toolName:u||"unknown",estimatedInputTokens:Ie,estimatedOutputTokens:we,originDatasetTokens:xe});}catch{}}}catch{}s.write(x$1,()=>{s.end();});}catch(f$1){let d=f$1,m=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",b$1=d.message||String(f$1);b.error(`[LIOP-RPC] Execution Error: ${b$1}`);let T=m?`Execution Error: ${b$1}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.";this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:0,outputHash:O__default.createHash("sha256").update(T).digest("hex"),zkReceiptSig:"",status:"ERROR"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:"error",role:"executor"}),g$1.inc({capability:u||"unknown",error_type:"runtime_error"});let A={semantic_evidence:T,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{s.write(A,()=>{s.end();});}catch{s.end();}}},"proceed");if(this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info(`[LIOP-RPC] Bypass authentication in executeLogic for matching localTestToken: ${y}`),await a$1();return}s.emit("error",{code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}try{let p=await this.jwtValidator.validate(l),f=a$3("tools/call",p);if(!f.allowed){s.emit("error",{code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}await a$1();}catch(p){s.emit("error",{code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p instanceof Error?p.message:String(p)}`});}}else await a$1();},"executeLogic")}),this.boundPort=await this.rpcServer.listen(r),b.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,t,r){try{let i=r?this.tools.get(r)?.policy:void 0,n=i?{epsilon:i.dpEpsilon??1,sensitivity:i.dpSensitivity??1,smallDatasetThreshold:i.dpSmallDatasetThreshold??50}:void 0,s=0;i?.zkMode==="required"?s=2:i?.zkMode==="optimistic"&&(s=1);let o=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(t),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1,proofMode:s,guestImageId:i?.guestImageId??this.config?.guestImageId,pqcSigningKey:i?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:n});if(s===2&&o.proof_type!==2&&o.proof_type!==3)return {content:[{type:"text",text:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable."}],isError:!0};let a=o.output,c=a$2(a),u=[{type:"text",text:JSON.stringify({computation_result:c,image_id:o.image_id,zk_receipt:o.zk_receipt,proof_type:o.proof_type===3?"GROTH16_PQC_HYBRID":o.proof_type===2?"GROTH16":"HMAC_LEGACY",guest_image_id:o.guest_image_id,status:"Worker Pool Execution Success"})}],y=r?this.tools.get(r)?.policy:void 0,v=this.validateOutputPolicy(r||"unknown_tool",c,y);if(v)return b.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${v}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?v:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let p=await this.piiScanner.scan(c),f=this.violatesAggregationFirstPolicy(c,y?.enforceAggregationFirst,this.sandboxRecords?.length);if(p||f){let d=p||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return b.info(`[LIOP-SDK] Secure egress blocked in local execution: ${d}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${d}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:u}}catch(i){let n=i,s=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",o=n.message||String(i);return b.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:o.includes("worker_thread_exited")||o.includes("ERR_WORKER_OUT_OF_MEMORY")||o.includes("terminated")||o.includes("heap limit")?"[LIOP] Execution terminated: memory limit exceeded (64MB heap). Reduce data processing volume.":s?`WorkerPoolError: ${o}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error."}],isError:true}}}async close(){this.workerPool&&await this.workerPool.close({force:true}),this.rpcServer&&await this.rpcServer.stop(),this.meshNode&&await this.meshNode.stop();}loadRevocationList(){let e=this.config?.auth?.revocationPath;if(e)try{if(S.existsSync(e)){let t=S.statSync(e);if(t.mtimeMs<=this.lastRevocationLoadTime)return;let r=S.readFileSync(e,"utf-8"),i=JSON.parse(r);if(Array.isArray(i)){this.revokedTokenHashes.clear();for(let n of i)typeof n=="string"&&this.revokedTokenHashes.add(n.trim().toLowerCase());this.lastRevocationLoadTime=t.mtimeMs,b.info(`[LiopServer] Loaded ${this.revokedTokenHashes.size} revoked token hashes from ${e}`);}}else {let t=L.dirname(e);S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),S.writeFileSync(e,JSON.stringify([],null,2),"utf-8"),this.lastRevocationLoadTime=Date.now(),b.info(`[LiopServer] Created empty local revocation list at ${e}`);}}catch(t){b.error(`[LiopServer] Failed to load revocation list: ${t instanceof Error?t.message:String(t)}`);}}revokeToken(e){if(!e)return;let t=O__default.createHash("sha256").update(e).digest("hex").toLowerCase();this.revokeTokenHash(t);}revokeTokenHash(e){if(!e)return;let t=e.toLowerCase();this.loadRevocationList(),this.revokedTokenHashes.add(t);let r=this.config?.auth?.revocationPath;if(r)try{let i=L.dirname(r);S.existsSync(i)||S.mkdirSync(i,{recursive:!0});let n=Array.from(this.revokedTokenHashes);S.writeFileSync(r,JSON.stringify(n,null,2),"utf-8");let s=S.statSync(r);this.lastRevocationLoadTime=s.mtimeMs,b.info(`[LiopServer] Persisted revocation for hash ${t} to ${r}`);}catch(i){b.error(`[LiopServer] Failed to persist revocation: ${i instanceof Error?i.message:String(i)}`);}}resetFieldBudget(e,t){if(e==="__proto__"||e==="constructor"||e==="prototype"||t&&(t==="__proto__"||t==="constructor"||t==="prototype")){b.warn(`[LiopServer] Rejected resetFieldBudget for unsafe clientId/toolName: ${e}`);return}if(t){let i=this.fieldQueryBudget.get(e);i&&i.delete(t);}else this.fieldQueryBudget.delete(e);let r=this.config?.budgetStorePath;if(r)try{this.executeWithBudgetLock(r,i=>(t?Object.hasOwn(i,e)&&i[e]&&delete i[e][t]:Object.hasOwn(i,e)&&delete i[e],{result:void 0,updatedBudget:i})),b.info(`[LiopServer] Reset query budget for client ${e}${t?` / tool ${t}`:""}`);}catch(i){b.error(`[LiopServer] Failed to reset persistent budget: ${i instanceof Error?i.message:String(i)}`);}}getPersistentBudget(e){try{if(!S.existsSync(e))return Object.create(null);let t=S.readFileSync(e,"utf-8"),r=JSON.parse(t||"{}");if(r&&typeof r=="object"){let i=Object.create(null);for(let[n,s]of Object.entries(r))n!=="__proto__"&&n!=="constructor"&&n!=="prototype"&&(i[n]=s);return i}return Object.create(null)}catch{return Object.create(null)}}savePersistentBudget(e,t){let r=`${e}.tmp`,i=L.dirname(e);S.existsSync(i)||S.mkdirSync(i,{recursive:true}),S.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),S.renameSync(r,e);}executeWithBudgetLock(e,t){let r=`${e}.lock`,i=100,s=0,o=L.dirname(e);if(!S.existsSync(o))try{S.mkdirSync(o,{recursive:!0});}catch{}for(;s<i;)try{S.writeFileSync(r,process.pid.toString(),{flag:"wx"});break}catch(a){if(a&&typeof a=="object"&&"code"in a&&a.code==="EEXIST"){s++;}else throw a}if(s>=i)throw new Error("Timeout acquiring lock for persistent query budget database");try{let a=this.getPersistentBudget(e),{result:c,updatedBudget:l}=t(a);return l&&this.savePersistentBudget(e,l),c}finally{try{S.existsSync(r)&&S.unlinkSync(r);}catch{}}}applyInMemoryBudget(e,t,r,i){let n=this.fieldQueryBudget.get(e);n||(n=new Map,this.fieldQueryBudget.set(e,n));let s=n.get(t);s||(s=new Map,n.set(t,s));for(let o of r){let a=this.taintAnalyzer.classifyField(o,i?.sensitiveKeys),c=25,l="public";if(i?.queryBudgetPerField!==void 0?(c=i.queryBudgetPerField,l="override"):a==="forbidden"?(c=3,l="forbidden"):a==="sensitive"&&(c=8,l="sensitive"),(s.get(o)??0)>=c)return `Preflight policy rejected: Query budget exceeded for field '${o}' (max ${c} per session for ${l} fields). Rotate PQC session to reset budget.`}for(let o of r){let a=s.get(o)??0;s.set(o,a+1);}return null}};
45
- export{J as a,ve as b,Ee as c,ie as d,Se as e,H as f,q as g,be as h,X as i,R as j,Te as k,ee as l,Re as m};//# sourceMappingURL=chunk-YD2AF2M6.js.map
46
- //# sourceMappingURL=chunk-YD2AF2M6.js.map