Spaces:
Sleeping
Sleeping
File size: 8,877 Bytes
cf28d83 894a3b5 588b6da c4da555 894a3b5 c4da555 894a3b5 c4da555 588b6da 894a3b5 f19fb44 c4da555 894a3b5 588b6da c4da555 588b6da c4da555 894a3b5 c4da555 588b6da 894a3b5 588b6da c4da555 588b6da c4da555 588b6da c4da555 588b6da c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 588b6da c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 588b6da c4da555 894a3b5 c4da555 588b6da c4da555 894a3b5 588b6da 894a3b5 588b6da 894a3b5 c4da555 894a3b5 c4da555 588b6da 894a3b5 588b6da 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 894a3b5 c4da555 588b6da 894a3b5 588b6da 894a3b5 c4da555 894a3b5 c4da555 588b6da 894a3b5 588b6da c4da555 588b6da 894a3b5 c4da555 894a3b5 588b6da 894a3b5 c4da555 588b6da | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | 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.`);
}
}); |