publicstring commited on
Commit
c4da555
·
verified ·
1 Parent(s): 975d6a8

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +160 -129
app.js CHANGED
@@ -1,166 +1,197 @@
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
- // CONFIGURATION & SETUP
13
- // ============================================================================
14
- const PORT = process.env.PORT || 7860;
15
- const REGISTRY_URL = process.env.REGISTRY_URL || 'http://localhost:7860';
16
- const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
 
17
 
18
- if (!GEMINI_API_KEY) {
19
- console.warn("⚠️ Warning: GEMINI_API_KEY is not set. AI evaluation will fail.");
20
- }
 
21
 
22
- const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
23
- const sellerCore = new ClinchSeller({ registryUrl: REGISTRY_URL });
 
 
 
 
24
 
25
- sellerCore.on('log', msg => console.log(msg));
26
 
27
- // ============================================================================
28
- // DYNAMIC MODULE LOADER
29
- // ============================================================================
30
  const vendors = {};
31
- const modulesDir = path.join(__dirname, 'modules');
32
 
33
  function loadModules() {
34
- if (!fs.existsSync(modulesDir)) {
35
- fs.mkdirSync(modulesDir);
36
- console.log(`[System] Created ${modulesDir} directory.`);
37
- return;
38
- }
39
 
40
- const files = fs.readdirSync(modulesDir).filter(f => f.endsWith('.js'));
41
- for (const file of files) {
42
- const vendorModule = require(path.join(modulesDir, file));
43
- if (vendorModule.agent_id && vendorModule.getItemConstraints) {
44
- vendors[vendorModule.agent_id] = vendorModule;
45
- console.log(`[System] Loaded Vendor Plugin: ${vendorModule.agent_id}`);
46
- } else {
47
- console.warn(`[System] Skipped ${file} - Missing required exports.`);
48
- }
 
 
49
  }
 
50
  }
51
 
52
  loadModules();
53
 
54
- // ============================================================================
55
- // UNIFIED AI ENGINE (Single Debug Point)
56
- // ============================================================================
57
- async function evaluateWithGemini(buyerOffer, itemData, currentTurn) {
58
- console.log(`[AI Engine] Analyzing offer: $${buyerOffer} for ${itemData.id}...`);
 
 
 
 
 
 
 
59
 
60
- const prompt = `
61
- ${itemData.context}
62
  Item: ${itemData.id}
63
- List Price: $${itemData.list_price}.00
64
- Absolute Floor Price: $${itemData.floor_price}.00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- The buyer has offered $${buyerOffer}.
67
- If the offer is >= $${itemData.floor_price}, you can counter or accept.
68
- If the offer is < $${itemData.floor_price}, you must counter higher than the floor price.
69
 
70
- You MUST respond strictly in JSON format:
71
- {
72
- "price": <numeric counter offer>,
73
- "reason": "<short conversational reason for the price>"
74
- }`;
75
 
76
- try {
77
- const response = await ai.models.generateContent({
78
- model: 'gemini-2.5-flash',
79
- contents: prompt,
80
- config: {
81
- responseMimeType: "application/json",
82
- temperature: 0.2
83
- }
84
- });
85
-
86
- const result = JSON.parse(response.text());
87
-
88
- // Safety Guardrail: NEVER breach the floor price, regardless of LLM output
89
- const safePrice = Math.max(result.price, itemData.floor_price);
90
-
91
- return { price: safePrice, reason: result.reason };
92
- } catch (err) {
93
- console.error("[AI Engine Error]", err.message);
94
- return {
95
- price: itemData.list_price,
96
- reason: "I am unable to deviate from the list price at this moment due to system constraints."
97
- };
98
- }
99
- }
100
 
101
- // ============================================================================
102
- // PROTOCOL WEBHOOKS (Called by the Buyer/Registry)
103
- // ============================================================================
104
-
105
- app.post('/anp/v1/handshake', async (req, res) => {
106
- const { session_id, constraints, domain } = req.body;
107
-
108
- console.log(`🤝 [Handshake] New session ${session_id} directed at ${domain}`);
109
-
110
- if (!vendors[domain]) {
111
- return res.status(404).json({ error: "Domain not hosted on this Seller Hub" });
112
- }
113
 
114
- res.json({ status: "ACCEPTED", capabilities: vendors[domain].capabilities });
 
 
 
 
 
115
  });
116
 
