@nekzus/liop 2.5.0-beta.2 → 2.5.0-beta.4

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.
Files changed (109) hide show
  1. package/README.md +87 -40
  2. package/dist/bin/agent.js +27 -894
  3. package/dist/bridge.d.ts +4 -3
  4. package/dist/bridge.js +1 -4
  5. package/dist/chunk-2XHSALII.js +3 -0
  6. package/dist/chunk-2ZYX736J.js +2 -0
  7. package/dist/chunk-3WRKTVOF.js +2 -0
  8. package/dist/chunk-6KFKO6ZX.js +2 -0
  9. package/dist/chunk-6VK2XALI.js +2 -0
  10. package/dist/chunk-AYDF3IFZ.js +2 -0
  11. package/dist/chunk-CTTTLCGL.js +31 -0
  12. package/dist/chunk-ECRS6N33.js +4 -0
  13. package/dist/chunk-FDJMH4CB.js +2 -0
  14. package/dist/chunk-FTF6AMF6.js +0 -1
  15. package/dist/chunk-GWVSCZUS.js +2 -0
  16. package/dist/chunk-LEXMMIQI.js +15 -0
  17. package/dist/chunk-LM26HOJ6.js +31 -0
  18. package/dist/chunk-MQ5SU26J.js +2 -0
  19. package/dist/chunk-N35BC62H.js +2 -0
  20. package/dist/chunk-P6IJ3VBD.js +3 -0
  21. package/dist/chunk-TKLRW52V.js +2 -0
  22. package/dist/chunk-V35CXJQN.js +2 -0
  23. package/dist/chunk-WP5ER7RH.js +3 -0
  24. package/dist/chunk-XLVEDKM6.js +2 -0
  25. package/dist/chunk-Y675R34Z.js +2 -0
  26. package/dist/chunk-YD2AF2M6.js +46 -0
  27. package/dist/chunk-YLCNV764.js +3 -0
  28. package/dist/chunk-ZZMSFCJP.js +3 -0
  29. package/dist/client.d.ts +5 -4
  30. package/dist/client.js +1 -11
  31. package/dist/gateway.d.ts +6 -5
  32. package/dist/gateway.js +1 -11
  33. package/dist/{hybrid-DWe1bMoV.d.ts → hybrid-BZpCiUaV.d.ts} +4 -4
  34. package/dist/{index-BuEQtBHD.d.ts → index-BYDtRGue.d.ts} +8 -4
  35. package/dist/{index-CdW8j8Bn.d.ts → index-ByzjpRCk.d.ts} +30 -2
  36. package/dist/index.d.ts +57 -10
  37. package/dist/index.js +4 -317
  38. package/dist/kyber-PULV7PQX.js +2 -0
  39. package/dist/mesh.d.ts +1 -1
  40. package/dist/mesh.js +1 -5
  41. package/dist/{node-B0b2vUFS.d.ts → node-Djzm6UYd.d.ts} +8 -0
  42. package/dist/protocol/liop_core.proto +22 -6
  43. package/dist/server.d.ts +4 -3
  44. package/dist/server.js +1 -8
  45. package/dist/{types-CzRSOlOo.d.ts → types-29zv9X1V.d.ts} +3 -0
  46. package/dist/types.d.ts +2 -1
  47. package/dist/types.js +1 -2
  48. package/dist/verifier-DqZ9MQ9l.d.ts +82 -0
  49. package/dist/verifier-J4NQYZX5.js +2 -0
  50. package/dist/workers/logic-execution.d.ts +7 -0
  51. package/dist/workers/logic-execution.js +1 -271
  52. package/dist/workers/zk-verifier.d.ts +9 -0
  53. package/dist/workers/zk-verifier.js +1 -173
  54. package/dist/zk-DzYNWBgo.d.ts +104 -0
  55. package/package.json +7 -2
  56. package/dist/bin/agent.js.map +0 -1
  57. package/dist/bridge.js.map +0 -1
  58. package/dist/chunk-2KSO3W4A.js +0 -77
  59. package/dist/chunk-2KSO3W4A.js.map +0 -1
  60. package/dist/chunk-2STZHJ24.js +0 -114
  61. package/dist/chunk-2STZHJ24.js.map +0 -1
  62. package/dist/chunk-3QH44NKZ.js +0 -115
  63. package/dist/chunk-3QH44NKZ.js.map +0 -1
  64. package/dist/chunk-5SWHE62F.js +0 -3683
  65. package/dist/chunk-5SWHE62F.js.map +0 -1
  66. package/dist/chunk-7BSCUYUE.js +0 -421
  67. package/dist/chunk-7BSCUYUE.js.map +0 -1
  68. package/dist/chunk-7PITYWOV.js +0 -68
  69. package/dist/chunk-7PITYWOV.js.map +0 -1
  70. package/dist/chunk-EJ426URA.js +0 -818
  71. package/dist/chunk-EJ426URA.js.map +0 -1
  72. package/dist/chunk-FCFTYOAS.js +0 -793
  73. package/dist/chunk-FCFTYOAS.js.map +0 -1
  74. package/dist/chunk-FTF6AMF6.js.map +0 -1
  75. package/dist/chunk-IK7CGWAZ.js +0 -24
  76. package/dist/chunk-IK7CGWAZ.js.map +0 -1
  77. package/dist/chunk-K3DGJLUY.js +0 -106
  78. package/dist/chunk-K3DGJLUY.js.map +0 -1
  79. package/dist/chunk-PAICJCKJ.js +0 -332
  80. package/dist/chunk-PAICJCKJ.js.map +0 -1
  81. package/dist/chunk-PUDETPL4.js +0 -279
  82. package/dist/chunk-PUDETPL4.js.map +0 -1
  83. package/dist/chunk-UJFWPRDM.js +0 -206884
  84. package/dist/chunk-UJFWPRDM.js.map +0 -1
  85. package/dist/chunk-VRB5HUYU.js +0 -1492
  86. package/dist/chunk-VRB5HUYU.js.map +0 -1
  87. package/dist/chunk-VRDZ5IKE.js +0 -558
  88. package/dist/chunk-VRDZ5IKE.js.map +0 -1
  89. package/dist/chunk-WPTOJYN5.js +0 -181
  90. package/dist/chunk-WPTOJYN5.js.map +0 -1
  91. package/dist/chunk-XRDN232O.js +0 -877
  92. package/dist/chunk-XRDN232O.js.map +0 -1
  93. package/dist/chunk-Y62GORQF.js +0 -51
  94. package/dist/chunk-Y62GORQF.js.map +0 -1
  95. package/dist/chunk-ZP3VVXOI.js +0 -66
  96. package/dist/chunk-ZP3VVXOI.js.map +0 -1
  97. package/dist/client.js.map +0 -1
  98. package/dist/gateway.js.map +0 -1
  99. package/dist/index.js.map +0 -1
  100. package/dist/kyber-CGOA7Q6A.js +0 -3
  101. package/dist/kyber-CGOA7Q6A.js.map +0 -1
  102. package/dist/mesh.js.map +0 -1
  103. package/dist/server.js.map +0 -1
  104. package/dist/types.js.map +0 -1
  105. package/dist/verifier-COnid_dg.d.ts +0 -31
  106. package/dist/verifier-XFU7ZB2W.js +0 -6
  107. package/dist/verifier-XFU7ZB2W.js.map +0 -1
  108. package/dist/workers/logic-execution.js.map +0 -1
  109. package/dist/workers/zk-verifier.js.map +0 -1
