@nekzus/liop 2.0.0-alpha.4 → 2.0.0-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/bin/agent.js +1 -1
- package/dist/bridge.js +1 -1
- package/dist/chunk-5OAZNVIU.js +31 -0
- package/dist/chunk-5OAZNVIU.js.map +1 -0
- package/dist/{chunk-LYULZHZO.js → chunk-62YQHKSS.js} +2 -2
- package/dist/{chunk-LYULZHZO.js.map → chunk-62YQHKSS.js.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/server.d.ts +18 -0
- package/dist/server.js +1 -1
- package/dist/workers/logic-execution.d.ts +5 -0
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/package.json +1 -4
- package/dist/chunk-FW6CICSY.js +0 -29
- package/dist/chunk-FW6CICSY.js.map +0 -1
package/README.md
CHANGED
|
@@ -425,7 +425,7 @@ await server.connectToMesh();
|
|
|
425
425
|
|
|
426
426
|
This package is continuously tested across multiple platforms and Node.js versions via CI/CD:
|
|
427
427
|
|
|
428
|
-
- **
|
|
428
|
+
- **285+ tests** spanning unit, integration, conformance, adversarial, and crossnet suites
|
|
429
429
|
- **Multi-OS matrix:** Ubuntu, Windows, macOS
|
|
430
430
|
- **Node.js versions:** 20.x, 22.x
|
|
431
431
|
- **Code quality:** Enforced by [Biome.js](https://biomejs.dev/) (linting + formatting)
|
package/dist/bin/agent.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {f}from'../chunk-
|
|
2
|
+
import {f}from'../chunk-5OAZNVIU.js';import {g}from'../chunk-7MAGL6ON.js';import'../chunk-UVTEJYHN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-HM77MWB6.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-PPCOS2NU.js';import {a}from'../chunk-S6RJHZV2.js';import*as l from'fs';import*as _ from'os';import*as d from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let c=t.endsWith("/health")?t:`${t}/health`,u=await fetch(c,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!u.ok)return null;let e=await u.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(a=>a.includes("/tcp/")&&!a.includes("/ws")&&!a.includes("/ip4/127.0.0.1/"));if(!p)return null;let i=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"?N(p):p;if(!i||i===p){let a=new URL(t).hostname;i=p.replace(/\/ip4\/[^/]+/,`/ip4/${a}`);}return i?(i+=i.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,i):null}catch{return null}}function P(t){let c=t.trim(),u=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(u.test(c)||e.test(c)||p.test(c)){let f="127.0.0.1",i=c.replace(u,`/ip4/${f}`).replace(e,`/ip4/${f}`).replace(p,`/ip4/${f}`);return i!==c&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${i}`),i}return c}function N(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}async function E(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",r=>process.exit(r??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let c=d.join(_.homedir(),".liop"),u=d.join(c,"identity.json");l.existsSync(c)||l.mkdirSync(c,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=d.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let r=l.readFileSync(n,"utf8").trim();r&&e.push(P(r));}}s.push(process.cwd(),d.join(process.cwd(),"tests/infra/nexus-data"),c,d.join(d.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let T=d.join(n,g),I=l.readFileSync(T,"utf8").trim();if(I){let S=P(I);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let r=P(n);e.includes(r)||(e.push(r),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${r}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let f$1=new f({name:"@nekzus/liop",version:"1.0.0"});f$1.enableZeroShotAutonomy();let i=new a$1({identityPath:u,bootstrapNodes:e,addressMapper:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"?N:void 0});await i.start();let a$2=new g(f$1,i);a$2.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
3
3
|
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
4
4
|
`);},setTimeout(()=>{let s=i.getRoutingTableSize?.()||0;a.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${s}`),a$2.refreshManifestCache(true).catch(()=>{});},2e3);let O=1e4,R=12e4,m=O,v=()=>{setTimeout(async()=>{let s=a$2.getCacheSize();await a$2.refreshManifestCache(true).catch(()=>{});let n=a$2.getCacheSize();n!==s?(m=O,a.info(`[LIOP-Agent] Topology change detected (${s} \u2192 ${n}). Resetting poll to ${O/1e3}s.`)):m=Math.min(Math.round(m*1.5),R),v();},m);};v();let L=(await import('readline')).createInterface({input:process.stdin,terminal:false});process.stdout.on("error",s=>{s.code==="EPIPE"&&process.exit(0);}),L.on("line",async s=>{let n=s.trim();if(n)try{let r=JSON.parse(n);if(r.method){let h=await a$2.dispatch(r);h&&process.stdout.write(`${JSON.stringify(h)}
|
|
5
5
|
`);}}catch{}}),L.on("close",()=>{process.exit(0);}),a.info("[LIOP-Agent] Guarding Claude Desktop via STDIO."),a.info(`[LIOP-Agent] P2P Mesh: Joined (${e.length} bootstraps)`),a.info("[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0"),process.on("SIGINT",async()=>{await i.stop(),process.exit(0);});}E().catch(t=>{a.error(`[LIOP-Agent] Fatal Error: ${t.message}`),process.exit(1);});//# sourceMappingURL=agent.js.map
|
package/dist/bridge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-62YQHKSS.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=bridge.js.map
|
|
2
2
|
//# sourceMappingURL=bridge.js.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {a,b}from'./chunk-HM77MWB6.js';import {a as a$2}from'./chunk-PPCOS2NU.js';import {a as a$1}from'./chunk-S6RJHZV2.js';import {Buffer}from'buffer';import H from'crypto';import*as Z from'fs';import {createRequire}from'module';import R from'path';import {fileURLToPath,pathToFileURL}from'url';import*as z from'@grpc/grpc-js';import {Piscina,FixedQueue}from'piscina';import {z as z$1}from'zod';import {zodToJsonSchema}from'zod-to-json-schema';import*as k from'acorn';import {simple}from'acorn-walk';var Y={"grpc.keepalive_time_ms":3e4,"grpc.keepalive_timeout_ms":1e4,"grpc.keepalive_permit_without_calls":1,"grpc.max_send_message_length":-1,"grpc.max_receive_message_length":-1,"grpc.enable_retries":1},T=class{server;constructor(){this.server=new z.Server(Y);}addService(e){this.server.addService(a.LogicMesh.service,{NegotiateIntent:e.negotiateIntent,ExecuteLogic:e.executeLogic});}async listen(e=50051,t){let r=b(t);return new Promise((i,n)=>{this.server.bindAsync(`0.0.0.0:${e}`,r,(s,o)=>{if(s){n(s);return}a$1.info(`[LIOP-RPC] Server listening on port ${o}`),i(o);});})}async stop(){return new Promise(e=>{this.server.tryShutdown(()=>{a$1.info("[LIOP-RPC] Server shut down"),e();});})}};var A=class p{piiFields;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"]);constructor(e){this.piiFields=new Set(e.map(t=>t.toLowerCase()));}analyze(e,t,r=50){let i;try{let a=`function liop_analysis_wrapper(env) {
|
|
2
|
+
${e}
|
|
3
|
+
}`;i=k.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=k.parse(`function w(env) {
|
|
4
|
+
${e}
|
|
5
|
+
}`,{ecmaVersion:2022,sourceType:"script"});}catch{return []}let r=new Set;return simple(t,{CallExpression:n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isEnvRecordsChain(s.object))return;let a=n.arguments[0];if(!a||a.type!=="ArrowFunctionExpression"&&a.type!=="FunctionExpression")return;let c=a,l=0;if(p.REDUCE_METHODS.has(o)&&(l=1),c.params.length>l){let u=c.params[l];if(u.type==="Identifier"){let d=u.name,m=this.extractFieldsFromBody(c.body,d);for(let h of m)r.add(h);}}}}),Array.from(r)}detectCorrelatedAggregations(e){let t=new Map;simple(e,{CallExpression:i=>{if(i.callee.type!=="MemberExpression")return;let n=i.callee,s=this.getPropertyName(n);if(!s||!p.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||c.type!=="Identifier")return;let l=c.name,u=this.extractFieldsFromBody(a.body,l);for(let d of u){let m=t.get(d)??0;t.set(d,m+1);}}});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}extractFieldsFromBody(e,t){let r=[];return simple(e,{MemberExpression:n=>{if(n.object.type==="Identifier"&&n.object.name===t){let s=this.getPropertyName(n);s&&s!=="length"&&r.push(s);}}}),r}detectMinMaxExtraction(e){let t=null;return simple(e,{CallExpression: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.`});}}},MemberExpression: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."});}}}}}),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.isEnvRecordsChain(r.object)}identifyRecordBoundVars(e,t){simple(e,{CallExpression:n=>{if(n.callee.type!=="MemberExpression")return;let s=n.callee,o=this.getPropertyName(s);if(!o||!this.isEnvRecordsAccess(s.object))return;let a=n.arguments[0];if(a&&(a.type==="ArrowFunctionExpression"||a.type==="FunctionExpression")){let c=a;if(p.ARRAY_CALLBACK_METHODS.has(o)&&c.params.length>0){let l=c.params[0];l.type==="Identifier"&&t.add(l.name);}if(p.REDUCE_METHODS.has(o)&&c.params.length>1){let l=c.params[1];l.type==="Identifier"&&t.add(l.name);}}},ForOfStatement:n=>{if(this.isEnvRecordsAccess(n.right)&&n.left.type==="VariableDeclaration")for(let s of n.left.declarations)s.id.type==="Identifier"&&t.add(s.id.name);}}),simple(e,{VariableDeclarator:n=>{if(!(!n.init||n.id.type!=="Identifier")&&n.init.type==="MemberExpression"&&n.init.computed){let s=n.init;this.isEnvRecordsAccess(s.object)&&t.add(n.id.name);}}});}propagateTaint(e,t,r){for(let i=0;i<3;i++){let n=r.size;if(simple(e,{VariableDeclarator:o=>{!o.init||o.id.type!=="Identifier"||this.isExpressionTainted(o.init,t,r)&&r.add(o.id.name);},AssignmentExpression:o=>{o.left.type==="Identifier"&&this.isExpressionTainted(o.right,t,r)&&r.add(o.left.name);},CallExpression: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);}}),r.size===n)break}}checkReturnStatements(e,t,r){let i=null;return simple(e,{ReturnStatement: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};}}}),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 "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"&&this.isExpressionTainted(n.value,t,r));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.isEnvRecordsAccess(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&&p.TAINT_PROPAGATING_METHODS.has(n)&&this.isExpressionTainted(i.object,t,r))return true;if(this.isEnvRecordsAccess(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(!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&&p.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);let o=false,a={ReturnStatement:c=>{c.argument&&this.isExpressionTainted(c.argument,n,s)&&(o=true);}};return simple(e.body,a),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 V={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"},_=4,J=/^[\d\s.,:;!?()[\]{}<>@#$%^&*+=|\\/"'`~_-]+$/,N=class p{static nlp=null;async getNlp(){if(!p.nlp){let e=await import('compromise/three');p.nlp=e.default||e,p.nlp.addWords(V);}return p.nlp}async scan(e){if(e.length<_||J.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>=_&&i.push({type:"person",text:c});}let s=r.places().out("array");for(let a of s){let c=a.trim();c.length>=_&&i.push({type:"place",text:c});}let o=r.organizations().out("array");for(let a of o){let c=a.trim();c.length>=_&&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 Q(p){let e=p.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}function X(p){let e=p.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}}var f={EMAIL:{name:"EMAIL",pattern:/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/gi,validator:p=>!p.endsWith("@example.com")&&!p.endsWith("@test.com")},CREDIT_CARD:{name:"CREDIT_CARD",pattern:/\b(?:\d[ -]*?){13,16}\b/g,validator:Q},IP_ADDRESS:{name:"IP_ADDRESS",pattern:/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,validator:p=>["127.0.0.1","0.0.0.0","255.255.255.255"].includes(p)?false:p.split(".").map(Number).every(r=>r>=0&&r<=255)},PHONE:{name:"PHONE",pattern:/(?:(?:\+?\d{1,3}[-. ]?)?\(?\d{3}\)?[-. ]?\d{3}[-. ]?\d{4})\b/g,validator:p=>{let e=p.replace(/\D/g,"");return !(e.length<7||e.length>15||/^(\d)\1+$/.test(e)||e==="1234567890")}},SSN:{name:"SSN",pattern:/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,validator:p=>{let e=p.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")}},IBAN:{name:"IBAN",pattern:/\b[A-Z]{2}[0-9]{2}[A-Z0-9]{1,30}\b/gi,validator:X},PASSPORT_MRZ:{name:"PASSPORT_MRZ",pattern:/\bP[A-Z<][A-Z<]{3}[A-Z0-9<]{39}(?:\b|\s|$)/g}},U={GLOBAL_STRICT:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.PASSPORT_MRZ,f.IBAN],US_COMPLIANT:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.SSN,f.PASSPORT_MRZ],EU_GDPR:[f.EMAIL,f.CREDIT_CARD,f.IP_ADDRESS,f.PHONE,f.IBAN,f.PASSPORT_MRZ]},M=class p{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(`(?:^|[_-])${i}(?:$|[_-])|(?:^|[a-z])${i.charAt(0).toUpperCase()}${i.slice(1)}|^${i}$`,"i")):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(p.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 G=R.dirname(fileURLToPath(import.meta.url)),K=class p{constructor(e,t){this.serverInfo=e;this.config=t;let r=this.config?.security?.enableNerScanning?new N:null;this.piiScanner=new M(this.config?.security?.piiPatterns??U.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"];this.taintAnalyzer=new A(n);let s=import.meta.url.endsWith(".ts"),o=s?".ts":".js",a=[];if(s)try{let m=createRequire(import.meta.url).resolve("tsx/package.json");a=["--import",pathToFileURL(R.join(R.dirname(m),"dist","loader.mjs")).href];}catch{a=["--import","tsx"];}let c=process.env.NODE_ENV==="test"||process.env.VITEST;this.config?.capabilities&&!this.serverInfo.capabilities&&(this.serverInfo.capabilities=this.config.capabilities);let l=[R.resolve(G,`./workers/logic-execution${o}`),R.resolve(G,`../workers/logic-execution${o}`)],u=l.find(d=>Z.existsSync(d))||l[1];this.workerPool=new Piscina({filename:u,minThreads:this.config?.workerPool?.minThreads??(c?0:2),maxThreads:this.config?.workerPool?.maxThreads??(c?1:8),idleTimeout:this.config?.workerPool?.idleTimeout??(c?500:5e3),maxQueue:"auto",taskQueue:new FixedQueue,execArgv:a,resourceLimits:{maxOldGenerationSizeMb:this.config?.workerPool?.maxHeapMb??Number.parseInt(process.env.LIOP_WORKER_MAX_HEAP_MB??"64",10)}}),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()));}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;sessions=new Map;static LIOP_COMPACT_REGEX=/@LIOP\{(?<target>[^,}]+)(?:,(?<name>[^}]*))?\}\n(?<logic>[\s\S]*?)\n@END/m;extractLogic(e){let t=e.match(p.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){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 i=50;typeof r?.enforceAggregationFirst=="object"&&(i=r.enforceAggregationFirst.minMaxBlockThreshold??50);let n=this.taintAnalyzer.analyze(t,this.sandboxRecords.length,i);if(n)return `Preflight policy rejected: ${n.reason}`;let s=r?.queryBudgetPerField??5,o=this.taintAnalyzer.extractQueriedFields(t);if(o.length>0){let a=this.fieldQueryBudget.get(e);a||(a=new Map,this.fieldQueryBudget.set(e,a));for(let c of o)if((a.get(c)??0)>=s)return `Preflight policy rejected: Query budget exceeded for field '${c}' (max ${s} per session). Rotate PQC session to reset budget.`;for(let c of o){let l=a.get(c)??0;a.set(c,l+1);}}return null}validateOutputPolicy(e,t,r){if(!r)return null;let i=this.parseUnknownJson(t);if(r.outputSchema){let s=(()=>{if(!(r.outputSchema instanceof z$1.ZodObject))return r.outputSchema;let o=r.outputSchema;return o._def.catchall instanceof z$1.ZodNever?o.strict():o})().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(!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(`
|
|
6
|
+
`);return this.unwrapForAggregationPolicyScan(i)}violatesAggregationFirstPolicy(e,t,r){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","","SECURITY CONSTRAINTS:","- PII Egress Shield blocks raw identifiers in output","- Aggregation-First policy: prefer counts, averages, summaries","- AST Guardian: static analysis before execution"];return this.config?.security?.forbiddenKeys?.length&&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:","- Datasets < 10 records: max 3 scalar output fields, no nesting","- Datasets >= 10 records: max 10 output fields","","RATE LIMITS (OWASP A01):","- Per-tool: 15 calls/min (configurable via LIOP_RATE_LIMIT_MAX)","- Global: 40 calls/min across all tools (LIOP_RATE_LIMIT_GLOBAL_MAX)","","OPTIONAL PARAMETERS:","- __liop_bypass_ast_cache: boolean (force AST re-evaluation)"),e.join(`
|
|
7
|
+
`)}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$1.object(r),o=zodToJsonSchema(s),a=t,c=i;if(r.payload&&r.payload instanceof z$1.ZodString){let u=this.config?.security?.forbiddenKeys||[];if(a+=`
|
|
8
|
+
|
|
9
|
+
Payload: LIOP v1 envelope (WASI sandbox). Format: @LIOP{wasi_v1,TaskName}\\n<JS code>\\n@END | Access data: env.records. Return aggregated object. | Full spec: resource liop://protocol/envelope-spec`,u.length>0&&(a+=`
|
|
10
|
+
Restricted fields: ${u.join(", ")}.`),this.activeSchema){let d=this.extractSchemaFieldSummary(this.activeSchema);a+=`
|
|
11
|
+
Data structure: ${d}. Full schema: resource liop://schema/global`;}c=async(d,m)=>{let h="global_connection",b=Date.now(),y=this.connectionStats.get(h)||{failures:0,lastAttempt:0};if(y.failures>=this.THROTTLE_THRESHOLD&&b-y.lastAttempt<this.THROTTLE_COOLDOWN_MS)return {content:[{type:"text",text:"LIOP_THROTTLED: Too many violations. Cooling down for 60 seconds."}],isError:true};let C=d.payload,B=d.__liop_bypass_ast_cache===true,O=H.createHash("sha256").update(C).digest("hex"),S=this.extractLogic(C),D=this.logicCache.get(O);if(!B&&D&&b-D.timestamp<this.CACHE_TTL_MS&&S){d.payload=S;let v=this.runPreflightPolicy(e,S,n);return v?{content:[{type:"text",text:v}],isError:true}:await this.executeInWorkerPool(d,S,e)}if(!S)return y.failures++,y.lastAttempt=b,this.connectionStats.set(h,y),{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 v=this.extractLogic(d.payload);d.payload=v;let w=this.runPreflightPolicy(e,v,n);if(w)return y.failures++,y.lastAttempt=b,this.connectionStats.set(h,y),{content:[{type:"text",text:w}],isError:!0};let j=await this.executeInWorkerPool(d,v,e);return j.isError?(y.failures++,y.lastAttempt=b,this.connectionStats.set(h,y)):(this.connectionStats.set(h,{failures:0,lastAttempt:b}),this.logicCache.set(O,{hash:O,timestamp:b})),j}catch(v){let w=v;return y.failures++,y.lastAttempt=b,this.connectionStats.set(h,y),{content:[{type:"text",text:`ExecutionRuntimeException: ${w.message}`}],isError:true}}};}let l={type:"object",properties:o.properties||{},required:o.required};this.tools.set(e,{tool:{name:e,description:a,inputSchema:l},handler:c,schema:s,policy:n}),this.meshNode&&this.meshNode.announceCapability(e).catch(u=>{a$1.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.
|
|
12
|
+
Your objective is to perform secure Logic-on-Origin injections. You must process remote data without ever requesting its extraction.
|
|
13
|
+
|
|
14
|
+
INDUSTRIAL CONSTRAINTS & PROTOCOL RULES:
|
|
15
|
+
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.
|
|
16
|
+
2. AGGREGATION FIRST: Always prefer returning counts, averages, or anonymized summaries.
|
|
17
|
+
3. PAYLOAD ENCAPSULATION: Your JavaScript payloads MUST strictly adhere to the Compact Envelope. DO NOT include markdown backticks or leading text inside the 'payload' argument.
|
|
18
|
+
Structure:
|
|
19
|
+
@LIOP{wasi_v1,AnalysisTask}
|
|
20
|
+
// Your JS Code Here
|
|
21
|
+
@END
|
|
22
|
+
4. RUNTIME SCOPE: The execution environment provides a global 'env' object. Use 'env.records' to access the target dataset.
|
|
23
|
+
5. 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).
|
|
24
|
+
6. SCHEMA RIGIDITY: Only use fields defined in the 'Data Dictionary'. Usage of non-existent fields will trigger a sandbox runtime exception.${this.activeSchema?`
|
|
25
|
+
|
|
26
|
+
CURRENT DATA DICTIONARY (STRICT):
|
|
27
|
+
${JSON.stringify(this.activeSchema,null,2)}`:""}
|
|
28
|
+
|
|
29
|
+
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});}dataDictionary(e,t="Global Medical Data Dictionary",r="liop://schema/global",i="Exposes the internal database schema for Zero-Shot Autonomy planning"){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$1.ZodString&&o.tool.description&&!o.tool.description.includes("Data structure:")&&(o.tool.description+=`
|
|
30
|
+
Data structure: ${n}. Full schema: resource ${r}`,this.tools.set(s,o));this.resource(t,r,i,"application/json",JSON.stringify(e,null,2));}clearAstCache(){this.logicCache.clear(),a$1.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){let t=this.tools.get(e.name);if(!t)throw new Error(`Tool not found: ${e.name}`);let r=this.checkGlobalRateLimit();if(r)return r;let i=this.checkToolCallRateLimit(e.name);if(i)return i;try{let n=t.schema.parse(e.arguments||{});if(e.arguments?.__liop_bypass_ast_cache===!0&&(n.__liop_bypass_ast_cache=!0),n&&typeof n.payload=="string"){let o=n.payload,a=this.extractLogic(o);if(a){let c=this.runPreflightPolicy(e.name,a,t.policy);return c?{content:[{type:"text",text:c}],isError:!0}:(n.payload=a,await this.executeInWorkerPool(n,a,e.name))}}return await t.handler(n,{})}catch(n){let s=n;return s instanceof z$1.ZodError?{content:[{type:"text",text:`Validation Error: ${s.message}`}],isError:true}:{content:[{type:"text",text:`Internal Execution Error: ${s.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;}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;this.meshNode=new a$2(e.meshConfig),await this.meshNode.start();let i=this.meshNode;this.meshNode.registerManifestHandler(()=>{let n=this.listTools().map(o=>({name:o.name,description:o.description,inputSchema:o.inputSchema})),s=Array.from(this.resources.values()).map(o=>({name:o.name,uri:o.uri,description:o.description,mimeType:o.mimeType,text:typeof o.content=="string"?o.content:o.description}));return {peerId:i.getPeerId(),grpcPort:r,tools:n,resources:s,serverInfo:this.serverInfo}});for(let n of this.listTools())await this.meshNode.announceCapability(n.name).catch(a$1.info);await this.meshNode.announceManifest().catch(a$1.info),this.rpcServer=new T,this.rpcServer.addService({negotiateIntent:(n,s)=>{let o=n.request;a$1.info(`[LIOP-RPC] Negotiating intent for capability: ${o.capability_hash}`),import('./kyber-2WDOTUQX.js').then(async({Kyber768Wrapper:a})=>{let{publicKey:c,secretKey:l}=await a.generateKeyPair(),u=H.randomUUID();this.fieldQueryBudget.clear(),this.sessions.set(u,{capability_hash:o.capability_hash,kyber_sk:l}),s(null,{accepted:true,session_token:u,error_message:"",kyber_public_key:c});});},executeLogic:async n=>{let s=n.request;a$1.info(`[LIOP-RPC] Executing Logic-on-Origin for session: ${s.session_token}`);let o=this.sessions.get(s.session_token);if(!o){n.emit("error",{code:z.status.UNAUTHENTICATED,details:"Invalid session token"});return}try{let a=await this.workerPool.run({ciphertext:s.pqc_ciphertext,secretKeyObj:Array.from(o.kyber_sk),wasmBinary:s.wasm_binary,inputs:s.inputs,aesNonce:s.aes_nonce,records:this.sandboxRecords,sessionToken:s.session_token,isEncrypted:!0}),c;try{c=typeof a.output=="string"?a.output:JSON.stringify(a.output);let m=JSON.parse(c);if(m.__liop_proxy_tool){a$1.info(`[LIOP-RPC] Executing Proxied Tool: ${m.__liop_proxy_tool}`);let h=await this.callTool({name:m.__liop_proxy_tool,arguments:m.__liop_proxy_args||{}});c=JSON.stringify(h);}}catch{c=String(a.output);}let l={semantic_evidence:c,cryptographic_proof:Buffer.from(a.image_id||"","hex"),zk_receipt:a.zk_receipt?Buffer.from(a.zk_receipt,"base64"):Buffer.from(""),is_error:!1},u=await this.piiScanner.scan([{type:"text",text:c}]),d=this.violatesAggregationFirstPolicy(this.unwrapForAggregationPolicyScan(c));if(u||d){let m=u||"Aggregation-First Policy Violation";a$1.info(`[LIOP-RPC] Secure egress blocked in gRPC stream: ${m}`),l.semantic_evidence="[LIOP] Egress Security Violation. Output blocked due to policy enforcement.",l.is_error=!0;}n.write(l,()=>{n.end();});}catch(a){let c=a,l=process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test",u=c.message||String(a);a$1.error(`[LIOP-RPC] Execution Error: ${u}`);let m={semantic_evidence:l?`Execution Error: ${u}`:"[LIOP] Execution Failed. The injected logic violated runtime constraints or encountered a fatal error.",cryptographic_proof:Buffer.from(""),zk_receipt:Buffer.from(""),is_error:true};try{n.write(m,()=>{n.end();});}catch{n.end();}}}}),this.boundPort=await this.rpcServer.listen(r),a$1.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:50}:void 0,s=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,dpConfig:n}),o=s.output,c=[{type:"text",text:JSON.stringify({computation_result:o,image_id:s.image_id,zk_receipt:s.zk_receipt,status:"Worker Pool Execution Success"})}],l=r?this.tools.get(r)?.policy:void 0,u=this.validateOutputPolicy(r||"unknown_tool",o,l);if(u)return a$1.info(`[LIOP-SDK] Output policy blocked for ${r||"unknown_tool"}: ${u}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?u:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0};let d=await this.piiScanner.scan(c),m=this.violatesAggregationFirstPolicy(o);if(d||m){let h=d||"Aggregation-First Policy Violation: Output blocked due to dynamic flat-key policy enforcement.";return a$1.info(`[LIOP-SDK] Secure egress blocked in local execution: ${h}`),{content:[{type:"text",text:process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_SEC_VERBOSE==="1"?`[LIOP] Egress Security Violation: ${h}`:"[LIOP] Egress Security Violation. Output blocked due to policy enforcement. Ensure your logic uses strictly aggregated, non-PII patterns."}],isError:!0}}return {content:c}}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 a$1.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();}};export{T as a,N as b,f as c,U as d,M as e,K as f};//# sourceMappingURL=chunk-5OAZNVIU.js.map
|
|
31
|
+
//# sourceMappingURL=chunk-5OAZNVIU.js.map
|