@nekzus/liop 2.0.0-alpha.19 → 2.0.0-alpha.20

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 {f}from'../chunk-3642NPOH.js';import'../chunk-2MGFSIXN.js';import {g}from'../chunk-UK7OBXGZ.js';import'../chunk-UVTEJYHN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-V5MKJT6S.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-7I6YJS3C.js';import {a}from'../chunk-S6RJHZV2.js';import'../chunk-4C666HHU.js';import*as l from'fs';import*as w from'os';import*as u from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let o=t.endsWith("/health")?t:`${t}/health`,d=await fetch(o,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!d.ok)return null;let e=await d.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(c=>c.includes("/tcp/")&&!c.includes("/ws")&&!c.includes("/ip4/127.0.0.1/"));if(!p)return null;let r=E()?R(p):p;if(!r||r===p){let c=new URL(t).hostname;r=p.replace(/\/ip4\/[^/]+/,`/ip4/${c}`);}return r?(r+=r.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,r):null}catch{return null}}function L(t){let o=t.trim(),d=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(d.test(o)||e.test(o)||p.test(o)){let r="127.0.0.1",c=o.replace(d,`/ip4/${r}`).replace(e,`/ip4/${r}`).replace(p,`/ip4/${r}`);return c!==o&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${c}`),c}return o}function R(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}function D(t){try{let o=new URL(t);return (o.hostname==="127.0.0.1"||o.hostname==="localhost")&&(o.port==="13000"||o.port==="13001")}catch{return false}}function E(){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&&D(process.env.LIOP_NEXUS_URL)}async function M(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",a=>process.exit(a??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let o=u.join(w.homedir(),".liop"),d=u.join(o,"identity.json");l.existsSync(o)||l.mkdirSync(o,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=u.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let a=l.readFileSync(n,"utf8").trim();a&&e.push(L(a));}}s.push(process.cwd(),u.join(process.cwd(),"tests/infra/nexus-data"),o,u.join(u.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let $=u.join(n,g),v=l.readFileSync($,"utf8").trim();if(v){let S=L(v);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let a$1=L(n);e.includes(a$1)||(e.push(a$1),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${a$1}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let r=new f({name:"@nekzus/liop",version:"1.0.0"});r.enableZeroShotAutonomy();let c=new a$1({identityPath:d,bootstrapNodes:e,addressMapper:E()?R:void 0});await c.start();let f$1=new g(r,c);f$1.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
2
+ import {f}from'../chunk-WG353XMU.js';import'../chunk-2MGFSIXN.js';import {g}from'../chunk-UK7OBXGZ.js';import'../chunk-UVTEJYHN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-V5MKJT6S.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-7I6YJS3C.js';import {a}from'../chunk-S6RJHZV2.js';import'../chunk-4C666HHU.js';import*as l from'fs';import*as w from'os';import*as u from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let o=t.endsWith("/health")?t:`${t}/health`,d=await fetch(o,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!d.ok)return null;let e=await d.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(c=>c.includes("/tcp/")&&!c.includes("/ws")&&!c.includes("/ip4/127.0.0.1/"));if(!p)return null;let r=E()?R(p):p;if(!r||r===p){let c=new URL(t).hostname;r=p.replace(/\/ip4\/[^/]+/,`/ip4/${c}`);}return r?(r+=r.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,r):null}catch{return null}}function L(t){let o=t.trim(),d=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(d.test(o)||e.test(o)||p.test(o)){let r="127.0.0.1",c=o.replace(d,`/ip4/${r}`).replace(e,`/ip4/${r}`).replace(p,`/ip4/${r}`);return c!==o&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${c}`),c}return o}function R(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}function D(t){try{let o=new URL(t);return (o.hostname==="127.0.0.1"||o.hostname==="localhost")&&(o.port==="13000"||o.port==="13001")}catch{return false}}function E(){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&&D(process.env.LIOP_NEXUS_URL)}async function M(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",a=>process.exit(a??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let o=u.join(w.homedir(),".liop"),d=u.join(o,"identity.json");l.existsSync(o)||l.mkdirSync(o,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=u.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let a=l.readFileSync(n,"utf8").trim();a&&e.push(L(a));}}s.push(process.cwd(),u.join(process.cwd(),"tests/infra/nexus-data"),o,u.join(u.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let $=u.join(n,g),v=l.readFileSync($,"utf8").trim();if(v){let S=L(v);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let a$1=L(n);e.includes(a$1)||(e.push(a$1),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${a$1}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let r=new f({name:"@nekzus/liop",version:"1.0.0"});r.enableZeroShotAutonomy();let c=new a$1({identityPath:d,bootstrapNodes:e,addressMapper:E()?R:void 0});await c.start();let f$1=new g(r,c);f$1.onToolsChanged=()=>{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
  `);},setTimeout(()=>{let s=c.getRoutingTableSize?.()||0;a.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${s}`),f$1.refreshManifestCache(true).catch(()=>{});},2e3);let O=1e4,T=12e4,m=O,P=()=>{setTimeout(async()=>{let s=f$1.getCacheSize();await f$1.refreshManifestCache(true).catch(()=>{});let n=f$1.getCacheSize();n!==s?(m=O,a.info(`[LIOP-Agent] Topology change detected (${s} \u2192 ${n}). Resetting poll to ${O/1e3}s.`)):m=Math.min(Math.round(m*1.5),T),P();},m);};P();let I=(await import('readline')).createInterface({input:process.stdin,terminal:false});process.stdout.on("error",s=>{s.code==="EPIPE"&&process.exit(0);}),I.on("line",async s=>{let n=s.trim();if(n)try{let a=JSON.parse(n);if(a.method){let h=await f$1.dispatch(a);h&&process.stdout.write(`${JSON.stringify(h)}
5
5
  `);}}catch{}}),I.on("close",()=>{process.exit(0);}),a.info("[LIOP-Agent] Guarding Claude Desktop via STDIO."),a.info(`[LIOP-Agent] P2P Mesh: Joined (${e.length} bootstraps)`),a.info("[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0"),process.on("SIGINT",async()=>{await c.stop(),process.exit(0);});}M().catch(t=>{a.error(`[LIOP-Agent] Fatal Error: ${t.message}`),process.exit(1);});//# sourceMappingURL=agent.js.map
