Spaces:
Sleeping
Sleeping
File size: 20,393 Bytes
cf28d83 d3b28ac e4d3204 d3b28ac e4d3204 588b6da d3b28ac 215f01d d3b28ac 215f01d 7b3361b 215f01d d3b28ac 215f01d d3b28ac 6d903a4 e4d3204 d1f3a73 215f01d e4d3204 65d5980 e4d3204 65d5980 e4d3204 65d5980 e4d3204 65d5980 e4d3204 65d5980 e4d3204 d268ec0 65d5980 e4d3204 65d5980 e4d3204 65d5980 e4d3204 65d5980 e4d3204 215f01d d3b28ac 215f01d d3b28ac 215f01d 588b6da 215f01d d3b28ac 588b6da 215f01d 7b3361b 215f01d 7b3361b 215f01d d3b28ac 588b6da d3b28ac 996d653 d3b28ac 996d653 7b3361b d268ec0 d3b28ac 215f01d c4da555 7b3361b e4d3204 65d5980 7b3361b e4d3204 215f01d 996d653 215f01d 7b3361b 215f01d d3b28ac 215f01d 588b6da d3b28ac d268ec0 d3b28ac 996d653 7b3361b 65d5980 e4d3204 215f01d d268ec0 a35af1c d268ec0 e4d3204 d268ec0 7b3361b 215f01d d268ec0 215f01d 4d5976a 215f01d 7b3361b e4d3204 7b3361b e4d3204 7b3361b e4d3204 215f01d e4d3204 996d653 d268ec0 e4d3204 996d653 e4d3204 996d653 d3b28ac e4d3204 d268ec0 7b3361b d3b28ac e4d3204 d3b28ac 4d5976a 7b3361b 215f01d e4d3204 7b3361b 215f01d e4d3204 996d653 e4d3204 996d653 e4d3204 d3b28ac e4d3204 215f01d d3b28ac e4d3204 215f01d 7b3361b e4d3204 d3b28ac 215f01d e4d3204 d3b28ac e4d3204 d3b28ac 215f01d e4d3204 d3b28ac a956cde 996d653 7b3361b a956cde 7b3361b a956cde 7b3361b a956cde 7b3361b a956cde 996d653 a956cde 996d653 a956cde | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | 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); }); |