@@ -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,8 @@
1
- import './verifier-COnid_dg.js';
2
- import './node-B0b2vUFS.js';
3
- export { c as LiopClient } from './index-BuEQtBHD.js';
4
- import './types-CzRSOlOo.js';
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';
5
6
  import '@grpc/grpc-js';
6
7
  import 'node:events';
7
8
  import 'zod';
package/dist/client.js CHANGED
@@ -1,12 +1,2 @@
1
- export { LiopClient } from './chunk-FCFTYOAS.js';
2
- import './chunk-3QH44NKZ.js';
3
- import './chunk-2STZHJ24.js';
4
- import './chunk-IK7CGWAZ.js';
5
- import './chunk-7PITYWOV.js';
6
- import './chunk-UJFWPRDM.js';
7
- import './chunk-PAICJCKJ.js';
8
- import './chunk-2KSO3W4A.js';
9
- import './chunk-XRDN232O.js';
10
- import './chunk-K3DGJLUY.js';
11
- //# 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
12
2
  //# sourceMappingURL=client.js.map
package/dist/gateway.d.ts CHANGED
@@ -1,7 +1,8 @@
1
- import './node-B0b2vUFS.js';
2
- import './index-CdW8j8Bn.js';
3
- import './types-CzRSOlOo.js';
4
- export { L as LiopHybridGateway } from './hybrid-DWe1bMoV.js';
1
+ import './node-Djzm6UYd.js';
2
+ import './index-ByzjpRCk.js';
3
+ import './types-29zv9X1V.js';
4
+ export { L as LiopHybridGateway } from './hybrid-BZpCiUaV.js';
5
5
  import 'zod';
