publicstring commited on
Commit
588b6da
·
verified ·
1 Parent(s): caedf2d

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +166 -1
app.js CHANGED
@@ -1 +1,166 @@
1
- g
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 || 8000;
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: `http://localhost:${PORT}/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
+ });