package/dist/bridge.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-HIMYXEHH.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=bridge.js.map
1
+ export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-NWZ5KZDN.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=bridge.js.map
2
2
  //# sourceMappingURL=bridge.js.map
@@ -1,3 +1,3 @@
1
1
  import {a}from'./chunk-S6RJHZV2.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var T=10,R=1800*1e3,y=60*1e3,f=class{constructor(e,r={}){this.options=r;this.app=new Hono,this.bridgeLogic=new p(e),this.activeSessions=new Map,this.maxSessionsPerIp=r.maxSessionsPerIp??T,this.sessionTimeoutMs=r.sessionTimeoutMs??R,this.setupRoutes();}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:r}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new r({sessionIdGenerator:()=>randomUUID(),onsessioninitialized:t=>{this.activeSessions.set(t,{transport:s,lastActivity:Date.now(),clientIp:e}),a.info(`[LIOP-StreamBridge] Session opened: ${t} (IP: ${e})`);}});return s.onmessage=async t=>{if(s.sessionId){let i=this.activeSessions.get(s.sessionId);i&&(i.lastActivity=Date.now());}try{let i=await this.bridgeLogic.handleJsonRpcRequest(t);i!==void 0&&await s.send(i);}catch(i){a.info("[LIOP-StreamBridge] JSON-RPC error:",i.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),a.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let r=0;for(let s of this.activeSessions.values())s.clientIp===e&&r++;return r}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[r,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(a.info(`[LIOP-StreamBridge] Evicting idle session: ${r}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(r));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),a.info("=".repeat(60)),a.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),a.info("No ZERO_TRUST_TOKEN found in environment."),a.info("A secure ephemeral token has been generated for this session:"),a.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),a.info("=".repeat(60))),this.app.use("/mcp",async(e,r)=>{let s=e.req.header("Authorization"),t=process.env.ZERO_TRUST_TOKEN;if(!s?.startsWith("Bearer ")||s.split(" ")[1]!==t)return a.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);await r();}),this.app.all("/mcp",async e=>{let r=e.req.header("mcp-session-id");if(r){let o=this.activeSessions.get(r);if(!o)return e.json({error:"Session not found"},404);o.lastActivity=Date.now();let c=await o.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(r),a.info(`[LIOP-StreamBridge] Session closed (DELETE): ${r}`)),c}let s=this.getClientIp(e),t=this.countSessionsByIp(s);return t>=this.maxSessionsPerIp?(a.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${s} (${t} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(s)).handleRequest(e.req.raw)});}async start(e){let r=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),y),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:r},t=>{a.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${t.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,r]of this.activeSessions)await r.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),a.info("[LIOP-StreamBridge] HTTP ports released."));}};var p=class{constructor(e,r={}){this.options=r;e?.constructor?.name==="LiopServer"?(this.liopServer=e,a.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let r=e.id,s=e.method,t=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(r,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(r,s,t):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(r,s,t):this.errorResponse(r,-32601,"Bridge source not configured")}async handleLiopToMcp(e,r,s){if(!this.liopServer)return null;if(r==="initialize")return this.successResponse(e,{protocolVersion:"2025-11-25",capabilities:{prompts:{},resources:{},tools:{}},serverInfo:this.liopServer.getServerInfo()});if(r!=="notifications/initialized"){if(r==="ping")return this.successResponse(e,{});if(r==="tools/list"){let t=this.liopServer.listTools();return this.successResponse(e,{tools:t})}if(r==="resources/list"){let t=this.liopServer.listResources();return this.successResponse(e,{resources:t})}if(r==="prompts/list"){let t=this.liopServer.listPrompts();return this.successResponse(e,{prompts:t})}if(r==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let t=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let t=await this.liopServer.readResource(s.uri);return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let t={name:s.name,arguments:s.arguments||{}};try{let i=await this.liopServer.callTool(t);return (i.isError?!0:await this.verifyZkReceipt(t,i))?this.successResponse(e,i):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(i){return this.errorResponse(e,-32e3,i.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,r){return {jsonrpc:"2.0",id:e,result:r}}errorResponse(e,r,s){return {jsonrpc:"2.0",id:e,error:{code:r,message:s}}}async verifyZkReceipt(e,r){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,t=r.content[0]?.text;if(t&&typeof t=="string")try{let i=JSON.parse(t);if(i.image_id||i.zk_receipt){let{LiopVerifier:o}=await import('./verifier-6M7GY4TW.js');if(!await new o().verifyZkReceipt(Buffer.from(s,"utf-8"),i.image_id,Buffer.from(i.zk_receipt||"","base64")))return !1;i.audit_status="VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",r.content[0].text=JSON.stringify(i);}}catch{}return !0}catch(s){return a.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:t}=await import('./server.js');if(this.liopServer=new t(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let i=this.legacyMcpServer;if(i._registeredTools)for(let[o,c]of Object.entries(i._registeredTools)){let a=c;this.liopServer.tool(o,a.description||"",a.inputSchema||{},async l=>await a.handler(l));}if(i._registeredResources)for(let[o,c]of Object.entries(i._registeredResources)){let a=c;this.liopServer.resource(a.name,o,a.metadata?.description||"",a.metadata?.mimeType||"application/octet-stream",async()=>(await a.readCallback(new URL(o))).contents[0].text);}}return}let r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=async()=>{a.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);};r.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),r.on("line",async t=>{if(t.trim())try{let i=JSON.parse(t),o=await this.handleJsonRpcRequest(i);o&&process.stdout.write(`${JSON.stringify(o)}
