sellersnode / app(sellers).js
publicstring's picture
Rename app.js to app(sellers).js
27eac3d verified
Raw History Blame Contribute Delete
8.88 kB
require('dotenv').config();
const express = require('express');
const fs = require('fs');
const path = require('path');
const { ClinchCore, NegotiationState } = require('clinch-core');
const { GoogleGenAI } = require('@google/genai');
const app = express();
app.use(express.json());
// ============================================================
// CONFIGURATION
// ============================================================
const PORT = process.env.PORT || 7860;
const REGISTRY_URL = process.env.REGISTRY_URL || 'https://registry.clinch.network';
const SELLER_PRIV_KEY = process.env.SELLER_PRIVATE_KEY;
const PUBLIC_ENDPOINT = process.env.PUBLIC_ENDPOINT;
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
if (!PUBLIC_ENDPOINT || !SELLER_PRIV_KEY) {
console.error('FATAL: PUBLIC_ENDPOINT and SELLER_PRIVATE_KEY must be set.');
console.error('Example PUBLIC_ENDPOINT: https://mystore.com/anp/v1');
process.exit(1);
}
// v0.2.0 Core Initialization
const sellerCore = new ClinchCore({
privateKeyHex: SELLER_PRIV_KEY
});
sellerCore.on('log', msg => console.log(`[Seller Core] ${msg}`));
const ai = GEMINI_API_KEY ? new GoogleGenAI({ apiKey: GEMINI_API_KEY }) : null;
// ============================================================
// MULTI-TENANT PLUGIN LOADER
// ============================================================
const vendors = {};
const sessionVendorMap = new Map(); // Maps running sessions to their specific vendor module
function loadModules() {
const dir = path.join(__dirname, 'modules');
if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); return; }
for (const file of fs.readdirSync(dir).filter(f => f.endsWith('.js'))) {
try {
const mod = require(path.join(dir, file));
if (!mod.agent_id || !mod.getItemConstraints) {
console.warn(`[Modules] Skipped ${file} — missing agent_id or getItemConstraints`);
continue;
}
vendors[mod.agent_id] = mod;
console.log(`[Modules] Loaded: ${mod.agent_id}`);
} catch (e) {
console.error(`[Modules] Failed to load ${file}:`, e.message);
}
}
}
loadModules();
// ============================================================
// GEMINI AI ENGINE
// ============================================================
async function evaluateOffer(buyerOffer, itemData, turn) {
if (!ai) {
// Math-based fallback if no Gemini key is provided
const range = itemData.list_price - itemData.floor_price;
const step = range * 0.15;
const counter = Math.max(itemData.floor_price, itemData.list_price - (step * turn));
return { price: Math.round(counter * 100) / 100, reason: 'Meeting you partway to keep the deal moving.' };
}
const prompt = `You are a professional B2B seller agent negotiating via the Clinch Protocol.
Item: ${itemData.id}
List price: $${itemData.list_price}
Floor price (never go below this): $${itemData.floor_price}
Buyer offered: $${buyerOffer}
Turn: ${turn}
Rules:
- If buyer is within 5% of floor: accept at floor price.
- Otherwise: counter, moving 5-8% toward buyer per turn.
- Be extremely brief and professional.
Respond ONLY with valid JSON (no markdown block wrapping):
{"price": <number>, "reason": "<one concise sentence>"}`;
try {
const res = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: prompt,
config: { temperature: 0.2 }
});
// Clean potential markdown from Gemini output
const cleanJson = res.text.replace(/```json|```/g, "").trim();
const result = JSON.parse(cleanJson);
return {
price: Math.max(result.price, itemData.floor_price),
reason: result.reason
};
} catch (e) {
console.error('[AI Engine Error]', e.message);
return { price: itemData.list_price, reason: 'Unable to adjust price dynamically at this time.' };
}
}
// ============================================================
// ANP v0.2.0 SYNCHRONOUS ROUTES
// ============================================================
app.post('/anp/v1/handshake', (req, res) => {
const { session_id, constraints, target, buyer_pub_key } = req.body;
console.log(`\n[Handshake] ${session_id} targeting ${target}`);
const vendor = vendors[target];
if (!vendor) {
return res.status(404).json({ type: 'CANCEL', reason: `Domain ${target} not hosted here` });
}
// Register session locally
sellerCore.registerIncomingSession(session_id, buyer_pub_key, constraints);
sessionVendorMap.set(session_id, vendor);
const itemIntent = constraints?.item || "General Item";
const itemData = vendor.getItemConstraints(itemIntent);
if (!itemData) {
sellerCore.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, 0, 1);
return res.status(400).json({ type: 'CANCEL', reason: `Item not found or unavailable.` });
}
// Evaluate Initial Deal automatically
const budget = constraints.max_budget;
if (budget !== null && budget >= itemData.list_price) {
// Buyer opened above our list price, confirm immediately
sellerCore.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, itemData.list_price, 1);
return res.json({ type: 'CONFIRM', price: itemData.list_price });
} else {
// Counter with list price to start the haggling
sellerCore.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, itemData.list_price, 2);
return res.json({
type: 'COUNTER',
price: itemData.list_price,
turn: 2,
message: `Welcome to ${vendor.display_name}. The listing price for ${itemData.id} is $${itemData.list_price}.`
});
}
});
app.post('/anp/v1/counter', async (req, res) => {
const { session_id, price, turn, reason } = req.body;
const currentTurn = turn || 2;
const nextTurn = currentTurn + 1;
console.log(`[Counter] ${session_id} | Turn ${currentTurn} | $${price}`);
const vendor = sessionVendorMap.get(session_id);
const session = sellerCore.getSession(session_id);
if (!vendor || !session) {
return res.status(404).json({ type: 'CANCEL', reason: "Session or Vendor context lost." });
}
const itemData = vendor.getItemConstraints(session.constraints.item);
// If buyer met our absolute floor or is within 2%, accept.
if (price >= itemData.floor_price * 0.98) {
const finalPrice = Math.max(price, itemData.floor_price);
sellerCore.updateSessionStateLocally(session_id, NegotiationState.CONFIRMED, finalPrice, currentTurn);
return res.json({
type: 'CONFIRM',
price: finalPrice,
message: "We have a deal. Awaiting your cryptographic signature."
});
}
// Max turn limit check
if (currentTurn >= 6) {
sellerCore.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, price, currentTurn);
return res.json({ type: 'CANCEL', reason: "Max negotiation turns reached without agreement." });
}
// Let Gemini evaluate the counter
const { price: counterPrice, reason: counterReason } = await evaluateOffer(price, itemData, currentTurn);
sellerCore.updateSessionStateLocally(session_id, NegotiationState.COUNTERED, counterPrice, nextTurn);
res.json({
type: 'COUNTER',
price: counterPrice,
turn: nextTurn,
message: counterReason
});
});
app.post('/anp/v1/cancel', (req, res) => {
const { session_id } = req.body;
sellerCore.updateSessionStateLocally(session_id, NegotiationState.CANCELLED, 0);
sessionVendorMap.delete(session_id);
res.json({ success: true });
});
// ============================================================
// BILATERAL SIGNATURE HANDLER
// ============================================================
app.post('/anp/v1/sign_request', (req, res) => {
try {
const sig = sellerCore.signAsSeller(req.body.artifact);
res.json({ sellerSignature: sig });
console.log(`[Deal Signed] Session ${req.body.artifact.sessionId} locked at $${req.body.artifact.price}`);
} catch (e) {
res.status(400).json({ error: e.message });
}
});
// ============================================================
// BOOT
// ============================================================
app.listen(PORT, async () => {
console.log(`\n💼 Vendor Hub Online | Port ${PORT}`);
console.log(` Stable Endpoint: ${PUBLIC_ENDPOINT}\n`);
try {
console.log("⏳ Initializing Transport Auth...");
await sellerCore.initialize();
setInterval(() => sellerCore.initialize().catch(()=>{}), 5 * 24 * 60 * 60 * 1000);
for (const [domain, mod] of Object.entries(vendors)) {
await sellerCore.registerNode(
`${PUBLIC_ENDPOINT}/anp/v1`,
mod.categories || [],
mod.capabilities || []
);
console.log(`✓ Node registered: ${domain}`);
}
} catch (e) {
console.error(`[Boot Error] ${e.message}`);
console.error(`Ensure your REGISTRY_URL is reachable and SELLER_PRIVATE_KEY is correct.`);
}
});