Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -27,8 +27,8 @@ 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.0 Core Initialization
|
| 31 |
-
// (Dynamic Firebase Discovery handles the registryURL automatically
|
| 32 |
const core = new ClinchCore({
|
| 33 |
privateKeyHex: SELLER_PRIV_KEY
|
| 34 |
});
|
|
@@ -44,27 +44,28 @@ const MODEL_URL = "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolv
|
|
| 44 |
|
| 45 |
let cachedLlamaModel = null;
|
| 46 |
let cachedLlamaContext = null;
|
|
|
|
| 47 |
|
| 48 |
function downloadModel() {
|
| 49 |
return new Promise((resolve, reject) => {
|
| 50 |
if (!fs.existsSync(MODEL_DIR)) fs.mkdirSync(MODEL_DIR, { recursive: true });
|
| 51 |
console.log(`[AI] Downloading Qwen 1.5B Mediator Model (1.1GB)...`);
|
| 52 |
-
|
| 53 |
const file = fs.createWriteStream(MODEL_PATH);
|
| 54 |
const request = (currentUrl) => {
|
| 55 |
https.get(currentUrl, (response) => {
|
| 56 |
if ([301, 302, 303, 307, 308].includes(response.statusCode)) return request(response.headers.location);
|
| 57 |
if (response.statusCode !== 200) return reject(new Error(`Download failed: ${response.statusCode}`));
|
| 58 |
-
|
| 59 |
const total = parseInt(response.headers['content-length'], 10);
|
| 60 |
let downloaded = 0;
|
| 61 |
-
|
| 62 |
response.on('data', (chunk) => {
|
| 63 |
downloaded += chunk.length;
|
| 64 |
const percent = total ? ((downloaded / total) * 100).toFixed(1) : (downloaded / 1024 / 1024).toFixed(1);
|
| 65 |
process.stdout.write(`\r[AI] Fetching model... ${percent}%`);
|
| 66 |
});
|
| 67 |
-
|
| 68 |
response.pipe(file);
|
| 69 |
file.on('finish', () => {
|
| 70 |
console.log("\n[AI] ✓ Download complete!");
|
|
@@ -82,15 +83,25 @@ async function getMediatorAI() {
|
|
| 82 |
|
| 83 |
const nodeLlama = await import('node-llama-cpp');
|
| 84 |
const threads = Math.max(2, os.cpus().length - 1);
|
| 85 |
-
|
| 86 |
console.log(`[AI] Loading Qwen 1.5B into RAM with ${threads} threads...`);
|
| 87 |
const llama = await nodeLlama.getLlama();
|
| 88 |
cachedLlamaModel = await llama.loadModel({ modelPath: MODEL_PATH });
|
| 89 |
cachedLlamaContext = await cachedLlamaModel.createContext({ contextSize: 2048, threads });
|
|
|
|
| 90 |
console.log(`[AI] Mediator Engine Hot.`);
|
| 91 |
}
|
| 92 |
|
| 93 |
async function mediatePrice(currentPrice, item) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
const nodeLlama = await import('node-llama-cpp');
|
| 95 |
const systemPrompt = `You are the Ginger P2P AI Mediator. Two human/agent peers are deadlocked negotiating a price for "${item}".
|
| 96 |
The current proposed price is $${currentPrice}.
|
|
@@ -105,7 +116,7 @@ Output ONLY valid JSON matching exactly: {"price": number, "message": "string"}`
|
|
| 105 |
|
| 106 |
let responseText = "";
|
| 107 |
await session.prompt("Suggest a compromise.", { maxTokens: 200, onTextChunk: (chunk) => { responseText += chunk; } });
|
| 108 |
-
|
| 109 |
try {
|
| 110 |
const clean = responseText.replace(/```json|```/g, "").trim();
|
| 111 |
return JSON.parse(clean);
|
|
@@ -165,7 +176,7 @@ app.post('/anp/v1/register-handle', async (req, res) => {
|
|
| 165 |
const { error } = await supabase.from('p2p_handles').upsert({
|
| 166 |
handle: normalizedHandle,
|
| 167 |
session_id,
|
| 168 |
-
pub_key: session_pub_key,
|
| 169 |
updated_at: new Date().toISOString()
|
| 170 |
});
|
| 171 |
|
|
@@ -182,8 +193,17 @@ app.post('/anp/v1/register-handle', async (req, res) => {
|
|
| 182 |
// ANP HANDSHAKE ROUTE (Creation & Joining)
|
| 183 |
// ============================================================================
|
| 184 |
app.post('/anp/v1/handshake', async (req, res) => {
|
| 185 |
-
const { session_id, buyer_pub_key, constraints } = req.body;
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
// Explicitly sync seller's local state machine
|
| 188 |
core.registerIncomingSession(session_id, buyer_pub_key, constraints);
|
| 189 |
|
|
@@ -297,7 +317,7 @@ app.post('/anp/v1/counter', async (req, res) => {
|
|
| 297 |
const aiSuggestion = await mediatePrice(price, "P2P Service");
|
| 298 |
routedPrice = aiSuggestion.price;
|
| 299 |
routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
|
| 300 |
-
|
| 301 |
// Log mediation occurrence
|
| 302 |
await supabase.from('p2p_messages').insert({ room_id: room.room_id, turn: currentTurn, sender_session_id: 'ginger_ai', price: routedPrice, reason: routedMessage });
|
| 303 |
}
|
|
@@ -346,13 +366,19 @@ app.listen(PORT, async () => {
|
|
| 346 |
try {
|
| 347 |
console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)...");
|
| 348 |
await core.initialize();
|
| 349 |
-
|
| 350 |
-
// Refresh token every 5 days before the 7-day expiry
|
| 351 |
-
setInterval(() => core.initialize().catch(()=>console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
|
| 352 |
|
| 353 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
console.log("✓ Successfully registered 'ginger.anp' to the Network.");
|
| 355 |
|
|
|
|
| 356 |
getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
|
| 357 |
|
| 358 |
} catch (e) {
|
|
|
|
| 27 |
|
| 28 |
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
|
| 29 |
|
| 30 |
+
// Protocol v0.2.0 Core Initialization
|
| 31 |
+
// (Dynamic Firebase Discovery handles the registryURL automatically)
|
| 32 |
const core = new ClinchCore({
|
| 33 |
privateKeyHex: SELLER_PRIV_KEY
|
| 34 |
});
|
|
|
|
| 44 |
|
| 45 |
let cachedLlamaModel = null;
|
| 46 |
let cachedLlamaContext = null;
|
| 47 |
+
let mediatorReady = false;
|
| 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!");
|
|
|
|
| 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 |
+
mediatorReady = true;
|
| 92 |
console.log(`[AI] Mediator Engine Hot.`);
|
| 93 |
}
|
| 94 |
|
| 95 |
async function mediatePrice(currentPrice, item) {
|
| 96 |
+
// Guard: model may still be loading during the startup window
|
| 97 |
+
if (!mediatorReady || !cachedLlamaContext) {
|
| 98 |
+
console.log(`[AI] Mediator not ready yet — returning safe fallback.`);
|
| 99 |
+
return {
|
| 100 |
+
price: currentPrice * 0.9,
|
| 101 |
+
message: "Ginger AI Mediator is warming up. Suggesting a 10% compromise to keep the deal moving."
|
| 102 |
+
};
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
const nodeLlama = await import('node-llama-cpp');
|
| 106 |
const systemPrompt = `You are the Ginger P2P AI Mediator. Two human/agent peers are deadlocked negotiating a price for "${item}".
|
| 107 |
The current proposed price is $${currentPrice}.
|
|
|
|
| 116 |
|
| 117 |
let responseText = "";
|
| 118 |
await session.prompt("Suggest a compromise.", { maxTokens: 200, onTextChunk: (chunk) => { responseText += chunk; } });
|
| 119 |
+
|
| 120 |
try {
|
| 121 |
const clean = responseText.replace(/```json|```/g, "").trim();
|
| 122 |
return JSON.parse(clean);
|
|
|
|
| 176 |
const { error } = await supabase.from('p2p_handles').upsert({
|
| 177 |
handle: normalizedHandle,
|
| 178 |
session_id,
|
| 179 |
+
pub_key: session_pub_key,
|
| 180 |
updated_at: new Date().toISOString()
|
| 181 |
});
|
| 182 |
|
|
|
|
| 193 |
// ANP HANDSHAKE ROUTE (Creation & Joining)
|
| 194 |
// ============================================================================
|
| 195 |
app.post('/anp/v1/handshake', async (req, res) => {
|
| 196 |
+
const { session_id, buyer_pub_key, constraints, blind_auth_token } = req.body;
|
| 197 |
+
|
| 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
|
| 208 |
core.registerIncomingSession(session_id, buyer_pub_key, constraints);
|
| 209 |
|
|
|
|
| 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 |
}
|
|
|
|
| 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) {
|