Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -283,4 +283,107 @@ app.post('/anp/v1/handshake', async (req, res) => {
|
|
| 283 |
}
|
| 284 |
});
|
| 285 |
|
| 286 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
}
|
| 284 |
});
|
| 285 |
|
| 286 |
+
// ============================================================================
|
| 287 |
+
// ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation)
|
| 288 |
+
// ============================================================================
|
| 289 |
+
app.post('/anp/v1/counter', async (req, res) => {
|
| 290 |
+
const { session_id, turn, price, reason } = req.body;
|
| 291 |
+
const currentTurn = turn || 2;
|
| 292 |
+
const nextTurn = currentTurn + 1;
|
| 293 |
+
|
| 294 |
+
try {
|
| 295 |
+
let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
|
| 296 |
+
|
| 297 |
+
if (!room) {
|
| 298 |
+
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();
|
| 299 |
+
if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
|
| 300 |
+
room = data;
|
| 301 |
+
localRoomCache.set(room.room_id, room);
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
const isInitiator = room.initiator_session_id === session_id;
|
| 305 |
+
const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
|
| 306 |
+
const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key;
|
| 307 |
+
|
| 308 |
+
// --- AI MEDIATION INTERCEPT ---
|
| 309 |
+
let routedPrice = price;
|
| 310 |
+
let routedMessage = reason;
|
| 311 |
+
|
| 312 |
+
if (reason && reason.toLowerCase().includes('@mediate')) {
|
| 313 |
+
console.log(`[AI] Mediation requested by ${session_id}`);
|
| 314 |
+
const aiSuggestion = await mediatePrice(price, "P2P Service");
|
| 315 |
+
routedPrice = aiSuggestion.price;
|
| 316 |
+
routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
|
| 317 |
+
|
| 318 |
+
// Log mediation occurrence
|
| 319 |
+
await supabase.from('p2p_messages').insert({ room_id: room.room_id, turn: currentTurn, sender_session_id: 'ginger_ai', price: routedPrice, reason: routedMessage });
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
// --- PUSH ASYNC CALLBACK TO PEER ---
|
| 323 |
+
await core.request('/api/route/async-callback', 'POST', {
|
| 324 |
+
buyer_pub_key: targetPubKey,
|
| 325 |
+
payload: {
|
| 326 |
+
type: "COUNTER",
|
| 327 |
+
session_id: targetSessionId,
|
| 328 |
+
turn: nextTurn,
|
| 329 |
+
price: routedPrice,
|
| 330 |
+
message: routedMessage
|
| 331 |
+
}
|
| 332 |
+
});
|
| 333 |
+
|
| 334 |
+
// --- ACKNOWLEDGE SENDER ---
|
| 335 |
+
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn);
|
| 336 |
+
return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." });
|
| 337 |
+
|
| 338 |
+
} catch (err) {
|
| 339 |
+
console.error("[Counter Error]", err.message);
|
| 340 |
+
return res.status(500).json({ type: 'CANCEL', reason: "Routing failed." });
|
| 341 |
+
}
|
| 342 |
+
});
|
| 343 |
+
|
| 344 |
+
// ============================================================================
|
| 345 |
+
// BILATERAL SIGNATURE HANDLER
|
| 346 |
+
// ============================================================================
|
| 347 |
+
app.post('/anp/v1/sign_request', (req, res) => {
|
| 348 |
+
try {
|
| 349 |
+
const sig = core.signAsSeller(req.body.artifact);
|
| 350 |
+
res.json({ sellerSignature: sig });
|
| 351 |
+
} catch (e) {
|
| 352 |
+
res.status(400).json({ error: e.message });
|
| 353 |
+
}
|
| 354 |
+
});
|
| 355 |
+
|
| 356 |
+
// ============================================================================
|
| 357 |
+
// BOOT
|
| 358 |
+
// ============================================================================
|
| 359 |
+
app.listen(PORT, async () => {
|
| 360 |
+
console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`);
|
| 361 |
+
console.log(` Stable Public Endpoint: ${PUBLIC_ENDPOINT}\n`);
|
| 362 |
+
|
| 363 |
+
try {
|
| 364 |
+
console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)...");
|
| 365 |
+
await core.initialize();
|
| 366 |
+
|
| 367 |
+
// Refresh token every 5 days before the 7-day expiry
|
| 368 |
+
setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
|
| 369 |
+
|
| 370 |
+
// [FIX]: Passed target domain (AGENT_ID) as first arg, switched 'tags' option to 'supported_modes'
|
| 371 |
+
await core.registerNode(
|
| 372 |
+
AGENT_ID,
|
| 373 |
+
`${PUBLIC_ENDPOINT}/anp/v1`,
|
| 374 |
+
['p2p_bridge', 'mediation', 'scheduling'],
|
| 375 |
+
['p2p_bridge', 'room_routing', 'ai_mediator'],
|
| 376 |
+
{ supported_modes: ['ANP/C'] }
|
| 377 |
+
);
|
| 378 |
+
console.log(`✓ Successfully registered '${AGENT_ID}' to the Network.`);
|
| 379 |
+
|
| 380 |
+
// Load AI model in the background — mediatePrice() handles the not-ready state safely
|
| 381 |
+
getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
|
| 382 |
+
|
| 383 |
+
} catch (e) {
|
| 384 |
+
console.error(`[-] Failed to self-register ginger node: ${e.message}`);
|
| 385 |
+
}
|
| 386 |
+
});
|
| 387 |
+
|
| 388 |
+
process.on('SIGINT', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
|
| 389 |
+
process.on('SIGTERM', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
|