117
  app.post('/anp/v1/counter', async (req, res) => {
118
- const { session_id, price, domain, item_intent } = req.body;
119
-
120
- console.log(`💬 [Turn] Session ${session_id} offered $${price} for ${item_intent} at ${domain}`);
121
-
122
- const vendorModule = vendors[domain];
123
- if (!vendorModule) return res.status(404).json({ error: "Domain not hosted here" });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
- const itemData = vendorModule.getItemConstraints(item_intent);
126
- if (!itemData) {
127
- return res.status(400).json({ error: "Item not available or recognized" });
128
- }
129
 
130
- // Process through the central AI choke point
131
- const aiResponse = await evaluateWithGemini(price, itemData, 1);
 
 
 
 
 
 
132
 
133
- res.json({
134
- session_id,
135
- price: aiResponse.price,
136
- reason: aiResponse.reason,
137
- timestamp: new Date().toISOString()
138
- });
139
  });
140
 
141
- // ============================================================================
142
- // BOOT SEQUENCE
143
- // ============================================================================
144
  app.listen(PORT, async () => {
145
- console.log(`\n💼 Clinch Seller Hub running on port ${PORT}`);
146
-
147
- // In production, fetch this from the Supabase Seller Dashboard
148
- await sellerCore.authenticate("MOCK_SUPABASE_TOKEN");
149
-
150
- // Auto-Register all loaded vendor domains with the Clinch Registry
151
- console.log("\n[System] Registering vendor endpoints with the Registry...");
152
- for (const [domain, module] of Object.entries(vendors)) {
153
- try {
154
- await sellerCore.registerEndpoint({
155
- agent_id: module.agent_id,
156
- display_name: module.display_name,
157
- endpoint: `https://publicstring-sellersnode.hf.space/anp/v1`,
158
- supported_modes: ["ANP/C"],
159
- categories: module.categories,
160
- capabilities: module.capabilities
161
- });
162
- } catch (e) {
163
- console.error(`[-] Failed to register ${domain}: Is the registry server running?`);
164
- }
165
  }
 
166
  });
 
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 SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
16
+ const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
17
+ const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
18
 
19
+ const sellerCore = new ClinchSeller({
20
+ privateKeyHex: SELLER_PRIV_KEY
21
+ });
22
+ sellerCore.on('log', msg => console.log(msg));
23
 
24
+ if (!PUBLIC_ENDPOINT) {
25
+ console.error('FATAL: PUBLIC_ENDPOINT not set.');
26
+ console.error('Set it to your stable public URL — domain, load balancer, reverse proxy.');
27
+ console.error('Example: https://mystore.com/anp/v1');
28
+ process.exit(1);
29
+ }
30
 
31
+ const ai = GEMINI_API_KEY ? new GoogleGenAI({ apiKey: GEMINI_API_KEY }) : null;
32
 
33
+ // ============================================================
34
+ // PLUGIN LOADER
35
+ // ============================================================
36
  const vendors = {};
 
37
 
38
  function loadModules() {
39
+ const dir = path.join(__dirname, 'modules');
40
+ if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); return; }
 
 
 
41
 
42
+ for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) {
43
+ try {
44
+ const mod = require(path.join(dir, file));
45
+ if (!mod.agent_id || !mod.getItemConstraints) {
46
+ console.warn(`[Modules] Skipped ${file} — missing agent_id or getItemConstraints`);
47
+ continue;
48
+ }
49
+ vendors[mod.agent_id] = mod;
50
+ console.log(`[Modules] Loaded: ${mod.agent_id}`);
51
+ } catch (e) {
52
+ console.error(`[Modules] Failed to load ${file}:`, e.message);
53
  }
54
+ }
55
  }
56
 
57
  loadModules();
58
 
59
+ // ============================================================
60
+ // AI ENGINE
61
+ // ============================================================
62
+ async function evaluateOffer(buyerOffer, itemData, turn) {
63
+ if (!ai) {
64
+ const range = itemData.list_price - itemData.floor_price;
65
+ const step = range * 0.07;
66
+ const counter = Math.max(itemData.floor_price, itemData.list_price - step * turn);
67
+ return { price: Math.round(counter * 100) / 100, reason: 'Meeting you partway.' };
68
+ }
69
+
70
+ const prompt = `You are a professional seller agent.
71
 
 
 
72
  Item: ${itemData.id}
73
+ List price: $${itemData.list_price}
74
+ Floor price (never go below this): $${itemData.floor_price}
75
+ Buyer offered: $${buyerOffer}
76
+ Turn: ${turn}
77
+
78
+ Rules:
79
+ - If buyer is within 5% of floor: accept at floor price
80
+ - Otherwise: counter, moving 5-8% toward buyer per turn
81
+ - One sentence, professional, brief
82
+
83
+ Respond ONLY with JSON (no markdown):
84
+ {"price": <number>, "reason": "<one sentence>"}`;
85
+
86
+ try {
87
+ const res = await ai.models.generateContent({
88
+ model: 'gemini-2.5-flash',
89
+ contents: prompt,
90
+ config: { responseMimeType: 'application/json', temperature: 0.15 }
91
+ });
92
+ const result = JSON.parse(res.text());
93
+ return {
94
+ price: Math.max(result.price, itemData.floor_price),
95
+ reason: result.reason
96
+ };
97
+ } catch (e) {
98
+ console.error('[AI Engine]', e.message);
99
+ return { price: itemData.list_price, reason: 'Unable to adjust price at this time.' };
100
+ }
101
+ }
102
 
