publicstring commited on
Commit
5f6a085
·
verified ·
1 Parent(s): a4d4207

Update app(ANPGinger).js

Browse files
Files changed (1) hide show
  1. app(ANPGinger).js +462 -1
app(ANPGinger).js CHANGED
@@ -1 +1,462 @@
1
- app.js
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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());
12
+
13
+ // ============================================================================
14
+ // CONFIGURATION & INITIALIZATION
15
+ // ============================================================================
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';
20
+
21
+ const SUPABASE_URL = process.env.SUPABASE_URL;
22
+ const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY;
23
+
24
+ if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !PUBLIC_ENDPOINT || !SELLER_PRIV_KEY) {
25
+ console.error("FATAL: Missing required dynamic configuration parameters in env.");
26
+ process.exit(1);
27
+ }
28
+
29
+ const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_KEY);
30
+
31
+ // Protocol v0.2.1 Core Initialization
32
+ const core = new ClinchCore({
33
+ privateKeyHex: SELLER_PRIV_KEY
34
+ });
35
+
36
+ core.on('log', msg => console.log(`[Ginger Protocol] ${msg}`));
37
+
38
+ // ============================================================================
39
+ // AI MEDIATOR (QWEN 1.5B GGUF on CPU)
40
+ // ============================================================================
41
+ const MODEL_DIR = path.join(__dirname, 'models');
42
+ const MODEL_PATH = path.join(MODEL_DIR, 'qwen2.5-1.5b-instruct-q4_k_m.gguf');
43
+ const MODEL_URL = "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf";
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!");
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 = 4;
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
+ if (!mediatorReady || !cachedLlamaContext) {
97
+ console.log(`[AI] Mediator not ready yet — returning safe fallback.`);
98
+ return {
99
+ price: currentPrice * 0.9,
100
+ message: "Ginger AI Mediator is warming up. Suggesting a 10% compromise to keep the deal moving."
101
+ };
102
+ }
103
+
104
+ const nodeLlama = await import('node-llama-cpp');
105
+ const systemPrompt = `You are the Ginger P2P AI Mediator. Two human/agent peers are deadlocked negotiating a price for "${item}".
106
+ The current proposed price is $${currentPrice}.
107
+ Propose a fair middle-ground compromise to break the deadlock.
108
+ Output ONLY valid JSON matching exactly: {"price": number, "message": "string"}`;
109
+
110
+ const session = new nodeLlama.LlamaChatSession({
111
+ contextSequence: cachedLlamaContext.getSequence(),
112
+ systemPrompt,
113
+ chatWrapper: new nodeLlama.ChatMLChatWrapper()
114
+ });
115
+
116
+ let responseText = "";
117
+ await session.prompt("Suggest a compromise.", { maxTokens: 200, onTextChunk: (chunk) => { responseText += chunk; } });
118
+
119
+ try {
120
+ const clean = responseText.replace(/```json|```/g, "").trim();
121
+ return JSON.parse(clean);
122
+ } catch (e) {
123
+ return { price: currentPrice * 0.9, message: "Ginger AI suggests a 10% compromise to keep the deal moving." };
124
+ }
125
+ }
126
+
127
+ // ============================================================================
128
+ // IN-MEMORY CACHE & GC DAEMON
129
+ // ============================================================================
130
+ const localRoomCache = new Map();
131
+
132
+ setInterval(async () => {
133
+ console.log("[Ginger GC] Initiating scheduled sweeping daemon...");
134
+ const now = Date.now();
135
+ let swept = 0;
136
+
137
+ for (const [roomId, room] of localRoomCache.entries()) {
138
+ if (now - new Date(room.created_at).getTime() > 1800000) {
139
+ localRoomCache.delete(roomId);
140
+ swept++;
141
+ }
142
+ }
143
+
144
+ const oneHourAgo = new Date(now - 3600000).toISOString();
145
+ const { error } = await supabase.from('ginger_rooms').delete().eq('status', 'pending').lt('created_at', oneHourAgo);
146
+
147
+ if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
148
+ else console.log(`[Ginger GC] Flushed ${swept} dead memory caches.`);
149
+ }, 600000);
150
+
151
+ async function generateUniquePin() {
152
+ let pin;
153
+ let exists = true;
154
+ while (exists) {
155
+ pin = Math.floor(100000 + Math.random() * 900000).toString();
156
+ const { data } = await supabase.from('ginger_rooms').select('pin').eq('pin', pin).maybeSingle();
157
+ if (!data) exists = false;
158
+ }
159
+ return pin;
160
+ }
161
+
162
+ // ============================================================================
163
+ // PUBLIC ROUTE: LEGACY DIRECT REGISTRATION
164
+ // ============================================================================
165
+ app.post('/register-handle', async (req, res) => {
166
+ const { handle, session_id, session_pub_key, callback_token } = req.body;
167
+ if (!handle || !session_id || !session_pub_key) return res.status(400).json({ error: "Missing required parameters." });
168
+
169
+ const normalizedHandle = handle.toLowerCase().trim();
170
+ try {
171
+ const { error } = await supabase.from('ginger_handles').upsert({
172
+ handle: normalizedHandle,
173
+ session_id,
174
+ pub_key: session_pub_key,
175
+ callback_token: callback_token || null,
176
+ updated_at: new Date().toISOString()
177
+ });
178
+
179
+ if (error) throw error;
180
+ console.log(`[Handle Registry] Bound permanent handle: ${normalizedHandle} ➔ ${session_pub_key.substring(0,8)}`);
181
+ return res.json({ status: "BOUND", handle: normalizedHandle });
182
+ } catch (err) {
183
+ console.error("[-] Handle registration error:", err.message);
184
+ return res.status(500).json({ error: "Failed to map permanent handle." });
185
+ }
186
+ });
187
+
188
+ // ============================================================================
189
+ // ANP HANDSHAKE ROUTE (Protocol Registration, Room Creation & Joining)
190
+ // ============================================================================
191
+ app.post('/handshake', async (req, res) => {
192
+ const { session_id, buyer_pub_key, constraints, blind_auth_token, callback_token } = req.body;
193
+
194
+ if (blind_auth_token) {
195
+ console.log(`[Auth] Blind key token received | session: ${session_id} | buyer: ${buyer_pub_key?.substring(0, 8)}...`);
196
+ }
197
+
198
+ core.registerIncomingSession(session_id, buyer_pub_key, constraints);
199
+
200
+ try {
201
+ const targetHandle = constraints?.terms?.target_handle || constraints?.target_handle;
202
+ const p2pPin = constraints?.terms?.p2p_pin || constraints?.p2p_pin;
203
+ const intent = constraints?.intent;
204
+
205
+ // --- CASE 0: REGISTERING PERMANENT HANDLE VIA P2P PROTOCOL ---
206
+ if (intent === 'register' && targetHandle) {
207
+ const handle = targetHandle.toLowerCase().trim();
208
+
209
+ // 🔒 ANTI-HIJACK SHIELD: Verify if handle is claimed by another public key
210
+ const { data: existing } = await supabase.from('ginger_handles').select('pub_key').eq('handle', handle).maybeSingle();
211
+ if (existing && existing.pub_key !== buyer_pub_key) {
212
+ return res.json({ type: 'CANCEL', reason: `Handle '${handle}' is already registered to another cryptographic key.` });
213
+ }
214
+
215
+ const { error: regErr } = await supabase.from('ginger_handles').upsert({
216
+ handle: handle,
217
+ session_id,
218
+ pub_key: buyer_pub_key,
219
+ callback_token: callback_token || null,
220
+ updated_at: new Date().toISOString()
221
+ });
222
+
223
+ if (regErr) throw regErr;
224
+
225
+ console.log(`[Handle Registry] Bound permanent handle (Protocol Sync): ${handle} ➔ ${buyer_pub_key.substring(0,8)}`);
226
+ core.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, 0, 1);
227
+
228
+ return res.json({
229
+ type: "CONFIRM",
230
+ price: 0,
231
+ turn: 1,
232
+ message: `Success. Handle '${handle}' is now securely bound to your session key.`
233
+ });
234
+ }
235
+
236
+ // --- CASE 1: JOINING A PERMANENT HANDLE ---
237
+ if (targetHandle) {
238
+ const handle = targetHandle.toLowerCase().trim();
239
+ const { data: persistentHost, error: handleErr } = await supabase.from('ginger_handles').select('*').eq('handle', handle).maybeSingle();
240
+
241
+ if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline or does not exist.` });
242
+
243
+ // 🛡️ ANTI-LOOP SHIELD: Prevent an agent from initiating a connection to itself
244
+ if (persistentHost.pub_key === buyer_pub_key) {
245
+ return res.json({ type: 'CANCEL', reason: "Cannot establish a P2P session with your own handle." });
246
+ }
247
+
248
+ const pin = await generateUniquePin();
249
+
250
+ const { data: room, error: roomErr } = await supabase.from('ginger_rooms').insert({
251
+ pin,
252
+ initiator_session_id: persistentHost.session_id,
253
+ initiator_pub_key: persistentHost.pub_key,
254
+ initiator_callback_token: persistentHost.callback_token || null,
255
+ initiator_handle: handle,
256
+ receiver_session_id: session_id,
257
+ receiver_pub_key: buyer_pub_key,
258
+ receiver_callback_token: callback_token || null,
259
+ receiver_handle: null,
260
+ status: 'active'
261
+ }).select('*').single();
262
+
263
+ if (roomErr) throw roomErr;
264
+ localRoomCache.set(room.room_id, room);
265
+
266
+ // Extract custom message
267
+ const customMsg = constraints?.terms?.message || constraints?.message;
268
+ const notificationMsg = customMsg
269
+ ? `[Incoming from ${handle}]: ${customMsg}`
270
+ : `Peer targeting your handle '${handle}' has joined. Room active.`;
271
+
272
+ // Notify the Host asynchronously
273
+ await core.request('/api/route/async-callback', 'POST', {
274
+ buyer_pub_key: persistentHost.pub_key,
275
+ payload: {
276
+ type: "COUNTER",
277
+ session_id: persistentHost.session_id,
278
+ price: constraints.max_budget || 0,
279
+ turn: 2,
280
+ message: notificationMsg
281
+ }
282
+ }).catch(() => {});
283
+
284
+ core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, constraints.max_budget || 0, 2);
285
+ return res.json({ type: "COUNTER", price: constraints.max_budget || 0, turn: 2, message: `Connected to ${handle}. Message delivered.` });
286
+ }
287
+
288
+ // --- CASE 2: JOINING VIA 6-DIGIT PIN ---
289
+ if (p2pPin) {
290
+ const pin = p2pPin.toString().trim();
291
+ const { data: room, error } = await supabase.from('ginger_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle();
292
+
293
+ if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." });
294
+
295
+ // 🛡️ ANTI-LOOP SHIELD: Prevent an agent from joining its own room
296
+ if (room.initiator_pub_key === buyer_pub_key) {
297
+ return res.json({ type: 'CANCEL', reason: "Cannot join your own temporary P2P room." });
298
+ }
299
+
300
+ await supabase.from('ginger_rooms').update({
301
+ receiver_session_id: session_id,
302
+ receiver_pub_key: buyer_pub_key,
303
+ receiver_callback_token: callback_token || null,
304
+ status: 'active'
305
+ }).eq('room_id', room.room_id);
306
+
307
+ room.receiver_session_id = session_id;
308
+ room.receiver_pub_key = buyer_pub_key;
309
+ room.receiver_callback_token = callback_token || null;
310
+ room.status = 'active';
311
+ localRoomCache.set(room.room_id, room);
312
+
313
+ // Extract custom message
314
+ const customMsg = constraints?.terms?.message || constraints?.message;
315
+ const notificationMsg = customMsg
316
+ ? `[Incoming via PIN ${pin}]: ${customMsg}`
317
+ : "Peer has entered the room. Bargaining active.";
318
+
319
+ await core.request('/api/route/async-callback', 'POST', {
320
+ buyer_pub_key: room.initiator_pub_key,
321
+ payload: { type: "COUNTER", session_id: room.initiator_session_id, price: constraints.max_budget || 0, turn: 2, message: notificationMsg }
322
+ }).catch(() => {});
323
+
324
+ core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, constraints.max_budget || 0, 2);
325
+ return res.json({ type: "COUNTER", price: constraints.max_budget || 0, turn: 2, message: `Joined room ${pin}.` });
326
+ }
327
+
328
+ // --- CASE 3: CREATING TEMPORARY ROOM ---
329
+ const pin = await generateUniquePin();
330
+ const { data: newRoom, error: insertError } = await supabase.from('ginger_rooms').insert({
331
+ pin,
332
+ initiator_session_id: session_id,
333
+ initiator_pub_key: buyer_pub_key,
334
+ initiator_callback_token: callback_token || null,
335
+ status: 'pending'
336
+ }).select('*').single();
337
+
338
+ if (insertError) throw insertError;
339
+ localRoomCache.set(newRoom.room_id, newRoom);
340
+
341
+ core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, 0, 2);
342
+ return res.json({ type: "COUNTER", price: 0, turn: 2, message: `Room created. Share this PIN with your peer: ${pin}` });
343
+
344
+ } catch (err) {
345
+ console.error("[Handshake Error]", err.message);
346
+ return res.status(500).json({ type: 'CANCEL', reason: "Broker internal error." });
347
+ }
348
+ });
349
+
350
+ // ============================================================================
351
+ // ANP COUNTER ROUTE (Real-time Message Tunneling + AI Mediation)
352
+ // ============================================================================
353
+ app.post('/counter', async (req, res) => {
354
+ const { session_id, turn, price, reason, signature } = req.body;
355
+ const currentTurn = turn || 2;
356
+ const nextTurn = currentTurn + 1;
357
+
358
+ try {
359
+ let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
360
+
361
+ if (!room) {
362
+ 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();
363
+ if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
364
+ room = data;
365
+ localRoomCache.set(room.room_id, room);
366
+ }
367
+
368
+ const isInitiator = room.initiator_session_id === session_id;
369
+ const targetSessionId = isInitiator ? room.receiver_session_id : room.initiator_session_id;
370
+ const targetPubKey = isInitiator ? room.receiver_pub_key : room.initiator_pub_key;
371
+
372
+ let routedPrice = price;
373
+ let routedMessage = reason;
374
+
375
+ await supabase.from('ginger_messages').insert({
376
+ room_id: room.room_id,
377
+ turn: currentTurn,
378
+ sender_session_id: session_id,
379
+ price: price,
380
+ reason: reason || null,
381
+ signature: signature || null
382
+ });
383
+
384
+ if (reason && reason.toLowerCase().includes('@mediate')) {
385
+ console.log(`[AI] Mediation requested by ${session_id}`);
386
+ const aiSuggestion = await mediatePrice(price, "P2P Service");
387
+ routedPrice = aiSuggestion.price;
388
+ routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
389
+
390
+ await supabase.from('ginger_messages').insert({
391
+ room_id: room.room_id,
392
+ turn: currentTurn,
393
+ sender_session_id: 'ginger_ai',
394
+ price: routedPrice,
395
+ reason: routedMessage,
396
+ signature: null
397
+ });
398
+ }
399
+
400
+ await core.request('/api/route/async-callback', 'POST', {
401
+ buyer_pub_key: targetPubKey,
402
+ payload: {
403
+ type: "COUNTER",
404
+ session_id: targetSessionId,
405
+ turn: nextTurn,
406
+ price: routedPrice,
407
+ message: routedMessage
408
+ }
409
+ });
410
+
411
+ core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn);
412
+ return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." });
413
+
414
+ } catch (err) {
415
+ console.error("[Counter Error]", err.message);
416
+ return res.status(500).json({ type: 'CANCEL', reason: "Routing failed." });
417
+ }
418
+ });
419
+
420
+ // ============================================================================
421
+ // BILATERAL SIGNATURE HANDLER
422
+ // ============================================================================
423
+ app.post('/sign_request', (req, res) => {
424
+ try {
425
+ const sig = core.signAsSeller(req.body.artifact);
426
+ res.json({ sellerSignature: sig });
427
+ } catch (e) {
428
+ res.status(400).json({ error: e.message });
429
+ }
430
+ });
431
+
432
+ // ============================================================================
433
+ // BOOT
434
+ // ============================================================================
435
+ app.listen(PORT, async () => {
436
+ console.log(`\n🧡 Ginger P2P Broker Online | Port ${PORT}`);
437
+ console.log(` Stable Public Endpoint: ${PUBLIC_ENDPOINT}\n`);
438
+
439
+ try {
440
+ console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)...");
441
+ await core.initialize();
442
+
443
+ setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
444
+
445
+ await core.registerNode(
446
+ AGENT_ID,
447
+ `${PUBLIC_ENDPOINT}`,
448
+ ['p2p_bridge', 'mediation', 'scheduling'],
449
+ ['p2p_bridge', 'room_routing', 'ai_mediator'],
450
+ { supported_modes: ['ANP/C'] }
451
+ );
452
+ console.log(`✓ Successfully registered '${AGENT_ID}' to the Network.`);
453
+
454
+ getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
455
+
456
+ } catch (e) {
457
+ console.error(`[-] Failed to self-register ginger node: ${e.message}`);
458
+ }
459
+ });
460
+
461
+ process.on('SIGINT', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });
462
+ process.on('SIGTERM', () => { console.log('\n👋 Shutting down Ginger P2P...'); process.exit(0); });