Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
| 1 |
require('dotenv').config();
|
| 2 |
const express = require('express');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
const { createClient } = require('@supabase/supabase-js');
|
| 4 |
-
const {
|
| 5 |
|
| 6 |
const app = express();
|
| 7 |
app.use(express.json());
|
|
@@ -12,6 +16,7 @@ app.use(express.json());
|
|
| 12 |
const PORT = process.env.PORT || 7860;
|
| 13 |
const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
|
| 14 |
const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
|
|
|
|
| 15 |
|
| 16 |
const SUPABASE_URL = process.env.SUPABASE_URL;
|
| 17 |
const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
|
|
@@ -23,24 +28,104 @@ if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !PUBLIC_ENDPOINT || !SELLER_PRIV_K
|
|
| 23 |
|
| 24 |
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
| 27 |
privateKeyHex: SELLER_PRIV_KEY
|
| 28 |
});
|
| 29 |
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
// ============================================================================
|
| 33 |
// IN-MEMORY CACHE & GC DAEMON
|
| 34 |
// ============================================================================
|
| 35 |
const localRoomCache = new Map();
|
| 36 |
|
| 37 |
-
// Interval GC sweeps every 10 minutes to prevent resource bloat and flush dead caches
|
| 38 |
setInterval(async () => {
|
| 39 |
console.log("[Ginger GC] Initiating scheduled sweeping daemon...");
|
| 40 |
const now = Date.now();
|
| 41 |
let swept = 0;
|
| 42 |
|
| 43 |
-
// 1. Flush in-memory caches older than 30 minutes
|
| 44 |
for (const [roomId, room] of localRoomCache.entries()) {
|
| 45 |
if (now - new Date(room.created_at).getTime() > 1800000) {
|
| 46 |
localRoomCache.delete(roomId);
|
|
@@ -48,19 +133,13 @@ setInterval(async () => {
|
|
| 48 |
}
|
| 49 |
}
|
| 50 |
|
| 51 |
-
// 2. Garbage collect un-joined pending rooms from Supabase older than 1 hour
|
| 52 |
const oneHourAgo = new Date(now - 3600000).toISOString();
|
| 53 |
-
const { error } = await supabase
|
| 54 |
-
.from('p2p_rooms')
|
| 55 |
-
.delete()
|
| 56 |
-
.eq('status', 'pending')
|
| 57 |
-
.lt('created_at', oneHourAgo);
|
| 58 |
|
| 59 |
if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
|
| 60 |
else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`);
|
| 61 |
}, 600000);
|
| 62 |
|
| 63 |
-
// Helper to generate secure, non-clashing 6-digit pairing PINs
|
| 64 |
async function generateUniquePin() {
|
| 65 |
let pin;
|
| 66 |
let exists = true;
|
|
@@ -76,31 +155,27 @@ async function generateUniquePin() {
|
|
| 76 |
// PUBLIC ROUTE: PERMANENT HANDLE SELF-REGISTRATION
|
| 77 |
// ============================================================================
|
| 78 |
app.post('/anp/v1/register-handle', async (req, res) => {
|
| 79 |
-
const { handle, session_id, session_pub_key
|
| 80 |
|
| 81 |
if (!handle || !session_id || !session_pub_key) {
|
| 82 |
-
return res.status(400).json({ error: "Missing required parameters
|
| 83 |
}
|
| 84 |
|
| 85 |
const normalizedHandle = handle.toLowerCase().trim();
|
| 86 |
|
| 87 |
try {
|
| 88 |
-
const { error } = await supabase
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
callback_token,
|
| 95 |
-
updated_at: new Date().toISOString()
|
| 96 |
-
});
|
| 97 |
|
| 98 |
if (error) throw error;
|
| 99 |
-
console.log(`[Handle Registry] Binded permanent handle: ${normalizedHandle} ➔ ${
|
| 100 |
return res.json({ status: "BOUND", handle: normalizedHandle });
|
| 101 |
|
| 102 |
} catch (err) {
|
| 103 |
-
console.error("[Handle Registry Error]", err.message);
|
| 104 |
return res.status(500).json({ error: "Failed to map permanent handle." });
|
| 105 |
}
|
| 106 |
});
|
|
@@ -109,303 +184,159 @@ app.post('/anp/v1/register-handle', async (req, res) => {
|
|
| 109 |
// ANP HANDSHAKE ROUTE (Creation & Joining - PIN vs Handles)
|
| 110 |
// ============================================================================
|
| 111 |
app.post('/anp/v1/handshake', async (req, res) => {
|
| 112 |
-
|
|
|
|
| 113 |
|
|
|
|
|
|
|
|
|
|
| 114 |
try {
|
| 115 |
-
// --- CASE 1:
|
| 116 |
if (constraints && constraints.target_handle) {
|
| 117 |
const handle = constraints.target_handle.toLowerCase().trim();
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
const { data: persistentHost, error: handleErr } = await supabase
|
| 121 |
-
.from('p2p_handles')
|
| 122 |
-
.select('*')
|
| 123 |
-
.eq('handle', handle)
|
| 124 |
-
.maybeSingle();
|
| 125 |
|
| 126 |
-
if (handleErr || !persistentHost) {
|
| 127 |
-
return res.status(404).json({ error: `Permanent handle '${handle}' is currently offline.` });
|
| 128 |
-
}
|
| 129 |
|
| 130 |
-
// Dynamically instantiate a room pairing the client to the permanent host
|
| 131 |
const pin = await generateUniquePin();
|
| 132 |
-
const { data: room, error: roomErr } = await supabase
|
| 133 |
-
|
| 134 |
-
.
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
receiver_session_id: session_id,
|
| 141 |
-
receiver_pub_key: session_pub_key,
|
| 142 |
-
status: 'active'
|
| 143 |
-
})
|
| 144 |
-
.select('*')
|
| 145 |
-
.single();
|
| 146 |
|
| 147 |
if (roomErr) throw roomErr;
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
//
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
}
|
| 164 |
-
|
| 165 |
-
return res.json({
|
| 166 |
-
status: "ACCEPTED",
|
| 167 |
-
p2p_role: "receiver",
|
| 168 |
-
session_id,
|
| 169 |
-
capabilities: ["p2p_bridge"],
|
| 170 |
-
supported_modes: ["ANP/C"]
|
| 171 |
-
});
|
| 172 |
}
|
| 173 |
|
| 174 |
-
// --- CASE 2:
|
| 175 |
if (constraints && constraints.p2p_pin) {
|
| 176 |
const pin = constraints.p2p_pin.toString().trim();
|
| 177 |
-
|
| 178 |
|
| 179 |
-
|
| 180 |
-
.from('p2p_rooms')
|
| 181 |
-
.select('*')
|
| 182 |
-
.eq('pin', pin)
|
| 183 |
-
.eq('status', 'pending')
|
| 184 |
-
.maybeSingle();
|
| 185 |
|
| 186 |
-
|
| 187 |
-
return res.status(404).json({ error: "Active pairing room not found for this PIN." });
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
const { error: updateError } = await supabase
|
| 191 |
-
.from('p2p_rooms')
|
| 192 |
-
.update({
|
| 193 |
-
receiver_session_id: session_id,
|
| 194 |
-
receiver_pub_key: session_pub_key,
|
| 195 |
-
status: 'active'
|
| 196 |
-
})
|
| 197 |
-
.eq('room_id', room.room_id);
|
| 198 |
-
|
| 199 |
-
if (updateError) throw updateError;
|
| 200 |
|
| 201 |
room.receiver_session_id = session_id;
|
| 202 |
-
room.receiver_pub_key =
|
| 203 |
room.status = 'active';
|
| 204 |
-
localRoomCache.set(room.room_id, room);
|
| 205 |
-
|
| 206 |
-
//
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
body: JSON.stringify({
|
| 212 |
-
msg_type: "handshake_joined",
|
| 213 |
-
session_id: room.initiator_session_id,
|
| 214 |
-
receiver_session_id: session_id,
|
| 215 |
-
message: "Your peer has successfully entered your room. Bargaining coordinates are active."
|
| 216 |
-
})
|
| 217 |
-
}).catch(() => console.warn(`[P2P Tunnel] Handshake callback failed for initiator ${room.initiator_session_id}`));
|
| 218 |
-
}
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
p2p_role: "receiver",
|
| 223 |
-
session_id,
|
| 224 |
-
capabilities: ["p2p_bridge"],
|
| 225 |
-
supported_modes: ["ANP/C"]
|
| 226 |
-
});
|
| 227 |
}
|
| 228 |
|
| 229 |
-
// --- CASE 3:
|
| 230 |
const pin = await generateUniquePin();
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
.from('p2p_rooms')
|
| 235 |
-
.insert({
|
| 236 |
-
pin,
|
| 237 |
-
initiator_session_id: session_id,
|
| 238 |
-
initiator_pub_key: session_pub_key,
|
| 239 |
-
status: 'pending'
|
| 240 |
-
})
|
| 241 |
-
.select('*')
|
| 242 |
-
.single();
|
| 243 |
|
| 244 |
if (insertError) throw insertError;
|
|
|
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
return res.json({
|
| 249 |
-
status: "ACCEPTED",
|
| 250 |
-
p2p_role: "initiator",
|
| 251 |
-
p2p_pin: pin,
|
| 252 |
-
session_id,
|
| 253 |
-
capabilities: ["p2p_bridge"],
|
| 254 |
-
supported_modes: ["ANP/C"]
|
| 255 |
-
});
|
| 256 |
|
| 257 |
} catch (err) {
|
| 258 |
console.error("[Handshake Error]", err.message);
|
| 259 |
-
return res.status(500).json({
|
| 260 |
}
|
| 261 |
});
|
| 262 |
|
| 263 |
// ============================================================================
|
| 264 |
-
// ANP COUNTER ROUTE (Real-time Message Tunneling)
|
| 265 |
// ============================================================================
|
| 266 |
app.post('/anp/v1/counter', async (req, res) => {
|
| 267 |
-
const { session_id, turn, price, reason
|
|
|
|
|
|
|
| 268 |
|
| 269 |
try {
|
| 270 |
-
let room =
|
| 271 |
-
|
| 272 |
-
// 1. Read-Through local Cache first to bypass Postgres overhead
|
| 273 |
-
for (const cachedRoom of localRoomCache.values()) {
|
| 274 |
-
if ((cachedRoom.initiator_session_id === session_id || cachedRoom.receiver_session_id === session_id) && cachedRoom.status === 'active') {
|
| 275 |
-
room = cachedRoom;
|
| 276 |
-
break;
|
| 277 |
-
}
|
| 278 |
-
}
|
| 279 |
|
| 280 |
-
// 2. Fallback to Supabase if cache missed
|
| 281 |
if (!room) {
|
| 282 |
-
const { data, error } = await supabase
|
| 283 |
-
|
| 284 |
-
.select('*')
|
| 285 |
-
.or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`)
|
| 286 |
-
.eq('status', 'active')
|
| 287 |
-
.maybeSingle();
|
| 288 |
-
|
| 289 |
-
if (error || !data) {
|
| 290 |
-
return res.status(404).json({ error: "Active paired P2P session not found." });
|
| 291 |
-
}
|
| 292 |
room = data;
|
| 293 |
-
localRoomCache.set(room.room_id, room);
|
| 294 |
}
|
| 295 |
|
| 296 |
const isInitiator = room.initiator_session_id === session_id;
|
| 297 |
-
const senderPubKey = isInitiator ? room.initiator_pub_key : room.receiver_pub_key;
|
| 298 |
const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
|
| 299 |
-
const
|
| 300 |
|
| 301 |
-
//
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
buyer_sig,
|
| 305 |
-
senderPubKey
|
| 306 |
-
);
|
| 307 |
-
|
| 308 |
-
if (!isValid) {
|
| 309 |
-
return res.status(401).json({ error: "Cryptographic signature mismatch on turn payload." });
|
| 310 |
-
}
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
.
|
| 316 |
-
|
| 317 |
-
turn,
|
| 318 |
-
sender_session_id: session_id,
|
| 319 |
-
price,
|
| 320 |
-
reason,
|
| 321 |
-
signature: buyer_sig
|
| 322 |
-
});
|
| 323 |
-
|
| 324 |
-
if (msgError) throw msgError;
|
| 325 |
-
|
| 326 |
-
// Route payload instantly through the Registry callback to the target peer
|
| 327 |
-
if (targetCallbackToken) {
|
| 328 |
-
console.log(`[P2P Tunnel] Routing Turn ${turn} from ${session_id} ➔ ${targetSessionId}`);
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
headers: { 'Content-Type': 'application/json' },
|
| 333 |
-
body: JSON.stringify({
|
| 334 |
-
session_id: targetSessionId,
|
| 335 |
-
turn,
|
| 336 |
-
price,
|
| 337 |
-
message: reason,
|
| 338 |
-
buyer_sig,
|
| 339 |
-
timestamp: new Date().toISOString()
|
| 340 |
-
})
|
| 341 |
-
});
|
| 342 |
-
|
| 343 |
-
if (!fwd.ok) {
|
| 344 |
-
console.warn(`[P2P Tunnel] Registry rejected callback routing: ${await fwd.text()}`);
|
| 345 |
-
}
|
| 346 |
-
} else {
|
| 347 |
-
console.log(`[P2P Tunnel] Peer ${targetSessionId} has not registered a callback token yet.`);
|
| 348 |
}
|
| 349 |
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
});
|
| 356 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
} catch (err) {
|
| 358 |
console.error("[Counter Error]", err.message);
|
| 359 |
-
return res.status(500).json({
|
| 360 |
}
|
| 361 |
});
|
| 362 |
|
| 363 |
// ============================================================================
|
| 364 |
-
//
|
| 365 |
// ============================================================================
|
| 366 |
-
app.post('/anp/v1/
|
| 367 |
-
const { session_id, callback_token } = req.body;
|
| 368 |
-
|
| 369 |
try {
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
if (error || !room) {
|
| 377 |
-
return res.status(404).json({ error: "P2P Session not found." });
|
| 378 |
-
}
|
| 379 |
-
|
| 380 |
-
const isInitiator = room.initiator_session_id === session_id;
|
| 381 |
-
const updateField = isInitiator ? { initiator_callback_token: callback_token } : { receiver_callback_token: callback_token };
|
| 382 |
-
|
| 383 |
-
const { error: updateError } = await supabase
|
| 384 |
-
.from('p2p_rooms')
|
| 385 |
-
.update(updateField)
|
| 386 |
-
.eq('room_id', room.room_id);
|
| 387 |
-
|
| 388 |
-
if (updateError) throw updateError;
|
| 389 |
-
|
| 390 |
-
// Dynamically update the cached room record
|
| 391 |
-
if (localRoomCache.has(room.room_id)) {
|
| 392 |
-
const cached = localRoomCache.get(room.room_id);
|
| 393 |
-
if (isInitiator) cached.initiator_callback_token = callback_token;
|
| 394 |
-
else cached.receiver_callback_token = callback_token;
|
| 395 |
-
}
|
| 396 |
-
|
| 397 |
-
// Also check if this session registered a permanent handle, if so, update its token
|
| 398 |
-
await supabase
|
| 399 |
-
.from('p2p_handles')
|
| 400 |
-
.update({ callback_token })
|
| 401 |
-
.eq('session_id', session_id);
|
| 402 |
-
|
| 403 |
-
console.log(`[Registry Link] Registered callback token for session ${session_id}`);
|
| 404 |
-
return res.json({ status: "REGISTERED", session_id });
|
| 405 |
-
|
| 406 |
-
} catch (err) {
|
| 407 |
-
console.error("[Exit Token Register Error]", err.message);
|
| 408 |
-
return res.status(500).json({ error: "Failed to register active callback token." });
|
| 409 |
}
|
| 410 |
});
|
| 411 |
|
|
@@ -414,20 +345,25 @@ app.post('/anp/v1/exit', async (req, res) => {
|
|
| 414 |
// ============================================================================
|
| 415 |
app.listen(PORT, async () => {
|
| 416 |
console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`);
|
| 417 |
-
|
| 418 |
|
| 419 |
try {
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
|
|
|
|
|
|
|
|
|
| 429 |
} catch (e) {
|
| 430 |
-
console.error(`[-] Failed to self-register ginger
|
| 431 |
-
console.error(` Ensure you claimed 'ginger.anp' on the dashboard first using the matching SELLER_PRIVATE_KEY.`);
|
| 432 |
}
|
| 433 |
-
});
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
require('dotenv').config();
|
| 2 |
const express = require('express');
|
| 3 |
+
const fs = require('fs');
|
| 4 |
+
const path = require('path');
|
| 5 |
+
const https = require('https');
|
| 6 |
+
const os = require('os');
|
| 7 |
const { createClient } = require('@supabase/supabase-js');
|
| 8 |
+
const { ClinchCore, NegotiationState } = require('clinch-core');
|
| 9 |
|
| 10 |
const app = express();
|
| 11 |
app.use(express.json());
|
|
|
|
| 16 |
const PORT = process.env.PORT || 7860;
|
| 17 |
const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
|
| 18 |
const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
|
| 19 |
+
const REGISTRY_URL = process.env.REGISTRY_URL || 'https://registry.clinch.network';
|
| 20 |
|
| 21 |
const SUPABASE_URL = process.env.SUPABASE_URL;
|
| 22 |
const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
|
|
|
|
| 28 |
|
| 29 |
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
|
| 30 |
|
| 31 |
+
// Protocol v0.2.0 Core Initialization
|
| 32 |
+
const core = new ClinchCore({
|
| 33 |
+
registryUrl: REGISTRY_URL,
|
| 34 |
privateKeyHex: SELLER_PRIV_KEY
|
| 35 |
});
|
| 36 |
|
| 37 |
+
core.on('log', msg => console.log(`[Ginger Protocol] ${msg}`));
|
| 38 |
+
|
| 39 |
+
// ============================================================================
|
| 40 |
+
// AI MEDIATOR (QWEN 1.5B GGUF on CPU)
|
| 41 |
+
// ============================================================================
|
| 42 |
+
const MODEL_DIR = path.join(__dirname, 'models');
|
| 43 |
+
const MODEL_PATH = path.join(MODEL_DIR, 'qwen2.5-1.5b-instruct-q4_k_m.gguf');
|
| 44 |
+
const MODEL_URL = "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf";
|
| 45 |
+
|
| 46 |
+
let cachedLlamaModel = null;
|
| 47 |
+
let cachedLlamaContext = null;
|
| 48 |
+
|
| 49 |
+
function downloadModel() {
|
| 50 |
+
return new Promise((resolve, reject) => {
|
| 51 |
+
if (!fs.existsSync(MODEL_DIR)) fs.mkdirSync(MODEL_DIR, { recursive: true });
|
| 52 |
+
console.log(`[AI] Downloading Qwen 1.5B Mediator Model (1.1GB)...`);
|
| 53 |
+
|
| 54 |
+
const file = fs.createWriteStream(MODEL_PATH);
|
| 55 |
+
const request = (currentUrl) => {
|
| 56 |
+
https.get(currentUrl, (response) => {
|
| 57 |
+
if ([301, 302, 303, 307, 308].includes(response.statusCode)) return request(response.headers.location);
|
| 58 |
+
if (response.statusCode !== 200) return reject(new Error(`Download failed: ${response.statusCode}`));
|
| 59 |
+
|
| 60 |
+
const total = parseInt(response.headers['content-length'], 10);
|
| 61 |
+
let downloaded = 0;
|
| 62 |
+
|
| 63 |
+
response.on('data', (chunk) => {
|
| 64 |
+
downloaded += chunk.length;
|
| 65 |
+
const percent = total ? ((downloaded / total) * 100).toFixed(1) : (downloaded / 1024 / 1024).toFixed(1);
|
| 66 |
+
process.stdout.write(`\r[AI] Fetching model... ${percent}%`);
|
| 67 |
+
});
|
| 68 |
+
|
| 69 |
+
response.pipe(file);
|
| 70 |
+
file.on('finish', () => {
|
| 71 |
+
console.log("\n[AI] ✓ Download complete!");
|
| 72 |
+
file.close(resolve);
|
| 73 |
+
});
|
| 74 |
+
}).on('error', (err) => { fs.unlink(MODEL_PATH, () => reject(err)); });
|
| 75 |
+
};
|
| 76 |
+
request(MODEL_URL);
|
| 77 |
+
});
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
async function getMediatorAI() {
|
| 81 |
+
if (cachedLlamaModel) return;
|
| 82 |
+
if (!fs.existsSync(MODEL_PATH)) await downloadModel();
|
| 83 |
+
|
| 84 |
+
const nodeLlama = await import('node-llama-cpp');
|
| 85 |
+
const threads = Math.max(2, os.cpus().length - 1);
|
| 86 |
+
|
| 87 |
+
console.log(`[AI] Loading Qwen 1.5B into RAM with ${threads} threads...`);
|
| 88 |
+
const llama = await nodeLlama.getLlama();
|
| 89 |
+
cachedLlamaModel = await llama.loadModel({ modelPath: MODEL_PATH });
|
| 90 |
+
cachedLlamaContext = await cachedLlamaModel.createContext({ contextSize: 2048, threads });
|
| 91 |
+
console.log(`[AI] Mediator Engine Hot.`);
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
async function mediatePrice(currentPrice, item) {
|
| 95 |
+
const nodeLlama = await import('node-llama-cpp');
|
| 96 |
+
const systemPrompt = `You are the Ginger P2P AI Mediator. Two human/agent peers are deadlocked negotiating a price for "${item}".
|
| 97 |
+
The current proposed price is $${currentPrice}.
|
| 98 |
+
Propose a fair middle-ground compromise to break the deadlock.
|
| 99 |
+
Output ONLY valid JSON matching exactly: {"price": number, "message": "string"}`;
|
| 100 |
+
|
| 101 |
+
const session = new nodeLlama.LlamaChatSession({
|
| 102 |
+
contextSequence: cachedLlamaContext.getSequence(),
|
| 103 |
+
systemPrompt,
|
| 104 |
+
chatWrapper: new nodeLlama.ChatMLChatWrapper()
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
let responseText = "";
|
| 108 |
+
await session.prompt("Suggest a compromise.", { maxTokens: 200, onTextChunk: (chunk) => { responseText += chunk; } });
|
| 109 |
+
|
| 110 |
+
try {
|
| 111 |
+
const clean = responseText.replace(/```json|```/g, "").trim();
|
| 112 |
+
return JSON.parse(clean);
|
| 113 |
+
} catch (e) {
|
| 114 |
+
// Fallback calculation if LLM format breaks
|
| 115 |
+
return { price: currentPrice * 0.9, message: "Ginger AI suggests a 10% compromise to keep the deal moving." };
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
|
| 119 |
// ============================================================================
|
| 120 |
// IN-MEMORY CACHE & GC DAEMON
|
| 121 |
// ============================================================================
|
| 122 |
const localRoomCache = new Map();
|
| 123 |
|
|
|
|
| 124 |
setInterval(async () => {
|
| 125 |
console.log("[Ginger GC] Initiating scheduled sweeping daemon...");
|
| 126 |
const now = Date.now();
|
| 127 |
let swept = 0;
|
| 128 |
|
|
|
|
| 129 |
for (const [roomId, room] of localRoomCache.entries()) {
|
| 130 |
if (now - new Date(room.created_at).getTime() > 1800000) {
|
| 131 |
localRoomCache.delete(roomId);
|
|
|
|
| 133 |
}
|
| 134 |
}
|
| 135 |
|
|
|
|
| 136 |
const oneHourAgo = new Date(now - 3600000).toISOString();
|
| 137 |
+
const { error } = await supabase.from('p2p_rooms').delete().eq('status', 'pending').lt('created_at', oneHourAgo);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
|
| 140 |
else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`);
|
| 141 |
}, 600000);
|
| 142 |
|
|
|
|
| 143 |
async function generateUniquePin() {
|
| 144 |
let pin;
|
| 145 |
let exists = true;
|
|
|
|
| 155 |
// PUBLIC ROUTE: PERMANENT HANDLE SELF-REGISTRATION
|
| 156 |
// ============================================================================
|
| 157 |
app.post('/anp/v1/register-handle', async (req, res) => {
|
| 158 |
+
const { handle, session_id, session_pub_key } = req.body;
|
| 159 |
|
| 160 |
if (!handle || !session_id || !session_pub_key) {
|
| 161 |
+
return res.status(400).json({ error: "Missing required parameters." });
|
| 162 |
}
|
| 163 |
|
| 164 |
const normalizedHandle = handle.toLowerCase().trim();
|
| 165 |
|
| 166 |
try {
|
| 167 |
+
const { error } = await supabase.from('p2p_handles').upsert({
|
| 168 |
+
handle: normalizedHandle,
|
| 169 |
+
session_id,
|
| 170 |
+
pub_key: session_pub_key, // Used for async-callback routing in v0.2.0
|
| 171 |
+
updated_at: new Date().toISOString()
|
| 172 |
+
});
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
if (error) throw error;
|
| 175 |
+
console.log(`[Handle Registry] Binded permanent handle: ${normalizedHandle} ➔ ${session_pub_key.substring(0,8)}`);
|
| 176 |
return res.json({ status: "BOUND", handle: normalizedHandle });
|
| 177 |
|
| 178 |
} catch (err) {
|
|
|
|
| 179 |
return res.status(500).json({ error: "Failed to map permanent handle." });
|
| 180 |
}
|
| 181 |
});
|
|
|
|
| 184 |
// ANP HANDSHAKE ROUTE (Creation & Joining - PIN vs Handles)
|
| 185 |
// ============================================================================
|
| 186 |
app.post('/anp/v1/handshake', async (req, res) => {
|
| 187 |
+
// Note: In v0.2.0, the Registry Proxy automatically injects 'buyer_pub_key'
|
| 188 |
+
const { session_id, buyer_pub_key, constraints } = req.body;
|
| 189 |
|
| 190 |
+
// Explicitly sync seller's local state machine
|
| 191 |
+
core.registerIncomingSession(session_id, buyer_pub_key, constraints);
|
| 192 |
+
|
| 193 |
try {
|
| 194 |
+
// --- CASE 1: JOINING A PERMANENT HANDLE ---
|
| 195 |
if (constraints && constraints.target_handle) {
|
| 196 |
const handle = constraints.target_handle.toLowerCase().trim();
|
| 197 |
+
const { data: persistentHost, error: handleErr } = await supabase.from('p2p_handles').select('*').eq('handle', handle).maybeSingle();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline.` });
|
|
|
|
|
|
|
| 200 |
|
|
|
|
| 201 |
const pin = await generateUniquePin();
|
| 202 |
+
const { data: room, error: roomErr } = await supabase.from('p2p_rooms').insert({
|
| 203 |
+
pin,
|
| 204 |
+
initiator_session_id: persistentHost.session_id,
|
| 205 |
+
initiator_pub_key: persistentHost.pub_key,
|
| 206 |
+
receiver_session_id: session_id,
|
| 207 |
+
receiver_pub_key: buyer_pub_key,
|
| 208 |
+
status: 'active'
|
| 209 |
+
}).select('*').single();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
if (roomErr) throw roomErr;
|
| 212 |
+
localRoomCache.set(room.room_id, room);
|
| 213 |
+
|
| 214 |
+
// Notify the Host asynchronously via Registry
|
| 215 |
+
await core.request('/api/route/async-callback', 'POST', {
|
| 216 |
+
buyer_pub_key: persistentHost.pub_key,
|
| 217 |
+
payload: {
|
| 218 |
+
type: "COUNTER",
|
| 219 |
+
session_id: persistentHost.session_id,
|
| 220 |
+
price: constraints.max_budget || 0,
|
| 221 |
+
turn: 2,
|
| 222 |
+
message: `Peer targeting your handle '${handle}' has joined. Room active.`
|
| 223 |
+
}
|
| 224 |
+
}).catch(() => {});
|
| 225 |
+
|
| 226 |
+
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, constraints.max_budget || 0, 2);
|
| 227 |
+
return res.json({ type: "COUNTER", price: constraints.max_budget || 0, turn: 2, message: `Connected to ${handle}.` });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
}
|
| 229 |
|
| 230 |
+
// --- CASE 2: JOINING VIA 6-DIGIT PIN ---
|
| 231 |
if (constraints && constraints.p2p_pin) {
|
| 232 |
const pin = constraints.p2p_pin.toString().trim();
|
| 233 |
+
const { data: room, error } = await supabase.from('p2p_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle();
|
| 234 |
|
| 235 |
+
if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
await supabase.from('p2p_rooms').update({ receiver_session_id: session_id, receiver_pub_key: buyer_pub_key, status: 'active' }).eq('room_id', room.room_id);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
room.receiver_session_id = session_id;
|
| 240 |
+
room.receiver_pub_key = buyer_pub_key;
|
| 241 |
room.status = 'active';
|
| 242 |
+
localRoomCache.set(room.room_id, room);
|
| 243 |
+
|
| 244 |
+
// Notify Initiator asynchronously
|
| 245 |
+
await core.request('/api/route/async-callback', 'POST', {
|
| 246 |
+
buyer_pub_key: room.initiator_pub_key,
|
| 247 |
+
payload: { type: "COUNTER", session_id: room.initiator_session_id, price: constraints.max_budget || 0, turn: 2, message: "Peer has entered the room. Bargaining active." }
|
| 248 |
+
}).catch(() => {});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, constraints.max_budget || 0, 2);
|
| 251 |
+
return res.json({ type: "COUNTER", price: constraints.max_budget || 0, turn: 2, message: `Joined room ${pin}.` });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
}
|
| 253 |
|
| 254 |
+
// --- CASE 3: CREATING TEMPORARY ROOM ---
|
| 255 |
const pin = await generateUniquePin();
|
| 256 |
+
const { data: newRoom, error: insertError } = await supabase.from('p2p_rooms').insert({
|
| 257 |
+
pin, initiator_session_id: session_id, initiator_pub_key: buyer_pub_key, status: 'pending'
|
| 258 |
+
}).select('*').single();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
if (insertError) throw insertError;
|
| 261 |
+
localRoomCache.set(newRoom.room_id, newRoom);
|
| 262 |
|
| 263 |
+
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, 0, 2);
|
| 264 |
+
return res.json({ type: "COUNTER", price: 0, turn: 2, message: `Room created. Share this PIN with your peer: ${pin}` });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
} catch (err) {
|
| 267 |
console.error("[Handshake Error]", err.message);
|
| 268 |
+
return res.status(500).json({ type: 'CANCEL', reason: "Broker internal error." });
|
| 269 |
}
|
| 270 |
});
|
| 271 |
|
| 272 |
// ============================================================================
|
| 273 |
+
// ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation)
|
| 274 |
// ============================================================================
|
| 275 |
app.post('/anp/v1/counter', async (req, res) => {
|
| 276 |
+
const { session_id, turn, price, reason } = req.body;
|
| 277 |
+
const currentTurn = turn || 2;
|
| 278 |
+
const nextTurn = currentTurn + 1;
|
| 279 |
|
| 280 |
try {
|
| 281 |
+
let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
|
|
|
| 283 |
if (!room) {
|
| 284 |
+
const { data, error } = await supabase.from('p2p_rooms').select('*').or(`initiator_session_id.eq.${session_id},receiver_session_id.eq.${session_id}`).eq('status', 'active').maybeSingle();
|
| 285 |
+
if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
room = data;
|
| 287 |
+
localRoomCache.set(room.room_id, room);
|
| 288 |
}
|
| 289 |
|
| 290 |
const isInitiator = room.initiator_session_id === session_id;
|
|
|
|
| 291 |
const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
|
| 292 |
+
const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key;
|
| 293 |
|
| 294 |
+
// --- AI MEDIATION INTERCEPT ---
|
| 295 |
+
let routedPrice = price;
|
| 296 |
+
let routedMessage = reason;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
+
if (reason && reason.toLowerCase().includes('@mediate')) {
|
| 299 |
+
console.log(`[AI] Mediation requested by ${session_id}`);
|
| 300 |
+
const aiSuggestion = await mediatePrice(price, "P2P Service");
|
| 301 |
+
routedPrice = aiSuggestion.price;
|
| 302 |
+
routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
// Log mediation occurrence
|
| 305 |
+
await supabase.from('p2p_messages').insert({ room_id: room.room_id, turn: currentTurn, sender_session_id: 'ginger_ai', price: routedPrice, reason: routedMessage });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
}
|
| 307 |
|
| 308 |
+
// --- PUSH ASYNC CALLBACK TO PEER ---
|
| 309 |
+
await core.request('/api/route/async-callback', 'POST', {
|
| 310 |
+
buyer_pub_key: targetPubKey,
|
| 311 |
+
payload: {
|
| 312 |
+
type: "COUNTER",
|
| 313 |
+
session_id: targetSessionId,
|
| 314 |
+
turn: nextTurn,
|
| 315 |
+
price: routedPrice,
|
| 316 |
+
message: routedMessage
|
| 317 |
+
}
|
| 318 |
});
|
| 319 |
|
| 320 |
+
// --- ACKNOWLEDGE SENDER ---
|
| 321 |
+
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn);
|
| 322 |
+
return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." });
|
| 323 |
+
|
| 324 |
} catch (err) {
|
| 325 |
console.error("[Counter Error]", err.message);
|
| 326 |
+
return res.status(500).json({ type: 'CANCEL', reason: "Routing failed." });
|
| 327 |
}
|
| 328 |
});
|
| 329 |
|
| 330 |
// ============================================================================
|
| 331 |
+
// BILATERAL SIGNATURE HANDLER
|
| 332 |
// ============================================================================
|
| 333 |
+
app.post('/anp/v1/sign_request', (req, res) => {
|
|
|
|
|
|
|
| 334 |
try {
|
| 335 |
+
// Ginger acts as the notary for the P2P room
|
| 336 |
+
const sig = core.signAsSeller(req.body.artifact);
|
| 337 |
+
res.json({ sellerSignature: sig });
|
| 338 |
+
} catch (e) {
|
| 339 |
+
res.status(400).json({ error: e.message });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
}
|
| 341 |
});
|
| 342 |
|
|
|
|
| 345 |
// ============================================================================
|
| 346 |
app.listen(PORT, async () => {
|
| 347 |
console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`);
|
| 348 |
+
console.log(` Stable Public Endpoint: ${PUBLIC_ENDPOINT}\n`);
|
| 349 |
|
| 350 |
try {
|
| 351 |
+
console.log("⏳ Initializing Protocol Core (PoW Handshake)...");
|
| 352 |
+
await core.initialize();
|
| 353 |
+
|
| 354 |
+
// Refresh token every 5 days before the 7-day expiry
|
| 355 |
+
setInterval(() => core.initialize().catch(()=>console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
|
| 356 |
+
|
| 357 |
+
await core.registerNode(`${PUBLIC_ENDPOINT}/anp/v1`, ['p2p_bridge', 'mediation', 'scheduling'], ['p2p_bridge', 'room_routing', 'ai_mediator']);
|
| 358 |
+
console.log("✓ Successfully registered 'ginger.anp' to the Network.");
|
| 359 |
+
|
| 360 |
+
// Warm up the AI Mediator in the background
|
| 361 |
+
getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
|
| 362 |
+
|
| 363 |
} catch (e) {
|
| 364 |
+
console.error(`[-] Failed to self-register ginger node: ${e.message}`);
|
|
|
|
| 365 |
}
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
process.on('SIGINT', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
|
| 369 |
+
process.on('SIGTERM', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
|