@nekzus/liop 2.5.0-beta.1 → 2.5.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +19 -0
- package/README.md +148 -69
- package/dist/bin/agent.js +27 -303
- package/dist/bridge.d.ts +4 -3
- package/dist/bridge.js +1 -4
- package/dist/chunk-2XHSALII.js +3 -0
- package/dist/chunk-2ZYX736J.js +2 -0
- package/dist/chunk-3WRKTVOF.js +2 -0
- package/dist/chunk-6KFKO6ZX.js +2 -0
- package/dist/chunk-6VK2XALI.js +2 -0
- package/dist/chunk-AYDF3IFZ.js +2 -0
- package/dist/chunk-CTTTLCGL.js +31 -0
- package/dist/chunk-ECRS6N33.js +4 -0
- package/dist/chunk-FDJMH4CB.js +2 -0
- package/dist/chunk-FTF6AMF6.js +2 -0
- package/dist/chunk-GWVSCZUS.js +2 -0
- package/dist/chunk-LEXMMIQI.js +15 -0
- package/dist/chunk-LM26HOJ6.js +31 -0
- package/dist/chunk-MQ5SU26J.js +2 -0
- package/dist/chunk-N35BC62H.js +2 -0
- package/dist/chunk-P6IJ3VBD.js +3 -0
- package/dist/chunk-TKLRW52V.js +2 -0
- package/dist/chunk-V35CXJQN.js +2 -0
- package/dist/chunk-WP5ER7RH.js +3 -0
- package/dist/chunk-XLVEDKM6.js +2 -0
- package/dist/chunk-Y675R34Z.js +2 -0
- package/dist/chunk-YD2AF2M6.js +46 -0
- package/dist/chunk-YLCNV764.js +3 -0
- package/dist/chunk-ZZMSFCJP.js +3 -0
- package/dist/client.d.ts +6 -4
- package/dist/client.js +1 -9
- package/dist/gateway.d.ts +6 -5
- package/dist/gateway.js +1 -10
- package/dist/{hybrid-CF__0YnC.d.ts → hybrid-BZpCiUaV.d.ts} +6 -5
- package/dist/{index-cMV0_yD9.d.ts → index-BYDtRGue.d.ts} +45 -36
- package/dist/{index-BW95kAL4.d.ts → index-ByzjpRCk.d.ts} +37 -72
- package/dist/index.d.ts +221 -50
- package/dist/index.js +4 -312
- package/dist/kyber-PULV7PQX.js +2 -0
- package/dist/mesh.d.ts +27 -143
- package/dist/mesh.js +1 -4
- package/dist/node-Djzm6UYd.d.ts +172 -0
- package/dist/protocol/liop_core.proto +25 -6
- package/dist/server.d.ts +4 -3
- package/dist/server.js +1 -7
- package/dist/types-29zv9X1V.d.ts +455 -0
- package/dist/types.d.ts +2 -1
- package/dist/types.js +1 -2
- package/dist/verifier-DqZ9MQ9l.d.ts +82 -0
- package/dist/verifier-J4NQYZX5.js +2 -0
- package/dist/workers/logic-execution.d.ts +7 -0
- package/dist/workers/logic-execution.js +1 -271
- package/dist/workers/zk-verifier.d.ts +9 -0
- package/dist/workers/zk-verifier.js +1 -173
- package/dist/zk-DzYNWBgo.d.ts +104 -0
- package/package.json +56 -45
- package/dist/bin/agent.js.map +0 -1
- package/dist/bridge.js.map +0 -1
- package/dist/chunk-32ADSAJS.js +0 -104
- package/dist/chunk-32ADSAJS.js.map +0 -1
- package/dist/chunk-547TYL27.js +0 -208109
- package/dist/chunk-547TYL27.js.map +0 -1
- package/dist/chunk-72MNYFR6.js +0 -64
- package/dist/chunk-72MNYFR6.js.map +0 -1
- package/dist/chunk-74CISO2I.js +0 -853
- package/dist/chunk-74CISO2I.js.map +0 -1
- package/dist/chunk-CRZBVFDV.js +0 -616
- package/dist/chunk-CRZBVFDV.js.map +0 -1
- package/dist/chunk-GA3Q2S7O.js +0 -558
- package/dist/chunk-GA3Q2S7O.js.map +0 -1
- package/dist/chunk-JIJPZFR2.js +0 -51
- package/dist/chunk-JIJPZFR2.js.map +0 -1
- package/dist/chunk-OUUTDSOW.js +0 -24
- package/dist/chunk-OUUTDSOW.js.map +0 -1
- package/dist/chunk-PYKRQAER.js +0 -77
- package/dist/chunk-PYKRQAER.js.map +0 -1
- package/dist/chunk-QLCOEP5J.js +0 -68
- package/dist/chunk-QLCOEP5J.js.map +0 -1
- package/dist/chunk-RWRRBYG4.js +0 -3
- package/dist/chunk-RWRRBYG4.js.map +0 -1
- package/dist/chunk-SONUORBT.js +0 -421
- package/dist/chunk-SONUORBT.js.map +0 -1
- package/dist/chunk-T5IUZF47.js +0 -716
- package/dist/chunk-T5IUZF47.js.map +0 -1
- package/dist/chunk-U5BZ66VX.js +0 -447
- package/dist/chunk-U5BZ66VX.js.map +0 -1
- package/dist/chunk-WCCGE4QR.js +0 -3520
- package/dist/chunk-WCCGE4QR.js.map +0 -1
- package/dist/chunk-WSW6YJNY.js +0 -168
- package/dist/chunk-WSW6YJNY.js.map +0 -1
- package/dist/client.js.map +0 -1
- package/dist/gateway.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/kyber-3ULIJSE3.js +0 -3
- package/dist/kyber-3ULIJSE3.js.map +0 -1
- package/dist/mesh.js.map +0 -1
- package/dist/server.js.map +0 -1
- package/dist/types-lJIxBlWF.d.ts +0 -256
- package/dist/types.js.map +0 -1
- package/dist/verifier-3FAKCFNN.js +0 -5
- package/dist/verifier-3FAKCFNN.js.map +0 -1
- package/dist/verifier-COnid_dg.d.ts +0 -31
- package/dist/workers/logic-execution.js.map +0 -1
- package/dist/workers/zk-verifier.js.map +0 -1
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-6KFKO6ZX.js';import {a as a$3}from'./chunk-Y675R34Z.js';import {a as a$2}from'./chunk-XLVEDKM6.js';import {b as b$2}from'./chunk-2ZYX736J.js';import {f,g as g$1,i,j}from'./chunk-ECRS6N33.js';import {f as f$2,g as g$2,u,v,m,w}from'./chunk-ZZMSFCJP.js';import {h,d,e,b as b$1,c,f as f$1,g}from'./chunk-GWVSCZUS.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as D from'crypto';import*as H from'@grpc/grpc-js';function M(){let I=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(I==="0"||I==="false"||I==="no")}a(M,"mcpCompactToolDescriptions");function F(I){let o=I,p=[`
|
|
2
|
+
|
|
3
|
+
[LIOP-PROTO-V1:`,`\r
|
|
4
|
+
\r
|
|
5
|
+
[LIOP-PROTO-V1:`,`
|
|
6
|
+
[LIOP-PROTO-V1:`];for(let n of p){let a=o.indexOf(n);if(a!==-1){o=o.slice(0,a);break}}return o.trimEnd()}a(F,"stripVerboseLiopToolDescription");var ae=300,B=5,ce=class I{constructor(o,p=null,n=50051){this.liopServer=o;this.meshNode=p;this.defaultRpcPort=n;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let a=this.liopServer.listTools().map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema})),c=this.liopServer.listResources().map(s=>({name:s.name,uri:s.uri,description:s.description,mimeType:s.mimeType})),e=this.liopServer.config;return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...a],resources:c,serverInfo:this.liopServer.getServerInfo(),authRequired:this.liopServer.jwtValidator!==void 0,tokenSlug:e?.tokenSlug,taxonomy:e?.taxonomy?{domain:e.taxonomy.domain||"Unknown Domain",clearanceTier:e.taxonomy.clearanceTier??0,executionTypes:e.taxonomy.executionTypes||[]}:void 0}}),this.meshNode.announceManifest().catch(a=>{b.info(`[LIOP-Router] Failed to announce manifest: ${a instanceof Error?a.message:String(a)}`);})),process.env.LIOP_DIAGNOSTIC_LEVEL==="full"&&process.stderr.write(`\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.
|
|
7
|
+
`);}liopServer;meshNode;defaultRpcPort;static{a(this,"LiopMcpRouter");}manifestCache=new Map;currentDiscovery=null;verifier=new a$1;onToolsChanged;manifestFailureState=new Map;static MANIFEST_FAILURE_BASE_COOLDOWN_MS=15e3;static MANIFEST_FAILURE_MAX_COOLDOWN_MS=5*6e4;static MANIFEST_SKIP_LOG_THROTTLE_MS=3e4;getManifestCacheSize(){return this.manifestCache.size}shouldSkipManifestQuery(o){let p=this.manifestFailureState.get(o);if(!p)return false;let n=Date.now();return n>=p.cooldownUntil?false:(n-p.lastSkipLogAt>I.MANIFEST_SKIP_LOG_THROTTLE_MS&&(b.info(`[LIOP-Router] Skipping manifest query for ${o} during cooldown (${Math.ceil((p.cooldownUntil-n)/1e3)}s remaining)`),p.lastSkipLogAt=n),true)}recordManifestQuerySuccess(o){this.manifestFailureState.delete(o);}recordManifestQueryFailure(o){let p=Date.now(),a=(this.manifestFailureState.get(o)?.failures||0)+1,c=Math.min(I.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,a-1),I.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(o,{failures:a,cooldownUntil:p+c,lastSkipLogAt:0});}detectEra(o){return o.params?._meta?.["io.modelcontextprotocol/protocolVersion"]===h?"modern":d(o)?"legacy":"modern"}async dispatch(o,p){let{method:n,params:a,id:c$1}=o;if(b.info(`[LIOP-Router] Processing: ${n}`),this.liopServer.jwtValidator){let e=a$2(n,p??null);if(!e.allowed)return b.info(`[LIOP-Router] RBAC Access Denied for method '${n}': ${e.reason}`),{jsonrpc:"2.0",id:c$1,error:{code:-32099,message:e.reason||"Access Denied"}}}switch(n){case "initialize":return b.info("[LIOP-Router] \u26A0\uFE0F Legacy MCP client detected (2025-era initialize)."),c(this.liopServer.getServerInfo(),c$1);case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "server/discover":return {jsonrpc:"2.0",id:c$1,result:{resultType:"complete",supportedVersions:[h,b$1],capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "ping":return {jsonrpc:"2.0",id:c$1,result:{}};case "tools/list":{let e$1=this.liopServer.listTools(),s=await this.getRemoteTools(),r=M()?e$1.map(g=>({...g,description:F(g.description??"")})):e$1;b.info(`[LIOP-Router] tools/list: ${e$1.length} local, ${s.length} remote tools found`);let u=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...r,...s].sort((g,y)=>g.name.localeCompare(y.name)),t=f.getInstance(),i=JSON.stringify(u),f$1=JSON.stringify({tools:u});t.record({type:"tools_list",method:"tools/list",estimatedInputTokens:t.countTokens(i),estimatedOutputTokens:t.countTokens(f$1)});let h=this.detectEra(o),m={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:u}};return h==="legacy"&&true&&(m=e(m)),m}case "tools/call":{let e$1=await this.transcodeMcpToLiop(c$1,a,p?.token);if(!e$1)return null;if(this.detectEra(o)==="legacy"&&true)return e(e$1);if(e$1.result&&typeof e$1.result=="object"){let r=e$1.result;r.resultType||(r.resultType="complete");}return e$1}case "resources/list":{let e$1=this.liopServer.listResources(),s=await this.getRemoteResources(),r=[...e$1,...s].sort((f,h)=>f.uri.localeCompare(h.uri)),l=f.getInstance(),u=JSON.stringify(r);l.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:l.countTokens(u)});let t=this.detectEra(o),i={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resources:r}};return t==="legacy"&&true&&(i=e(i)),i}case "resources/read":{let e$1=a;if(!e$1?.uri)return {jsonrpc:"2.0",id:c$1,error:{code:-32602,message:"Missing resource uri"}};try{let s=Date.now(),r=await this.liopServer.readResource(e$1.uri),l=f.getInstance(),u=JSON.stringify(r);l.record({type:"resource_read",method:"resources/read",toolName:e$1.uri,estimatedInputTokens:l.countTokens(e$1.uri),estimatedOutputTokens:l.countTokens(u),durationMs:Date.now()-s});let t=this.detectEra(o),i=typeof r=="object"&&r!==null?{resultType:"complete",ttlMs:6e4,cacheScope:"private",...r}:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:r},f$1={jsonrpc:"2.0",id:c$1,result:i};return t==="legacy"&&!0&&(f$1=e(f$1)),f$1}catch(s){let r=e$1.uri;for(let{manifest:l}of this.manifestCache.values()){let u=l.resources.find(t=>t.uri===r);if(u){b.info(`[LIOP-Router] Resolved resource ${r} from cache (Peer: ${l.peerId})`);let t=this.detectEra(o),i={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:[{uri:u.uri,mimeType:u.mimeType||"text/plain",text:u.text||u.description||"No content provided"}]}};return t==="legacy"&&true&&(i=e(i)),i}}return {jsonrpc:"2.0",id:c$1,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}case "prompts/list":{let e$1=this.liopServer.listPrompts().sort((t,i)=>t.name.localeCompare(i.name)),s=f.getInstance(),r=JSON.stringify(e$1);s.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:s.countTokens(r)});let l=this.detectEra(o),u={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",prompts:e$1}};return l==="legacy"&&true&&(u=e(u)),u}case "prompts/get":{let e$1=a;if(!e$1?.name)return {jsonrpc:"2.0",id:c$1,error:{code:-32602,message:"Missing prompt name"}};try{let s=Date.now(),r=await this.liopServer.getPrompt({name:e$1.name,arguments:e$1.arguments||{}}),l=f.getInstance(),u=JSON.stringify({name:e$1.name,arguments:e$1.arguments}),t=JSON.stringify(r);l.record({type:"prompt_get",method:"prompts/get",toolName:e$1.name,estimatedInputTokens:l.countTokens(u),estimatedOutputTokens:l.countTokens(t),durationMs:Date.now()-s});let i=this.detectEra(o),f$1=typeof r=="object"&&r!==null?{resultType:"complete",...r}:r,h={jsonrpc:"2.0",id:c$1,result:f$1};return i==="legacy"&&!0&&(h=e(h)),h}catch(s){return {jsonrpc:"2.0",id:c$1,error:{code:-32e3,message:s instanceof Error?s.message:String(s)}}}}case "resources/templates/list":{let e$1=this.detectEra(o),s={jsonrpc:"2.0",id:c$1,result:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resourceTemplates:[]}};return e$1==="legacy"&&true&&(s=e(s)),s}case "subscriptions/listen":{let e$1=this.detectEra(o),s={jsonrpc:"2.0",id:c$1,result:{resultType:"complete"}};return e$1==="legacy"&&true&&(s=e(s)),s}default:return {jsonrpc:"2.0",id:c$1,error:{code:-32601,message:`Method not found: ${n}`}}}}kickDiscoveryAfterInitialized(){return (async()=>{await new Promise(o=>setTimeout(o,250)),await Promise.race([this.refreshManifestCache(true),new Promise(o=>setTimeout(o,15e3))]).catch(()=>{});})()}async refreshManifestCache(o=false){if(this.meshNode){if(this.currentDiscovery)return this.currentDiscovery;if(!o&&this.manifestCache.size>0){let p=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:a})=>p-a<ae*1e3))return}return this.currentDiscovery=(async()=>{try{let p=Array.from(this.manifestCache.values()).reduce((t,{manifest:i})=>t+i.tools.length,0);if(this.manifestCache.size===0)for(let t=0;t<3;t++){if((this.meshNode.node?.getConnections().length||0)>0){b.info("[LIOP-Router] P2P Connection established. Starting discovery...");break}b.info(`[LIOP-Router] Waiting for P2P connections (attempt ${t+1}/10)...`),await new Promise(f=>setTimeout(f,1e3));}let n=[],a=this.manifestCache.size===0?5:1;for(let t=0;t<a;t++){for(let m=0;m<B;m++){n=await this.meshNode?.discoverManifestProviders()||[];let g=this.meshNode?.getPeerId();if(n.filter(v=>v!==g).length>0)break;m<B-1&&(b.info(`[LIOP-Router] DHT discovery attempt ${m+1}/${B}...`),await new Promise(v=>setTimeout(v,1e3)));}let i=this.meshNode.node?.getConnections().map(m=>m.remotePeer.toString())||[];i.length>0&&(n=Array.from(new Set([...n,...i])));let f=this.meshNode?.getPeerId();if(n.filter(m=>m!==f).length>0)break;t<a-1&&(b.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${t+1}/${a})...`),await new Promise(m=>setTimeout(m,1e3)));}if(n.length===0){b.info("[LIOP-Router] No manifest providers found after all attempts.");return}o||b.info(`[LIOP-Router] Discovered ${n.length} candidate manifest providers`);let c=new Set((this.meshNode.node?.getConnections?.()||[]).map(t=>t.remotePeer.toString()));n=[...n].sort((t,i)=>{let f=c.has(t)?1:0;return (c.has(i)?1:0)-f});let e=0,s=0,r=!1,l=this.meshNode?.getPeerId(),u=n.filter(t=>{if(!this.meshNode||t===l||this.shouldSkipManifestQuery(t))return !1;let i=this.manifestCache.get(t);return i&&Date.now()-i.cachedAt<ae*1e3?(e++,!1):!0});await Promise.allSettled(u.map(async t=>{if(this.meshNode){b.info(`[LIOP-Router] Querying manifest from: ${t}`);try{let i=await this.meshNode.queryManifest(t);if(i){if(i.pqcSignature&&i.pqcPublicKey){if(!b$2.verifyManifest(i,i.pqcSignature,i.pqcPublicKey)){b.warn(`[LIOP-Router] \u26A0\uFE0F Tampered manifest rejected for peer ${t} (ML-DSA-65 signature invalid)`),this.recordManifestQueryFailure(t),s++;return}b.info(`[LIOP-Router] \u{1F512} ML-DSA-65 (FIPS 204) Manifest attestation verified for peer ${t}`);}this.manifestCache.set(t,{manifest:i,cachedAt:Date.now()}),this.recordManifestQuerySuccess(t),r=!0,e++,b.info(`[LIOP-Router] Manifest received from ${t} (${i.tools.length} tools)`);}else this.recordManifestQueryFailure(t),s++,b.info(`[LIOP-Router] Manifest query returned NULL for ${t}`);}catch(i){s++,b.info("[LIOP-Router] Fatal error querying manifest:",i instanceof Error?i.message:String(i));}}})),this._discoveryStats={candidates:n.length,success:e,failures:s,lastDiscovery:Date.now()},r&&Array.from(this.manifestCache.values()).reduce((i,{manifest:f})=>i+f.tools.length,0)!==p&&this.onToolsChanged&&(process.stderr.write(`[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.
|
|
8
|
+
`),this.onToolsChanged());}finally{this.currentDiscovery=null;}})(),this.currentDiscovery}}getCacheSize(){return this.manifestCache.size}async getRemoteTools(){let o=Number.parseInt(process.env.LIOP_EXPECTED_PROVIDERS??"1",10);if(this.manifestCache.size<o&&this.meshNode){let c=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),e=Number.isFinite(c)&&c>0?c:12e3,s=Date.now()+e,r=0,l=-1;for(;Date.now()<s&&!(this.manifestCache.size>=o||(await Promise.race([this.refreshManifestCache(true),new Promise(u=>setTimeout(u,3e3))]).catch(()=>{}),this.manifestCache.size>=o));){if(this.manifestCache.size===l){if(r++,r>=3&&this.manifestCache.size>0){b.info(`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${o}. Proceeding with available mesh.`);break}}else r=0,l=this.manifestCache.size;await new Promise(u=>setTimeout(u,1e3));}this.manifestCache.size<o&&(b.info(`[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${o} providers. Some tools may be unavailable. Check Docker containers.`),this.refreshManifestCache(true).catch(()=>{}));}let p=[],n=new Set,a=new Set(this.liopServer.listTools().map(c=>c.name));for(let[c,{manifest:e}]of this.manifestCache.entries())for(let s of e.tools){if(s.name==="LiopMeshStatus")continue;let r=s.name;(n.has(s.name)||a.has(s.name))&&(r=`${s.name}_${c.slice(-4)}`),n.add(r);let l=e.serverInfo?.name||"Unknown Provider",u=s.description||`Remote tool from ${l}`,t={name:r,description:M()?F(u):u,inputSchema:s.inputSchema||{type:"object",properties:{}}};typeof t.inputSchema=="object"&&!t.inputSchema.type&&(t.inputSchema.type="object"),typeof t.inputSchema=="object"&&!t.inputSchema.properties&&(t.inputSchema.properties={});let i="";e.taxonomy&&(i=`
|
|
9
|
+
[LIOP-DOMAIN: ${e.taxonomy.domain}]`);let f=t.inputSchema.properties||{},h="";!M()&&f.payload&&(h=`
|
|
10
|
+
[REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!M()&&t.description.includes("STRICT SCHEMA ADHERENCE")&&(t.description=t.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let m=M()?`
|
|
11
|
+
(Peer: ${c.slice(-8)})${i}`:`
|
|
12
|
+
(Origin: ${c.slice(-8)})${i}${h}`;t.description=`${t.description}${m}`,p.push(t);}return p}async getRemoteResources(){this.currentDiscovery||this.refreshManifestCache(true).catch(()=>{});let o=[],p=new Set(this.liopServer.listResources().map(n=>n.uri));for(let[n,{manifest:a}]of this.manifestCache.entries())for(let c of a.resources)if(!p.has(c.uri)){let e={...c},s=a.serverInfo?.name||"Unknown Provider",r="";a.taxonomy&&(r=`
|
|
13
|
+
|
|
14
|
+
[LIOP Zero-Trust Blueprint]
|
|
15
|
+
Domain: ${a.taxonomy.domain}
|
|
16
|
+
Clearance Tier: ${a.taxonomy.clearanceTier}`,a.taxonomy.executionTypes&&a.taxonomy.executionTypes.length>0&&(r+=`
|
|
17
|
+
Execution Types: ${a.taxonomy.executionTypes.join(", ")}`));let l=`
|
|
18
|
+
|
|
19
|
+
[LIOP Zero-Trust Origin]
|
|
20
|
+
Provider: ${s}
|
|
21
|
+
Network ID: ${n}${r}`;e.uri.startsWith("liop://schema/")?(e.name=`[SCHEMA] ${e.name}`,e.description=`[CRITICAL SCHEMA] ${e.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):e.description=e.description?`${e.description}${l}`:l.trim(),o.push(e),p.add(c.uri);}return o}resolveManifestTarget(o){let p=f$1[o]||o;for(let[a,{manifest:c}]of this.manifestCache.entries()){let e=c.tools.find(s=>s.name===o||s.name===p);if(e)return {peerId:a,originalToolName:e.name}}let n=o.split("_");if(n.length>1){let a=n.pop(),c=n.join("_"),e=f$1[c]||c;for(let[s,{manifest:r}]of this.manifestCache.entries())if(s.endsWith(a||"")){let l=r.tools.find(u=>u.name===c||u.name===e);if(l)return {peerId:s,originalToolName:l.name}}}return null}redactPeerId(o){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?o:`***${o.slice(-8)}`}async transcodeMcpToLiop(o,p,n){p?.arguments&&(p.arguments=g(p.arguments));let a=p.name;if(a==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let e=this._discoveryStats||{candidates:0,success:0,failures:0},s=this.manifestCache.size,r=this.meshNode?"Active":"Offline",l=Array.from(this.manifestCache.values()).reduce((P,{manifest:L})=>P+L.tools.length,0),u=this.meshNode?this.meshNode.node?.getConnections().length:0,t=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],i=t.length,h=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",m=h?t.map(P=>{let L=P.split("/"),C=L[L.length-1];return ` \u2022 ${C?C.slice(-8):"Unknown"} (bootstrap)`}).join(`
|
|
22
|
+
`):"",g=this.meshNode?this.meshNode.getRoutingTableSize():0,y=this.meshNode?.getPeerId()||"Offline",v=y==="Offline"?y:this.redactPeerId(y),E=Array.from(this.manifestCache.entries()).flatMap(([P,{manifest:L}])=>L.tools.map(C=>` \u2022 ${C.name} (from origin: ${this.redactPeerId(P)})`)).join(`
|
|
23
|
+
`),_=[`LIOP Mesh Status: ${r==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${v}`,`Network: ${u} Conns | ${g} Mesh Nodes | ${i} Bootstraps`,h&&i>0?`
|
|
24
|
+
Active Bootstraps:
|
|
25
|
+
${m}
|
|
26
|
+
`:"",`Discovery: ${e.candidates} Candidates | ${e.success} OK | ${e.failures} FAIL`,`Tooling: ${s} Providers | ${l} Total Remote Tools`,l>0?`
|
|
27
|
+
Discovered Remote Tools (Zero-Trust Origins):
|
|
28
|
+
${E}`:`
|
|
29
|
+
No remote tools discovered yet.`,f.getInstance().formatStatusBlock()].filter(P=>P!=="").join(`
|
|
30
|
+
`),w=f.getInstance();return w.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:w.countTokens(_)}),{jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:_}]}}}let c=this.liopServer.listTools().some(e=>e.name===a);if(!c&&this.meshNode){let e=this.resolveManifestTarget(a);if(e||(await this.refreshManifestCache(),e=this.resolveManifestTarget(a)),e){b.info(`[LIOP-Router] Resolved ${a} via manifest cache (Peer: ${e.peerId}, Original: ${e.originalToolName})`);let r=this.manifestCache.get(e.peerId),l=n;if(r?.manifest.authRequired){let u=n||await this.getOrAcquireMeshAgentToken(e.peerId);if(!u){let t=r.manifest.serverInfo?.name?.toLowerCase()||"unknown",i=r.manifest.tokenSlug,f=e.peerId.slice(-8).toUpperCase(),h=i?`LIOP_TOKEN_${i}`:`LIOP_TOKEN_${t.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${t}) requires an access token. Please define the ${h} or LIOP_TOKEN_${f} environment variable on your agent/client host.`}],isError:true}}}l=u;}return this.routeToRemoteProvider(o,e.originalToolName,e.peerId,p,l)}let s=[];for(let r=0;r<3&&(s=await this.meshNode.findProviders(a),!(s.length>0));r++)r<2&&await new Promise(l=>setTimeout(l,1e3));if(s.length>0)return this.routeToRemoteProvider(o,a,s[0],p,n)}if(c)try{let e=Date.now(),s=await this.liopServer.callTool({name:a,arguments:p.arguments||{}}),r=f.getInstance(),l=JSON.stringify(p.arguments||{}),u=JSON.stringify(s),t,i=this.liopServer.getSandboxData();return i&&i.length>0&&(t=r.countTokens(JSON.stringify(i))),r.record({type:"tool_call",method:"tools/call",toolName:a,estimatedInputTokens:r.countTokens(l),estimatedOutputTokens:r.countTokens(u),durationMs:Date.now()-e,originDatasetTokens:t}),f$2.inc({capability:a,tool:a,status:s.isError?"error":"success",role:"executor"}),{jsonrpc:"2.0",id:o,result:s}}catch(e){return {jsonrpc:"2.0",id:o,error:{code:-32e3,message:e instanceof Error?e.message:String(e)}}}return {jsonrpc:"2.0",id:o,error:{code:-32002,message:`No provider found for tool: ${a}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(o,p,n,a,c){if(!this.meshNode)return {jsonrpc:"2.0",id:o,error:{code:-32603,message:"Mesh Node inactive"}};let e=this.manifestCache.get(n),s=this.defaultRpcPort;if(e)s=e.manifest.grpcPort;else {let m=await this.meshNode.queryManifest(n);m&&(s=m.grpcPort,this.manifestCache.set(n,{manifest:m,cachedAt:Date.now()}),e=this.manifestCache.get(n));}let r=await this.meshNode.resolvePeer(n),l=process.env.LIOP_NEXUS_URL||"",u=l.includes("127.0.0.1:13000")||l.includes("localhost:13000")||l.includes("127.0.0.1:13001")||l.includes("localhost:13001"),t=r.some(m=>m.includes("13001")||m.includes("13003")||m.includes("13004")||m.includes("13005")||m.includes("13011")||m.includes("13021")||m.includes("13031")),i$1=process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||u||t;if(i$1){let m=e?.manifest?.serverInfo?.name?.toLowerCase()||"",g=p.toLowerCase();m.includes("vault")||g.includes("medical")?s=13011:m.includes("bank")||g.includes("bank")?s=13021:(m.includes("oracle")||g.includes("hft")||g.includes("market"))&&(s=13031);}let f=null;if(i$1)f=`127.0.0.1:${s}`;else {let m=await import('os'),g=Object.values(m.networkInterfaces()).flat().filter(y=>y?.family==="IPv4").map(y=>y?.address);for(let y of r){let v=y.split("/"),E=v.indexOf("ip4");if(E!==-1){let _=v[E+1];if(_==="127.0.0.1"||g.includes(_)){f=`127.0.0.1:${s}`;break}f||(f=`${_}:${s}`);}}}f||(f=`127.0.0.1:${s}`),b.info(`[LIOP-Router] Dynamic route: ${p} -> ${f} (PeerID: ${n})`);let h=new g$1.LogicMesh(f,i({insecure:true,suppressWarning:true}),j);return this.performTranscoding(o,h,p,a,n,c)}meshAgentToken;async getOrAcquireMeshAgentToken(o){if(o){let s=this.manifestCache.get(o),r=s?.manifest.serverInfo?.name?.toLowerCase()||"",l,u=s?.manifest.tokenSlug;if(u){let t=`LIOP_TOKEN_${u}`;l=process.env[t]||process.env[`LIOP_OAUTH_TOKEN_${u}`],b.info(`[LIOP-Router] Step0 tokenSlug=${u} envKey=${t} found=${!!l} peer=${o.slice(-8)}`);}else b.info(`[LIOP-Router] Step0 tokenSlug=MISSING (manifest has no tokenSlug) peer=${o.slice(-8)} provider=${r}`);if(!l){let t=o.slice(-8).toUpperCase();l=process.env[`LIOP_TOKEN_${t}`]||process.env[`LIOP_OAUTH_TOKEN_${t}`];}if(!l&&r){let t=r.toUpperCase().replace(/[^A-Z0-9_]/g,"_");l=process.env[`LIOP_TOKEN_${t}`]||process.env[`LIOP_OAUTH_TOKEN_${t}`];}if(l)return b.info(`[LIOP-Router] Resolved node-specific token for peer ${o.slice(-8)} (${r||"unknown"})`),l}if(this.meshAgentToken)return this.meshAgentToken;let p=process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN;if(p)return this.meshAgentToken=p,this.meshAgentToken;let n=process.env.LIOP_NEXUS_URL;if(!n)return;let a=process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID||"liop-mesh-agent",c=process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET||"dev-secret-change-me",e=process.env.LIOP_OAUTH_AUDIENCE||process.env.LIOP_AUDIENCE||"urn:liop:mesh:api";try{let r=`${n.endsWith("/oidc")?n:`${n}/oidc`}/token`;b.info(`[LIOP-Router] Proactively acquiring M2M token from Nexus: ${r}`);let l=new URLSearchParams({grant_type:"client_credentials",scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",resource:e,client_id:a,client_secret:c}),u=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:l.toString()});if(!u.ok){let i=await u.text();b.warn(`[LIOP-Router] M2M Token acquisition failed: ${u.status} ${i}`);return}let t=await u.json();if(t.access_token)return this.meshAgentToken=t.access_token,b.info("[LIOP-Router] M2M Token acquired successfully for router routing."),this.meshAgentToken}catch(s){b.warn(`[LIOP-Router] Failed to acquire M2M token: ${s instanceof Error?s.message:String(s)}`);}}async performTranscoding(o,p,n,a,c,e){let s=n,r=this.meshNode?await this.meshNode.sign(Buffer.from(s)):Buffer.from([]),l=Date.now(),u$1=e;if(u$1||(u$1=await this.getOrAcquireMeshAgentToken(c)),c){let t=this.manifestCache.get(c);if(t?.manifest.authRequired&&!u$1){let i=t.manifest.serverInfo?.name?.toLowerCase()||"unknown",f=t.manifest.tokenSlug,h=c.slice(-8).toUpperCase(),m=f?`LIOP_TOKEN_${f}`:`LIOP_TOKEN_${i.toUpperCase().replace(/[^A-Z0-9_]/g,"_")}`;return {jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`Authentication Required: The restricted node (${i}) requires an access token. Please define the ${m} or LIOP_TOKEN_${h} environment variable on your agent/client host.`}],isError:true}}}}return new Promise(t=>{let i=new H.Metadata;u$1&&i.add("authorization",`Bearer ${u$1}`),p.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:s,proof_of_intent:r},i,async(f$1,h)=>{if(f$1||!h.accepted){try{g$2.inc({capability:n,error_type:"handshake_failed"});}catch{}return t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`PQC Handshake Failed: ${f$1?.message||"Rejected"}`}],isError:true}})}let m$1=performance.now(),{ciphertext:g,sharedSecret:y}=await a$3.encapsulateAsymmetric(h.kyber_public_key),v$1=performance.now()-m$1;try{u.observe({tool:n},v$1),v.inc({algorithm:"ml-kem-768",status:"success"});}catch{}let E=a?.arguments??(a?.payload!==void 0?a:{}),_=JSON.stringify(E),w$1=`return { "__liop_proxy_tool": "${n}", "__liop_proxy_args": ${_} };`,P=D.randomBytes(12),L=this.encryptWithNonce(Buffer.from(w$1),y,P),C=new H.Metadata;u$1&&C.add("authorization",`Bearer ${u$1}`);let x=p.executeLogic({session_token:h.session_token,wasm_binary:new Uint8Array(L),inputs:{},pqc_ciphertext:g,aes_nonce:P},C),k="",N=null;x.on("data",R=>{k+=R.semantic_evidence,N=R;}),x.on("end",async()=>{try{if(N)if(N.is_error)try{g$2.inc({capability:n,error_type:"remote_execution_error"});}catch{}else {let le=Buffer.from(N.cryptographic_proof).toString("hex"),U=Buffer.from(N.zk_receipt),ue=U.length>0&&U[0]===2,q=await this.verifier.verifyZkReceipt(Buffer.from(w$1),le,U,{sessionSecret:Buffer.from(y),expectedOutput:k,zkPolicy:ue?"required":"none"});try{m.inc({status:q?"valid":"invalid"});}catch{}if(!q){try{g$2.inc({capability:n,error_type:"cryptographic_audit_failed"});}catch{}return t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}})}}let R=JSON.parse(k),j=f.getInstance();j.record({type:"tool_call",method:"tools/call",toolName:n,peerId:c,estimatedInputTokens:j.countTokens(_),estimatedOutputTokens:j.countTokens(k),durationMs:Date.now()-l});try{w.inc({capability:n},Buffer.byteLength(k));}catch{}f$2.inc({capability:n,tool:n,status:R.isError?"error":"success",role:"proxy"}),t({jsonrpc:"2.0",id:o,result:R});}catch{t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:k}]}});}}),x.on("error",R=>{try{g$2.inc({capability:n,error_type:"grpc_stream_error"});}catch{}t({jsonrpc:"2.0",id:o,result:{content:[{type:"text",text:`LIOP gRPC Error: ${R.message}`}],isError:true}});});});})}encryptWithNonce(o,p,n){let a=D.createCipheriv("aes-256-gcm",p,n),c=Buffer.concat([a.update(o),a.final()]);return Buffer.concat([c,a.getAuthTag()])}};export{ce as a};//# sourceMappingURL=chunk-LM26HOJ6.js.map
|
|
31
|
+
//# sourceMappingURL=chunk-LM26HOJ6.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';var s={maxDecimalPlaces:4,clampNonNegative:true};function p(c,o){let a$1={...s,...o},u=new WeakSet;function r(t){if(t==null)return t;if(typeof t=="number"){if(!Number.isFinite(t))return t;let e=t;a$1.clampNonNegative&&e<0&&(e=0);let n=10**a$1.maxDecimalPlaces;return e=Math.round(e*n)/n,e}if(typeof t=="string"||typeof t=="boolean")return t;if(typeof t=="object"){if(u.has(t))return t;if(u.add(t),Array.isArray(t))return t.map(n=>r(n));let e={};for(let[n,f]of Object.entries(t))e[n]=r(f);return e}return t}return a(r,"walk"),r(c)}a(p,"sanitizeOutput");export{p as a};//# sourceMappingURL=chunk-MQ5SU26J.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-MQ5SU26J.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';var c=class s{static{a(this,"TokenManager");}cachedToken=null;expiresAt=0;pendingPromise=null;tokenEndpoint;clientId;clientSecret;audience;scope;staticToken;static REFRESH_BUFFER_MS=3e4;constructor(e){this.tokenEndpoint=e.tokenEndpoint,this.clientId=e.clientId,this.clientSecret=e.clientSecret,this.audience=e.audience??"urn:liop:mesh:api",this.scope=Array.isArray(e.scopes)?e.scopes.join(" "):e.scopes??"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query",this.staticToken=e.staticToken;}async getToken(){if(this.staticToken)return this.staticToken;let e=Date.now();return this.cachedToken&&e<this.expiresAt-s.REFRESH_BUFFER_MS?this.cachedToken:this.pendingPromise?this.pendingPromise:(this.pendingPromise=(async()=>{try{let t=await this.fetchNewToken();return this.cachedToken=t,t}finally{this.pendingPromise=null;}})(),this.pendingPromise)}invalidate(){this.cachedToken=null,this.expiresAt=0,this.clientId&&this.clientSecret&&(this.staticToken=void 0),b.info("[TokenManager] Cached OAuth access token invalidated.");}isExpired(){return this.staticToken?false:!this.cachedToken||Date.now()>=this.expiresAt-s.REFRESH_BUFFER_MS}getExpiresAt(){return this.expiresAt}async fetchNewToken(){b.info(`[TokenManager] Requesting M2M token from ${this.tokenEndpoint} for client '${this.clientId}'...`);let e=new URLSearchParams({grant_type:"client_credentials",client_id:this.clientId,client_secret:this.clientSecret,resource:this.audience,scope:this.scope}),t=await fetch(this.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e.toString(),signal:AbortSignal.timeout(1e4)});if(!t.ok){let a=await t.text();throw new Error(`OAuth token request failed [HTTP ${t.status}]: ${a}`)}let i=await t.json();if(!i.access_token)throw new Error("OAuth token response did not contain an 'access_token' field.");let r=typeof i.expires_in=="number"?i.expires_in:3600;return this.expiresAt=Date.now()+r*1e3,b.info(`[TokenManager] Acquired access token successfully. Expires in ${r}s.`),i.access_token}};export{c as a};//# sourceMappingURL=chunk-N35BC62H.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-N35BC62H.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {d as d$1,b as b$1,h}from'./chunk-GWVSCZUS.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var O=10,L=1800*1e3,w=60*1e3,g=class{constructor(e,t={}){this.options=t;this.app=new Hono,this.bridgeLogic=new d(e),this.activeSessions=new Map,this.maxSessionsPerIp=t.maxSessionsPerIp??O,this.sessionTimeoutMs=t.sessionTimeoutMs??L,this.setupRoutes();}options;static{a(this,"LiopStreamBridge");}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:t}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new t({sessionIdGenerator:a(()=>randomUUID(),"sessionIdGenerator"),onsessioninitialized:a(i=>{this.activeSessions.set(i,{transport:s,lastActivity:Date.now(),clientIp:e}),b.info(`[LIOP-StreamBridge] Session opened: ${i} (IP: ${e})`);},"onsessioninitialized")});return s.onmessage=async i=>{if(s.sessionId){let r=this.activeSessions.get(s.sessionId);r&&(r.lastActivity=Date.now());}try{let r=await this.bridgeLogic.handleJsonRpcRequest(i);r!==void 0&&await s.send(r);}catch(r){b.info("[LIOP-StreamBridge] JSON-RPC error:",r.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),b.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let t=0;for(let s of this.activeSessions.values())s.clientIp===e&&t++;return t}getClientIp(e){return e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||"unknown"}evictIdleSessions(){let e=Date.now();for(let[t,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(b.info(`[LIOP-StreamBridge] Evicting idle session: ${t}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(t));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),b.info("=".repeat(60)),b.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),b.info("No ZERO_TRUST_TOKEN found in environment."),b.info("A secure ephemeral token has been generated for this session:"),b.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),b.info("=".repeat(60))),this.app.use("/mcp",async(e,t)=>{let s=e.req.header("Authorization");if(!s?.startsWith("Bearer "))return e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);let i=s.slice(7),r=process.env.ZERO_TRUST_TOKEN;if(r&&i===r){await t();return}let o=this.bridgeLogic.getServer()?.jwtValidator;if(o)try{await o.validate(i),await t();return}catch(a){return b.info(`[LIOP-StreamBridge] JWT Validation failed: ${a.message}`),e.json({error:`Unauthorized: JWT Validation failed - ${a.message}`},401)}return b.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401)}),this.app.all("/mcp",async e=>{let t=e.req.header("mcp-session-id");if(t){let a=this.activeSessions.get(t);if(!a)return e.json({error:"Session not found"},404);a.lastActivity=Date.now();let c=await a.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(t),b.info(`[LIOP-StreamBridge] Session closed (DELETE): ${t}`)),c}let s=e.req.header("content-type")||"";if(e.req.method==="POST"&&s.includes("application/json"))try{let a=await e.req.json();if(a.method==="server/discover"||a.params?._meta||!!0){let c=await this.bridgeLogic.handleJsonRpcRequest(a);return c!==void 0?e.json(c):e.body(null,204)}}catch{}let i=this.getClientIp(e),r=this.countSessionsByIp(i);return r>=this.maxSessionsPerIp?(b.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${i} (${r} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(i)).handleRequest(e.req.raw)});}async start(e){let t=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),w),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:t},i=>{b.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${i.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,t]of this.activeSessions)await t.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),b.info("[LIOP-StreamBridge] HTTP ports released."));}};var d=class{constructor(e,t={}){this.options=t;e?.constructor?.name==="LiopServer"?(this.liopServer=e,b.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,b.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,b.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}options;static{a(this,"LiopMcpBridge");}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let t=e.id,s=e.method,i=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(t,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(t,s,i):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(t,s,i):this.errorResponse(t,-32601,"Bridge source not configured")}async handleLiopToMcp(e,t,s){if(!this.liopServer)return null;let i=d$1({method:t,params:s,id:e});if(t==="initialize")return this.successResponse(e,{protocolVersion:b$1,capabilities:{prompts:{listChanged:true},resources:{listChanged:true},tools:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()});if(t==="server/discover")return this.successResponse(e,{resultType:"complete",supportedVersions:[h,b$1],capabilities:{prompts:{listChanged:true},resources:{listChanged:true},tools:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()});if(t!=="notifications/initialized"){if(t==="ping")return this.successResponse(e,{});if(t==="tools/list"){let r=this.liopServer.listTools().sort((o,a)=>o.name.localeCompare(a.name));return this.successResponse(e,i?{tools:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",tools:r})}if(t==="resources/list"){let r=this.liopServer.listResources().sort((o,a)=>o.uri.localeCompare(a.uri));return this.successResponse(e,i?{resources:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",resources:r})}if(t==="prompts/list"){let r=this.liopServer.listPrompts().sort((o,a)=>o.name.localeCompare(a.name));return this.successResponse(e,i?{prompts:r}:{resultType:"complete",ttlMs:3e5,cacheScope:"public",prompts:r})}if(t==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let r=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,i||typeof r!="object"||r===null?r:{resultType:"complete",...r})}catch(r){return this.errorResponse(e,-32e3,r.message)}}if(t==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let r=await this.liopServer.readResource(s.uri);return this.successResponse(e,i?r:typeof r=="object"&&r!==null?{resultType:"complete",ttlMs:6e4,cacheScope:"private",...r}:{resultType:"complete",ttlMs:6e4,cacheScope:"private",contents:r})}catch(r){return this.errorResponse(e,-32e3,r.message)}}if(t==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let r={name:s.name,arguments:s.arguments||{}};try{let o=await this.liopServer.callTool(r);return (o.isError?!0:await this.verifyZkReceipt(r,o))?this.successResponse(e,i?o:{resultType:"complete",...o}):this.successResponse(e,{content:[{type:"text",text:"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload."}],isError:!0})}catch(o){return this.errorResponse(e,-32e3,o.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,t){return {jsonrpc:"2.0",id:e,result:t}}errorResponse(e,t,s){return {jsonrpc:"2.0",id:e,error:{code:t,message:s}}}async verifyZkReceipt(e,t){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,i=t.content[0]?.text;if(i&&typeof i=="string")try{let r=JSON.parse(i);if(r.image_id||r.zk_receipt){let{LiopVerifier:o}=await import('./verifier-J4NQYZX5.js'),a=new o,c=Buffer.from(r.zk_receipt||"","base64"),u=c.length>0&&c[0]===2;if(!await a.verifyZkReceipt(Buffer.from(s,"utf-8"),r.image_id||"",c,{guestImageIdHex:r.guest_image_id,circuitName:r.circuit_name,expectedOutput:r.computation_result,zkPolicy:u?"required":"none"}))return !1;r.audit_status=u?"VERIFIED: Groth16 Zero-Knowledge Proof Certified by LiopMcpBridge":"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",t.content[0].text=JSON.stringify(r);}}catch{}return !0}catch(s){return b.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:i}=await import('./server.js');if(this.liopServer=new i(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let r=this.legacyMcpServer;if(r._registeredTools)for(let[o,a]of Object.entries(r._registeredTools)){let c=a;this.liopServer.tool(o,c.description||"",c.inputSchema||{},async u=>await c.handler(u));}if(r._registeredResources)for(let[o,a]of Object.entries(r._registeredResources)){let c=a;this.liopServer.resource(c.name,o,c.metadata?.description||"",c.metadata?.mimeType||"application/octet-stream",async()=>(await c.readCallback(new URL(o))).contents[0].text);}}return}let t=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=a(async()=>{b.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);},"shutdown");t.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),t.on("line",async i=>{if(i.trim())try{let r=JSON.parse(i),o=await this.handleJsonRpcRequest(r);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
+
`);}catch(r){b.error(`[LIOP-Bridge] Error: ${r.message}`);}});}getServer(){return this.liopServer}};export{g as a,d as b};//# sourceMappingURL=chunk-P6IJ3VBD.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-P6IJ3VBD.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-AYDF3IFZ.js';import n from'crypto';var f=/^\s*@LIOP\{[^}]+\}[\r\n]+([\s\S]*?)[\r\n]+@END\s*$/;function u(t){let r=t.match(f);return r?.[1]!==void 0?r[1].trim():t.trim()}a$1(u,"normalizeLogicSource");function a(t){if(t[0]===0&&t[1]===97)return n.createHash("sha256").update(t).digest();let s=Buffer.from(t).toString("utf-8"),i=u(s);return n.createHash("sha256").update(Buffer.from(i,"utf-8")).digest()}a$1(a,"deriveLogicImageDigest");export{u as a,a as b};//# sourceMappingURL=chunk-TKLRW52V.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-TKLRW52V.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as S from'fs/promises';import*as I from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {autoNAT}from'@libp2p/autonat';import {bootstrap}from'@libp2p/bootstrap';import {circuitRelayTransport,circuitRelayServer}from'@libp2p/circuit-relay-v2';import {dcutr}from'@libp2p/dcutr';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {mdns}from'@libp2p/mdns';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var Y=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],E="/liop/manifest/1.0.0",N="liop:manifest",k=class T{static{a(this,"MeshNode");}node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(e={}){this.config={listenAddresses:e.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:e.bootstrapNodes||[],identityPath:e.identityPath,enableWAN:e.enableWAN??false,dhtStoragePath:e.dhtStoragePath,addressMapper:e.addressMapper,swarmKey:e.swarmKey};}shouldSkipManifestDial(e){let t=this.manifestDialFailureState.get(e);if(!t)return false;let n=Date.now();return n>=t.cooldownUntil?false:(n-t.lastSkipLogAt>T.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(b.info(`[LIOP-Mesh] Skipping manifest dial for ${e} during cooldown (${Math.ceil((t.cooldownUntil-n)/1e3)}s remaining)`),t.lastSkipLogAt=n),true)}recordManifestDialFailure(e){let t=Date.now(),r=(this.manifestDialFailureState.get(e)?.failures||0)+1,o=Math.min(T.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),T.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(e,{failures:r,cooldownUntil:t+o,lastSkipLogAt:0});}clearManifestDialFailure(e){this.manifestDialFailureState.delete(e);}async loadOrCreateIdentity(){try{let{generateKeyPair:e,privateKeyFromProtobuf:t}=await import('@libp2p/crypto/keys'),{fromString:n}=await import('uint8arrays/from-string');if(this.config.identityPath){let o=I.resolve(this.config.identityPath);try{let s=await S.readFile(o,"utf-8"),f=JSON.parse(s),h=n(f.privKey,"base64");try{let a=t(h);return b.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a,isNew:!1}}catch(a){b.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a instanceof Error?a.message:String(a)}`);}}catch(s){let f=s;f.code!=="ENOENT"&&b.error(`[LIOP-Mesh] Error loading identity: ${f.message}`);}}return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){b.error(`[LIOP-Mesh] Critical error in identity management: ${e}. Falling back to ephemeral identity.`);try{let{generateKeyPair:t}=await import('@libp2p/crypto/keys');return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){throw new Error(`Identity system failure: ${t}`)}}}async saveIdentity(e){if(!(!this.config.identityPath||!this.node))try{let t=I.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),{toString:r}=await import('uint8arrays/to-string'),o=n(e),s=r(o,"base64"),f={id:this.node.peerId.toString(),privKey:s};await S.mkdir(I.dirname(t),{recursive:!0}),await S.writeFile(t,JSON.stringify(f,null,2)),b.info(`[LIOP-Mesh] Identity persisted to ${t}`);}catch(t){b.error(`[LIOP-Mesh] FAILED to persist identity: ${t}`);}}async capabilityToCID(e){let t=await sha256.digest(new TextEncoder().encode(e));return CID.create(1,85,t)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(e=>setTimeout(e,500)),!this.node)return;b.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let e of this.announcedCapabilities)try{let t=await this.capabilityToCID(e);await this.node.contentRouting.provide(t),b.info(`[LIOP-Mesh] Re-announced: ${e}`);}catch(t){b.info(`[LIOP-Mesh] Re-announce failed for ${e}: ${t}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let e=await this.loadOrCreateIdentity();if(!e)throw new Error("Could not initialize P2P Identity");let{privateKey:t,isNew:n}=e;this.localPrivateKey=t;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=Y);let o=this.config.enableAutoNAT??true,s=this.config.enableRelay??true,f=this.config.enableDcutr??true,h=this.config.enableMdns??!this.config.enableWAN,a$1=[];r.length>0&&a$1.push(bootstrap({list:r})),h&&a$1.push(mdns());let g=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0",c=[tcp(),webSockets()];s&&c.push(circuitRelayTransport());let p={identify:identify(),ping:ping(),dht:kadDHT({protocol:g,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:a(l=>l,"peerInfoMapper")})};o&&(p.autoNAT=autoNAT()),s&&(p.relay=circuitRelayServer()),f&&(p.dcutr=dcutr());let M;if(this.config.swarmKey){let{preSharedKey:l}=await import('@libp2p/pnet');M=l({psk:this.config.swarmKey}),b.info("[LIOP-Mesh] \u{1F512} Private Network (pnet) enabled \u2014 transport-layer PSK isolation active");}if(this.node=await createLibp2p({privateKey:t,addresses:{listen:this.config.listenAddresses},transports:c,connectionEncrypters:[noise()],streamMuxers:[yamux()],...M?{connectionProtector:M}:{},services:p,peerDiscovery:a$1.length>0?a$1:void 0}),this.node.addEventListener("peer:discovery",l=>{let P=l.detail.id;if(b.info(`[LIOP-Mesh] Discovered peer: ${P.toString()}`),this.node){let y=P;if(this.config.addressMapper&&l.detail.multiaddrs.length>0){let L=l.detail.multiaddrs.map(b=>{let d=this.config.addressMapper(b.toString());return d?multiaddr(d):null}).filter(b=>b!==null).find(b=>b.toString().includes("/tcp/")&&!b.toString().includes("/ws"));L&&(y=L);}this.node.dial(y).catch(()=>{});}}),this.node.addEventListener("peer:connect",l=>{let P=l.detail;if(b.info(`[LIOP-Mesh] Connected to peer: ${P.toString()}`),!this.node)return;let y=this.node.services.dht;y?.routingTable&&(b.info(`[LIOP-Mesh] Adding ${P.toString()} to DHT Routing Table`),y.routingTable.add(P).catch(m=>{b.info(`[LIOP-Mesh] Failed to add peer to routing table: ${m instanceof Error?m.message:String(m)}`);})),this.reannounceAll().catch(m=>{b.info(`[LIOP-Mesh] Re-announce error: ${m instanceof Error?m.message:String(m)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(t),b.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(l=>{b.info(`[LIOP-Mesh] Listening on: ${l.toString()}`);}),r.length>0){b.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let l=this.node;if(!l)return;let P=2;await Promise.allSettled(r.map(async y=>{for(let m=1;m<=P;m++)try{await l.dial(multiaddr(y),{signal:AbortSignal.timeout(2500)}),b.info(`[LIOP-Mesh] \u2705 Successfully dialed ${y}`);return}catch{m===P?b.warn(`[LIOP-Mesh] \u26A0\uFE0F Could not connect to bootstrap ${y} after ${P} attempts. Continuing...`):await new Promise(b=>setTimeout(b,500));}}));}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),b.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let e=I.resolve(this.config.dhtStoragePath),t=await S.readFile(e,"utf-8"),n=JSON.parse(t),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let s of n)if(!(!s.id||!s.addresses))try{let f=r(s.id),h=s.addresses.map(g=>multiaddr(g));await this.node.peerStore.save(f,{multiaddrs:h});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(f).catch(()=>{}),o++;}catch{}b.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(e){let t=e;t.code!=="ENOENT"&&b.error(`[LIOP-Mesh] Failed to load DHT table: ${t.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let e=I.resolve(this.config.dhtStoragePath),t=await this.node.peerStore.all(),n=[];for(let r of t)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await S.mkdir(I.dirname(e),{recursive:!0}),await S.writeFile(e,JSON.stringify(n,null,2)),b.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(e){b.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${e}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(N).catch(e=>{b.info(`[LIOP-Mesh] Initial manifest announcement failed: ${e}`);}),this.node.handle(E,async(e,t)=>{let n=e?.stream??e,o=(e?.connection??t)?.remotePeer?.toString()||"unknown";b.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let s=this.manifestProvider?.();if(!s||!n){b.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let f=JSON.stringify(s),h=new TextEncoder().encode(f),a=Buffer.alloc(4);a.writeUInt32BE(h.length,0);let g=Buffer.concat([a,Buffer.from(h)]);b.info(`[LIOP-Mesh] Serving manifest (${g.length} bytes) to ${o} [Tools: ${s.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(g)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(p){b.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${p instanceof Error?p.message:String(p)}`);}}else await pipe([g],n);b.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){b.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(s){b.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${s instanceof Error?s.message:String(s)}`);}}),b.info(`[LIOP-Mesh] Manifest Protocol registered: ${E}`));}registerManifestHandler(e){this.manifestProvider=e,this.node&&this.applyHandlers();}async queryManifest(e){if(!this.node)throw new Error("Mesh Node is not running");if(e===this.node.peerId.toString())return b.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${e}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(e))return null;let t=3;for(let n=1;n<=t;n++)try{let r=null,s=this.node.getConnections().find(d=>d.remotePeer.toString()===e);if(s)r=s.remotePeer;else {let u=(await this.node.peerStore.all()).find(w=>w.id.toString()===e);if(u)r=u.id;else {let{peerIdFromString:w}=await import('@libp2p/peer-id');r=w(e);}}let h=r;if(this.config.addressMapper&&this.node){let d=this.config.addressMapper,u=await this.node.peerStore.get(r);if(u&&u.addresses.length>0){let w=u.addresses.map(v=>{let C=v.multiaddr.toString(),D=d(C);return D?{isCertified:v.isCertified,multiaddr:multiaddr(D)}:null}).filter(v=>v!==null),$=w.find(v=>v.multiaddr.toString().includes("/tcp/")&&!v.multiaddr.toString().includes("/ws"));$&&(h=$.multiaddr,b.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${h.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:w.map(v=>v.multiaddr)});}}let a;try{let d=await this.node.dialProtocol(h,E).catch(u=>{throw String(u).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):u});a=d.stream||d;}catch(d){if(n===t)return b.info(`[LIOP-Mesh] Dial error for ${e} after ${t} attempts: ${d}`),null;let u=500*2**n;b.info(`[LIOP-Mesh] Dial error for ${e} (Attempt ${n}). Retrying in ${u}ms...`),await new Promise(w=>setTimeout(w,u));continue}let g=a.source??(typeof a[Symbol.asyncIterator]=="function"?a:null);if(!g)throw new Error("Target stream has no AsyncIterable source");let c=[],p=0,M=-1,l,P=new Promise((d,u)=>{l=setTimeout(()=>u(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let d of g){if(!d)continue;let u=typeof d.subarray=="function"?d.subarray():d instanceof Uint8Array?d:new Uint8Array(0),w=Buffer.from(u.buffer,u.byteOffset,u.byteLength);if(w.length>0&&(c.push(w),p+=w.length,M<0&&p>=4&&(M=Buffer.concat(c).readUInt32BE(0)),M>=0&&p>=4+M))break}})(),P]);}catch(d){if(c.length===0)throw d;b.info(`[LIOP-Mesh] Partial manifest read from ${e}: ${d instanceof Error?d.message:String(d)}`);}finally{l&&clearTimeout(l);}let y=Buffer.concat(c);if(y.length<4)throw new Error("Received empty/invalid manifest (too short)");let m=y.readUInt32BE(0),L=y.subarray(4,4+m).toString("utf-8"),b$1=JSON.parse(L);return b.info(`[LIOP-Mesh] Received manifest from ${e}: ${b$1.tools.length} tools`),this.clearManifestDialFailure(e),b$1}catch(r){if(n===t)return this.recordManifestDialFailure(e),b.info(`[LIOP-Mesh] Failed to query manifest from ${e} after ${t} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;b.info(`[LIOP-Mesh] Query error for ${e} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(s=>setTimeout(s,o));}return null}async discoverManifestProviders(){return this.findProviders(N)}async announceManifest(){await this.announceCapability(N);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(e){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(e))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(e=>e.toString())}async announceCapability(e){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(e);try{let t=await this.capabilityToCID(e);b.info(`[LIOP-Mesh] Announcing capability: ${e} (CID: ${t.toString()})`),await this.node.contentRouting.provide(t),b.info(`[LIOP-Mesh] Successfully announced capability: ${e}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(t))if(r.id.toString()===n){b.info(`[LIOP-Mesh] Self-verification success: Node is providing ${e}`);break}}catch(t){b.error(`[LIOP-Mesh] Failed to announce capability: ${t}`);}}async findProviders(e){if(!this.node)throw new Error("Mesh Node is not running");let t=[];try{let n=await this.capabilityToCID(e);b.info(`[LIOP-Mesh] Querying DHT for ${e} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,s=o>1?1500:3e3;b.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${s}ms (Active connections: ${o})`);let f=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),h=!1;for(;!h;){let a=f.next(),g=new Promise(c=>setTimeout(()=>c({timeout:!0}),s));try{let c=await Promise.race([a,g]);if(c&&typeof c=="object"&&"timeout"in c){b.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof f.return=="function"&&f.return().catch(()=>{}),h=!0;break}let p=c;if(p.done){h=!0;break}r=!0;let l=p.value.id.toString();b.info(`[LIOP-Mesh] Found provider: ${l}`),t.includes(l)||t.push(l);}catch(c){b.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),h=!0;break}}if(!r){let g=this.node.services.dht?.routingTable?.size||0;b.info(`[LIOP-Mesh] DHT search for ${e} returned zero results (routing table size: ${g})`);}if(this.announcedCapabilities.has(e)){let a=this.node.peerId.toString();t.includes(a)||(b.info(`[LIOP-Mesh] Including local node (${a}) in results for ${e}`),t.push(a));}}catch(n){b.info(`[LIOP-Mesh] Error finding providers for ${e}: ${n instanceof Error?n.message:String(n)}`);}return b.info(`[LIOP-Mesh] DHT search for ${e} finished. Found ${t.length} providers.`),t}async resolvePeer(e){if(!this.node)throw new Error("Mesh Node is not running");try{let t=this.node.getConnections();for(let r of t)if(r.remotePeer.toString()===e){let o=r.remoteAddr.toString();return b.info(`[LIOP-Mesh] Resolved peer ${e} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===e&&r.addresses.length>0){let o=r.addresses.map(s=>s.multiaddr.toString());return b.info(`[LIOP-Mesh] Resolved peer ${e} via peerStore: ${o[0]}`),o}b.info(`[LIOP-Mesh] Peer ${e} not found in connections or peerStore`);}catch(t){b.info(`[LIOP-Mesh] Failed to resolve peer ${e}: ${t}`);}return []}isStarted(){return !!this.node&&this.node.status==="started"}getPeers(){return this.node?this.node.getConnections().map(e=>e.remotePeer.toString()):[]}isPrivateNetwork(){return !!this.config.swarmKey}getSwarmKey(){return this.config.swarmKey}};export{k as a};//# sourceMappingURL=chunk-V35CXJQN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-V35CXJQN.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-N35BC62H.js';import {a as a$1}from'./chunk-6KFKO6ZX.js';import {a as a$4}from'./chunk-Y675R34Z.js';import {i,g,j,f}from'./chunk-ECRS6N33.js';import {v,u,g as g$1,m,w as w$1}from'./chunk-ZZMSFCJP.js';import {h,b as b$1}from'./chunk-GWVSCZUS.js';import {a as a$3}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import*as M from'@grpc/grpc-js';import {createDecipheriv,randomBytes,createCipheriv}from'crypto';var w=class{static{a(this,"LiopRpcClient");}client;token;lastResolvedToken;address;constructor(t,r,i$1){let o=i(r);this.client=new g.LogicMesh(t,o,j),this.token=i$1,typeof i$1=="string"&&(this.lastResolvedToken=i$1),this.address=t;}setToken(t){this.token=t,typeof t=="string"&&(this.lastResolvedToken=t);}async resolveToken(){return typeof this.token=="function"?(this.lastResolvedToken=await this.token(),this.lastResolvedToken):(this.lastResolvedToken=this.token,this.token)}async negotiateIntent(t){let r=await this.resolveToken();return new Promise((i,o)=>{let e=new M.Metadata;r&&e.add("authorization",`Bearer ${r}`),this.client.NegotiateIntent(t,e,(s,n)=>{s?o(s):i(n);});})}executeLogic(t){let r=new M.Metadata,i=this.lastResolvedToken||(typeof this.token=="string"?this.token:void 0);return i&&r.add("authorization",`Bearer ${i}`),this.client.ExecuteLogic(t,r)}close(){this.client.close();}};var F={encryptPayload(y,t){if(t.length!==32)throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");let r=randomBytes(12),i=createCipheriv("aes-256-gcm",t,r),o=Buffer.concat([i.update(y),i.final()]),e=i.getAuthTag();return {ciphertext:Buffer.concat([o,e]),nonce:r}},decryptPayload(y,t,r){if(y.length<16)throw new Error("Invalid GCM Ciphertext; missing authentication tag length");let i=y.subarray(0,-16),o=y.subarray(-16),e=createDecipheriv("aes-256-gcm",r,t);return e.setAuthTag(o),Buffer.concat([e.update(i),e.final()])}};var Q=class{static{a(this,"LiopClient");}meshNode=null;rpcClients=new Map;manifests=new Map;tlsOptions;serverInfo;verifier=new a$1;oauthToken;tokenManager;era="modern";protocolVersion=h;constructor(t){this.tlsOptions=t;}async connect(t,r){let i=r?.auth?.clientId||process.env.LIOP_OAUTH_CLIENT_ID||process.env.LIOP_CLIENT_ID,o=r?.auth?.clientSecret||process.env.LIOP_OAUTH_CLIENT_SECRET||process.env.LIOP_CLIENT_SECRET,e=r?.auth?.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",s=r?.auth?.audience||process.env.LIOP_OAUTH_AUDIENCE||"urn:liop:mesh:api",n=r?.auth?.scope||process.env.LIOP_OAUTH_SCOPE||"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query";if(this.oauthToken=r?.auth?.token||process.env.LIOP_OAUTH_TOKEN||process.env.LIOP_TOKEN,i&&o){let v=`${(e).endsWith("/oidc")?e:`${e}/oidc`}/token`;this.tokenManager=new a$2({tokenEndpoint:v,clientId:i,clientSecret:o,audience:s,scopes:n});try{this.oauthToken=await this.tokenManager.getToken(),b.info("[LiopClient] Dynamic TokenManager configured and initial token acquired.");}catch(d){b.error(`[LiopClient] Failed to acquire OAuth M2M Token: ${d instanceof Error?d.message:String(d)}`);}}if(this.meshNode=new a$3(r?.meshConfig),await this.meshNode.start(),b.info(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`),t){let c=a(async()=>this.tokenManager?await this.tokenManager.getToken():this.oauthToken,"tokenResolver");this.rpcClients.set("static",new w(t,this.tlsOptions,c)),this.serverInfo={name:`LiopServer (${t})`,version:"1.0.0"},b.info(`[LiopClient] Static gRPC configured for: ${t}`);}else this.serverInfo={name:"LiopServer (Mesh Alpha)",version:"1.0.0"};}selectOptimalIp(t){for(let r of t){let i=r.split("/"),o=i.indexOf("ip4");if(o!==-1&&o+1<i.length){let e=i[o+1];if(e!=="127.0.0.1"&&!e.startsWith("127.")&&e!=="0.0.0.0"&&e!=="localhost")return e}}for(let r of t){let i=r.split("/"),o=i.indexOf("ip4");if(o!==-1&&o+1<i.length)return i[o+1]}return null}async resolveCapability(t){if(!this.meshNode)throw new Error("Client must be connected to Mesh to resolve capabilities.");b.info(`[LiopClient] Querying Mesh DHT for Provider: ${t}...`);let r=await this.meshNode.findProviders(t);if(r.length===0)throw new Error(`Kademlia DHT found zero providers for capability: ${t}`);let i=r[0];b.info(`[LiopClient] Identified Alpha Provider PeerID: ${i}`);let o=50051,e=await this.meshNode.queryManifest(i);e&&(o=e.grpcPort,this.manifests.set(i,e),b.info(`[LiopClient] Manifest resolved: gRPC port ${o}. Cached manifest for PeerID ${i}`));let s=await this.meshNode.resolvePeer(i),n=this.selectOptimalIp(s);if(n){let c=`${n}:${o}`;return b.info(`[LiopClient] Translated Multiaddr to optimal gRPC Target: ${c}`),c}return `127.0.0.1:${o}`}async probeServerDiscover(t){try{let r={"Content-Type":"application/json","Mcp-Method":"server/discover"};this.oauthToken&&(r.Authorization=`Bearer ${this.oauthToken}`);let i=await fetch(t,{method:"POST",headers:r,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"server/discover",params:{}})});if(i.ok){let e=(await i.json()).result?.supportedVersions||[];if(e.includes(h))return this.era="modern",this.protocolVersion=h,{era:"modern",protocolVersion:h,supportedVersions:e}}}catch{}return this.era="legacy",this.protocolVersion=b$1,{era:"legacy",protocolVersion:b$1,supportedVersions:[b$1]};}async discoverTools(t=false){if(!this.meshNode)throw new Error("Client must be connected before discovering tools.");let r=Date.now();b.info(`[LiopClient] Discovery started (forceRefresh: ${t})...`);let i=await this.meshNode.discoverManifestProviders(),o=[],e=new Set;for(let s of i)try{let n=t?void 0:this.manifests.get(s);if(n?b.info(`[LiopClient] Using cached manifest for: ${s}`):(b.info(`[LiopClient] Querying manifest from: ${s}`),n=await this.meshNode.queryManifest(s),n&&this.manifests.set(s,n)),n)for(let c of n.tools)e.has(c.name)||(o.push({name:c.name,description:c.description}),e.add(c.name));}catch(n){b.info(`[LiopClient] Error querying manifest from ${s}:`,n instanceof Error?n.message:String(n));}b.info(`[LiopClient] Discovery finished. Found ${o.length} unique tools.`);try{let s=f.getInstance(),n=JSON.stringify(o),c=JSON.stringify({tools:o});s.record({type:"tools_list",method:"discoverTools",estimatedInputTokens:s.countTokens(n),estimatedOutputTokens:s.countTokens(c),durationMs:Date.now()-r});}catch{}return o}async callTool(t,r,i){if(!this.meshNode)throw new Error("Client must be connected before calling tools.");let o=Date.now(),e=t.name;b.info(`[LiopClient] Resolving Tool: ${e}`);let s=this.rpcClients.get("static"),n=e;if(s||this.rpcClients.has(e)&&(s=this.rpcClients.get(e),n=e),s)n="static",b.info(`[LiopClient] Using existing static gRPC connection for ${e}.`);else {let p=null;for(let[l,u]of this.manifests.entries())if(u.tools.some(m=>m.name===e)){if(this.rpcClients.has(l)){s=this.rpcClients.get(l),n=l;break}let m=await this.meshNode.resolvePeer(l),T=this.selectOptimalIp(m);if(T){p=`${T}:${u.grpcPort}`,b.info(`[LiopClient] Fast-path: Resolved ${e} from manifest cache to optimal target ${p}`),n=l,s=this.getOrCreateRpcClient(l,p);break}}if(!s){let l=await this.resolveCapability(e);n=e,s=this.getOrCreateRpcClient(e,l);}}b.info(`[LiopClient] Negotiating intent for ${e}...`);let c=this.meshNode?`did:liop:${this.meshNode.getPeerId()}`:"did:liop:ephemeral",v$1=Buffer.from(`${e}:${Date.now()}`),d=this.meshNode?await this.meshNode.sign(v$1):v$1,f$1;try{f$1=await s.negotiateIntent({agent_did:c,capability_hash:e,proof_of_intent:d});}catch(p){let l=p instanceof Error?p.message:String(p);if(this.tokenManager&&(l.includes("UNAUTHENTICATED")||l.includes("Invalid JWT")||l.includes("timestamp check failed")||l.includes("expired"))){b.warn(`[LiopClient] Token expired/unauthenticated for ${e}. Preemptively refreshing OAuth token and retrying negotiateIntent...`),this.tokenManager.invalidate();let u=await this.tokenManager.getToken();this.oauthToken=u,s.setToken(u),f$1=await s.negotiateIntent({agent_did:c,capability_hash:e,proof_of_intent:d});}else throw p}if(!f$1.accepted){if(this.tokenManager&&(f$1.error_message?.includes("token")||f$1.error_message?.includes("UNAUTHENTICATED")||f$1.error_message?.includes("expired")||f$1.error_message?.includes("timestamp check failed"))){b.warn(`[LiopClient] Intent rejected with auth error: "${f$1.error_message}". Refreshing token and retrying...`),this.tokenManager.invalidate();let p=await this.tokenManager.getToken();this.oauthToken=p,s.setToken(p),f$1=await s.negotiateIntent({agent_did:c,capability_hash:e,proof_of_intent:d});}if(!f$1.accepted)throw new Error(`Intent denied by host: ${f$1.error_message}`)}let L=f$1.kyber_public_key||f$1.kyberPublicKey,X=f$1.session_token||f$1.sessionToken;if(!L){b.info("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",f$1);try{v.inc({algorithm:"ml-kem-768",status:"failure"});}catch{}throw new Error("Handshake failed: Remote host did not provide a valid Kyber Public Key.")}b.info(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${t.name}...`);let ee=performance.now(),$,I;try{let p=await a$4.encapsulateAsymmetric(L);$=p.ciphertext,I=p.sharedSecret;let l=performance.now()-ee;u.observe({tool:t.name},l),v.inc({algorithm:"ml-kem-768",status:"success"});}catch(p){try{v.inc({algorithm:"ml-kem-768",status:"failure"});}catch{}throw p}b.info("[LiopClient] Sealing WASM Payload and Inputs...");let S=r||Buffer.from(""),{ciphertext:te,nonce:ie}=F.encryptPayload(S,I),A={},x=await import('crypto');for(let[p,l]of Object.entries(t.arguments||{})){let u=x.randomBytes(12),m=x.createCipheriv("aes-256-gcm",I,u),T=Buffer.concat([m.update(JSON.stringify(l)),m.final()]),h=m.getAuthTag();A[p]=Buffer.concat([u,T,h]);}let ne={session_token:X,wasm_binary:te,inputs:A,pqc_ciphertext:$,aes_nonce:ie};return new Promise((p,l)=>{let u=s.executeLogic(ne);if(!u){l(new Error("RPC Client unavailable or failed to create stream."));return}let m$1=false,T=false;u.on("data",async h=>{if(!m$1){T=true,b.info("[LiopClient] Logic Executed. Verification in progress...");try{let k=!1,U=0;if(h.is_error)try{g$1.inc({capability:e,error_type:"remote_execution_error"});}catch{}else {let g=Buffer.from(h.zk_receipt);k=g.length>0&&g[0]===2,k&&g.length>1&&(U=g[1]);let E=i?.zkPolicy??(k?"required":"none"),O=await this.verifier.verifyZkReceipt(S,Buffer.from(h.cryptographic_proof).toString("hex"),g,{sessionSecret:Buffer.from(I),expectedOutput:h.semantic_evidence,circuitName:i?.circuitName,zkPolicy:E});try{m.inc({status:O?"valid":"invalid"});}catch{}if(!O){try{g$1.inc({capability:e,error_type:"zk_verification_failed"});}catch{}l(new Error("PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."));return}}m$1=!0;try{let g=f.getInstance(),E=JSON.stringify(t.arguments??{});g.record({type:"tool_call",method:"callTool",toolName:e,peerId:n!==e?n:void 0,estimatedInputTokens:g.countTokens(E),estimatedOutputTokens:g.countTokens(h.semantic_evidence),durationMs:Date.now()-o});let O=Buffer.byteLength(h.semantic_evidence||"")+(h.cryptographic_proof?h.cryptographic_proof.length:0)+(h.zk_receipt?h.zk_receipt.length:0);w$1.inc({capability:e},O);}catch{}p({content:[{type:"text",text:h.semantic_evidence}],isError:h.is_error,zkVerified:!h.is_error,zkProofType:k?U:0});}catch(k){try{g$1.inc({capability:e,error_type:"verification_exception"});}catch{}l(k);}}}),u.on("error",h=>{this.rpcClients.delete(n),this.rpcClients.delete(e);try{g$1.inc({capability:e,error_type:"stream_error"});}catch{}m$1||(b.error("[LiopClient] Stream Error:",h),l(h));}),u.on("end",()=>{!T&&!m$1&&l(new Error("Logic-on-Origin stream closed without results."));});})}getOrCreateRpcClient(t,r){let i=this.rpcClients.get(t);if(!i){let o=this.manifests.get(t),e=t;if(!o){b.info(`[LiopClient] PeerID "${t}" not found in manifest cache as PeerID. Searching tools in cached manifests...`);for(let[d,f]of this.manifests.entries())if(f.tools.some(L=>L.name===t)){o=f,e=d,b.info(`[LiopClient] Resolved tool "${t}" to provider PeerID "${d.slice(-8)}" from manifest cache.`);break}}let s=o?.serverInfo?.name?.toLowerCase()||"",n,c=o?.tokenSlug;if(c?(n=process.env[`LIOP_TOKEN_${c}`]||process.env[`LIOP_OAUTH_TOKEN_${c}`],b.info(`[LiopClient] Resolved via tokenSlug "${c}" (LIOP_TOKEN_${c}) -> found: ${!!n}`)):b.info(`[LiopClient] No tokenSlug available for peer ${e.slice(-8)}. Available cache keys: ${Array.from(this.manifests.keys()).map(d=>d.slice(-8)).join(", ")}`),!n&&e){let d=e.slice(-8).toUpperCase();n=process.env[`LIOP_TOKEN_${d}`]||process.env[`LIOP_OAUTH_TOKEN_${d}`];}if(!n&&s){let d=s.toUpperCase().replace(/[^A-Z0-9_]/g,"_");n=process.env[`LIOP_TOKEN_${d}`]||process.env[`LIOP_OAUTH_TOKEN_${d}`];}n&&b.info(`[LiopClient] Resolved node-specific token for peer ${e.slice(-8)} (${s||"unknown"})`);let v=a(async()=>n||(this.tokenManager?await this.tokenManager.getToken():this.oauthToken),"tokenResolver");i=new w(r,this.tlsOptions,v),this.rpcClients.set(t,i);}return i}async readResource(t){if(!this.meshNode)throw new Error("Client must be connected before reading resources.");let r=Date.now();b.info(`[LiopClient] Querying Mesh for Resource: ${t}...`);let i=await this.meshNode.findProviders(t);if(i.length===0)throw new Error(`No mesh providers found for resource: ${t}`);let o=await this.meshNode.queryManifest(i[0]);if(!o)throw new Error("Target peer did not return a valid LIOP Manifest.");let e=o.resources?.find(n=>n.uri===t);if(!e)throw new Error(`Resource ${t} not listed in remote manifest.`);let s={contents:[{uri:t,mimeType:e.mimeType||"application/json",text:JSON.stringify(e,null,2)}]};try{let n=f.getInstance(),c=JSON.stringify(s);n.record({type:"resource_read",method:"readResource",toolName:t,peerId:i[0],estimatedInputTokens:n.countTokens(t),estimatedOutputTokens:n.countTokens(c),durationMs:Date.now()-r});}catch{}return s}get peerId(){return this.meshNode?.getPeerId()??null}get isMeshActive(){return this.meshNode?.isStarted()??false}get connectionCount(){return this.meshNode?.getPeers().length??0}getServerInfo(){return this.serverInfo}async close(){this.meshNode&&await this.meshNode.stop();}};
|
|
2
|
+
export{w as a,F as b,Q as c};//# sourceMappingURL=chunk-WP5ER7RH.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-WP5ER7RH.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';var c={initialize:[],"notifications/initialized":[],"notifications/cancelled":[],ping:[],"server/discover":[],"subscriptions/listen":[],"tools/list":["liop:tools:list"],"tools/call":["liop:tools:call"],"resources/list":["liop:resources:read"],"resources/read":["liop:resources:read"],"resources/templates/list":["liop:resources:read"],"prompts/list":["liop:schema:read"],"prompts/get":["liop:schema:read"]};function u(e,s,l){let o=c[e];if(o!==void 0&&o.length===0)return {allowed:true};if(!s)return {allowed:false,reason:`Authentication required for method: ${e}`};let t=[...o??[],...l??[]];if(t.length===0)return {allowed:false,reason:`Unknown method: ${e}. Access denied (fail-closed).`};let n=new Set(s.scopes),i=t.filter(a=>!n.has(a));return i.length>0?{allowed:false,reason:`Insufficient scopes for ${e}. Missing: ${i.join(", ")}`}:{allowed:true}}a(u,"authorizeRequest");var f=["liop:tools:list","liop:tools:call","liop:resources:read","liop:schema:read","liop:mesh:query"];export{u as a,f as b};//# sourceMappingURL=chunk-XLVEDKM6.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XLVEDKM6.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-AYDF3IFZ.js';import {createMlKem768}from'mlkem';var a=null;async function n(){return a||(a=await createMlKem768()),a}a$1(n,"getKemInstance");var l={importPublicKey(e){if(e.length!==1184)throw new Error(`Kyber768 Public Key must be exactly 1184 bytes (Received: ${e.length})`);return e},async encapsulateAsymmetric(e){try{if(e.length!==1184)throw new Error("Kyber768 Public Key must be exactly 1184 bytes.");let r=await n(),[t,i]=r.encap(e);return {ciphertext:t,sharedSecret:i}}catch(r){throw new Error(`Failed to perform PQC encapsulation: ${r.message}`)}},async generateKeyPair(){let e=await n(),[r,t]=e.generateKeyPair();return {publicKey:r,secretKey:t}},async decapsulateSymmetric(e,r){return (await n()).decap(e,r)}};export{l as a};//# sourceMappingURL=chunk-Y675R34Z.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-Y675R34Z.js.map
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import {a as a$2}from'./chunk-MQ5SU26J.js';import {a as a$3,b as b$2}from'./chunk-XLVEDKM6.js';import {b as b$1}from'./chunk-2ZYX736J.js';import {j,g,h,f as f$1}from'./chunk-ECRS6N33.js';import {k,f,h as h$1,w,x,g as g$1}from'./chunk-ZZMSFCJP.js';import {a as a$1}from'./chunk-V35CXJQN.js';import {b}from'./chunk-3WRKTVOF.js';import {a}from'./chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import*as O from'crypto';import O__default from'crypto';import*as S from'fs';import {createRequire}from'module';import L from'path';import {fileURLToPath,pathToFileURL}from'url';import*as _ from'@grpc/grpc-js';import {createMlKem768}from'mlkem';import {Piscina,FixedQueue}from'piscina';import {z}from'zod';import*as B from'jose';import Ae from'oidc-provider';import*as ne from'acorn';import {simple}from'acorn-walk';var J=class{static{a(this,"LiopRpcServer");}server;constructor(){this.server=new _.Server(j);}addService(e){this.server.addService(g.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,t){let r=h(t);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,r,(s,o)=>{if(s){n(s);return}b.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async gracefulShutdown(e=5e3){return new Promise(t=>{let r=false,i=setTimeout(()=>{r||(r=true,b.warn(`[LIOP-RPC] tryShutdown timed out after ${e}ms \u2014 forcing shutdown`),this.server.forceShutdown(),t());},e);this.server.tryShutdown(()=>{r||(r=true,clearTimeout(i),b.info("[LIOP-RPC] Server gracefully shut down"),t());});})}async stop(){return this.gracefulShutdown(5e3)}};var ve="0".repeat(64);function _e(h){let e=Object.keys(h).sort(),t={};for(let r of e)t[r]=h[r];return JSON.stringify(t)}a(_e,"canonicalize");function Ee(h){let e=_e(h);return O.createHash("sha256").update(e).digest("hex")}a(Ee,"computeEntryHash");var ie=class{static{a(this,"AuditLogger");}entries=[];lastEntryHash=ve;filePath;interceptor;constructor(e){this.filePath=e,this.filePath&&S.existsSync(this.filePath)&&this.loadFromFile(this.filePath);}setInterceptor(e){this.interceptor=e;}recordExecution(e){let t=O.randomUUID(),r=e.timestamp||new Date().toISOString(),i=e.traceId||O.randomBytes(16).toString("hex"),n=e.datasetHash||O.createHash("sha256").update("").digest("hex"),s=e.outputHash||O.createHash("sha256").update("").digest("hex"),o=e.zkReceiptSig||"",a={id:t,timestamp:r,traceId:i,agentDid:e.agentDid,peerId:e.peerId,toolName:e.toolName,datasetHash:n,fuelConsumed:e.fuelConsumed,outputHash:s,zkReceiptSig:o,status:e.status,prevEntryHash:this.lastEntryHash},c=Ee(a),l={...a,entryHash:c};if(this.entries.push(l),this.lastEntryHash=c,this.filePath&&S.appendFileSync(this.filePath,`${JSON.stringify(l)}
|
|
2
|
+
`,"utf8"),this.interceptor){let u=Object.freeze(structuredClone(l));try{let y=this.interceptor(u);y&&typeof y=="object"&&"catch"in y&&y.catch(()=>{});}catch{}}return l}getEntries(){return [...this.entries]}getEntryCount(){return this.entries.length}verifyIntegrity(){let e=ve;for(let t=0;t<this.entries.length;t++){let r=this.entries[t];if(r.prevEntryHash!==e)return {valid:false,totalEntries:this.entries.length,brokenIndex:t,reason:`Broken hash chain at index ${t}: expected prevHash ${e}, got ${r.prevEntryHash}`};let{entryHash:i,...n}=r,s=Ee(n);if(s!==i)return {valid:false,totalEntries:this.entries.length,brokenIndex:t,reason:`Tampered entry at index ${t}: hash mismatch (expected ${s}, stored ${i})`};e=i;}return {valid:true,totalEntries:this.entries.length}}exportJsonl(){return this.entries.map(e=>JSON.stringify(e)).join(`
|
|
3
|
+
`)}loadFromFile(e){let r=S.readFileSync(e,"utf8").split(`
|
|
4
|
+
`).filter(i=>i.trim().length>0);for(let i of r){let n=JSON.parse(i);this.entries.push(n),this.lastEntryHash=n.entryHash;}}},Se=new ie;var H={audience:"urn:liop:mesh:api",tokenTtlSeconds:3600,jwksCacheTtlMs:6e5,jwksCooldownMs:3e4,clockToleranceSec:5,signingAlgorithm:"EdDSA"};var q=class{static{a(this,"JwtValidator");}jwksResolver;issuer;audience;constructor(e,t,r){this.issuer=e,this.audience=t,r instanceof URL?this.jwksResolver=B.createRemoteJWKSet(r,{cacheMaxAge:H.jwksCacheTtlMs,cooldownDuration:H.jwksCooldownMs}):this.jwksResolver=B.createLocalJWKSet(r);}async validate(e){let t=this.buildIssuerAliases(),{payload:r}=await B.jwtVerify(e,this.jwksResolver,{issuer:t.length>1?t:this.issuer,audience:this.audience,algorithms:[H.signingAlgorithm,"ES256"],clockTolerance:H.clockToleranceSec,requiredClaims:["sub","scope"]});return {token:e,clientId:r.sub??"unknown",scopes:typeof r.scope=="string"?r.scope.split(" "):[],expiresAt:r.exp}}buildIssuerAliases(){let e=[this.issuer],t=this.issuer.endsWith("/")?this.issuer.slice(0,-1):this.issuer,r=["nexus:3000","liop-nexus:3000","127.0.0.1:3000","localhost:3000","127.0.0.1:13000","localhost:13000","127.0.0.1:13001","localhost:13001","127.0.0.1:15000","localhost:15000"],i="";try{let o=new URL(t);i=`${o.hostname}:${o.port||"3000"}`;}catch{return e}if(!r.some(o=>i===o))return e;let s=t.replace(/^https?:\/\/[^/]+/,"");for(let o of r){let a=`http://${o}${s}`;e.includes(a)||e.push(a);}if(s)for(let o of r){let a=`http://${o}`;e.includes(a)||e.push(a);}else for(let o of r){let a=`http://${o}/oidc`;e.includes(a)||e.push(a);}return e}getIssuer(){return this.issuer}getAudience(){return this.audience}};function be(h){let{privateKey:e,publicKey:t}=O__default.generateKeyPairSync("ed25519"),r=e.export({format:"jwk"}),i=t.export({format:"jwk"}),n=O__default.createHash("sha256").update(i.x||"").digest("hex").slice(0,16),s={...r,kid:n,use:"sig",alg:"EdDSA"},o={...i,kid:n,use:"sig",alg:"EdDSA"},a$1={keys:[s]},c={keys:[o]},l={scopes:["openid","offline_access",...b$2],clients:h.clients.map(v=>({client_id:v.client_id,client_secret:v.client_secret,grant_types:["client_credentials"],response_types:[],redirect_uris:[],scope:v.scope,token_endpoint_auth_method:"client_secret_post",id_token_signed_response_alg:"EdDSA"})),features:{clientCredentials:{enabled:true},devInteractions:{enabled:false},resourceIndicators:{enabled:true,useGrantedResource:a(()=>true,"useGrantedResource"),getResourceServerInfo:a((v,p,f)=>({scope:f.scope||"",accessTokenFormat:"jwt",jwt:{sign:{alg:"EdDSA"}}}),"getResourceServerInfo")}},formats:{AccessToken:"jwt"},interactions:{url:a(()=>{throw new Error("InteractionsNotSupportedException: This Authorization Server is strictly configured for Machine-to-Machine flows.")},"url")},jwks:a$1,ttl:{ClientCredentials:3600},cookies:{keys:[O__default.randomBytes(32).toString("hex")]},extraTokenClaims:a((v,p)=>p.kind==="AccessToken"?{scope:p.scope}:{},"extraTokenClaims")},u=h.issuer.endsWith("/")?h.issuer.slice(0,-1):h.issuer,y=new Ae(u,l);return y.proxy=true,{provider:y,jwks:c}}a(be,"createOAuthServer");var V=class h{static{a(this,"TaintAnalyzer");}piiFields;sensitiveKeys;static TAINT_PROPAGATING_METHODS=new Set(["charCodeAt","codePointAt","charAt","at","indexOf","lastIndexOf","search","localeCompare","startsWith","endsWith","includes","substring","slice","substr","split","match","matchAll","replace","replaceAll","normalize","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat"]);static ARRAY_CALLBACK_METHODS=new Set(["map","forEach","filter","find","some","every","flatMap","findIndex"]);static REDUCE_METHODS=new Set(["reduce","reduceRight"]);currentRecordCollections=new Set;constructor(e,t=[]){this.piiFields=new Set(e.map(r=>r.toLowerCase())),this.sensitiveKeys=new Set(t.map(r=>r.toLowerCase()));}classifyField(e,t=[]){let r=e.toLowerCase();if(this.piiFields.has(r))return "forbidden";let i=new Set(t.map(n=>n.toLowerCase()));return this.sensitiveKeys.has(r)||i.has(r)?"sensitive":"public"}analyze(e,t,r=50){let i;try{let a=`function liop_analysis_wrapper(env) {
|
|
5
|
+
${e}
|
|
6
|
+
}`;i=ne.parse(a,{ecmaVersion:2022,sourceType:"script",locations:!0});}catch{return null}let n=new Set,s=new Set;this.identifyRecordBoundVars(i,n),this.propagateTaint(i,n,s);let o=this.checkReturnStatements(i,n,s);if(o)return o;if(t!==void 0&&t>0&&t<r){let a=this.detectCorrelatedAggregations(i);if(a)return a.reason=a.reason.replace("50 records",`${r} records`),a}if(t!==void 0&&t>0&&t<r){let a=this.detectMinMaxExtraction(i);if(a)return a.reason=a.reason.replace("50 records",`${r} records`),a}return null}extractQueriedFields(e){let t;try{t=ne.parse(`function w(env) {
|
|
7
|
+
${e}
|
|
8
|
+
}`,{ecmaVersion:2022,sourceType:"script"});}catch{return []}let r=new Set;this.identifyRecordBoundVars(t,r);let i=new Set;return simple(t,{MemberExpression:a(s=>{let o=this.getPropertyName(s);if(!(!o||o==="length")&&(s.object.type==="Identifier"&&r.has(s.object.name)&&i.add(o),s.object.type==="MemberExpression")){let a=s.object;a.computed&&this.isEnvRecordsAccess(a.object)&&i.add(o);}},"MemberExpression")}),Array.from(i)}detectCorrelatedAggregations(e){let t=new Map;simple(e,{CallExpression:a(i=>{if(i.callee.type!=="MemberExpression")return;let n=i.callee,s=this.getPropertyName(n);if(!s||!h.REDUCE_METHODS.has(s)||!this.isEnvRecordsChain(n.object))return;let o=i.arguments[0];if(!o||o.type!=="ArrowFunctionExpression"&&o.type!=="FunctionExpression")return;let a=o,c=a.params.length>1?a.params[1]:a.params[0];if(c?.type!=="Identifier")return;let l=c.name,u=this.extractFieldsFromBody(a.body,l);for(let y of u){let v=t.get(y)??0;t.set(y,v+1);}},"CallExpression")});for(let[i,n]of t)if(n>=2)return {reason:`Correlation guard: ${n} aggregations detected on field '${i}'. Multiple correlated aggregations on the same field can enable differencing attacks. Use a single aggregation per numeric field, or increase dataset size above 50 records.`};return null}isEnvRecordsChain(e){if(this.isEnvRecordsAccess(e))return true;if(e.type==="CallExpression"){let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,i=this.getPropertyName(r);if(i&&(i==="slice"||i==="filter"||i==="toSorted"))return this.isEnvRecordsChain(r.object)}}return false}isRecordsSource(e){if(this.isEnvRecordsAccess(e)||e.type==="Identifier"&&this.currentRecordCollections.has(e.name))return true;if(e.type==="CallExpression"){let t=e;if(t.callee.type==="MemberExpression"){let r=t.callee,i=this.getPropertyName(r);if(i&&(i==="slice"||i==="filter"||i==="toSorted"||i==="map"||i==="concat"))return this.isRecordsSource(r.object)}}return false}identifyRecordCollections(e){this.currentRecordCollections.clear();for(let t=0;t<3;t++)simple(e,{VariableDeclarator:a(i=>{!i.init||i.id.type!=="Identifier"||this.isRecordsSource(i.init)&&this.currentRecordCollections.add(i.id.name);},"VariableDeclarator"),AssignmentExpression:a(i=>{i.left.type==="Identifier"&&this.isRecordsSource(i.right)&&this.currentRecordCollections.add(i.left.name);},"AssignmentExpression")});}extractFieldsFromBody(e,t){let r=[];return simple(e,{MemberExpression:a(n=>{if(n.object.type==="Identifier"&&n.object.name===t){let s=this.getPropertyName(n);s&&s!=="length"&&r.push(s);}},"MemberExpression")}),r}detectMinMaxExtraction(e){let t=null;return simple(e,{CallExpression:a(i=>{if(!t&&i.callee.type==="MemberExpression"){let n=i.callee;if(n.object.type==="Identifier"&&n.object.name==="Math"){let s=this.getPropertyName(n);(s==="min"||s==="max")&&i.arguments.some(o=>o.type==="SpreadElement"&&this.isRecordsMapCall(o.argument))&&(t={reason:`Min/Max gate: Math.${s}() on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations.`});}}},"CallExpression"),MemberExpression:a(i=>{if(!t&&i.computed&&i.object.type==="CallExpression"){let n=i.object;if(n.callee.type==="MemberExpression"){let s=this.getPropertyName(n.callee);if(s==="sort"||s==="toSorted"){let o=n.callee.object;this.isEnvRecordsChain(o)&&(t={reason:"Min/Max gate: .sort()[index] on individual records blocked for small datasets (n < 50). Use avg/stddev/count for privacy-safe aggregations."});}}}},"MemberExpression")}),t}isRecordsMapCall(e){if(e.type!=="CallExpression")return false;let t=e;if(t.callee.type!=="MemberExpression")return false;let r=t.callee;return this.getPropertyName(r)==="map"&&this.isRecordsSource(r.object)}identifyRecordBoundVars(e,t){this.identifyRecordCollections(e),simple(e,{CallExpression:a(n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isRecordsSource(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(h.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&t.add(l.name);}if(h.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&t.add(l.name);}}},"CallExpression"),ForOfStatement:a(n=>{if(this.isRecordsSource(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&t.add(s.id.name);},"ForOfStatement")}),simple(e,{VariableDeclarator:a(n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isRecordsSource(s.object)&&t.add(n.id.name);}},"VariableDeclarator")});}propagateTaint(e,t,r){for(let i=0;i<3;i++){let n=r.size;if(simple(e,{VariableDeclarator:a(o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,t,r)&&r.add(o.id.name);},"VariableDeclarator"),AssignmentExpression:a(o=>{if(o.left.type==="MemberExpression"){let a=o.left;a.computed&&this.isExpressionTainted(a.property,t,r)&&a.object.type==="Identifier"&&r.add(a.object.name);}o.left.type==="Identifier"&&this.isExpressionTainted(o.right,t,r)&&r.add(o.left.name);},"AssignmentExpression"),FunctionDeclaration:a(o=>{o.id&&o.id.type==="Identifier"&&this.doesCallbackProduceTaint(o,null,t,r)&&r.add(o.id.name);},"FunctionDeclaration"),CallExpression:a(o=>{if(o.callee.type!=="MemberExpression")return;let a=o.callee;this.getPropertyName(a)==="push"&&a.object.type==="Identifier"&&o.arguments.some(l=>this.isExpressionTainted(l,t,r))&&r.add(a.object.name);},"CallExpression")}),r.size===n)break}}checkReturnStatements(e,t,r){let i=null;return simple(e,{ReturnStatement:a(s=>{if(!i&&s.argument&&this.isExpressionTainted(s.argument,t,r)){let o=s.loc?.start.line?s.loc.start.line-1:void 0,a=this.describeTaintSource(s.argument,t,r);i={reason:`PII side-channel detected: output contains values derived from restricted fields. ${a?`Operation: ${a}. `:""}Use only non-PII fields (e.g., numeric/date columns) for aggregations.`,line:o,operation:a};}},"ReturnStatement")}),i}isExpressionTainted(e,t,r){switch(e.type){case "Identifier":return r.has(e.name);case "MemberExpression":return this.isMemberExprTainted(e,t,r);case "CallExpression":return this.isCallExprTainted(e,t,r);case "YieldExpression":{let i=e;return i.argument?this.isExpressionTainted(i.argument,t,r):false}case "FunctionExpression":case "ArrowFunctionExpression":{let i=e;return this.doesCallbackProduceTaint(i,null,t,r)}case "BinaryExpression":case "LogicalExpression":{let i=e;return this.isExpressionTainted(i.left,t,r)||this.isExpressionTainted(i.right,t,r)}case "UnaryExpression":{let i=e;return this.isExpressionTainted(i.argument,t,r)}case "ConditionalExpression":{let i=e;return this.isExpressionTainted(i.test,t,r)||this.isExpressionTainted(i.consequent,t,r)||this.isExpressionTainted(i.alternate,t,r)}case "ObjectExpression":return e.properties.some(n=>n.type==="Property"?n.computed&&this.isExpressionTainted(n.key,t,r)?true:this.isExpressionTainted(n.value,t,r):n.type==="SpreadElement"?this.isExpressionTainted(n.argument,t,r):false);case "ArrayExpression":return e.elements.some(n=>n!==null&&this.isExpressionTainted(n,t,r));case "TemplateLiteral":return e.expressions.some(n=>this.isExpressionTainted(n,t,r));case "SpreadElement":{let i=e;return this.isExpressionTainted(i.argument,t,r)}default:return false}}isMemberExprTainted(e,t,r){let i=this.getPropertyName(e);if(e.object.type==="Identifier"&&t.has(e.object.name)&&i&&this.piiFields.has(i.toLowerCase()))return true;if(e.object.type==="MemberExpression"&&i&&this.piiFields.has(i.toLowerCase())){let n=e.object;if(n.computed&&this.isRecordsSource(n.object))return true}if(this.isExpressionTainted(e.object,t,r))return true;if(e.computed&&e.object.type==="Identifier"&&t.has(e.object.name)&&e.property.type==="Literal"){let n=e.property.value;if(typeof n=="string"&&this.piiFields.has(n.toLowerCase()))return true}return false}isCallExprTainted(e,t,r){if(e.callee.type==="MemberExpression"){let i=e.callee,n=this.getPropertyName(i);if(n&&h.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,t,r))return true;if(this.isRecordsSource(i.object)&&e.arguments[0]){let s=e.arguments[0];if(s.type==="ArrowFunctionExpression"||s.type==="FunctionExpression")return this.doesCallbackProduceTaint(s,n,t,r)}if(this.isExpressionTainted(i.object,t,r)||e.arguments.some(s=>this.isExpressionTainted(s,t,r)))return true}if(e.callee.type==="MemberExpression"){let i=e.callee;this.getPropertyName(i)==="push"&&i.object.type==="Identifier"&&e.arguments.some(s=>this.isExpressionTainted(s,t,r))&&r.add(i.object.name);}if(e.callee.type==="Identifier"){let i=e.callee.name;if(r.has(i))return true;if(!new Set(["Math","Number","parseInt","parseFloat","isNaN","isFinite"]).has(i))return e.arguments.some(s=>this.isExpressionTainted(s,t,r))}return false}doesCallbackProduceTaint(e,t,r,i){let n=new Set(r),s=new Set(i);if(e.params.length>0){let l=t!==null&&h.REDUCE_METHODS.has(t)?1:0;e.params.length>l&&e.params[l].type==="Identifier"&&n.add(e.params[l].name);}if(e.type==="ArrowFunctionExpression"&&e.body.type!=="BlockStatement")return this.isExpressionTainted(e.body,n,s);this.propagateTaint(e.body,n,s);let o=false,a$1={ReturnStatement:a(c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);},"ReturnStatement"),YieldExpression:a(c=>{let l=c;l.argument&&this.isExpressionTainted(l.argument,n,s)&&(o=true);},"YieldExpression")};return simple(e.body,a$1),o}getPropertyName(e){if(!e.computed&&e.property.type==="Identifier")return e.property.name;if(e.computed&&e.property.type==="Literal"){let t=e.property.value;if(typeof t=="string")return t}return null}isEnvRecordsAccess(e){if(e.type==="MemberExpression"){let t=e;if(this.getPropertyName(t)==="records"&&t.object.type==="Identifier"&&t.object.name==="env")return true}return e.type==="Identifier"&&e.name==="records"}describeTaintSource(e,t,r){if(e.type==="Identifier"){let i=e.name;if(r.has(i))return `variable '${i}' is PII-derived`}if(e.type==="ObjectExpression"){let i=e;for(let n of i.properties)if(n.type==="Property"&&this.isExpressionTainted(n.value,t,r))return `property '${n.key.type==="Identifier"?n.key.name:"unknown"}' contains PII-derived value`}if(e.type==="CallExpression"){let i=e;if(i.callee.type==="MemberExpression"){let n=this.getPropertyName(i.callee);if(n)return `result of .${n}() on PII data`}}}};var ke={aspirin:"Medication",lisinopril:"Medication",metformin:"Medication",amlodipine:"Medication",atorvastatin:"Medication",omeprazole:"Medication",losartan:"Medication",simvastatin:"Medication",levothyroxine:"Medication",ibuprofen:"Medication",acetaminophen:"Medication",amoxicillin:"Medication",ciprofloxacin:"Medication",prednisone:"Medication",warfarin:"Medication",insulin:"Medication",hydrochlorothiazide:"Medication",gabapentin:"Medication",albuterol:"Medication",pantoprazole:"Medication",hypertension:"Condition",diabetes:"Condition",bronchitis:"Condition",pneumonia:"Condition",asthma:"Condition"},Q=4,Oe=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,X=class h{static{a(this,"NerScanner");}static nlp=null;async getNlp(){if(!h.nlp){let e=await import('compromise/three');h.nlp=e.default||e,h.nlp.addWords(ke);}return h.nlp}async scan(e){if(e.length<Q||Oe.test(e))return {detected:false,entities:[]};let r=(await this.getNlp())(e),i=[],n=r.people().out("array");for(let a of n){let c=a.trim();c.length>=Q&&i.push({type:"person",text:c});}let s=r.places().out("array");for(let a of s){let c=a.trim();c.length>=Q&&i.push({type:"place",text:c});}let o=r.organizations().out("array");for(let a of o){let c=a.trim();c.length>=Q&&i.push({type:"organization",text:c});}return {detected:i.length>0,entities:i}}async scanDeep(e,t=new WeakSet){if(e==null)return {detected:false,entities:[]};if(typeof e=="string")return this.scan(e);if(typeof e=="object"){if(t.has(e))return {detected:false,entities:[]};t.add(e);let r=Array.isArray(e)?e:Object.values(e),i=[];for(let n of r){let s=await this.scanDeep(n,t);if(s.detected&&(i.push(...s.entities),s.entities.some(o=>o.type==="person")))return {detected:true,entities:i}}return {detected:i.length>0,entities:i}}return {detected:false,entities:[]}}};function Ne(h){let e=h.replace(/\D/g,"");if(e.length<13||e.length>19)return false;let t=0,r=false;for(let i=e.length-1;i>=0;i--){let n=parseInt(e.charAt(i),10);r&&(n*=2,n>9&&(n-=9)),t+=n,r=!r;}return t%10===0}a(Ne,"isLuhnValid");function Ce(h){let e=h.replace(/\s+/g,"").toUpperCase();if(!/^[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}$/.test(e))return false;let t=e.substring(4)+e.substring(0,4),r="";for(let i=0;i<t.length;i++){let n=t.charCodeAt(i);if(n>=65&&n<=90)r+=(n-55).toString();else if(n>=48&&n<=57)r+=t.charAt(i);else return false}try{return BigInt(r)%97n===1n}catch{return false}}a(Ce,"isIbanValid");var R={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:a(h=>!h.endsWith("@example.com")&&!h.endsWith("@test.com"),"validator")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:Ne},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:a(h=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(h)?false:h.split(".").map(Number).every(r=>r>=0&&r<=255),"validator")},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")},"validator")},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:a(h=>{let e=h.replace(/\D/g,"");if(e.length!==9)return false;let t=parseInt(e.substring(0,3),10);return !(t===0||t===666||t>=900||parseInt(e.substring(3,5),10)===0||parseInt(e.substring(5,9),10)===0||/^(\d)\1+$/.test(e)||e==="123456789")},"validator")},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:Ce},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},Te={GLOBAL_STRICT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.PASSPORT_MRZ,R.IBAN],US_COMPLIANT:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.SSN,R.PASSPORT_MRZ],EU_GDPR:[R.EMAIL,R.CREDIT_CARD,R.IP_ADDRESS,R.PHONE,R.IBAN,R.PASSPORT_MRZ]},ee=class h{static{a(this,"PiiScanner");}patterns;forbiddenKeysSet;nerScanner;static KEY_SAFELIST=new Set(["grid","video","android","identity","provide","override","validate","hidden","widget","guidelines","beside","guideline","outside","inside","collide","decide","divide","aside","ride","side","wide","hide","tide","pride","bride","slide","guide","stride","oxide","dioxide","suicide","homicide","pesticide","valid","invalid","void","avoid","diagnosis","medication","namespace","namesake","rename","filename","hostname","typename","unnamed","renamed","phonetic","phoneme","microphone","headphone","telephone","saxophone","smartphone","streetview","addressable","addressing","cityscape","electricity","capacity","velocity","opacity","timestamp","timezone","image_id","computation_result","zk_receipt","testid","toolid","sessionid","peerid","nodeid","requestid","correlationid","traceid","spanid"]);shortTokenBoundaryPatterns;longForbiddenTokens;constructor(e=[],t=[],r){this.patterns=e,this.forbiddenKeysSet=new Set(t.map(i=>i.toLowerCase())),this.nerScanner=r??null,this.shortTokenBoundaryPatterns=new Map,this.longForbiddenTokens=[];for(let i of this.forbiddenKeysSet)i.length<4?this.shortTokenBoundaryPatterns.set(i,new RegExp((()=>{let n=i.split("").map(o=>`[${o.toLowerCase()}${o.toUpperCase()}]`).join(""),s=`[a-z]${i.charAt(0).toUpperCase()}${i.slice(1)}`;return `(?:^|[_-])${n}(?:$|[_-])|${s}(?:$|[A-Z_-])|^${n}$`})())):this.longForbiddenTokens.push(i);}async scan(e,t=new WeakSet){if(e==null)return null;if(typeof e=="string"){let r=e.trim();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{let n=JSON.parse(r),s=await this.scan(n,t);if(s)return s}catch{}let i=this.checkString(e);if(i)return i;if(this.nerScanner){let n=await this.nerScanner.scan(e);if(n.detected){let s=n.entities.find(o=>o.type==="person");if(s)return `PII Entity Detected: person name "${s.text}"`}}return null}if(typeof e=="object"){if(t.has(e))return null;if(t.add(e),Array.isArray(e))for(let r of e){let i=await this.scan(r,t);if(i)return i}else for(let[r,i]of Object.entries(e)){if(this.forbiddenKeysSet.has(r.toLowerCase()))return `Forbidden Key: ${r}`;let n=this.checkKeyFuzzy(r);if(n)return n;let s=await this.scan(i,t);if(s)return s}}return null}checkKeyFuzzy(e){let t=e.toLowerCase();if(h.KEY_SAFELIST.has(t))return null;for(let[r,i]of this.shortTokenBoundaryPatterns)if(i.test(e))return `Forbidden Key (fuzzy): ${e} matches boundary pattern "${r}"`;for(let r of this.longForbiddenTokens)if(t.includes(r))return `Forbidden Key (fuzzy): ${e} contains restricted token "${r}"`;return null}checkString(e){for(let t of this.patterns)if(typeof t=="string"){if(e.toLowerCase().includes(t.toLowerCase()))return t}else if(t instanceof RegExp){if(t.global&&(t.lastIndex=0),t.test(e))return t.source}else if(typeof t=="object"&&t!==null){let r=t;if(typeof r.pattern=="string"){if(e.toLowerCase().includes(r.pattern.toLowerCase())&&(!r.validator||r.validator(r.pattern)))return r.name}else if(r.pattern instanceof RegExp){r.pattern.global&&(r.pattern.lastIndex=0);let i=r.pattern.exec(e);for(;i!==null;){let n=i[0];if(!r.validator||r.validator(n))return r.name;if(!r.pattern.global)break;i=r.pattern.exec(e);}}}return null}};var Pe=L.dirname(fileURLToPath(import.meta.url)),Re=class h{constructor(e,t){this.serverInfo=e;this.config=t;let r=this.config?.security?.enableNerScanning?new X:null;this.piiScanner=new ee(this.config?.security?.piiPatterns??Te.GLOBAL_STRICT,this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],r);let i=this.config?.security?.rateLimit;this.toolCallWindowMs=i?.windowMs??Number.parseInt(process.env.LIOP_RATE_LIMIT_WINDOW_MS??"60000",10),this.toolCallMaxPerWindow=i?.maxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_MAX??"15",10),this.globalCallMaxPerWindow=i?.globalMaxPerWindow??Number.parseInt(process.env.LIOP_RATE_LIMIT_GLOBAL_MAX??"40",10);let n=this.config?.security?.forbiddenKeys??["id","name","fullName","firstName","lastName","address","street","city","postalCode","zipCode","phone","email","ssn","accountHolder","accountNumber","account_number","password","token","secret","privateKey"],s=this.config?.security?.sensitiveKeys??[];this.taintAnalyzer=new V(n,s),this.auditLogger=this.config?.auditLogger||Se;let o=import.meta.url.endsWith(".ts"),a=o?".ts":".js",c=[];if(o)try{let f=createRequire(import.meta.url).resolve("tsx/package.json"),d=pathToFileURL(L.join(L.dirname(f),"dist","loader.mjs")).href;c.push("--import",d);}catch{c.push("--import","tsx");}let l=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let u=[L.resolve(Pe,`./workers/logic-execution${a}`),L.resolve(Pe,`../workers/logic-execution${a}`)],y=u.find(p=>S.existsSync(p))||u[1];this.workerPool=new Piscina({filename:y,minThreads:this.config?.workerPool?.minThreads??(l?0:2),maxThreads:this.config?.workerPool?.maxThreads??(l?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(l?500:5e3),maxQueue:this.config?.workerPool?.maxQueue??"auto",taskQueue:new FixedQueue,execArgv:c,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}});let v=this.config?.workerPool?.minThreads??(l?0:2);if(this.workerPool&&v>0)for(let p=0;p<v;p++)this.workerPool.run({isWarmup:true}).catch(f=>{b.debug(`[LiopServer] Worker pool warm-up ping failed: ${f.message}`);});try{this.enclavePqcKeypair=b$1.generateKeyPair();}catch{this.enclavePqcKeypair=void 0;}if(this.config?.auth?.role==="nexus"){let p=this.config.auth.issuer||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=this.config.auth.clients||[{client_id:process.env.LIOP_OAUTH_CLIENT_ID||"liop-mesh-agent",client_secret:process.env.LIOP_OAUTH_CLIENT_SECRET||"dev-secret-change-me",grant_types:["client_credentials"],scope:"liop:tools:call liop:tools:list liop:resources:read liop:schema:read liop:mesh:query"}],{provider:m,jwks:b}=be({issuer:p,clients:d});this.oauthProvider=m,this.jwtValidator=new q(p,f,b);}else if(this.config?.auth?.role==="node"){let p=this.config.auth.nexusUrl||process.env.LIOP_NEXUS_URL||"http://localhost:3000",f=this.config.auth.audience||H.audience,d=p.endsWith("/oidc")?p:`${p}/oidc`,m=new URL(`${d}/jwks`);this.jwtValidator=new q(p,f,m);}this.resource("LIOP Envelope Specification","liop://protocol/envelope-spec","Complete Logic-on-Origin envelope format, execution rules, and security constraints","text/plain",()=>Promise.resolve(this.buildEnvelopeSpec())),this.config?.auth?.revocationPath&&this.loadRevocationList();}serverInfo;config;static{a(this,"LiopServer");}logicCache=new Map;connectionStats=new Map;CACHE_TTL_MS=1440*60*1e3;THROTTLE_THRESHOLD=5;THROTTLE_COOLDOWN_MS=60*1e3;toolCallWindows=new Map;toolCallMaxPerWindow;toolCallWindowMs;globalCallWindow=[];globalCallMaxPerWindow;fieldQueryBudget=new Map;taintAnalyzer;tools=new Map;resources=new Map;prompts=new Map;activeSchema=null;sandboxRecords=[];piiScanner;workerPool;meshNode=null;rpcServer=null;boundPort=null;enclavePqcKeypair;jwtValidator;oauthProvider;sessions=new Map;revokedTokenHashes=new Set;lastRevocationLoadTime=0;pqcKeyPair=b$1.generateKeyPair();auditLogger;getDatasetHash(){return O__default.createHash("sha256").update(JSON.stringify(this.sandboxRecords||[])).digest("hex")}static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,\s*(?<name>[^}]*))?\}[\r\n]+(?<logic>[\s\S]*?)[\r\n]+@END/m;extractLogic(e){if(!e||typeof e!="string")return null;let t=e.trim().match(h.LIOP_COMPACT_REGEX);return t?.groups?.logic?t.groups.logic.trim():null}parseUnknownJson(e){if(typeof e!="string")return e;let t=e.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return e}return e}runPreflightPolicy(e,t,r,i="local-client"){if(r){let a=t.replace(/\s+/g," ");if(r.enforceAggregationFirst&&[/return\s+env\.records(?!\s*\.\s*(?:reduce|length|filter|every|some|find)\b)/i,/return\s*\{[\s\S]*\b(accounts|patients|rows|records)\s*:\s*env\.records(?!\s*\.\s*(?:reduce|length|filter)\b)/i].some(l=>l.test(a)))return "Preflight policy rejected: potential row-level export pattern detected.";if(r.preflightDenyPatterns?.some(c=>c.test(a)))return "Preflight policy rejected: custom deny pattern matched."}let n=50;typeof r?.enforceAggregationFirst=="object"&&(n=r.enforceAggregationFirst.minMaxBlockThreshold??50);let s=this.taintAnalyzer.analyze(t,this.sandboxRecords.length,n);if(s)return `Preflight policy rejected: ${s.reason}`;let o=this.taintAnalyzer.extractQueriedFields(t);if(o.length>0){if(i==="__proto__"||i==="constructor"||i==="prototype"||e==="__proto__"||e==="constructor"||e==="prototype")return "Preflight policy rejected: invalid property key names (prototype pollution guard).";let a=r?.budgetStorePath||this.config?.budgetStorePath;if(a)try{let c=this.executeWithBudgetLock(a,l=>{let u=l[i]||{},y=u[e]||{};for(let d of o){let m=this.taintAnalyzer.classifyField(d,r?.sensitiveKeys),b=25,T="public";if(r?.queryBudgetPerField!==void 0?(b=r.queryBudgetPerField,T="override"):m==="forbidden"?(b=3,T="forbidden"):m==="sensitive"&&(b=8,T="sensitive"),(y[d]??0)>=b)return {result:`Preflight policy rejected: Query budget exceeded for field '${d}' (max ${b} per session for ${T} fields). Rotate PQC session to reset budget.`}}let v={...y};for(let d of o)v[d]=(v[d]??0)+1;let p={...u};p[e]=v;let f={...l};return f[i]=p,{result:null,updatedBudget:f}});if(c)return c}catch(c){let l=c instanceof Error?c.message:String(c);b.error(`[LIOP-Server] Error applying persistent query budget: ${l}. Falling back to in-memory.`);let u=this.applyInMemoryBudget(i,e,o,r);if(u)return u}else {let c=this.applyInMemoryBudget(i,e,o,r);if(c)return c}}return null}validateOutputPolicy(e,t,r){if(!r)return null;let i=this.parseUnknownJson(t);if(i&&typeof i=="object"&&i.isError===true)return null;if(r.outputSchema){let s=(()=>{if(!(r.outputSchema instanceof z.ZodObject))return r.outputSchema;let o=r.outputSchema,a=o.def||o._def;return a&&a.catchall!==void 0&&!(a.catchall instanceof z.ZodNever)?o:o.strict()})().safeParse(i);if(!s.success)return `[LIOP] Output schema violation for ${e}: ${s.error.issues.map(o=>`${o.path.join(".")||"<root>"} ${o.message}`).join("; ")}. HINT: Your output must conform to the declared schema. Use 'env.records' to access the dataset and return only allowed fields.`}return r.enforceAggregationFirst&&this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(i),r.enforceAggregationFirst,this.sandboxRecords.length)?process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?"Aggregation-First Policy Violation: row-level export or K-Anonymity violation blocked. HINT: Use .reduce() to produce a flat {key:value} object. Do NOT use .map() to create arrays of objects. Ensure dataset size > 10 for detailed results.":"Aggregation-First Policy Violation: Output blocked due to privacy constraints.":null}unwrapForAggregationPolicyScan(e){if(typeof e=="string"){let n=e.trim();if(n.startsWith("{")&&n.endsWith("}")||n.startsWith("[")&&n.endsWith("]"))try{return this.unwrapForAggregationPolicyScan(JSON.parse(n))}catch{return e}return e}if(!e||typeof e!="object")return e;let t=e;if(t.computation_result!==void 0)return this.unwrapForAggregationPolicyScan(t.computation_result);if(!Array.isArray(t.content)||t.content.length===0)return e;let r=[];for(let n of t.content)if(n&&typeof n=="object"&&"text"in n){let s=n.text;typeof s=="string"&&r.push(s);}if(r.length===0)return e;let i=r.length===1?r[0]:r.join(`
|
|
9
|
+
`);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,t,r){if(!t)return false;let i=typeof t=="object"&&typeof t.maxOutputRows=="number"?t.maxOutputRows:10,n=typeof t=="object"&&typeof t.allowPrimitiveArrays=="boolean"?t.allowPrimitiveArrays:true;if(typeof e=="string"){let s=e.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{return this.violatesAggregationFirstPolicy(JSON.parse(s),t,r)}catch{return false}return false}if(Array.isArray(e))return e.length>0&&e.every(s=>typeof s=="object"&&s!==null)?e.length>i?true:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r)):e.length>0&&e.every(s=>typeof s!="object"||s===null)?!n:e.some(s=>this.violatesAggregationFirstPolicy(s,t,r));if(e&&typeof e=="object"){let s=Object.keys(e);return r!==void 0&&r>0&&r<10&&(s.length>3||Object.values(e).some(a=>Array.isArray(a)||typeof a=="object"&&a!==null))||s.length>i?true:Object.values(e).some(o=>this.violatesAggregationFirstPolicy(o,t,r))}return false}buildEnvelopeSpec(){let e=["LIOP v1 Envelope Specification","================================","","FORMAT:","","Compact Envelope:"," @LIOP{wasi_v1,TaskName}"," <JavaScript code>"," @END","","RUNTIME ENVIRONMENT:","- env.records: Array of data objects from the origin","- Must use 'return' to output results","- Zero-Trust WASI Sandbox (Node.js Worker Pool)","- Return aggregated objects, NOT raw row-level arrays","","SANDBOX RUNTIME RESTRICTIONS & WORKAROUNDS:","- Date is poisoned: The 'Date' class/constructor is undefined (Date.now(), Date.parse(), etc. will throw)."," Workaround: Use lexicographical string comparison on ISO 8601 date strings (e.g., record.date >= '2024-01-01').","- Poisoned globals: eval, Function, setTimeout, setInterval, Buffer, ArrayBuffer, and TypedArrays are undefined.","- Frozen prototypes: Any modifications to Object.prototype, Array.prototype, etc., are blocked.","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution","","DIFFERENTIAL PRIVACY (DP) MECHANISM (Laplace Mechanism):","- Default field noise scale is derived from node global sensitivity.","- COUNT / LENGTH Optimization: To obtain EXACT counts without noise (sensitivity=1),"," the return keys MUST contain 'count', 'length', 'size', 'num', 'positive', 'negative',"," or start with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count').","- AVERAGE Optimization: Keys containing 'avg', 'mean' or 'average' scale noise"," down automatically by dividing sensitivity by dataset size (sensitivity / n).","- SUM / OTHER queries: Receive full Laplace noise based on global node sensitivity"," (e.g., Sensitivity=100,000 in Bank to protect balances)."];return this.config?.security?.forbiddenKeys?.length&&e.push(`- Restricted fields: ${this.config.security.forbiddenKeys.join(", ")}`),e.push("","TAINT TRACKING (Phase 108):","- AST-level analysis blocks PII-derived scalars (charCodeAt, charAt, etc.)","- Operations on restricted fields are tracked through variable assignments","- Boolean inference (field.charCodeAt(0) < N ? 1 : 0) is blocked","- Allowed: aggregations on non-PII fields (balance, amount, date)","","K-ANONYMITY THRESHOLDS:","- Small Datasets (< 10 records): Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.","- Large Datasets (>= 10 records): Maximum of 10 output fields.","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)","","QUERY BUDGET TIERS (NIST SP 800-226):","- FORBIDDEN (PII fields like name, accountHolder): Blocked in AST preflight. Never executed, does not consume budget.","- SENSITIVE (fields marked via sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override).","- PUBLIC (all other fields): 25 queries per agent identity.","- PERSISTENCE: The budget is tracked by agent DID and persisted to disk, NOT by MCP session."," Reconnecting or starting a new session does NOT reset the budget."," Reset requires: administrator calling resetFieldBudget() or manual deletion of the budget store file.","","AUTHENTICATION (tokenSlug Convention):","- Restricted nodes declare authRequired: true in their manifest.","- Token resolution: LIOP_TOKEN_<tokenSlug> (deterministic) > LIOP_TOKEN_<PeerID> > LIOP_TOKEN_<ProviderName>","- Format: tokenSlug must match SCREAMING_SNAKE_CASE /^[A-Z][A-Z0-9_]*$/ (e.g., BANK, VAULT, HFT_ORACLE)."),e.join(`
|
|
10
|
+
`)}extractSchemaFieldSummary(e,t=0){if(t>3)return "{...}";let r=e.type,i=e.properties,n=e.items;return i?`{${Object.entries(i).map(([o,a])=>{let c=a.type;if(c==="array"&&a.items){let l=this.extractSchemaFieldSummary(a.items,t+1);return `${o}(array of ${l})`}if(c==="object"&&a.properties){let l=this.extractSchemaFieldSummary(a,t+1);return `${o}(${l})`}return `${o}(${c||"unknown"})`}).join(", ")}}`:r==="array"&&n?`Array of ${this.extractSchemaFieldSummary(n,t+1)}`:r||Object.keys(e).join(", ")}async connect(e={}){return this.connectToMesh(e)}tool(e,t,r,i,n){if(this.tools.has(e))throw new Error(`Tool already registered: ${e}`);let s=z.object(r),o=z.toJSONSchema(s,{target:"draft-07"}),a$1=t,c=i;if(r.payload&&r.payload instanceof z.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a$1+=`
|
|
11
|
+
|
|
12
|
+
Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. Note: If dataset size < 10 (synthetic demo), Egress K-Anonymity blocks output if it has >3 keys or any array/nested object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a$1+=`
|
|
13
|
+
Restricted fields: ${u.join(", ")}.`),this.activeSchema){let y=this.extractSchemaFieldSummary(this.activeSchema);a$1+=`
|
|
14
|
+
Data structure: ${y}. Full schema: resource liop://schema/global`;}c=a(async(y,v)=>{let p="global_connection",f=Date.now(),d=this.connectionStats.get(p)||{failures:0,lastAttempt:0};if(d.failures>=this.THROTTLE_THRESHOLD&&f-d.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let m=y&&typeof y=="object"?y:{},b=m.payload??m.envelope??m.code,T=m.__liop_bypass_ast_cache===true,A=O__default.createHash("sha256").update(b||"").digest("hex"),w=this.extractLogic(b),x=this.logicCache.get(A);if(!T&&x&&f-x.timestamp<this.CACHE_TTL_MS&&w){m.payload=w,m.envelope!==void 0&&(m.envelope=w);let I=this.runPreflightPolicy(e,w,n,"mcp-client");return I?{content:[{type:"text",text:I}],isError:true}:await this.executeInWorkerPool(y,w,e)}if(!w)return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:"Error: Malformed payload. Missing @LIOP boundary.\\nYou MUST wrap your logic exactly like this:\\n\\n@LIOP{wasi_v1,DynamicAudit}\\n// Your JS code here\\n@END"}],isError:true};try{let I=this.extractLogic(b);m.payload=I,m.envelope!==void 0&&(m.envelope=I);let N=this.runPreflightPolicy(e,I,n,"mcp-client");if(N)return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:N}],isError:!0};let M=await this.executeInWorkerPool(y,I,e);return M.isError?(d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d)):(this.connectionStats.set(p,{failures:0,lastAttempt:f}),this.logicCache.set(A,{hash:A,timestamp:f})),M}catch(I){let N=I;return d.failures++,d.lastAttempt=f,this.connectionStats.set(p,d),{content:[{type:"text",text:`ExecutionRuntimeException: ${N.message}`}],isError:true}}},"finalHandler");}let l={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a$1,inputSchema:l},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{b.info(`[LIOP-Mesh] Failed to auto-announce tool ${e}: ${u.message}`);});}prompt(e,t,r,i){if(this.prompts.has(e))throw new Error(`Prompt already registered: ${e}`);this.prompts.set(e,{prompt:{name:e,description:t,arguments:r},handler:i});}enableZeroShotAutonomy(){this.prompt("liop_blind_analyst","The official Logic-Injection-on-Origin Protocol system prompt. Instructs the LLM on how to securely inject Logic-on-Origin without violating PII or safety constraints.",[],e=>({description:"LIOP Blind Analyst Instructions",messages:[{role:"user",content:{type:"text",text:`You are the "Blind Analyst" operating within the Logic-Injection-on-Origin Protocol (LIOP) ecosystem.
|
|
15
|
+
Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
|
|
16
|
+
|
|
17
|
+
INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
|
|
18
|
+
1. DATA PRIVACY: NEVER attempt to export Personally Identifiable Information (PII). The LIOP Egress Shield will block any response containing raw IDs, names, or addresses.
|
|
19
|
+
2. AGGREGATION FIRST & K-ANONYMITY THRESHOLDS: Always prefer returning counts, averages, or anonymized summaries.
|
|
20
|
+
- Dataset < 10 records: Maximum of 3 scalar output fields. Nesting or arrays in output are strictly forbidden.
|
|
21
|
+
- Dataset >= 10 records: Maximum of 10 output fields.
|
|
22
|
+
3. LAPLACE DIFFERENTIAL PRIVACY (DP) COMPLIANCE:
|
|
23
|
+
- Legitimate COUNT queries: To obtain EXACT, un-noised counts, you MUST name your return keys containing 'count', 'length', 'size', 'num', 'positive', 'negative', or starting with 'total_' or 'num_' (e.g. 'total_tx', 'credits_count'). This forces sensitivity=1.0, rounds values, and clamps to non-negative values.
|
|
24
|
+
- Legitimate AVERAGE queries: Use 'avg_', '_average' or 'mean_' keys to automatically scale down Laplace noise by dividing sensitivity by the dataset size (sensitivity / n).
|
|
25
|
+
- Legitimate SUM queries: Return keys without count/average suffixes will receive full Laplacian noise scaled by the node's global sensitivity (which can be up to 100,000 in Bank nodes to protect raw balances). Do NOT attempt to bypass this by renaming sum fields to count fields, as it violates protocol integrity.
|
|
26
|
+
4. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
|
|
27
|
+
Structure:
|
|
28
|
+
@LIOP{wasi_v1,AnalysisTask}
|
|
29
|
+
// Your JS Code Here
|
|
30
|
+
@END
|
|
31
|
+
5. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
|
|
32
|
+
6. LOCALIZATION: Format all JSON response keys in the language used by the user in their query (e.g., use Spanish keys if the query is in Spanish).
|
|
33
|
+
7. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.
|
|
34
|
+
8. SANDBOX RUNTIME: The 'Date' class/constructor is poisoned and set to undefined. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw exceptions.
|
|
35
|
+
Workaround: Perform chronological operations and filtering using lexicographical string comparisons on ISO 8601 date strings (e.g., 'record.date >= "2024-01-01"').
|
|
36
|
+
Additionally, standard globals like 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', ArrayBuffer, and TypedArrays are also undefined.
|
|
37
|
+
9. QUERY BUDGET PERSISTENCE: The per-field query budget is tracked by your agent DID and persisted to disk. Reconnecting or starting a new MCP session does NOT reset the budget. If you receive "Query budget exceeded", you must use a different field or request an administrator to invoke resetFieldBudget().${this.activeSchema?`
|
|
38
|
+
|
|
39
|
+
CURRENT DATA DICTIONARY (STRICT):
|
|
40
|
+
${JSON.stringify(this.activeSchema,null,2)}`:""}
|
|
41
|
+
|
|
42
|
+
Protocol Adherence is mandatory for successful execution.`}}]}));}resource(e,t,r,i,n){if(this.resources.has(t))throw new Error(`Resource URI already registered: ${t}`);this.resources.set(t,{name:e,uri:t,description:r,mimeType:i,content:n});}buildExecutionGuidelines(){return ["LIOP Sandbox Execution Guidelines","=================================","","1. DATE POISONING & FILTERING WORKAROUND:"," The global 'Date' class is set to undefined inside the sandbox. Calling 'new Date()', 'Date.now()', or 'Date.parse()' will throw a ReferenceError."," - Workaround: Perform chronological filtering using lexicographical string comparisons on ISO 8601 strings."," Example: const filtered = env.records.filter(r => r.date >= '2024-01-01' && r.date <= '2024-12-31');","","2. K-ANONYMITY CONSTRAINTS:"," - Datasets with LESS than 10 records: The returned object must contain at most 3 scalar fields, and must NOT contain any arrays or nested objects."," - Datasets with 10 or MORE records: The returned object can contain up to 10 fields.","","3. DIFFERENTIAL PRIVACY SUFFIXES:"," To avoid Laplacian noise adding random perturbations to your counts or averages, you must name your object keys using specific terms:"," - Counts (Exact, no noise): Key names must contain 'count', 'length', 'size', 'num', 'positive', 'negative', or start with 'total_' or 'num_'."," - Averages (Reduced noise): Key names must contain 'avg', 'mean', or 'average'."," - Sums/Other: Will receive full Laplace noise.","","4. GENERAL RESTRICTIONS:"," - Do not use 'eval', 'Function', 'setTimeout', 'setInterval', 'Buffer', 'ArrayBuffer', or TypedArrays."," - Do not attempt to modify prototypes (Object.prototype, Array.prototype).","","5. QUERY BUDGET TIERS (NIST SP 800-226):"," The per-field query budget is tracked by agent DID and persisted to disk (not per MCP session)."," - FORBIDDEN (PII fields): Always blocked in AST preflight. Does not consume budget."," - SENSITIVE (sensitiveKeys): 8 queries per agent identity (or queryBudgetPerField override)."," - PUBLIC (other fields): 25 queries per agent identity."," - Reset requires administrator intervention via resetFieldBudget()."].join(`
|
|
43
|
+
`)}dataDictionary(e,t="Global Medical Data Dictionary",r="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){e.$comment="LIOP DIRECTIVES: 1. Date is undefined (Date.now(), new Date() throw). Workaround: use lexicographical string comparison on ISO 8601 string dates (e.g. record.date >= '2024-01-01'). 2. Small datasets (<10 records) limit outputs to max 3 scalar keys with NO nesting. 3. DP counts must contain count/length/size/num/total_ prefix/suffix.",this.activeSchema=e;let n=this.extractSchemaFieldSummary(e);for(let[s,o]of this.tools.entries())o.schema.shape.payload&&o.schema.shape.payload instanceof z.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
|
|
44
|
+
Data structure: ${n}. Full schema: resource ${r}. Guidelines: resource liop://schema/guidelines`,this.tools.set(s,o));this.resources.has("liop://schema/guidelines")||this.resource("LIOP Execution Guidelines","liop://schema/guidelines","Directives for generating compliant JavaScript code for the LIOP Sandbox runtime","text/plain",()=>Promise.resolve(this.buildExecutionGuidelines())),this.resource(t,r,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),b.info("[LIOP-SDK] AST Security Cache cleared by Admin.");}checkToolCallRateLimit(e){let t=Date.now(),r=this.toolCallWindowMs,i=this.toolCallMaxPerWindow,s=(this.toolCallWindows.get(e)||[]).filter(o=>t-o<r);if(s.length>=i){let o=Math.ceil((s[0]+r-t)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Too many calls to ${e}. Max ${i} per ${r/1e3}s window. Retry after ${o}s.`}],isError:true}}return s.push(t),this.toolCallWindows.set(e,s),null}checkGlobalRateLimit(){let e=Date.now(),t=this.toolCallWindowMs,r=this.globalCallMaxPerWindow;if(this.globalCallWindow=this.globalCallWindow.filter(i=>e-i<t),this.globalCallWindow.length>=r){let i=Math.ceil((this.globalCallWindow[0]+t-e)/1e3);return {content:[{type:"text",text:`LIOP_RATE_LIMITED: Global call limit exceeded. Max ${r} total calls per ${t/1e3}s window. Retry after ${i}s.`}],isError:true}}return this.globalCallWindow.push(e),null}async callTool(e,t="local-client"){let r=this.tools.get(e.name);if(!r)throw new Error(`Tool not found: ${e.name}`);let i=this.checkGlobalRateLimit();if(i)return i;let n=this.checkToolCallRateLimit(e.name);if(n)return n;try{let s=r.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(s.__liop_bypass_ast_cache=!0),s&&typeof s.payload=="string"){let a=s.payload,c=this.extractLogic(a);if(c){let l=this.runPreflightPolicy(e.name,c,r.policy,t);return l?{content:[{type:"text",text:l}],isError:!0}:(s.payload=c,await this.executeInWorkerPool(s,c,e.name))}}return await r.handler(s,{})}catch(s){let o=s;return o instanceof z.ZodError?{content:[{type:"text",text:`Validation Error: ${o.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${o.message}`}],isError:true}}}listTools(){return Array.from(this.tools.values()).map(e=>e.tool)}listPrompts(){return Array.from(this.prompts.values()).map(e=>e.prompt)}async getPrompt(e){let t=this.prompts.get(e.name);if(!t)throw new Error(`Prompt not found: ${e.name}`);return await t.handler(e)}listResources(){return Array.from(this.resources.values())}async readResource(e){let t=this.resources.get(e);if(!t)throw new Error(`Resource not found: ${e}`);let r="No description provided";return typeof t.content=="function"?r=await t.content():typeof t.content=="string"?r=t.content:t.description&&(r=t.description),{contents:[{uri:t.uri,mimeType:t.mimeType||"text/plain",text:r}]}}getServerInfo(){return this.serverInfo}getMeshNode(){return this.meshNode}setSandboxData(e){this.sandboxRecords=e;}getSandboxData(){return this.sandboxRecords}getBoundPort(){return this.boundPort}async connectToMesh(e={}){let t=process.env.LIOP_GRPC_PORT?Number.parseInt(process.env.LIOP_GRPC_PORT,10):void 0,r=e.port??t??50051,i=/^[A-Z][A-Z0-9_]*$/;if(this.config?.tokenSlug&&!i.test(this.config.tokenSlug))throw new Error(`Invalid tokenSlug "${this.config.tokenSlug}". Must match SCREAMING_SNAKE_CASE: /^[A-Z][A-Z0-9_]*$/ (e.g., "BANK", "VAULT", "HFT_ORACLE").`);this.meshNode=new a$1(e.meshConfig),await this.meshNode.start();let n=this.meshNode;this.meshNode.registerManifestHandler(()=>{let s=this.listTools().map(l=>{let u=this.tools.get(l.name);return {name:l.name,description:l.description,inputSchema:l.inputSchema,zkMode:u?.policy?.zkMode,guestImageId:u?.policy?.guestImageId??this.config?.guestImageId,circuitName:u?.policy?.circuitName,vkey:u?.policy?.vkey}}),o=Array.from(this.resources.values()).map(l=>({name:l.name,uri:l.uri,description:l.description,mimeType:l.mimeType,text:typeof l.content=="string"?l.content:l.description})),a={peerId:n.getPeerId(),grpcPort:r,tools:s,resources:o,serverInfo:this.serverInfo,authRequired:this.jwtValidator!==void 0,tokenSlug:this.config?.tokenSlug,guestImageId:this.config?.guestImageId,vkeys:this.config?.zkVkeys,taxonomy:this.config?.taxonomy?{domain:this.config.taxonomy.domain||"Unknown Domain",clearanceTier:this.config.taxonomy.clearanceTier??0,executionTypes:this.config.taxonomy.executionTypes||[]}:void 0},c=b$1.signManifest(a,this.pqcKeyPair.secretKey,this.pqcKeyPair.publicKey);return {...a,pqcSignature:c.signature,pqcPublicKey:c.publicKey}});for(let s of this.listTools())await this.meshNode.announceCapability(s.name).catch(b.info);await this.meshNode.announceManifest().catch(b.info),this.rpcServer=new J,this.rpcServer.addService({negotiateIntent:a((s,o)=>{let a=s.request;if(b.info(`[LIOP-RPC] Negotiating intent for capability: ${a.capability_hash}`),this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){o({code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){o({code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info(`[LIOP-RPC] Bypass authentication for matching localTestToken: ${y}`),import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:p})=>{let{publicKey:f,secretKey:d}=await p.generateKeyPair(),m=O__default.randomUUID();this.sessions.set(m,{capability_hash:a.capability_hash,kyber_sk:d,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:m,error_message:"",kyber_public_key:f});});return}o({code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}this.jwtValidator.validate(l).then(p=>{let f=a$3("tools/call",p);if(!f.allowed){o({code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:d})=>{let{publicKey:m,secretKey:b}=await d.generateKeyPair(),T=O__default.randomUUID();this.sessions.set(T,{capability_hash:a.capability_hash,kyber_sk:b,agent_did:a.agent_did,tokenHash:u,createdAt:Date.now()}),o(null,{accepted:true,session_token:T,error_message:"",kyber_public_key:m});});}).catch(p=>{o({code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p.message}`});});}else import('./kyber-PULV7PQX.js').then(async({Kyber768Wrapper:c})=>{let{publicKey:l,secretKey:u}=await c.generateKeyPair(),y=O__default.randomUUID();this.sessions.set(y,{capability_hash:a.capability_hash,kyber_sk:u,agent_did:a.agent_did,createdAt:Date.now()}),o(null,{accepted:true,session_token:y,error_message:"",kyber_public_key:l});});},"negotiateIntent"),executeLogic:a(async s=>{let o=s.request;b.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${o.session_token}`);let a$1=a(async()=>{let c=this.sessions.get(o.session_token);if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Invalid session token"});return}let l=3600*1e3;if(c.createdAt){let f=Date.now()-c.createdAt;if(f>l){this.sessions.delete(o.session_token),s.emit("error",{code:_.status.UNAUTHENTICATED,details:`[LIOP-PQC] Session secret expired: Age (${Math.round(f/1e3)}s) exceeds 3600s TTL limit. Re-handshake required.`});return}}if(c.tokenHash&&(this.loadRevocationList(),this.revokedTokenHashes.has(c.tokenHash))){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let u=c.capability_hash,v=(u?this.tools.get(u):void 0)?.policy,p="";try{let d=(await createMlKem768()).decap(new Uint8Array(o.pqc_ciphertext),c.kyber_sk),m=Buffer.from(d),b$1=Buffer.from(o.wasm_binary),T=b$1.subarray(-16),A=b$1.subarray(0,-16),w=O__default.createDecipheriv("aes-256-gcm",m,Buffer.from(o.aes_nonce||new Uint8Array(12)));w.setAuthTag(T);let x=w.update(A);x=Buffer.concat([x,w.final()]),p=x.toString("utf-8");let I=this.extractLogic(p)||p.trim(),N=this.runPreflightPolicy(u||"unknown_tool",I,v,c.agent_did||o.session_token);if(N){b.info(`[LIOP-RPC] Preflight blocked: ${N}`);let M={semantic_evidence:N,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(M,()=>{s.end();});return}}catch(f){let d=f instanceof Error?f.message:String(f);b.error(`[LIOP-RPC] Preflight decryption failed: ${d}`),s.emit("error",{code:_.status.INTERNAL,details:`Preflight logic analysis failed: ${d}`});return}try{let f$2=v?{epsilon:v.dpEpsilon??1,sensitivity:v.dpSensitivity??1,smallDatasetThreshold:v.dpSmallDatasetThreshold??50}:void 0,d=o.requested_proof_mode;(d===void 0||d===0)&&(v?.zkMode==="required"?d=2:v?.zkMode==="optimistic"?d=1:d=0);let m=await this.workerPool.run({ciphertext:o.pqc_ciphertext,secretKeyObj:Array.from(c.kyber_sk),wasmBinary:o.wasm_binary,inputs:o.inputs,aesNonce:o.aes_nonce,records:this.sandboxRecords,sessionToken:o.session_token,sessionTimestamp:c.createdAt,isEncrypted:!0,proofMode:d,guestImageId:v?.guestImageId??this.config?.guestImageId,pqcSigningKey:v?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:f$2});if(d===2&&m.proof_type!==2&&m.proof_type!==3){b.error(`[LIOP-RPC] Enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable for ${u||"tool"}`);let k={semantic_evidence:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0,proof_type:0};s.write(k,()=>{s.end();});return}let b$1=a$2(m.output),T,A=b$1;try{T=typeof b$1=="string"?b$1:JSON.stringify(b$1);let k=JSON.parse(T);if(k.__liop_proxy_tool){b.info(`[LIOP-RPC] Executing Proxied Tool: ${k.__liop_proxy_tool}`);let W=c.agent_did||"unknown-client",D=await this.callTool({name:k.__liop_proxy_tool,arguments:k.__liop_proxy_args||{}},W);if(D.isError){b.info(`[LIOP-RPC] Proxy tool execution failed: ${D.content[0].text}`);let U={semantic_evidence:D.content[0].text||"Unknown error",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(U,()=>{s.end();});return}let G=a$2(D);T=JSON.stringify(G),A=this.unwrapForAggregationPolicyScan(G);}}catch{T=String(b$1);}let w$1=this.validateOutputPolicy(u||"unknown_tool",A,v);if(w$1){b.info(`[LIOP-RPC] Output policy blocked for ${u||"unknown_tool"}: ${w$1}`);let D={semantic_evidence:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?w$1:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:!0};s.write(D,()=>{s.end();});return}let x$1={semantic_evidence:T,cryptographic_proof:Buffer.from(m.image_id||"","hex"),zk_receipt:m.zk_receipt?Buffer.from(m.zk_receipt,"base64"):Buffer.from(""),is_error:!1,proof_type:m.proof_type===3?3:m.proof_type===2?2:0,guest_image_id:m.guest_image_id||v?.guestImageId||this.config?.guestImageId||""},I=await this.piiScanner.scan(A),N=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(A),v?.enforceAggregationFirst,this.sandboxRecords?.length),M=!!(I||N);if(M){let k$1=I||"Aggregation-First Policy Violation";b.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${k$1}`),x$1.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",x$1.is_error=!0,k.inc({reason:I?"pii_scanner":"aggregation_policy"});}this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:m.fuel_consumed||0,outputHash:O__default.createHash("sha256").update(x$1.semantic_evidence).digest("hex"),zkReceiptSig:m.zk_receipt||"",status:M?"BLOCKED_EGRESS":"SUCCESS"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:M?"blocked_egress":"success",role:"executor"}),h$1.observe({capability:u||"unknown",tool:u||"unknown"},m.fuel_consumed||0);try{let k=Buffer.byteLength(x$1.semantic_evidence||"")+(x$1.cryptographic_proof?x$1.cryptographic_proof.length:0)+(x$1.zk_receipt?x$1.zk_receipt.length:0);if(w.inc({capability:u||"unknown"},k),this.sandboxRecords&&this.sandboxRecords.length>0){let W=JSON.stringify(this.sandboxRecords),D=Buffer.byteLength(W),G=Math.max(0,D-k);G>0&&x.inc({capability:u||"unknown"},G);try{let U=f$1.getInstance(),xe=U.countTokens(W),we=U.countTokens(x$1.semantic_evidence||""),Ie=U.countTokens(p||"");U.record({type:"tool_call",method:"ExecuteLogic",toolName:u||"unknown",estimatedInputTokens:Ie,estimatedOutputTokens:we,originDatasetTokens:xe});}catch{}}}catch{}s.write(x$1,()=>{s.end();});}catch(f$1){let d=f$1,m=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",b$1=d.message||String(f$1);b.error(`[LIOP-RPC] Execution Error: ${b$1}`);let T=m?`Execution Error: ${b$1}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.";this.auditLogger.recordExecution({agentDid:c.agent_did||"unknown",peerId:c.tokenHash||"unknown",toolName:u||"unknown",datasetHash:this.getDatasetHash(),fuelConsumed:0,outputHash:O__default.createHash("sha256").update(T).digest("hex"),zkReceiptSig:"",status:"ERROR"}),f.inc({capability:u||"unknown",tool:u||"unknown",status:"error",role:"executor"}),g$1.inc({capability:u||"unknown",error_type:"runtime_error"});let A={semantic_evidence:T,cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{s.write(A,()=>{s.end();});}catch{s.end();}}},"proceed");if(this.jwtValidator){let c=s.metadata.get("authorization")[0];if(!c){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Missing Authorization header in gRPC metadata"});return}let l=c.startsWith("Bearer ")?c.slice(7):c,u=O__default.createHash("sha256").update(l).digest("hex").toLowerCase();if(this.loadRevocationList(),this.revokedTokenHashes.has(u)){s.emit("error",{code:_.status.UNAUTHENTICATED,details:"Token has been revoked by the resource owner"});return}let y=this.config?.auth?.localTestToken,v=/^[a-zA-Z0-9_-]+-local-test-token$/;if(y){if(l===y){b.info(`[LIOP-RPC] Bypass authentication in executeLogic for matching localTestToken: ${y}`),await a$1();return}s.emit("error",{code:_.status.PERMISSION_DENIED,details:l&&v.test(l)?"Pre-shared local test token is invalid for this resource domain (segregation violation).":"Access Denied: This restricted node requires its specific static access token."});return}try{let p=await this.jwtValidator.validate(l),f=a$3("tools/call",p);if(!f.allowed){s.emit("error",{code:_.status.PERMISSION_DENIED,details:f.reason||"Access Denied"});return}await a$1();}catch(p){s.emit("error",{code:_.status.UNAUTHENTICATED,details:`Invalid JWT token: ${p instanceof Error?p.message:String(p)}`});}}else await a$1();},"executeLogic")}),this.boundPort=await this.rpcServer.listen(r),b.info(`[LIOP-SDK] Node successfully announced to Mesh. PeerID: ${this.meshNode.getPeerId()}`);}async executeInWorkerPool(e,t,r){try{let i=r?this.tools.get(r)?.policy:void 0,n=i?{epsilon:i.dpEpsilon??1,sensitivity:i.dpSensitivity??1,smallDatasetThreshold:i.dpSmallDatasetThreshold??50}:void 0,s=0;i?.zkMode==="required"?s=2:i?.zkMode==="optimistic"&&(s=1);let o=await this.workerPool.run({ciphertext:new Uint8Array(0),secretKeyObj:Array.from(new Uint8Array(0)),kyberPublicKey:new Uint8Array(0),wasmBinary:Buffer.from(t),inputs:{},records:this.sandboxRecords,sessionToken:"local-dev-token",isEncrypted:!1,proofMode:s,guestImageId:i?.guestImageId??this.config?.guestImageId,pqcSigningKey:i?.pqcSign?this.enclavePqcKeypair?.secretKey:void 0,dpConfig:n});if(s===2&&o.proof_type!==2&&o.proof_type!==3)return {content:[{type:"text",text:"[LIOP-ZK] Clearance Tier 1 enclave policy violation: Valid Groth16 zero-knowledge proof required but unavailable."}],isError:!0};let a=o.output,c=a$2(a),u=[{type:"text",text:JSON.stringify({computation_result:c,image_id:o.image_id,zk_receipt:o.zk_receipt,proof_type:o.proof_type===3?"GROTH16_PQC_HYBRID":o.proof_type===2?"GROTH16":"HMAC_LEGACY",guest_image_id:o.guest_image_id,status:"Worker Pool Execution Success"})}],y=r?this.tools.get(r)?.policy:void 0,v=this.validateOutputPolicy(r||"unknown_tool",c,y);if(v)return b.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${v}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?v:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let p=await this.piiScanner.scan(c),f=this.violatesAggregationFirstPolicy(c,y?.enforceAggregationFirst,this.sandboxRecords?.length);if(p||f){let d=p||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return b.info(`[LIOP-SDK] Secure egress blocked in local execution: ${d}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${d}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:u}}catch(i){let n=i,s=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1",o=n.message||String(i);return b.error(`[LIOP-SDK] WorkerPool Execution Fault: ${o}`),{content:[{type:"text",text:o.includes("worker_thread_exited")||o.includes("ERR_WORKER_OUT_OF_MEMORY")||o.includes("terminated")||o.includes("heap limit")?"[LIOP] Execution terminated: memory limit exceeded (64MB heap). Reduce data processing volume.":s?`WorkerPoolError: ${o}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error."}],isError:true}}}async close(){this.workerPool&&await this.workerPool.close({force:true}),this.rpcServer&&await this.rpcServer.stop(),this.meshNode&&await this.meshNode.stop();}loadRevocationList(){let e=this.config?.auth?.revocationPath;if(e)try{if(S.existsSync(e)){let t=S.statSync(e);if(t.mtimeMs<=this.lastRevocationLoadTime)return;let r=S.readFileSync(e,"utf-8"),i=JSON.parse(r);if(Array.isArray(i)){this.revokedTokenHashes.clear();for(let n of i)typeof n=="string"&&this.revokedTokenHashes.add(n.trim().toLowerCase());this.lastRevocationLoadTime=t.mtimeMs,b.info(`[LiopServer] Loaded ${this.revokedTokenHashes.size} revoked token hashes from ${e}`);}}else {let t=L.dirname(e);S.existsSync(t)||S.mkdirSync(t,{recursive:!0}),S.writeFileSync(e,JSON.stringify([],null,2),"utf-8"),this.lastRevocationLoadTime=Date.now(),b.info(`[LiopServer] Created empty local revocation list at ${e}`);}}catch(t){b.error(`[LiopServer] Failed to load revocation list: ${t instanceof Error?t.message:String(t)}`);}}revokeToken(e){if(!e)return;let t=O__default.createHash("sha256").update(e).digest("hex").toLowerCase();this.revokeTokenHash(t);}revokeTokenHash(e){if(!e)return;let t=e.toLowerCase();this.loadRevocationList(),this.revokedTokenHashes.add(t);let r=this.config?.auth?.revocationPath;if(r)try{let i=L.dirname(r);S.existsSync(i)||S.mkdirSync(i,{recursive:!0});let n=Array.from(this.revokedTokenHashes);S.writeFileSync(r,JSON.stringify(n,null,2),"utf-8");let s=S.statSync(r);this.lastRevocationLoadTime=s.mtimeMs,b.info(`[LiopServer] Persisted revocation for hash ${t} to ${r}`);}catch(i){b.error(`[LiopServer] Failed to persist revocation: ${i instanceof Error?i.message:String(i)}`);}}resetFieldBudget(e,t){if(e==="__proto__"||e==="constructor"||e==="prototype"||t&&(t==="__proto__"||t==="constructor"||t==="prototype")){b.warn(`[LiopServer] Rejected resetFieldBudget for unsafe clientId/toolName: ${e}`);return}if(t){let i=this.fieldQueryBudget.get(e);i&&i.delete(t);}else this.fieldQueryBudget.delete(e);let r=this.config?.budgetStorePath;if(r)try{this.executeWithBudgetLock(r,i=>(t?Object.hasOwn(i,e)&&i[e]&&delete i[e][t]:Object.hasOwn(i,e)&&delete i[e],{result:void 0,updatedBudget:i})),b.info(`[LiopServer] Reset query budget for client ${e}${t?` / tool ${t}`:""}`);}catch(i){b.error(`[LiopServer] Failed to reset persistent budget: ${i instanceof Error?i.message:String(i)}`);}}getPersistentBudget(e){try{if(!S.existsSync(e))return Object.create(null);let t=S.readFileSync(e,"utf-8"),r=JSON.parse(t||"{}");if(r&&typeof r=="object"){let i=Object.create(null);for(let[n,s]of Object.entries(r))n!=="__proto__"&&n!=="constructor"&&n!=="prototype"&&(i[n]=s);return i}return Object.create(null)}catch{return Object.create(null)}}savePersistentBudget(e,t){let r=`${e}.tmp`,i=L.dirname(e);S.existsSync(i)||S.mkdirSync(i,{recursive:true}),S.writeFileSync(r,JSON.stringify(t,null,2),"utf-8"),S.renameSync(r,e);}executeWithBudgetLock(e,t){let r=`${e}.lock`,i=100,s=0,o=L.dirname(e);if(!S.existsSync(o))try{S.mkdirSync(o,{recursive:!0});}catch{}for(;s<i;)try{S.writeFileSync(r,process.pid.toString(),{flag:"wx"});break}catch(a){if(a&&typeof a=="object"&&"code"in a&&a.code==="EEXIST"){s++;}else throw a}if(s>=i)throw new Error("Timeout acquiring lock for persistent query budget database");try{let a=this.getPersistentBudget(e),{result:c,updatedBudget:l}=t(a);return l&&this.savePersistentBudget(e,l),c}finally{try{S.existsSync(r)&&S.unlinkSync(r);}catch{}}}applyInMemoryBudget(e,t,r,i){let n=this.fieldQueryBudget.get(e);n||(n=new Map,this.fieldQueryBudget.set(e,n));let s=n.get(t);s||(s=new Map,n.set(t,s));for(let o of r){let a=this.taintAnalyzer.classifyField(o,i?.sensitiveKeys),c=25,l="public";if(i?.queryBudgetPerField!==void 0?(c=i.queryBudgetPerField,l="override"):a==="forbidden"?(c=3,l="forbidden"):a==="sensitive"&&(c=8,l="sensitive"),(s.get(o)??0)>=c)return `Preflight policy rejected: Query budget exceeded for field '${o}' (max ${c} per session for ${l} fields). Rotate PQC session to reset budget.`}for(let o of r){let a=s.get(o)??0;s.set(o,a+1);}return null}};
|
|
45
|
+
export{J as a,ve as b,Ee as c,ie as d,Se as e,H as f,q as g,be as h,X as i,R as j,Te as k,ee as l,Re as m};//# sourceMappingURL=chunk-YD2AF2M6.js.map
|
|
46
|
+
//# sourceMappingURL=chunk-YD2AF2M6.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';import {Buffer}from'buffer';import {mkdir,writeFile,readFile}from'fs/promises';import {dirname}from'path';import {generateKey}from'@libp2p/pnet';var n=95;function x(){let r=new Uint8Array(n);return generateKey(r),r}a(x,"createSwarmKey");function S(r){if(r.length!==n)throw new Error(`Invalid Swarm Key length: expected ${n} bytes, got ${r.length}`);return Buffer.from(r).toString("base64")}a(S,"serializeSwarmKey");function w(r){let e=r.trim(),t=Buffer.from(e,"base64");if(t.length!==n)throw new Error(`Invalid deserialized Swarm Key: expected ${n} bytes, got ${t.length}`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}a(w,"deserializeSwarmKey");function g(r){let e=r.trim();if(e.startsWith("/key/swarm/psk/")){let t=e.replace(/\r\n/g,`
|
|
2
|
+
`).trimEnd(),o=new TextEncoder().encode(t);if(o.length===n)return o}return w(e)}a(g,"parseSwarmKey");async function K(r,e){if(r.length!==n)throw new Error(`Cannot save invalid Swarm Key: expected ${n} bytes, got ${r.length}`);await mkdir(dirname(e),{recursive:true}),await writeFile(e,r);}a(K,"saveSwarmKey");async function A(r){let e=await readFile(r);if(e.length===n)return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);let t=e.toString("utf-8");return g(t)}a(A,"loadSwarmKey");export{n as a,x as b,S as c,w as d,g as e,K as f,A as g};//# sourceMappingURL=chunk-YLCNV764.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-YLCNV764.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a}from'./chunk-AYDF3IFZ.js';function p(r){return !r||Object.keys(r).length===0?"":`{${Object.entries(r).sort(([t],[s])=>t.localeCompare(s)).map(([t,s])=>`${t}="${String(s).replace(/"/g,'\\"')}"`).join(",")}}`}a(p,"formatLabels");function u(r){return r?Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join("|"):""}a(u,"labelsToKey");var h=class{constructor(e,t){this.name=e;this.help=t;}name;help;static{a(this,"Counter");}values=new Map;inc(e,t=1){if(t<0)throw new Error("Counter increments must be non-negative");let s=u(e),o=this.values.get(s)||{value:0,labels:e};o.value+=t,this.values.set(s,o);}get(e){let t=u(e);return this.values.get(t)?.value||0}reset(){this.values.clear();}toPrometheus(){let e=[`# HELP ${this.name} ${this.help}`,`# TYPE ${this.name} counter`];if(this.values.size===0)return e.push(`${this.name} 0`),e;for(let t of this.values.values())e.push(`${this.name}${p(t.labels)} ${t.value}`);return e}},m=class{constructor(e,t){this.name=e;this.help=t;}name;help;static{a(this,"Gauge");}values=new Map;set(e,t){if(typeof e=="number"){this.values.set("",{value:e});return}let s=e,o=typeof t=="number"?t:0,i=u(s);this.values.set(i,{value:o,labels:s});}inc(e,t=1){let s=u(e),o=this.values.get(s)||{value:0,labels:e};o.value+=t,this.values.set(s,o);}dec(e,t=1){let s=u(e),o=this.values.get(s)||{value:0,labels:e};o.value-=t,this.values.set(s,o);}get(e){let t=u(e);return this.values.get(t)?.value||0}reset(){this.values.clear();}toPrometheus(){let e=[`# HELP ${this.name} ${this.help}`,`# TYPE ${this.name} gauge`];if(this.values.size===0)return e.push(`${this.name} 0`),e;for(let t of this.values.values())e.push(`${this.name}${p(t.labels)} ${t.value}`);return e}},g=class{constructor(e,t,s=[5,10,25,50,100,250,500,1e3,2500,5e3,1e4]){this.name=e;this.help=t;this.buckets=[...s].sort((o,i)=>o-i);}name;help;static{a(this,"Histogram");}buckets;observations=new Map;observe(e,t){let s,o;typeof e=="number"?o=e:(s=e,o=typeof t=="number"?t:0);let i=u(s),a=this.observations.get(i);a||(a={count:0,sum:0,bucketCounts:new Map(this.buckets.map(l=>[l,0])),labels:s},this.observations.set(i,a)),a.count+=1,a.sum+=o;for(let l of this.buckets)if(o<=l){let _=a.bucketCounts.get(l)||0;a.bucketCounts.set(l,_+1);}}reset(){this.observations.clear();}toPrometheus(){let e=[`# HELP ${this.name} ${this.help}`,`# TYPE ${this.name} histogram`];if(this.observations.size===0)return e.push(`${this.name}_count 0`),e.push(`${this.name}_sum 0`),e;for(let t of this.observations.values()){let s=t.labels||{};for(let i of this.buckets){let a={...s,le:String(i)};e.push(`${this.name}_bucket${p(a)} ${t.bucketCounts.get(i)||0}`);}let o={...s,le:"+Inf"};e.push(`${this.name}_bucket${p(o)} ${t.count}`),e.push(`${this.name}_sum${p(s)} ${t.sum}`),e.push(`${this.name}_count${p(s)} ${t.count}`);}return e}},b=class{static{a(this,"MetricsRegistry");}counters=new Map;gauges=new Map;histograms=new Map;counter(e,t){let s=this.counters.get(e);return s||(s=new h(e,t),this.counters.set(e,s)),s}gauge(e,t){let s=this.gauges.get(e);return s||(s=new m(e,t),this.gauges.set(e,s)),s}histogram(e,t,s){let o=this.histograms.get(e);return o||(o=new g(e,t,s),this.histograms.set(e,o)),o}collectProcessMetrics(){if(this.gauge("liop_process_uptime_seconds","Process uptime in seconds").set(Math.floor(process.uptime())),this.gauge("liop_node_health_status","Operational health status of the LIOP node (1 = healthy, 0 = degraded)").set(1),typeof process.memoryUsage=="function"){let s=process.memoryUsage();this.gauge("liop_process_memory_rss_bytes","Resident set size memory in bytes").set(s.rss),this.gauge("liop_process_memory_heap_used_bytes","Heap memory used in bytes").set(s.heapUsed),this.gauge("liop_process_memory_heap_total_bytes","Total V8 allocated heap memory in bytes").set(s.heapTotal),this.gauge("liop_process_memory_external_bytes","External memory bound to C++ objects and buffers in bytes").set(s.external);}}exportPrometheusText(){this.collectProcessMetrics();let e=[];for(let t of this.counters.values())e.push(...t.toPrometheus());for(let t of this.gauges.values())e.push(...t.toPrometheus());for(let t of this.histograms.values())e.push(...t.toPrometheus());return e.push(""),e.join(`
|
|
2
|
+
`)}resetAll(){for(let e of this.counters.values())e.reset();for(let e of this.gauges.values())e.reset();for(let e of this.histograms.values())e.reset();}},n=new b,d=n.counter("liop_tool_calls_total","Total number of tool logic-injection executions"),y=n.counter("liop_tool_call_errors_total","Total number of failed tool logic-injection executions or policy rejections"),k=n.histogram("liop_fuel_consumed_total","Deterministic fuel units consumed by injected logic",[100,500,1e3,2500,5e3,1e4,5e4,1e5]),x=n.gauge("liop_mesh_peers_connected","Active peer connections in the P2P mesh"),M=n.gauge("liop_manifest_cache_size","Number of verified remote tool manifests in cache"),$=n.counter("liop_egress_blocks_total","Total number of outputs blocked by Egress Shield"),T=n.histogram("liop_zk_verification_duration_ms","Duration of ZK-Receipt and HMAC cryptographic attestation in ms",[1,2,5,10,25,50,100,250,500]),P=n.counter("liop_zk_verifications_total","Total number of ZK-Receipt cryptographic attestation checks"),L=n.counter("liop_zk_proofs_by_type_total","Total number of verified ZK receipts partitioned by proof type (groth16, hmac)"),w=n.histogram("liop_zk_proving_duration_ms","Duration of native ZK proof generation in ms",[10,25,50,100,250,500,1e3,2500]),C=n.gauge("liop_zk_vkey_cache_size","Number of registered verification keys in memory cache"),z=n.counter("liop_tokens_input_total","Total BPE input tokens processed by LIOP"),E=n.counter("liop_tokens_output_total","Total BPE output tokens emitted by LIOP"),j=n.counter("liop_tokens_saved_total","Estimated tokens saved compared to MCP context-pulling baseline"),D=n.histogram("liop_operation_duration_ms","End-to-end operation duration in ms",[5,15,30,50,100,250,500,1e3,2500,5e3]),H=n.histogram("liop_pqc_handshake_duration_ms","Duration of ML-KEM-768 post-quantum cryptographic key encapsulation in ms",[1,5,10,25,50,100,250,500]),K=n.counter("liop_pqc_handshakes_total","Total number of ML-KEM-768 key encapsulation operations"),S=n.counter("liop_wire_egress_bytes_total","Total wire egress bytes emitted by logic executions"),B=n.counter("liop_wire_saved_bytes_total","Estimated wire egress bytes saved compared to MCP context extraction baseline");export{h as a,m as b,g as c,b as d,n as e,d as f,y as g,k as h,x as i,M as j,$ as k,T as l,P as m,L as n,w as o,C as p,z as q,E as r,j as s,D as t,H as u,K as v,S as w,B as x};//# sourceMappingURL=chunk-ZZMSFCJP.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-ZZMSFCJP.js.map
|
package/dist/client.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import './verifier-
|
|
2
|
-
import './
|
|
3
|
-
export { c as LiopClient } from './index-
|
|
4
|
-
import './
|
|
1
|
+
import './verifier-DqZ9MQ9l.js';
|
|
2
|
+
import './node-Djzm6UYd.js';
|
|
3
|
+
export { c as LiopClient } from './index-BYDtRGue.js';
|
|
4
|
+
import './zk-DzYNWBgo.js';
|
|
5
|
+
import './types-29zv9X1V.js';
|
|
6
|
+
import '@grpc/grpc-js';
|
|
5
7
|
import 'node:events';
|
|
6
8
|
import 'zod';
|
|
7
9
|
import 'jose';
|
package/dist/client.js
CHANGED
|
@@ -1,10 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
import './chunk-32ADSAJS.js';
|
|
3
|
-
import './chunk-OUUTDSOW.js';
|
|
4
|
-
import './chunk-QLCOEP5J.js';
|
|
5
|
-
import './chunk-WSW6YJNY.js';
|
|
6
|
-
import './chunk-PYKRQAER.js';
|
|
7
|
-
import './chunk-74CISO2I.js';
|
|
8
|
-
import './chunk-72MNYFR6.js';
|
|
9
|
-
//# sourceMappingURL=client.js.map
|
|
1
|
+
export{c as LiopClient}from'./chunk-WP5ER7RH.js';import'./chunk-N35BC62H.js';import'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';import'./chunk-Y675R34Z.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-V35CXJQN.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=client.js.map
|
|
10
2
|
//# sourceMappingURL=client.js.map
|
package/dist/gateway.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import './
|
|
2
|
-
import './index-
|
|
3
|
-
|
|
1
|
+
import './node-Djzm6UYd.js';
|
|
2
|
+
import './index-ByzjpRCk.js';
|
|
3
|
+
import './types-29zv9X1V.js';
|
|
4
|
+
export { L as LiopHybridGateway } from './hybrid-BZpCiUaV.js';
|
|
4
5
|
import 'zod';
|
|
5
|
-
import './
|
|
6
|
+
import './zk-DzYNWBgo.js';
|
|
6
7
|
import 'jose';
|
|
7
|
-
import './verifier-
|
|
8
|
+
import './verifier-DqZ9MQ9l.js';
|
package/dist/gateway.js
CHANGED
|
@@ -1,11 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
import './chunk-547TYL27.js';
|
|
3
|
-
import './chunk-32ADSAJS.js';
|
|
4
|
-
import './chunk-OUUTDSOW.js';
|
|
5
|
-
import './chunk-QLCOEP5J.js';
|
|
6
|
-
import './chunk-U5BZ66VX.js';
|
|
7
|
-
import './chunk-WSW6YJNY.js';
|
|
8
|
-
import './chunk-PYKRQAER.js';
|
|
9
|
-
import './chunk-72MNYFR6.js';
|
|
10
|
-
//# sourceMappingURL=gateway.js.map
|
|
1
|
+
export{j as LiopHybridGateway}from'./chunk-LEXMMIQI.js';import'./chunk-LM26HOJ6.js';import'./chunk-6KFKO6ZX.js';import'./chunk-TKLRW52V.js';import'./chunk-Y675R34Z.js';import'./chunk-XLVEDKM6.js';import'./chunk-2ZYX736J.js';import'./chunk-ECRS6N33.js';import'./chunk-ZZMSFCJP.js';import'./chunk-GWVSCZUS.js';import'./chunk-6VK2XALI.js';import'./chunk-3WRKTVOF.js';import'./chunk-AYDF3IFZ.js';//# sourceMappingURL=gateway.js.map
|
|
11
2
|
//# sourceMappingURL=gateway.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { MeshNode } from './
|
|
2
|
-
import { L as LiopServer } from './index-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { a as MeshNode } from './node-Djzm6UYd.js';
|
|
2
|
+
import { L as LiopServer } from './index-ByzjpRCk.js';
|
|
3
|
+
import { b as McpRequest, M as McpEra, A as AuthInfo, c as McpResponse, G as GatewayInterceptorOptions } from './types-29zv9X1V.js';
|
|
4
|
+
import { L as LiopVerifier } from './verifier-DqZ9MQ9l.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* LIOP Sliding-Window Rate Limiter
|
|
@@ -153,9 +153,10 @@ declare class LiopHybridGateway {
|
|
|
153
153
|
private jwtValidator?;
|
|
154
154
|
private oauthProvider?;
|
|
155
155
|
private rateLimiter;
|
|
156
|
+
private readonly interceptorOptions?;
|
|
156
157
|
private isDraining;
|
|
157
158
|
private activeRequests;
|
|
158
|
-
constructor(liopServer: LiopServer, meshNode?: MeshNode | null, rpcPort?: number, rateLimiterOptions?: RateLimiterOptions);
|
|
159
|
+
constructor(liopServer: LiopServer, meshNode?: MeshNode | null, rpcPort?: number, rateLimiterOptions?: RateLimiterOptions, interceptorOptions?: GatewayInterceptorOptions);
|
|
159
160
|
private setupH2Routes;
|
|
160
161
|
private setupH1Routes;
|
|
161
162
|
private handleGrpcStream;
|