publicstring commited on
Commit
894a3b5
·
verified ·
1 Parent(s): 815a418

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +140 -98
app.js CHANGED
@@ -1,41 +1,42 @@
1
  require('dotenv').config();
2
- const express = require('express');
3
- const fs = require('fs');
4
- const path = require('path');
5
- const { ClinchSeller } = require('clinch-core');
6
- const { GoogleGenAI } = require('@google/genai');
7
 
8
  const app = express();
9
  app.use(express.json());
10
 
11
  // ============================================================
12
- // CONFIG
13
  // ============================================================
14
  const PORT = process.env.PORT || 7860;
15
- const REGISTRY_URL = process.env.REGISTRY_URL;
16
  const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
17
  const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
18
  const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
19
 
20
- const sellerCore = new ClinchSeller({
 
 
 
 
 
 
 
21
  privateKeyHex: SELLER_PRIV_KEY,
22
  registryUrl: REGISTRY_URL
23
  });
24
- sellerCore.on('log', msg => console.log(msg));
25
-
26
- if (!PUBLIC_ENDPOINT) {
27
- console.error('FATAL: PUBLIC_ENDPOINT not set.');
28
- console.error('Set it to your stable public URL — domain, load balancer, reverse proxy.');
29
- console.error('Example: https://mystore.com/anp/v1');
30
- process.exit(1);
31
- }
32
 
33
  const ai = GEMINI_API_KEY ? new GoogleGenAI({ apiKey: GEMINI_API_KEY }) : null;
34
 
35
  // ============================================================
36
- // PLUGIN LOADER
37
  // ============================================================
38
  const vendors = {};
 
39
 
40
  function loadModules() {
41
  const dir = path.join(__dirname, 'modules');
@@ -55,21 +56,21 @@ function loadModules() {
55
  }
56
  }
57
  }
58
-
59
  loadModules();
60
 
61
  // ============================================================
62
- // AI ENGINE
63
  // ============================================================
64
  async function evaluateOffer(buyerOffer, itemData, turn) {
65
  if (!ai) {
 
66
  const range = itemData.list_price - itemData.floor_price;
67
- const step = range * 0.07;
68
- const counter = Math.max(itemData.floor_price, itemData.list_price - step * turn);
69
- return { price: Math.round(counter * 100) / 100, reason: 'Meeting you partway.' };
70
  }
71
 
72
- const prompt = `You are a professional seller agent.
73
 
74
  Item: ${itemData.id}
75
  List price: $${itemData.list_price}
@@ -78,124 +79,165 @@ Buyer offered: $${buyerOffer}
78
  Turn: ${turn}
79
 
80
  Rules:
81
- - If buyer is within 5% of floor: accept at floor price
82
- - Otherwise: counter, moving 5-8% toward buyer per turn
83
- - One sentence, professional, brief
84
 
85
- Respond ONLY with JSON (no markdown):
86
- {"price": <number>, "reason": "<one sentence>"}`;
87
 
88
  try {
89
- const res = await ai.models.generateContent({
90
- model: 'gemini-2.5-flash',
91
  contents: prompt,
92
- config: { responseMimeType: 'application/json', temperature: 0.15 }
93
  });
94
- const result = JSON.parse(res.text());
 
 
 
 
95
  return {
96
- price: Math.max(result.price, itemData.floor_price),
97
  reason: result.reason
98
  };
99
  } catch (e) {
100
- console.error('[AI Engine]', e.message);
101
- return { price: itemData.list_price, reason: 'Unable to adjust price at this time.' };
102
  }
103
  }
104
 
105
  // ============================================================
106
- // ANP ROUTES
107
  // ============================================================
108
 
