publicstring commited on
Commit
d268ec0
·
verified ·
1 Parent(s): 02f745a

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +47 -36
app.js CHANGED
@@ -29,7 +29,6 @@ if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY || !PUBLIC_ENDPOINT || !SELLER_PRIV_K
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
35
  });
@@ -83,7 +82,7 @@ async function getMediatorAI() {
83
  if (!fs.existsSync(MODEL_PATH)) await downloadModel();
84
 
85
  const nodeLlama = await import('node-llama-cpp');
86
- const threads = 4; // Math.max(2, os.cpus().length - 1);
87
 
88
  console.log(`[AI] Loading Qwen 1.5B into RAM with ${threads} threads...`);
89
  const llama = await nodeLlama.getLlama();
@@ -94,7 +93,6 @@ async function getMediatorAI() {
94
  }
95
 
96
  async function mediatePrice(currentPrice, item) {
97
- // Guard: model may still be loading during the startup window
98
  if (!mediatorReady || !cachedLlamaContext) {
99
  console.log(`[AI] Mediator not ready yet — returning safe fallback.`);
100
  return {
@@ -144,7 +142,6 @@ setInterval(async () => {
144
  }
145
 
146
  const oneHourAgo = new Date(now - 3600000).toISOString();
147
- // [FIX]: Aligned GC operation strictly against the "ginger_rooms" table
148
  const { error } = await supabase.from('ginger_rooms').delete().eq('status', 'pending').lt('created_at', oneHourAgo);
149
 
150
  if (error) console.error("[-] Failed to clean orphaned DB sessions:", error.message);
@@ -156,7 +153,6 @@ async function generateUniquePin() {
156
  let exists = true;
157
  while (exists) {
158
  pin = Math.floor(100000 + Math.random() * 900000).toString();
159
- // [FIX]: Querying against schema table "ginger_rooms"
160
  const { data } = await supabase.from('ginger_rooms').select('pin').eq('pin', pin).maybeSingle();
161
  if (!data) exists = false;
162
  }
@@ -164,19 +160,14 @@ async function generateUniquePin() {
164
  }
165
 
166
  // ============================================================================
167
- // PUBLIC ROUTE: PERMANENT HANDLE SELF-REGISTRATION
168
  // ============================================================================
169
  app.post('/anp/v1/register-handle', async (req, res) => {
170
  const { handle, session_id, session_pub_key, callback_token } = req.body;
171
-
172
- if (!handle || !session_id || !session_pub_key) {
173
- return res.status(400).json({ error: "Missing required parameters." });
174
- }
175
 
176
  const normalizedHandle = handle.toLowerCase().trim();
177
-
178
  try {
179
- // [FIX]: Aligned to schema table "ginger_handles" and populated "callback_token"
180
  const { error } = await supabase.from('ginger_handles').upsert({
181
  handle: normalizedHandle,
182
  session_id,
@@ -186,9 +177,8 @@ app.post('/anp/v1/register-handle', async (req, res) => {
186
  });
187
 
188
  if (error) throw error;
189
- console.log(`[Handle Registry] Bound permanent handle: ${normalizedHandle} ➔ ${session_pub_key.substring(0,8)}`);
190
  return res.json({ status: "BOUND", handle: normalizedHandle });
191
-
192
  } catch (err) {
193
  console.error("[-] Handle registration error:", err.message);
194
  return res.status(500).json({ error: "Failed to map permanent handle." });
@@ -196,7 +186,7 @@ app.post('/anp/v1/register-handle', async (req, res) => {
196
  });
197
 
198
  // ============================================================================
199
- // ANP HANDSHAKE ROUTE (Creation & Joining)
200
  // ============================================================================
201
  app.post('/anp/v1/handshake', async (req, res) => {
202
  const { session_id, buyer_pub_key, constraints, blind_auth_token, callback_token } = req.body;
@@ -209,17 +199,51 @@ app.post('/anp/v1/handshake', async (req, res) => {
209
  core.registerIncomingSession(session_id, buyer_pub_key, constraints);
210
 
211
  try {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  // --- CASE 1: JOINING A PERMANENT HANDLE ---
213
- if (constraints && constraints.target_handle) {
214
- const handle = constraints.target_handle.toLowerCase().trim();
215
- // [FIX]: Querying against schema table "ginger_handles"
216
  const { data: persistentHost, error: handleErr } = await supabase.from('ginger_handles').select('*').eq('handle', handle).maybeSingle();
217
 
218
- if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline.` });
219
 
220
  const pin = await generateUniquePin();
221
 
222
- // [FIX]: Mapping parameters strictly to the "ginger_rooms" table columns
223
  const { data: room, error: roomErr } = await supabase.from('ginger_rooms').insert({
224
  pin,
225
  initiator_session_id: persistentHost.session_id,
@@ -236,7 +260,7 @@ app.post('/anp/v1/handshake', async (req, res) => {
236
  if (roomErr) throw roomErr;
237
  localRoomCache.set(room.room_id, room);
238
 
239
- // Notify the Host asynchronously via Registry
240
  await core.request('/api/route/async-callback', 'POST', {
241
  buyer_pub_key: persistentHost.pub_key,
242
  payload: {
@@ -253,14 +277,12 @@ app.post('/anp/v1/handshake', async (req, res) => {
253
  }
254
 
255
  // --- CASE 2: JOINING VIA 6-DIGIT PIN ---
256
- if (constraints && constraints.p2p_pin) {
257
- const pin = constraints.p2p_pin.toString().trim();
258
- // [FIX]: Querying strictly against "ginger_rooms"
259
  const { data: room, error } = await supabase.from('ginger_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle();
260
 
261
  if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." });
262
 
263
- // [FIX]: Mapping update values to exact "ginger_rooms" column schema
264
  await supabase.from('ginger_rooms').update({
265
  receiver_session_id: session_id,
266
  receiver_pub_key: buyer_pub_key,
@@ -274,7 +296,6 @@ app.post('/anp/v1/handshake', async (req, res) => {
274
  room.status = 'active';
275
  localRoomCache.set(room.room_id, room);
276
 
277
- // Notify Initiator asynchronously
278
  await core.request('/api/route/async-callback', 'POST', {
279
  buyer_pub_key: room.initiator_pub_key,
280
  payload: { type: "COUNTER", session_id: room.initiator_session_id, price: constraints.max_budget || 0, turn: 2, message: "Peer has entered the room. Bargaining active." }
@@ -286,7 +307,6 @@ app.post('/anp/v1/handshake', async (req, res) => {
286
 
287
  // --- CASE 3: CREATING TEMPORARY ROOM ---
288
  const pin = await generateUniquePin();
289
- // [FIX]: Mapping parameters and inserting strictly into "ginger_rooms"
290
  const { data: newRoom, error: insertError } = await supabase.from('ginger_rooms').insert({
291
  pin,
292
  initiator_session_id: session_id,
@@ -319,7 +339,6 @@ app.post('/anp/v1/counter', async (req, res) => {
319
  let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
320
 
321
  if (!room) {
322
- // [FIX]: Aligned table queries strictly to the "ginger_rooms" schema
323
  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();
324
  if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
325
  room = data;
@@ -333,8 +352,6 @@ app.post('/anp/v1/counter', async (req, res) => {
333
  let routedPrice = price;
334
  let routedMessage = reason;
335
 
336
- // --- SAVE MESSAGE LOG TO DATABASE ---
337
- // [FIX]: Strictly aligned insert body parameters to matches the schema of table "ginger_messages"
338
  await supabase.from('ginger_messages').insert({
339
  room_id: room.room_id,
340
  turn: currentTurn,
@@ -344,14 +361,12 @@ app.post('/anp/v1/counter', async (req, res) => {
344
  signature: signature || null
345
  });
346
 
347
- // --- AI MEDIATION INTERCEPT ---
348
  if (reason && reason.toLowerCase().includes('@mediate')) {
349
  console.log(`[AI] Mediation requested by ${session_id}`);
350
  const aiSuggestion = await mediatePrice(price, "P2P Service");
351
  routedPrice = aiSuggestion.price;
352
  routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
353
 
354
- // [FIX]: Save Mediation outcome strictly targeting "ginger_messages" schema
355
  await supabase.from('ginger_messages').insert({
356
  room_id: room.room_id,
357
  turn: currentTurn,
@@ -362,7 +377,6 @@ app.post('/anp/v1/counter', async (req, res) => {
362
  });
363
  }
364
 
365
- // --- PUSH ASYNC CALLBACK TO PEER ---
366
  await core.request('/api/route/async-callback', 'POST', {
367
  buyer_pub_key: targetPubKey,
368
  payload: {
@@ -374,7 +388,6 @@ app.post('/anp/v1/counter', async (req, res) => {
374
  }
375
  });
376
 
377
- // --- ACKNOWLEDGE SENDER ---
378
  core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn);
379
  return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." });
380
 
@@ -407,7 +420,6 @@ app.listen(PORT, async () => {
407
  console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)...");
408
  await core.initialize();
409
 
410
- // Refresh token every 5 days before the 7-day expiry
411
  setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
412
 
413
  await core.registerNode(
@@ -419,7 +431,6 @@ app.listen(PORT, async () => {
419
  );
420
  console.log(`✓ Successfully registered '${AGENT_ID}' to the Network.`);
421
 
422
- // Load AI model in the background — mediatePrice() handles the not-ready state safely
423
  getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
424
 
425
  } catch (e) {
 
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
  });
 
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();
 
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 {
 
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);
 
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
  }
 
160
  }
161
 
162
  // ============================================================================
163
+ // PUBLIC ROUTE: LEGACY DIRECT REGISTRATION (CURL SUPPORT)
164
  // ============================================================================
165
  app.post('/anp/v1/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,
 
177
  });
178
 
179
  if (error) throw error;
180
+ console.log(`[Handle Registry] Bound permanent handle (Direct API): ${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." });
 
186
  });
187
 
188
  // ============================================================================
189
+ // ANP HANDSHAKE ROUTE (Protocol Registration, Room Creation & Joining)
190
  // ============================================================================
191
  app.post('/anp/v1/handshake', async (req, res) => {
192
  const { session_id, buyer_pub_key, constraints, blind_auth_token, callback_token } = req.body;
 
199
  core.registerIncomingSession(session_id, buyer_pub_key, constraints);
200
 
201
  try {
202
+ // Support strict JSON objects generated by the AI extracting constraints
203
+ const targetHandle = constraints?.terms?.target_handle || constraints?.target_handle;
204
+ const p2pPin = constraints?.terms?.p2p_pin || constraints?.p2p_pin;
205
+ const intent = constraints?.intent;
206
+
207
+ // --- CASE 0: REGISTERING PERMANENT HANDLE VIA P2P PROTOCOL ---
208
+ if (intent === 'register' && targetHandle) {
209
+ const handle = targetHandle.toLowerCase().trim();
210
+
211
+ // Check if handle exists and is owned by someone else
212
+ const { data: existing } = await supabase.from('ginger_handles').select('pub_key').eq('handle', handle).maybeSingle();
213
+ if (existing && existing.pub_key !== buyer_pub_key) {
214
+ return res.json({ type: 'CANCEL', reason: `Handle '${handle}' is already registered to another cryptographic key.` });
215
+ }
216
+
217
+ const { error: regErr } = await supabase.from('ginger_handles').upsert({
218
+ handle: handle,
219
+ session_id,
220
+ pub_key: buyer_pub_key,
221
+ callback_token: callback_token || null,
222
+ updated_at: new Date().toISOString()
223
+ });
224
+
225
+ if (regErr) throw regErr;
226
+
227
+ console.log(`[Handle Registry] Bound permanent handle (Protocol Sync): ${handle} ➔ ${buyer_pub_key.substring(0,8)}`);
228
+ core.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, 0, 1);
229
+
230
+ return res.json({
231
+ type: "CONFIRM",
232
+ price: 0,
233
+ turn: 1,
234
+ message: `Success. Handle '${handle}' is now securely bound to your session key.`
235
+ });
236
+ }
237
+
238
  // --- CASE 1: JOINING A PERMANENT HANDLE ---
239
+ if (targetHandle) {
240
+ const handle = targetHandle.toLowerCase().trim();
 
241
  const { data: persistentHost, error: handleErr } = await supabase.from('ginger_handles').select('*').eq('handle', handle).maybeSingle();
242
 
243
+ if (handleErr || !persistentHost) return res.status(404).json({ type: 'CANCEL', reason: `Handle '${handle}' offline or does not exist.` });
244
 
245
  const pin = await generateUniquePin();
246
 
 
247
  const { data: room, error: roomErr } = await supabase.from('ginger_rooms').insert({
248
  pin,
249
  initiator_session_id: persistentHost.session_id,
 
260
  if (roomErr) throw roomErr;
261
  localRoomCache.set(room.room_id, room);
262
 
263
+ // Notify the Host asynchronously
264
  await core.request('/api/route/async-callback', 'POST', {
265
  buyer_pub_key: persistentHost.pub_key,
266
  payload: {
 
277
  }
278
 
279
  // --- CASE 2: JOINING VIA 6-DIGIT PIN ---
280
+ if (p2pPin) {
281
+ const pin = p2pPin.toString().trim();
 
282
  const { data: room, error } = await supabase.from('ginger_rooms').select('*').eq('pin', pin).eq('status', 'pending').maybeSingle();
283
 
284
  if (error || !room) return res.status(404).json({ type: 'CANCEL', reason: "Active pairing room not found." });
285
 
 
286
  await supabase.from('ginger_rooms').update({
287
  receiver_session_id: session_id,
288
  receiver_pub_key: buyer_pub_key,
 
296
  room.status = 'active';
297
  localRoomCache.set(room.room_id, room);
298
 
 
299
  await core.request('/api/route/async-callback', 'POST', {
300
  buyer_pub_key: room.initiator_pub_key,
301
  payload: { type: "COUNTER", session_id: room.initiator_session_id, price: constraints.max_budget || 0, turn: 2, message: "Peer has entered the room. Bargaining active." }
 
307
 
308
  // --- CASE 3: CREATING TEMPORARY ROOM ---
309
  const pin = await generateUniquePin();
 
310
  const { data: newRoom, error: insertError } = await supabase.from('ginger_rooms').insert({
311
  pin,
312
  initiator_session_id: session_id,
 
339
  let room = Array.from(localRoomCache.values()).find(r => (r.initiator_session_id === session_id || r.receiver_session_id === session_id) && r.status === 'active');
340
 
341
  if (!room) {
 
342
  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();
343
  if (error || !data) return res.status(404).json({ type: 'CANCEL', reason: "P2P session dropped or inactive." });
344
  room = data;
 
352
  let routedPrice = price;
353
  let routedMessage = reason;
354
 
 
 
355
  await supabase.from('ginger_messages').insert({
356
  room_id: room.room_id,
357
  turn: currentTurn,
 
361
  signature: signature || null
362
  });
363
 
 
364
  if (reason && reason.toLowerCase().includes('@mediate')) {
365
  console.log(`[AI] Mediation requested by ${session_id}`);
366
  const aiSuggestion = await mediatePrice(price, "P2P Service");
367
  routedPrice = aiSuggestion.price;
368
  routedMessage = `[🤖 Ginger AI Mediator] ${aiSuggestion.message}`;
369
 
 
370
  await supabase.from('ginger_messages').insert({
371
  room_id: room.room_id,
372
  turn: currentTurn,
 
377
  });
378
  }
379
 
 
380
  await core.request('/api/route/async-callback', 'POST', {
381
  buyer_pub_key: targetPubKey,
382
  payload: {
 
388
  }
389
  });
390
 
 
391
  core.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, routedPrice, nextTurn);
392
  return res.json({ type: "COUNTER", price: routedPrice, turn: nextTurn, message: "Turn routed to peer." });
393
 
 
420
  console.log("⏳ Initializing Protocol Core (Firebase Discovery & PoW)...");
421
  await core.initialize();
422
 
 
423
  setInterval(() => core.initialize().catch(() => console.error("Token refresh failed")), 5 * 24 * 60 * 60 * 1000);
424
 
425
  await core.registerNode(
 
431
  );
432
  console.log(`✓ Successfully registered '${AGENT_ID}' to the Network.`);
433
 
 
434
  getMediatorAI().catch(e => console.error("[AI] Failed to load Qwen 1.5B:", e.message));
435
 
436
  } catch (e) {