Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -16,6 +16,7 @@ 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 |
|
| 20 |
const SUPABASE_URL = process.env.SUPABASE_URL;
|
| 21 |
const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
|
|
@@ -27,7 +28,7 @@ if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !PUBLIC_ENDPOINT || !SELLER_PRIV_K
|
|
| 27 |
|
| 28 |
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
|
| 29 |
|
| 30 |
-
// Protocol v0.2.
|
| 31 |
// (Dynamic Firebase Discovery handles the registryURL automatically)
|
| 32 |
const core = new ClinchCore({
|
| 33 |
privateKeyHex: SELLER_PRIV_KEY
|
|
@@ -198,10 +199,6 @@ app.post('/anp/v1/handshake', async (req, res) => {
|
|
| 198 |
// Blind Key Pass — log receipt so sellers can audit per-session
|
| 199 |
if (blind_auth_token) {
|
| 200 |
console.log(`[Auth] Blind key token received | session: ${session_id} | buyer: ${buyer_pub_key?.substring(0, 8)}...`);
|
| 201 |
-
// Add your own gate here if this node requires a valid token, e.g.:
|
| 202 |
-
// if (blind_auth_token !== process.env.EXPECTED_BUYER_TOKEN) {
|
| 203 |
-
// return res.status(403).json({ type: 'CANCEL', reason: 'Invalid auth token.' });
|
| 204 |
-
// }
|
| 205 |
}
|
| 206 |
|
| 207 |
// Explicitly sync seller's local state machine
|
|
@@ -286,105 +283,4 @@ app.post('/anp/v1/handshake', async (req, res) => {
|
|
| 286 |
}
|
| 287 |
});
|
| 288 |
|
| 289 |
-
//
|
| 290 |
-
// ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation)
|
| 291 |
-
// ============================================================================
|
| 292 |
-
app.post('/anp/v1/counter', async (req, res) => {
|
| 293 |
-
const { session_id, turn, price, reason } = req.body;
|
| 294 |
-
const currentTurn = turn || 2;
|
| 295 |
-
const nextTurn = currentTurn + 1;
|
| 296 |
-
|
| 297 |
-
try {
|
| 298 |
-
let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
|
| 299 |
-
|
| 300 |
-
if (!room) {
|
| 301 |
-
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();
|
| 302 |
-
if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
|
| 303 |
-
room = data;
|
| 304 |
-
localRoomCache.set(room.room_id, room);
|
| 305 |
-
}
|
| 306 |
-
|
| 307 |
-
const isInitiator = room.initiator_session_id === session_id;
|
| 308 |
-
const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
|
| 309 |
-
const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key;
|
| 310 |
-
|
| 311 |
-
// --- AI MEDIATION INTERCEPT ---
|
| 312 |
-
let routedPrice = price;
|
| 313 |
-
let routedMessage = reason;
|
| 314 |
-
|
| 315 |
-
if (reason && reason.toLowerCase().includes('@mediate')) {
|
| 316 |
-
console.log(`[AI] Mediation requested by ${session_id}`);
|
| 317 |
-
const aiSuggestion = await mediatePrice(price, "P2P Service");
|
| 318 |
-
routedPrice = aiSuggestion.price;
|
| 319 |
-
routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
|
| 320 |
-
|
| 321 |
-
// Log mediation occurrence
|
| 322 |
-
await supabase.from('p2p_messages').insert({ room_id: room.room_id, turn: currentTurn, sender_session_id: 'ginger_ai', price: routedPrice, reason: routedMessage });
|
| 323 |
-
}
|
| 324 |
-
|
| 325 |
-
// --- PUSH ASYNC CALLBACK TO PEER ---
|
| 326 |
-
await core.request('/api/route/async-callback', 'POST', {
|
| 327 |
-
buyer_pub_key: targetPubKey,
|
| 328 |
-
payload: {
|
| 329 |
-
type: "COUNTER",
|
| 330 |
-
session_id: targetSessionId,
|
| 331 |
-
turn: nextTurn,
|
| 332 |
-
price: routedPrice,
|
| 333 |
-
message: routedMessage
|
| 334 |
-
}
|
| 335 |
-
});
|
| 336 |
-
|
| 337 |
-
// --- ACKNOWLEDGE SENDER ---
|
| 338 |
-
core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn);
|
| 339 |
-
return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." });
|
| 340 |
-
|
| 341 |
-
} catch (err) {
|
| 342 |
-
console.error("[Counter Error]", err.message);
|
| 343 |
-
return res.status(500).json({ type: 'CANCEL', reason: "Routing failed." });
|
| 344 |
-
}
|
| 345 |
-
});
|
| 346 |
-
|
| 347 |
-
// ============================================================================
|
| 348 |
-
// BILATERAL SIGNATURE HANDLER
|
| 349 |
-
// ============================================================================
|
| 350 |
-
app.post('/anp/v1/sign_request', (req, res) => {
|
| 351 |
-
try {
|
| 352 |
-
const sig = core.signAsSeller(req.body.artifact);
|
| 353 |
-
res.json({ sellerSignature: sig });
|
| 354 |
-
} catch (e) {
|
| 355 |
-
res.status(400).json({ error: e.message });
|
| 356 |
-
}
|
| 357 |
-
});
|
| 358 |
-
|
| 359 |
-
// ============================================================================
|
| 360 |
-
// BOOT
|
| 361 |
-
// ============================================================================
|
| 362 |
-
app.listen(PORT, async () => {
|
| 363 |
-
console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`);
|
| 364 |
-
console.log(` Stable Public Endpoint: ${PUBLIC_ENDPOINT}\n`);
|
| 365 |
-
|
| 366 |
-
try {
|
| 367 |
-
console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)...");
|
| 368 |
-
await core.initialize();
|
| 369 |
-
|
| 370 |
-
// Refresh token every 5 days before the 7-day expiry
|
| 371 |
-
setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
|
| 372 |
-
|
| 373 |
-
await core.registerNode(
|
| 374 |
-
`${PUBLIC_ENDPOINT}/anp/v1`,
|
| 375 |
-
['p2p_bridge', 'mediation', 'scheduling'],
|
| 376 |
-
['p2p_bridge', 'room_routing', 'ai_mediator'],
|
| 377 |
-
{ tags: ['p2p', 'ginger', 'ai-mediation', 'room-broker'] }
|
| 378 |
-
);
|
| 379 |
-
console.log("✓ Successfully registered 'ginger.anp' to the Network.");
|
| 380 |
-
|
| 381 |
-
// Load AI model in the background — mediatePrice() handles the not-ready state safely
|
| 382 |
-
getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
|
| 383 |
-
|
| 384 |
-
} catch (e) {
|
| 385 |
-
console.error(`[-] Failed to self-register ginger node: ${e.message}`);
|
| 386 |
-
}
|
| 387 |
-
});
|
| 388 |
-
|
| 389 |
-
process.on('SIGINT', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
|
| 390 |
-
process.on('SIGTERM', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
|
|
|
|
| 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 AGENT_ID = process.env.AGENT_ID || 'ginger.anp'; // [FIX]: Added target ID tracking
|
| 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.1 Core Initialization
|
| 32 |
// (Dynamic Firebase Discovery handles the registryURL automatically)
|
| 33 |
const core = new ClinchCore({
|
| 34 |
privateKeyHex: SELLER_PRIV_KEY
|
|
|
|
| 199 |
// Blind Key Pass — log receipt so sellers can audit per-session
|
| 200 |
if (blind_auth_token) {
|
| 201 |
console.log(`[Auth] Blind key token received | session: ${session_id} | buyer: ${buyer_pub_key?.substring(0, 8)}...`);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
}
|
| 203 |
|
| 204 |
// Explicitly sync seller's local state machine
|
|
|
|
| 283 |
}
|
| 284 |
});
|
| 285 |
|
| 286 |
+
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|