@nekzus/liop 2.0.0-alpha.25 → 2.0.0-alpha.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/agent.js +1 -1
- package/dist/bridge.js +1 -1
- package/dist/{chunk-ISKM7EAL.js → chunk-AKTU6ZMX.js} +2 -2
- package/dist/{chunk-ISKM7EAL.js.map → chunk-AKTU6ZMX.js.map} +1 -1
- package/dist/{chunk-GD6EOKYV.js → chunk-BDQZURCS.js} +9 -9
- package/dist/chunk-BDQZURCS.js.map +1 -0
- package/dist/{chunk-LJQF6ULT.js → chunk-GFRRQ2EB.js} +3 -3
- package/dist/{chunk-LJQF6ULT.js.map → chunk-GFRRQ2EB.js.map} +1 -1
- package/dist/{chunk-F7B6B4XS.js → chunk-GYK2HORK.js} +3 -3
- package/dist/{chunk-F7B6B4XS.js.map → chunk-GYK2HORK.js.map} +1 -1
- package/dist/chunk-SW53FNSN.js +2 -0
- package/dist/chunk-SW53FNSN.js.map +1 -0
- package/dist/{chunk-ALLOYPMN.js → chunk-YTIMVS2I.js} +3 -3
- package/dist/{chunk-ALLOYPMN.js.map → chunk-YTIMVS2I.js.map} +1 -1
- package/dist/client.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/index.js +1 -1
- package/dist/server.js +1 -1
- package/dist/verifier-Z26UC7M4.js +2 -0
- package/dist/{verifier-6M7GY4TW.js.map → verifier-Z26UC7M4.js.map} +1 -1
- package/dist/workers/logic-execution.d.ts +7 -6
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/dist/workers/zk-verifier.d.ts +4 -4
- package/dist/workers/zk-verifier.js +1 -1
- package/dist/workers/zk-verifier.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-GD6EOKYV.js.map +0 -1
- package/dist/chunk-UVTEJYHN.js +0 -2
- package/dist/chunk-UVTEJYHN.js.map +0 -1
- package/dist/verifier-6M7GY4TW.js +0 -2
package/dist/bin/agent.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {g}from'../chunk-
|
|
2
|
+
import {g}from'../chunk-BDQZURCS.js';import'../chunk-2MGFSIXN.js';import {g as g$1}from'../chunk-GFRRQ2EB.js';import'../chunk-SW53FNSN.js';import'../chunk-ANFXJGMP.js';import'../chunk-DBXGYHKY.js';import'../chunk-V5MKJT6S.js';import'../chunk-RWRRBYG4.js';import {a as a$1}from'../chunk-7I6YJS3C.js';import {a}from'../chunk-S6RJHZV2.js';import'../chunk-4C666HHU.js';import*as l from'fs';import*as w from'os';import*as u from'path';import {multiaddr}from'@multiformats/multiaddr';async function x(t){try{let o=t.endsWith("/health")?t:`${t}/health`,d=await fetch(o,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!d.ok)return null;let e=await d.json();if(!e.mesh?.multiaddrs?.length||!e.mesh?.peerId)return null;let p=e.mesh.multiaddrs.find(c=>c.includes("/tcp/")&&!c.includes("/ws")&&!c.includes("/ip4/127.0.0.1/"));if(!p)return null;let r=E()?R(p):p;if(!r||r===p){let c=new URL(t).hostname;r=p.replace(/\/ip4\/[^/]+/,`/ip4/${c}`);}return r?(r+=r.includes("/p2p/")?"":`/p2p/${e.mesh.peerId}`,r):null}catch{return null}}function L(t){let o=t.trim(),d=/\/ip4\/172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]{1,3}\.[0-9]{1,3}/,e=/\/ip4\/127\.0\.0\.1/,p=/\/ip4\/192\.168\.[0-9]{1,3}\.[0-9]{1,3}/;if(d.test(o)||e.test(o)||p.test(o)){let r="127.0.0.1",c=o.replace(d,`/ip4/${r}`).replace(e,`/ip4/${r}`).replace(p,`/ip4/${r}`);return c!==o&&a.info(`[LIOP-Agent] \u{1F504} Local Routing Hack \u2192 Forced 127.0.0.1: ${c}`),c}return o}function R(t){return t.includes("/ip4/172.20.0.10")?t.replace(/\/ip4\/172\.20\.0\.10\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13001"):t.includes("/ip4/172.20.0.11")?t.replace(/\/ip4\/172\.20\.0\.11\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13003"):t.includes("/ip4/172.20.0.12")?t.replace(/\/ip4\/172\.20\.0\.12\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13004"):t.includes("/ip4/172.20.0.13")?t.replace(/\/ip4\/172\.20\.0\.13\/tcp\/[0-9]+/,"/ip4/127.0.0.1/tcp/13005"):t.includes("/ip4/127.0.0.1/tcp/4000")||t.includes("/ip4/127.0.0.1/tcp/3000")?null:t}function D(t){try{let o=new URL(t);return (o.hostname==="127.0.0.1"||o.hostname==="localhost")&&(o.port==="13000"||o.port==="13001")}catch{return false}}function E(){return process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test"||process.env.LIOP_DOCKER_MAP==="true"||process.env.LIOP_DEV_MODE==="true"||!!process.env.LIOP_NEXUS_URL&&D(process.env.LIOP_NEXUS_URL)}async function M(){if((process.platform==="win32"||process.platform==="darwin")&&!process.execArgv.includes("--use-system-ca")&&!(process.env.NODE_OPTIONS??"").includes("--use-system-ca")){let{spawn:s}=await import('child_process'),n=s(process.execPath,["--use-system-ca",...process.argv.slice(1)],{stdio:"inherit",env:process.env});n.on("exit",a=>process.exit(a??1)),n.on("error",()=>process.exit(1)),await new Promise(()=>{});return}let t=new Date().toISOString();a.info(`[LIOP-Agent] \u{1F680} Version 1.2.0-alpha.9 | Build: ${t}`);let o=u.join(w.homedir(),".liop"),d=u.join(o,"identity.json");l.existsSync(o)||l.mkdirSync(o,{recursive:true});let e=[],p=process.argv.slice(2);if(p.length>0&&(e=p.filter(s=>s.startsWith("/"))),e.length===0){let s=[];if(process.env.LIOP_BOOTSTRAP_FILE){a.warn("LIOP_BOOTSTRAP_FILE is deprecated and will be removed in the next major version. Use LIOP_NEXUS_URL for Auto-Discovery instead.");let n=u.resolve(process.env.LIOP_BOOTSTRAP_FILE);if(l.existsSync(n)){let a=l.readFileSync(n,"utf8").trim();a&&e.push(L(a));}}s.push(process.cwd(),u.join(process.cwd(),"tests/infra/nexus-data"),o,u.join(u.dirname(new URL(import.meta.url).pathname).replace(/^\/([A-Z]:)/,"$1"),"../../tests/infra/nexus-data"));for(let n of s)try{if(l.existsSync(n)){let h=l.readdirSync(n).filter(g=>g.endsWith(".multiaddr"));for(let g of h){let $=u.join(n,g),v=l.readFileSync($,"utf8").trim();if(v){let S=L(v);e.includes(S)||(e.push(S),a.info(`[LIOP-Agent] \u2705 Loaded beacon: ${g} from ${n}`));}}if(e.length>0)break}}catch{}}if(process.env.LIOP_NEXUS_URL){let s=process.env.LIOP_NEXUS_URL;a.info(`[LIOP-Agent] \u{1F310} Running parallel discovery from: ${s} (Sources Found: ${e.length})`);let n=await x(s);if(n){let a$1=L(n);e.includes(a$1)||(e.push(a$1),a.info(`[LIOP-Agent] \u2705 Added bootstrap from URL discovery: ${a$1}`));}}e.length===0&&process.env.LIOP_BOOTSTRAP&&e.push(process.env.LIOP_BOOTSTRAP.trim()),e.length===0&&e.push("/ip4/127.0.0.1/tcp/13001/p2p/12D3KooWD8FUFdnLQzzLFNdicsaTknM5cpD7os9sK9NWVSVABJMD"),e=e.filter(s=>{try{return multiaddr(s),!0}catch{return a.warn(`[LIOP-Agent] Ignoring invalid bootstrap multiaddr: ${s}`),false}}),e.length===0&&(a.info("[LIOP-Agent] No bootstrap nodes configured. Operating in standalone mode."),a.info("[LIOP-Agent] Pass a multiaddr as argument or create 'nexus.multiaddr' file."));let r=new g({name:"@nekzus/liop",version:"1.0.0"});r.enableZeroShotAutonomy();let c=new a$1({identityPath:d,bootstrapNodes:e,addressMapper:E()?R:void 0});await c.start();let f=new g$1(r,c);f.onToolsChanged=()=>{process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
|
|
3
3
|
`),process.stdout.write(`{"jsonrpc":"2.0","method":"notifications/resources/list_changed"}
|
|
4
4
|
`);},setTimeout(()=>{let s=c.getRoutingTableSize?.()||0;a.info(`[LIOP-Agent] Warm-up complete. Routing Table size: ${s}`),f.refreshManifestCache(true).catch(()=>{});},2e3);let O=1e4,T=12e4,m=O,P=()=>{setTimeout(async()=>{let s=f.getCacheSize();await f.refreshManifestCache(true).catch(()=>{});let n=f.getCacheSize();n!==s?(m=O,a.info(`[LIOP-Agent] Topology change detected (${s} \u2192 ${n}). Resetting poll to ${O/1e3}s.`)):m=Math.min(Math.round(m*1.5),T),P();},m);};P();let I=(await import('readline')).createInterface({input:process.stdin,terminal:false});process.stdout.on("error",s=>{s.code==="EPIPE"&&process.exit(0);}),I.on("line",async s=>{let n=s.trim();if(n)try{let a=JSON.parse(n);if(a.method){let h=await f.dispatch(a);h&&process.stdout.write(`${JSON.stringify(h)}
|
|
5
5
|
`);}}catch{}}),I.on("close",()=>{process.exit(0);}),a.info("[LIOP-Agent] Guarding Claude Desktop via STDIO."),a.info(`[LIOP-Agent] P2P Mesh: Joined (${e.length} bootstraps)`),a.info("[LIOP-Agent] Tool discovery: Dynamic via /liop/manifest/1.0.0"),process.on("SIGINT",async()=>{await c.stop(),process.exit(0);});}M().catch(t=>{a.error(`[LIOP-Agent] Fatal Error: ${t.message}`),process.exit(1);});//# sourceMappingURL=agent.js.map
|
package/dist/bridge.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-
|
|
1
|
+
export{b as LiopMcpBridge,a as LiopStreamBridge}from'./chunk-GYK2HORK.js';import'./chunk-S6RJHZV2.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=bridge.js.map
|
|
2
2
|
//# sourceMappingURL=bridge.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import {a as a$1}from'./chunk-SW53FNSN.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {c,a}from'./chunk-V5MKJT6S.js';import {a as a$2}from'./chunk-7I6YJS3C.js';import {a as a$3}from'./chunk-S6RJHZV2.js';import {createDecipheriv,randomBytes,createCipheriv}from'crypto';var u=class{client;constructor(e,r){let t=c(r);this.client=new a.LogicMesh(e,t);}async negotiateIntent(e){return new Promise((r,t)=>{this.client.NegotiateIntent(e,(i,o)=>{i?t(i):r(o);});})}executeLogic(e){return this.client.ExecuteLogic(e)}close(){this.client.close();}};var $={encryptPayload(l,e){if(e.length!==32)throw new Error("Symmetric Key must be exactly 32 bytes (256 bits).");let r=randomBytes(12),t=createCipheriv("aes-256-gcm",e,r),i=Buffer.concat([t.update(l),t.final()]),o=t.getAuthTag();return {ciphertext:Buffer.concat([i,o]),nonce:r}},decryptPayload(l,e,r){if(l.length<16)throw new Error("Invalid GCM Ciphertext; missing authentication tag length");let t=l.subarray(0,-16),i=l.subarray(-16),o=createDecipheriv("aes-256-gcm",r,e);return o.setAuthTag(i),Buffer.concat([o.update(t),o.final()])}};var O=class{meshNode=null;rpcClients=new Map;manifests=new Map;tlsOptions;serverInfo;verifier=new a$1;constructor(e){this.tlsOptions=e;}async connect(e,r){this.meshNode=new a$2(r?.meshConfig),await this.meshNode.start(),a$3.info(`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`),e?(this.rpcClients.set("static",new u(e,this.tlsOptions)),this.serverInfo={name:`LiopServer (${e})`,version:"1.0.0"},a$3.info(`[LiopClient] Static gRPC configured for: ${e}`)):this.serverInfo={name:"LiopServer (Mesh Alpha)",version:"1.0.0"};}async resolveCapability(e){if(!this.meshNode)throw new Error("Client must be connected to Mesh to resolve capabilities.");a$3.info(`[LiopClient] Querying Mesh DHT for Provider: ${e}...`);let r=await this.meshNode.findProviders(e);if(r.length===0)throw new Error(`Kademlia DHT found zero providers for capability: ${e}`);let t=r[0];a$3.info(`[LiopClient] Identified Alpha Provider PeerID: ${t}`);let i=50051,o=await this.meshNode.queryManifest(t);o&&(i=o.grpcPort,a$3.info(`[LiopClient] Manifest resolved: gRPC port ${i}`));let s=await this.meshNode.resolvePeer(t);for(let y of s){let a=y.split("/");if(a[1]==="ip4"){let m=`${a[2]}:${i}`;return a$3.info(`[LiopClient] Translated Multiaddr to gRPC Target: ${m}`),m}}return `127.0.0.1:${i}`}async discoverTools(){if(!this.meshNode)throw new Error("Client must be connected before discovering tools.");a$3.info("[LiopClient] Discovery started...");let e=await this.meshNode.discoverManifestProviders(),r=[],t=new Set;for(let i of e)try{a$3.info(`[LiopClient] Querying manifest from: ${i}`);let o=await this.meshNode.queryManifest(i);if(o){this.manifests.set(i,o);for(let s of o.tools)t.has(s.name)||(r.push({name:s.name,description:s.description}),t.add(s.name));}}catch(o){a$3.info(`[LiopClient] Error querying manifest from ${i}:`,o instanceof Error?o.message:String(o));}return a$3.info(`[LiopClient] Discovery finished. Found ${r.length} unique tools.`),r}async callTool(e,r){if(!this.meshNode)throw new Error("Client must be connected before calling tools.");let t=e.name;a$3.info(`[LiopClient] Resolving Tool: ${t}`);let i=this.rpcClients.get("static");if(i)a$3.info(`[LiopClient] Using existing static gRPC connection for ${t}.`);else {let h=await this.resolveCapability(t);i=this.getOrCreateRpcClient(t,h);}a$3.info(`[LiopClient] Negotiating intent for ${t}...`);let o=this.meshNode?`did:liop:${this.meshNode.getPeerId()}`:"did:liop:ephemeral",s=Buffer.from(`${t}:${Date.now()}`),y=this.meshNode?await this.meshNode.sign(s):s,a=await i.negotiateIntent({agent_did:o,capability_hash:t,proof_of_intent:y});if(!a.accepted)throw new Error(`Intent denied by host: ${a.error_message}`);let m=a.kyber_public_key||a.kyberPublicKey,_=a.session_token||a.sessionToken;if(!m)throw a$3.info("[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.",a),new Error("Handshake failed: Remote host did not provide a valid Kyber Public Key.");a$3.info(`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${e.name}...`);let{ciphertext:x,sharedSecret:C}=await a$4.encapsulateAsymmetric(m);a$3.info("[LiopClient] Sealing WASM Payload and Inputs...");let v=r||Buffer.from(""),{ciphertext:k,nonce:A}=$.encryptPayload(v,C),w={},b=await import('crypto');for(let[h,f]of Object.entries(e.arguments||{})){let d=b.randomBytes(12),p=b.createCipheriv("aes-256-gcm",C,d),g=Buffer.concat([p.update(JSON.stringify(f)),p.final()]),c=p.getAuthTag();w[h]=Buffer.concat([d,g,c]);}let B={session_token:_,wasm_binary:k,inputs:w,pqc_ciphertext:x,aes_nonce:A};return new Promise((h,f)=>{let d=i.executeLogic(B);if(!d){f(new Error("RPC Client unavailable or failed to create stream."));return}let p=false,g=false;d.on("data",async c=>{if(!p){g=true,a$3.info("[LiopClient] Logic Executed. Verification in progress...");try{if(!c.is_error&&!await this.verifier.verifyZkReceipt(v,Buffer.from(c.cryptographic_proof).toString("hex"),Buffer.from(c.zk_receipt),Buffer.from(C))){f(new Error("PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed."));return}p=!0,h({content:[{type:"text",text:c.semantic_evidence}],isError:c.is_error});}catch(L){f(L);}}}),d.on("error",c=>{p||(a$3.error("[LiopClient] Stream Error:",c),f(c));}),d.on("end",()=>{!g&&!p&&f(new Error("Logic-on-Origin stream closed without results."));});})}getOrCreateRpcClient(e,r){let t=this.rpcClients.get(e);return t||(t=new u(r,this.tlsOptions),this.rpcClients.set(e,t)),t}async readResource(e){if(!this.meshNode)throw new Error("Client must be connected before reading resources.");a$3.info(`[LiopClient] Querying Mesh for Resource: ${e}...`);let r=await this.meshNode.findProviders(e);if(r.length===0)throw new Error(`No mesh providers found for resource: ${e}`);let t=await this.meshNode.queryManifest(r[0]);if(!t)throw new Error("Target peer did not return a valid LIOP Manifest.");let i=t.resources?.find(o=>o.uri===e);if(!i)throw new Error(`Resource ${e} not listed in remote manifest.`);return {contents:[{uri:e,mimeType:i.mimeType||"application/json",text:JSON.stringify(i,null,2)}]}}getServerInfo(){return this.serverInfo}async close(){this.meshNode&&await this.meshNode.stop();}};export{u as a,O as b};//# sourceMappingURL=chunk-AKTU6ZMX.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-AKTU6ZMX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/rpc/client.ts","../src/rpc/crypto/aes.ts","../src/client/index.ts"],"names":["LiopRpcClient","address","tls","credentials","createChannelCredentials","liopV1","request","resolve","reject","error","response","AesGcmWrapper","payload","sharedSecret","nonce","randomBytes","cipher","createCipheriv","encrypted","authTag","ciphertextBuffer","encryptedData","decipher","createDecipheriv","LiopClient","LiopVerifier","options","MeshNode","log","toolName","providers","providerId","grpcPort","manifest","addrs","maddr","parts","grpcHost","providerIds","tools","seenNames","peerId","tool","err","_wasmPayload","rpcClient","dynamicAddress","agentDid","intentPayload","proofOfIntent","intentResponse","publicKey","sessionToken","kyberCiphertext","Kyber768Wrapper","_safePayload","encryptedWasm","aesNonce","encryptedInputs","crypto","key","value","inputNonce","logicRequest","stream","resultFulfilled","hasReceivedData","client","uri","resourceDef","r"],"mappings":"mRAcO,IAAMA,CAAAA,CAAN,KAAoB,CAElB,MAAA,CAER,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAsB,CAClD,IAAMC,CAAAA,CAAcC,CAAAA,CAAyBF,CAAG,CAAA,CAChD,IAAA,CAAK,MAAA,CAAS,IAAIG,CAAAA,CAAO,SAAA,CAAUJ,CAAAA,CAASE,CAAW,EACxD,CAMA,MAAa,eAAA,CACZG,CAAAA,CAC0B,CAC1B,OAAO,IAAI,QAAQ,CAACC,CAAAA,CAASC,CAAAA,GAAW,CACvC,IAAA,CAAK,MAAA,CAAO,eAAA,CACXF,CAAAA,CACA,CAACG,CAAAA,CAAiCC,CAAAA,GAA6B,CAC1DD,CAAAA,CACHD,CAAAA,CAAOC,CAAK,CAAA,CAEZF,CAAAA,CAAQG,CAAQ,EAElB,CACD,EACD,CAAC,CACF,CAMO,YAAA,CACNJ,CAAAA,CAC2C,CAC3C,OAAO,IAAA,CAAK,MAAA,CAAO,YAAA,CAAaA,CAAO,CACxC,CAEO,KAAA,EAA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AM,IAAI,KAAA,CAAM,mDAAmD,CAAA,CAIpE,IAAMoC,CAAAA,CAAcpC,CAAAA,CAAS,SAAA,EAAW,IAAA,CAAMqC,CAAAA,EAAMA,CAAAA,CAAE,GAAA,GAAQF,CAAG,CAAA,CACjE,GAAI,CAACC,CAAAA,CACJ,MAAM,IAAI,KAAA,CAAM,CAAA,SAAA,EAAYD,CAAG,CAAA,+BAAA,CAAiC,CAAA,CAIjE,OAAO,CACN,QAAA,CAAU,CACT,CACC,GAAA,CAAAA,CAAAA,CACA,QAAA,CAAUC,CAAAA,CAAY,QAAA,EAAY,kBAAA,CAClC,IAAA,CAAM,IAAA,CAAK,SAAA,CAAUA,CAAAA,CAAa,IAAA,CAAM,CAAC,CAC1C,CACD,CACD,CACD,CAEO,aAAA,EAA+D,CACrE,OAAO,IAAA,CAAK,UACb,CAKA,MAAa,KAAA,EAAuB,CAC/B,IAAA,CAAK,QAAA,EACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,GAEtB,CACD","file":"chunk-ISKM7EAL.js","sourcesContent":["import type * as grpc from \"@grpc/grpc-js\";\nimport { liopV1 } from \"./proto.js\";\nimport { createChannelCredentials, type LiopTlsOptions } from \"./tls.js\";\nimport type {\n\tIntentRequest,\n\tIntentResponse,\n\tLogicRequest,\n\tLogicResponse,\n} from \"./types.js\";\n\n/**\n * LIOP gRPC Client Implementation\n * Provides a high-level interface for secure intent negotiation and logic execution.\n */\nexport class LiopRpcClient {\n\t// biome-ignore lint/suspicious/noExplicitAny: internal gRPC client type\n\tprivate client: any;\n\n\tconstructor(address: string, tls?: LiopTlsOptions) {\n\t\tconst credentials = createChannelCredentials(tls);\n\t\tthis.client = new liopV1.LogicMesh(address, credentials);\n\t}\n\n\t/**\n\t * Negotiates intent with the remote host.\n\t * Returns the ephemeral Kyber public key for payload encryption.\n\t */\n\tpublic async negotiateIntent(\n\t\trequest: IntentRequest,\n\t): Promise<IntentResponse> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.client.NegotiateIntent(\n\t\t\t\trequest,\n\t\t\t\t(error: grpc.ServiceError | null, response: IntentResponse) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Pushes the encrypted Logic-on-Origin payload to the origin.\n\t * Returns a stream of semantic responses and ZK proofs.\n\t */\n\tpublic executeLogic(\n\t\trequest: LogicRequest,\n\t): grpc.ClientReadableStream<LogicResponse> {\n\t\treturn this.client.ExecuteLogic(request);\n\t}\n\n\tpublic close(): void {\n\t\tthis.client.close();\n\t}\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\n/**\n * LIOP Symmetric Payload Encryption Wrapper\n * Uses AES-256-GCM to secure WASM Code transport over Zero-Trust networks.\n * Fully compatible with the `aes-gcm` Rust crate used by Wasmtime.\n */\nexport const AesGcmWrapper = {\n\t/**\n\t * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.\n\t *\n\t * @param payload Raw incoming WASM byte array or string.\n\t * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array\n\t * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.\n\t */\n\tencryptPayload(\n\t\tpayload: Uint8Array | Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): {\n\t\tciphertext: Buffer;\n\t\tnonce: Buffer;\n\t} {\n\t\tif (sharedSecret.length !== 32) {\n\t\t\tthrow new Error(\"Symmetric Key must be exactly 32 bytes (256 bits).\");\n\t\t}\n\n\t\t// LIOP standard demands 96-bit (12 byte) IVs/Nonces for AES-GCM\n\t\tconst nonce = randomBytes(12);\n\n\t\tconst cipher = createCipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\n\t\t// Encrypt the payload and seal the tag\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\tconst authTag = cipher.getAuthTag(); // 16 bytes for GCM integrity\n\n\t\t// In LIOP, the auth tag is strictly appended to the end of the ciphertext bytes\n\t\t// mirroring the default serialization logic within `aes_gcm::Aes256Gcm` in Rust\n\t\tconst finalCiphertext = Buffer.concat([encrypted, authTag]);\n\n\t\treturn {\n\t\t\tciphertext: finalCiphertext,\n\t\t\tnonce: nonce,\n\t\t};\n\t},\n\n\t/**\n\t * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.\n\t */\n\tdecryptPayload(\n\t\tciphertextBuffer: Buffer,\n\t\tnonce: Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): Buffer {\n\t\tif (ciphertextBuffer.length < 16) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Invalid GCM Ciphertext; missing authentication tag length\",\n\t\t\t);\n\t\t}\n\n\t\t// The last 16 bytes represent the AuthTag appended by rust-aes-gcm\n\t\tconst encryptedData = ciphertextBuffer.subarray(0, -16);\n\t\tconst authTag = ciphertextBuffer.subarray(-16);\n\n\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\t\tdecipher.setAuthTag(authTag);\n\n\t\treturn Buffer.concat([decipher.update(encryptedData), decipher.final()]);\n\t},\n};\n","import { LiopVerifier } from \"../crypto/verifier.js\";\nimport {\n\ttype LiopManifest,\n\tMeshNode,\n\ttype MeshNodeConfig,\n} from \"../mesh/node.js\";\nimport { LiopRpcClient } from \"../rpc/client.js\";\nimport { AesGcmWrapper } from \"../rpc/crypto/aes.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport type { LiopTlsOptions } from \"../rpc/tls.js\";\nimport type { LogicRequest, LogicResponse } from \"../rpc/types.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * LIOP Client\n * High-level orchestration for discovery and execution in the Logic-Injection-on-Origin mesh.\n */\nexport class LiopClient {\n\tprivate meshNode: MeshNode | null = null;\n\tprivate rpcClients: Map<string, LiopRpcClient> = new Map();\n\tprivate manifests: Map<string, LiopManifest> = new Map();\n\tprivate tlsOptions?: LiopTlsOptions;\n\tprivate serverInfo?: { name: string; version: string };\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\n\tconstructor(tls?: LiopTlsOptions) {\n\t\tthis.tlsOptions = tls;\n\t}\n\n\t/**\n\t * Discovers and connects to the target server or mesh capability.\n\t * If address is omitted, it sets up the MeshNode to act purely dynamically.\n\t */\n\tpublic async connect(\n\t\taddress?: string,\n\t\toptions?: { meshConfig?: MeshNodeConfig },\n\t): Promise<void> {\n\t\tthis.meshNode = new MeshNode(options?.meshConfig);\n\t\tawait this.meshNode.start();\n\t\tlog.info(\n\t\t\t`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`,\n\t\t);\n\n\t\tif (address) {\n\t\t\tthis.rpcClients.set(\n\t\t\t\t\"static\",\n\t\t\t\tnew LiopRpcClient(address, this.tlsOptions),\n\t\t\t);\n\t\t\tthis.serverInfo = { name: `LiopServer (${address})`, version: \"1.0.0\" };\n\t\t\tlog.info(`[LiopClient] Static gRPC configured for: ${address}`);\n\t\t} else {\n\t\t\tthis.serverInfo = { name: \"LiopServer (Mesh Alpha)\", version: \"1.0.0\" };\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically queries Kademlia DHT to find the optimal PeerID providing the Capability\n\t * and returns the physical gRPC target (host:port) resolved from the provider's manifest.\n\t */\n\tpublic async resolveCapability(toolName: string): Promise<string> {\n\t\tif (!this.meshNode)\n\t\t\tthrow new Error(\n\t\t\t\t\"Client must be connected to Mesh to resolve capabilities.\",\n\t\t\t);\n\n\t\tlog.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);\n\t\tconst providers = await this.meshNode.findProviders(toolName);\n\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Kademlia DHT found zero providers for capability: ${toolName}`,\n\t\t\t);\n\t\t}\n\n\t\tconst providerId = providers[0];\n\t\tlog.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);\n\n\t\tlet grpcPort = 50051;\n\t\tconst manifest = await this.meshNode.queryManifest(providerId);\n\t\tif (manifest) {\n\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\tlog.info(`[LiopClient] Manifest resolved: gRPC port ${grpcPort}`);\n\t\t}\n\n\t\tconst addrs = await this.meshNode.resolvePeer(providerId);\n\t\tfor (const maddr of addrs) {\n\t\t\tconst parts = maddr.split(\"/\");\n\t\t\tif (parts[1] === \"ip4\") {\n\t\t\t\tconst grpcHost = `${parts[2]}:${grpcPort}`;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Translated Multiaddr to gRPC Target: ${grpcHost}`,\n\t\t\t\t);\n\t\t\t\treturn grpcHost;\n\t\t\t}\n\t\t}\n\n\t\treturn `127.0.0.1:${grpcPort}`;\n\t}\n\n\t/**\n\t * Discovers remote capabilities via the LIOP Manifest Protocol.\n\t */\n\tpublic async discoverTools(): Promise<\n\t\t{ name: string; description?: string }[]\n\t> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before discovering tools.\");\n\t\t}\n\n\t\tlog.info(`[LiopClient] Discovery started...`);\n\t\tconst providerIds = await this.meshNode.discoverManifestProviders();\n\t\tconst tools: { name: string; description?: string }[] = [];\n\t\tconst seenNames = new Set<string>();\n\n\t\tfor (const peerId of providerIds) {\n\t\t\ttry {\n\t\t\t\tlog.info(`[LiopClient] Querying manifest from: ${peerId}`);\n\t\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\t\tif (manifest) {\n\t\t\t\t\tthis.manifests.set(peerId, manifest);\n\t\t\t\t\tfor (const tool of manifest.tools) {\n\t\t\t\t\t\tif (!seenNames.has(tool.name)) {\n\t\t\t\t\t\t\ttools.push({ name: tool.name, description: tool.description });\n\t\t\t\t\t\t\tseenNames.add(tool.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Error querying manifest from ${peerId}:`,\n\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LiopClient] Discovery finished. Found ${tools.length} unique tools.`,\n\t\t);\n\t\treturn tools;\n\t}\n\n\t/**\n\t * Invokes a tool.\n\t */\n\tpublic async callTool(\n\t\trequest: CallToolRequest,\n\t\t_wasmPayload?: Buffer,\n\t): Promise<CallToolResult> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before calling tools.\");\n\t\t}\n\n\t\tconst toolName = request.name;\n\t\tlog.info(`[LiopClient] Resolving Tool: ${toolName}`);\n\n\t\t// [ALPHA-FIX] Bypass DHT discovery if we are already statically connected to a provider (Enterprise/Test mode)\n\t\tlet rpcClient = this.rpcClients.get(\"static\");\n\n\t\tif (!rpcClient) {\n\t\t\tconst dynamicAddress = await this.resolveCapability(toolName);\n\t\t\trpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);\n\t\t} else {\n\t\t\tlog.info(\n\t\t\t\t`[LiopClient] Using existing static gRPC connection for ${toolName}.`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(`[LiopClient] Negotiating intent for ${toolName}...`);\n\t\tconst agentDid = this.meshNode\n\t\t\t? `did:liop:${this.meshNode.getPeerId()}`\n\t\t\t: \"did:liop:ephemeral\";\n\t\tconst intentPayload = Buffer.from(`${toolName}:${Date.now()}`);\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(intentPayload)\n\t\t\t: intentPayload;\n\n\t\tconst intentResponse = (await rpcClient.negotiateIntent({\n\t\t\tagent_did: agentDid,\n\t\t\tcapability_hash: toolName,\n\t\t\tproof_of_intent: proofOfIntent,\n\t\t})) as unknown as {\n\t\t\taccepted: boolean;\n\t\t\terror_message: string;\n\t\t\tkyber_public_key: Uint8Array;\n\t\t\tkyberPublicKey: Uint8Array;\n\t\t\tsession_token: string;\n\t\t\tsessionToken: string;\n\t\t};\n\n\t\tif (!intentResponse.accepted) {\n\t\t\tthrow new Error(`Intent denied by host: ${intentResponse.error_message}`);\n\t\t}\n\n\t\t// LIOP Robust Field Extraction (Supports both snake_case and camelCase via gRPC-JS)\n\t\tconst publicKey =\n\t\t\tintentResponse.kyber_public_key || intentResponse.kyberPublicKey;\n\t\tconst sessionToken =\n\t\t\tintentResponse.session_token || intentResponse.sessionToken;\n\n\t\tif (!publicKey) {\n\t\t\tlog.info(\n\t\t\t\t\"[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.\",\n\t\t\t\tintentResponse,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\t\"Handshake failed: Remote host did not provide a valid Kyber Public Key.\",\n\t\t\t);\n\t\t}\n\n\t\t// 2. Post-Quantum Encapsulation (ML-KEM-768)\n\t\tlog.info(\n\t\t\t`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`,\n\t\t);\n\t\tconst { ciphertext: kyberCiphertext, sharedSecret } =\n\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(publicKey);\n\n\t\t// 3. Symmetric Sealing (AES-256-GCM)\n\t\tlog.info(`[LiopClient] Sealing WASM Payload and Inputs...`);\n\n\t\tconst _safePayload = _wasmPayload || Buffer.from(\"\");\n\n\t\t// Encrypt WASM binary\n\t\tconst { ciphertext: encryptedWasm, nonce: aesNonce } =\n\t\t\tAesGcmWrapper.encryptPayload(_safePayload, sharedSecret);\n\n\t\t// Encrypt inputs using a fresh random nonce per input to prevent AES-GCM nonce reuse\n\t\tconst encryptedInputs: Record<string, Uint8Array> = {};\n\t\tconst crypto = await import(\"node:crypto\");\n\t\tfor (const [key, value] of Object.entries(request.arguments || {})) {\n\t\t\tconst inputNonce = crypto.randomBytes(12);\n\t\t\tconst cipher = crypto.createCipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\tsharedSecret,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tconst encrypted = Buffer.concat([\n\t\t\t\tcipher.update(JSON.stringify(value)),\n\t\t\t\tcipher.final(),\n\t\t\t]);\n\t\t\tconst authTag = cipher.getAuthTag();\n\t\t\t// Prepend the 12-byte nonce to the ciphertext\n\t\t\tencryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);\n\t\t}\n\n\t\t// 4. Assemble and Execute gRPC LogicRequest\n\t\tconst logicRequest: LogicRequest = {\n\t\t\tsession_token: sessionToken,\n\t\t\twasm_binary: encryptedWasm,\n\t\t\tinputs: encryptedInputs,\n\t\t\tpqc_ciphertext: kyberCiphertext,\n\t\t\taes_nonce: aesNonce,\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst stream = rpcClient.executeLogic(logicRequest);\n\t\t\tif (!stream) {\n\t\t\t\treject(new Error(\"RPC Client unavailable or failed to create stream.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet resultFulfilled = false;\n\t\t\tlet hasReceivedData = false;\n\n\t\t\tstream.on(\"data\", async (response: LogicResponse) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\thasReceivedData = true;\n\n\t\t\t\tlog.info(\"[LiopClient] Logic Executed. Verification in progress...\");\n\n\t\t\t\ttry {\n\t\t\t\t\t// Only verify ZK-Receipt if the remote execution succeeded.\n\t\t\t\t\t// If the remote execution failed due to a policy error (e.g. Egress Shield),\n\t\t\t\t\t// the ZK proof is empty and we should bypass validation to propagate the original error.\n\t\t\t\t\tif (!response.is_error) {\n\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t_safePayload,\n\t\t\t\t\t\t\tBuffer.from(response.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\tBuffer.from(response.zk_receipt),\n\t\t\t\t\t\t\tBuffer.from(sharedSecret),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\"PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresultFulfilled = true;\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: response.semantic_evidence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: response.is_error,\n\t\t\t\t\t});\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstream.on(\"error\", (err) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\tlog.error(\"[LiopClient] Stream Error:\", err);\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tstream.on(\"end\", () => {\n\t\t\t\t// We don't throw here if we already received a response block that is currently\n\t\t\t\t// undergoing ZK Verification in the Piscina worker pool.\n\t\t\t\tif (!hasReceivedData && !resultFulfilled) {\n\t\t\t\t\treject(new Error(\"Logic-on-Origin stream closed without results.\"));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate getOrCreateRpcClient(peerId: string, address: string): LiopRpcClient {\n\t\tlet client = this.rpcClients.get(peerId);\n\t\tif (!client) {\n\t\t\tclient = new LiopRpcClient(address, this.tlsOptions);\n\t\t\tthis.rpcClients.set(peerId, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\t/**\n\t * Reads a specific resource by URI.\n\t * In LIOP, resources can be static definitions or dynamic streams.\n\t */\n\tpublic async readResource(uri: string): Promise<{\n\t\tcontents: Array<{ uri: string; mimeType?: string; text: string }>;\n\t}> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before reading resources.\");\n\t\t}\n\t\tlog.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);\n\n\t\t// We search for the peer hosting the resource in the P2P Mesh\n\t\tconst providers = await this.meshNode.findProviders(uri);\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(`No mesh providers found for resource: ${uri}`);\n\t\t}\n\n\t\t// Query the remote peer's manifest\n\t\tconst manifest = await this.meshNode.queryManifest(providers[0]);\n\t\tif (!manifest) {\n\t\t\tthrow new Error(\"Target peer did not return a valid LIOP Manifest.\");\n\t\t}\n\n\t\t// Locate the exact resource metadata\n\t\tconst resourceDef = manifest.resources?.find((r) => r.uri === uri);\n\t\tif (!resourceDef) {\n\t\t\tthrow new Error(`Resource ${uri} not listed in remote manifest.`);\n\t\t}\n\n\t\t// Return the declarative metadata (Logic-Injection is required for actual data extraction)\n\t\treturn {\n\t\t\tcontents: [\n\t\t\t\t{\n\t\t\t\t\turi,\n\t\t\t\t\tmimeType: resourceDef.mimeType || \"application/json\",\n\t\t\t\t\ttext: JSON.stringify(resourceDef, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tpublic getServerInfo(): { name: string; version: string } | undefined {\n\t\treturn this.serverInfo;\n\t}\n\n\t/**\n\t * Destroys the active Mesh Node resources.\n\t */\n\tpublic async close(): Promise<void> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/rpc/client.ts","../src/rpc/crypto/aes.ts","../src/client/index.ts"],"names":["LiopRpcClient","address","tls","credentials","createChannelCredentials","liopV1","request","resolve","reject","error","response","AesGcmWrapper","payload","sharedSecret","nonce","randomBytes","cipher","createCipheriv","encrypted","authTag","ciphertextBuffer","encryptedData","decipher","createDecipheriv","LiopClient","LiopVerifier","options","MeshNode","log","toolName","providers","providerId","grpcPort","manifest","addrs","maddr","parts","grpcHost","providerIds","tools","seenNames","peerId","tool","err","_wasmPayload","rpcClient","dynamicAddress","agentDid","intentPayload","proofOfIntent","intentResponse","publicKey","sessionToken","kyberCiphertext","Kyber768Wrapper","_safePayload","encryptedWasm","aesNonce","encryptedInputs","crypto","key","value","inputNonce","logicRequest","stream","resultFulfilled","hasReceivedData","client","uri","resourceDef","r"],"mappings":"mRAcO,IAAMA,CAAAA,CAAN,KAAoB,CAElB,MAAA,CAER,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAsB,CAClD,IAAMC,CAAAA,CAAcC,CAAAA,CAAyBF,CAAG,CAAA,CAChD,IAAA,CAAK,MAAA,CAAS,IAAIG,CAAAA,CAAO,SAAA,CAAUJ,CAAAA,CAASE,CAAW,EACxD,CAMA,MAAa,eAAA,CACZG,CAAAA,CAC0B,CAC1B,OAAO,IAAI,QAAQ,CAACC,CAAAA,CAASC,CAAAA,GAAW,CACvC,IAAA,CAAK,MAAA,CAAO,eAAA,CACXF,CAAAA,CACA,CAACG,CAAAA,CAAiCC,CAAAA,GAA6B,CAC1DD,CAAAA,CACHD,CAAAA,CAAOC,CAAK,CAAA,CAEZF,CAAAA,CAAQG,CAAQ,EAElB,CACD,EACD,CAAC,CACF,CAMO,YAAA,CACNJ,CAAAA,CAC2C,CAC3C,OAAO,IAAA,CAAK,MAAA,CAAO,YAAA,CAAaA,CAAO,CACxC,CAEO,KAAA,EAAc,CACpB,IAAA,CAAK,MAAA,CAAO,KAAA,GACb,CACD,EClDO,IAAMK,CAAAA,CAAgB,CAQ5B,cAAA,CACCC,CAAAA,CACAC,CAAAA,CAIC,CACD,GAAIA,CAAAA,CAAa,MAAA,GAAW,EAAA,CAC3B,MAAM,IAAI,KAAA,CAAM,oDAAoD,EAIrE,IAAMC,CAAAA,CAAQC,WAAAA,CAAY,EAAE,CAAA,CAEtBC,CAAAA,CAASC,cAAAA,CAAe,aAAA,CAAeJ,CAAAA,CAAcC,CAAK,CAAA,CAG1DI,CAAAA,CAAY,MAAA,CAAO,MAAA,CAAO,CAACF,CAAAA,CAAO,MAAA,CAAOJ,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AAUA,CAAAA,CAAa,IAAA,CAAM,CAAC,CAC1C,CACD,CACD,CACD,CAEO,aAAA,EAA+D,CACrE,OAAO,IAAA,CAAK,UACb,CAKA,MAAa,KAAA,EAAuB,CAC/B,IAAA,CAAK,QAAA,EACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,GAEtB,CACD","file":"chunk-AKTU6ZMX.js","sourcesContent":["import type * as grpc from \"@grpc/grpc-js\";\nimport { liopV1 } from \"./proto.js\";\nimport { createChannelCredentials, type LiopTlsOptions } from \"./tls.js\";\nimport type {\n\tIntentRequest,\n\tIntentResponse,\n\tLogicRequest,\n\tLogicResponse,\n} from \"./types.js\";\n\n/**\n * LIOP gRPC Client Implementation\n * Provides a high-level interface for secure intent negotiation and logic execution.\n */\nexport class LiopRpcClient {\n\t// biome-ignore lint/suspicious/noExplicitAny: internal gRPC client type\n\tprivate client: any;\n\n\tconstructor(address: string, tls?: LiopTlsOptions) {\n\t\tconst credentials = createChannelCredentials(tls);\n\t\tthis.client = new liopV1.LogicMesh(address, credentials);\n\t}\n\n\t/**\n\t * Negotiates intent with the remote host.\n\t * Returns the ephemeral Kyber public key for payload encryption.\n\t */\n\tpublic async negotiateIntent(\n\t\trequest: IntentRequest,\n\t): Promise<IntentResponse> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.client.NegotiateIntent(\n\t\t\t\trequest,\n\t\t\t\t(error: grpc.ServiceError | null, response: IntentResponse) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Pushes the encrypted Logic-on-Origin payload to the origin.\n\t * Returns a stream of semantic responses and ZK proofs.\n\t */\n\tpublic executeLogic(\n\t\trequest: LogicRequest,\n\t): grpc.ClientReadableStream<LogicResponse> {\n\t\treturn this.client.ExecuteLogic(request);\n\t}\n\n\tpublic close(): void {\n\t\tthis.client.close();\n\t}\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\n/**\n * LIOP Symmetric Payload Encryption Wrapper\n * Uses AES-256-GCM to secure WASM Code transport over Zero-Trust networks.\n * Fully compatible with the `aes-gcm` Rust crate used by Wasmtime.\n */\nexport const AesGcmWrapper = {\n\t/**\n\t * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.\n\t *\n\t * @param payload Raw incoming WASM byte array or string.\n\t * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array\n\t * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.\n\t */\n\tencryptPayload(\n\t\tpayload: Uint8Array | Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): {\n\t\tciphertext: Buffer;\n\t\tnonce: Buffer;\n\t} {\n\t\tif (sharedSecret.length !== 32) {\n\t\t\tthrow new Error(\"Symmetric Key must be exactly 32 bytes (256 bits).\");\n\t\t}\n\n\t\t// LIOP standard demands 96-bit (12 byte) IVs/Nonces for AES-GCM\n\t\tconst nonce = randomBytes(12);\n\n\t\tconst cipher = createCipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\n\t\t// Encrypt the payload and seal the tag\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\tconst authTag = cipher.getAuthTag(); // 16 bytes for GCM integrity\n\n\t\t// In LIOP, the auth tag is strictly appended to the end of the ciphertext bytes\n\t\t// mirroring the default serialization logic within `aes_gcm::Aes256Gcm` in Rust\n\t\tconst finalCiphertext = Buffer.concat([encrypted, authTag]);\n\n\t\treturn {\n\t\t\tciphertext: finalCiphertext,\n\t\t\tnonce: nonce,\n\t\t};\n\t},\n\n\t/**\n\t * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.\n\t */\n\tdecryptPayload(\n\t\tciphertextBuffer: Buffer,\n\t\tnonce: Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): Buffer {\n\t\tif (ciphertextBuffer.length < 16) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Invalid GCM Ciphertext; missing authentication tag length\",\n\t\t\t);\n\t\t}\n\n\t\t// The last 16 bytes represent the AuthTag appended by rust-aes-gcm\n\t\tconst encryptedData = ciphertextBuffer.subarray(0, -16);\n\t\tconst authTag = ciphertextBuffer.subarray(-16);\n\n\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\t\tdecipher.setAuthTag(authTag);\n\n\t\treturn Buffer.concat([decipher.update(encryptedData), decipher.final()]);\n\t},\n};\n","import { LiopVerifier } from \"../crypto/verifier.js\";\nimport {\n\ttype LiopManifest,\n\tMeshNode,\n\ttype MeshNodeConfig,\n} from \"../mesh/node.js\";\nimport { LiopRpcClient } from \"../rpc/client.js\";\nimport { AesGcmWrapper } from \"../rpc/crypto/aes.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport type { LiopTlsOptions } from \"../rpc/tls.js\";\nimport type { LogicRequest, LogicResponse } from \"../rpc/types.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * LIOP Client\n * High-level orchestration for discovery and execution in the Logic-Injection-on-Origin mesh.\n */\nexport class LiopClient {\n\tprivate meshNode: MeshNode | null = null;\n\tprivate rpcClients: Map<string, LiopRpcClient> = new Map();\n\tprivate manifests: Map<string, LiopManifest> = new Map();\n\tprivate tlsOptions?: LiopTlsOptions;\n\tprivate serverInfo?: { name: string; version: string };\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\n\tconstructor(tls?: LiopTlsOptions) {\n\t\tthis.tlsOptions = tls;\n\t}\n\n\t/**\n\t * Discovers and connects to the target server or mesh capability.\n\t * If address is omitted, it sets up the MeshNode to act purely dynamically.\n\t */\n\tpublic async connect(\n\t\taddress?: string,\n\t\toptions?: { meshConfig?: MeshNodeConfig },\n\t): Promise<void> {\n\t\tthis.meshNode = new MeshNode(options?.meshConfig);\n\t\tawait this.meshNode.start();\n\t\tlog.info(\n\t\t\t`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`,\n\t\t);\n\n\t\tif (address) {\n\t\t\tthis.rpcClients.set(\n\t\t\t\t\"static\",\n\t\t\t\tnew LiopRpcClient(address, this.tlsOptions),\n\t\t\t);\n\t\t\tthis.serverInfo = { name: `LiopServer (${address})`, version: \"1.0.0\" };\n\t\t\tlog.info(`[LiopClient] Static gRPC configured for: ${address}`);\n\t\t} else {\n\t\t\tthis.serverInfo = { name: \"LiopServer (Mesh Alpha)\", version: \"1.0.0\" };\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically queries Kademlia DHT to find the optimal PeerID providing the Capability\n\t * and returns the physical gRPC target (host:port) resolved from the provider's manifest.\n\t */\n\tpublic async resolveCapability(toolName: string): Promise<string> {\n\t\tif (!this.meshNode)\n\t\t\tthrow new Error(\n\t\t\t\t\"Client must be connected to Mesh to resolve capabilities.\",\n\t\t\t);\n\n\t\tlog.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);\n\t\tconst providers = await this.meshNode.findProviders(toolName);\n\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Kademlia DHT found zero providers for capability: ${toolName}`,\n\t\t\t);\n\t\t}\n\n\t\tconst providerId = providers[0];\n\t\tlog.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);\n\n\t\tlet grpcPort = 50051;\n\t\tconst manifest = await this.meshNode.queryManifest(providerId);\n\t\tif (manifest) {\n\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\tlog.info(`[LiopClient] Manifest resolved: gRPC port ${grpcPort}`);\n\t\t}\n\n\t\tconst addrs = await this.meshNode.resolvePeer(providerId);\n\t\tfor (const maddr of addrs) {\n\t\t\tconst parts = maddr.split(\"/\");\n\t\t\tif (parts[1] === \"ip4\") {\n\t\t\t\tconst grpcHost = `${parts[2]}:${grpcPort}`;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Translated Multiaddr to gRPC Target: ${grpcHost}`,\n\t\t\t\t);\n\t\t\t\treturn grpcHost;\n\t\t\t}\n\t\t}\n\n\t\treturn `127.0.0.1:${grpcPort}`;\n\t}\n\n\t/**\n\t * Discovers remote capabilities via the LIOP Manifest Protocol.\n\t */\n\tpublic async discoverTools(): Promise<\n\t\t{ name: string; description?: string }[]\n\t> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before discovering tools.\");\n\t\t}\n\n\t\tlog.info(`[LiopClient] Discovery started...`);\n\t\tconst providerIds = await this.meshNode.discoverManifestProviders();\n\t\tconst tools: { name: string; description?: string }[] = [];\n\t\tconst seenNames = new Set<string>();\n\n\t\tfor (const peerId of providerIds) {\n\t\t\ttry {\n\t\t\t\tlog.info(`[LiopClient] Querying manifest from: ${peerId}`);\n\t\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\t\tif (manifest) {\n\t\t\t\t\tthis.manifests.set(peerId, manifest);\n\t\t\t\t\tfor (const tool of manifest.tools) {\n\t\t\t\t\t\tif (!seenNames.has(tool.name)) {\n\t\t\t\t\t\t\ttools.push({ name: tool.name, description: tool.description });\n\t\t\t\t\t\t\tseenNames.add(tool.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Error querying manifest from ${peerId}:`,\n\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LiopClient] Discovery finished. Found ${tools.length} unique tools.`,\n\t\t);\n\t\treturn tools;\n\t}\n\n\t/**\n\t * Invokes a tool.\n\t */\n\tpublic async callTool(\n\t\trequest: CallToolRequest,\n\t\t_wasmPayload?: Buffer,\n\t): Promise<CallToolResult> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before calling tools.\");\n\t\t}\n\n\t\tconst toolName = request.name;\n\t\tlog.info(`[LiopClient] Resolving Tool: ${toolName}`);\n\n\t\t// [ALPHA-FIX] Bypass DHT discovery if we are already statically connected to a provider (Enterprise/Test mode)\n\t\tlet rpcClient = this.rpcClients.get(\"static\");\n\n\t\tif (!rpcClient) {\n\t\t\tconst dynamicAddress = await this.resolveCapability(toolName);\n\t\t\trpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);\n\t\t} else {\n\t\t\tlog.info(\n\t\t\t\t`[LiopClient] Using existing static gRPC connection for ${toolName}.`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(`[LiopClient] Negotiating intent for ${toolName}...`);\n\t\tconst agentDid = this.meshNode\n\t\t\t? `did:liop:${this.meshNode.getPeerId()}`\n\t\t\t: \"did:liop:ephemeral\";\n\t\tconst intentPayload = Buffer.from(`${toolName}:${Date.now()}`);\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(intentPayload)\n\t\t\t: intentPayload;\n\n\t\tconst intentResponse = (await rpcClient.negotiateIntent({\n\t\t\tagent_did: agentDid,\n\t\t\tcapability_hash: toolName,\n\t\t\tproof_of_intent: proofOfIntent,\n\t\t})) as unknown as {\n\t\t\taccepted: boolean;\n\t\t\terror_message: string;\n\t\t\tkyber_public_key: Uint8Array;\n\t\t\tkyberPublicKey: Uint8Array;\n\t\t\tsession_token: string;\n\t\t\tsessionToken: string;\n\t\t};\n\n\t\tif (!intentResponse.accepted) {\n\t\t\tthrow new Error(`Intent denied by host: ${intentResponse.error_message}`);\n\t\t}\n\n\t\t// LIOP Robust Field Extraction (Supports both snake_case and camelCase via gRPC-JS)\n\t\tconst publicKey =\n\t\t\tintentResponse.kyber_public_key || intentResponse.kyberPublicKey;\n\t\tconst sessionToken =\n\t\t\tintentResponse.session_token || intentResponse.sessionToken;\n\n\t\tif (!publicKey) {\n\t\t\tlog.info(\n\t\t\t\t\"[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.\",\n\t\t\t\tintentResponse,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\t\"Handshake failed: Remote host did not provide a valid Kyber Public Key.\",\n\t\t\t);\n\t\t}\n\n\t\t// 2. Post-Quantum Encapsulation (ML-KEM-768)\n\t\tlog.info(\n\t\t\t`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`,\n\t\t);\n\t\tconst { ciphertext: kyberCiphertext, sharedSecret } =\n\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(publicKey);\n\n\t\t// 3. Symmetric Sealing (AES-256-GCM)\n\t\tlog.info(`[LiopClient] Sealing WASM Payload and Inputs...`);\n\n\t\tconst _safePayload = _wasmPayload || Buffer.from(\"\");\n\n\t\t// Encrypt WASM binary\n\t\tconst { ciphertext: encryptedWasm, nonce: aesNonce } =\n\t\t\tAesGcmWrapper.encryptPayload(_safePayload, sharedSecret);\n\n\t\t// Encrypt inputs using a fresh random nonce per input to prevent AES-GCM nonce reuse\n\t\tconst encryptedInputs: Record<string, Uint8Array> = {};\n\t\tconst crypto = await import(\"node:crypto\");\n\t\tfor (const [key, value] of Object.entries(request.arguments || {})) {\n\t\t\tconst inputNonce = crypto.randomBytes(12);\n\t\t\tconst cipher = crypto.createCipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\tsharedSecret,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tconst encrypted = Buffer.concat([\n\t\t\t\tcipher.update(JSON.stringify(value)),\n\t\t\t\tcipher.final(),\n\t\t\t]);\n\t\t\tconst authTag = cipher.getAuthTag();\n\t\t\t// Prepend the 12-byte nonce to the ciphertext\n\t\t\tencryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);\n\t\t}\n\n\t\t// 4. Assemble and Execute gRPC LogicRequest\n\t\tconst logicRequest: LogicRequest = {\n\t\t\tsession_token: sessionToken,\n\t\t\twasm_binary: encryptedWasm,\n\t\t\tinputs: encryptedInputs,\n\t\t\tpqc_ciphertext: kyberCiphertext,\n\t\t\taes_nonce: aesNonce,\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst stream = rpcClient.executeLogic(logicRequest);\n\t\t\tif (!stream) {\n\t\t\t\treject(new Error(\"RPC Client unavailable or failed to create stream.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet resultFulfilled = false;\n\t\t\tlet hasReceivedData = false;\n\n\t\t\tstream.on(\"data\", async (response: LogicResponse) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\thasReceivedData = true;\n\n\t\t\t\tlog.info(\"[LiopClient] Logic Executed. Verification in progress...\");\n\n\t\t\t\ttry {\n\t\t\t\t\t// Only verify ZK-Receipt if the remote execution succeeded.\n\t\t\t\t\t// If the remote execution failed due to a policy error (e.g. Egress Shield),\n\t\t\t\t\t// the ZK proof is empty and we should bypass validation to propagate the original error.\n\t\t\t\t\tif (!response.is_error) {\n\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t_safePayload,\n\t\t\t\t\t\t\tBuffer.from(response.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\tBuffer.from(response.zk_receipt),\n\t\t\t\t\t\t\tBuffer.from(sharedSecret),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\"PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresultFulfilled = true;\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: response.semantic_evidence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: response.is_error,\n\t\t\t\t\t});\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstream.on(\"error\", (err) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\tlog.error(\"[LiopClient] Stream Error:\", err);\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tstream.on(\"end\", () => {\n\t\t\t\t// We don't throw here if we already received a response block that is currently\n\t\t\t\t// undergoing ZK Verification in the Piscina worker pool.\n\t\t\t\tif (!hasReceivedData && !resultFulfilled) {\n\t\t\t\t\treject(new Error(\"Logic-on-Origin stream closed without results.\"));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate getOrCreateRpcClient(peerId: string, address: string): LiopRpcClient {\n\t\tlet client = this.rpcClients.get(peerId);\n\t\tif (!client) {\n\t\t\tclient = new LiopRpcClient(address, this.tlsOptions);\n\t\t\tthis.rpcClients.set(peerId, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\t/**\n\t * Reads a specific resource by URI.\n\t * In LIOP, resources can be static definitions or dynamic streams.\n\t */\n\tpublic async readResource(uri: string): Promise<{\n\t\tcontents: Array<{ uri: string; mimeType?: string; text: string }>;\n\t}> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before reading resources.\");\n\t\t}\n\t\tlog.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);\n\n\t\t// We search for the peer hosting the resource in the P2P Mesh\n\t\tconst providers = await this.meshNode.findProviders(uri);\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(`No mesh providers found for resource: ${uri}`);\n\t\t}\n\n\t\t// Query the remote peer's manifest\n\t\tconst manifest = await this.meshNode.queryManifest(providers[0]);\n\t\tif (!manifest) {\n\t\t\tthrow new Error(\"Target peer did not return a valid LIOP Manifest.\");\n\t\t}\n\n\t\t// Locate the exact resource metadata\n\t\tconst resourceDef = manifest.resources?.find((r) => r.uri === uri);\n\t\tif (!resourceDef) {\n\t\t\tthrow new Error(`Resource ${uri} not listed in remote manifest.`);\n\t\t}\n\n\t\t// Return the declarative metadata (Logic-Injection is required for actual data extraction)\n\t\treturn {\n\t\t\tcontents: [\n\t\t\t\t{\n\t\t\t\t\turi,\n\t\t\t\t\tmimeType: resourceDef.mimeType || \"application/json\",\n\t\t\t\t\ttext: JSON.stringify(resourceDef, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tpublic getServerInfo(): { name: string; version: string } | undefined {\n\t\treturn this.serverInfo;\n\t}\n\n\t/**\n\t * Destroys the active Mesh Node resources.\n\t */\n\tpublic async close(): Promise<void> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t}\n}\n"]}
|