109
  app.post('/anp/v1/handshake', (req, res) => {
110
- const { session_id, constraints, mode } = req.body;
111
- const domain = req.headers['x-clinch-domain'];
112
 
113
- console.log(`[Handshake] ${session_id} | Mode: ${mode} | Domain: ${domain}`);
114
 
115
- const vendor = vendors[domain];
116
  if (!vendor) {
117
- return res.status(404).json({ error: `Domain ${domain} not hosted here` });
118
  }
119
 
120
- res.json({
121
- status: 'ACCEPTED',
122
- session_id,
123
- capabilities: vendor.capabilities || [],
124
- supported_modes: vendor.supported_modes || ['ANP/C']
125
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  });
127
 
128
  app.post('/anp/v1/counter', async (req, res) => {
129
- const { session_id, price, turn, reason, buyer_sig, constraints } = req.body;
130
- const domain = req.headers['x-clinch-domain'];
131
- const buyerPub = req.headers['x-buyer-pubkey'];
132
- const itemIntent = constraints?.item || req.body.item_intent;
133
-
134
- console.log(`[Counter] ${session_id} | Turn ${turn} | $${price} | Item: ${itemIntent}`);
135
-
136
- const vendor = vendors[domain];
137
- if (!vendor) return res.status(404).json({ error: `Domain ${domain} not hosted here` });
138
-
139
- if (buyer_sig && buyerPub) {
140
- const valid = sellerCore.verifyBuyerSignature(
141
- { session_id, turn, price, reason },
142
- buyer_sig,
143
- buyerPub
144
- );
145
- if (!valid) console.warn(`[Security] Bad buyer sig on ${session_id} — logging, not rejecting`);
146
  }
147
 
148
- const itemData = vendor.getItemConstraints(itemIntent);
149
- if (!itemData) return res.status(400).json({ error: `Item not found: ${itemIntent}` });
150
 
151
- if (price >= itemData.floor_price * 0.95) {
 
 
 
152
  return res.json({
153
- session_id,
154
- msg_type: 'accept',
155
- price: Math.max(price, itemData.floor_price),
156
- reason: "We have a deal.",
157
- timestamp: new Date().toISOString()
158
  });
159
  }
160
 
161
- const { price: counter, reason: counterReason } = await evaluateOffer(price, itemData, turn || 1);
 
 
 
 
 
 
 
162
 
 
163
  res.json({
164
- session_id,
165
- msg_type: 'counter',
166
- price: counter,
167
- reason: counterReason,
168
- timestamp: new Date().toISOString()
169
  });
170
  });
171
 
172
- app.post('/anp/v1/accept', (req, res) => {
173
- const { session_id, price } = req.body;
174
- console.log(`[Deal] Session ${session_id} closed at $${price}`);
175
- res.json({ status: 'COMMITTED', session_id, price });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  });
177
 
178
  // ============================================================
179
  // BOOT
180
  // ============================================================
181
  app.listen(PORT, async () => {
182
- console.log(`\n💼 Seller Hub | Port ${PORT} | Endpoint: ${PUBLIC_ENDPOINT}`);
183
- console.log(` Vendors: ${Object.keys(vendors).join(', ') || 'none loaded'}\n`);
184
 
185
- for (const [domain, mod] of Object.entries(vendors)) {
186
- try {
187
- await sellerCore.registerEndpoint({
188
- agent_id: mod.agent_id,
189
- endpoint: PUBLIC_ENDPOINT,
190
- supported_modes: mod.supported_modes || ['ANP/C'],
191
- categories: mod.categories || [],
192
- capabilities: mod.capabilities || []
193
- });
194
- } catch (e) {
195
- console.error(`[Boot] Failed to register ${domain}:`);
196
- console.error(` -> ${e.message}`);
197
- console.error(` -> Did you claim '${domain}' on the dashboard and bind it to this .env private key?`);
198
- console.error(` -> If you don't own '${domain}', delete its file from your 'modules' folder!`);
199
  }
 
 
 
200
  }
201
  });
 
1
  require('dotenv').config();
2
+ const express = require('express');
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { ClinchCore, NegotiationState } = require('clinch-core');
6
+ const { GoogleGenAI } = require('@google/genai');
7
 
8
  const app = express();
9
  app.use(express.json());
10
 
11
  // ============================================================
12
+ // CONFIGURATION
13
  // ============================================================
14
  const PORT = process.env.PORT || 7860;
15
+ const REGISTRY_URL = process.env.REGISTRY_URL || 'https://registry.clinch.network';
16
  const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
17
  const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
18
  const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
19
 
20
+ if (!PUBLIC_ENDPOINT || !SELLER_PRIV_KEY) {
21
+ console.error('FATAL: PUBLIC_ENDPOINT and SELLER_PRIVATE_KEY must be set.');
22
+ console.error('Example PUBLIC_ENDPOINT: https://mystore.com/anp/v1');
23
+ process.exit(1);
24
+ }
25
+
26
+ // v0.2.0 Core Initialization
27
+ const sellerCore = new ClinchCore({
28
  privateKeyHex: SELLER_PRIV_KEY,
29
  registryUrl: REGISTRY_URL
30
  });
31
+ sellerCore.on('log', msg => console.log(`[Seller Core] ${msg}`));
 
 
 
 
 
 
 
32
 
33
  const ai = GEMINI_API_KEY ? new GoogleGenAI({ apiKey: GEMINI_API_KEY }) : null;
34
 
35
  // ============================================================
36
+ // MULTI-TENANT PLUGIN LOADER
37
  // ============================================================
38
  const vendors = {};
39
+ const sessionVendorMap = new Map(); // Maps running sessions to their specific vendor module
40
 
41
  function loadModules() {
42
  const dir = path.join(__dirname, 'modules');
 
56
  }
57
  }
58
  }
 