6
+ import './zk-DzYNWBgo.js';
6
7
  import 'jose';
7
- import './verifier-COnid_dg.js';
8
+ import './verifier-DqZ9MQ9l.js';
package/dist/gateway.js CHANGED
@@ -1,12 +1,2 @@
1
- export { LiopHybridGateway } from './chunk-EJ426URA.js';
2
- import './chunk-VRB5HUYU.js';
3
- import './chunk-2STZHJ24.js';
4
- import './chunk-IK7CGWAZ.js';
5
- import './chunk-7PITYWOV.js';
6
- import './chunk-WPTOJYN5.js';
7
- import './chunk-UJFWPRDM.js';
8
- import './chunk-PAICJCKJ.js';
9
- import './chunk-2KSO3W4A.js';
10
- import './chunk-K3DGJLUY.js';
11
- //# 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
12
2
  //# sourceMappingURL=gateway.js.map
@@ -1,7 +1,7 @@
1
- import { a as MeshNode } from './node-B0b2vUFS.js';
2
- import { L as LiopServer } from './index-CdW8j8Bn.js';
3
- import { b as McpRequest, M as McpEra, A as AuthInfo, c as McpResponse, G as GatewayInterceptorOptions } from './types-CzRSOlOo.js';
4
- import { L as LiopVerifier } from './verifier-COnid_dg.js';
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
@@ -1,8 +1,9 @@
1
- import { L as LiopVerifier } from './verifier-COnid_dg.js';
2
- import { M as MeshNodeConfig } from './node-B0b2vUFS.js';
1
+ import { L as LiopVerifier } from './verifier-DqZ9MQ9l.js';
2
+ import { M as MeshNodeConfig } from './node-Djzm6UYd.js';
3
3
  import * as grpc from '@grpc/grpc-js';
4
4
  import { EventEmitter } from 'node:events';
5
- import { M as McpEra, C as CallToolRequest, a as CallToolResult } from './types-CzRSOlOo.js';
5
+ import { Z as ZkPolicy } from './zk-DzYNWBgo.js';
6
+ import { M as McpEra, C as CallToolRequest, a as CallToolResult } from './types-29zv9X1V.js';
6
7
 