2
- `);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}};export{f as a,p as b};//# sourceMappingURL=chunk-HIMYXEHH.js.map
3
- //# sourceMappingURL=chunk-HIMYXEHH.js.map
2
+ `);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}};export{f as a,p as b};//# sourceMappingURL=chunk-NWZ5KZDN.js.map
3
+ //# sourceMappingURL=chunk-NWZ5KZDN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CACCC,CAAAA,CACQC,CAAAA,CAAmC,GAC1C,CADO,IAAA,CAAA,OAAA,CAAAA,EAER,IAAA,CAAK,GAAA,CAAM,IAAIC,IAAAA,CACf,IAAA,CAAK,WAAA,CAAc,IAAIC,EAAcH,CAAc,CAAA,CACnD,IAAA,CAAK,cAAA,CAAiB,IAAI,GAAA,CAC1B,IAAA,CAAK,gBAAA,CACJC,CAAAA,CAAQ,kBAAoBL,CAAAA,CAC7B,IAAA,CAAK,iBACJK,CAAAA,CAAQ,gBAAA,EAAoBJ,EAE7B,IAAA,CAAK,WAAA,GACN,CArBQ,IACA,UAAA,CAA8C,IAAA,CAC9C,WAAA,CACA,cAAA,CACA,cAAuD,IAAA,CACvD,gBAAA,CACA,gBAAA,CAoBR,MAAc,uBACbO,CAAAA,CACoD,CACpD,GAAM,CAAE,wCAAA,CAAAC,CAAyC,CAAA,CAAI,MAAM,OAC1D,+DACD,EACMC,CAAAA,CAAY,IAAID,CAAAA,CAAyC,CAC9D,mBAAoB,IAAME,UAAAA,EAAW,CACrC,oBAAA,CAAuBC,GAAsB,CAC5C,IAAA,CAAK,eAAe,GAAA,CAAIA,CAAAA,CAAW,CAClC,SAAA,CAAAF,CAAAA,CACA,YAAA,CAAc,IAAA,CAAK,KAAI,CACvB,QAA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,CAAC,CAAA,CAAE,IAEzB,EACD,CAEF,CACA,MACD,CAIA,IAAMG,CAAAA,CAAAA,CADW,aAAa,UAAe,CAAA,EACzB,eAAA,CAAgB,CACnC,MAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,OAChB,QAAA,CAAU,KACX,CAAC,CAAA,CAEKC,CAAAA,CAAW,SAAY,CAC5B7C,CAAAA,CAAI,IAAA,CAAK,wCAAwC,EAC7C,IAAA,CAAK,UAAA,EAAY,MAAM,IAAA,CAAK,WAAW,KAAA,EAAM,CACjD,OAAA,CAAQ,IAAA,CAAK,CAAC,EACf,CAAA,CAEA4C,EAAG,EAAA,CAAG,OAAA,CAASC,CAAQ,CAAA,CACvB,OAAA,CAAQ,EAAA,CAAG,QAAA,CAAUA,CAAQ,CAAA,CAC7B,OAAA,CAAQ,EAAA,CAAG,SAAA,CAAWA,CAAQ,CAAA,CAE9BD,CAAAA,CAAG,EAAA,CAAG,MAAA,CAAQ,MAAOE,CAAAA,EAAS,CAC7B,GAAKA,CAAAA,CAAK,IAAA,GACV,GAAI,CACH,IAAMvB,CAAAA,CAAU,KAAK,KAAA,CAAMuB,CAAI,EACzBhC,CAAAA,CAAW,MAAM,KAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CAAA,MAASoB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-HIMYXEHH.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\t// If the tool execution returned an error (e.g. policy violation), we bypass\n\t\t\t\t// ZK-Receipt verification because no cryptographic proof is generated for errors.\n\t\t\t\tconst isVerified = result.isError\n\t\t\t\t\t? true\n\t\t\t\t\t: await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
1
+ {"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CACCC,CAAAA,CACQC,CAAAA,CAAmC,GAC1C,CADO,IAAA,CAAA,OAAA,CAAAA,EAER,IAAA,CAAK,GAAA,CAAM,IAAIC,IAAAA,CACf,IAAA,CAAK,WAAA,CAAc,IAAIC,EAAcH,CAAc,CAAA,CACnD,IAAA,CAAK,cAAA,CAAiB,IAAI,GAAA,CAC1B,IAAA,CAAK,gBAAA,CACJC,CAAAA,CAAQ,kBAAoBL,CAAAA,CAC7B,IAAA,CAAK,iBACJK,CAAAA,CAAQ,gBAAA,EAAoBJ,EAE7B,IAAA,CAAK,WAAA,GACN,CArBQ,IACA,UAAA,CAA8C,IAAA,CAC9C,WAAA,CACA,cAAA,CACA,cAAuD,IAAA,CACvD,gBAAA,CACA,gBAAA,CAoBR,MAAc,uBAC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oB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-NWZ5KZDN.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\t// If the tool execution returned an error (e.g. policy violation), we bypass\n\t\t\t\t// ZK-Receipt verification because no cryptographic proof is generated for errors.\n\t\t\t\tconst isVerified = result.isError\n\t\t\t\t\t? true\n\t\t\t\t\t: await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
@@ -18,14 +18,14 @@ ${t}
18
18
  `);return this.unwrapForAggregationPolicyScan(s)}violatesAggregationFirstPolicy(t,i,r){if(!i)return false;let s=typeof i=="object"&&typeof i.maxOutputRows=="number"?i.maxOutputRows:10,a=typeof i=="object"&&typeof i.allowPrimitiveArrays=="boolean"?i.allowPrimitiveArrays:true;if(typeof t=="string"){let o=t.trim();if(o.startsWith("{")&&o.endsWith("}")||o.startsWith("[")&&o.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(o),i,r)}catch{return false}return false}if(Array.isArray(t))return t.length>0&&t.every(o=>typeof o=="object"&&o!==null)?t.length>s?true:t.some(o=>this.violatesAggregationFirstPolicy(o,i,r)):t.length>0&&t.every(o=>typeof o!="object"||o===null)?!a:t.some(o=>this.violatesAggregationFirstPolicy(o,i,r));if(t&&typeof t=="object"){let o=Object.keys(t);return r!==void 0&&r>0&&r<10&&(o.length>3||Object.values(t).some(c=>Array.isArray(c)||typeof c=="object"&&c!==null))||o.length>s?true:Object.values(t).some(u=>this.violatesAggregationFirstPolicy(u,i,r))}return false}buildEnvelopeSpec(){let t=["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","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution"];return this.config?.security?.forbiddenKeys?.length&&t.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),t.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:","- Datasets < 10 records: max 3 scalar output fields, no nesting","- Datasets >= 10 records: max 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)"),t.join(`
19
19
  `)}extractSchemaFieldSummary(t,i=0){if(i>3)return "{...}";let r=t.type,s=t.properties,a=t.items;return s?`{${Object.entries(s).map(([u,c])=>{let l=c.type;if(l==="array"&&c.items){let p=this.extractSchemaFieldSummary(c.items,i+1);return `${u}(array of ${p})`}if(l==="object"&&c.properties){let p=this.extractSchemaFieldSummary(c,i+1);return `${u}(${p})`}return `${u}(${l||"unknown"})`}).join(", ")}}`:r==="array"&&a?`Array of ${this.extractSchemaFieldSummary(a,i+1)}`:r||Object.keys(t).join(", ")}async connect(t={}){return this.connectToMesh(t)}tool(t,i,r,s,a){if(this.tools.has(t))throw new Error(`Tool already registered: ${t}`);let o=b$1.object(r),u=Ke(o),c=i,l=s;if(r.payload&&r.payload instanceof b$1.ZodString){let m=this.config?.security?.forbiddenKeys||[];if(c+=`
20
20
 
21
- Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. | Full spec: resource liop://protocol/envelope-spec`,m.length>0&&(c+=`
21
+ 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`,m.length>0&&(c+=`
22
22
  Restricted fields: ${m.join(", ")}.`),this.activeSchema){let x=this.extractSchemaFieldSummary(this.activeSchema);c+=`
23
23
  Data structure: ${x}. Full schema: resource liop://schema/global`;}l=async(x,T)=>{let k="global_connection",N=Date.now(),A=this.connectionStats.get(k)||{failures:0,lastAttempt:0};if(A.failures>=this.THROTTLE_THRESHOLD&&N-A.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let q=x.payload,_e=x.__liop_bypass_ast_cache===true,ge=Fi.createHash("sha256").update(q).digest("hex"),B=this.extractLogic(q),he=this.logicCache.get(ge);if(!_e&&he&&N-he.timestamp<this.CACHE_TTL_MS&&B){x.payload=B;let Q=this.runPreflightPolicy(t,B,a);return Q?{content:[{type:"text",text:Q}],isError:true}:await this.executeInWorkerPool(x,B,t)}if(!B)return A.failures++,A.lastAttempt=N,this.connectionStats.set(k,A),{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 Q=this.extractLogic(x.payload);x.payload=Q;let we=this.runPreflightPolicy(t,Q,a);if(we)return A.failures++,A.lastAttempt=N,this.connectionStats.set(k,A),{content:[{type:"text",text:we}],isError:!0};let ht=await this.executeInWorkerPool(x,Q,t);return ht.isError?(A.failures++,A.lastAttempt=N,this.connectionStats.set(k,A)):(this.connectionStats.set(k,{failures:0,lastAttempt:N}),this.logicCache.set(ge,{hash:ge,timestamp:N})),ht}catch(Q){let we=Q;return A.failures++,A.lastAttempt=N,this.connectionStats.set(k,A),{content:[{type:"text",text:`ExecutionRuntimeException: ${we.message}`}],isError:true}}};}let p={type:"object",properties:u.properties||{},required:u.required};this.tools.set(t,{tool:{name:t,description:c,inputSchema:p},handler:l,schema:o,policy:a}),this.meshNode&&this.meshNode.announceCapability(t).catch(m=>{a$1.info(`[LIOP-Mesh] Failed to auto-announce tool ${t}: ${m.message}`);});}prompt(t,i,r,s){if(this.prompts.has(t))throw new Error(`Prompt already registered: ${t}`);this.prompts.set(t,{prompt:{name:t,description:i,arguments:r},handler:s});}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.",[],t=>({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.
24
24
  Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
25
25
 
26
26
  INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
27
27
  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.
28
- 2. AGGREGATION FIRST: Always prefer returning counts, averages, or anonymized summaries.
28
+ 2. AGGREGATION FIRST: Always prefer returning counts, averages, or anonymized summaries. Note: If the source dataset size is small (< 10 records), K-Anonymity blocks output if it contains more than 3 keys or any nested objects/arrays.
29
29
  3. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
30
30
  Structure:
31
31
  @LIOP{wasi_v1,AnalysisTask}
@@ -39,5 +39,5 @@ CURRENT DATA DICTIONARY (STRICT):
39
39
  ${JSON.stringify(this.activeSchema,null,2)}`:""}
40
40
 
41
41
  Protocol Adherence is mandatory for successful execution.`}}]}));}resource(t,i,r,s,a){if(this.resources.has(i))throw new Error(`Resource URI already registered: ${i}`);this.resources.set(i,{name:t,uri:i,description:r,mimeType:s,content:a});}dataDictionary(t,i="Global Medical Data Dictionary",r="liop://schema/global",s="Exposes the internal database schema for Zero-Shot Autonomy planning"){this.activeSchema=t;let a=this.extractSchemaFieldSummary(t);for(let[o,u]of this.tools.entries())u.schema.shape.payload&&u.schema.shape.payload instanceof b$1.ZodString&&u.tool.description&&!u.tool.description.includes("Data structure:")&&(u.tool.description+=`
42
- Data structure: ${a}. Full schema: resource ${r}`,this.tools.set(o,u));this.resource(i,r,s,"application/json",JSON.stringify(t,null,2));}clearAstCache(){this.logicCache.clear(),a$1.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(t){let i=Date.now(),r=this.toolCallWindowMs,s=this.toolCallMaxPerWindow,o=(this.toolCallWindows.get(t)||[]).filter(u=>i-u<r);if(o.length>=s){let u=Math.ceil((o[0]+r-i)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${t}. Max ${s} per ${r/1e3}s window. Retry after ${u}s.`}],isError:true}}return o.push(i),this.toolCallWindows.set(t,o),null}checkGlobalRateLimit(){let t=Date.now(),i=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(s=>t-s<i),this.globalCallWindow.length>=r){let s=Math.ceil((this.globalCallWindow[0]+i-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${i/1e3}s window. Retry after ${s}s.`}],isError:true}}return this.globalCallWindow.push(t),null}async callTool(t){let i=this.tools.get(t.name);if(!i)throw new Error(`Tool not found: ${t.name}`);let r=this.checkGlobalRateLimit();if(r)return r;let s=this.checkToolCallRateLimit(t.name);if(s)return s;try{let a=i.schema.parse(t.arguments||{});if(t.arguments?.__liop_bypass_ast_cache===!0&&(a.__liop_bypass_ast_cache=!0),a&&typeof a.payload=="string"){let u=a.payload,c=this.extractLogic(u);if(c){let l=this.runPreflightPolicy(t.name,c,i.policy);return l?{content:[{type:"text",text:l}],isError:!0}:(a.payload=c,await this.executeInWorkerPool(a,c,t.name))}}return await i.handler(a,{})}catch(a){let o=a;return o instanceof b$1.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(t=>t.tool)}listPrompts(){return Array.from(this.prompts.values()).map(t=>t.prompt)}async getPrompt(t){let i=this.prompts.get(t.name);if(!i)throw new Error(`Prompt not found: ${t.name}`);return await i.handler(t)}listResources(){return Array.from(this.resources.values())}async readResource(t){let i=this.resources.get(t);if(!i)throw new Error(`Resource not found: ${t}`);let r="No description provided";return typeof i.content=="function"?r=await i.content():typeof i.content=="string"?r=i.content:i.description&&(r=i.description),{contents:[{uri:i.uri,mimeType:i.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(t){this.sandboxRecords=t;}getBoundPort(){return this.boundPort}async connectToMesh(t={}){let i=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=t.port??i??50051;this.meshNode=new a$2(t.meshConfig),await this.meshNode.start();let s=this.meshNode;this.meshNode.registerManifestHandler(()=>{let a=this.listTools().map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema})),o=Array.from(this.resources.values()).map(u=>({name:u.name,uri:u.uri,description:u.description,mimeType:u.mimeType,text:typeof u.content=="string"?u.content:u.description}));return {peerId:s.getPeerId(),grpcPort:r,tools:a,resources:o,serverInfo:this.serverInfo}});for(let a of this.listTools())await this.meshNode.announceCapability(a.name).catch(a$1.info);await this.meshNode.announceManifest().catch(a$1.info),this.rpcServer=new Ie,this.rpcServer.addService({negotiateIntent:(a,o)=>{let u=a.request;a$1.info(`[LIOP-RPC] Negotiating intent for capability: ${u.capability_hash}`),import('./kyber-NONMBQNH.js').then(async({Kyber768Wrapper:c})=>{let{publicKey:l,secretKey:p}=await c.generateKeyPair(),m=Fi.randomUUID();this.fieldQueryBudget.clear(),this.sessions.set(m,{capability_hash:u.capability_hash,kyber_sk:p}),o(null,{accepted:true,session_token:m,error_message:"",kyber_public_key:l});});},executeLogic:async a=>{let o=a.request;a$1.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${o.session_token}`);let u=this.sessions.get(o.session_token);if(!u){a.emit("error",{code:Ht.status.UNAUTHENTICATED,details:"Invalid session token"});return}try{let c=u.capability_hash,p=(c?this.tools.get(c):void 0)?.policy,m=p?{epsilon:p.dpEpsilon??1,sensitivity:p.dpSensitivity??1,smallDatasetThreshold:50}:void 0,x=await this.workerPool.run({ciphertext:o.pqc_ciphertext,secretKeyObj:Array.from(u.kyber_sk),wasmBinary:o.wasm_binary,inputs:o.inputs,aesNonce:o.aes_nonce,records:this.sandboxRecords,sessionToken:o.session_token,isEncrypted:!0,dpConfig:m}),T,k=x.output;try{T=typeof x.output=="string"?x.output:JSON.stringify(x.output);let B=JSON.parse(T);if(B.__liop_proxy_tool){a$1.info(`[LIOP-RPC] Executing Proxied Tool: ${B.__liop_proxy_tool}`);let he=await this.callTool({name:B.__liop_proxy_tool,arguments:B.__liop_proxy_args||{}});T=JSON.stringify(he),k=this.unwrapForAggregationPolicyScan(he);}}catch{T=String(x.output);}let N=this.validateOutputPolicy(c||"unknown_tool",k,p);if(N){a$1.info(`[LIOP-RPC] Output policy blocked for ${c||"unknown_tool"}: ${N}`);let Q={semantic_evidence:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?N:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};a.write(Q,()=>{a.end();});return}let A={semantic_evidence:T,cryptographic_proof:Buffer.from(x.image_id||"","hex"),zk_receipt:x.zk_receipt?Buffer.from(x.zk_receipt,"base64"):Buffer.from(""),is_error:!1},q=typeof k=="string"?k:JSON.stringify(k??""),_e=await this.piiScanner.scan([{type:"text",text:q}]),ge=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(k),p?.enforceAggregationFirst,this.sandboxRecords?.length);if(_e||ge){let B=_e||"Aggregation-First Policy Violation";a$1.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${B}`),A.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",A.is_error=!0;}a.write(A,()=>{a.end();});}catch(c){let l=c,p=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",m=l.message||String(c);a$1.error(`[LIOP-RPC] Execution Error: ${m}`);let T={semantic_evidence:p?`Execution Error: ${m}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{a.write(T,()=>{a.end();});}catch{a.end();}}}}),this.boundPort=await this.rpcServer.listen(r),a$1.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(t,i,r){try{let s=r?this.tools.get(r)?.policy:void 0,a=s?{epsilon:s.dpEpsilon??1,sensitivity:s.dpSensitivity??1,smallDatasetThreshold:50}:void 0,o=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(i),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1,dpConfig:a}),u=o.output,l=[{type:"text",text:JSON.stringify({computation_result:u,image_id:o.image_id,zk_receipt:o.zk_receipt,status:"Worker Pool Execution Success"})}],p=r?this.tools.get(r)?.policy:void 0,m=this.validateOutputPolicy(r||"unknown_tool",u,p);if(m)return a$1.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${m}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?m:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let x=await this.piiScanner.scan([{type:"text",text:typeof u=="string"?u:JSON.stringify(u)}]),T=this.violatesAggregationFirstPolicy(u,p?.enforceAggregationFirst,this.sandboxRecords?.length);if(x||T){let k=x||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return a$1.info(`[LIOP-SDK] Secure egress blocked in local execution: ${k}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${k}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:l}}catch(s){let a=s,o=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",u=a.message||String(s);return a$1.error(`[LIOP-SDK] WorkerPool Execution Fault: ${u}`),{content:[{type:"text",text:u.includes("worker_thread_exited")||u.includes("ERR_WORKER_OUT_OF_MEMORY")||u.includes("terminated")||u.includes("heap limit")?"[LIOP] Execution terminated: memory limit exceeded (64MB heap). Reduce data processing volume.":o?`WorkerPoolError: ${u}`:"[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();}};export{Ie as a,We as b,L as c,Vi as d,Ze as e,Bi as f};//# sourceMappingURL=chunk-3642NPOH.js.map
43
- //# sourceMappingURL=chunk-3642NPOH.js.map
42
+ Data structure: ${a}. Full schema: resource ${r}`,this.tools.set(o,u));this.resource(i,r,s,"application/json",JSON.stringify(t,null,2));}clearAstCache(){this.logicCache.clear(),a$1.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(t){let i=Date.now(),r=this.toolCallWindowMs,s=this.toolCallMaxPerWindow,o=(this.toolCallWindows.get(t)||[]).filter(u=>i-u<r);if(o.length>=s){let u=Math.ceil((o[0]+r-i)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${t}. Max ${s} per ${r/1e3}s window. Retry after ${u}s.`}],isError:true}}return o.push(i),this.toolCallWindows.set(t,o),null}checkGlobalRateLimit(){let t=Date.now(),i=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(s=>t-s<i),this.globalCallWindow.length>=r){let s=Math.ceil((this.globalCallWindow[0]+i-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${i/1e3}s window. Retry after ${s}s.`}],isError:true}}return this.globalCallWindow.push(t),null}async callTool(t){let i=this.tools.get(t.name);if(!i)throw new Error(`Tool not found: ${t.name}`);let r=this.checkGlobalRateLimit();if(r)return r;let s=this.checkToolCallRateLimit(t.name);if(s)return s;try{let a=i.schema.parse(t.arguments||{});if(t.arguments?.__liop_bypass_ast_cache===!0&&(a.__liop_bypass_ast_cache=!0),a&&typeof a.payload=="string"){let u=a.payload,c=this.extractLogic(u);if(c){let l=this.runPreflightPolicy(t.name,c,i.policy);return l?{content:[{type:"text",text:l}],isError:!0}:(a.payload=c,await this.executeInWorkerPool(a,c,t.name))}}return await i.handler(a,{})}catch(a){let o=a;return o instanceof b$1.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(t=>t.tool)}listPrompts(){return Array.from(this.prompts.values()).map(t=>t.prompt)}async getPrompt(t){let i=this.prompts.get(t.name);if(!i)throw new Error(`Prompt not found: ${t.name}`);return await i.handler(t)}listResources(){return Array.from(this.resources.values())}async readResource(t){let i=this.resources.get(t);if(!i)throw new Error(`Resource not found: ${t}`);let r="No description provided";return typeof i.content=="function"?r=await i.content():typeof i.content=="string"?r=i.content:i.description&&(r=i.description),{contents:[{uri:i.uri,mimeType:i.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(t){this.sandboxRecords=t;}getBoundPort(){return this.boundPort}async connectToMesh(t={}){let i=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=t.port??i??50051;this.meshNode=new a$2(t.meshConfig),await this.meshNode.start();let s=this.meshNode;this.meshNode.registerManifestHandler(()=>{let a=this.listTools().map(u=>({name:u.name,description:u.description,inputSchema:u.inputSchema})),o=Array.from(this.resources.values()).map(u=>({name:u.name,uri:u.uri,description:u.description,mimeType:u.mimeType,text:typeof u.content=="string"?u.content:u.description}));return {peerId:s.getPeerId(),grpcPort:r,tools:a,resources:o,serverInfo:this.serverInfo}});for(let a of this.listTools())await this.meshNode.announceCapability(a.name).catch(a$1.info);await this.meshNode.announceManifest().catch(a$1.info),this.rpcServer=new Ie,this.rpcServer.addService({negotiateIntent:(a,o)=>{let u=a.request;a$1.info(`[LIOP-RPC] Negotiating intent for capability: ${u.capability_hash}`),import('./kyber-NONMBQNH.js').then(async({Kyber768Wrapper:c})=>{let{publicKey:l,secretKey:p}=await c.generateKeyPair(),m=Fi.randomUUID();this.fieldQueryBudget.clear(),this.sessions.set(m,{capability_hash:u.capability_hash,kyber_sk:p}),o(null,{accepted:true,session_token:m,error_message:"",kyber_public_key:l});});},executeLogic:async a=>{let o=a.request;a$1.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${o.session_token}`);let u=this.sessions.get(o.session_token);if(!u){a.emit("error",{code:Ht.status.UNAUTHENTICATED,details:"Invalid session token"});return}try{let c=u.capability_hash,p=(c?this.tools.get(c):void 0)?.policy,m=p?{epsilon:p.dpEpsilon??1,sensitivity:p.dpSensitivity??1,smallDatasetThreshold:50}:void 0,x=await this.workerPool.run({ciphertext:o.pqc_ciphertext,secretKeyObj:Array.from(u.kyber_sk),wasmBinary:o.wasm_binary,inputs:o.inputs,aesNonce:o.aes_nonce,records:this.sandboxRecords,sessionToken:o.session_token,isEncrypted:!0,dpConfig:m}),T,k=x.output;try{T=typeof x.output=="string"?x.output:JSON.stringify(x.output);let B=JSON.parse(T);if(B.__liop_proxy_tool){a$1.info(`[LIOP-RPC] Executing Proxied Tool: ${B.__liop_proxy_tool}`);let he=await this.callTool({name:B.__liop_proxy_tool,arguments:B.__liop_proxy_args||{}});T=JSON.stringify(he),k=this.unwrapForAggregationPolicyScan(he);}}catch{T=String(x.output);}let N=this.validateOutputPolicy(c||"unknown_tool",k,p);if(N){a$1.info(`[LIOP-RPC] Output policy blocked for ${c||"unknown_tool"}: ${N}`);let Q={semantic_evidence:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?N:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};a.write(Q,()=>{a.end();});return}let A={semantic_evidence:T,cryptographic_proof:Buffer.from(x.image_id||"","hex"),zk_receipt:x.zk_receipt?Buffer.from(x.zk_receipt,"base64"):Buffer.from(""),is_error:!1},q=typeof k=="string"?k:JSON.stringify(k??""),_e=await this.piiScanner.scan([{type:"text",text:q}]),ge=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(k),p?.enforceAggregationFirst,this.sandboxRecords?.length);if(_e||ge){let B=_e||"Aggregation-First Policy Violation";a$1.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${B}`),A.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",A.is_error=!0;}a.write(A,()=>{a.end();});}catch(c){let l=c,p=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",m=l.message||String(c);a$1.error(`[LIOP-RPC] Execution Error: ${m}`);let T={semantic_evidence:p?`Execution Error: ${m}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{a.write(T,()=>{a.end();});}catch{a.end();}}}}),this.boundPort=await this.rpcServer.listen(r),a$1.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(t,i,r){try{let s=r?this.tools.get(r)?.policy:void 0,a=s?{epsilon:s.dpEpsilon??1,sensitivity:s.dpSensitivity??1,smallDatasetThreshold:50}:void 0,o=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(i),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1,dpConfig:a}),u=o.output,l=[{type:"text",text:JSON.stringify({computation_result:u,image_id:o.image_id,zk_receipt:o.zk_receipt,status:"Worker Pool Execution Success"})}],p=r?this.tools.get(r)?.policy:void 0,m=this.validateOutputPolicy(r||"unknown_tool",u,p);if(m)return a$1.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${m}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?m:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let x=await this.piiScanner.scan([{type:"text",text:typeof u=="string"?u:JSON.stringify(u)}]),T=this.violatesAggregationFirstPolicy(u,p?.enforceAggregationFirst,this.sandboxRecords?.length);if(x||T){let k=x||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return a$1.info(`[LIOP-SDK] Secure egress blocked in local execution: ${k}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${k}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:l}}catch(s){let a=s,o=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",u=a.message||String(s);return a$1.error(`[LIOP-SDK] WorkerPool Execution Fault: ${u}`),{content:[{type:"text",text:u.includes("worker_thread_exited")||u.includes("ERR_WORKER_OUT_OF_MEMORY")||u.includes("terminated")||u.includes("heap limit")?"[LIOP] Execution terminated: memory limit exceeded (64MB heap). Reduce data processing volume.":o?`WorkerPoolError: ${u}`:"[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();}};export{Ie as a,We as b,L as c,Vi as d,Ze as e,Bi as f};//# sourceMappingURL=chunk-WG353XMU.js.map
43
+ //# sourceMappingURL=chunk-WG353XMU.js.map