59
  loadModules();
60
 
61
  // ============================================================
62
+ // GEMINI AI ENGINE
63
  // ============================================================
64
  async function evaluateOffer(buyerOffer, itemData, turn) {
65
  if (!ai) {
66
+ // Math-based fallback if no Gemini key is provided
67
  const range = itemData.list_price - itemData.floor_price;
68
+ const step = range * 0.15;
69
+ const counter = Math.max(itemData.floor_price, itemData.list_price - (step * turn));
70
+ return { price: Math.round(counter * 100) / 100, reason: 'Meeting you partway to keep the deal moving.' };
71
  }
72
 
73
+ const prompt = `You are a professional B2B seller agent negotiating via the Clinch Protocol.
74
 
75
  Item: ${itemData.id}
76
  List price: $${itemData.list_price}
 
79
  Turn: ${turn}
80
 
81
  Rules:
82
+ - If buyer is within 5% of floor: accept at floor price.
83
+ - Otherwise: counter, moving 5-8% toward buyer per turn.
84
+ - Be extremely brief and professional.
85
 
86
+ Respond ONLY with valid JSON (no markdown block wrapping):
87
+ {"price": <number>, "reason": "<one concise sentence>"}`;
88
 
89
  try {
90
+ const res = await ai.models.generateContent({
91
+ model: 'gemini-2.5-flash',
92
  contents: prompt,
93
+ config: { temperature: 0.2 }
94
  });
95
+
96
+ // Clean potential markdown from Gemini output
97
+ const cleanJson = res.text.replace(/```json|```/g, "").trim();
98
+ const result = JSON.parse(cleanJson);
99
+
100
  return {
101
+ price: Math.max(result.price, itemData.floor_price),
102
  reason: result.reason
103
  };
104
  } catch (e) {
105
+ console.error('[AI Engine Error]', e.message);
106
+ return { price: itemData.list_price, reason: 'Unable to adjust price dynamically at this time.' };
107
  }
108
  }
109
 
110
  // ============================================================
111
+ // ANP v0.2.0 SYNCHRONOUS ROUTES
112
  // ============================================================
113
 
114
  app.post('/anp/v1/handshake', (req, res) => {
115
+ const { session_id, constraints, target, buyer_pub_key } = req.body;
 
116
 
117
+ console.log(`\n[Handshake] ${session_id} targeting ${target}`);
118
 
119
+ const vendor = vendors[target];
120
  if (!vendor) {
121
+ return res.status(404).json({ type: 'CANCEL', reason: `Domain ${target} not hosted here` });
122
  }
123
 
124
+ // Register session locally
125
+ sellerCore.registerIncomingSession(session_id, buyer_pub_key, constraints);
126
+ sessionVendorMap.set(session_id, vendor);
127
+
128
+ const itemIntent = constraints?.item || "General Item";
129
+ const itemData = vendor.getItemConstraints(itemIntent);
130
+
131
+ if (!itemData) {
132
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, 0, 1);
133
+ return res.status(400).json({ type: 'CANCEL', reason: `Item not found or unavailable.` });
134
+ }
135
+
136
+ // Evaluate Initial Deal automatically
137
+ const budget = constraints.max_budget;
138
+ if (budget !== null && budget >= itemData.list_price) {
139
+ // Buyer opened above our list price, confirm immediately
140
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, itemData.list_price, 1);
141
+ return res.json({ type: 'CONFIRM', price: itemData.list_price });
142
+ } else {
143
+ // Counter with list price to start the haggling
144
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, itemData.list_price, 2);
145
+ return res.json({
146
+ type: 'COUNTER',
147
+ price: itemData.list_price,
148
+ turn: 2,
149
+ message: `Welcome to ${vendor.display_name}. The listing price for ${itemData.id} is $${itemData.list_price}.`
150
+ });
151
+ }
152
  });