7
8
  interface CertManagerOptions {
8
9
  /** Path to the root CA certificate (PEM format) */
@@ -166,7 +167,10 @@ declare class LiopClient {
166
167
  /**
167
168
  * Invokes a tool.
168
169
  */
169
- callTool(request: CallToolRequest, _wasmPayload?: Buffer): Promise<CallToolResult>;
170
+ callTool(request: CallToolRequest, _wasmPayload?: Buffer, options?: {
171
+ zkPolicy?: ZkPolicy;
172
+ circuitName?: string;
173
+ }): Promise<CallToolResult>;
170
174
  private getOrCreateRpcClient;
171
175
  /**
172
176
  * Reads a specific resource by URI.
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
- import { M as MeshNodeConfig, a as MeshNode } from './node-B0b2vUFS.js';
3
- import { d as AuditLogger, J as JwtValidator, S as ServerInfo, a as CallToolResult, P as Prompt, e as GetPromptRequest, f as GetPromptResult, C as CallToolRequest, T as Tool, R as Resource } from './types-CzRSOlOo.js';
2
+ import { M as MeshNodeConfig, a as MeshNode } from './node-Djzm6UYd.js';
3
+ import { d as AuditLogger, J as JwtValidator, S as ServerInfo, a as CallToolResult, P as Prompt, e as GetPromptRequest, f as GetPromptResult, C as CallToolRequest, T as Tool, R as Resource } from './types-29zv9X1V.js';
4
4
 
5
5
  /**
6
6
  * LIOP OAuth 2.1 Hybrid Auth — Configuration Types
@@ -281,6 +281,10 @@ interface LiopServerOptions {
281
281
  * Path to a shared JSON file for persistent Query Budget tracking across multiple server instances.
282
282
  */
283
283
  budgetStorePath?: string;
284
+ /** Expected guest image identifier hash for sovereign enclaves (Hex) */
285
+ guestImageId?: string;
286
+ /** Static verification key mappings for fast-path analytical circuits */
287
+ zkVkeys?: Record<string, unknown>;
284
288
  }
285
289
  interface AggregationPolicy {
286
290
  /** Maximum number of object-type array elements allowed (default: 10) */
@@ -331,6 +335,29 @@ interface LogicExecutionPolicy {
331
335
  * Path to a shared JSON file for persistent Query Budget tracking across multiple server instances.
332
336
  */
333
337
  budgetStorePath?: string;
338
+ /**
339
+ * Zero-Knowledge proof mode required for this tool capability.
340
+ * - "none": standard HMAC-SHA256 session commitment
341
+ * - "optimistic": Groth16 v2 receipt generated if prover available, otherwise fallback
342
+ * - "required": strictly enforces Groth16 v2 proof generation; rejects if unavailable
343
+ */
344
+ zkMode?: "none" | "optimistic" | "required";
345
+ /**
346
+ * Optional custom guest image identifier hash for this capability.
347
+ */
348
+ guestImageId?: string;
349
+ /**
350
+ * Name of the designated R1CS circuit (e.g. "sum", "count", "average", "filter").
351
+ */
352
+ circuitName?: string;
353
+ /**
354
+ * Static verification key JSON structure for this capability.
355
+ */
356
+ vkey?: Record<string, unknown>;
357
+ /**
358
+ * Whether to co-sign the Groth16 receipt with an ML-DSA-65 post-quantum digital signature (FIPS 204).
359
+ */
360
+ pqcSign?: boolean;
334
361
  }
335
362
  declare class LiopServer {
336
363
  private serverInfo;
@@ -357,6 +384,7 @@ declare class LiopServer {
357
384
  private meshNode;
358
385
  private rpcServer;
359
386
  private boundPort;
387
+ private enclavePqcKeypair?;
360
388
  jwtValidator?: JwtValidator;
361
389
  oauthProvider?: any;
362
390
  private sessions;
package/dist/index.d.ts CHANGED
@@ -1,21 +1,48 @@
1
1
  export { LiopBridgeOptions, LiopMcpBridge, LiopStreamBridge, LiopStreamBridgeOptions } from './bridge.js';
2
- import { L as LiopTlsOptions } from './index-BuEQtBHD.js';
3
- export { C as CertInfo, a as CertManager, b as CertManagerOptions, c as LiopClient, d as createChannelCredentials, e as createServerCredentials } from './index-BuEQtBHD.js';
2
+ import { L as LiopTlsOptions } from './index-BYDtRGue.js';
3
+ export { C as CertInfo, a as CertManager, b as CertManagerOptions, c as LiopClient, d as createChannelCredentials, e as createServerCredentials } from './index-BYDtRGue.js';
4
+ import { ProofWithSignals, VerificationKey } from 'micro-zk-proofs';
5
+ export { ProofWithSignals, VerificationKey } from 'micro-zk-proofs';
6
+ export { L as LiopVerifier, T as TeePolicy, a as TeeVerificationOptions, b as TeeVerificationResult, V as VerifyZkOptions } from './verifier-DqZ9MQ9l.js';
4
7
  import * as http from 'node:http';
5
- export { I as InMemoryRateLimiter, L as LiopHybridGateway, a as LiopMcpRouter, R as RateLimitStatus, b as RateLimiterOptions } from './hybrid-DWe1bMoV.js';
6
- import { A as AuthInfo } from './types-CzRSOlOo.js';
7
- export { g as AuditEntry, h as AuditInterceptor, d as AuditLogger, i as AuditRecordParams, j as AuditStatus, k as CacheableResult, C as CallToolRequest, a as CallToolResult, D as DiscoverResult, l as GENESIS_HASH, m as GatewayAdmissionResult, n as GatewayInterceptor, o as GatewayInterceptorContext, G as GatewayInterceptorOptions, e as GetPromptRequest, f as GetPromptResult, I as InputRequest, p as InputRequiredResult, q as InputResponse, J as JwtValidator, L as LiopLogger, r as LogEvent, s as LogInterceptor, t as LogLevel, u as MCP_LEGACY_SUPPORT_ENABLED, v as MCP_PROTOCOL_VERSION, w as MCP_PROTOCOL_VERSION_LEGACY, M as McpEra, b as McpRequest, x as McpRequestMeta, c as McpResponse, P as Prompt, y as PromptSchema, R as Resource, z as ResourceSchema, S as ServerInfo, T as Tool, B as ToolSchema, E as computeEntryHash, F as executeGatewayInterceptor, H as globalAuditLogger, K as log } from './types-CzRSOlOo.js';
8
- export { L as LiopManifest, a as MeshNode, M as MeshNodeConfig } from './node-B0b2vUFS.js';
8
+ export { I as InMemoryRateLimiter, L as LiopHybridGateway, a as LiopMcpRouter, R as RateLimitStatus, b as RateLimiterOptions } from './hybrid-BZpCiUaV.js';
9
+ import { A as AuthInfo } from './types-29zv9X1V.js';
10
+ export { g as AuditEntry, h as AuditInterceptor, d as AuditLogger, i as AuditRecordParams, j as AuditStatus, k as CacheableResult, C as CallToolRequest, a as CallToolResult, D as DiscoverResult, l as GENESIS_HASH, m as GatewayAdmissionResult, n as GatewayInterceptor, o as GatewayInterceptorContext, G as GatewayInterceptorOptions, e as GetPromptRequest, f as GetPromptResult, I as InputRequest, p as InputRequiredResult, q as InputResponse, J as JwtValidator, L as LiopLogger, r as LogEvent, s as LogInterceptor, t as LogLevel, u as MCP_LEGACY_SUPPORT_ENABLED, v as MCP_PROTOCOL_VERSION, w as MCP_PROTOCOL_VERSION_LEGACY, M as McpEra, b as McpRequest, x as McpRequestMeta, c as McpResponse, P as Prompt, y as PromptSchema, R as Resource, z as ResourceSchema, S as ServerInfo, T as Tool, B as ToolSchema, E as computeEntryHash, F as executeGatewayInterceptor, H as globalAuditLogger, K as log } from './types-29zv9X1V.js';
11
+ export { L as LiopManifest, a as MeshNode, M as MeshNodeConfig } from './node-Djzm6UYd.js';
9
12
  export { SWARM_KEY_BYTE_LENGTH, createSwarmKey, deserializeSwarmKey, loadSwarmKey, parseSwarmKey, saveSwarmKey, serializeSwarmKey } from './mesh.js';
10
13
  import * as grpc from '@grpc/grpc-js';
11
- export { A as AUTH_DEFAULTS, b as AggregationPolicy, c as AuthRole, d as LiopAuthConfig, L as LiopServer, a as LiopServerOptions, e as LogicExecutionPolicy, N as NerScanner, O as OAuthClientConfig, f as OutputSanitizerConfig, P as PII_PATTERNS, g as PII_PRESETS, h as PiiRule, i as PiiScanner, T as ToolHandler, s as sanitizeOutput } from './index-CdW8j8Bn.js';
14
+ export { A as AUTH_DEFAULTS, b as AggregationPolicy, c as AuthRole, d as LiopAuthConfig, L as LiopServer, a as LiopServerOptions, e as LogicExecutionPolicy, N as NerScanner, O as OAuthClientConfig, f as OutputSanitizerConfig, P as PII_PATTERNS, g as PII_PRESETS, h as PiiRule, i as PiiScanner, T as ToolHandler, s as sanitizeOutput } from './index-ByzjpRCk.js';
12
15
  import * as jose from 'jose';
13
16
  import Provider from 'oidc-provider';
17
+ export { D as DecodedReceipt, P as ProofType, R as RECEIPT_VERSION_V1, a as RECEIPT_VERSION_V2, b as ZK_JOURNAL_V2_SIZE, c as ZkJournalV2, Z as ZkPolicy, d as ZkReceipt, e as ZkVerificationError, f as ZkVerifier, g as decodeJournalV2, h as encodeJournalV2, r as receiptCodec } from './zk-DzYNWBgo.js';
14
18
  import '@modelcontextprotocol/sdk/server/mcp.js';
15
19
  import 'zod';
16
- import './verifier-COnid_dg.js';
17
20
  import 'node:events';
18
21
 
22
+ declare const VERIFICATION_LATENCY_BUDGET_MS = 250;
23
+
24
+ /**
25
+ * Verifies a Groth16 Zero-Knowledge proof against a verification key.
26
+ * Traps curve validation errors gracefully to ensure safe verification.
27
+ */
28
+ declare function verifyGroth16Proof(vkey: VerificationKey, proofWithSignals: ProofWithSignals): boolean;
29
+ /**
30
+ * Serializes a VerificationKey into a Buffer.
31
+ */
32
+ declare function serializeVKey(vkey: VerificationKey): Buffer;
33
+ /**
34
+ * Deserializes a Buffer into a typed VerificationKey.
35
+ */
36
+ declare function deserializeVKey(buf: Buffer): VerificationKey;
37
+ /**
38
+ * Serializes a ProofWithSignals into a Buffer.
39
+ */
40
+ declare function serializeGrothProof(proofWithSignals: ProofWithSignals): Buffer;
41
+ /**
42
+ * Deserializes a Buffer into a typed ProofWithSignals.
43
+ */
44
+ declare function deserializeGrothProof(buf: Buffer): ProofWithSignals;
45
+
19
46
  /**
20
47
  * TokenEstimator — Pluggable strategy for counting tokens in text content.
21
48
  *
@@ -37,7 +64,7 @@ interface TokenEstimator {
37
64
  *
38
65
  * - Synchronous: safe for hot-path usage without async overhead
39
66
  * - Merge cache reduced to 10K entries for long-running server processes
40
- * - Inlined at build-time: zero external runtime dependencies in node_modules
67
+ * - External dependency: resolved from gpt-tokenizer in node_modules at runtime
41
68
  */
42
69
  declare class RealTokenEstimator implements TokenEstimator {
43
70
  readonly name = "o200k_base";
@@ -322,6 +349,9 @@ declare const manifestCacheSize: Gauge;
322
349
  declare const egressBlocksTotal: Counter;
323
350
  declare const zkVerificationDurationMs: Histogram;
324
351
  declare const zkVerificationsTotal: Counter;
352
+ declare const zkProofsByTypeTotal: Counter;
353
+ declare const zkProvingDurationMs: Histogram;
354
+ declare const zkVkeyCacheSize: Gauge;
325
355
  declare const tokensInputTotal: Counter;
326
356
  declare const tokensOutputTotal: Counter;
327
357
  declare const tokensSavedTotal: Counter;
@@ -389,6 +419,16 @@ declare const GRPC_CHANNEL_OPTIONS: Readonly<Record<string, string | number>>;
389
419
  * TypeScript interfaces reflecting liop_core.proto (LIOP v1)
390
420
  * Optimized for logic-on-origin and high-performance serialization.
391
421
  */
422
+ declare enum ProofMode {
423
+ PROOF_MODE_LEGACY_HMAC = 0,
424
+ PROOF_MODE_ZK_OPTIMISTIC = 1,
425
+ PROOF_MODE_ZK_BLOCKING = 2
426
+ }
427
+ declare enum ProofType {
428
+ PROOF_TYPE_HMAC_LEGACY = 0,
429
+ PROOF_TYPE_GROTH16 = 2,
430
+ PROOF_TYPE_GROTH16_PQC_HYBRID = 3
431
+ }
392
432
  interface IntentRequest {
393
433
  agent_did: string;
394
434
  capability_hash: string;
@@ -406,12 +446,15 @@ interface LogicRequest {
406
446
  inputs: Record<string, Uint8Array>;
407
447
  pqc_ciphertext: Uint8Array;
408
448
  aes_nonce: Uint8Array;
449
+ requested_proof_mode?: ProofMode;
409
450
  }
410
451
  interface LogicResponse {
411
452
  semantic_evidence: string;
412
453
  cryptographic_proof: Uint8Array;
413
454
  zk_receipt: Uint8Array;
414
455
  is_error: boolean;
456
+ proof_type?: ProofType;
457
+ guest_image_id?: Uint8Array;
415
458
  }
416
459
 
417
460
  type TokenProvider = string | (() => Promise<string | undefined> | string | undefined);
@@ -482,6 +525,10 @@ declare const Dilithium65Wrapper: {
482
525
  publicKey: Uint8Array;
483
526
  secretKey: Uint8Array;
484
527
  };
528
+ /**
529
+ * Derives the ML-DSA-65 public key from a given secret key.
530
+ */
531
+ getPublicKey(secretKey: Uint8Array): Uint8Array;
485
532
  /**
486
533
  * Validates and imports a raw ML-DSA-65 public key.
487
534
  */
@@ -807,4 +854,4 @@ declare function authorizeRequest(method: string, auth: AuthInfo | null, additio
807
854
  declare const LIOP_SCOPES: readonly ["liop:tools:list", "liop:tools:call", "liop:resources:read", "liop:schema:read", "liop:mesh:query"];
808
855
  type LiopScope = (typeof LIOP_SCOPES)[number];
809
856
 
810
- export { type AIProvider, AesGcmWrapper, AuthInfo, Counter, DILITHIUM65_CONSTANTS, Dilithium65Wrapper, ErrorCode, GRPC_CHANNEL_OPTIONS, GRPC_WEB_CONSTANTS, type GatewayTopologyInfo, Gauge, type GrpcWebFrame, HeuristicTokenEstimator, Histogram, Kyber768Wrapper, LIOP_SCOPES, LiopError, LiopOTelBridge, LiopRpcClient, LiopRpcServer, type LiopScope, type LiopSpan, LiopTlsOptions, LiopTracer, type MeshTopologyInfo, type MetricDefinition, type MetricLabels, MetricsRegistry, type PromptConfig, RealTokenEstimator, RoutingTable, type SandboxConfig, type SpanContext, type TokenEstimator, TokenManager, type TokenManagerOptions, type TokenOperationMetric, type TokenProvider, type TokenSessionReport, TokenTelemetryEngine, type ToolDefinition, type ToolRoute, type ToolTokenBreakdown, type TopologyProbeOptions, type TopologyProbeResult, type TransportProvider, WasiSandbox, authorizeRequest, buildProtectedResourceMetadata, calculateAstInstructionFuel, createOAuthServer, createSyncTokenEstimator, createTokenEstimator, decodeFrames, defaultTracer, dispatchGrpcWebRequest, egressBlocksTotal, encodeDataFrame, encodeTrailerFrame, fuelConsumed, generateSystemInstructions, getDefaultEnvironment, isGrpcWebRequest, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, probeTopology, protocolMetrics, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, wireEgressBytesTotal, wireSavedBytesTotal, zkVerificationDurationMs, zkVerificationsTotal };
857
+ export { type AIProvider, AesGcmWrapper, AuthInfo, Counter, DILITHIUM65_CONSTANTS, Dilithium65Wrapper, ErrorCode, GRPC_CHANNEL_OPTIONS, GRPC_WEB_CONSTANTS, type GatewayTopologyInfo, Gauge, type GrpcWebFrame, HeuristicTokenEstimator, Histogram, Kyber768Wrapper, LIOP_SCOPES, LiopError, LiopOTelBridge, LiopRpcClient, LiopRpcServer, type LiopScope, type LiopSpan, LiopTlsOptions, LiopTracer, type MeshTopologyInfo, type MetricDefinition, type MetricLabels, MetricsRegistry, type PromptConfig, RealTokenEstimator, RoutingTable, type SandboxConfig, type SpanContext, type TokenEstimator, TokenManager, type TokenManagerOptions, type TokenOperationMetric, type TokenProvider, type TokenSessionReport, TokenTelemetryEngine, type ToolDefinition, type ToolRoute, type ToolTokenBreakdown, type TopologyProbeOptions, type TopologyProbeResult, type TransportProvider, VERIFICATION_LATENCY_BUDGET_MS, WasiSandbox, authorizeRequest, buildProtectedResourceMetadata, calculateAstInstructionFuel, createOAuthServer, createSyncTokenEstimator, createTokenEstimator, decodeFrames, defaultTracer, deserializeGrothProof, deserializeVKey, dispatchGrpcWebRequest, egressBlocksTotal, encodeDataFrame, encodeTrailerFrame, fuelConsumed, generateSystemInstructions, getDefaultEnvironment, isGrpcWebRequest, manifestCacheSize, meshPeersConnected, operationDurationMs, pqcHandshakeDurationMs, pqcHandshakesTotal, probeTopology, protocolMetrics, serializeGrothProof, serializeVKey, tokensInputTotal, tokensOutputTotal, tokensSavedTotal, toolCallErrorsTotal, toolCallsTotal, verifyGroth16Proof, wireEgressBytesTotal, wireSavedBytesTotal, zkProofsByTypeTotal, zkProvingDurationMs, zkVerificationDurationMs, zkVerificationsTotal, zkVkeyCacheSize };