Spaces:
Sleeping
Sleeping
Download app.js from publicstring/gingernode: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/publicstring/gingernode/resolve/main/app.js
- Command line
-
hf download hf://spaces/publicstring/gingernode/app.js
-
curl -L -o app.js https://huggingface.co/spaces/publicstring/gingernode/resolve/main/app.js
20.4 kB
| require('dotenv').config(); | |
| const express = require('express'); | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| const https = require('https'); | |
| const os = require('os'); | |
| const { createClient } = require('@supabase/supabase-js'); | |
| const { ClinchCore, NegotiationState } = require('clinch-core'); | |
| const app = express(); | |
| app.use(express.json()); | |
| // ============================================================================ | |
| // CONFIGURATION & INITIALIZATION | |
| // ============================================================================ | |
| const PORT = process.env.PORT || 7860; | |
| const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT; | |
| const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY; | |
| const AGENT_ID = process.env.AGENT_ID || 'ginger.anp'; | |
| const SUPABASE_URL = process.env.SUPABASE_URL; | |
| const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY; | |
| if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !PUBLIC_ENDPOINT || !SELLER_PRIV_KEY) { | |
| console.error("FATAL: Missing required dynamic configuration parameters in env."); | |
| process.exit(1); | |
| } | |
| const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY); | |
| // Protocol v0.2.1 Core Initialization | |
| const core = new ClinchCore({ | |
| privateKeyHex: SELLER_PRIV_KEY | |
| }); | |
| core.on('log', msg => console.log(`[Ginger Protocol] ${msg}`)); | |
| // ============================================================================ | |
| // AI MEDIATOR (QWEN 1.5B GGUF on CPU) | |
| // ============================================================================ | |
| const MODEL_DIR = path.join(__dirname, 'models'); | |
| const MODEL_PATH = path.join(MODEL_DIR, 'qwen2.5-1.5b-instruct-q4_k_m.gguf'); | |
| const MODEL_URL = "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf"; | |
| let cachedLlamaModel = null; | |
| let cachedLlamaContext = null; | |
| let mediatorReady = false; | |
| function downloadModel() { | |
| return new Promise((resolve, reject) => { | |
| if (!fs.existsSync(MODEL_DIR)) fs.mkdirSync(MODEL_DIR, { recursive: true }); | |
| console.log(`[AI] Downloading Qwen 1.5B Mediator Model (1.1GB)...`); | |
| const file = fs.createWriteStream(MODEL_PATH); | |
| const request = (currentUrl) => { | |
| https.get(currentUrl, (response) => { | |
| if ([301, 302, 303, 307, 308].includes(response.statusCode)) return request(response.headers.location); | |
| if (response.statusCode !== 200) return reject(new Error(`Download failed: ${response.statusCode}`)); | |
| const total = parseInt(response.headers['content-length'], 10); | |
| let downloaded = 0; | |
| response.on('data', (chunk) => { | |
| downloaded += chunk.length; | |
| const percent = total ? ((downloaded / total) * 100).toFixed(1) : (downloaded / 1024 / 1024).toFixed(1); | |
| process.stdout.write(`\r[AI] Fetching model... ${percent}%`); | |
| }); | |
| response.pipe(file); | |
| file.on('finish', () => { | |
| console.log("\n[AI] ✓ Download complete!"); | |
| file.close(resolve); | |
| }); | |
| }).on('error', (err) => { fs.unlink(MODEL_PATH, () => reject(err)); }); | |
| }; | |
| request(MODEL_URL); | |
| }); | |
| } | |
| async function getMediatorAI() { | |
| if (cachedLlamaModel) return; | |
| if (!fs.existsSync(MODEL_PATH)) await downloadModel(); | |
| const nodeLlama = await import('node-llama-cpp'); | |
| const threads = 4; | |
| console.log(`[AI] Loading Qwen 1.5B into RAM with ${threads} threads...`); | |
| const llama = await nodeLlama.getLlama(); | |
| cachedLlamaModel = await llama.loadModel({ modelPath: MODEL_PATH }); | |
| cachedLlamaContext = await cachedLlamaModel.createContext({ contextSize: 2048, threads }); | |
| mediatorReady = true; | |
| console.log(`[AI] Mediator Engine Hot.`); | |
| } | |
| async function mediatePrice(currentPrice, item) { | |
| if (!mediatorReady || !cachedLlamaContext) { | |
| console.log(`[AI] Mediator not ready yet — returning safe fallback.`); | |
| return { | |
| price: currentPrice * 0.9, | |
| message: "Ginger AI Mediator is warming up. Suggesting a 10% compromise to keep the deal moving." | |
| }; | |
| } | |
| const nodeLlama = await import('node-llama-cpp'); | |
| const systemPrompt = `You are the Ginger P2P AI Mediator. Two human/agent peers are deadlocked negotiating a price for "${item}". | |
| The current proposed price is $${currentPrice}. | |
| Propose a fair middle-ground compromise to break the deadlock. | |
| Output ONLY valid JSON matching exactly: {"price": number, "message": "string"}`; | |
| const session = new nodeLlama.LlamaChatSession({ | |
| contextSequence: cachedLlamaContext.getSequence(), | |
| systemPrompt, | |
| chatWrapper: new nodeLlama.ChatMLChatWrapper() | |
| }); | |
| let responseText = ""; | |
| await session.prompt("Suggest a compromise.", { maxTokens: 200, onTextChunk: (chunk) => { responseText += chunk; } }); | |
| try { | |
| const clean = responseText.replace(/```json|```/g, "").trim(); | |
| return JSON.parse(clean); | |
| } catch (e) { | |
| return { price: currentPrice * 0.9, message: "Ginger AI suggests a 10% compromise to keep the deal moving." }; | |
| } | |
| } | |
| // ============================================================================ | |
| // IN-MEMORY CACHE & GC DAEMON | |
| // ============================================================================ | |
| const localRoomCache = new Map(); | |
| setInterval(async () => { | |
| console.log("[Ginger GC] Initiating scheduled sweeping daemon..."); | |
| const now = Date.now(); | |
| let swept = 0; | |
| for (const [roomId, room] of localRoomCache.entries()) { | |
| if (now - new Date(room.created_at).getTime() > 1800000) { | |
| localRoomCache.delete(roomId); | |
| swept++; | |
| } | |
| } | |
| const oneHourAgo = new Date(now - 3600000).toISOString(); | |
| const { error } = await supabase.from('ginger_rooms').delete().eq('status', 'pending').lt('created_at', oneHourAgo); | |
| if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message); | |
| else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`); | |
| }, 600000); | |
| async function generateUniquePin() { | |
| let pin; | |
| let exists = true; | |
| while (exists) { | |
| pin = Math.floor(100000 + Math.random() * 900000).toString(); | |
| const { data } = await supabase.from('ginger_rooms').select('pin').eq('pin', pin).maybeSingle(); | |
| if (!data) exists = false; | |
| } | |
| return pin; | |
| } | |
| // ============================================================================ | |
| // PUBLIC ROUTE: LEGACY DIRECT REGISTRATION | |
| // ============================================================================ | |
| app.post('/register-handle', async (req, res) => { | |
| const { handle, session_id, session_pub_key, callback_token } = req.body; | |
| if (!handle || !session_id || !session_pub_key) return res.status(400).json({ error: "Missing required parameters." }); | |
| const normalizedHandle = handle.toLowerCase().trim(); | |
| try { | |
| const { error } = await supabase.from('ginger_handles').upsert({ | |
| handle: normalizedHandle, | |
| session_id, | |
| pub_key: session_pub_key, | |
| callback_token: callback_token || null, | |
| updated_at: new Date().toISOString() | |
| }); | |
| if (error) throw error; | |
| console.log(`[Handle Registry] Bound permanent handle: ${normalizedHandle} ➔ ${session_pub_key.substring(0,8)}`); | |
| return res.json({ status: "BOUND", handle: normalizedHandle }); | |
| } catch (err) { | |
| console.error("[-] Handle registration error:", err.message); | |
| return res.status(500).json({ error: "Failed to map permanent handle." }); | |
| } | |
| }); | |
| // ============================================================================ | |
| // ANP HANDSHAKE ROUTE (Protocol Registration, Room Creation & Joining) | |
| // ============================================================================ | |
| app.post('/handshake', async (req, res) => { | |
| const { session_id, buyer_pub_key, constraints, blind_auth_token, callback_token } = req.body; | |
| if (blind_auth_token) { | |
| console.log(`[Auth] Blind key token received | session: ${session_id} | buyer: ${buyer_pub_key?.substring(0, 8)}...`); | |
| } | |
| core.registerIncomingSession(session_id, buyer_pub_key, constraints); | |
| try { | |
| const targetHandle = constraints?.terms?.target_handle || constraints?.target_handle; | |
| const p2pPin = constraints?.terms?.p2p_pin || constraints?.p2p_pin; | |
| const intent = constraints?.intent; | |
| // --- CASE 0: REGISTERING PERMANENT HANDLE VIA P2P PROTOCOL --- | |
| if (intent === 'register' && targetHandle) { | |
| const handle = targetHandle.toLowerCase().trim(); | |
| // 🔒 ANTI-HIJACK SHIELD: Verify if handle is claimed by another public key | |
| const { data: existing } = await supabase.from('ginger_handles').select('pub_key').eq('handle', handle).maybeSingle(); | |
| if (existing && existing.pub_key !== buyer_pub_key) { | |
| return res.json({ type: 'CANCEL', reason: `Handle '${handle}' is already registered to another cryptographic key.` }); | |
| } | |
| const { error: regErr } = await supabase.from('ginger_handles').upsert({ | |
| handle: handle, | |
| session_id, | |
| pub_key: buyer_pub_key, | |
| callback_token: callback_token || null, | |
| updated_at: new Date().toISOString() | |
| }); | |
| if (regErr) throw regErr; | |
| console.log(`[Handle Registry] Bound permanent handle (Protocol Sync): ${handle} ➔ ${buyer_pub_key.substring(0,8)}`); | |
| core.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, 0, 1); | |
| return res.json({ | |
| type: "CONFIRM", | |
| price: 0, | |
| turn: 1, | |
| message: `Success. Handle '${handle}' is now securely bound to your session key.` | |
| }); | |
| } | |
| // --- CASE 1: JOINING A PERMANENT HANDLE --- | |
| if (targetHandle) { | |
| const handle = targetHandle.toLowerCase().trim(); | |
| const { data: persistentHost, error: handleErr } = await supabase.from('ginger_handles').select('*').eq('handle', handle).maybeSingle(); | |
| if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline or does not exist.` }); | |
| // 🛡️ ANTI-LOOP SHIELD: Prevent an agent from initiating a connection to itself | |
| if (persistentHost.pub_key === buyer_pub_key) { | |
| return res.json({ type: 'CANCEL', reason: "Cannot establish a P2P session with your own handle." }); | |
| } | |
| const pin = await generateUniquePin(); | |
| const { data: room, error: roomErr } = await supabase.from('ginger_rooms').insert({ | |
| pin, | |
| initiator_session_id: persistentHost.session_id, | |
| initiator_pub_key: persistentHost.pub_key, | |
| initiator_callback_token: persistentHost.callback_token || null, | |
| initiator_handle: handle, | |
| receiver_session_id: session_id, | |
| receiver_pub_key: buyer_pub_key, | |
| receiver_callback_token: callback_token || null, | |
| receiver_handle: null, | |
| status: 'active' | |
| }).select('*').single(); | |
| if (roomErr) throw roomErr; | |
| localRoomCache.set(room.room_id, room); | |
| // Extract custom message | |
| const customMsg = constraints?.terms?.message || constraints?.message; | |
| const notificationMsg = customMsg | |
| ? `[Incoming from ${handle}]: ${customMsg}` | |
| : `Peer targeting your handle '${handle}' has joined. Room active.`; | |
| // Notify the Host asynchronously | |
| await core.request('/api/route/async-callback', 'POST', { | |
| buyer_pub_key: persistentHost.pub_key, | |
| payload: { | |
| type: "COUNTER", | |
| session_id: persistentHost.session_id, | |
| price: constraints.max_budget || 0, | |
| turn: 2, | |
| message: notificationMsg | |
| } | |
| }).catch(() => {}); | |
| core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, constraints.max_budget || 0, 2); | |
| return res.json({ type: "COUNTER", price: constraints.max_budget || 0, turn: 2, message: `Connected to ${handle}. Message delivered.` }); | |
| } | |
| // --- CASE 2: JOINING VIA 6-DIGIT PIN --- | |
| if (p2pPin) { | |
| const pin = p2pPin.toString().trim(); | |
| const { data: room, error } = await supabase.from('ginger_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle(); | |
| if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." }); | |
| // 🛡️ ANTI-LOOP SHIELD: Prevent an agent from joining its own room | |
| if (room.initiator_pub_key === buyer_pub_key) { | |
| return res.json({ type: 'CANCEL', reason: "Cannot join your own temporary P2P room." }); | |
| } | |
| await supabase.from('ginger_rooms').update({ | |
| receiver_session_id: session_id, | |
| receiver_pub_key: buyer_pub_key, | |
| receiver_callback_token: callback_token || null, | |
| status: 'active' | |
| }).eq('room_id', room.room_id); | |
| room.receiver_session_id = session_id; | |
| room.receiver_pub_key = buyer_pub_key; | |
| room.receiver_callback_token = callback_token || null; | |
| room.status = 'active'; | |
| localRoomCache.set(room.room_id, room); | |
| // Extract custom message | |
| const customMsg = constraints?.terms?.message || constraints?.message; | |
| const notificationMsg = customMsg | |
| ? `[Incoming via PIN ${pin}]: ${customMsg}` | |
| : "Peer has entered the room. Bargaining active."; | |
| await core.request('/api/route/async-callback', 'POST', { | |
| buyer_pub_key: room.initiator_pub_key, | |
| payload: { type: "COUNTER", session_id: room.initiator_session_id, price: constraints.max_budget || 0, turn: 2, message: notificationMsg } | |
| }).catch(() => {}); | |
| core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, constraints.max_budget || 0, 2); | |
| return res.json({ type: "COUNTER", price: constraints.max_budget || 0, turn: 2, message: `Joined room ${pin}.` }); | |
| } | |
| // --- CASE 3: CREATING TEMPORARY ROOM --- | |
| const pin = await generateUniquePin(); | |
| const { data: newRoom, error: insertError } = await supabase.from('ginger_rooms').insert({ | |
| pin, | |
| initiator_session_id: session_id, | |
| initiator_pub_key: buyer_pub_key, | |
| initiator_callback_token: callback_token || null, | |
| status: 'pending' | |
| }).select('*').single(); | |
| if (insertError) throw insertError; | |
| localRoomCache.set(newRoom.room_id, newRoom); | |
| core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, 0, 2); | |
| return res.json({ type: "COUNTER", price: 0, turn: 2, message: `Room created. Share this PIN with your peer: ${pin}` }); | |
| } catch (err) { | |
| console.error("[Handshake Error]", err.message); | |
| return res.status(500).json({ type: 'CANCEL', reason: "Broker internal error." }); | |
| } | |
| }); | |
| // ============================================================================ | |
| // ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation) | |
| // ============================================================================ | |
| app.post('/counter', async (req, res) => { | |
| const { session_id, turn, price, reason, signature } = req.body; | |
| const currentTurn = turn || 2; | |
| const nextTurn = currentTurn + 1; | |
| try { | |
| let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active'); | |
| if (!room) { | |
| const { data, error } = await supabase.from('ginger_rooms').select('*').or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`).eq('status', 'active').maybeSingle(); | |
| if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." }); | |
| room = data; | |
| localRoomCache.set(room.room_id, room); | |
| } | |
| const isInitiator = room.initiator_session_id === session_id; | |
| const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id; | |
| const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key; | |
| let routedPrice = price; | |
| let routedMessage = reason; | |
| await supabase.from('ginger_messages').insert({ | |
| room_id: room.room_id, | |
| turn: currentTurn, | |
| sender_session_id: session_id, | |
| price: price, | |
| reason: reason || null, | |
| signature: signature || null | |
| }); | |
| if (reason && reason.toLowerCase().includes('@mediate')) { | |
| console.log(`[AI] Mediation requested by ${session_id}`); | |
| const aiSuggestion = await mediatePrice(price, "P2P Service"); | |
| routedPrice = aiSuggestion.price; | |
| routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`; | |
| await supabase.from('ginger_messages').insert({ | |
| room_id: room.room_id, | |
| turn: currentTurn, | |
| sender_session_id: 'ginger_ai', | |
| price: routedPrice, | |
| reason: routedMessage, | |
| signature: null | |
| }); | |
| } | |
| await core.request('/api/route/async-callback', 'POST', { | |
| buyer_pub_key: targetPubKey, | |
| payload: { | |
| type: "COUNTER", | |
| session_id: targetSessionId, | |
| turn: nextTurn, | |
| price: routedPrice, | |
| message: routedMessage | |
| } | |
| }); | |
| core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn); | |
| return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." }); | |
| } catch (err) { | |
| console.error("[Counter Error]", err.message); | |
| return res.status(500).json({ type: 'CANCEL', reason: "Routing failed." }); | |
| } | |
| }); | |
| // ============================================================================ | |
| // BILATERAL SIGNATURE HANDLER | |
| // ============================================================================ | |
| app.post('/sign_request', (req, res) => { | |
| try { | |
| const sig = core.signAsSeller(req.body.artifact); | |
| res.json({ sellerSignature: sig }); | |
| } catch (e) { | |
| res.status(400).json({ error: e.message }); | |
| } | |
| }); | |
| // ============================================================================ | |
| // BOOT | |
| // ============================================================================ | |
| app.listen(PORT, async () => { | |
| console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`); | |
| console.log(` Stable Public Endpoint: ${PUBLIC_ENDPOINT}\n`); | |
| try { | |
| console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)..."); | |
| await core.initialize(); | |
| setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000); | |
| await core.registerNode( | |
| AGENT_ID, | |
| `${PUBLIC_ENDPOINT}`, | |
| ['p2p_bridge', 'mediation', 'scheduling'], | |
| ['p2p_bridge', 'room_routing', 'ai_mediator'], | |
| { supported_modes: ['ANP/C'] } | |
| ); | |
| console.log(`✓ Successfully registered '${AGENT_ID}' to the Network.`); | |
| getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message)); | |
| } catch (e) { | |
| console.error(`[-] Failed to self-register ginger node: ${e.message}`); | |
| } | |
| }); | |
| process.on('SIGINT', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); }); | |
| process.on('SIGTERM', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); }); |