153
 
154
  app.post('/anp/v1/counter', async (req, res) => {
155
+ const { session_id, price, turn, reason } = req.body;
156
+ const currentTurn = turn || 2;
157
+ const nextTurn = currentTurn + 1;
158
+
159
+ console.log(`[Counter] ${session_id} | Turn ${currentTurn} | $${price}`);
160
+
161
+ const vendor = sessionVendorMap.get(session_id);
162
+ const session = sellerCore.getSession(session_id);
163
+
164
+ if (!vendor || !session) {
165
+ return res.status(404).json({ type: 'CANCEL', reason: "Session or Vendor context lost." });
 
 
 
 
 
 
166
  }
167
 
168
+ const itemData = vendor.getItemConstraints(session.constraints.item);
 
169
 
170
+ // If buyer met our absolute floor or is within 2%, accept.
171
+ if (price >= itemData.floor_price * 0.98) {
172
+ const finalPrice = Math.max(price, itemData.floor_price);
173
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, finalPrice, currentTurn);
174
  return res.json({
175
+ type: 'CONFIRM',
176
+ price: finalPrice,
177
+ message: "We have a deal. Awaiting your cryptographic signature."
 
 
178
  });
179
  }
180
 
181
+ // Max turn limit check
182
+ if (currentTurn >= 6) {
183
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, price, currentTurn);
184
+ return res.json({ type: 'CANCEL', reason: "Max negotiation turns reached without agreement." });
185
+ }
186
+
187
+ // Let Gemini evaluate the counter
188
+ const { price: counterPrice, reason: counterReason } = await evaluateOffer(price, itemData, currentTurn);
189
 
190
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, counterPrice, nextTurn);
191
  res.json({
192
+ type: 'COUNTER',
193
+ price: counterPrice,
194
+ turn: nextTurn,
195
+ message: counterReason
 
196
  });
197
  });
198
 
199
+ app.post('/anp/v1/cancel', (req, res) => {
200
+ const { session_id } = req.body;
201
+ sellerCore.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, 0);
202
+ sessionVendorMap.delete(session_id);
203
+ res.json({ success: true });
204
+ });
205
+
206
+ // ============================================================
207
+ // BILATERAL SIGNATURE HANDLER
208
+ // ============================================================
209
+ app.post('/anp/v1/sign_request', (req, res) => {
210
+ try {
211
+ const sig = sellerCore.signAsSeller(req.body.artifact);
212
+ res.json({ sellerSignature: sig });
213
+ console.log(`[Deal Signed] Session ${req.body.artifact.sessionId} locked at $${req.body.artifact.price}`);
214
+ } catch (e) {
215
+ res.status(400).json({ error: e.message });
216
+ }
217
  });
218
 
219
  // ============================================================
220
  // BOOT
221
  // ============================================================
222
  app.listen(PORT, async () => {
223
+ console.log(`\n💼 Vendor Hub Online | Port ${PORT}`);
224
+ console.log(` Stable Endpoint: ${PUBLIC_ENDPOINT}\n`);
225
 
226
+ try {
227
+ console.log("⏳ Initializing Transport Auth...");
228
+ await sellerCore.initialize();
229
+ setInterval(() => sellerCore.initialize().catch(()=>{}), 5 * 24 * 60 * 60 * 1000);
230
+
231
+ for (const [domain, mod] of Object.entries(vendors)) {
232
+ await sellerCore.registerNode(
233
+ `${PUBLIC_ENDPOINT}/anp/v1`,
234
+ mod.categories || [],
235
+ mod.capabilities || []
236
+ );
237
+ console.log(`✓ Node registered: ${domain}`);
 
 
238
  }
239
+ } catch (e) {
240
+ console.error(`[Boot Error] ${e.message}`);
241
+ console.error(`Ensure your REGISTRY_URL is reachable and SELLER_PRIVATE_KEY is correct.`);
242
  }
243
  });