@nekzus/liop 2.0.0-beta.1 → 2.0.0-beta.2
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 +10 -0
- package/dist/bin/agent.js +3 -3
- package/dist/bin/agent.js.map +1 -1
- package/dist/bridge.js +1 -1
- package/dist/chunk-2MGFSIXN.js +2 -0
- package/dist/chunk-2MGFSIXN.js.map +1 -0
- package/dist/chunk-4C666HHU.js +2 -0
- package/dist/chunk-4C666HHU.js.map +1 -0
- package/dist/{chunk-PPCOS2NU.js → chunk-7I6YJS3C.js} +2 -2
- package/dist/{chunk-PPCOS2NU.js.map → chunk-7I6YJS3C.js.map} +1 -1
- package/dist/{chunk-HNDVAKEK.js → chunk-C65RM2A3.js} +6 -6
- package/dist/chunk-C65RM2A3.js.map +1 -0
- package/dist/{chunk-P52IE4L6.js → chunk-ISKM7EAL.js} +2 -2
- package/dist/{chunk-P52IE4L6.js.map → chunk-ISKM7EAL.js.map} +1 -1
- package/dist/{chunk-62YQHKSS.js → chunk-NWZ5KZDN.js} +3 -3
- package/dist/chunk-NWZ5KZDN.js.map +1 -0
- package/dist/{chunk-JBMEAXYU.js → chunk-SYMZRXI3.js} +3 -3
- package/dist/{chunk-JBMEAXYU.js.map → chunk-SYMZRXI3.js.map} +1 -1
- package/dist/chunk-TNMS53OP.js +2 -0
- package/dist/chunk-TNMS53OP.js.map +1 -0
- package/dist/chunk-UK7OBXGZ.js +33 -0
- package/dist/chunk-UK7OBXGZ.js.map +1 -0
- package/dist/chunk-V5MKJT6S.js +2 -0
- package/dist/chunk-V5MKJT6S.js.map +1 -0
- package/dist/chunk-WG353XMU.js +43 -0
- package/dist/chunk-WG353XMU.js.map +1 -0
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/gateway.js +1 -1
- package/dist/{index-CyxNLlz7.d.ts → index-BihN3W-K.d.ts} +9 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/kyber-NONMBQNH.js +2 -0
- package/dist/{kyber-2WDOTUQX.js.map → kyber-NONMBQNH.js.map} +1 -1
- package/dist/mesh.js +1 -1
- package/dist/server.js +1 -1
- package/dist/types.js +1 -1
- package/dist/verifier-6M7GY4TW.js +2 -0
- package/dist/{verifier-RQRYXA4C.js.map → verifier-6M7GY4TW.js.map} +1 -1
- package/dist/workers/logic-execution.js +1 -1
- package/dist/workers/logic-execution.js.map +1 -1
- package/dist/workers/zk-verifier.js +1 -1
- package/dist/workers/zk-verifier.js.map +1 -1
- package/package.json +48 -45
- package/dist/chunk-5OAZNVIU.js +0 -31
- package/dist/chunk-5OAZNVIU.js.map +0 -1
- package/dist/chunk-62YQHKSS.js.map +0 -1
- package/dist/chunk-7MAGL6ON.js +0 -33
- package/dist/chunk-7MAGL6ON.js.map +0 -1
- package/dist/chunk-HM77MWB6.js +0 -2
- package/dist/chunk-HM77MWB6.js.map +0 -1
- package/dist/chunk-HNDVAKEK.js.map +0 -1
- package/dist/chunk-HQZHZM6U.js +0 -2
- package/dist/chunk-HQZHZM6U.js.map +0 -1
- package/dist/kyber-2WDOTUQX.js +0 -2
- package/dist/verifier-RQRYXA4C.js +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/rpc/client.ts","../src/rpc/crypto/aes.ts","../src/client/index.ts"],"names":["LiopRpcClient","address","tls","credentials","createChannelCredentials","liopV1","request","resolve","reject","error","response","AesGcmWrapper","payload","sharedSecret","nonce","randomBytes","cipher","createCipheriv","encrypted","authTag","ciphertextBuffer","encryptedData","decipher","createDecipheriv","LiopClient","LiopVerifier","options","MeshNode","log","toolName","providers","providerId","grpcPort","manifest","addrs","maddr","parts","grpcHost","providerIds","tools","seenNames","peerId","tool","err","_wasmPayload","rpcClient","dynamicAddress","agentDid","intentPayload","proofOfIntent","intentResponse","publicKey","sessionToken","kyberCiphertext","Kyber768Wrapper","_safePayload","encryptedWasm","aesNonce","encryptedInputs","crypto","key","value","inputNonce","logicRequest","stream","resultFulfilled","hasReceivedData","client","uri","resourceDef","r"],"mappings":"mRAcO,IAAMA,CAAAA,CAAN,KAAoB,CAElB,MAAA,CAER,WAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAsB,CAClD,IAAMC,CAAAA,CAAcC,CAAAA,CAAyBF,CAAG,CAAA,CAChD,IAAA,CAAK,MAAA,CAAS,IAAIG,CAAAA,CAAO,SAAA,CAAUJ,CAAAA,CAASE,CAAW,EACxD,CAMA,MAAa,eAAA,CACZG,CAAAA,CAC0B,CAC1B,OAAO,IAAI,QAAQ,CAACC,CAAAA,CAASC,CAAAA,GAAW,CACvC,IAAA,CAAK,MAAA,CAAO,eAAA,CACXF,CAAAA,CACA,CAACG,CAAAA,CAAiCC,CAAAA,GAA6B,CAC1DD,CAAAA,CACHD,CAAAA,CAAOC,CAAK,CAAA,CAEZF,CAAAA,CAAQG,CAAQ,EAElB,CACD,EACD,CAAC,CACF,CAMO,YAAA,CACNJ,CAAAA,CAC2C,CAC3C,OAAO,IAAA,CAAK,MAAA,CAAO,YAAA,CAAaA,CAAO,CACxC,CAEO,KAAA,EAAc,CACpB,IAAA,CAAK,MAAA,CAAO,KAAA,GACb,CACD,EClDO,IAAMK,CAAAA,CAAgB,CAQ5B,cAAA,CACCC,CAAAA,CACAC,CAAAA,CAIC,CACD,GAAIA,CAAAA,CAAa,MAAA,GAAW,EAAA,CAC3B,MAAM,IAAI,KAAA,CAAM,oDAAoD,EAIrE,IAAMC,CAAAA,CAAQC,WAAAA,CAAY,EAAE,CAAA,CAEtBC,CAAAA,CAASC,cAAAA,CAAe,aAAA,CAAeJ,CAAAA,CAAcC,CAAK,CAAA,CAG1DI,CAAAA,CAAY,MAAA,CAAO,MAAA,CAAO,CAACF,CAAAA,CAAO,MAAA,CAAOJ,CAAO,CAAA,CAAGI,CAAAA,CAAO,KAAA,EAAO,CAAC,CAAA,CAClEG,CAAAA,CAAUH,CAAAA,CAAO,UAAA,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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"]}
|
|
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,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,QAAA,CAAS,aAAA,CAAcH,CAAAA,CAAU,CAAC,CAAC,CAAA,CAC/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-ISKM7EAL.js","sourcesContent":["import type * as grpc from \"@grpc/grpc-js\";\nimport { liopV1 } from \"./proto.js\";\nimport { createChannelCredentials, type LiopTlsOptions } from \"./tls.js\";\nimport type {\n\tIntentRequest,\n\tIntentResponse,\n\tLogicRequest,\n\tLogicResponse,\n} from \"./types.js\";\n\n/**\n * LIOP gRPC Client Implementation\n * Provides a high-level interface for secure intent negotiation and logic execution.\n */\nexport class LiopRpcClient {\n\t// biome-ignore lint/suspicious/noExplicitAny: internal gRPC client type\n\tprivate client: any;\n\n\tconstructor(address: string, tls?: LiopTlsOptions) {\n\t\tconst credentials = createChannelCredentials(tls);\n\t\tthis.client = new liopV1.LogicMesh(address, credentials);\n\t}\n\n\t/**\n\t * Negotiates intent with the remote host.\n\t * Returns the ephemeral Kyber public key for payload encryption.\n\t */\n\tpublic async negotiateIntent(\n\t\trequest: IntentRequest,\n\t): Promise<IntentResponse> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.client.NegotiateIntent(\n\t\t\t\trequest,\n\t\t\t\t(error: grpc.ServiceError | null, response: IntentResponse) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tresolve(response);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Pushes the encrypted Logic-on-Origin payload to the origin.\n\t * Returns a stream of semantic responses and ZK proofs.\n\t */\n\tpublic executeLogic(\n\t\trequest: LogicRequest,\n\t): grpc.ClientReadableStream<LogicResponse> {\n\t\treturn this.client.ExecuteLogic(request);\n\t}\n\n\tpublic close(): void {\n\t\tthis.client.close();\n\t}\n}\n","import { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\n\n/**\n * LIOP Symmetric Payload Encryption Wrapper\n * Uses AES-256-GCM to secure WASM Code transport over Zero-Trust networks.\n * Fully compatible with the `aes-gcm` Rust crate used by Wasmtime.\n */\nexport const AesGcmWrapper = {\n\t/**\n\t * Encrypts a raw WASM payload using the shared secret negotiated via Kyber768.\n\t *\n\t * @param payload Raw incoming WASM byte array or string.\n\t * @param sharedSecret A perfectly derived 32-byte (256-bit) shared secret array\n\t * @returns The encrypted buffer to push to the GRPc stream, along with the 12-byte initialization vector natively generated.\n\t */\n\tencryptPayload(\n\t\tpayload: Uint8Array | Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): {\n\t\tciphertext: Buffer;\n\t\tnonce: Buffer;\n\t} {\n\t\tif (sharedSecret.length !== 32) {\n\t\t\tthrow new Error(\"Symmetric Key must be exactly 32 bytes (256 bits).\");\n\t\t}\n\n\t\t// LIOP standard demands 96-bit (12 byte) IVs/Nonces for AES-GCM\n\t\tconst nonce = randomBytes(12);\n\n\t\tconst cipher = createCipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\n\t\t// Encrypt the payload and seal the tag\n\t\tconst encrypted = Buffer.concat([cipher.update(payload), cipher.final()]);\n\t\tconst authTag = cipher.getAuthTag(); // 16 bytes for GCM integrity\n\n\t\t// In LIOP, the auth tag is strictly appended to the end of the ciphertext bytes\n\t\t// mirroring the default serialization logic within `aes_gcm::Aes256Gcm` in Rust\n\t\tconst finalCiphertext = Buffer.concat([encrypted, authTag]);\n\n\t\treturn {\n\t\t\tciphertext: finalCiphertext,\n\t\t\tnonce: nonce,\n\t\t};\n\t},\n\n\t/**\n\t * Decrypts a remote Zero-Knowledge receipt using AES-256-GCM.\n\t */\n\tdecryptPayload(\n\t\tciphertextBuffer: Buffer,\n\t\tnonce: Buffer,\n\t\tsharedSecret: Uint8Array,\n\t): Buffer {\n\t\tif (ciphertextBuffer.length < 16) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Invalid GCM Ciphertext; missing authentication tag length\",\n\t\t\t);\n\t\t}\n\n\t\t// The last 16 bytes represent the AuthTag appended by rust-aes-gcm\n\t\tconst encryptedData = ciphertextBuffer.subarray(0, -16);\n\t\tconst authTag = ciphertextBuffer.subarray(-16);\n\n\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", sharedSecret, nonce);\n\t\tdecipher.setAuthTag(authTag);\n\n\t\treturn Buffer.concat([decipher.update(encryptedData), decipher.final()]);\n\t},\n};\n","import { LiopVerifier } from \"../crypto/verifier.js\";\nimport {\n\ttype LiopManifest,\n\tMeshNode,\n\ttype MeshNodeConfig,\n} from \"../mesh/node.js\";\nimport { LiopRpcClient } from \"../rpc/client.js\";\nimport { AesGcmWrapper } from \"../rpc/crypto/aes.js\";\nimport { Kyber768Wrapper } from \"../rpc/crypto/kyber.js\";\nimport type { LiopTlsOptions } from \"../rpc/tls.js\";\nimport type { LogicRequest, LogicResponse } from \"../rpc/types.js\";\nimport type { CallToolRequest, CallToolResult } from \"../types.js\";\nimport { log } from \"../utils/logger.js\";\n\n/**\n * LIOP Client\n * High-level orchestration for discovery and execution in the Logic-Injection-on-Origin mesh.\n */\nexport class LiopClient {\n\tprivate meshNode: MeshNode | null = null;\n\tprivate rpcClients: Map<string, LiopRpcClient> = new Map();\n\tprivate manifests: Map<string, LiopManifest> = new Map();\n\tprivate tlsOptions?: LiopTlsOptions;\n\tprivate serverInfo?: { name: string; version: string };\n\tpublic verifier: LiopVerifier = new LiopVerifier();\n\n\tconstructor(tls?: LiopTlsOptions) {\n\t\tthis.tlsOptions = tls;\n\t}\n\n\t/**\n\t * Discovers and connects to the target server or mesh capability.\n\t * If address is omitted, it sets up the MeshNode to act purely dynamically.\n\t */\n\tpublic async connect(\n\t\taddress?: string,\n\t\toptions?: { meshConfig?: MeshNodeConfig },\n\t): Promise<void> {\n\t\tthis.meshNode = new MeshNode(options?.meshConfig);\n\t\tawait this.meshNode.start();\n\t\tlog.info(\n\t\t\t`[LiopClient] Mesh Node synchronized. PeerID: ${this.meshNode.getPeerId()}`,\n\t\t);\n\n\t\tif (address) {\n\t\t\tthis.rpcClients.set(\n\t\t\t\t\"static\",\n\t\t\t\tnew LiopRpcClient(address, this.tlsOptions),\n\t\t\t);\n\t\t\tthis.serverInfo = { name: `LiopServer (${address})`, version: \"1.0.0\" };\n\t\t\tlog.info(`[LiopClient] Static gRPC configured for: ${address}`);\n\t\t} else {\n\t\t\tthis.serverInfo = { name: \"LiopServer (Mesh Alpha)\", version: \"1.0.0\" };\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically queries Kademlia DHT to find the optimal PeerID providing the Capability\n\t * and returns the physical gRPC target (host:port) resolved from the provider's manifest.\n\t */\n\tpublic async resolveCapability(toolName: string): Promise<string> {\n\t\tif (!this.meshNode)\n\t\t\tthrow new Error(\n\t\t\t\t\"Client must be connected to Mesh to resolve capabilities.\",\n\t\t\t);\n\n\t\tlog.info(`[LiopClient] Querying Mesh DHT for Provider: ${toolName}...`);\n\t\tconst providers = await this.meshNode.findProviders(toolName);\n\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`Kademlia DHT found zero providers for capability: ${toolName}`,\n\t\t\t);\n\t\t}\n\n\t\tconst providerId = providers[0];\n\t\tlog.info(`[LiopClient] Identified Alpha Provider PeerID: ${providerId}`);\n\n\t\tlet grpcPort = 50051;\n\t\tconst manifest = await this.meshNode.queryManifest(providerId);\n\t\tif (manifest) {\n\t\t\tgrpcPort = manifest.grpcPort;\n\t\t\tlog.info(`[LiopClient] Manifest resolved: gRPC port ${grpcPort}`);\n\t\t}\n\n\t\tconst addrs = await this.meshNode.resolvePeer(providerId);\n\t\tfor (const maddr of addrs) {\n\t\t\tconst parts = maddr.split(\"/\");\n\t\t\tif (parts[1] === \"ip4\") {\n\t\t\t\tconst grpcHost = `${parts[2]}:${grpcPort}`;\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Translated Multiaddr to gRPC Target: ${grpcHost}`,\n\t\t\t\t);\n\t\t\t\treturn grpcHost;\n\t\t\t}\n\t\t}\n\n\t\treturn `127.0.0.1:${grpcPort}`;\n\t}\n\n\t/**\n\t * Discovers remote capabilities via the LIOP Manifest Protocol.\n\t */\n\tpublic async discoverTools(): Promise<\n\t\t{ name: string; description?: string }[]\n\t> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before discovering tools.\");\n\t\t}\n\n\t\tlog.info(`[LiopClient] Discovery started...`);\n\t\tconst providerIds = await this.meshNode.discoverManifestProviders();\n\t\tconst tools: { name: string; description?: string }[] = [];\n\t\tconst seenNames = new Set<string>();\n\n\t\tfor (const peerId of providerIds) {\n\t\t\ttry {\n\t\t\t\tlog.info(`[LiopClient] Querying manifest from: ${peerId}`);\n\t\t\t\tconst manifest = await this.meshNode.queryManifest(peerId);\n\t\t\t\tif (manifest) {\n\t\t\t\t\tthis.manifests.set(peerId, manifest);\n\t\t\t\t\tfor (const tool of manifest.tools) {\n\t\t\t\t\t\tif (!seenNames.has(tool.name)) {\n\t\t\t\t\t\t\ttools.push({ name: tool.name, description: tool.description });\n\t\t\t\t\t\t\tseenNames.add(tool.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (err: unknown) {\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LiopClient] Error querying manifest from ${peerId}:`,\n\t\t\t\t\terr instanceof Error ? err.message : String(err),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tlog.info(\n\t\t\t`[LiopClient] Discovery finished. Found ${tools.length} unique tools.`,\n\t\t);\n\t\treturn tools;\n\t}\n\n\t/**\n\t * Invokes a tool.\n\t */\n\tpublic async callTool(\n\t\trequest: CallToolRequest,\n\t\t_wasmPayload?: Buffer,\n\t): Promise<CallToolResult> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before calling tools.\");\n\t\t}\n\n\t\tconst toolName = request.name;\n\t\tlog.info(`[LiopClient] Resolving Tool: ${toolName}`);\n\n\t\t// [ALPHA-FIX] Bypass DHT discovery if we are already statically connected to a provider (Enterprise/Test mode)\n\t\tlet rpcClient = this.rpcClients.get(\"static\");\n\n\t\tif (!rpcClient) {\n\t\t\tconst dynamicAddress = await this.resolveCapability(toolName);\n\t\t\trpcClient = this.getOrCreateRpcClient(toolName, dynamicAddress);\n\t\t} else {\n\t\t\tlog.info(\n\t\t\t\t`[LiopClient] Using existing static gRPC connection for ${toolName}.`,\n\t\t\t);\n\t\t}\n\n\t\tlog.info(`[LiopClient] Negotiating intent for ${toolName}...`);\n\t\tconst agentDid = this.meshNode\n\t\t\t? `did:liop:${this.meshNode.getPeerId()}`\n\t\t\t: \"did:liop:ephemeral\";\n\t\tconst intentPayload = Buffer.from(`${toolName}:${Date.now()}`);\n\t\tconst proofOfIntent = this.meshNode\n\t\t\t? await this.meshNode.sign(intentPayload)\n\t\t\t: intentPayload;\n\n\t\tconst intentResponse = (await rpcClient.negotiateIntent({\n\t\t\tagent_did: agentDid,\n\t\t\tcapability_hash: toolName,\n\t\t\tproof_of_intent: proofOfIntent,\n\t\t})) as unknown as {\n\t\t\taccepted: boolean;\n\t\t\terror_message: string;\n\t\t\tkyber_public_key: Uint8Array;\n\t\t\tkyberPublicKey: Uint8Array;\n\t\t\tsession_token: string;\n\t\t\tsessionToken: string;\n\t\t};\n\n\t\tif (!intentResponse.accepted) {\n\t\t\tthrow new Error(`Intent denied by host: ${intentResponse.error_message}`);\n\t\t}\n\n\t\t// LIOP Robust Field Extraction (Supports both snake_case and camelCase via gRPC-JS)\n\t\tconst publicKey =\n\t\t\tintentResponse.kyber_public_key || intentResponse.kyberPublicKey;\n\t\tconst sessionToken =\n\t\t\tintentResponse.session_token || intentResponse.sessionToken;\n\n\t\tif (!publicKey) {\n\t\t\tlog.info(\n\t\t\t\t\"[LiopClient] Critical Error: Kyber Public Key not found in IntentResponse.\",\n\t\t\t\tintentResponse,\n\t\t\t);\n\t\t\tthrow new Error(\n\t\t\t\t\"Handshake failed: Remote host did not provide a valid Kyber Public Key.\",\n\t\t\t);\n\t\t}\n\n\t\t// 2. Post-Quantum Encapsulation (ML-KEM-768)\n\t\tlog.info(\n\t\t\t`[LiopClient] Encapsulating Post-Quantum Shared Secret for ${request.name}...`,\n\t\t);\n\t\tconst { ciphertext: kyberCiphertext, sharedSecret } =\n\t\t\tawait Kyber768Wrapper.encapsulateAsymmetric(publicKey);\n\n\t\t// 3. Symmetric Sealing (AES-256-GCM)\n\t\tlog.info(`[LiopClient] Sealing WASM Payload and Inputs...`);\n\n\t\tconst _safePayload = _wasmPayload || Buffer.from(\"\");\n\n\t\t// Encrypt WASM binary\n\t\tconst { ciphertext: encryptedWasm, nonce: aesNonce } =\n\t\t\tAesGcmWrapper.encryptPayload(_safePayload, sharedSecret);\n\n\t\t// Encrypt inputs using a fresh random nonce per input to prevent AES-GCM nonce reuse\n\t\tconst encryptedInputs: Record<string, Uint8Array> = {};\n\t\tconst crypto = await import(\"node:crypto\");\n\t\tfor (const [key, value] of Object.entries(request.arguments || {})) {\n\t\t\tconst inputNonce = crypto.randomBytes(12);\n\t\t\tconst cipher = crypto.createCipheriv(\n\t\t\t\t\"aes-256-gcm\",\n\t\t\t\tsharedSecret,\n\t\t\t\tinputNonce,\n\t\t\t);\n\t\t\tconst encrypted = Buffer.concat([\n\t\t\t\tcipher.update(JSON.stringify(value)),\n\t\t\t\tcipher.final(),\n\t\t\t]);\n\t\t\tconst authTag = cipher.getAuthTag();\n\t\t\t// Prepend the 12-byte nonce to the ciphertext\n\t\t\tencryptedInputs[key] = Buffer.concat([inputNonce, encrypted, authTag]);\n\t\t}\n\n\t\t// 4. Assemble and Execute gRPC LogicRequest\n\t\tconst logicRequest: LogicRequest = {\n\t\t\tsession_token: sessionToken,\n\t\t\twasm_binary: encryptedWasm,\n\t\t\tinputs: encryptedInputs,\n\t\t\tpqc_ciphertext: kyberCiphertext,\n\t\t\taes_nonce: aesNonce,\n\t\t};\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst stream = rpcClient.executeLogic(logicRequest);\n\t\t\tif (!stream) {\n\t\t\t\treject(new Error(\"RPC Client unavailable or failed to create stream.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet resultFulfilled = false;\n\t\t\tlet hasReceivedData = false;\n\n\t\t\tstream.on(\"data\", async (response: LogicResponse) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\thasReceivedData = true;\n\n\t\t\t\tlog.info(\"[LiopClient] Logic Executed. Verification in progress...\");\n\n\t\t\t\ttry {\n\t\t\t\t\t// Only verify ZK-Receipt if the remote execution succeeded.\n\t\t\t\t\t// If the remote execution failed due to a policy error (e.g. Egress Shield),\n\t\t\t\t\t// the ZK proof is empty and we should bypass validation to propagate the original error.\n\t\t\t\t\tif (!response.is_error) {\n\t\t\t\t\t\tconst isValid = await this.verifier.verifyZkReceipt(\n\t\t\t\t\t\t\t_safePayload,\n\t\t\t\t\t\t\tBuffer.from(response.cryptographic_proof).toString(\"hex\"),\n\t\t\t\t\t\t\tBuffer.from(response.zk_receipt),\n\t\t\t\t\t\t\tBuffer.from(sharedSecret),\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!isValid) {\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t\t\t\"PROTOCOL INTEGRITY VIOLATION: ZK-Receipt verification failed.\",\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresultFulfilled = true;\n\t\t\t\t\tresolve({\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: response.semantic_evidence,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tisError: response.is_error,\n\t\t\t\t\t});\n\t\t\t\t} catch (err) {\n\t\t\t\t\treject(err);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstream.on(\"error\", (err) => {\n\t\t\t\tif (resultFulfilled) return;\n\t\t\t\tlog.error(\"[LiopClient] Stream Error:\", err);\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tstream.on(\"end\", () => {\n\t\t\t\t// We don't throw here if we already received a response block that is currently\n\t\t\t\t// undergoing ZK Verification in the Piscina worker pool.\n\t\t\t\tif (!hasReceivedData && !resultFulfilled) {\n\t\t\t\t\treject(new Error(\"Logic-on-Origin stream closed without results.\"));\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate getOrCreateRpcClient(peerId: string, address: string): LiopRpcClient {\n\t\tlet client = this.rpcClients.get(peerId);\n\t\tif (!client) {\n\t\t\tclient = new LiopRpcClient(address, this.tlsOptions);\n\t\t\tthis.rpcClients.set(peerId, client);\n\t\t}\n\t\treturn client;\n\t}\n\n\t/**\n\t * Reads a specific resource by URI.\n\t * In LIOP, resources can be static definitions or dynamic streams.\n\t */\n\tpublic async readResource(uri: string): Promise<{\n\t\tcontents: Array<{ uri: string; mimeType?: string; text: string }>;\n\t}> {\n\t\tif (!this.meshNode) {\n\t\t\tthrow new Error(\"Client must be connected before reading resources.\");\n\t\t}\n\t\tlog.info(`[LiopClient] Querying Mesh for Resource: ${uri}...`);\n\n\t\t// We search for the peer hosting the resource in the P2P Mesh\n\t\tconst providers = await this.meshNode.findProviders(uri);\n\t\tif (providers.length === 0) {\n\t\t\tthrow new Error(`No mesh providers found for resource: ${uri}`);\n\t\t}\n\n\t\t// Query the remote peer's manifest\n\t\tconst manifest = await this.meshNode.queryManifest(providers[0]);\n\t\tif (!manifest) {\n\t\t\tthrow new Error(\"Target peer did not return a valid LIOP Manifest.\");\n\t\t}\n\n\t\t// Locate the exact resource metadata\n\t\tconst resourceDef = manifest.resources?.find((r) => r.uri === uri);\n\t\tif (!resourceDef) {\n\t\t\tthrow new Error(`Resource ${uri} not listed in remote manifest.`);\n\t\t}\n\n\t\t// Return the declarative metadata (Logic-Injection is required for actual data extraction)\n\t\treturn {\n\t\t\tcontents: [\n\t\t\t\t{\n\t\t\t\t\turi,\n\t\t\t\t\tmimeType: resourceDef.mimeType || \"application/json\",\n\t\t\t\t\ttext: JSON.stringify(resourceDef, null, 2),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\tpublic getServerInfo(): { name: string; version: string } | undefined {\n\t\treturn this.serverInfo;\n\t}\n\n\t/**\n\t * Destroys the active Mesh Node resources.\n\t */\n\tpublic async close(): Promise<void> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t}\n}\n"]}
|
|
@@ -1,3 +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-
|
|
2
|
-
`);}catch(i){a.error(`[LIOP-Bridge] Error: ${i.message}`);}});}};export{f as a,p as b};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
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 (i.isError?!0: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-6M7GY4TW.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-NWZ5KZDN.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-NWZ5KZDN.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,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C,EAAI,KAAA,CAAM,CAAA,qBAAA,EAAyBkC,CAAAA,CAAY,OAAO,CAAA,CAAE,EACzD,CACD,CAAC,EACF,CACD","file":"chunk-NWZ5KZDN.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\t// If the tool execution returned an error (e.g. policy violation), we bypass\n\t\t\t\t// ZK-Receipt verification because no cryptographic proof is generated for errors.\n\t\t\t\tconst isVerified = result.isError\n\t\t\t\t\t? true\n\t\t\t\t\t: 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"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {g}from'./chunk-
|
|
1
|
+
import {g}from'./chunk-UK7OBXGZ.js';import {a}from'./chunk-S6RJHZV2.js';import*as d from'http';import*as c from'http2';import*as l from'net';var h=class{constructor(e,r=null,o=50051){this.liopServer=e;this.meshNode=r;this.router=new g(this.liopServer,this.meshNode,o),this.h2Server=c.createServer(),this.setupH2Routes(),this.h1Server=d.createServer(),this.setupH1Routes(),this.netServer=l.createServer(t=>{t.once("data",n=>{let s=n.toString().startsWith("PRI * HTTP/2.0");a.info(`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${s?"HTTP/2 (gRPC)":"HTTP/1.1 (MCP)"}`),s?this.h2Server.emit("connection",t):this.h1Server.emit("connection",t),t.unshift(n);}),t.on("error",n=>a.error(`[LIOP-Gateway] NetServer Socket Error: ${n.message}`));}),this.h1Server.on("error",t=>a.error(`[LIOP-Gateway] H1 Server Error: ${t.message}`)),this.h2Server.on("error",t=>a.error(`[LIOP-Gateway] H2 Server Error: ${t.message}`)),a.info("[LIOP-Gateway] Hybrid adapter initialized.");}netServer;h2Server;h1Server;router;setupH2Routes(){this.h2Server.on("stream",(e,r)=>{let o=r["content-type"],t=r[":path"];o==="application/grpc"?this.handleGrpcStream(e):t==="/mcp"&&this.handleMcpH2Stream(e,r);});}setupH1Routes(){this.h1Server.on("request",async(e,r)=>{let o=e.url||"",t=e.method;if(t==="GET"&&(o==="/"||o==="/mcp"||o==="/health")){if(o==="/health"&&e.headers.accept?.includes("application/json")){let n=this.meshNode?{peerId:this.meshNode.getPeerId()?.toString()||"",multiaddrs:this.meshNode.getMultiaddrs().map(s=>s.toString())}:null;r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({status:"healthy",node:this.liopServer.getServerInfo(),mesh:n,tools:this.liopServer.listTools().map(s=>s.name),timestamp:new Date().toISOString()}));return}r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
|
|
2
2
|
<body style="background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0">
|
|
3
3
|
<div style="background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)">
|
|
4
4
|
<h1 style="color:#38bdf8;margin-top:0">LIOP Protocol Transformer</h1>
|
|
@@ -9,5 +9,5 @@ import {g}from'./chunk-7MAGL6ON.js';import {a}from'./chunk-S6RJHZV2.js';import*a
|
|
|
9
9
|
</div>
|
|
10
10
|
</div>
|
|
11
11
|
</body>
|
|
12
|
-
`);return}if(o==="/mcp"&&t==="POST"){let n="";e.on("data",s=>n+=s.toString()),e.on("end",async()=>{try{let s=JSON.parse(n),a=await this.router.dispatch(s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify(a));}catch(s){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${s.message}`),r.writeHead(400),r.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else r.writeHead(404),r.end("Not Found");});}handleGrpcStream(e){e.on("data",r=>{let o=r;o&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${o.length} bytes`);}),e.respond({":status":200,"content-type":"application/grpc"}),e.end();}handleMcpH2Stream(e,r){let o="";e.on("data",t=>o+=t.toString()),e.on("end",async()=>{try{let t=await this.router.dispatch(JSON.parse(o));t?(e.respond({":status":200,"content-type":"application/json"}),e.end(JSON.stringify(t))):e.close();}catch{e.respond({":status":400}),e.end();}});}async listen(e,r="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let o=this.liopServer.listTools();for(let t of o)await this.meshNode.announceCapability(t.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${t.name}`);}return new Promise((o,t)=>{this.netServer.on("error",n=>{n.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${e} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${n.message}`),t(n);}),this.netServer.listen(e,r,()=>{let n=this.netServer.address(),s=typeof n=="string"?n:n?.address||r,a$1=typeof n=="string"?e:n?.port||e;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${s}:${a$1}`),o(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{h as a};//# sourceMappingURL=chunk-
|
|
13
|
-
//# sourceMappingURL=chunk-
|
|
12
|
+
`);return}if(o==="/mcp"&&t==="POST"){let n="";e.on("data",s=>n+=s.toString()),e.on("end",async()=>{try{let s=JSON.parse(n),a=await this.router.dispatch(s);r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify(a));}catch(s){a.info(`[LIOP-Gateway] Error processing JSON-RPC payload: ${s.message}`),r.writeHead(400),r.end(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"}}));}});}else r.writeHead(404),r.end("Not Found");});}handleGrpcStream(e){e.on("data",r=>{let o=r;o&&a.info(`[LIOP-Gateway] Native gRPC Proxy passing ${o.length} bytes`);}),e.respond({":status":200,"content-type":"application/grpc"}),e.end();}handleMcpH2Stream(e,r){let o="";e.on("data",t=>o+=t.toString()),e.on("end",async()=>{try{let t=await this.router.dispatch(JSON.parse(o));t?(e.respond({":status":200,"content-type":"application/json"}),e.end(JSON.stringify(t))):e.close();}catch{e.respond({":status":400}),e.end();}});}async listen(e,r="0.0.0.0"){if(this.meshNode){await this.meshNode.start();let o=this.liopServer.listTools();for(let t of o)await this.meshNode.announceCapability(t.name),a.info(`[LIOP-Gateway] \u{1F4E1} Announced local tool to Mesh: ${t.name}`);}return new Promise((o,t)=>{this.netServer.on("error",n=>{n.code==="EADDRINUSE"?a.info(`[LIOP-Gateway] FATAL: Port ${e} is already in use by another process.`):a.error(`[LIOP-Gateway] Binding Error: ${n.message}`),t(n);}),this.netServer.listen(e,r,()=>{let n=this.netServer.address(),s=typeof n=="string"?n:n?.address||r,a$1=typeof n=="string"?e:n?.port||e;a.info(`[LIOP-Gateway] \u2705 Transformer Mesh Gateway READY and listening on ${s}:${a$1}`),o(a$1);});})}async stop(){this.meshNode&&await this.meshNode.stop(),this.netServer.close(),this.h2Server.close(),this.h1Server.close();}getRouter(){return this.router}};export{h as a};//# sourceMappingURL=chunk-SYMZRXI3.js.map
|
|
13
|
+
//# sourceMappingURL=chunk-SYMZRXI3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/gateway/hybrid.ts"],"names":["LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","meshInfo","m","t","body","chunk","jsonRequest","response","e","data","_headers","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"6IAYO,IAAMA,CAAAA,CAAN,KAAwB,CAM9B,WAAA,CACSC,EACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EAIR,IAAA,CAAK,MAAA,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CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-JBMEAXYU.js","sourcesContent":["import * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC ↔ gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\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} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\t_headers: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body));\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/gateway/hybrid.ts"],"names":["LiopHybridGateway","liopServer","meshNode","rpcPort","LiopMcpRouter","socket","buffer","isHttp2","log","err","stream","headers","contentType","path","req","res","url","method","meshInfo","m","t","body","chunk","jsonRequest","response","e","data","_headers","port","host","tools","tool","resolve","reject","addr","actualHost","assignedPort"],"mappings":"6IAYO,IAAMA,CAAAA,CAAN,KAAwB,CAM9B,WAAA,CACSC,EACAC,CAAAA,CAA4B,IAAA,CACpCC,CAAAA,CAAkB,KAAA,CACjB,CAHO,IAAA,CAAA,UAAA,CAAAF,CAAAA,CACA,IAAA,CAAA,QAAA,CAAAC,EAIR,IAAA,CAAK,MAAA,CAAS,IAAIE,CAAAA,CAAc,KAAK,UAAA,CAAY,IAAA,CAAK,QAAA,CAAUD,CAAO,EAGvE,IAAA,CAAK,QAAA,CAAiB,CAAA,CAAA,YAAA,EAAa,CACnC,IAAA,CAAK,aAAA,EAAc,CAGnB,IAAA,CAAK,SAAgB,CAAA,CAAA,YAAA,EAAa,CAClC,IAAA,CAAK,aAAA,EAAc,CAGnB,IAAA,CAAK,SAAA,CAAgB,CAAA,CAAA,YAAA,CAAcE,GAAW,CAC7CA,CAAAA,CAAO,IAAA,CAAK,MAAA,CAASC,CAAAA,EAAW,CAC/B,IAAMC,CAAAA,CAAUD,EAAO,QAAA,EAAS,CAAE,UAAA,CAAW,gBAAgB,EAC7DE,CAAAA,CAAI,IAAA,CACH,CAAA,iDAAA,EAAoDD,CAAAA,CAAU,gBAAkB,gBAAgB,CAAA,CACjG,CAAA,CACIA,CAAAA,CACH,IAAA,CAAK,QAAA,CAAS,IAAA,CAAK,YAAA,CAAcF,CAAM,CAAA,CAEvC,IAAA,CAAK,QAAA,CAAS,IAAA,CAAK,YAAA,CAAcA,CAAM,CAAA,CAExCA,CAAAA,CAAO,QAAQC,CAAM,EACtB,CAAC,CAAA,CACDD,CAAAA,CAAO,EAAA,CAAG,OAAA,CAAUI,CAAAA,EACnBD,EAAI,KAAA,CAAM,CAAA,uCAAA,EAA0CC,CAAAA,CAA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A,EAAM,MAAQN,CAAAA,CAEjDpB,CAAAA,CAAI,IAAA,CACH,CAAA,sEAAA,EAAoE2B,CAAU,CAAA,CAAA,EAAIC,GAAY,EAC/F,CAAA,CACAJ,CAAAA,CAAQI,GAAY,EACrB,CAAC,EACF,CAAC,CACF,CAEA,MAAa,MAAO,CACf,IAAA,CAAK,UACR,MAAM,IAAA,CAAK,QAAA,CAAS,IAAA,GAErB,IAAA,CAAK,SAAA,CAAU,OAAM,CACrB,IAAA,CAAK,SAAS,KAAA,EAAM,CACpB,KAAK,QAAA,CAAS,KAAA,GACf,CAEO,SAAA,EAA2B,CACjC,OAAO,IAAA,CAAK,MACb,CACD","file":"chunk-SYMZRXI3.js","sourcesContent":["import * as http from \"node:http\";\nimport * as http2 from \"node:http2\";\nimport * as net from \"node:net\";\nimport type { MeshNode } from \"../mesh/index.js\";\nimport type { LiopServer } from \"../server/index.js\";\nimport { log } from \"../utils/logger.js\";\nimport { LiopMcpRouter } from \"./router.js\";\n\n/**\n * LIOP Hybrid Gateway\n * High-level orchestration for connecting MCP (JSON-RPC) clients to the LIOP Mesh.\n */\nexport class LiopHybridGateway {\n\tprivate netServer: net.Server;\n\tprivate h2Server: http2.Http2Server;\n\tprivate h1Server: http.Server;\n\tprivate router: LiopMcpRouter;\n\n\tconstructor(\n\t\tprivate liopServer: LiopServer,\n\t\tprivate meshNode: MeshNode | null = null,\n\t\trpcPort: number = 50051,\n\t) {\n\t\t// Initialize the Universal Router\n\t\tthis.router = new LiopMcpRouter(this.liopServer, this.meshNode, rpcPort);\n\n\t\t// Internal HTTP/2 Server (for Native gRPC Proxying)\n\t\tthis.h2Server = http2.createServer();\n\t\tthis.setupH2Routes();\n\n\t\t// Internal HTTP/1 Server (for Browser/MCP)\n\t\tthis.h1Server = http.createServer();\n\t\tthis.setupH1Routes();\n\n\t\t// Primary Multiplexer (L4)\n\t\tthis.netServer = net.createServer((socket) => {\n\t\t\tsocket.once(\"data\", (buffer) => {\n\t\t\t\tconst isHttp2 = buffer.toString().startsWith(\"PRI * HTTP/2.0\");\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Incoming L4 Connection. Protocol: ${isHttp2 ? \"HTTP/2 (gRPC)\" : \"HTTP/1.1 (MCP)\"}`,\n\t\t\t\t);\n\t\t\t\tif (isHttp2) {\n\t\t\t\t\tthis.h2Server.emit(\"connection\", socket);\n\t\t\t\t} else {\n\t\t\t\t\tthis.h1Server.emit(\"connection\", socket);\n\t\t\t\t}\n\t\t\t\tsocket.unshift(buffer);\n\t\t\t});\n\t\t\tsocket.on(\"error\", (err) =>\n\t\t\t\tlog.error(`[LIOP-Gateway] NetServer Socket Error: ${err.message}`),\n\t\t\t);\n\t\t});\n\n\t\t// Attach error listeners to sub-servers to catch silent failures\n\t\tthis.h1Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H1 Server Error: ${err.message}`),\n\t\t);\n\t\tthis.h2Server.on(\"error\", (err) =>\n\t\t\tlog.error(`[LIOP-Gateway] H2 Server Error: ${err.message}`),\n\t\t);\n\n\t\tlog.info(\"[LIOP-Gateway] Hybrid adapter initialized.\");\n\t}\n\n\tprivate setupH2Routes() {\n\t\tthis.h2Server.on(\"stream\", (stream, headers) => {\n\t\t\tconst contentType = headers[\"content-type\"] as string;\n\t\t\tconst path = headers[\":path\"] as string;\n\n\t\t\tif (contentType === \"application/grpc\") {\n\t\t\t\tthis.handleGrpcStream(stream as http2.ServerHttp2Stream);\n\t\t\t} else if (path === \"/mcp\") {\n\t\t\t\tthis.handleMcpH2Stream(stream as http2.ServerHttp2Stream, headers);\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate setupH1Routes() {\n\t\tthis.h1Server.on(\"request\", async (req, res) => {\n\t\t\tconst url = req.url || \"\";\n\t\t\tconst method = req.method;\n\n\t\t\tif (\n\t\t\t\tmethod === \"GET\" &&\n\t\t\t\t(url === \"/\" || url === \"/mcp\" || url === \"/health\")\n\t\t\t) {\n\t\t\t\tif (\n\t\t\t\t\turl === \"/health\" &&\n\t\t\t\t\treq.headers.accept?.includes(\"application/json\")\n\t\t\t\t) {\n\t\t\t\t\tconst meshInfo = this.meshNode\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tpeerId: this.meshNode.getPeerId()?.toString() || \"\",\n\t\t\t\t\t\t\t\tmultiaddrs: this.meshNode\n\t\t\t\t\t\t\t\t\t.getMultiaddrs()\n\t\t\t\t\t\t\t\t\t.map((m) => m.toString()),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: null;\n\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\tres.end(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tstatus: \"healthy\",\n\t\t\t\t\t\t\tnode: this.liopServer.getServerInfo(),\n\t\t\t\t\t\t\tmesh: meshInfo,\n\t\t\t\t\t\t\ttools: this.liopServer.listTools().map((t) => t.name),\n\t\t\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(`\n <body style=\"background:#0f172a;color:#f8fafc;font-family:sans-serif;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;margin:0\">\n <div style=\"background:#1e293b;padding:40px;border-radius:16px;border:1px solid #38bdf8;text-align:center;box-shadow:0 20px 25px -5px rgba(0,0,0,0.1)\">\n <h1 style=\"color:#38bdf8;margin-top:0\">LIOP Protocol Transformer</h1>\n <p style=\"opacity:0.8;font-weight:600\">L4/L7 Transcoding: JSON-RPC ↔ gRPC</p>\n <p style=\"opacity:0.6;font-size:14px\">Active Protections: Kyber768 + AES-256-GCM + ZK-Proof Ready</p>\n <div style=\"background:#0f172a;padding:15px;border-radius:8px;margin-top:20px;border:1px dashed #334155\">\n <code style=\"color:#10b981\">Endpoint: http://localhost:3000/mcp</code>\n </div>\n </div>\n </body>\n `);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (url === \"/mcp\" && method === \"POST\") {\n\t\t\t\tlet body = \"\";\n\t\t\t\treq.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\t\t\treq.on(\"end\", async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst jsonRequest = JSON.parse(body);\n\t\t\t\t\t\tconst response = await this.router.dispatch(jsonRequest);\n\t\t\t\t\t\tres.writeHead(200, { \"Content-Type\": \"application/json\" });\n\t\t\t\t\t\tres.end(JSON.stringify(response));\n\t\t\t\t\t} catch (e: unknown) {\n\t\t\t\t\t\tlog.info(\n\t\t\t\t\t\t\t`[LIOP-Gateway] Error processing JSON-RPC payload: ${(e as Error).message}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tres.writeHead(400);\n\t\t\t\t\t\tres.end(\n\t\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\t\tjsonrpc: \"2.0\",\n\t\t\t\t\t\t\t\terror: { code: -32700, message: \"Parse error\" },\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} else {\n\t\t\t\tres.writeHead(404);\n\t\t\t\tres.end(\"Not Found\");\n\t\t\t}\n\t\t});\n\t}\n\n\tprivate handleGrpcStream(stream: http2.ServerHttp2Stream) {\n\t\tstream.on(\"data\", (chunk: unknown) => {\n\t\t\t// biome-ignore lint/suspicious/noExplicitAny: Standard gRPC stream data is Buffer\n\t\t\tconst data = chunk as any;\n\t\t\tif (data)\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] Native gRPC Proxy passing ${data.length} bytes`,\n\t\t\t\t);\n\t\t});\n\t\tstream.respond({ \":status\": 200, \"content-type\": \"application/grpc\" });\n\t\tstream.end();\n\t}\n\n\tprivate handleMcpH2Stream(\n\t\tstream: http2.ServerHttp2Stream,\n\t\t_headers: http2.IncomingHttpHeaders,\n\t) {\n\t\tlet body = \"\";\n\t\tstream.on(\"data\", (chunk) => (body += chunk.toString()));\n\t\tstream.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tconst response = await this.router.dispatch(JSON.parse(body));\n\t\t\t\tif (response) {\n\t\t\t\t\tstream.respond({\n\t\t\t\t\t\t\":status\": 200,\n\t\t\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\t});\n\t\t\t\t\tstream.end(JSON.stringify(response));\n\t\t\t\t} else stream.close();\n\t\t\t} catch (_e) {\n\t\t\t\tstream.respond({ \":status\": 400 });\n\t\t\t\tstream.end();\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic async listen(port: number, host: string = \"0.0.0.0\"): Promise<number> {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.start();\n\n\t\t\t// Announce all local tools to the DHT\n\t\t\tconst tools = this.liopServer.listTools();\n\t\t\tfor (const tool of tools) {\n\t\t\t\tawait this.meshNode.announceCapability(tool.name);\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] 📡 Announced local tool to Mesh: ${tool.name}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.netServer.on(\"error\", (err: Error & { code?: string }) => {\n\t\t\t\tif (err.code === \"EADDRINUSE\") {\n\t\t\t\t\tlog.info(\n\t\t\t\t\t\t`[LIOP-Gateway] FATAL: Port ${port} is already in use by another process.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlog.error(`[LIOP-Gateway] Binding Error: ${err.message}`);\n\t\t\t\t}\n\t\t\t\treject(err);\n\t\t\t});\n\n\t\t\tthis.netServer.listen(port, host, () => {\n\t\t\t\tconst addr = this.netServer.address();\n\t\t\t\tconst actualHost =\n\t\t\t\t\ttypeof addr === \"string\" ? addr : addr?.address || host;\n\t\t\t\tconst assignedPort =\n\t\t\t\t\ttypeof addr === \"string\" ? port : addr?.port || port;\n\n\t\t\t\tlog.info(\n\t\t\t\t\t`[LIOP-Gateway] ✅ Transformer Mesh Gateway READY and listening on ${actualHost}:${assignedPort}`,\n\t\t\t\t);\n\t\t\t\tresolve(assignedPort);\n\t\t\t});\n\t\t});\n\t}\n\n\tpublic async stop() {\n\t\tif (this.meshNode) {\n\t\t\tawait this.meshNode.stop();\n\t\t}\n\t\tthis.netServer.close();\n\t\tthis.h2Server.close();\n\t\tthis.h1Server.close();\n\t}\n\n\tpublic getRouter(): LiopMcpRouter {\n\t\treturn this.router;\n\t}\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-2MGFSIXN.js';var o=b.object({name:b.string(),description:b.string().optional(),inputSchema:b.record(b.string(),b.unknown())}),i=b.object({uri:b.string(),name:b.string(),description:b.string().optional(),mimeType:b.string().optional()}),s=b.object({name:b.string(),description:b.string().optional(),arguments:b.array(b.object({name:b.string(),description:b.string().optional(),required:b.boolean().optional()})).optional()});export{o as a,i as b,s as c};//# sourceMappingURL=chunk-TNMS53OP.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-TNMS53OP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"names":["ToolSchema","external_exports","ResourceSchema","PromptSchema"],"mappings":"oCAMO,IAAMA,CAAAA,CAAaC,EAAE,MAAA,CAAO,CAClC,KAAMA,CAAAA,CAAE,MAAA,GACR,WAAA,CAAaA,CAAAA,CAAE,QAAO,CAAE,QAAA,GACxB,WAAA,CAAaA,CAAAA,CAAE,OAAOA,CAAAA,CAAE,MAAA,GAAUA,CAAAA,CAAE,OAAA,EAAS,CAC9C,CAAC,EAIYC,CAAAA,CAAiBD,CAAAA,CAAE,OAAO,CACtC,GAAA,CAAKA,EAAE,MAAA,EAAO,CACd,KAAMA,CAAAA,CAAE,MAAA,GACR,WAAA,CAAaA,CAAAA,CAAE,QAAO,CAAE,QAAA,GACxB,QAAA,CAAUA,CAAAA,CAAE,QAAO,CAAE,QAAA,EACtB,CAAC,CAAA,CAIYE,EAAeF,CAAAA,CAAE,MAAA,CAAO,CACpC,IAAA,CAAMA,CAAAA,CAAE,QAAO,CACf,WAAA,CAAaA,EAAE,MAAA,EAAO,CAAE,UAAS,CACjC,SAAA,CAAWA,EACT,KAAA,CACAA,CAAAA,CAAE,OAAO,CACR,IAAA,CAAMA,EAAE,MAAA,EAAO,CACf,YAAaA,CAAAA,CAAE,MAAA,GAAS,QAAA,EAAS,CACjC,SAAUA,CAAAA,CAAE,OAAA,GAAU,QAAA,EACvB,CAAC,CACF,CAAA,CACC,QAAA,EACH,CAAC","file":"chunk-TNMS53OP.js","sourcesContent":["import { z } from \"zod\";\n\n/**\n * Base Protocol Types representing parity with Model Context Protocol\n */\n\nexport const ToolSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tinputSchema: z.record(z.string(), z.unknown()), // Represents a JSON Schema\n});\n\nexport type Tool = z.infer<typeof ToolSchema>;\n\nexport const ResourceSchema = z.object({\n\turi: z.string(),\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\tmimeType: z.string().optional(),\n});\n\nexport type Resource = z.infer<typeof ResourceSchema>;\n\nexport const PromptSchema = z.object({\n\tname: z.string(),\n\tdescription: z.string().optional(),\n\targuments: z\n\t\t.array(\n\t\t\tz.object({\n\t\t\t\tname: z.string(),\n\t\t\t\tdescription: z.string().optional(),\n\t\t\t\trequired: z.boolean().optional(),\n\t\t\t}),\n\t\t)\n\t\t.optional(),\n});\n\nexport type Prompt = z.infer<typeof PromptSchema>;\n\nexport interface CallToolRequest {\n\tname: string;\n\targuments?: Record<string, unknown>;\n}\n\nexport interface CallToolResult {\n\tcontent: Array<{\n\t\ttype: \"text\" | \"image\" | \"resource\";\n\t\ttext?: string;\n\t\tdata?: string;\n\t\tmimeType?: string;\n\t\tresource?: {\n\t\t\turi: string;\n\t\t\ttext?: string;\n\t\t\tblob?: string;\n\t\t};\n\t}>;\n\tisError?: boolean;\n}\n\nexport interface GetPromptRequest {\n\tname: string;\n\targuments?: Record<string, string>;\n}\n\nexport interface GetPromptResult {\n\tdescription?: string;\n\tmessages: Array<{\n\t\trole: \"user\" | \"assistant\";\n\t\tcontent:\n\t\t\t| { type: \"text\"; text: string }\n\t\t\t| { type: \"image\"; data: string; mimeType: string }\n\t\t\t| {\n\t\t\t\t\ttype: \"resource\";\n\t\t\t\t\tresource: { uri: string; text?: string; blob?: string };\n\t\t\t };\n\t}>;\n}\n\nexport interface ServerInfo {\n\tname: string;\n\tversion: string;\n\tcapabilities?: {\n\t\tprompts?: { listChanged?: boolean };\n\t\tresources?: { subscribe?: boolean; listChanged?: boolean };\n\t\ttools?: { listChanged?: boolean };\n\t\tlogging?: Record<string, unknown>;\n\t};\n}\n\nexport interface McpRequest {\n\tmethod: string;\n\tparams?: unknown;\n\tid?: string | number | null;\n\tjsonrpc?: \"2.0\";\n}\n\nexport interface McpResponse {\n\tjsonrpc: \"2.0\";\n\tid?: string | number | null;\n\tresult?: unknown;\n\terror?: {\n\t\tcode: number;\n\t\tmessage: string;\n\t\tdata?: unknown;\n\t};\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-UVTEJYHN.js';import {a as a$3}from'./chunk-DBXGYHKY.js';import {a as a$2,c}from'./chunk-V5MKJT6S.js';import {a}from'./chunk-S6RJHZV2.js';import*as G from'crypto';var H=class{name="o200k_base";countFn;constructor(e,t){this.countFn=e,t&&t(1e4);}countTokens(e){return e.length===0?0:this.countFn(e)}},B=class{name="heuristic (chars/4)";countTokens(e){return e.length===0?0:Math.ceil(e.length/4)}};async function le(){try{let i=await import('gpt-tokenizer'),e=new H(i.countTokens,i.setMergeCacheSize);return a.debug("[LIOP-Economy] Token estimator initialized: o200k_base"),e}catch{return a.info("[LIOP-Economy] gpt-tokenizer unavailable, falling back to heuristic estimator"),new B}}function ue(){return new B}var b="1.9.1";var pe=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function ye(i){let e=new Set([i]),t=new Set,r=i.match(pe);if(!r)return ()=>false;let s={major:+r[1],minor:+r[2],patch:+r[3],prerelease:r[4]};if(s.prerelease!=null)return function(a){return a===i};function o(c){return t.add(c),false}function n(c){return e.add(c),true}return function(a){if(e.has(a))return true;if(t.has(a))return false;let l=a.match(pe);if(!l)return o(a);let m={major:+l[1],minor:+l[2],patch:+l[3],prerelease:l[4]};return m.prerelease!=null||s.major!==m.major?o(a):s.major===0?s.minor===m.minor&&s.patch<=m.patch?n(a):o(a):s.minor<=m.minor?n(a):o(a)}}var me=ye(b);var ve=b.split(".")[0],L=Symbol.for(`opentelemetry.js.api.${ve}`),x=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};function j(i,e,t,r=false){var s;let o=x[L]=(s=x[L])!==null&&s!==void 0?s:{version:b};if(!r&&o[i]){let n=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${i}`);return t.error(n.stack||n.message),false}if(o.version!==b){let n=new Error(`@opentelemetry/api: Registration of version v${o.version} for ${i} does not match previously registered API v${b}`);return t.error(n.stack||n.message),false}return o[i]=e,t.debug(`@opentelemetry/api: Registered a global for ${i} v${b}.`),true}function N(i){var e,t;let r=(e=x[L])===null||e===void 0?void 0:e.version;if(!(!r||!me(r)))return (t=x[L])===null||t===void 0?void 0:t[i]}function U(i,e){e.debug(`@opentelemetry/api: Unregistering a global for ${i} v${b}.`);let t=x[L];t&&delete t[i];}var F=class{constructor(e){this._namespace=e.namespace||"DiagComponentLogger";}debug(...e){return $("debug",this._namespace,e)}error(...e){return $("error",this._namespace,e)}info(...e){return $("info",this._namespace,e)}warn(...e){return $("warn",this._namespace,e)}verbose(...e){return $("verbose",this._namespace,e)}};function $(i,e,t){let r=N("diag");if(r)return r[i](e,...t)}var _;(function(i){i[i.NONE=0]="NONE",i[i.ERROR=30]="ERROR",i[i.WARN=50]="WARN",i[i.INFO=60]="INFO",i[i.DEBUG=70]="DEBUG",i[i.VERBOSE=80]="VERBOSE",i[i.ALL=9999]="ALL";})(_||(_={}));function de(i,e){i<_.NONE?i=_.NONE:i>_.ALL&&(i=_.ALL),e=e||{};function t(r,s){let o=e[r];return typeof o=="function"&&i>=s?o.bind(e):function(){}}return {error:t("error",_.ERROR),warn:t("warn",_.WARN),info:t("info",_.INFO),debug:t("debug",_.DEBUG),verbose:t("verbose",_.VERBOSE)}}var Oe="diag",A=class i{static instance(){return this._instance||(this._instance=new i),this._instance}constructor(){function e(s){return function(...o){let n=N("diag");if(n)return n[s](...o)}}let t=this,r=(s,o={logLevel:_.INFO})=>{var n,c,a;if(s===t){let f=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((n=f.stack)!==null&&n!==void 0?n:f.message),false}typeof o=="number"&&(o={logLevel:o});let l=N("diag"),m=de((c=o.logLevel)!==null&&c!==void 0?c:_.INFO,s);if(l&&!o.suppressOverrideMessage){let f=(a=new Error().stack)!==null&&a!==void 0?a:"<failed to generate stacktrace>";l.warn(`Current logger will be overwritten from ${f}`),m.warn(`Current logger will overwrite one already registered from ${f}`);}return j("diag",m,t,true)};t.setLogger=r,t.disable=()=>{U(Oe,t);},t.createComponentLogger=s=>new F(s),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error");}};var W=class{constructor(){}createGauge(e,t){return Ie}createHistogram(e,t){return Se}createCounter(e,t){return _e}createUpDownCounter(e,t){return Pe}createObservableGauge(e,t){return ke}createObservableCounter(e,t){return Ee}createObservableUpDownCounter(e,t){return be}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},M=class{},J=class extends M{add(e,t){}},q=class extends M{add(e,t){}},K=class extends M{record(e,t){}},Q=class extends M{record(e,t){}},D=class{addCallback(e){}removeCallback(e){}},X=class extends D{},Y=class extends D{},Z=class extends D{},fe=new W,_e=new J,Ie=new K,Se=new Q,Pe=new q,Ee=new X,ke=new Y,be=new Z;var ee=class{getMeter(e,t,r){return fe}},he=new ee;var te="metrics",V=class i{constructor(){}static getInstance(){return this._instance||(this._instance=new i),this._instance}setGlobalMeterProvider(e){return j(te,e,A.instance())}getMeterProvider(){return N(te)||he}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){U(te,A.instance());}};var oe=V.getInstance();var Re="@nekzus/liop",Ne="1.2.0-alpha.9",we=[1,4,16,64,256,1024,4096,16384,65536,262144,1048576,4194304,16777216,67108864],Me=[.01,.02,.04,.08,.16,.32,.64,1.28,2.56,5.12,10.24,20.48,40.96,81.92],z=class{tokenUsage;operationDuration;active=false;constructor(){try{let e=oe.getMeter(Re,Ne);this.tokenUsage=e.createHistogram("gen_ai.client.token.usage",{description:"Number of tokens used in LIOP Logic-on-Origin operations",unit:"{token}",advice:{explicitBucketBoundaries:we}}),this.operationDuration=e.createHistogram("gen_ai.client.operation.duration",{description:"Duration of LIOP operations",unit:"s",advice:{explicitBucketBoundaries:Me}}),this.active=!0,a.debug("[LIOP-OTel] gen_ai.* metrics bridge initialized");}catch(e){a.debug(`[LIOP-OTel] Bridge disabled: ${e instanceof Error?e.message:String(e)}`);let t={record:()=>{}};this.tokenUsage=t,this.operationDuration=t;}}recordTokens(e,t,r,s){this.tokenUsage.record(e,{"gen_ai.system":"liop","gen_ai.operation.name":r,"gen_ai.token.type":t,"gen_ai.request.model":"liop-mesh",...s?{"liop.tool.name":s}:{}});}recordDuration(e,t,r){this.operationDuration.record(e/1e3,{"gen_ai.system":"liop","gen_ai.operation.name":t,...r?{"error.type":r}:{}});}isActive(){return this.active}};var Ce={tools_list:"chat",tool_call:"execute_tool",resource_read:"chat",resource_list:"chat",prompt_get:"chat",prompt_list:"chat",diagnostic:"chat"},S=class i{static instance=null;operations=[];sessionId;startedAt;estimator;otelBridge;constructor(){this.sessionId=crypto.randomUUID(),this.startedAt=Date.now(),this.estimator=ue(),this.otelBridge=new z,this.initRealEstimator();}initRealEstimator(){le().then(e=>{this.estimator=e;}).catch(()=>{});}static getInstance(){return i.instance||(i.instance=new i),i.instance}countTokens(e){try{return this.estimator.countTokens(e)}catch{return Math.ceil(e.length/4)}}record(e){let t={...e,timestamp:Date.now()};this.operations.push(t);try{let r=Ce[e.type]||"chat";e.estimatedInputTokens>0&&this.otelBridge.recordTokens(e.estimatedInputTokens,"input",r,e.toolName),e.estimatedOutputTokens>0&&this.otelBridge.recordTokens(e.estimatedOutputTokens,"output",r,e.toolName),e.durationMs!==void 0&&this.otelBridge.recordDuration(e.durationMs,r);}catch{}}estimateTokens(e){return this.countTokens(e)}getReport(){return {sessionId:this.sessionId,operations:[...this.operations],totalInputTokens:this.operations.reduce((e,t)=>e+t.estimatedInputTokens,0),totalOutputTokens:this.operations.reduce((e,t)=>e+t.estimatedOutputTokens,0),estimatorName:this.estimator.name,sessionUptimeMs:Date.now()-this.startedAt}}getPerToolReport(){let e=new Map;for(let t of this.operations){let r=t.toolName||t.method,s=e.get(r)||{input:0,output:0,calls:0,avgDurationMs:0},o=s.avgDurationMs*s.calls+(t.durationMs||0),n=s.calls+1;e.set(r,{input:s.input+t.estimatedInputTokens,output:s.output+t.estimatedOutputTokens,calls:n,avgDurationMs:n>0?o/n:0});}return e}formatStatusBlock(){let e=this.getReport();if(e.operations.length===0)return "";let t=this.formatUptime(e.sessionUptimeMs),r=e.totalInputTokens+e.totalOutputTokens,s=new Map;for(let d of e.operations){let g=d.type,h=s.get(g)||{count:0,input:0,output:0};s.set(g,{count:h.count+1,input:h.input+d.estimatedInputTokens,output:h.output+d.estimatedOutputTokens});}let o=Array.from(s.entries()),n=o.map(([d,g],h)=>{let k=h===o.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",P=g.output>0?` / ${g.output.toLocaleString()} out`:"";return `${k} ${d} \xD7${g.count} \u2192 ${g.input.toLocaleString()} in${P}`}),c=this.getPerToolReport(),a=Array.from(c.entries()).filter(([d])=>d!=="tools/list"&&d!=="LiopMeshStatus"),l=[];a.length>0&&(l.push("\u251C\u2500 By Tool:"),a.forEach(([d,g],h)=>{let k=h===a.length-1?"\u2502 \u2514\u2500":"\u2502 \u251C\u2500",P=g.output>0?` / ${g.output.toLocaleString()} out`:"",I=g.avgDurationMs>0?` ~${Math.round(g.avgDurationMs)}ms`:"";l.push(`${k} ${d}: ${g.input.toLocaleString()} in${P} (\xD7${g.calls})${I}`);}));let m=e.operations.filter(d=>d.durationMs!==void 0),f=m.length>0?Math.round(m.reduce((d,g)=>d+(g.durationMs||0),0)/m.length):0,u=this.otelBridge.isActive()?"gen_ai.client.token.usage \u2192 active":"disabled";return [`
|
|
2
|
+
Token Economy:`,`\u251C\u2500 Session: ${e.sessionId.slice(0,8)} (${t})`,`\u251C\u2500 Estimator: ${e.estimatorName}`,`\u251C\u2500 Operations: ${e.operations.length}`,...n,`\u251C\u2500 Total: ${e.totalInputTokens.toLocaleString()} in / ${e.totalOutputTokens.toLocaleString()} out (${r.toLocaleString()} combined)`,...l,...f>0?[`\u251C\u2500 Avg Latency: ${f}ms`]:[],`\u2514\u2500 OTel: ${u}`].join(`
|
|
3
|
+
`)}formatUptime(e){let t=Math.floor(e/1e3);if(t<60)return `${t}s`;let r=Math.floor(t/60),s=t%60;if(r<60)return `${r}m ${s}s`;let o=Math.floor(r/60),n=r%60;return `${o}h ${n}m`}reset(){this.operations=[];}static destroy(){i.instance=null;}};function C(){let i=process.env.LIOP_MCP_COMPACT_TOOL_DESCRIPTIONS?.toLowerCase().trim();return !(i==="0"||i==="false"||i==="no")}function re(i){let e=i,t=[`
|
|
4
|
+
|
|
5
|
+
[LIOP-PROTO-V1:`,`\r
|
|
6
|
+
\r
|
|
7
|
+
[LIOP-PROTO-V1:`,`
|
|
8
|
+
[LIOP-PROTO-V1:`];for(let r of t){let s=e.indexOf(r);if(s!==-1){e=e.slice(0,s);break}}return e.trimEnd()}var ge=300,ne=5,Te=class i{constructor(e,t=null,r=50051){this.liopServer=e;this.meshNode=t;this.defaultRpcPort=r;this.meshNode&&(this.meshNode.registerManifestHandler(()=>{let s=this.liopServer.listTools().map(n=>({name:n.name,description:n.description,inputSchema:n.inputSchema})),o=this.liopServer.listResources().map(n=>({name:n.name,uri:n.uri,description:n.description,mimeType:n.mimeType}));return {peerId:this.meshNode?.getPeerId()||"unknown",grpcPort:this.defaultRpcPort,tools:[...s],resources:o,serverInfo:this.liopServer.getServerInfo()}}),this.meshNode.announceManifest().catch(s=>{a.info(`[LIOP-Router] Failed to announce manifest: ${s instanceof Error?s.message:String(s)}`);})),process.env.LIOP_DIAGNOSTIC_LEVEL==="full"&&process.stderr.write(`\u26A0\uFE0F [LIOP-Security] Diagnostic level set to FULL \u2014 PeerIDs and network topology are exposed. Do NOT use in production.
|
|
9
|
+
`);}manifestCache=new Map;currentDiscovery=null;verifier=new a$1;onToolsChanged;manifestFailureState=new Map;static MANIFEST_FAILURE_BASE_COOLDOWN_MS=15e3;static MANIFEST_FAILURE_MAX_COOLDOWN_MS=5*6e4;static MANIFEST_SKIP_LOG_THROTTLE_MS=3e4;shouldSkipManifestQuery(e){let t=this.manifestFailureState.get(e);if(!t)return false;let r=Date.now();return r>=t.cooldownUntil?false:(r-t.lastSkipLogAt>i.MANIFEST_SKIP_LOG_THROTTLE_MS&&(a.info(`[LIOP-Router] Skipping manifest query for ${e} during cooldown (${Math.ceil((t.cooldownUntil-r)/1e3)}s remaining)`),t.lastSkipLogAt=r),true)}recordManifestQuerySuccess(e){this.manifestFailureState.delete(e);}recordManifestQueryFailure(e){let t=Date.now(),s=(this.manifestFailureState.get(e)?.failures||0)+1,o=Math.min(i.MANIFEST_FAILURE_BASE_COOLDOWN_MS*2**Math.max(0,s-1),i.MANIFEST_FAILURE_MAX_COOLDOWN_MS);this.manifestFailureState.set(e,{failures:s,cooldownUntil:t+o,lastSkipLogAt:0});}async dispatch(e){let{method:t,params:r,id:s}=e;switch(a.info(`[LIOP-Router] Processing: ${t}`),t){case "initialize":return {jsonrpc:"2.0",id:s,result:{protocolVersion:"2025-11-25",capabilities:{tools:{listChanged:true},resources:{listChanged:true},prompts:{listChanged:true}},serverInfo:this.liopServer.getServerInfo()}};case "notifications/initialized":return this.kickDiscoveryAfterInitialized().catch(()=>{}),null;case "notifications/cancelled":return null;case "ping":return {jsonrpc:"2.0",id:s,result:{}};case "tools/list":{let o=this.liopServer.listTools(),n=await this.getRemoteTools(),c=C()?o.map(p=>({...p,description:re(p.description??"")})):o;a.info(`[LIOP-Router] tools/list: ${o.length} local, ${n.length} remote tools found`);let l=[{name:"LiopMeshStatus",description:"LiopMeshStatus: Returns the current dynamic diagnostic status of the Zero-Trust Neural Mesh.",inputSchema:{type:"object",properties:{},additionalProperties:false}},...c,...n],m=S.getInstance(),f=JSON.stringify(l),u=JSON.stringify({tools:l});return m.record({type:"tools_list",method:"tools/list",estimatedInputTokens:m.countTokens(f),estimatedOutputTokens:m.countTokens(u)}),{jsonrpc:"2.0",id:s,result:{tools:l}}}case "tools/call":return this.transcodeMcpToLiop(s,r);case "resources/list":{let o=this.liopServer.listResources(),n=await this.getRemoteResources(),c=[...o,...n],a=S.getInstance(),l=JSON.stringify(c);return a.record({type:"resource_list",method:"resources/list",estimatedInputTokens:0,estimatedOutputTokens:a.countTokens(l)}),{jsonrpc:"2.0",id:s,result:{resources:c}}}case "resources/read":{let o=r;if(!o?.uri)return {jsonrpc:"2.0",id:s,error:{code:-32602,message:"Missing resource uri"}};try{let n=Date.now(),c=await this.liopServer.readResource(o.uri),a=S.getInstance(),l=JSON.stringify(c);return a.record({type:"resource_read",method:"resources/read",toolName:o.uri,estimatedInputTokens:a.countTokens(o.uri),estimatedOutputTokens:a.countTokens(l),durationMs:Date.now()-n}),{jsonrpc:"2.0",id:s,result:c}}catch(n){let c=o.uri;for(let{manifest:a$1}of this.manifestCache.values()){let l=a$1.resources.find(m=>m.uri===c);if(l)return a.info(`[LIOP-Router] Resolved resource ${c} from cache (Peer: ${a$1.peerId})`),{jsonrpc:"2.0",id:s,result:{contents:[{uri:l.uri,mimeType:l.mimeType||"text/plain",text:l.text||l.description||"No content provided"}]}}}return {jsonrpc:"2.0",id:s,error:{code:-32e3,message:n instanceof Error?n.message:String(n)}}}}case "prompts/list":{let o=this.liopServer.listPrompts(),n=S.getInstance(),c=JSON.stringify(o);return n.record({type:"prompt_list",method:"prompts/list",estimatedInputTokens:0,estimatedOutputTokens:n.countTokens(c)}),{jsonrpc:"2.0",id:s,result:{prompts:o}}}case "prompts/get":{let o=r;if(!o?.name)return {jsonrpc:"2.0",id:s,error:{code:-32602,message:"Missing prompt name"}};try{let n=Date.now(),c=await this.liopServer.getPrompt({name:o.name,arguments:o.arguments||{}}),a=S.getInstance(),l=JSON.stringify({name:o.name,arguments:o.arguments}),m=JSON.stringify(c);return a.record({type:"prompt_get",method:"prompts/get",toolName:o.name,estimatedInputTokens:a.countTokens(l),estimatedOutputTokens:a.countTokens(m),durationMs:Date.now()-n}),{jsonrpc:"2.0",id:s,result:c}}catch(n){return {jsonrpc:"2.0",id:s,error:{code:-32e3,message:n instanceof Error?n.message:String(n)}}}}default:return {jsonrpc:"2.0",id:s,error:{code:-32601,message:`Method not found: ${t}`}}}}kickDiscoveryAfterInitialized(){return (async()=>{await new Promise(e=>setTimeout(e,250)),await Promise.race([this.refreshManifestCache(true),new Promise(e=>setTimeout(e,15e3))]).catch(()=>{});})()}async refreshManifestCache(e=false){if(this.meshNode){if(this.currentDiscovery)return this.currentDiscovery;if(!e&&this.manifestCache.size>0){let t=Date.now();if(Array.from(this.manifestCache.values()).every(({cachedAt:s})=>t-s<ge*1e3))return}return this.currentDiscovery=(async()=>{try{let t=Array.from(this.manifestCache.values()).reduce((u,{manifest:p})=>u+p.tools.length,0);if(this.manifestCache.size===0)for(let u=0;u<3;u++){if((this.meshNode.node?.getConnections().length||0)>0){a.info("[LIOP-Router] P2P Connection established. Starting discovery...");break}a.info(`[LIOP-Router] Waiting for P2P connections (attempt ${u+1}/10)...`),await new Promise(d=>setTimeout(d,1e3));}let r=[],s=this.manifestCache.size===0?5:1;for(let u=0;u<s;u++){for(let h=0;h<ne;h++){r=await this.meshNode?.discoverManifestProviders()||[];let k=this.meshNode?.getPeerId();if(r.filter(I=>I!==k).length>0)break;h<ne-1&&(a.info(`[LIOP-Router] DHT discovery attempt ${h+1}/${ne}...`),await new Promise(I=>setTimeout(I,1e3)));}let p=this.meshNode.node?.getConnections().map(h=>h.remotePeer.toString())||[];p.length>0&&(r=Array.from(new Set([...r,...p])));let d=this.meshNode?.getPeerId();if(r.filter(h=>h!==d).length>0)break;u<s-1&&(a.info(`[LIOP-Router] Initial discovery failed (0 providers). Retrying in 1s (${u+1}/${s})...`),await new Promise(h=>setTimeout(h,1e3)));}if(r.length===0){a.info("[LIOP-Router] No manifest providers found after all attempts.");return}e||a.info(`[LIOP-Router] Discovered ${r.length} candidate manifest providers`);let o=new Set((this.meshNode.node?.getConnections?.()||[]).map(u=>u.remotePeer.toString()));r=[...r].sort((u,p)=>{let d=o.has(u)?1:0;return (o.has(p)?1:0)-d});let n=0,c=0,a$1=!1,l=this.meshNode?.getPeerId(),m=r.filter(u=>{if(!this.meshNode||u===l||this.shouldSkipManifestQuery(u))return !1;let p=this.manifestCache.get(u);return p&&Date.now()-p.cachedAt<ge*1e3?(n++,!1):!0}),f=await Promise.allSettled(m.map(async u=>this.meshNode?(a.info(`[LIOP-Router] Querying manifest from: ${u}`),{peerId:u,manifest:await this.meshNode.queryManifest(u)}):null));for(let u of f)if(u.status==="fulfilled"&&u.value?.manifest){let{peerId:p,manifest:d}=u.value;this.manifestCache.set(p,{manifest:d,cachedAt:Date.now()}),this.recordManifestQuerySuccess(p),a$1=!0,n++,a.info(`[LIOP-Router] Manifest received from ${p} (${d.tools.length} tools)`);}else u.status==="fulfilled"&&u.value?(this.recordManifestQueryFailure(u.value.peerId),c++,a.info(`[LIOP-Router] Manifest query returned NULL for ${u.value.peerId}`)):u.status==="rejected"&&(c++,a.info("[LIOP-Router] Fatal error querying manifest:",u.reason instanceof Error?u.reason.message:String(u.reason)));this._discoveryStats={candidates:r.length,success:n,failures:c,lastDiscovery:Date.now()},a$1&&Array.from(this.manifestCache.values()).reduce((p,{manifest:d})=>p+d.tools.length,0)!==t&&this.onToolsChanged&&(process.stderr.write(`[LIOP-Router] Mesh topology updated! Emitting notifications/tools/list_changed.
|
|
10
|
+
`),this.onToolsChanged());}finally{this.currentDiscovery=null;}})(),this.currentDiscovery}}getCacheSize(){return this.manifestCache.size}async getRemoteTools(){let e=Number.parseInt(process.env.LIOP_EXPECTED_PROVIDERS??"1",10);if(this.manifestCache.size<e&&this.meshNode){let o=Number.parseInt(process.env.LIOP_INITIAL_DISCOVERY_TIMEOUT_MS??"8000",10),n=Number.isFinite(o)&&o>0?o:12e3,c=Date.now()+n,a$1=0,l=-1;for(;Date.now()<c&&!(this.manifestCache.size>=e||(await Promise.race([this.refreshManifestCache(true),new Promise(m=>setTimeout(m,3e3))]).catch(()=>{}),this.manifestCache.size>=e));){if(this.manifestCache.size===l){if(a$1++,a$1>=3&&this.manifestCache.size>0){a.info(`[LIOP-Router] Provider count stabilized at ${this.manifestCache.size}/${e}. Proceeding with available mesh.`);break}}else a$1=0,l=this.manifestCache.size;await new Promise(m=>setTimeout(m,1e3));}this.manifestCache.size<e&&(a.info(`[LIOP-Router] \u26A0\uFE0F Mesh partially available: ${this.manifestCache.size}/${e} providers. Some tools may be unavailable. Check Docker containers.`),this.refreshManifestCache(true).catch(()=>{}));}let t=[],r=new Set,s=new Set(this.liopServer.listTools().map(o=>o.name));for(let[o,{manifest:n}]of this.manifestCache.entries())for(let c of n.tools){if(c.name==="LiopMeshStatus")continue;let a=c.name;(r.has(c.name)||s.has(c.name))&&(a=`${c.name}_${o.slice(-4)}`),r.add(a);let l=n.serverInfo?.name||"Unknown Provider",m=c.description||`Remote tool from ${l}`,f={name:a,description:C()?re(m):m,inputSchema:c.inputSchema||{type:"object",properties:{}}};typeof f.inputSchema=="object"&&!f.inputSchema.type&&(f.inputSchema.type="object"),typeof f.inputSchema=="object"&&!f.inputSchema.properties&&(f.inputSchema.properties={});let u="";n.taxonomy&&(u=`
|
|
11
|
+
[LIOP-DOMAIN: ${n.taxonomy.domain}]`);let p=f.inputSchema.properties||{},d="";!C()&&p.payload&&(d=`
|
|
12
|
+
[REQUIRES: LIOP-PROTO-V1 ENVELOPE]`),!C()&&f.description.includes("STRICT SCHEMA ADHERENCE")&&(f.description=f.description.replace("STRICT SCHEMA ADHERENCE:","[INDUSTRIAL-REQUISITE] STRICT SCHEMA ADHERENCE (MANDATORY):"));let g=C()?`
|
|
13
|
+
(Peer: ${o.slice(-8)})${u}`:`
|
|
14
|
+
(Origin: ${o.slice(-8)})${u}${d}`;f.description=`${f.description}${g}`,t.push(f);}return t}async getRemoteResources(){this.currentDiscovery||this.refreshManifestCache(true).catch(()=>{});let e=[],t=new Set(this.liopServer.listResources().map(r=>r.uri));for(let[r,{manifest:s}]of this.manifestCache.entries())for(let o of s.resources)if(!t.has(o.uri)){let n={...o},c=s.serverInfo?.name||"Unknown Provider",a="";s.taxonomy&&(a=`
|
|
15
|
+
|
|
16
|
+
[LIOP Zero-Trust Blueprint]
|
|
17
|
+
Domain: ${s.taxonomy.domain}
|
|
18
|
+
Clearance Tier: ${s.taxonomy.clearanceTier}`,s.taxonomy.executionTypes&&s.taxonomy.executionTypes.length>0&&(a+=`
|
|
19
|
+
Execution Types: ${s.taxonomy.executionTypes.join(", ")}`));let l=`
|
|
20
|
+
|
|
21
|
+
[LIOP Zero-Trust Origin]
|
|
22
|
+
Provider: ${c}
|
|
23
|
+
Network ID: ${r}${a}`;n.uri.startsWith("liop://schema/")?(n.name=`[SCHEMA] ${n.name}`,n.description=`[CRITICAL SCHEMA] ${n.description||"Data Dictionary for Zero-Shot Autonomy"}${l}`):n.description=n.description?`${n.description}${l}`:l.trim(),e.push(n),t.add(o.uri);}return e}resolveManifestTarget(e){for(let[r,{manifest:s}]of this.manifestCache.entries())if(s.tools.find(n=>n.name===e))return {peerId:r,originalToolName:e};let t=e.split("_");if(t.length>1){let r=t.pop(),s=t.join("_");for(let[o,{manifest:n}]of this.manifestCache.entries())if(o.endsWith(r||"")&&n.tools.find(a=>a.name===s))return {peerId:o,originalToolName:s}}return null}redactPeerId(e){return (process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")==="full"?e:`***${e.slice(-8)}`}async transcodeMcpToLiop(e,t){let r=t.name;if(r==="LiopMeshStatus"){this.refreshManifestCache(true).catch(()=>{});let o=this._discoveryStats||{candidates:0,success:0,failures:0},n=this.manifestCache.size,c=this.meshNode?"Active":"Offline",a=Array.from(this.manifestCache.values()).reduce((O,{manifest:E})=>O+E.tools.length,0),l=this.meshNode?this.meshNode.node?.getConnections().length:0,m=this.meshNode&&this.meshNode.config?.bootstrapNodes?this.meshNode.config.bootstrapNodes:[],f=m.length,p=(process.env.LIOP_DIAGNOSTIC_LEVEL||"redacted")!=="minimal",d=p?m.map(O=>{let E=O.split("/"),w=E[E.length-1];return ` \u2022 ${w?w.slice(-8):"Unknown"} (bootstrap)`}).join(`
|
|
24
|
+
`):"",g=this.meshNode?this.meshNode.getRoutingTableSize():0,h=this.meshNode?.getPeerId()||"Offline",k=h==="Offline"?h:this.redactPeerId(h),P=Array.from(this.manifestCache.entries()).flatMap(([O,{manifest:E}])=>E.tools.map(w=>` \u2022 ${w.name} (from origin: ${this.redactPeerId(O)})`)).join(`
|
|
25
|
+
`),I=[`LIOP Mesh Status: ${c==="Active"?"Active":"Offline"}`,`Local Agent Identity: ${k}`,`Network: ${l} Conns | ${g} Mesh Nodes | ${f} Bootstraps`,p&&f>0?`
|
|
26
|
+
Active Bootstraps:
|
|
27
|
+
${d}
|
|
28
|
+
`:"",`Discovery: ${o.candidates} Candidates | ${o.success} OK | ${o.failures} FAIL`,`Tooling: ${n} Providers | ${a} Total Remote Tools`,a>0?`
|
|
29
|
+
Discovered Remote Tools (Zero-Trust Origins):
|
|
30
|
+
${P}`:`
|
|
31
|
+
No remote tools discovered yet.`,S.getInstance().formatStatusBlock()].filter(O=>O!=="").join(`
|
|
32
|
+
`),R=S.getInstance();return R.record({type:"diagnostic",method:"tools/call",toolName:"LiopMeshStatus",estimatedInputTokens:0,estimatedOutputTokens:R.countTokens(I)}),{jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:I}]}}}let s=this.liopServer.listTools().some(o=>o.name===r);if(!s&&this.meshNode){let o=this.resolveManifestTarget(r);if(o||(await this.refreshManifestCache(),o=this.resolveManifestTarget(r)),o)return a.info(`[LIOP-Router] Resolved ${r} via manifest cache (Peer: ${o.peerId}, Original: ${o.originalToolName})`),this.routeToRemoteProvider(e,o.originalToolName,o.peerId,t);let n=[];for(let c=0;c<3&&(n=await this.meshNode.findProviders(r),!(n.length>0));c++)c<2&&await new Promise(a=>setTimeout(a,1e3));if(n.length>0)return this.routeToRemoteProvider(e,r,n[0],t)}if(s)try{let o=Date.now(),n=await this.liopServer.callTool({name:r,arguments:t.arguments||{}}),c=S.getInstance(),a=JSON.stringify(t.arguments||{}),l=JSON.stringify(n);return c.record({type:"tool_call",method:"tools/call",toolName:r,estimatedInputTokens:c.countTokens(a),estimatedOutputTokens:c.countTokens(l),durationMs:Date.now()-o}),{jsonrpc:"2.0",id:e,result:n}}catch(o){return {jsonrpc:"2.0",id:e,error:{code:-32e3,message:o instanceof Error?o.message:String(o)}}}return {jsonrpc:"2.0",id:e,error:{code:-32002,message:`No provider found for tool: ${r}. Ensure the provider node is active and connected to the mesh.`}}}async routeToRemoteProvider(e,t,r,s){if(!this.meshNode)return {jsonrpc:"2.0",id:e,error:{code:-32603,message:"Mesh Node inactive"}};let o=this.manifestCache.get(r),n=this.defaultRpcPort;if(o)n=o.manifest.grpcPort;else {let p=await this.meshNode.queryManifest(r);p&&(n=p.grpcPort,this.manifestCache.set(r,{manifest:p,cachedAt:Date.now()}),o=this.manifestCache.get(r));}if((process.env.NODE_ENV==="development"||process.env.NODE_ENV==="test")&&o&&process.env.LIOP_USE_PUBLISHED_GRPC_PORTS==="1"){let p=o.manifest.serverInfo?.name?.toLowerCase()||"";p.includes("vault")?n=13011:p.includes("bank")?n=13021:p.includes("oracle")&&(n=13031);}let a$1=await this.meshNode.resolvePeer(r),l=null,m=await import('os'),f=Object.values(m.networkInterfaces()).flat().filter(p=>p?.family==="IPv4").map(p=>p?.address);for(let p of a$1){let d=p.split("/"),g=d.indexOf("ip4");if(g!==-1){let h=d[g+1];if(h==="127.0.0.1"||f.includes(h)){l=`127.0.0.1:${n}`;break}l||(l=`${h}:${n}`);}}l||(l=`127.0.0.1:${n}`),a.info(`[LIOP-Router] Dynamic route: ${t} -> ${l} (PeerID: ${r})`);let u=new a$2.LogicMesh(l,c());return this.performTranscoding(e,u,t,s,r)}async performTranscoding(e,t,r,s,o){let n=r,c=this.meshNode?await this.meshNode.sign(Buffer.from(n)):Buffer.from([]),a=Date.now();return new Promise(l=>{t.negotiateIntent({agent_did:`did:liop:${this.meshNode?.getPeerId()||"mcp-proxy"}`,capability_hash:n,proof_of_intent:c},async(m,f)=>{if(m||!f.accepted)return l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`PQC Handshake Failed: ${m?.message||"Rejected"}`}],isError:true}});let{ciphertext:u,sharedSecret:p}=await a$3.encapsulateAsymmetric(f.kyber_public_key),d=JSON.stringify(s.arguments||{}),g=`return { "__liop_proxy_tool": "${r}", "__liop_proxy_args": ${d} };`,h=G.randomBytes(12),k=this.encryptWithNonce(Buffer.from(g),p,h),P=t.executeLogic({session_token:f.session_token,wasm_binary:new Uint8Array(k),inputs:{},pqc_ciphertext:u,aes_nonce:h}),I="",R=null;P.on("data",O=>{I+=O.semantic_evidence,R=O;}),P.on("end",async()=>{try{if(R&&!R.is_error){let w=Buffer.from(R.cryptographic_proof).toString("hex");if(!await this.verifier.verifyZkReceipt(Buffer.from(g),w,Buffer.from(R.zk_receipt),Buffer.from(p)))return l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:"SECURITY ALERT: Remote response failed cryptographic integrity audit."}],isError:!0}})}let O=JSON.parse(I),E=S.getInstance();E.record({type:"tool_call",method:"tools/call",toolName:r,peerId:o,estimatedInputTokens:E.countTokens(d),estimatedOutputTokens:E.countTokens(I),durationMs:Date.now()-a}),l({jsonrpc:"2.0",id:e,result:O});}catch{l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:I}]}});}}),P.on("error",O=>l({jsonrpc:"2.0",id:e,result:{content:[{type:"text",text:`LIOP gRPC Error: ${O.message}`}],isError:true}}));});})}encryptWithNonce(e,t,r){let s=G.createCipheriv("aes-256-gcm",t,r),o=Buffer.concat([s.update(e),s.final()]);return Buffer.concat([o,s.getAuthTag()])}};export{H as a,B as b,le as c,ue as d,z as e,S as f,Te as g};//# sourceMappingURL=chunk-UK7OBXGZ.js.map
|
|
33
|
+
//# sourceMappingURL=chunk-UK7OBXGZ.js.map
|