Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -1,166 +1,197 @@
|
|
| 1 |
require('dotenv').config();
|
| 2 |
-
const express
|
| 3 |
-
const fs
|
| 4 |
-
const path
|
| 5 |
const { ClinchSeller } = require('clinch-core');
|
| 6 |
-
const { GoogleGenAI }
|
| 7 |
|
| 8 |
const app = express();
|
| 9 |
app.use(express.json());
|
| 10 |
|
| 11 |
-
// ============================================================
|
| 12 |
-
//
|
| 13 |
-
// ============================================================
|
| 14 |
-
const PORT
|
| 15 |
-
const
|
| 16 |
-
const
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
}
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
|
| 27 |
-
// ============================================================
|
| 28 |
-
//
|
| 29 |
-
// ============================================================
|
| 30 |
const vendors = {};
|
| 31 |
-
const modulesDir = path.join(__dirname, 'modules');
|
| 32 |
|
| 33 |
function loadModules() {
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
console.log(`[System] Created ${modulesDir} directory.`);
|
| 37 |
-
return;
|
| 38 |
-
}
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
}
|
|
|
|
| 50 |
}
|
| 51 |
|
| 52 |
loadModules();
|
| 53 |
|
| 54 |
-
// ============================================================
|
| 55 |
-
//
|
| 56 |
-
// ============================================================
|
| 57 |
-
async function
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
const prompt = `
|
| 61 |
-
${itemData.context}
|
| 62 |
Item: ${itemData.id}
|
| 63 |
-
List
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
|
| 71 |
-
{
|
| 72 |
-
|
| 73 |
-
"reason": "<short conversational reason for the price>"
|
| 74 |
-
}`;
|
| 75 |
|
| 76 |
-
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
});
|
| 116 |
|
| 117 |
app.post('/anp/v1/counter', async (req, res) => {
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
-
|
| 126 |
-
if (!itemData) {
|
| 127 |
-
return res.status(400).json({ error: "Item not available or recognized" });
|
| 128 |
-
}
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
timestamp: new Date().toISOString()
|
| 138 |
-
});
|
| 139 |
});
|
| 140 |
|
| 141 |
-
// ============================================================
|
| 142 |
-
// BOOT
|
| 143 |
-
// ============================================================
|
| 144 |
app.listen(PORT, async () => {
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 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 |
});
|