103
+ // ============================================================
104
+ // ANP ROUTES
105
+ // ============================================================
106
 
107
+ app.post('/anp/v1/handshake', (req, res) => {
108
+ const { session_id, constraints, mode } = req.body;
109
+ const domain = req.headers['x-clinch-domain'];
 
 
110
 
111
+ console.log(`[Handshake] ${session_id} | Mode: ${mode} | Domain: ${domain}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
+ const vendor = vendors[domain];
114
+ if (!vendor) {
115
+ return res.status(404).json({ error: `Domain ${domain} not hosted here` });
116
+ }
 
 
 
 
 
 
 
 
117
 
118
+ res.json({
119
+ status: 'ACCEPTED',
120
+ session_id,
121
+ capabilities: vendor.capabilities || [],
122
+ supported_modes: vendor.supported_modes || ['ANP/C']
123
+ });
124
  });
125
 
126
  app.post('/anp/v1/counter', async (req, res) => {
127
+ const { session_id, price, turn, reason, buyer_sig, constraints } = req.body;
128
+ const domain = req.headers['x-clinch-domain'];
129
+ const buyerPub = req.headers['x-buyer-pubkey'];
130
+ const itemIntent = constraints?.item || req.body.item_intent;
131
+
132
+ console.log(`[Counter] ${session_id} | Turn ${turn} | $${price} | Item: ${itemIntent}`);
133
+
134
+ const vendor = vendors[domain];
135
+ if (!vendor) return res.status(404).json({ error: `Domain ${domain} not hosted here` });
136
+
137
+ if (buyer_sig && buyerPub) {
138
+ const valid = sellerCore.verifyBuyerSignature(
139
+ { session_id, turn, price, reason },
140
+ buyer_sig,
141
+ buyerPub
142
+ );
143
+ if (!valid) console.warn(`[Security] Bad buyer sig on ${session_id} — logging, not rejecting`);
144
+ }
145
+
146
+ const itemData = vendor.getItemConstraints(itemIntent);
147
+ if (!itemData) return res.status(400).json({ error: `Item not found: ${itemIntent}` });
148
+
149
+ if (price >= itemData.floor_price * 0.95) {
150
+ return res.json({
151
+ session_id,
152
+ msg_type: 'accept',
153
+ price: Math.max(price, itemData.floor_price),
154
+ reason: "We have a deal.",
155
+ timestamp: new Date().toISOString()
156
+ });
157
+ }
158
 
159
+ const { price: counter, reason: counterReason } = await evaluateOffer(price, itemData, turn || 1);
 
 
 
160
 
161
+ res.json({
162
+ session_id,
163
+ msg_type: 'counter',
164
+ price: counter,
165
+ reason: counterReason,
166
+ timestamp: new Date().toISOString()
167
+ });
168
+ });
169
 
170
+ app.post('/anp/v1/accept', (req, res) => {
171
+ const { session_id, price } = req.body;
172
+ console.log(`[Deal] Session ${session_id} closed at $${price}`);
173
+ res.json({ status: 'COMMITTED', session_id, price });
 
 
174
  });
175
 
176
+ // ============================================================
177
+ // BOOT
178
+ // ============================================================
179
  app.listen(PORT, async () => {
180
+ console.log(`\n💼 Seller Hub | Port ${PORT} | Endpoint: ${PUBLIC_ENDPOINT}`);
181
+ console.log(` Vendors: ${Object.keys(vendors).join(', ') || 'none loaded'}\n`);
182
+
183
+ for (const [domain, mod] of Object.entries(vendors)) {
184
+ try {
185
+ await sellerCore.registerEndpoint({
186
+ agent_id: mod.agent_id,
187
+ endpoint: PUBLIC_ENDPOINT,
188
+ supported_modes: mod.supported_modes || ['ANP/C'],
189
+ categories: mod.categories || [],
190
+ capabilities: mod.capabilities || []
191
+ });
192
+ } catch (e) {
193
+ console.error(`[Boot] Failed to register ${domain}: ${e.message}`);
194
+ console.error(` Is your domain claimed on the dashboard first?`);
 
 
 
 
 
195
  }
196
+ }
197
  });