@nekzus/liop 2.0.0-alpha.1 → 2.0.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -20
- package/dist/bin/agent.d.ts +0 -1
- package/dist/bin/agent.js +5 -306
- package/dist/bin/agent.js.map +1 -0
- package/dist/{bridge/stream.d.ts → bridge.d.ts} +44 -3
- package/dist/bridge.js +2 -0
- package/dist/bridge.js.map +1 -0
- package/dist/chunk-7MAGL6ON.js +33 -0
- package/dist/chunk-7MAGL6ON.js.map +1 -0
- package/dist/chunk-ANFXJGMP.js +2 -0
- package/dist/chunk-ANFXJGMP.js.map +1 -0
- package/dist/chunk-DBXGYHKY.js +2 -0
- package/dist/chunk-DBXGYHKY.js.map +1 -0
- package/dist/chunk-FW6CICSY.js +29 -0
- package/dist/chunk-FW6CICSY.js.map +1 -0
- package/dist/chunk-HM77MWB6.js +2 -0
- package/dist/chunk-HM77MWB6.js.map +1 -0
- package/dist/chunk-HNDVAKEK.js +24 -0
- package/dist/chunk-HNDVAKEK.js.map +1 -0
- package/dist/chunk-HQZHZM6U.js +2 -0
- package/dist/chunk-HQZHZM6U.js.map +1 -0
- package/dist/chunk-JBMEAXYU.js +13 -0
- package/dist/chunk-JBMEAXYU.js.map +1 -0
- package/dist/chunk-LYULZHZO.js +3 -0
- package/dist/chunk-LYULZHZO.js.map +1 -0
- package/dist/chunk-P52IE4L6.js +2 -0
- package/dist/chunk-P52IE4L6.js.map +1 -0
- package/dist/chunk-PPCOS2NU.js +2 -0
- package/dist/chunk-PPCOS2NU.js.map +1 -0
- package/dist/chunk-RWRRBYG4.js +2 -0
- package/dist/chunk-RWRRBYG4.js.map +1 -0
- package/dist/chunk-S6RJHZV2.js +2 -0
- package/dist/chunk-S6RJHZV2.js.map +1 -0
- package/dist/chunk-UVTEJYHN.js +2 -0
- package/dist/chunk-UVTEJYHN.js.map +1 -0
- package/dist/client.d.ts +5 -0
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -0
- package/dist/{gateway/router.d.ts → gateway.d.ts} +30 -5
- package/dist/gateway.js +2 -0
- package/dist/gateway.js.map +1 -0
- package/dist/{client/index.d.ts → index-CyxNLlz7.d.ts} +24 -5
- package/dist/index.d.ts +313 -12
- package/dist/index.js +31 -12
- package/dist/index.js.map +1 -0
- package/dist/kyber-2WDOTUQX.js +2 -0
- package/dist/kyber-2WDOTUQX.js.map +1 -0
- package/dist/{mesh/node.d.ts → mesh.d.ts} +5 -3
- package/dist/mesh.js +2 -0
- package/dist/mesh.js.map +1 -0
- package/dist/{server/index.d.ts → server.d.ts} +125 -12
- package/dist/server.js +2 -0
- package/dist/server.js.map +1 -0
- package/dist/types.d.ts +17 -14
- package/dist/types.js +2 -26
- package/dist/types.js.map +1 -0
- package/dist/{crypto/verifier.d.ts → verifier-DTCD9imJ.d.ts} +3 -1
- package/dist/verifier-RQRYXA4C.js +2 -0
- package/dist/verifier-RQRYXA4C.js.map +1 -0
- package/dist/workers/logic-execution.d.ts +4 -2
- package/dist/workers/logic-execution.js +2 -123
- package/dist/workers/logic-execution.js.map +1 -0
- package/dist/workers/zk-verifier.d.ts +4 -2
- package/dist/workers/zk-verifier.js +2 -98
- package/dist/workers/zk-verifier.js.map +1 -0
- package/package.json +32 -19
- package/dist/bridge/index.d.ts +0 -37
- package/dist/bridge/index.js +0 -249
- package/dist/bridge/stream.js +0 -210
- package/dist/client/index.js +0 -275
- package/dist/crypto/logic-image-id.d.ts +0 -3
- package/dist/crypto/logic-image-id.js +0 -27
- package/dist/crypto/verifier.js +0 -97
- package/dist/economy/estimator.d.ts +0 -53
- package/dist/economy/estimator.js +0 -69
- package/dist/economy/index.d.ts +0 -5
- package/dist/economy/index.js +0 -3
- package/dist/economy/otel.d.ts +0 -38
- package/dist/economy/otel.js +0 -100
- package/dist/economy/telemetry.d.ts +0 -77
- package/dist/economy/telemetry.js +0 -224
- package/dist/errors.d.ts +0 -14
- package/dist/errors.js +0 -19
- package/dist/gateway/hybrid.d.ts +0 -23
- package/dist/gateway/hybrid.js +0 -199
- package/dist/gateway/router.js +0 -1054
- package/dist/mesh/index.d.ts +0 -1
- package/dist/mesh/index.js +0 -1
- package/dist/mesh/node.js +0 -853
- package/dist/prompts/adapters.d.ts +0 -16
- package/dist/prompts/adapters.js +0 -55
- package/dist/rpc/client.d.ts +0 -22
- package/dist/rpc/client.js +0 -40
- package/dist/rpc/codec/lpm.d.ts +0 -20
- package/dist/rpc/codec/lpm.js +0 -36
- package/dist/rpc/crypto/aes.d.ts +0 -22
- package/dist/rpc/crypto/aes.js +0 -47
- package/dist/rpc/crypto/kyber.d.ts +0 -27
- package/dist/rpc/crypto/kyber.js +0 -70
- package/dist/rpc/proto.d.ts +0 -2
- package/dist/rpc/proto.js +0 -33
- package/dist/rpc/server.d.ts +0 -13
- package/dist/rpc/server.js +0 -50
- package/dist/rpc/tls.d.ts +0 -26
- package/dist/rpc/tls.js +0 -54
- package/dist/rpc/types.d.ts +0 -28
- package/dist/rpc/types.js +0 -5
- package/dist/sandbox/guardian.d.ts +0 -18
- package/dist/sandbox/guardian.js +0 -58
- package/dist/sandbox/wasi.d.ts +0 -36
- package/dist/sandbox/wasi.js +0 -233
- package/dist/security/guardian.d.ts +0 -22
- package/dist/security/guardian.js +0 -52
- package/dist/security/zk.d.ts +0 -37
- package/dist/security/zk.js +0 -76
- package/dist/server/index.js +0 -1047
- package/dist/server/ner-scanner.d.ts +0 -29
- package/dist/server/ner-scanner.js +0 -141
- package/dist/server/pii.d.ts +0 -66
- package/dist/server/pii.js +0 -428
- package/dist/utils/logger.d.ts +0 -21
- package/dist/utils/logger.js +0 -70
- package/dist/utils/mcpCompact.d.ts +0 -11
- package/dist/utils/mcpCompact.js +0 -29
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a}from'./chunk-S6RJHZV2.js';import {randomUUID}from'crypto';import {serve}from'@hono/node-server';import {Hono}from'hono';import {cors}from'hono/cors';var T=10,R=1800*1e3,y=60*1e3,f=class{constructor(e,r={}){this.options=r;this.app=new Hono,this.bridgeLogic=new p(e),this.activeSessions=new Map,this.maxSessionsPerIp=r.maxSessionsPerIp??T,this.sessionTimeoutMs=r.sessionTimeoutMs??R,this.setupRoutes();}app;httpServer=null;bridgeLogic;activeSessions;evictionTimer=null;maxSessionsPerIp;sessionTimeoutMs;async createSessionTransport(e){let{WebStandardStreamableHTTPServerTransport:r}=await import('@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js'),s=new r({sessionIdGenerator:()=>randomUUID(),onsessioninitialized:t=>{this.activeSessions.set(t,{transport:s,lastActivity:Date.now(),clientIp:e}),a.info(`[LIOP-StreamBridge] Session opened: ${t} (IP: ${e})`);}});return s.onmessage=async t=>{if(s.sessionId){let i=this.activeSessions.get(s.sessionId);i&&(i.lastActivity=Date.now());}try{let i=await this.bridgeLogic.handleJsonRpcRequest(t);i!==void 0&&await s.send(i);}catch(i){a.info("[LIOP-StreamBridge] JSON-RPC error:",i.message);}},s.onclose=()=>{s.sessionId&&(this.activeSessions.delete(s.sessionId),a.info(`[LIOP-StreamBridge] Session closed: ${s.sessionId}`));},s}countSessionsByIp(e){let r=0;for(let s of this.activeSessions.values())s.clientIp===e&&r++;return r}getClientIp(e){return e.req.header("x-forwarded-for")?.split(",")[0]?.trim()||e.req.header("x-real-ip")||"unknown"}evictIdleSessions(){let e=Date.now();for(let[r,s]of this.activeSessions)e-s.lastActivity>this.sessionTimeoutMs&&(a.info(`[LIOP-StreamBridge] Evicting idle session: ${r}`),s.transport.close().catch(()=>{}),this.activeSessions.delete(r));}setupRoutes(){this.app.use("*",cors()),process.env.ZERO_TRUST_TOKEN||(process.env.ZERO_TRUST_TOKEN=randomUUID(),a.info("=".repeat(60)),a.info("\u26A0\uFE0F STRICT ZERO-TRUST MODE ENABLED \u26A0\uFE0F"),a.info("No ZERO_TRUST_TOKEN found in environment."),a.info("A secure ephemeral token has been generated for this session:"),a.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`),a.info("=".repeat(60))),this.app.use("/mcp",async(e,r)=>{let s=e.req.header("Authorization"),t=process.env.ZERO_TRUST_TOKEN;if(!s?.startsWith("Bearer ")||s.split(" ")[1]!==t)return a.info("[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token."),e.json({error:"Unauthorized: LIOP Zero-Trust Policy Enforced"},401);await r();}),this.app.all("/mcp",async e=>{let r=e.req.header("mcp-session-id");if(r){let o=this.activeSessions.get(r);if(!o)return e.json({error:"Session not found"},404);o.lastActivity=Date.now();let c=await o.transport.handleRequest(e.req.raw);return e.req.method==="DELETE"&&(this.activeSessions.delete(r),a.info(`[LIOP-StreamBridge] Session closed (DELETE): ${r}`)),c}let s=this.getClientIp(e),t=this.countSessionsByIp(s);return t>=this.maxSessionsPerIp?(a.info(`[LIOP-StreamBridge] Rate limit hit for IP: ${s} (${t} sessions)`),e.json({error:"Too Many Sessions: Rate limit exceeded"},429)):await(await this.createSessionTransport(s)).handleRequest(e.req.raw)});}async start(e){let r=e??this.options.port??3e3;return this.evictionTimer=setInterval(()=>this.evictIdleSessions(),y),new Promise(s=>{this.httpServer=serve({fetch:this.app.fetch,port:r},t=>{a.info(`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${t.port}/mcp`),s();});})}async stop(){this.evictionTimer&&(clearInterval(this.evictionTimer),this.evictionTimer=null);for(let[e,r]of this.activeSessions)await r.transport.close(),this.activeSessions.delete(e);this.httpServer&&(this.httpServer.close(),a.info("[LIOP-StreamBridge] HTTP ports released."));}};var p=class{constructor(e,r={}){this.options=r;e?.constructor?.name==="LiopServer"?(this.liopServer=e,a.info("[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)")):e?.constructor?.name==="McpServer"?(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)")):(this.legacyMcpServer=e,a.info("[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)"));}liopServer=null;legacyMcpServer=null;async handleJsonRpcRequest(e){let r=e.id,s=e.method,t=e.params;return e.jsonrpc!=="2.0"?this.errorResponse(r,-32600,"Invalid Request"):this.liopServer?this.handleLiopToMcp(r,s,t):this.legacyMcpServer&&this.liopServer?this.handleLiopToMcp(r,s,t):this.errorResponse(r,-32601,"Bridge source not configured")}async handleLiopToMcp(e,r,s){if(!this.liopServer)return null;if(r==="initialize")return this.successResponse(e,{protocolVersion:"2025-11-25",capabilities:{prompts:{},resources:{},tools:{}},serverInfo:this.liopServer.getServerInfo()});if(r!=="notifications/initialized"){if(r==="ping")return this.successResponse(e,{});if(r==="tools/list"){let t=this.liopServer.listTools();return this.successResponse(e,{tools:t})}if(r==="resources/list"){let t=this.liopServer.listResources();return this.successResponse(e,{resources:t})}if(r==="prompts/list"){let t=this.liopServer.listPrompts();return this.successResponse(e,{prompts:t})}if(r==="prompts/get"){if(!s?.name)return this.errorResponse(e,-32602,"Missing prompt name");try{let t=await this.liopServer.getPrompt({name:s.name,arguments:s.arguments});return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="resources/read"){if(!s?.uri)return this.errorResponse(e,-32602,"Missing resource URI");try{let t=await this.liopServer.readResource(s.uri);return this.successResponse(e,t)}catch(t){return this.errorResponse(e,-32e3,t.message)}}if(r==="tools/call"){if(!s?.name)return this.errorResponse(e,-32602,"Missing tool name");let t={name:s.name,arguments:s.arguments||{}};try{let i=await this.liopServer.callTool(t);return await this.verifyZkReceipt(t,i)?this.successResponse(e,i):this.successResponse(e,{content:[{type:"text",text:"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload."}],isError:!0})}catch(i){return this.errorResponse(e,-32e3,i.message)}}return this.errorResponse(e,-32601,"Method not found")}}successResponse(e,r){return {jsonrpc:"2.0",id:e,result:r}}errorResponse(e,r,s){return {jsonrpc:"2.0",id:e,error:{code:r,message:s}}}async verifyZkReceipt(e,r){if(!e.arguments?.payload||typeof e.arguments.payload!="string")return true;try{let s=e.arguments.payload,t=r.content[0]?.text;if(t&&typeof t=="string")try{let i=JSON.parse(t);if(i.image_id||i.zk_receipt){let{LiopVerifier:o}=await import('./verifier-RQRYXA4C.js');if(!await new o().verifyZkReceipt(Buffer.from(s,"utf-8"),i.image_id,Buffer.from(i.zk_receipt||"","base64")))return !1;i.audit_status="VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge",r.content[0].text=JSON.stringify(i);}}catch{}return !0}catch(s){return a.info("[LIOP-Bridge] ZK-Verifier Failure:",s),false}}async connect(){if(this.legacyMcpServer){let{LiopServer:t}=await import('./server.js');if(this.liopServer=new t(this.options.serverInfo||{name:"liop-bridge",version:"1.0.0"},{security:this.options.security}),this.options.publishToMesh){await this.liopServer.connect();let i=this.legacyMcpServer;if(i._registeredTools)for(let[o,c]of Object.entries(i._registeredTools)){let a=c;this.liopServer.tool(o,a.description||"",a.inputSchema||{},async l=>await a.handler(l));}if(i._registeredResources)for(let[o,c]of Object.entries(i._registeredResources)){let a=c;this.liopServer.resource(a.name,o,a.metadata?.description||"",a.metadata?.mimeType||"application/octet-stream",async()=>(await a.readCallback(new URL(o))).contents[0].text);}}return}let r=(await import('readline')).createInterface({input:process.stdin,output:process.stdout,terminal:false}),s=async()=>{a.info("[LIOP-Bridge] Disconnecting session..."),this.liopServer&&await this.liopServer.close(),process.exit(0);};r.on("close",s),process.on("SIGINT",s),process.on("SIGTERM",s),r.on("line",async t=>{if(t.trim())try{let i=JSON.parse(t),o=await this.handleJsonRpcRequest(i);o&&process.stdout.write(`${JSON.stringify(o)}
|
|
2
|
+
`);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}};export{f as a,p as b};//# sourceMappingURL=chunk-LYULZHZO.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-LYULZHZO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridge/stream.ts","../src/bridge/index.ts"],"names":["DEFAULT_MAX_SESSIONS_PER_IP","DEFAULT_SESSION_TIMEOUT_MS","EVICTION_INTERVAL_MS","LiopStreamBridge","internalServer","options","Hono","LiopMcpBridge","clientIp","WebStandardStreamableHTTPServerTransport","transport","randomUUID","sessionId","log","message","entry","result","err","ip","count","c","now","cors","next","auth","expectedToken","existing","response","currentSessions","port","listenPort","resolve","serve","info","id","source","payload","method","params","tools","resources","prompts","request","code","contentText","data","LiopVerifier","e","LiopServer","legacy","name","tool","t","args","uri","resource","r","rl","shutdown","line"],"mappings":"+JA6BA,IAAMA,EAA8B,EAAA,CAC9BC,CAAAA,CAA6B,IAAA,CAAU,GAAA,CACvCC,EAAuB,EAAA,CAAK,GAAA,CAgBrBC,CAAAA,CAAN,KAAuB,CAS7B,WAAA,CACCC,CAAAA,CACQC,CAAAA,CAAmC,GAC1C,CADO,IAAA,CAAA,OAAA,CAAAA,EAER,IAAA,CAAK,GAAA,CAAM,IAAIC,IAAAA,CACf,IAAA,CAAK,WAAA,CAAc,IAAIC,EAAcH,CAAc,CAAA,CACnD,IAAA,CAAK,cAAA,CAAiB,IAAI,GAAA,CAC1B,IAAA,CAAK,gBAAA,CACJC,CAAAA,CAAQ,kBAAoBL,CAAAA,CAC7B,IAAA,CAAK,iBACJK,CAAAA,CAAQ,gBAAA,EAAoBJ,EAE7B,IAAA,CAAK,WAAA,GACN,CArBQ,IACA,UAAA,CAA8C,IAAA,CAC9C,WAAA,CACA,cAAA,CACA,cAAuD,IAAA,CACvD,gBAAA,CACA,gBAAA,CAoBR,MAAc,uBACbO,CAAAA,CACoD,CACpD,GAAM,CAAE,wCAAA,CAAAC,CAAyC,CAAA,CAAI,MAAM,OAC1D,+DACD,EACMC,CAAAA,CAAY,IAAID,CAAAA,CAAyC,CAC9D,mBAAoB,IAAME,UAAAA,EAAW,CACrC,oBAAA,CAAuBC,GAAsB,CAC5C,IAAA,CAAK,eAAe,GAAA,CAAIA,CAAAA,CAAW,CAClC,SAAA,CAAAF,CAAAA,CACA,YAAA,CAAc,IAA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nC,MAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,OAChB,QAAA,CAAU,KACX,CAAC,CAAA,CAEKC,CAAAA,CAAW,SAAY,CAC5B7C,CAAAA,CAAI,IAAA,CAAK,wCAAwC,EAC7C,IAAA,CAAK,UAAA,EAAY,MAAM,IAAA,CAAK,WAAW,KAAA,EAAM,CACjD,OAAA,CAAQ,IAAA,CAAK,CAAC,EACf,CAAA,CAEA4C,EAAG,EAAA,CAAG,OAAA,CAASC,CAAQ,CAAA,CACvB,OAAA,CAAQ,EAAA,CAAG,QAAA,CAAUA,CAAQ,CAAA,CAC7B,OAAA,CAAQ,EAAA,CAAG,SAAA,CAAWA,CAAQ,CAAA,CAE9BD,CAAAA,CAAG,EAAA,CAAG,MAAA,CAAQ,MAAOE,CAAAA,EAAS,CAC7B,GAAKA,CAAAA,CAAK,IAAA,GACV,GAAI,CACH,IAAMvB,CAAAA,CAAU,KAAK,KAAA,CAAMuB,CAAI,EACzBhC,CAAAA,CAAW,MAAM,KAAK,oBAAA,CAAqBS,CAAO,CAAA,CACpDT,CAAAA,EACH,QAAQ,MAAA,CAAO,KAAA,CAAM,GAAG,IAAA,CAAK,SAAA,CAAUA,CAAQ,CAAC;AAAA,CAAI,EAEtD,CAAA,MAASoB,CAAAA,CAAY,CACpBlC,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-LYULZHZO.js","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { serve } from \"@hono/node-server\";\nimport type { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport type { JSONRPCMessage } from \"@modelcontextprotocol/sdk/types.js\";\nimport { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpBridge } from \"./index.js\";\n\n/**\n * Configuration options for LiopStreamBridge.\n */\nexport interface LiopStreamBridgeOptions {\n\t/** Port to listen on (default: 3000) */\n\tport?: number;\n\t/** Max concurrent sessions per IP (default: 5) */\n\tmaxSessionsPerIp?: number;\n\t/** Session idle timeout in milliseconds (default: 30 min) */\n\tsessionTimeoutMs?: number;\n}\n\n/** Internal metadata for tracked sessions */\ninterface SessionEntry {\n\ttransport: WebStandardStreamableHTTPServerTransport;\n\tlastActivity: number;\n\tclientIp: string;\n}\n\nconst DEFAULT_MAX_SESSIONS_PER_IP = 10;\nconst DEFAULT_SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst EVICTION_INTERVAL_MS = 60 * 1000; // Check every minute\n\n/**\n * LiopStreamBridge\n *\n * Exposes a LiopServer over a remote HTTP network using the industry-standard\n * MCP Streamable HTTP Transport + Hono JS.\n *\n * Supports concurrent multi-client connections via per-session transport instances (Map pattern).\n * External agents connect using only a URL + Bearer Token (Zero-Trust).\n *\n * Security hardening:\n * - Zero-Trust Bearer Token enforcement\n * - Per-IP rate limiting on session creation\n * - Automatic eviction of idle sessions (TTL)\n */\nexport class LiopStreamBridge {\n\tprivate app: Hono;\n\tprivate httpServer: ReturnType<typeof serve> | null = null;\n\tprivate bridgeLogic: LiopMcpBridge;\n\tprivate activeSessions: Map<string, SessionEntry>;\n\tprivate evictionTimer: ReturnType<typeof setInterval> | null = null;\n\tprivate maxSessionsPerIp: number;\n\tprivate sessionTimeoutMs: number;\n\n\tconstructor(\n\t\tinternalServer: LiopServer,\n\t\tprivate options: LiopStreamBridgeOptions = {},\n\t) {\n\t\tthis.app = new Hono();\n\t\tthis.bridgeLogic = new LiopMcpBridge(internalServer);\n\t\tthis.activeSessions = new Map();\n\t\tthis.maxSessionsPerIp =\n\t\t\toptions.maxSessionsPerIp ?? DEFAULT_MAX_SESSIONS_PER_IP;\n\t\tthis.sessionTimeoutMs =\n\t\t\toptions.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n\t\tthis.setupRoutes();\n\t}\n\n\t/**\n\t * Creates a new per-session transport instance and wires it to the LIOPMcpBridge logic.\n\t */\n\tprivate async createSessionTransport(\n\t\tclientIp: string,\n\t): Promise<WebStandardStreamableHTTPServerTransport> {\n\t\tconst { WebStandardStreamableHTTPServerTransport } = await import(\n\t\t\t\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\"\n\t\t);\n\t\tconst transport = new WebStandardStreamableHTTPServerTransport({\n\t\t\tsessionIdGenerator: () => randomUUID(),\n\t\t\tonsessioninitialized: (sessionId: string) => {\n\t\t\t\tthis.activeSessions.set(sessionId, {\n\t\t\t\t\ttransport,\n\t\t\t\t\tlastActivity: Date.now(),\n\t\t\t\t\tclientIp,\n\t\t\t\t});\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Session opened: ${sessionId} (IP: ${clientIp})`,\n\t\t\t\t);\n\t\t\t},\n\t\t});\n\n\t\t// Wire the transport's incoming messages to the LiopMcpBridge JSON-RPC router\n\t\ttransport.onmessage = async (message: JSONRPCMessage) => {\n\t\t\t// Touch activity timestamp on every message\n\t\t\tif (transport.sessionId) {\n\t\t\t\tconst entry = this.activeSessions.get(transport.sessionId);\n\t\t\t\tif (entry) entry.lastActivity = Date.now();\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.bridgeLogic.handleJsonRpcRequest(\n\t\t\t\t\tmessage as unknown as Record<string, unknown>,\n\t\t\t\t);\n\t\t\t\t// Notifications return undefined — no response needed\n\t\t\t\tif (result !== undefined) {\n\t\t\t\t\tawait transport.send(result as JSONRPCMessage);\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\"[LIOP-StreamBridge] JSON-RPC error:\", (err as Error).message);\n\t\t\t}\n\t\t};\n\n\t\ttransport.onclose = () => {\n\t\t\tif (transport.sessionId) {\n\t\t\t\tthis.activeSessions.delete(transport.sessionId);\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed: ${transport.sessionId}`);\n\t\t\t}\n\t\t};\n\n\t\treturn transport;\n\t}\n\n\t/**\n\t * Returns the number of active sessions for a given IP.\n\t */\n\tprivate countSessionsByIp(ip: string): number {\n\t\tlet count = 0;\n\t\tfor (const entry of this.activeSessions.values()) {\n\t\t\tif (entry.clientIp === ip) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\t/**\n\t * Extracts client IP from the request (supports X-Forwarded-For for reverse proxies).\n\t */\n\tprivate getClientIp(c: {\n\t\treq: { header: (name: string) => string | undefined };\n\t}): string {\n\t\treturn (\n\t\t\tc.req.header(\"x-forwarded-for\")?.split(\",\")[0]?.trim() ||\n\t\t\tc.req.header(\"x-real-ip\") ||\n\t\t\t\"unknown\"\n\t\t);\n\t}\n\n\t/**\n\t * Evicts sessions that have been idle longer than the configured timeout.\n\t */\n\tprivate evictIdleSessions(): void {\n\t\tconst now = Date.now();\n\t\tfor (const [sessionId, entry] of this.activeSessions) {\n\t\t\tif (now - entry.lastActivity > this.sessionTimeoutMs) {\n\t\t\t\tlog.info(`[LIOP-StreamBridge] Evicting idle session: ${sessionId}`);\n\t\t\t\tentry.transport.close().catch(() => {\n\t\t\t\t\t/* Swallow close errors */\n\t\t\t\t});\n\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate setupRoutes() {\n\t\tthis.app.use(\"*\", cors());\n\n\t\t// Initialize strict zero-trust token if not provided\n\t\tif (!process.env.ZERO_TRUST_TOKEN) {\n\t\t\tprocess.env.ZERO_TRUST_TOKEN = randomUUID();\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t\tlog.info(\"⚠️ STRICT ZERO-TRUST MODE ENABLED ⚠️\");\n\t\t\tlog.info(\"No ZERO_TRUST_TOKEN found in environment.\");\n\t\t\tlog.info(\"A secure ephemeral token has been generated for this session:\");\n\t\t\tlog.info(`Token: ${process.env.ZERO_TRUST_TOKEN}`);\n\t\t\tlog.info(\"=\".repeat(60));\n\t\t}\n\n\t\t// ZTA (Zero-Trust Architecture) Security Middleware\n\t\tthis.app.use(\"/mcp\", async (c, next) => {\n\t\t\tconst auth = c.req.header(\"Authorization\");\n\n\t\t\tconst expectedToken = process.env.ZERO_TRUST_TOKEN;\n\t\t\tif (\n\t\t\t\t!auth?.startsWith(\"Bearer \") ||\n\t\t\t\tauth.split(\" \")[1] !== expectedToken\n\t\t\t) {\n\t\t\t\tlog.info(\n\t\t\t\t\t\"[LIOP-StreamBridge] ALERT: Access denied - Invalid Zero-Trust token.\",\n\t\t\t\t);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{ error: \"Unauthorized: LIOP Zero-Trust Policy Enforced\" },\n\t\t\t\t\t401,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tawait next();\n\t\t});\n\n\t\t// Multi-Session Streamable HTTP Handler\n\t\tthis.app.all(\"/mcp\", async (c) => {\n\t\t\tconst sessionId = c.req.header(\"mcp-session-id\");\n\n\t\t\t// Route to existing session if session ID is present\n\t\t\tif (sessionId) {\n\t\t\t\tconst existing = this.activeSessions.get(sessionId);\n\t\t\t\tif (!existing) {\n\t\t\t\t\treturn c.json({ error: \"Session not found\" }, 404);\n\t\t\t\t}\n\t\t\t\t// Touch activity on every routed request\n\t\t\t\texisting.lastActivity = Date.now();\n\n\t\t\t\tconst response = await existing.transport.handleRequest(c.req.raw);\n\n\t\t\t\t// If DELETE, the transport closes internally but onclose may not fire.\n\t\t\t\t// Explicitly clean up the session from the Map.\n\t\t\t\tif (c.req.method === \"DELETE\") {\n\t\t\t\t\tthis.activeSessions.delete(sessionId);\n\t\t\t\t\tlog.info(`[LIOP-StreamBridge] Session closed (DELETE): ${sessionId}`);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t}\n\n\t\t\t// No session ID → New client initializing.\n\t\t\t// Rate-limit: enforce max sessions per IP\n\t\t\tconst clientIp = this.getClientIp(c);\n\t\t\tconst currentSessions = this.countSessionsByIp(clientIp);\n\t\t\tif (currentSessions >= this.maxSessionsPerIp) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-StreamBridge] Rate limit hit for IP: ${clientIp} (${currentSessions} sessions)`,\n\t\t\t\t);\n\t\t\t\treturn c.json({ error: \"Too Many Sessions: Rate limit exceeded\" }, 429);\n\t\t\t}\n\n\t\t\tconst transport = await this.createSessionTransport(clientIp);\n\t\t\treturn await transport.handleRequest(c.req.raw);\n\t\t});\n\t}\n\n\t/**\n\t * Starts the LiopStreamBridge HTTP server and session eviction timer.\n\t */\n\tpublic async start(port?: number): Promise<void> {\n\t\tconst listenPort = port ?? this.options.port ?? 3000;\n\n\t\t// Start the idle session eviction timer\n\t\tthis.evictionTimer = setInterval(\n\t\t\t() => this.evictIdleSessions(),\n\t\t\tEVICTION_INTERVAL_MS,\n\t\t);\n\n\t\treturn new Promise((resolve) => {\n\t\t\tthis.httpServer = serve(\n\t\t\t\t{\n\t\t\t\t\tfetch: this.app.fetch,\n\t\t\t\t\tport: listenPort,\n\t\t\t\t},\n\t\t\t\t(info) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-StreamBridge] Streamable HTTP Gateway on http://localhost:${info.port}/mcp`,\n\t\t\t\t\t);\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Graceful shutdown — closes all active sessions, stops timers, and releases port.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tif (this.evictionTimer) {\n\t\t\tclearInterval(this.evictionTimer);\n\t\t\tthis.evictionTimer = null;\n\t\t}\n\n\t\tfor (const [id, entry] of this.activeSessions) {\n\t\t\tawait entry.transport.close();\n\t\t\tthis.activeSessions.delete(id);\n\t\t}\n\n\t\tif (this.httpServer) {\n\t\t\tthis.httpServer.close();\n\t\t\tlog.info(\"[LIOP-StreamBridge] HTTP ports released.\");\n\t\t}\n\t}\n}\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport type { LiopServer, LiopServerOptions } from \"../server/index.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\nexport interface LiopBridgeOptions {\n\tpublishToMesh?: boolean;\n\tmeshIdentity?: string;\n\tserverInfo?: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n\tsecurity?: LiopServerOptions[\"security\"];\n}\n\n/**\n * LIOP MCP Bridge\n * A bi-directional bridge that allows legacy MCP servers to join the LIOP mesh,\n * or exposes a LIOP server as an MCP-compatible stdio process for tools like Claude Desktop.\n */\nexport class LiopMcpBridge {\n\tprivate liopServer: LiopServer | null = null;\n\tprivate legacyMcpServer: McpServer | null = null;\n\tconstructor(\n\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic source detection\n\t\tsource: LiopServer | McpServer | any,\n\t\tprivate options: LiopBridgeOptions = {},\n\t) {\n\t\t// Determine mode: Exposing LIOP to MCP (Claude) or Wrapping MCP to LIOP (Mesh)\n\t\t// We use constructor name check to avoid hard dependency on optional SDK at runtime start\n\t\tif (source?.constructor?.name === \"LiopServer\") {\n\t\t\tthis.liopServer = source as LiopServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: EXPOSE (LIOP -> MCP Stdio)\");\n\t\t} else if (source?.constructor?.name === \"McpServer\") {\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Legacy MCP -> LIOP Mesh)\");\n\t\t} else {\n\t\t\t// Fallback for inferred legacy MCP servers\n\t\t\tthis.legacyMcpServer = source as McpServer;\n\t\t\tlog.info(\"[LIOP-Bridge] Mode: WRAP (Inferred Legacy MCP -> LIOP Mesh)\");\n\t\t}\n\t}\n\n\t/**\n\t * Handles an incoming standard MCP JSON-RPC 2.0 payload.\n\t * Pipes it to the underlying server (LIOP or Legacy MCP).\n\t */\n\tpublic async handleJsonRpcRequest(\n\t\tpayload: Record<string, unknown>,\n\t): Promise<unknown> {\n\t\tconst id = payload.id as string | number;\n\t\tconst method = payload.method as string;\n\t\tconst params = payload.params as Record<string, unknown> | undefined;\n\n\t\tif (payload.jsonrpc !== \"2.0\") {\n\t\t\treturn this.errorResponse(id, -32600, \"Invalid Request\");\n\t\t}\n\n\t\t// Mode: EXPOSE (Standard behavior used by Claude Desktop)\n\t\tif (this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\t// Mode: WRAP (Redirecting via internal LiopServer after connect())\n\t\tif (this.legacyMcpServer && this.liopServer) {\n\t\t\treturn this.handleLiopToMcp(id, method, params);\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Bridge source not configured\");\n\t}\n\n\tprivate async handleLiopToMcp(\n\t\tid: string | number,\n\t\tmethod: string,\n\t\tparams: Record<string, unknown> | undefined,\n\t): Promise<unknown> {\n\t\tif (!this.liopServer) return null;\n\n\t\tif (method === \"initialize\") {\n\t\t\treturn this.successResponse(id, {\n\t\t\t\tprotocolVersion: \"2025-11-25\",\n\t\t\t\tcapabilities: {\n\t\t\t\t\tprompts: {},\n\t\t\t\t\tresources: {},\n\t\t\t\t\ttools: {},\n\t\t\t\t},\n\t\t\t\tserverInfo: this.liopServer.getServerInfo(),\n\t\t\t});\n\t\t}\n\n\t\tif (method === \"notifications/initialized\") return undefined;\n\t\tif (method === \"ping\") return this.successResponse(id, {});\n\n\t\tif (method === \"tools/list\") {\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\treturn this.successResponse(id, { tools });\n\t\t}\n\n\t\tif (method === \"resources/list\") {\n\t\t\tconst resources = this.liopServer.listResources();\n\t\t\treturn this.successResponse(id, { resources });\n\t\t}\n\n\t\tif (method === \"prompts/list\") {\n\t\t\tconst prompts = this.liopServer.listPrompts();\n\t\t\treturn this.successResponse(id, { prompts });\n\t\t}\n\n\t\tif (method === \"prompts/get\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing prompt name\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.getPrompt({\n\t\t\t\t\tname: params.name as string,\n\t\t\t\t\targuments: params.arguments as Record<string, string> | undefined,\n\t\t\t\t});\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"resources/read\") {\n\t\t\tif (!params?.uri) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing resource URI\");\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst result = await this.liopServer.readResource(params.uri as string);\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\tif (method === \"tools/call\") {\n\t\t\tif (!params?.name) {\n\t\t\t\treturn this.errorResponse(id, -32602, \"Missing tool name\");\n\t\t\t}\n\t\t\tconst request: CallToolRequest = {\n\t\t\t\tname: params.name as string,\n\t\t\t\targuments: (params.arguments as Record<string, unknown>) || {},\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tconst result: CallToolResult = await this.liopServer.callTool(request);\n\t\t\t\tconst isVerified = await this.verifyZkReceipt(request, result);\n\n\t\t\t\tif (!isVerified) {\n\t\t\t\t\treturn this.successResponse(id, {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"ALERT [LIOP ZERO-TRUST SHIELD] ZK Verification Failed. The mathematical ImageID does not match the original payload.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn this.successResponse(id, result);\n\t\t\t} catch (err: unknown) {\n\t\t\t\treturn this.errorResponse(id, -32000, (err as Error).message);\n\t\t\t}\n\t\t}\n\n\t\treturn this.errorResponse(id, -32601, \"Method not found\");\n\t}\n\n\tprivate successResponse(\n\t\tid: string | number | null | undefined,\n\t\tresult: unknown,\n\t) {\n\t\treturn { jsonrpc: \"2.0\", id, result };\n\t}\n\n\tprivate errorResponse(id: string | number, code: number, message: string) {\n\t\treturn { jsonrpc: \"2.0\", id, error: { code, message } };\n\t}\n\n\tprivate async verifyZkReceipt(\n\t\trequest: CallToolRequest,\n\t\tresult: CallToolResult,\n\t): Promise<boolean> {\n\t\tif (\n\t\t\t!request.arguments?.payload ||\n\t\t\ttypeof request.arguments.payload !== \"string\"\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\n\t\ttry {\n\t\t\tconst payload = request.arguments.payload as string;\n\t\t\tconst contentText = result.content[0]?.text;\n\n\t\t\tif (contentText && typeof contentText === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst data = JSON.parse(contentText);\n\n\t\t\t\t\tif (data.image_id || data.zk_receipt) {\n\t\t\t\t\t\t// 1. Instantiate the Industrial Verifier ( backed by Piscina Worker Pool )\n\t\t\t\t\t\tconst { LiopVerifier } = await import(\"../crypto/verifier.js\");\n\t\t\t\t\t\tconst verifier = new LiopVerifier();\n\n\t\t\t\t\t\t// 2. Delegate the heavy mathematical check (ZK Journal + Seal)\n\t\t\t\t\t\tconst isAuthentic = await verifier.verifyZkReceipt(\n\t\t\t\t\t\t\tBuffer.from(payload, \"utf-8\"),\n\t\t\t\t\t\t\tdata.image_id,\n\t\t\t\t\t\t\tBuffer.from(data.zk_receipt || \"\", \"base64\"),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isAuthentic) {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdata.audit_status =\n\t\t\t\t\t\t\t\"VERIFIED: ZK-Receipt & ImageID Mathematically Verified by LiopMcpBridge\";\n\t\t\t\t\t\tresult.content[0].text = JSON.stringify(data);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Output not JSON\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\tlog.info(\"[LIOP-Bridge] ZK-Verifier Failure:\", e);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Connects the bridge via stdio or Mesh depending on mode.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\t// In WRAP mode, we actually need to create a LiopServer and join the mesh\n\t\tif (this.legacyMcpServer) {\n\t\t\tconst { LiopServer } = await import(\"../server/index.js\");\n\t\t\tthis.liopServer = new LiopServer(\n\t\t\t\tthis.options.serverInfo || {\n\t\t\t\t\tname: \"liop-bridge\",\n\t\t\t\t\tversion: \"1.0.0\",\n\t\t\t\t},\n\t\t\t\t{ security: this.options.security },\n\t\t\t);\n\n\t\t\tif (this.options.publishToMesh) {\n\t\t\t\tawait this.liopServer.connect();\n\n\t\t\t\t// Automatically Bridge Legacy Capabilities to LIOP Mesh\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal legacy MCP properties are completely opaque and unexported\n\t\t\t\tconst legacy = this.legacyMcpServer as any;\n\n\t\t\t\t// 1. Sync Tools\n\t\t\t\tif (legacy._registeredTools) {\n\t\t\t\t\tfor (const [name, tool] of Object.entries(legacy._registeredTools)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst t = tool as any;\n\t\t\t\t\t\tthis.liopServer.tool(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tt.description || \"\",\n\t\t\t\t\t\t\tt.inputSchema || {},\n\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy callback args\n\t\t\t\t\t\t\tasync (args: any) => {\n\t\t\t\t\t\t\t\treturn await t.handler(args);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// 2. Sync Resources\n\t\t\t\tif (legacy._registeredResources) {\n\t\t\t\t\tfor (const [uri, resource] of Object.entries(\n\t\t\t\t\t\tlegacy._registeredResources,\n\t\t\t\t\t)) {\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Opaque legacy structure\n\t\t\t\t\t\tconst r = resource as any;\n\t\t\t\t\t\tthis.liopServer.resource(\n\t\t\t\t\t\t\tr.name,\n\t\t\t\t\t\t\turi,\n\t\t\t\t\t\t\tr.metadata?.description || \"\",\n\t\t\t\t\t\t\tr.metadata?.mimeType || \"application/octet-stream\",\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tconst res = await r.readCallback(new URL(uri));\n\t\t\t\t\t\t\t\treturn res.contents[0].text;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// In EXPOSE mode, listen to stdio (Claude Desktop)\n\t\tconst readline = await import(\"node:readline\");\n\t\tconst rl = readline.createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t\tterminal: false,\n\t\t});\n\n\t\tconst shutdown = async () => {\n\t\t\tlog.info(\"[LIOP-Bridge] Disconnecting session...\");\n\t\t\tif (this.liopServer) await this.liopServer.close();\n\t\t\tprocess.exit(0);\n\t\t};\n\n\t\trl.on(\"close\", shutdown);\n\t\tprocess.on(\"SIGINT\", shutdown);\n\t\tprocess.on(\"SIGTERM\", shutdown);\n\n\t\trl.on(\"line\", async (line) => {\n\t\t\tif (!line.trim()) return;\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(line);\n\t\t\t\tconst response = await this.handleJsonRpcRequest(payload);\n\t\t\t\tif (response) {\n\t\t\t\t\tprocess.stdout.write(`${JSON.stringify(response)}\\n`);\n\t\t\t\t}\n\t\t\t} catch (e: unknown) {\n\t\t\t\tlog.error(`[LIOP-Bridge] Error: ${(e as Error).message}`);\n\t\t\t}\n\t\t});\n\t}\n}\n\nexport * from \"./stream.js\";\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-UVTEJYHN.js';import {a as a$4}from'./chunk-DBXGYHKY.js';import {c,a}from'./chunk-HM77MWB6.js';import {a as a$2}from'./chunk-PPCOS2NU.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,x=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:_,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:x,wasm_binary:k,inputs:w,pqc_ciphertext:_,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(!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-P52IE4L6.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-P52IE4L6.js.map
|
|
@@ -0,0 +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,C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,CAAK,QAAA,CAAS,aAAA,CAAcH,CAAAA,CAAU,CAAC,CAAC,EAC/D,GAAI,CAACG,CAAAA,CACJ,MAAM,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-P52IE4L6.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\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t_safePayload,\n\t\t\t\t\t\tBuffer.from(response.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\tBuffer.from(response.zk_receipt),\n\t\t\t\t\t\tBuffer.from(sharedSecret),\n\t\t\t\t\t);\n\n\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\treject(\n\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\"PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed.\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\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"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-S6RJHZV2.js';import*as P from'fs/promises';import*as w from'path';import {noise}from'@chainsafe/libp2p-noise';import {yamux}from'@chainsafe/libp2p-yamux';import {bootstrap}from'@libp2p/bootstrap';import {identify}from'@libp2p/identify';import {kadDHT}from'@libp2p/kad-dht';import {ping}from'@libp2p/ping';import {tcp}from'@libp2p/tcp';import {webSockets}from'@libp2p/websockets';import {multiaddr}from'@multiformats/multiaddr';import {pipe}from'it-pipe';import {createLibp2p}from'libp2p';import {CID}from'multiformats/cid';import {sha256}from'multiformats/hashes/sha2';var q=["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR","/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt"],S="/liop/manifest/1.0.0",O="liop:manifest",E=class b{node=null;config;manifestDialFailureState=new Map;static MANIFEST_DIAL_BASE_COOLDOWN_MS=1e4;static MANIFEST_DIAL_MAX_COOLDOWN_MS=2*6e4;static MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS=3e4;announcedCapabilities=new Set;reannouncing=false;manifestProvider=null;manifestProtocolRegistered=false;localPrivateKey=null;constructor(t={}){this.config={listenAddresses:t.listenAddresses||["/ip4/0.0.0.0/tcp/0/ws","/ip4/0.0.0.0/tcp/0"],bootstrapNodes:t.bootstrapNodes||[],identityPath:t.identityPath,enableWAN:t.enableWAN??false,dhtStoragePath:t.dhtStoragePath,addressMapper:t.addressMapper};}shouldSkipManifestDial(t){let e=this.manifestDialFailureState.get(t);if(!e)return false;let n=Date.now();return n>=e.cooldownUntil?false:(n-e.lastSkipLogAt>b.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Mesh] Skipping manifest dial for ${t} during cooldown (${Math.ceil((e.cooldownUntil-n)/1e3)}s remaining)`),e.lastSkipLogAt=n),true)}recordManifestDialFailure(t){let e=Date.now(),r=(this.manifestDialFailureState.get(t)?.failures||0)+1,o=Math.min(b.MANIFEST_DIAL_BASE_COOLDOWN_MS*2**Math.max(0,r-1),b.MANIFEST_DIAL_MAX_COOLDOWN_MS);this.manifestDialFailureState.set(t,{failures:r,cooldownUntil:e+o,lastSkipLogAt:0});}clearManifestDialFailure(t){this.manifestDialFailureState.delete(t);}async loadOrCreateIdentity(){try{let{generateKeyPair:t,privateKeyFromProtobuf:e}=await import('@libp2p/crypto/keys'),n=await import('uint8arrays');if(this.config.identityPath){let o=w.resolve(this.config.identityPath);try{let d=await P.readFile(o,"utf-8"),s=JSON.parse(d),l=n.fromString(s.privKey,"base64");try{let a$1=e(l);return a.info(`[LIOP-Mesh] Loaded persistent identity from ${o}`),{privateKey:a$1,isNew:!1}}catch(a$1){a.error(`[LIOP-Mesh] Persistent identity at ${o} is invalid or corrupt. Generating new one. Error: ${a$1 instanceof Error?a$1.message:String(a$1)}`);}}catch(d){let s=d;s.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Error loading identity: ${s.message}`);}}return {privateKey:await t("Ed25519"),isNew:!0}}catch(t){a.error(`[LIOP-Mesh] Critical error in identity management: ${t}. Falling back to ephemeral identity.`);try{let{generateKeyPair:e}=await import('@libp2p/crypto/keys');return {privateKey:await e("Ed25519"),isNew:!0}}catch(e){throw new Error(`Identity system failure: ${e}`)}}}async saveIdentity(t){if(!(!this.config.identityPath||!this.node))try{let e=w.resolve(this.config.identityPath),{privateKeyToProtobuf:n}=await import('@libp2p/crypto/keys'),r=await import('uint8arrays'),o=n(t),d=(r.toString||r.default.toString)(o,"base64"),s={id:this.node.peerId.toString(),privKey:d};await P.mkdir(w.dirname(e),{recursive:!0}),await P.writeFile(e,JSON.stringify(s,null,2)),a.info(`[LIOP-Mesh] Identity persisted to ${e}`);}catch(e){a.error(`[LIOP-Mesh] FAILED to persist identity: ${e}`);}}async capabilityToCID(t){let e=await sha256.digest(new TextEncoder().encode(t));return CID.create(1,85,e)}async reannounceAll(){if(!(this.reannouncing||!this.node||this.announcedCapabilities.size===0)){this.reannouncing=true;try{if(await new Promise(t=>setTimeout(t,500)),!this.node)return;a.info(`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`);for(let t of this.announcedCapabilities)try{let e=await this.capabilityToCID(t);await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Re-announced: ${t}`);}catch(e){a.info(`[LIOP-Mesh] Re-announce failed for ${t}: ${e}`);}}finally{this.reannouncing=false;}}}async start(){if(this.node)return;let t=await this.loadOrCreateIdentity();if(!t)throw new Error("Could not initialize P2P Identity");let{privateKey:e,isNew:n}=t;this.localPrivateKey=e;let r=this.config.bootstrapNodes||[];r.length===0&&this.config.enableWAN&&(r=q);let o=r.length>0?[bootstrap({list:r})]:void 0,d=this.config.enableWAN?"/ipfs/kad/1.0.0":"/ipfs/lan/kad/1.0.0";if(this.node=await createLibp2p({privateKey:e,addresses:{listen:this.config.listenAddresses},transports:[tcp(),webSockets()],connectionEncrypters:[noise()],streamMuxers:[yamux()],services:{identify:identify(),ping:ping(),dht:kadDHT({protocol:d,clientMode:false,allowQueryWithZeroPeers:true,peerInfoMapper:s=>s})},peerDiscovery:o}),this.node.addEventListener("peer:discovery",s=>{let l=s.detail.id;if(a.info(`[LIOP-Mesh] Discovered peer: ${l.toString()}`),this.node){let a=l;if(this.config.addressMapper&&s.detail.multiaddrs.length>0){let c=s.detail.multiaddrs.map(u=>{let m=this.config.addressMapper(u.toString());return m?multiaddr(m):null}).filter(u=>u!==null).find(u=>u.toString().includes("/tcp/")&&!u.toString().includes("/ws"));c&&(a=c);}this.node.dial(a).catch(()=>{});}}),this.node.addEventListener("peer:connect",s=>{let l=s.detail;if(a.info(`[LIOP-Mesh] Connected to peer: ${l.toString()}`),!this.node)return;let a$1=this.node.services.dht;a$1?.routingTable&&(a.info(`[LIOP-Mesh] Adding ${l.toString()} to DHT Routing Table`),a$1.routingTable.add(l).catch(f=>{a.info(`[LIOP-Mesh] Failed to add peer to routing table: ${f instanceof Error?f.message:String(f)}`);})),this.reannounceAll().catch(f=>{a.info(`[LIOP-Mesh] Re-announce error: ${f instanceof Error?f.message:String(f)}`);});}),await this.node.start(),await this.loadRoutingTable(),this.applyHandlers(),n&&this.config.identityPath&&await this.saveIdentity(e),a.info(`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`),this.node.getMultiaddrs().forEach(s=>{a.info(`[LIOP-Mesh] Listening on: ${s.toString()}`);}),r.length>0){a.info(`[LIOP-Mesh] Forcing direct P2P dial to ${r.length} bootstrap nodes...`);let s=5;for(let l of r){let a$1=false,f=1;for(;f<=s&&!a$1;)try{await this.node.dial(multiaddr(l)),a.info(`[LIOP-Mesh] \u2705 Successfully dialed ${l}`),a$1=!0;}catch{let u=Math.min(1e3*2**(f-1),3e3);a.warn(`[LIOP-Mesh] \u26A0\uFE0F Dial attempt ${f}/${s} to ${l} failed. Retrying in ${u/1e3}s...`),f<s?await new Promise(m=>setTimeout(m,u)):a.error(`[LIOP-Mesh] \u274C Could not connect to bootstrap ${l} after ${s} attempts. Continuing...`),f++;}}}}async stop(){this.node&&(await this.saveRoutingTable(),await this.node.stop(),a.info("[LIOP-Mesh] Node stopped"));}async loadRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await P.readFile(t,"utf-8"),n=JSON.parse(e),{peerIdFromString:r}=await import('@libp2p/peer-id'),o=0;for(let d of n)if(!(!d.id||!d.addresses))try{let s=r(d.id),l=d.addresses.map(f=>multiaddr(f));await this.node.peerStore.save(s,{multiaddrs:l});let a=this.node.services.dht;a?.routingTable&&a.routingTable.add(s).catch(()=>{}),o++;}catch{}a.info(`[LIOP-Mesh] Loaded ${o} peers from DHT storage`);}catch(t){let e=t;e.code!=="ENOENT"&&a.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);}}async saveRoutingTable(){if(!(!this.config.dhtStoragePath||!this.node))try{let t=w.resolve(this.config.dhtStoragePath),e=await this.node.peerStore.all(),n=[];for(let r of e)r.addresses.length>0&&n.push({id:r.id.toString(),addresses:r.addresses.map(o=>o.multiaddr.toString())});await P.mkdir(w.dirname(t),{recursive:!0}),await P.writeFile(t,JSON.stringify(n,null,2)),a.info(`[LIOP-Mesh] Saved ${n.length} peers to DHT storage`);}catch(t){a.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${t}`);}}applyHandlers(){!this.node||this.manifestProtocolRegistered||this.manifestProvider&&(this.manifestProtocolRegistered=true,this.announceCapability(O).catch(t=>{a.info(`[LIOP-Mesh] Initial manifest announcement failed: ${t}`);}),this.node.handle(S,async(t,e)=>{let n=t?.stream??t,o=(t?.connection??e)?.remotePeer?.toString()||"unknown";a.info(`[LIOP-Mesh] Incoming manifest request from ${o}.`);try{let d=this.manifestProvider?.();if(!d||!n){a.info("[LIOP-Mesh] Skipping manifest request (no provider or stream)");try{typeof n?.close=="function"&&await n.close();}catch{}return}let s=JSON.stringify(d),l=new TextEncoder().encode(s),a$1=Buffer.alloc(4);a$1.writeUInt32BE(l.length,0);let f=Buffer.concat([a$1,Buffer.from(l)]);a.info(`[LIOP-Mesh] Serving manifest (${f.length} bytes) to ${o} [Tools: ${d.tools.map(c=>c.name).join(", ")}]`);try{if(typeof n.send=="function"){if(!n.send(f)&&typeof n.onDrain=="function")try{await n.onDrain({signal:AbortSignal.timeout(5e3)});}catch(u){a.info(`[LIOP-Mesh] WARN: Drain timeout for ${o}: ${u instanceof Error?u.message:String(u)}`);}}else await pipe([f],n);a.info(`[LIOP-Mesh] Manifest sent successfully to ${o}`);}catch(c){a.info(`[LIOP-Mesh] Write error serving manifest to ${o}: ${c instanceof Error?c.message:String(c)}`);}finally{try{typeof n.close=="function"&&await n.close();}catch{}}return}catch(d){a.info(`[LIOP-Mesh] Error serving manifest to ${o}: ${d instanceof Error?d.message:String(d)}`);}}),a.info(`[LIOP-Mesh] Manifest Protocol registered: ${S}`));}registerManifestHandler(t){this.manifestProvider=t,this.node&&this.applyHandlers();}async queryManifest(t){if(!this.node)throw new Error("Mesh Node is not running");if(t===this.node.peerId.toString())return a.info(`[LIOP-Mesh] Loopback: Returning local manifest directly for ${t}`),this.manifestProvider?.()||null;if(this.shouldSkipManifestDial(t))return null;let e=3;for(let n=1;n<=e;n++)try{let r=null,d=this.node.getConnections().find(h=>h.remotePeer.toString()===t);if(d)r=d.remotePeer;else {let p=(await this.node.peerStore.all()).find(g=>g.id.toString()===t);if(p)r=p.id;else {let{peerIdFromString:g}=await import('@libp2p/peer-id');r=g(t);}}let l=r;if(this.config.addressMapper&&this.node){let h=this.config.addressMapper,p=await this.node.peerStore.get(r);if(p&&p.addresses.length>0){let g=p.addresses.map(y=>{let C=y.multiaddr.toString(),T=h(C);return T?{isCertified:y.isCertified,multiaddr:multiaddr(T)}:null}).filter(y=>y!==null),L=g.find(y=>y.multiaddr.toString().includes("/tcp/")&&!y.multiaddr.toString().includes("/ws"));L&&(l=L.multiaddr,a.info(`[LIOP-Mesh] \u26A1 Direct dial to translated addr: ${l.toString()}`)),await this.node.peerStore.save(r,{multiaddrs:g.map(y=>y.multiaddr)});}}let a$1;try{let h=await this.node.dialProtocol(l,S).catch(p=>{throw String(p).includes("toMultihash")?new Error("INCOMPATIBLE_PEER_ID_INTERFACE"):p});a$1=h.stream||h;}catch(h){if(n===e)return a.info(`[LIOP-Mesh] Dial error for ${t} after ${e} attempts: ${h}`),null;let p=500*2**n;a.info(`[LIOP-Mesh] Dial error for ${t} (Attempt ${n}). Retrying in ${p}ms...`),await new Promise(g=>setTimeout(g,p));continue}let f=a$1.source??(typeof a$1[Symbol.asyncIterator]=="function"?a$1:null);if(!f)throw new Error("Target stream has no AsyncIterable source");let c=[],u=0,m=-1,M,A=new Promise((h,p)=>{M=setTimeout(()=>p(new Error("Manifest read timeout (5.0s)")),5e3);});try{await Promise.race([(async()=>{for await(let h of f){if(!h)continue;let p=typeof h.subarray=="function"?h.subarray():h instanceof Uint8Array?h:new Uint8Array(0),g=Buffer.from(p.buffer,p.byteOffset,p.byteLength);if(g.length>0&&(c.push(g),u+=g.length,m<0&&u>=4&&(m=Buffer.concat(c).readUInt32BE(0)),m>=0&&u>=4+m))break}})(),A]);}catch(h){if(c.length===0)throw h;a.info(`[LIOP-Mesh] Partial manifest read from ${t}: ${h instanceof Error?h.message:String(h)}`);}finally{M&&clearTimeout(M);}let I=Buffer.concat(c);if(I.length<4)throw new Error("Received empty/invalid manifest (too short)");let D=I.readUInt32BE(0),N=I.subarray(4,4+D).toString("utf-8"),$=JSON.parse(N);return a.info(`[LIOP-Mesh] Received manifest from ${t}: ${$.tools.length} tools`),this.clearManifestDialFailure(t),$}catch(r){if(n===e)return this.recordManifestDialFailure(t),a.info(`[LIOP-Mesh] Failed to query manifest from ${t} after ${e} attempts: ${r instanceof Error?r.message:String(r)}`),null;let o=500*2**n;a.info(`[LIOP-Mesh] Query error for ${t} (Attempt ${n}): ${r instanceof Error?r.message:String(r)}. Retrying in ${o}ms...`),await new Promise(d=>setTimeout(d,o));}return null}async discoverManifestProviders(){return this.findProviders(O)}async announceManifest(){await this.announceCapability(O);}getRoutingTableSize(){return this.node&&this.node.services.dht?.routingTable?.size||0}getPeerId(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.peerId.toString()}async sign(t){if(!this.localPrivateKey)throw new Error("Local identity not loaded or initialized");return Buffer.from(await this.localPrivateKey.sign(t))}getMultiaddrs(){if(!this.node)throw new Error("Mesh Node is not running");return this.node.getMultiaddrs().map(t=>t.toString())}async announceCapability(t){if(!this.node)throw new Error("Mesh Node is not running");this.announcedCapabilities.add(t);try{let e=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Announcing capability: ${t} (CID: ${e.toString()})`),await this.node.contentRouting.provide(e),a.info(`[LIOP-Mesh] Successfully announced capability: ${t}`);let n=this.node.peerId.toString();for await(let r of this.node.contentRouting.findProviders(e))if(r.id.toString()===n){a.info(`[LIOP-Mesh] Self-verification success: Node is providing ${t}`);break}}catch(e){a.error(`[LIOP-Mesh] Failed to announce capability: ${e}`);}}async findProviders(t){if(!this.node)throw new Error("Mesh Node is not running");let e=[];try{let n=await this.capabilityToCID(t);a.info(`[LIOP-Mesh] Querying DHT for ${t} (CID: ${n.toString()})...`);let r=!1,o=this.node.getConnections?.()?.length||0,d=o>1?1500:3e3;a.info(`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${d}ms (Active connections: ${o})`);let s=this.node.contentRouting.findProviders(n)[Symbol.asyncIterator](),l=!1;for(;!l;){let a$1=s.next(),f=new Promise(c=>setTimeout(()=>c({timeout:!0}),d));try{let c=await Promise.race([a$1,f]);if(c&&typeof c=="object"&&"timeout"in c){a.info("[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early."),typeof s.return=="function"&&s.return().catch(()=>{}),l=!0;break}let u=c;if(u.done){l=!0;break}r=!0;let M=u.value.id.toString();a.info(`[LIOP-Mesh] Found provider: ${M}`),e.includes(M)||e.push(M);}catch(c){a.warn(`[LIOP-Mesh] DHT iteration error: ${c instanceof Error?c.message:String(c)}`),l=!0;break}}if(!r){let f=this.node.services.dht?.routingTable?.size||0;a.info(`[LIOP-Mesh] DHT search for ${t} returned zero results (routing table size: ${f})`);}if(this.announcedCapabilities.has(t)){let a$1=this.node.peerId.toString();e.includes(a$1)||(a.info(`[LIOP-Mesh] Including local node (${a$1}) in results for ${t}`),e.push(a$1));}}catch(n){a.info(`[LIOP-Mesh] Error finding providers for ${t}: ${n instanceof Error?n.message:String(n)}`);}return a.info(`[LIOP-Mesh] DHT search for ${t} finished. Found ${e.length} providers.`),e}async resolvePeer(t){if(!this.node)throw new Error("Mesh Node is not running");try{let e=this.node.getConnections();for(let r of e)if(r.remotePeer.toString()===t){let o=r.remoteAddr.toString();return a.info(`[LIOP-Mesh] Resolved peer ${t} via active connection: ${o}`),[o]}let n=await this.node.peerStore.all();for(let r of n)if(r.id.toString()===t&&r.addresses.length>0){let o=r.addresses.map(d=>d.multiaddr.toString());return a.info(`[LIOP-Mesh] Resolved peer ${t} via peerStore: ${o[0]}`),o}a.info(`[LIOP-Mesh] Peer ${t} not found in connections or peerStore`);}catch(e){a.info(`[LIOP-Mesh] Failed to resolve peer ${t}: ${e}`);}return []}};export{E as a};//# sourceMappingURL=chunk-PPCOS2NU.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-PPCOS2NU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/mesh/node.ts"],"names":["DEFAULT_BOOTSTRAP_NODES","LIOP_MANIFEST_PROTOCOL","LIOP_MANIFEST_CAPABILITY","MeshNode","_MeshNode","config","peerIdStr","state","now","log","failures","backoff","generateKeyPair","privateKeyFromProtobuf","uint8arrays","absolutePath","data","json","protobufBytes","privateKey","parseError","error","e","fallbackError","privateKeyToProtobuf","privKeyEncoded","capability","hash","sha256","CID","resolve","cid","_e","result","isNew","bootNodes","discovery","bootstrap","dhtProtocol","createLibp2p","tcp","webSockets","noise","yamux","identify","ping","kadDHT","peer","evt","peerId","dialTarget","directTCP","ma","mapped","multiaddr","t","dht","err","addr","maxRetries","success","attempt","delay","peers","peerIdFromString","loadedCount","addrs","a","allPeers","peersToSave","streamArg","connectionArg","stream","remotePeer","manifest","manifestStr","payload","lengthBuf","fullPacket","drainErr","pipe","writeErr","provider","MAX_ATTEMPTS","targetPeer","activeConn","c","stored","p","mapper","translated","oa","original","dialErr","r","source","chunks","totalReceived","expectedPayloadLength","manifestTimeoutId","timeoutPromise","_","reject","chunk","raw","bytes","itErr","declaredLen","jsonStr","selfId","providers","foundAny","connections","idleTimeoutMs","iterator","isDone","nextPromise","itResult","dhtSize","conn","remoteAddr"],"mappings":"glBAwDA,IAAMA,EAA0B,CAC/B,iFAAA,CACA,iFAAA,CACA,iFAAA,CACA,iFACD,CAAA,CAEMC,CAAAA,CAAyB,uBACzBC,CAAAA,CAA2B,eAAA,CAQpBC,EAAN,MAAMC,CAAS,CACb,IAAA,CAAsB,KACtB,MAAA,CACA,wBAAA,CAGJ,IAAI,GAAA,CACR,OAAwB,+BAAiC,GAAA,CACzD,OAAwB,6BAAA,CAAgC,CAAA,CAAI,IAC5D,OAAwB,kCAAA,CAAqC,GAAA,CAQrD,qBAAA,CAAqC,IAAI,GAAA,CAGzC,YAAA,CAAe,KAAA,CAGf,gBAAA,CAAgD,KAGhD,0BAAA,CAA6B,KAAA,CAI7B,gBAA8B,IAAA,CAEtC,WAAA,CAAYC,EAAyB,EAAC,CAAG,CACx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/promises\";\nimport * as path from \"node:path\";\nimport { noise } from \"@chainsafe/libp2p-noise\";\nimport { yamux } from \"@chainsafe/libp2p-yamux\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { kadDHT } from \"@libp2p/kad-dht\";\nimport { ping } from \"@libp2p/ping\";\nimport { tcp } from \"@libp2p/tcp\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { pipe } from \"it-pipe\";\nimport type { Libp2p } from \"libp2p\";\nimport { createLibp2p } from \"libp2p\";\nimport { CID } from \"multiformats/cid\";\nimport { sha256 } from \"multiformats/hashes/sha2\";\nimport { log } from \"../utils/logger.js\";\n// import { pEvent } from \"p-event\"; // Disabled to avoid ESM conflicts in tests\n\n/**\n * Manifest describing a node's capabilities in the LIOP Mesh.\n * Exchanged via the /liop/manifest/1.0.0 protocol stream.\n */\nexport interface LiopManifest {\n\tpeerId: string;\n\tgrpcPort: number;\n\ttools: Array<{\n\t\tname: string;\n\t\tdescription?: string;\n\t\tinputSchema?: Record<string, unknown>;\n\t}>;\n\tresources: Array<{\n\t\tname: string;\n\t\turi: string;\n\t\tdescription?: string;\n\t\tmimeType?: string;\n\t\ttext?: string;\n\t}>;\n\tserverInfo: { name: string; version: string };\n\ttaxonomy?: {\n\t\tdomain: string;\n\t\tclearanceTier: number;\n\t\texecutionTypes: string[];\n\t};\n}\n\nexport interface MeshNodeConfig {\n\tlistenAddresses?: string[];\n\tbootstrapNodes?: string[];\n\tidentityPath?: string;\n\tenableWAN?: boolean;\n\tdhtStoragePath?: string;\n\t/** Optional function to translate multiaddrs (e.g. for Docker NAT traversal). Return null to drop an address. */\n\taddressMapper?: (addr: string) => string | null;\n}\n\nconst DEFAULT_BOOTSTRAP_NODES = [\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDuVkcruPhcoXdia1vAHm1qrCEYWvmqVkMBjeEbFR\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb\",\n\t\"/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjWZcYW7dwt\",\n];\n\nconst LIOP_MANIFEST_PROTOCOL = \"/liop/manifest/1.0.0\";\nconst LIOP_MANIFEST_CAPABILITY = \"liop:manifest\";\n\n/**\n * P2P Mesh Node backed by libp2p + Kademlia DHT.\n *\n * Provides capability advertisement via CID-based content routing\n * and decentralized peer discovery.\n */\nexport class MeshNode {\n\tprivate node: Libp2p | null = null;\n\tprivate config: MeshNodeConfig;\n\tprivate manifestDialFailureState: Map<\n\t\tstring,\n\t\t{ failures: number; cooldownUntil: number; lastSkipLogAt: number }\n\t> = new Map();\n\tprivate static readonly MANIFEST_DIAL_BASE_COOLDOWN_MS = 10_000;\n\tprivate static readonly MANIFEST_DIAL_MAX_COOLDOWN_MS = 2 * 60_000;\n\tprivate static readonly MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS = 30_000;\n\n\t/**\n\t * Buffer of capability hashes that have been announced.\n\t * Used to re-announce capabilities when new peers connect\n\t * (critical for small / isolated clusters where the initial\n\t * provide() finds zero peers in the routing table).\n\t */\n\tprivate announcedCapabilities: Set<string> = new Set();\n\n\t/** Guards against concurrent re-announcement storms. */\n\tprivate reannouncing = false;\n\n\t/** Callback that returns the local node's manifest on request. */\n\tprivate manifestProvider: (() => LiopManifest) | null = null;\n\n\t/** Flag to ensure the manifest protocol is only registered once. */\n\tprivate manifestProtocolRegistered = false;\n\n\t/** Local Ed25519 Private Key for protocol signatures */\n\t// biome-ignore lint/suspicious/noExplicitAny: libp2p keys type\n\tprivate localPrivateKey: any | null = null;\n\n\tconstructor(config: MeshNodeConfig = {}) {\n\t\tthis.config = {\n\t\t\tlistenAddresses: config.listenAddresses || [\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0/ws\",\n\t\t\t\t\"/ip4/0.0.0.0/tcp/0\",\n\t\t\t],\n\t\t\tbootstrapNodes: config.bootstrapNodes || [],\n\t\t\tidentityPath: config.identityPath,\n\t\t\tenableWAN: config.enableWAN ?? false,\n\t\t\tdhtStoragePath: config.dhtStoragePath,\n\t\t\taddressMapper: config.addressMapper,\n\t\t};\n\t}\n\n\tprivate shouldSkipManifestDial(peerIdStr: string): boolean {\n\t\tconst state = this.manifestDialFailureState.get(peerIdStr);\n\t\tif (!state) return false;\n\t\tconst now = Date.now();\n\t\tif (now >= state.cooldownUntil) return false;\n\t\tif (\n\t\t\tnow - state.lastSkipLogAt >\n\t\t\tMeshNode.MANIFEST_DIAL_SKIP_LOG_THROTTLE_MS\n\t\t) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Skipping manifest dial for ${peerIdStr} during cooldown (${Math.ceil((state.cooldownUntil - now) / 1000)}s remaining)`,\n\t\t\t);\n\t\t\tstate.lastSkipLogAt = now;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate recordManifestDialFailure(peerIdStr: string): void {\n\t\tconst now = Date.now();\n\t\tconst prev = this.manifestDialFailureState.get(peerIdStr);\n\t\tconst failures = (prev?.failures || 0) + 1;\n\t\tconst backoff = Math.min(\n\t\t\tMeshNode.MANIFEST_DIAL_BASE_COOLDOWN_MS * 2 ** Math.max(0, failures - 1),\n\t\t\tMeshNode.MANIFEST_DIAL_MAX_COOLDOWN_MS,\n\t\t);\n\t\tthis.manifestDialFailureState.set(peerIdStr, {\n\t\t\tfailures,\n\t\t\tcooldownUntil: now + backoff,\n\t\t\tlastSkipLogAt: 0,\n\t\t});\n\t}\n\n\tprivate clearManifestDialFailure(peerIdStr: string): void {\n\t\tthis.manifestDialFailureState.delete(peerIdStr);\n\t}\n\n\t/**\n\t * Loads a persistent identity from disk or generates a new Ed25519 keypair.\n\t * Uses privateKeyToProtobuf/privateKeyFromProtobuf (libp2p v3.x official API).\n\t */\n\tprivate async loadOrCreateIdentity() {\n\t\ttry {\n\t\t\tconst { generateKeyPair, privateKeyFromProtobuf } = (await import(\n\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\t)) as any;\n\t\t\t// @ts-expect-error: libp2p ESM dynamic import type conflict\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\tconst uint8arrays = (await import(\"uint8arrays\")) as any;\n\n\t\t\tif (this.config.identityPath) {\n\t\t\t\tconst absolutePath = path.resolve(this.config.identityPath);\n\t\t\t\ttry {\n\t\t\t\t\tconst data = await fs.readFile(absolutePath, \"utf-8\");\n\t\t\t\t\tconst json = JSON.parse(data);\n\t\t\t\t\tconst protobufBytes = uint8arrays.fromString(json.privKey, \"base64\");\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst privateKey = privateKeyFromProtobuf(protobufBytes);\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Loaded persistent identity from ${absolutePath}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { privateKey, isNew: false };\n\t\t\t\t\t} catch (parseError: unknown) {\n\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Persistent identity at ${absolutePath} is invalid or corrupt. Generating new one. Error: ${\n\t\t\t\t\t\t\t\tparseError instanceof Error\n\t\t\t\t\t\t\t\t\t? parseError.message\n\t\t\t\t\t\t\t\t\t: String(parseError)\n\t\t\t\t\t\t\t}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// Fall through to generate new key\n\t\t\t\t\t}\n\t\t\t\t} catch (error: unknown) {\n\t\t\t\t\tconst e = error as Error & { code?: string };\n\t\t\t\t\tif (e.code !== \"ENOENT\") {\n\t\t\t\t\t\tlog.error(`[LIOP-Mesh] Error loading identity: ${e.message}`);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst privateKey = await generateKeyPair(\"Ed25519\");\n\t\t\treturn { privateKey, isNew: true };\n\t\t} catch (error) {\n\t\t\tlog.error(\n\t\t\t\t`[LIOP-Mesh] Critical error in identity management: ${error}. Falling back to ephemeral identity.`,\n\t\t\t);\n\n\t\t\t// EPOCH FALLBACK: In extreme cases (corrupt env), use a volatile in-memory identity\n\t\t\t// to allow the node to start and serve traffic.\n\t\t\ttry {\n\t\t\t\tconst { generateKeyPair } = (await import(\n\t\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p ESM dynamic import type workaround\n\t\t\t\t)) as any;\n\t\t\t\tconst ephemeralKey = await generateKeyPair(\"Ed25519\");\n\t\t\t\treturn { privateKey: ephemeralKey, isNew: true };\n\t\t\t} catch (fallbackError) {\n\t\t\t\tthrow new Error(`Identity system failure: ${fallbackError}`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Persists the private key to disk using protobuf serialization (libp2p v3.x).\n\t */\n\t// biome-ignore lint/suspicious/noExplicitAny: Libp2p private key type is complex for Alpha\n\tprivate async saveIdentity(privateKey: any) {\n\t\tif (!this.config.identityPath || !this.node) return;\n\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.identityPath);\n\t\t\tconst { privateKeyToProtobuf } = (await import(\n\t\t\t\t\"@libp2p/crypto/keys\"\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <libp2p type workaround>\n\t\t\t)) as any;\n\t\t\t// @ts-expect-error: libp2p ESM dynamic import type conflict\n\t\t\tconst uint8arrays = await import(\"uint8arrays\");\n\n\t\t\tconst protobufBytes = privateKeyToProtobuf(privateKey);\n\t\t\tconst privKeyEncoded = (\n\t\t\t\tuint8arrays.toString || uint8arrays.default.toString\n\t\t\t)(protobufBytes, \"base64\");\n\n\t\t\tconst json = {\n\t\t\t\tid: this.node.peerId.toString(),\n\t\t\t\tprivKey: privKeyEncoded,\n\t\t\t};\n\n\t\t\tawait fs.mkdir(path.dirname(absolutePath), { recursive: true });\n\t\t\tawait fs.writeFile(absolutePath, JSON.stringify(json, null, 2));\n\t\t\tlog.info(`[LIOP-Mesh] Identity persisted to ${absolutePath}`);\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] FAILED to persist identity: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a CID v1 (raw codec 0x55) from a SHA-256 hash of the capability string.\n\t * Required by @libp2p/kad-dht v16+ for provide/findProviders.\n\t */\n\tprivate async capabilityToCID(capability: string): Promise<CID> {\n\t\tconst hash = await sha256.digest(new TextEncoder().encode(capability));\n\t\treturn CID.create(1, 0x55, hash);\n\t}\n\n\t/**\n\t * Re-announces all buffered capabilities after a new peer connects.\n\t * Uses a small delay to allow the DHT protocol handshake to complete.\n\t */\n\tprivate async reannounceAll(): Promise<void> {\n\t\tif (\n\t\t\tthis.reannouncing ||\n\t\t\t!this.node ||\n\t\t\tthis.announcedCapabilities.size === 0\n\t\t)\n\t\t\treturn;\n\n\t\tthis.reannouncing = true;\n\t\ttry {\n\t\t\t// Wait for the DHT protocol handshake to settle\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\n\t\t\tif (!this.node) return;\n\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Re-announcing ${this.announcedCapabilities.size} capabilities to updated routing table...`,\n\t\t\t);\n\n\t\t\tfor (const hash of this.announcedCapabilities) {\n\t\t\t\ttry {\n\t\t\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\t\t\tawait this.node.contentRouting.provide(cid);\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Re-announced: ${hash}`);\n\t\t\t\t} catch (_e) {\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Re-announce failed for ${hash}: ${_e}`);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.reannouncing = false;\n\t\t}\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.node) return;\n\t\tconst result = await this.loadOrCreateIdentity();\n\t\tif (!result) throw new Error(\"Could not initialize P2P Identity\");\n\n\t\tconst { privateKey, isNew } = result;\n\t\tthis.localPrivateKey = privateKey;\n\n\t\tlet bootNodes = this.config.bootstrapNodes || [];\n\t\tif (bootNodes.length === 0 && this.config.enableWAN) {\n\t\t\tbootNodes = DEFAULT_BOOTSTRAP_NODES;\n\t\t}\n\n\t\tconst discovery =\n\t\t\tbootNodes.length > 0\n\t\t\t\t? [\n\t\t\t\t\t\tbootstrap({\n\t\t\t\t\t\t\tlist: bootNodes,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]\n\t\t\t\t: undefined;\n\n\t\tconst dhtProtocol = this.config.enableWAN\n\t\t\t? \"/ipfs/kad/1.0.0\"\n\t\t\t: \"/ipfs/lan/kad/1.0.0\";\n\n\t\tthis.node = await createLibp2p({\n\t\t\tprivateKey,\n\t\t\taddresses: {\n\t\t\t\tlisten: this.config.listenAddresses,\n\t\t\t},\n\t\t\ttransports: [tcp(), webSockets()],\n\t\t\tconnectionEncrypters: [noise()],\n\t\t\tstreamMuxers: [yamux()],\n\t\t\tservices: {\n\t\t\t\tidentify: identify(),\n\t\t\t\tping: ping(),\n\t\t\t\tdht: kadDHT({\n\t\t\t\t\tprotocol: dhtProtocol,\n\t\t\t\t\tclientMode: false,\n\t\t\t\t\t// Allow local/private IPs in the DHT routing table for development/testing\n\t\t\t\t\tallowQueryWithZeroPeers: true,\n\t\t\t\t\t// By default kadDHT drops local IP addresses. Override the mapper to keep them.\n\t\t\t\t\tpeerInfoMapper: (peer) => peer,\n\t\t\t\t}),\n\t\t\t},\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p discovery type mismatch\n\t\t\tpeerDiscovery: discovery as any,\n\t\t});\n\n\t\t// Monitor Connectivity Events\n\t\tthis.node.addEventListener(\"peer:discovery\", (evt) => {\n\t\t\tconst peerId = evt.detail.id;\n\t\t\tlog.info(`[LIOP-Mesh] Discovered peer: ${peerId.toString()}`);\n\t\t\t// [Phase 104] Auto-dial discovered peers to bypass DHT propagation latency\n\t\t\tif (this.node) {\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: target polymorphic type\n\t\t\t\tlet dialTarget: any = peerId;\n\n\t\t\t\t// Apply port translation if necessary (Docker -> Windows Host)\n\t\t\t\tif (this.config.addressMapper && evt.detail.multiaddrs.length > 0) {\n\t\t\t\t\tconst translated = evt.detail.multiaddrs\n\t\t\t\t\t\t.map((ma) => {\n\t\t\t\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: mapped conditionally\n\t\t\t\t\t\t\tconst mapped = this.config.addressMapper!(ma.toString());\n\t\t\t\t\t\t\treturn mapped ? multiaddr(mapped) : null;\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.filter((t): t is NonNullable<typeof t> => t !== null);\n\n\t\t\t\t\tconst directTCP = translated.find(\n\t\t\t\t\t\t(ma) =>\n\t\t\t\t\t\t\tma.toString().includes(\"/tcp/\") && !ma.toString().includes(\"/ws\"),\n\t\t\t\t\t);\n\t\t\t\t\tif (directTCP) dialTarget = directTCP;\n\t\t\t\t}\n\n\t\t\t\tthis.node.dial(dialTarget).catch(() => {});\n\t\t\t}\n\t\t});\n\n\t\tthis.node.addEventListener(\"peer:connect\", (evt) => {\n\t\t\tconst peerId = evt.detail;\n\t\t\tlog.info(`[LIOP-Mesh] Connected to peer: ${peerId.toString()}`);\n\n\t\t\tif (!this.node) return;\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal services\n\t\t\tconst dht = (this.node.services as any).dht;\n\t\t\tif (dht?.routingTable) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Adding ${peerId.toString()} to DHT Routing Table`,\n\t\t\t\t);\n\t\t\t\tdht.routingTable.add(peerId).catch((err: unknown) => {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Failed to add peer to routing table: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Trigger reactive re-announcement of all capabilities\n\t\t\t// so that ADD_PROVIDER messages reach the new peer\n\t\t\tthis.reannounceAll().catch((err: unknown) => {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Re-announce error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t});\n\t\t});\n\n\t\tawait this.node.start();\n\n\t\t// Load persisted DHT routing table to enable rapid cold-start reconnections\n\t\tawait this.loadRoutingTable();\n\n\t\t// [LIOP-ALPHA] Protocols and services setup\n\t\tthis.applyHandlers();\n\n\t\tif (isNew && this.config.identityPath) {\n\t\t\tawait this.saveIdentity(privateKey);\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] Node started with id: ${this.node.peerId.toString()}`,\n\t\t);\n\t\tthis.node.getMultiaddrs().forEach((addr) => {\n\t\t\tlog.info(`[LIOP-Mesh] Listening on: ${addr.toString()}`);\n\t\t});\n\n\t\t// Force explicit dialing of Bootstrap nodes with bounded backoff\n\t\tif (bootNodes.length > 0) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Forcing direct P2P dial to ${bootNodes.length} bootstrap nodes...`,\n\t\t\t);\n\n\t\t\tconst maxRetries = 5;\n\t\t\tfor (const addr of bootNodes) {\n\t\t\t\tlet success = false;\n\t\t\t\tlet attempt = 1;\n\n\t\t\t\twhile (attempt <= maxRetries && !success) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.node.dial(multiaddr(addr));\n\t\t\t\t\t\tlog.info(`[LIOP-Mesh] ✅ Successfully dialed ${addr}`);\n\t\t\t\t\t\tsuccess = true;\n\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\tconst delay = Math.min(1000 * 2 ** (attempt - 1), 3000);\n\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t`[LIOP-Mesh] ⚠️ Dial attempt ${attempt}/${maxRetries} to ${addr} failed. Retrying in ${delay / 1000}s...`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (attempt < maxRetries) {\n\t\t\t\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t\t`[LIOP-Mesh] ❌ Could not connect to bootstrap ${addr} after ${maxRetries} attempts. Continuing...`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tattempt++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tif (this.node) {\n\t\t\tawait this.saveRoutingTable();\n\t\t\tawait this.node.stop();\n\t\t\tlog.info(\"[LIOP-Mesh] Node stopped\");\n\t\t}\n\t}\n\n\tprivate async loadRoutingTable() {\n\t\tif (!this.config.dhtStoragePath || !this.node) return;\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.dhtStoragePath);\n\t\t\tconst data = await fs.readFile(absolutePath, \"utf-8\");\n\t\t\tconst peers = JSON.parse(data);\n\t\t\tconst { peerIdFromString } = await import(\"@libp2p/peer-id\");\n\n\t\t\tlet loadedCount = 0;\n\t\t\tfor (const peer of peers) {\n\t\t\t\tif (!peer.id || !peer.addresses) continue;\n\t\t\t\ttry {\n\t\t\t\t\tconst peerId = peerIdFromString(peer.id);\n\t\t\t\t\tconst addrs = peer.addresses.map((a: string) => multiaddr(a));\n\t\t\t\t\t// @ts-expect-error: libp2p version drift workaround\n\t\t\t\t\tawait this.node.peerStore.save(peerId, { multiaddrs: addrs });\n\n\t\t\t\t\t// Pre-seed DHT routing table\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal service access\n\t\t\t\t\tconst dht = (this.node.services as any).dht;\n\t\t\t\t\tif (dht?.routingTable) {\n\t\t\t\t\t\tdht.routingTable.add(peerId).catch(() => {});\n\t\t\t\t\t}\n\t\t\t\t\tloadedCount++;\n\t\t\t\t} catch (_e) {}\n\t\t\t}\n\t\t\tlog.info(`[LIOP-Mesh] Loaded ${loadedCount} peers from DHT storage`);\n\t\t} catch (error: unknown) {\n\t\t\tconst e = error as Error & { code?: string };\n\t\t\tif (e.code !== \"ENOENT\") {\n\t\t\t\tlog.error(`[LIOP-Mesh] Failed to load DHT table: ${e.message}`);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async saveRoutingTable() {\n\t\tif (!this.config.dhtStoragePath || !this.node) return;\n\t\ttry {\n\t\t\tconst absolutePath = path.resolve(this.config.dhtStoragePath);\n\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\tconst peersToSave = [];\n\t\t\tfor (const peer of allPeers) {\n\t\t\t\tif (peer.addresses.length > 0) {\n\t\t\t\t\tpeersToSave.push({\n\t\t\t\t\t\tid: peer.id.toString(),\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: internal libp2p addr\n\t\t\t\t\t\taddresses: peer.addresses.map((a: any) => a.multiaddr.toString()),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait fs.mkdir(path.dirname(absolutePath), { recursive: true });\n\t\t\tawait fs.writeFile(absolutePath, JSON.stringify(peersToSave, null, 2));\n\t\t\tlog.info(`[LIOP-Mesh] Saved ${peersToSave.length} peers to DHT storage`);\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] FAILED to save DHT routing table: ${error}`);\n\t\t}\n\t}\n\n\t/**\n\t * Internal logic to register protocol handlers against the libp2p node.\n\t * Can be called multiple times; handles idempotent registration.\n\t */\n\tprivate applyHandlers(): void {\n\t\tif (!this.node || this.manifestProtocolRegistered) return;\n\t\tif (!this.manifestProvider) return;\n\n\t\tthis.manifestProtocolRegistered = true;\n\n\t\t// Announce manifest capability to the Mesh DHT for discovery\n\t\tthis.announceCapability(LIOP_MANIFEST_CAPABILITY).catch((err) => {\n\t\t\tlog.info(`[LIOP-Mesh] Initial manifest announcement failed: ${err}`);\n\t\t});\n\n\t\t// libp2p v3.x: handler receives (stream, connection) as separate args\n\t\tthis.node.handle(\n\t\t\tLIOP_MANIFEST_PROTOCOL,\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p v3.x stream/connection types\n\t\t\tasync (streamArg: any, connectionArg?: any) => {\n\t\t\t\t// v3.x passes (stream, connection); v1.x passed ({ stream, connection })\n\t\t\t\tconst stream = streamArg?.stream ?? streamArg;\n\t\t\t\tconst conn = streamArg?.connection ?? connectionArg;\n\t\t\t\tconst remotePeer = conn?.remotePeer?.toString() || \"unknown\";\n\n\t\t\t\tlog.info(`[LIOP-Mesh] Incoming manifest request from ${remotePeer}.`);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst manifest = this.manifestProvider?.();\n\t\t\t\t\tif (!manifest || !stream) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Skipping manifest request (no provider or stream)`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (typeof stream?.close === \"function\") await stream.close();\n\t\t\t\t\t\t} catch (_e) {}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst manifestStr = JSON.stringify(manifest);\n\t\t\t\t\tconst payload = new TextEncoder().encode(manifestStr);\n\n\t\t\t\t\t// Write length-prefixed payload (Big Endian 4 bytes)\n\t\t\t\t\tconst lengthBuf = Buffer.alloc(4);\n\t\t\t\t\tlengthBuf.writeUInt32BE(payload.length, 0);\n\t\t\t\t\tconst fullPacket = Buffer.concat([lengthBuf, Buffer.from(payload)]);\n\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Serving manifest (${fullPacket.length} bytes) to ${remotePeer} [Tools: ${manifest.tools.map((t) => t.name).join(\", \")}]`,\n\t\t\t\t\t);\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// libp2p v3.x: stream.send() for writing\n\t\t\t\t\t\tif (typeof stream.send === \"function\") {\n\t\t\t\t\t\t\tconst accepted = stream.send(fullPacket);\n\t\t\t\t\t\t\tif (!accepted && typeof stream.onDrain === \"function\") {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tawait stream.onDrain({ signal: AbortSignal.timeout(5000) });\n\t\t\t\t\t\t\t\t} catch (drainErr) {\n\t\t\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t\t\t`[LIOP-Mesh] WARN: Drain timeout for ${remotePeer}: ${drainErr instanceof Error ? drainErr.message : String(drainErr)}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Fallback for environments where stream.send is not available\n\t\t\t\t\t\t\tawait pipe([fullPacket], stream);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.info(`[LIOP-Mesh] Manifest sent successfully to ${remotePeer}`);\n\t\t\t\t\t} catch (writeErr: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Write error serving manifest to ${remotePeer}: ${writeErr instanceof Error ? writeErr.message : String(writeErr)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (typeof stream.close === \"function\") await stream.close();\n\t\t\t\t\t\t} catch (_e) {\n\t\t\t\t\t\t\t// Ignore close errors\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t} catch (err: unknown) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Error serving manifest to ${remotePeer}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] Manifest Protocol registered: ${LIOP_MANIFEST_PROTOCOL}`,\n\t\t);\n\t}\n\n\t/**\n\t * Registers a callback as the manifest provider.\n\t * Will be applied immediately if the node is already initialized.\n\t */\n\tregisterManifestHandler(provider: () => LiopManifest): void {\n\t\tthis.manifestProvider = provider;\n\t\tif (this.node) {\n\t\t\tthis.applyHandlers();\n\t\t}\n\t}\n\n\t/**\n\t * Queries a remote peer's manifest by opening a /liop/manifest/1.0.0 stream.\n\t * Returns null if the peer doesn't support the protocol or is unreachable.\n\t */\n\tasync queryManifest(peerIdStr: string): Promise<LiopManifest | null> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\n\t\t// [ALPHA-OPTIMIZATION] Local Loopback Bypass\n\t\t// If we are querying our own manifest, return it directly from the provider.\n\t\tif (peerIdStr === this.node.peerId.toString()) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Loopback: Returning local manifest directly for ${peerIdStr}`,\n\t\t\t);\n\t\t\treturn this.manifestProvider?.() || null;\n\t\t}\n\t\tif (this.shouldSkipManifestDial(peerIdStr)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tconst MAX_ATTEMPTS = 3;\n\t\tfor (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n\t\t\ttry {\n\t\t\t\ttype DialTarget = Parameters<Libp2p[\"dialProtocol\"]>[0];\n\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: targetPeer can be from connections or from string\n\t\t\t\tlet targetPeer: any = null;\n\t\t\t\tconst connections = this.node.getConnections();\n\t\t\t\tconst activeConn = connections.find(\n\t\t\t\t\t(c) => c.remotePeer.toString() === peerIdStr,\n\t\t\t\t);\n\n\t\t\t\tif (activeConn) {\n\t\t\t\t\ttargetPeer = activeConn.remotePeer;\n\t\t\t\t} else {\n\t\t\t\t\t// Fallback: search peerStore to find a valid PeerId object that libp2p understands natively\n\t\t\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\t\t\tconst stored = allPeers.find((p) => p.id.toString() === peerIdStr);\n\t\t\t\t\tif (stored) {\n\t\t\t\t\t\ttargetPeer = stored.id;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Final fallback parsing.\n\t\t\t\t\t\t// [LIOP-CAUTION] This is where the toMultihash error usually triggers if libp2p version drift exists.\n\t\t\t\t\t\tconst { peerIdFromString } = await import(\"@libp2p/peer-id\");\n\t\t\t\t\t\ttargetPeer = peerIdFromString(peerIdStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// [LIOP-PORT-TRANSLATION] If an address mapper is configured (e.g. in the Host Agent),\n\t\t\t\t// ensure the targetPeer's addresses are translated before libp2p attempts to dial.\n\t\t\t\tconst dialTargetFromPeer = targetPeer as DialTarget;\n\t\t\t\tlet dialTarget: DialTarget = dialTargetFromPeer;\n\t\t\t\tif (this.config.addressMapper && this.node) {\n\t\t\t\t\tconst mapper = this.config.addressMapper;\n\t\t\t\t\tconst peer = await this.node.peerStore.get(targetPeer);\n\t\t\t\t\tif (peer && peer.addresses.length > 0) {\n\t\t\t\t\t\tconst translated = peer.addresses\n\t\t\t\t\t\t\t.map((oa) => {\n\t\t\t\t\t\t\t\tconst original = oa.multiaddr.toString();\n\t\t\t\t\t\t\t\tconst mapped = mapper(original);\n\t\t\t\t\t\t\t\tif (!mapped) return null;\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tisCertified: oa.isCertified,\n\t\t\t\t\t\t\t\t\tmultiaddr: multiaddr(mapped),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.filter((t): t is NonNullable<typeof t> => t !== null);\n\n\t\t\t\t\t\t// Strategy: Force direct dial to the first translated TCP address to bypass DHT routing delays\n\t\t\t\t\t\tconst directTCP = translated.find(\n\t\t\t\t\t\t\t(t) =>\n\t\t\t\t\t\t\t\tt.multiaddr.toString().includes(\"/tcp/\") &&\n\t\t\t\t\t\t\t\t!t.multiaddr.toString().includes(\"/ws\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (directTCP) {\n\t\t\t\t\t\t\tdialTarget = directTCP.multiaddr as DialTarget;\n\t\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t\t`[LIOP-Mesh] ⚡ Direct dial to translated addr: ${dialTarget.toString()}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Update the peerStore so subsequent dials also use the right path\n\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: access internal peerStore\n\t\t\t\t\t\tawait (this.node as any).peerStore.save(targetPeer, {\n\t\t\t\t\t\t\tmultiaddrs: translated.map((t) => t.multiaddr),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Open a protocol stream using high-level dialProtocol for automated it-stream wrapping\n\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: stream type varies by transport\n\t\t\t\tlet stream: any;\n\t\t\t\ttry {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: libp2p returns polymorphic dialProtocol result\n\t\t\t\t\tconst result: any = await this.node\n\t\t\t\t\t\t.dialProtocol(dialTarget, LIOP_MANIFEST_PROTOCOL)\n\t\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\t\t// Catch specific TypeError that breaks the loop\n\t\t\t\t\t\t\tif (String(e).includes(\"toMultihash\")) {\n\t\t\t\t\t\t\t\tthrow new Error(\"INCOMPATIBLE_PEER_ID_INTERFACE\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t});\n\t\t\t\t\tstream = result.stream || result;\n\t\t\t\t} catch (dialErr) {\n\t\t\t\t\tif (attempt === MAX_ATTEMPTS) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] Dial error for ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${dialErr}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tconst delay = 500 * 2 ** attempt;\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Dial error for ${peerIdStr} (Attempt ${attempt}). Retrying in ${delay}ms...`,\n\t\t\t\t\t);\n\t\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// libp2p v3.x: stream IS the AsyncIterable<Uint8Array>\n\t\t\t\t// v1.x had stream.source; v3.x has the stream itself as iterable\n\t\t\t\tconst source: AsyncIterable<Uint8Array> =\n\t\t\t\t\tstream.source ??\n\t\t\t\t\t(typeof stream[Symbol.asyncIterator] === \"function\" ? stream : null);\n\n\t\t\t\tif (!source) {\n\t\t\t\t\tthrow new Error(\"Target stream has no AsyncIterable source\");\n\t\t\t\t}\n\n\t\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\t\tlet totalReceived = 0;\n\t\t\t\tlet expectedPayloadLength = -1;\n\n\t\t\t\t// Read length-prefixed manifest: first 4 bytes = payload length (BE)\n\t\t\t\tlet manifestTimeoutId: NodeJS.Timeout | undefined;\n\t\t\t\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\t\t\t\tmanifestTimeoutId = setTimeout(\n\t\t\t\t\t\t() => reject(new Error(\"Manifest read timeout (5.0s)\")),\n\t\t\t\t\t\t5000,\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\ttry {\n\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t(async () => {\n\t\t\t\t\t\t\tfor await (const chunk of source) {\n\t\t\t\t\t\t\t\tif (!chunk) continue;\n\t\t\t\t\t\t\t\t// libp2p streams yield Uint8ArrayList (from uint8arraylist package)\n\t\t\t\t\t\t\t\t// which reports .length correctly but Buffer.from() produces zeros.\n\t\t\t\t\t\t\t\t// .subarray() returns a flat contiguous Uint8Array with actual data.\n\t\t\t\t\t\t\t\tconst raw =\n\t\t\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Uint8ArrayList type guard\n\t\t\t\t\t\t\t\t\ttypeof (chunk as any).subarray === \"function\"\n\t\t\t\t\t\t\t\t\t\t? (chunk as { subarray: () => Uint8Array }).subarray()\n\t\t\t\t\t\t\t\t\t\t: chunk instanceof Uint8Array\n\t\t\t\t\t\t\t\t\t\t\t? chunk\n\t\t\t\t\t\t\t\t\t\t\t: new Uint8Array(0);\n\t\t\t\t\t\t\t\tconst bytes = Buffer.from(\n\t\t\t\t\t\t\t\t\traw.buffer,\n\t\t\t\t\t\t\t\t\traw.byteOffset,\n\t\t\t\t\t\t\t\t\traw.byteLength,\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tif (bytes.length > 0) {\n\t\t\t\t\t\t\t\t\tchunks.push(bytes);\n\t\t\t\t\t\t\t\t\ttotalReceived += bytes.length;\n\n\t\t\t\t\t\t\t\t\t// Extract expected length from the first 4 bytes once available\n\t\t\t\t\t\t\t\t\tif (expectedPayloadLength < 0 && totalReceived >= 4) {\n\t\t\t\t\t\t\t\t\t\tconst header = Buffer.concat(chunks);\n\t\t\t\t\t\t\t\t\t\texpectedPayloadLength = header.readUInt32BE(0);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t// Stop reading once we have the full payload (4 prefix + N payload)\n\t\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\t\texpectedPayloadLength >= 0 &&\n\t\t\t\t\t\t\t\t\t\ttotalReceived >= 4 + expectedPayloadLength\n\t\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})(),\n\t\t\t\t\t\ttimeoutPromise,\n\t\t\t\t\t]);\n\t\t\t\t} catch (itErr: unknown) {\n\t\t\t\t\tif (chunks.length === 0) throw itErr;\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Partial manifest read from ${peerIdStr}: ${itErr instanceof Error ? itErr.message : String(itErr)}`,\n\t\t\t\t\t);\n\t\t\t\t} finally {\n\t\t\t\t\tif (manifestTimeoutId) clearTimeout(manifestTimeoutId);\n\t\t\t\t}\n\n\t\t\t\tconst raw = Buffer.concat(chunks);\n\t\t\t\tif (raw.length < 4) {\n\t\t\t\t\tthrow new Error(\"Received empty/invalid manifest (too short)\");\n\t\t\t\t}\n\n\t\t\t\t// Use the length prefix to extract exactly the expected JSON\n\t\t\t\tconst declaredLen = raw.readUInt32BE(0);\n\t\t\t\tconst jsonStr = raw.subarray(4, 4 + declaredLen).toString(\"utf-8\");\n\t\t\t\tconst manifest: LiopManifest = JSON.parse(jsonStr);\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Received manifest from ${peerIdStr}: ${manifest.tools.length} tools`,\n\t\t\t\t);\n\t\t\t\tthis.clearManifestDialFailure(peerIdStr);\n\n\t\t\t\treturn manifest;\n\t\t\t} catch (err: unknown) {\n\t\t\t\tif (attempt === MAX_ATTEMPTS) {\n\t\t\t\t\tthis.recordManifestDialFailure(peerIdStr);\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Failed to query manifest from ${peerIdStr} after ${MAX_ATTEMPTS} attempts: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\tconst delay = 500 * 2 ** attempt;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] Query error for ${peerIdStr} (Attempt ${attempt}): ${err instanceof Error ? err.message : String(err)}. Retrying in ${delay}ms...`,\n\t\t\t\t);\n\t\t\t\tawait new Promise((r) => setTimeout(r, delay));\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Discovers all peers in the DHT that have announced \"liop:manifest\".\n\t * Returns their PeerIDs for subsequent manifest queries.\n\t */\n\tasync discoverManifestProviders(): Promise<string[]> {\n\t\treturn this.findProviders(LIOP_MANIFEST_CAPABILITY);\n\t}\n\n\t/**\n\t * Announces this node as a manifest provider in the DHT.\n\t * Should be called after tools/resources have been registered.\n\t */\n\tasync announceManifest(): Promise<void> {\n\t\tawait this.announceCapability(LIOP_MANIFEST_CAPABILITY);\n\t}\n\n\t/**\n\t * Returns the current size of the routing table for diagnostic purposes.\n\t */\n\tgetRoutingTableSize(): number {\n\t\tif (!this.node) return 0;\n\t\t// @ts-expect-error: Accessing internal routing table size for diagnostics\n\t\treturn this.node.services.dht?.routingTable?.size || 0;\n\t}\n\n\tgetPeerId(): string {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\treturn this.node.peerId.toString();\n\t}\n\n\tasync sign(data: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.localPrivateKey) {\n\t\t\tthrow new Error(\"Local identity not loaded or initialized\");\n\t\t}\n\t\t// libp2p private key implementations typically return a Promise<Uint8Array> or Uint8Array\n\t\treturn Buffer.from(await this.localPrivateKey.sign(data));\n\t}\n\n\tgetMultiaddrs(): string[] {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\treturn this.node.getMultiaddrs().map((a) => a.toString());\n\t}\n\n\tasync announceCapability(hash: string): Promise<void> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\n\t\t// Buffer the capability for reactive re-announcement\n\t\tthis.announcedCapabilities.add(hash);\n\n\t\ttry {\n\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Announcing capability: ${hash} (CID: ${cid.toString()})`,\n\t\t\t);\n\n\t\t\t// In libp2p v1.x, contentRouting.provide returns Promise<void>\n\t\t\tawait this.node.contentRouting.provide(cid);\n\t\t\tlog.info(`[LIOP-Mesh] Successfully announced capability: ${hash}`);\n\n\t\t\t// [DEV-ONLY] Self-verification\n\t\t\tconst selfId = this.node.peerId.toString();\n\t\t\tfor await (const peer of this.node.contentRouting.findProviders(cid)) {\n\t\t\t\tif (peer.id.toString() === selfId) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Self-verification success: Node is providing ${hash}`,\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlog.error(`[LIOP-Mesh] Failed to announce capability: ${error}`);\n\t\t}\n\t}\n\n\tasync findProviders(hash: string): Promise<string[]> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\tconst providers: string[] = [];\n\t\ttry {\n\t\t\tconst cid = await this.capabilityToCID(hash);\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Querying DHT for ${hash} (CID: ${cid.toString()})...`,\n\t\t\t);\n\n\t\t\tlet foundAny = false;\n\n\t\t\t// Phase 103: Adaptive Tail-Wait Polling for DHT Discovery\n\t\t\tconst connections = this.node.getConnections?.()?.length || 0;\n\t\t\tconst idleTimeoutMs = connections > 1 ? 1500 : 3000;\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Starting DHT search with intelligent idle-timeout of ${idleTimeoutMs}ms (Active connections: ${connections})`,\n\t\t\t);\n\n\t\t\t// We manually iterate the AsyncIterable to abort it via Promise.race\n\t\t\tconst iterator = this.node.contentRouting\n\t\t\t\t.findProviders(cid)\n\t\t\t\t[Symbol.asyncIterator]();\n\t\t\tlet isDone = false;\n\n\t\t\twhile (!isDone) {\n\t\t\t\tconst nextPromise = iterator.next();\n\t\t\t\tconst timeoutPromise = new Promise<{ timeout: true }>((resolve) =>\n\t\t\t\t\tsetTimeout(() => resolve({ timeout: true }), idleTimeoutMs),\n\t\t\t\t);\n\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await Promise.race([nextPromise, timeoutPromise]);\n\n\t\t\t\t\tif (result && typeof result === \"object\" && \"timeout\" in result) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Mesh] DHT discovery idle-timeout reached. Stopping search early.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (typeof iterator.return === \"function\") {\n\t\t\t\t\t\t\t// Fire-and-forget: Kademlia iterators can block for 30s on return()\n\t\t\t\t\t\t\titerator.return().catch(() => {});\n\t\t\t\t\t\t}\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: polymorphic Kademlia peer result\n\t\t\t\t\tconst itResult = result as IteratorResult<any>;\n\t\t\t\t\tif (itResult.done) {\n\t\t\t\t\t\tisDone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tfoundAny = true;\n\t\t\t\t\tconst peer = itResult.value;\n\t\t\t\t\tconst peerId = peer.id.toString();\n\t\t\t\t\tlog.info(`[LIOP-Mesh] Found provider: ${peerId}`);\n\t\t\t\t\tif (!providers.includes(peerId)) {\n\t\t\t\t\t\tproviders.push(peerId);\n\t\t\t\t\t}\n\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t`[LIOP-Mesh] DHT iteration error: ${e instanceof Error ? e.message : String(e)}`,\n\t\t\t\t\t);\n\t\t\t\t\tisDone = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!foundAny) {\n\t\t\t\tconst services = this.node.services as {\n\t\t\t\t\tdht?: { routingTable?: { size: number } };\n\t\t\t\t};\n\t\t\t\tconst dhtSize = services.dht?.routingTable?.size || 0;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Mesh] DHT search for ${hash} returned zero results (routing table size: ${dhtSize})`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// [DEVELOPER-EXPERIENCE] Local Loopback Discovery\n\t\t\t// If we are providing this capability, ensure we find ourselves even if DHT findProviders doesn't return us.\n\t\t\tif (this.announcedCapabilities.has(hash)) {\n\t\t\t\tconst selfId = this.node.peerId.toString();\n\t\t\t\tif (!providers.includes(selfId)) {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Including local node (${selfId}) in results for ${hash}`,\n\t\t\t\t\t);\n\t\t\t\t\tproviders.push(selfId);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Error finding providers for ${hash}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LIOP-Mesh] DHT search for ${hash} finished. Found ${providers.length} providers.`,\n\t\t);\n\t\treturn providers;\n\t}\n\n\tasync resolvePeer(peerIdStr: string): Promise<string[]> {\n\t\tif (!this.node) throw new Error(\"Mesh Node is not running\");\n\t\ttry {\n\t\t\t// Strategy 1: Check active connections for the peer's multiaddrs\n\t\t\tconst connections = this.node.getConnections();\n\t\t\tfor (const conn of connections) {\n\t\t\t\tif (conn.remotePeer.toString() === peerIdStr) {\n\t\t\t\t\tconst remoteAddr = conn.remoteAddr.toString();\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Resolved peer ${peerIdStr} via active connection: ${remoteAddr}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn [remoteAddr];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Strategy 2: Try peerStore (iterate all peers to avoid toMultihash conflict)\n\t\t\tconst allPeers = await this.node.peerStore.all();\n\t\t\tfor (const peer of allPeers) {\n\t\t\t\tif (peer.id.toString() === peerIdStr && peer.addresses.length > 0) {\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Internal libp2p addr type\n\t\t\t\t\tconst addrs = peer.addresses.map((a: any) => a.multiaddr.toString());\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Mesh] Resolved peer ${peerIdStr} via peerStore: ${addrs[0]}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn addrs;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlog.info(\n\t\t\t\t`[LIOP-Mesh] Peer ${peerIdStr} not found in connections or peerStore`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlog.info(`[LIOP-Mesh] Failed to resolve peer ${peerIdStr}: ${error}`);\n\t\t}\n\t\treturn [];\n\t}\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-RWRRBYG4.js"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var s=class r{static instance;level="info";constructor(){this.setLevelFromEnv();}static getInstance(){return r.instance||(r.instance=new r),r.instance}setLevelFromEnv(){let e=process.env.LIOP_LOG_LEVEL?.toLowerCase();e==="silent"||e==="error"||e==="warn"||e==="info"||e==="debug"?this.level=e:this.level="info";}setLevel(e){this.level=e;}shouldLog(e){let o={silent:0,error:1,warn:2,info:3,debug:4};return o[this.level]>=o[e]}formatMessage(e,o){return `[${new Date().toISOString()}] [${e}] ${o}`}error(e,...o){this.shouldLog("error")&&console.error(this.formatMessage("ERROR",e),...o);}warn(e,...o){this.shouldLog("warn")&&console.error(this.formatMessage("WARN",e),...o);}info(e,...o){this.shouldLog("info")&&console.error(this.formatMessage("INFO",e),...o);}debug(e,...o){this.shouldLog("debug")&&console.error(this.formatMessage("DEBUG",e),...o);}},l=s.getInstance();export{l as a};//# sourceMappingURL=chunk-S6RJHZV2.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-S6RJHZV2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/logger.ts"],"names":["LiopLogger","_LiopLogger","envLevel","level","targetLevel","levels","message","args","log"],"mappings":"AAOO,IAAMA,EAAN,MAAMC,CAAW,CACvB,OAAe,QAAA,CACP,MAAkB,MAAA,CAElB,WAAA,EAAc,CACrB,IAAA,CAAK,eAAA,GACN,CAEA,OAAc,aAA0B,CACvC,OAAKA,EAAW,QAAA,GACfA,CAAAA,CAAW,QAAA,CAAW,IAAIA,GAEpBA,CAAAA,CAAW,QACnB,CAEQ,eAAA,EAAkB,CACz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MAAMD,CAAAA,CAAAA,GAAoBC,CAAAA,CAAiB,CAC7C,IAAA,CAAK,SAAA,CAAU,OAAO,CAAA,EACzB,OAAA,CAAQ,MAAM,IAAA,CAAK,aAAA,CAAc,QAASD,CAAO,CAAA,CAAG,GAAGC,CAAI,EAE7D,CACD,CAAA,CAEaC,CAAAA,CAAMR,EAAW,WAAA","file":"chunk-S6RJHZV2.js","sourcesContent":["export type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\n/**\n * LiopLogger - Structured Logging Abstraction\n * Configurable via `process.env.LIOP_LOG_LEVEL`.\n * Emits strictly to stderr to comply with MCP stdio protocols.\n */\nexport class LiopLogger {\n\tprivate static instance: LiopLogger;\n\tprivate level: LogLevel = \"info\";\n\n\tprivate constructor() {\n\t\tthis.setLevelFromEnv();\n\t}\n\n\tpublic static getInstance(): LiopLogger {\n\t\tif (!LiopLogger.instance) {\n\t\t\tLiopLogger.instance = new LiopLogger();\n\t\t}\n\t\treturn LiopLogger.instance;\n\t}\n\n\tprivate setLevelFromEnv() {\n\t\tconst envLevel = process.env.LIOP_LOG_LEVEL?.toLowerCase();\n\t\tif (\n\t\t\tenvLevel === \"silent\" ||\n\t\t\tenvLevel === \"error\" ||\n\t\t\tenvLevel === \"warn\" ||\n\t\t\tenvLevel === \"info\" ||\n\t\t\tenvLevel === \"debug\"\n\t\t) {\n\t\t\tthis.level = envLevel as LogLevel;\n\t\t} else {\n\t\t\t// Default level: info\n\t\t\tthis.level = \"info\";\n\t\t}\n\t}\n\n\tpublic setLevel(level: LogLevel) {\n\t\tthis.level = level;\n\t}\n\n\tprivate shouldLog(targetLevel: LogLevel): boolean {\n\t\tconst levels: Record<LogLevel, number> = {\n\t\t\tsilent: 0,\n\t\t\terror: 1,\n\t\t\twarn: 2,\n\t\t\tinfo: 3,\n\t\t\tdebug: 4,\n\t\t};\n\t\treturn levels[this.level] >= levels[targetLevel];\n\t}\n\n\tprivate formatMessage(level: string, message: string): string {\n\t\tconst ts = new Date().toISOString();\n\t\treturn `[${ts}] [${level}] ${message}`;\n\t}\n\n\tpublic error(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"error\")) {\n\t\t\tconsole.error(this.formatMessage(\"ERROR\", message), ...args);\n\t\t}\n\t}\n\n\tpublic warn(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"warn\")) {\n\t\t\tconsole.error(this.formatMessage(\"WARN\", message), ...args);\n\t\t}\n\t}\n\n\tpublic info(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"info\")) {\n\t\t\tconsole.error(this.formatMessage(\"INFO\", message), ...args);\n\t\t}\n\t}\n\n\tpublic debug(message: string, ...args: unknown[]) {\n\t\tif (this.shouldLog(\"debug\")) {\n\t\t\tconsole.error(this.formatMessage(\"DEBUG\", message), ...args);\n\t\t}\n\t}\n}\n\nexport const log = LiopLogger.getInstance();\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-ANFXJGMP.js';import {a}from'./chunk-S6RJHZV2.js';import*as u from'fs';import {createRequire}from'module';import s from'path';import {fileURLToPath,pathToFileURL}from'url';import {Piscina}from'piscina';var P=fileURLToPath(import.meta.url),m=s.dirname(P),c=class f{static zkWorkerPool=null;getZkPool(){if(!f.zkWorkerPool){let e=import.meta.url.endsWith(".ts"),i=e?".ts":".js",o=[];if(e)try{let p=createRequire(import.meta.url).resolve("tsx/package.json");o=["--import",pathToFileURL(s.join(s.dirname(p),"dist","loader.mjs")).href];}catch{o=["--import","tsx"];}let t=[s.resolve(m,`./workers/zk-verifier${i}`),s.resolve(m,`../workers/zk-verifier${i}`)],a=t.find(r=>u.existsSync(r))||t[1];f.zkWorkerPool=new Piscina({filename:a,minThreads:1,maxThreads:2,idleTimeout:3e4,execArgv:o});}return f.zkWorkerPool}async verifyZkReceipt(e,i,o,t){let a$1=this.getZkPool();if(!a$1)throw new Error("Worker pool initialization failed");let r=await a$1.run({action:"verify_receipt",logicPayload:new Uint8Array(e),remoteImageIdHex:i,zkReceipt:new Uint8Array(o),sessionSecret:t?new Uint8Array(t):void 0});return r.verified?(a.info(`[LiopVerifier] ${r.message}`),true):(a.error(`[LiopVerifier] FAILED: ${r.message}`),false)}async verifyTeeAttestation(e){if(e.length===0)return true;try{return a.info("[LiopVerifier] TEE Attestation: Not configured (no-op)."),!0}catch(i){return a.error("[LiopVerifier] TEE Verification Failed:",i),false}}deriveImageId(e){return b(e)}};export{c as a};//# sourceMappingURL=chunk-UVTEJYHN.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-UVTEJYHN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crypto/verifier.ts"],"names":["__filename","fileURLToPath","__dirname","path","LiopVerifier","_LiopVerifier","isTS","workerExt","execArgv","tsxPkg","createRequire","pathToFileURL","workerPaths","workerFilename","p","Piscina","logicPayload","remoteImageIdHex","zkReceipt","sessionSecret","pool","result","log","attestationReport","err","deriveLogicImageDigest"],"mappings":"gOAQA,IAAMA,CAAAA,CAAaC,aAAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CAC1CC,CAAAA,CAAYC,CAAAA,CAAK,OAAA,CAAQH,CAAU,CAAA,CAS5BI,CAAAA,CAAN,MAAMC,CAAa,CAEzB,OAAe,YAAA,CAA+B,IAAA,CAEtC,SAAA,EAAY,CACnB,GAAI,CAACA,CAAAA,CAAa,YAAA,CAAc,CAC/B,IAAMC,CAAAA,CAAO,MAAA,CAAA,IAAA,CAAY,GAAA,CAAI,QAAA,CAAS,KAAK,CAAA,CACrCC,CAAAA,CAAYD,CAAAA,CAAO,KAAA,CAAQ,KAAA,CAE7BE,CAAAA,CAAqB,EAAC,CAC1B,GAAIF,CAAAA,CACH,GAAI,CAEH,IAAMG,CAAAA,CADMC,aAAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAA,CACtB,OAAA,CAAQ,kBAAkB,CAAA,CAI7CF,CAAAA,CAAW,CAAC,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,UAAA,CAAWA,CAAa,CAAA,CAAI,MAChE,CAAC,CAAA,CAED,OAAIE,CAAAA,CAAO,QAAA,EACVC,CAAAA,CAAI,IAAA,CAAK,CAAA,eAAA,EAAkBD,CAAAA,CAAO,OAAO,CAAA,CAAE,CAAA,CACpC,IAAA,GAGRC,CAAAA,CAAI,KAAA,CAAM,CAAA,uBAAA,EAA0BD,CAAAA,CAAO,OAAO,CAAA,CAAE,CAAA,CAC7C,KAAA,CACR,CAOA,MAAa,oBAAA,CACZE,CAAAA,CACmB,CACnB,GAAIA,CAAAA,CAAkB,MAAA,GAAW,CAAA,CAAG,OAAO,KAAA,CAE3C,GAAI,CAKH,OAAAD,CAAAA,CAAI,IAAA,CAAK,yDAAyD,CAAA,CAC3D,CAAA,CACR,CAAA,MAASE,CAAAA,CAAK,CACb,OAAAF,CAAAA,CAAI,KAAA,CAAM,yCAAA,CAA2CE,CAAG,CAAA,CACjD,KACR,CACD,CAKO,aAAA,CAAcR,CAAAA,CAA8B,CAClD,OAAOS,CAAAA,CAAuBT,CAAY,CAC3C,CACD","file":"chunk-UVTEJYHN.js","sourcesContent":["import * as fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { Piscina } from \"piscina\";\nimport { log } from \"../utils/logger.js\";\nimport { deriveLogicImageDigest } from \"./logic-image-id.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n/**\n * LIOP Tier-0 Industrial Verifier\n *\n * This engine is responsible for the trustless verification of remote logic execution.\n * It validates both the integrity of the code (ZkImageID) and the mathematical proof\n * of its execution (ZkSeal), as well as hardware-level attestation (TEE).\n */\nexport class LiopVerifier {\n\t// Singleton Worker Pool for heavy ZK verification\n\tprivate static zkWorkerPool: Piscina | null = null;\n\n\tprivate getZkPool() {\n\t\tif (!LiopVerifier.zkWorkerPool) {\n\t\t\tconst isTS = import.meta.url.endsWith(\".ts\");\n\t\t\tconst workerExt = isTS ? \".ts\" : \".js\";\n\n\t\t\tlet execArgv: string[] = [];\n\t\t\tif (isTS) {\n\t\t\t\ttry {\n\t\t\t\t\tconst req = createRequire(import.meta.url);\n\t\t\t\t\tconst tsxPkg = req.resolve(\"tsx/package.json\");\n\t\t\t\t\tconst absoluteTsx = pathToFileURL(\n\t\t\t\t\t\tpath.join(path.dirname(tsxPkg), \"dist\", \"loader.mjs\"),\n\t\t\t\t\t).href;\n\t\t\t\t\texecArgv = [\"--import\", absoluteTsx];\n\t\t\t\t} catch (_e) {\n\t\t\t\t\texecArgv = [\"--import\", \"tsx\"];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Support both flat dist/ and original src/ structure\n\t\t\tconst workerPaths = [\n\t\t\t\tpath.resolve(__dirname, `./workers/zk-verifier${workerExt}`), // Flat dist/ (tsup)\n\t\t\t\tpath.resolve(__dirname, `../workers/zk-verifier${workerExt}`), // Original src/\n\t\t\t];\n\n\t\t\tconst workerFilename =\n\t\t\t\tworkerPaths.find((p) => fs.existsSync(p)) || workerPaths[1];\n\n\t\t\tLiopVerifier.zkWorkerPool = new Piscina({\n\t\t\t\tfilename: workerFilename,\n\t\t\t\tminThreads: 1,\n\t\t\t\tmaxThreads: 2, // Minimal footprint since verification is fast compared to generation\n\t\t\t\tidleTimeout: 30000,\n\t\t\t\texecArgv,\n\t\t\t});\n\t\t}\n\t\treturn LiopVerifier.zkWorkerPool;\n\t}\n\n\t/**\n\t * Verifies a Zero-Knowledge Receipt from a remote LIOP node via Worker Pool.\n\t *\n\t * @param logicPayload The raw WASM or JS logic that was sent to the provider.\n\t * @param remoteImageIdHex The ImageID reported by the provider (must match our local calculation).\n\t * @param zkReceipt The mathematical proof (Seal + Journal) from the zkVM.\n\t */\n\tpublic async verifyZkReceipt(\n\t\tlogicPayload: Buffer,\n\t\tremoteImageIdHex: string,\n\t\tzkReceipt: Buffer,\n\t\tsessionSecret?: Buffer,\n\t): Promise<boolean> {\n\t\tconst pool = this.getZkPool();\n\t\tif (!pool) throw new Error(\"Worker pool initialization failed\");\n\t\tconst result = await pool.run({\n\t\t\taction: \"verify_receipt\",\n\t\t\tlogicPayload: new Uint8Array(logicPayload),\n\t\t\tremoteImageIdHex,\n\t\t\tzkReceipt: new Uint8Array(zkReceipt),\n\t\t\tsessionSecret: sessionSecret ? new Uint8Array(sessionSecret) : undefined,\n\t\t});\n\n\t\tif (result.verified) {\n\t\t\tlog.info(`[LiopVerifier] ${result.message}`);\n\t\t\treturn true;\n\t\t}\n\n\t\tlog.error(`[LiopVerifier] FAILED: ${result.message}`);\n\t\treturn false;\n\t}\n\n\t/**\n\t * Verifies if a node is running inside an authenticated TEE (e.g. AWS Nitro).\n\t *\n\t * @param attestationReport The COSE-signed attestation document from the hardware.\n\t */\n\tpublic async verifyTeeAttestation(\n\t\tattestationReport: Buffer,\n\t): Promise<boolean> {\n\t\tif (attestationReport.length === 0) return true; // Optional in Mesh Alpha\n\n\t\ttry {\n\t\t\t// Architecture for AWS Nitro Enclaves:\n\t\t\t// 1. Decode CBOR/COSE\n\t\t\t// 2. Verify Signature against AWS Nitro Root CA\n\t\t\t// 3. Compare PCRs\n\t\t\tlog.info(\"[LiopVerifier] TEE Attestation: Not configured (no-op).\");\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tlog.error(\"[LiopVerifier] TEE Verification Failed:\", err);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Derives the ImageID of a logic payload following the LIOP v1 Standard.\n\t */\n\tpublic deriveImageId(logicPayload: Buffer): Buffer {\n\t\treturn deriveLogicImageDigest(logicPayload);\n\t}\n}\n"]}
|
package/dist/client.d.ts
ADDED
package/dist/client.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{b as LiopClient}from'./chunk-P52IE4L6.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';import'./chunk-PPCOS2NU.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=client.js.map
|
|
2
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"client.js"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
1
|
+
import { MeshNode } from './mesh.js';
|
|
2
|
+
import { LiopServer } from './server.js';
|
|
3
|
+
import { L as LiopVerifier } from './verifier-DTCD9imJ.js';
|
|
4
|
+
import { McpRequest, McpResponse } from './types.js';
|
|
5
|
+
import 'zod';
|
|
6
|
+
|
|
5
7
|
/**
|
|
6
8
|
* LIOP MCP Router
|
|
7
9
|
*
|
|
@@ -11,7 +13,7 @@ import type { McpRequest, McpResponse } from "../types.js";
|
|
|
11
13
|
* All tool discovery and port resolution is DYNAMIC via the
|
|
12
14
|
* /liop/manifest/1.0.0 protocol stream over Kademlia DHT.
|
|
13
15
|
*/
|
|
14
|
-
|
|
16
|
+
declare class LiopMcpRouter {
|
|
15
17
|
private liopServer;
|
|
16
18
|
private meshNode;
|
|
17
19
|
private defaultRpcPort;
|
|
@@ -74,3 +76,26 @@ export declare class LiopMcpRouter {
|
|
|
74
76
|
private performTranscoding;
|
|
75
77
|
private encryptWithNonce;
|
|
76
78
|
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* LIOP Hybrid Gateway
|
|
82
|
+
* High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.
|
|
83
|
+
*/
|
|
84
|
+
declare class LiopHybridGateway {
|
|
85
|
+
private liopServer;
|
|
86
|
+
private meshNode;
|
|
87
|
+
private netServer;
|
|
88
|
+
private h2Server;
|
|
89
|
+
private h1Server;
|
|
90
|
+
private router;
|
|
91
|
+
constructor(liopServer: LiopServer, meshNode?: MeshNode | null, rpcPort?: number);
|
|
92
|
+
private setupH2Routes;
|
|
93
|
+
private setupH1Routes;
|
|
94
|
+
private handleGrpcStream;
|
|
95
|
+
private handleMcpH2Stream;
|
|
96
|
+
listen(port: number, host?: string): Promise<number>;
|
|
97
|
+
stop(): Promise<void>;
|
|
98
|
+
getRouter(): LiopMcpRouter;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export { LiopHybridGateway };
|
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{a as LiopHybridGateway}from'./chunk-JBMEAXYU.js';import'./chunk-7MAGL6ON.js';import'./chunk-UVTEJYHN.js';import'./chunk-ANFXJGMP.js';import'./chunk-DBXGYHKY.js';import'./chunk-HM77MWB6.js';import'./chunk-S6RJHZV2.js';//# sourceMappingURL=gateway.js.map
|
|
2
|
+
//# sourceMappingURL=gateway.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"gateway.js"}
|
|
@@ -1,12 +1,29 @@
|
|
|
1
|
-
import { LiopVerifier } from
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
|
|
1
|
+
import { L as LiopVerifier } from './verifier-DTCD9imJ.js';
|
|
2
|
+
import { MeshNodeConfig } from './mesh.js';
|
|
3
|
+
import { CallToolRequest, CallToolResult } from './types.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* LIOP TLS Configuration
|
|
7
|
+
*
|
|
8
|
+
* Provides conditional TLS credential factories for gRPC connections.
|
|
9
|
+
* When TLS options are provided, connections are secured with mutual TLS.
|
|
10
|
+
* Otherwise, falls back to insecure credentials (alpha/development mode).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
interface LiopTlsOptions {
|
|
14
|
+
/** Path to the root CA certificate (PEM format) */
|
|
15
|
+
rootCert?: string;
|
|
16
|
+
/** Path to the server/client certificate (PEM format) */
|
|
17
|
+
certChain?: string;
|
|
18
|
+
/** Path to the private key (PEM format) */
|
|
19
|
+
privateKey?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
5
22
|
/**
|
|
6
23
|
* LIOP Client
|
|
7
24
|
* High-level orchestration for discovery and execution in the Logic-Injection-on-Origin mesh.
|
|
8
25
|
*/
|
|
9
|
-
|
|
26
|
+
declare class LiopClient {
|
|
10
27
|
private meshNode;
|
|
11
28
|
private rpcClients;
|
|
12
29
|
private manifests;
|
|
@@ -58,3 +75,5 @@ export declare class LiopClient {
|
|
|
58
75
|
*/
|
|
59
76
|
close(): Promise<void>;
|
|
60
77
|
}
|
|
78
|
+
|
|
79
|
+
export { type LiopTlsOptions as L, LiopClient as a };
|