-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
435 lines (372 loc) · 14.2 KB
/
Copy pathserver.js
File metadata and controls
435 lines (372 loc) · 14.2 KB
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import express from "express";
import path from "path";
import { fileURLToPath } from "url";
import dotenv from "dotenv";
import { DefaultAzureCredential } from "@azure/identity";
import { SecretClient } from "@azure/keyvault-secrets";
import {
getCrop,
evaluateQuality,
optimizeValueChain,
generateSupplyContract,
getProcessorNetwork,
getAdvisorReply,
getCropInsights,
getPortfolioInsights,
syncFabricGraph,
getFabricStatus,
} from "./lib/iq-data.js";
import {
getWorkIQStatus,
notifyOptimizationComplete,
notifyContractGenerated,
} from "./lib/work-iq.js";
import { recordTrade, getTradeHistory } from "./lib/agent-memory.js";
dotenv.config();
const app = express();
app.set("trust proxy", 1); // Azure App Service runs behind a proxy — needed for per-IP rate limits
const PORT = process.env.PORT || 3000;
const ALLOWED_ORIGINS = (
process.env.CORS_ORIGINS || "https://cdm227.github.io,http://localhost:3000"
)
.split(",")
.map((s) => s.trim());
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function sameRequestHost(source, req) {
try {
const sourceUrl = new URL(source);
const host = req.headers["x-forwarded-host"] || req.headers.host;
return sourceUrl.host === host;
} catch {
return false;
}
}
function isAllowedOrigin(origin, req) {
if (!origin) return true;
if (sameRequestHost(origin, req)) return true;
return ALLOWED_ORIGINS.some((o) => origin === o || origin.startsWith(o.replace(/\/$/, "")));
}
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && isAllowedOrigin(origin, req)) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") return res.sendStatus(204);
next();
});
// Origin gate: reject browser API calls from foreign sites (CORS alone doesn't block the request server-side)
app.use("/api", (req, res, next) => {
const source = req.headers.origin || req.headers.referer;
if (source && !isAllowedOrigin(source, req)) {
console.warn(`[SECURITY] Blocked foreign origin: ${source} → ${req.path}`);
return res.status(403).json({ error: "Origin not allowed" });
}
next();
});
// Lightweight in-memory rate limiter (per IP, sliding window)
const rateBuckets = new Map();
function rateLimit(windowMs, max) {
return (req, res, next) => {
const key = `${req.ip}:${windowMs}:${max}`;
const now = Date.now();
const hits = (rateBuckets.get(key) || []).filter((t) => now - t < windowMs);
if (hits.length >= max) {
return res.status(429).json({ error: "Too many requests — slow down" });
}
hits.push(now);
rateBuckets.set(key, hits);
next();
};
}
setInterval(() => {
const now = Date.now();
for (const [key, hits] of rateBuckets) {
const alive = hits.filter((t) => now - t < 600000);
if (alive.length === 0) rateBuckets.delete(key);
else rateBuckets.set(key, alive);
}
}, 60000).unref();
app.use("/api", rateLimit(60000, 60)); // 60 req/min — all API
const expensiveLimit = rateLimit(300000, 15); // 15 req/5min — Azure-backed routes
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
const vaultName = process.env.KEYVAULT_NAME;
let secretClient = null;
if (vaultName) {
const vaultUrl = `https://${vaultName}.vault.azure.net`;
secretClient = new SecretClient(vaultUrl, new DefaultAzureCredential());
}
async function getSecureSecret(secretName) {
if (secretClient) {
try {
const secret = await secretClient.getSecret(secretName);
return secret.value;
} catch {
console.warn(`⚠️ Key Vault lookup failed for [${secretName}]`);
}
}
return process.env[secretName.replace(/-/g, "_")];
}
async function getFoundryAuthHeaders(apiKey) {
if (apiKey) return { "api-key": apiKey };
const token = await new DefaultAzureCredential().getToken("https://ai.azure.com/.default");
if (!token?.token) throw new Error("Unable to acquire Azure AI Foundry bearer token");
return { Authorization: `Bearer ${token.token}` };
}
async function pollRun(threadId, runId, apiKey, endpoint) {
const url = `${endpoint}/openai/threads/${threadId}/runs/${runId}?api-version=2024-02-15-preview`;
while (true) {
const res = await fetch(url, { headers: { "api-key": apiKey } });
const data = await res.json();
if (data.status === "completed") return data;
if (data.status === "failed" || data.status === "cancelled")
throw new Error(`Agent run: ${data.status}`);
await new Promise((r) => setTimeout(r, 1000));
}
}
function parseFoundryText(data) {
if (!data) return null;
if (typeof data.output_text === "string") return data.output_text;
if (typeof data.text === "string") return data.text;
const output = Array.isArray(data.output) ? data.output : [];
for (const item of output) {
const content = Array.isArray(item.content) ? item.content : [];
for (const part of content) {
if (typeof part.text === "string") return part.text;
if (typeof part.output_text === "string") return part.output_text;
}
}
const choices = Array.isArray(data.choices) ? data.choices : [];
return choices[0]?.message?.content ?? choices[0]?.text ?? null;
}
async function queryFoundryResponsesAgent({ crop, qtyTons, isOrganic }) {
const baseUrl = process.env.FOUNDRY_OPENAI_BASE_URL?.replace(/\/$/, "");
const endpoint =
process.env.FOUNDRY_RESPONSES_ENDPOINT || (baseUrl ? `${baseUrl}/responses` : null);
const model = process.env.FOUNDRY_MODEL_DEPLOYMENT || "gpt-4o";
const apiKey = await getSecureSecret("FOUNDRY-API-KEY");
if (!endpoint) return null;
const prompt = [
"You are AgriValue Advisor, a Microsoft Foundry agent for agricultural value-chain optimization.",
`Farmer scenario: ${qtyTons} metric tons of ${crop}.`,
`Certified organic/DOP/DOC flag: ${isOrganic}.`,
"Use your grounded project knowledge and answer with:",
"1. applicable compliance rule",
"2. required evidence/documents",
"3. premium bonus as $X/ton if eligible",
"4. one concise recommendation for Path B processing.",
].join("\n");
const headers = {
"Content-Type": "application/json",
...(await getFoundryAuthHeaders(apiKey)),
};
const body = endpoint.includes("/openai/v1/") ? { model, input: prompt } : { input: prompt };
const res = await fetch(endpoint, {
method: "POST",
headers,
body: JSON.stringify(body),
});
if (!res.ok) {
const body = await res.text();
throw new Error(`Foundry Responses API ${res.status}: ${body.slice(0, 240)}`);
}
return parseFoundryText(await res.json());
}
async function queryFoundryAgent({ crop, qtyTons, isOrganic }) {
const responsesReply = await queryFoundryResponsesAgent({ crop, qtyTons, isOrganic });
if (responsesReply) return responsesReply;
const azureApiKey = await getSecureSecret("AZURE-OPENAI-API-KEY");
const agentId = process.env.AZURE_AI_AGENT_ID;
const endpoint = process.env.AZURE_OPENAI_ENDPOINT;
if (!azureApiKey || !agentId || !endpoint) return null;
const apiVersion = "2024-02-15-preview";
const threadRes = await fetch(`${endpoint}/openai/threads?api-version=${apiVersion}`, {
method: "POST",
headers: { "Content-Type": "application/json", "api-key": azureApiKey },
});
const thread = await threadRes.json();
await fetch(`${endpoint}/openai/threads/${thread.id}/messages?api-version=${apiVersion}`, {
method: "POST",
headers: { "Content-Type": "application/json", "api-key": azureApiKey },
body: JSON.stringify({
role: "user",
content: `Farmer has ${qtyTons} tons of ${crop}. Organic certified: ${isOrganic}. Query knowledge files. Output compliance rule and premium bonus as $X/ton.`,
}),
});
const runRes = await fetch(
`${endpoint}/openai/threads/${thread.id}/runs?api-version=${apiVersion}`,
{
method: "POST",
headers: { "Content-Type": "application/json", "api-key": azureApiKey },
body: JSON.stringify({ assistant_id: agentId }),
}
);
const run = await runRes.json();
await pollRun(thread.id, run.id, azureApiKey, endpoint);
const msgRes = await fetch(
`${endpoint}/openai/threads/${thread.id}/messages?api-version=${apiVersion}`,
{
headers: { "api-key": azureApiKey },
}
);
const msgs = await msgRes.json();
return msgs.data[0]?.content[0]?.text?.value ?? null;
}
function foundryConfigured() {
return Boolean(
process.env.FOUNDRY_RESPONSES_ENDPOINT ||
process.env.FOUNDRY_OPENAI_BASE_URL ||
(process.env.AZURE_AI_AGENT_ID && process.env.AZURE_OPENAI_ENDPOINT)
);
}
app.get("/api/status", async (_req, res) => {
const fabric = getFabricStatus();
const work = getWorkIQStatus();
res.json({
fabricIQ: fabric,
foundryIQ: { configured: foundryConfigured(), live: foundryConfigured() },
workIQ: work,
version: "3.0.0",
});
});
app.get("/api/processors", (_req, res) => {
res.json(getProcessorNetwork());
});
app.get("/api/crop/:name", (req, res) => {
const crop = getCrop(req.params.name);
if (!crop) return res.status(404).json({ error: "Crop not found" });
res.json(crop);
});
app.post("/api/evaluate-quality", (req, res) => {
const { crop } = req.body;
if (!crop) return res.status(400).json({ error: "No crop specified" });
res.json(evaluateQuality(crop));
});
app.post("/api/advisor", expensiveLimit, async (req, res) => {
const { message, crop, language, stream, recentTrades } = req.body;
if (!message) return res.status(400).json({ error: "Message required" });
const memory =
Array.isArray(recentTrades) && recentTrades.length ? recentTrades : getTradeHistory(5);
let reply = getAdvisorReply(message, { crop, language, recentTrades: memory });
if (foundryConfigured() && message.length > 20) {
try {
const agentReply = await queryFoundryAgent({
crop: crop || "Olive Oil",
qtyTons: 10,
isOrganic: true,
});
if (agentReply) reply = `${reply}\n\n**Foundry IQ adds:** ${agentReply.slice(0, 500)}`;
} catch {
/* advisor falls back to rule-based */
}
}
if (stream) {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
const words = reply.split(" ");
for (const word of words) {
res.write(`data: ${JSON.stringify({ token: word + " " })}\n\n`);
await new Promise((r) => setTimeout(r, 30));
}
res.write(`data: ${JSON.stringify({ done: true })}\n\n`);
return res.end();
}
res.json({ reply });
});
app.get("/api/insights/portfolio", (req, res) => {
const qtyTons = Number(req.query.qty) || 10;
res.json(getPortfolioInsights(qtyTons));
});
app.get("/api/insights/:crop", (req, res) => {
const qtyTons = Number(req.query.qty) || 10;
const insights = getCropInsights(req.params.crop, qtyTons);
if (!insights) return res.status(404).json({ error: "Crop not found" });
res.json(insights);
});
app.post("/api/optimize", expensiveLimit, async (req, res) => {
const { crop, qtyTons, isOrganic, qualityMultiplier = 1.0, notifyTeams } = req.body;
if (!crop || !qtyTons) return res.status(400).json({ error: "Missing parameters" });
console.log(
`[IQ PIPELINE] ${crop} | ${qtyTons} MT | organic=${isOrganic} | quality=${qualityMultiplier}x`
);
let foundryRule = null;
let bonusOverride = 0;
try {
const agentReply = await queryFoundryAgent({ crop, qtyTons, isOrganic });
if (agentReply) {
foundryRule = agentReply;
const bonusMatch = agentReply.match(/\$?([0-9]+)\/ton/);
if (bonusMatch) bonusOverride = parseInt(bonusMatch[1]) * qtyTons;
}
} catch (err) {
console.warn("[FOUNDRY IQ]", err.message);
}
const result = optimizeValueChain({ crop, qtyTons, isOrganic, qualityMultiplier });
if (foundryRule) {
result.processedPath.foundryIQRule = foundryRule;
if (bonusOverride > 0) {
const prev = result.processedPath.organicBonus;
result.processedPath.organicBonus = bonusOverride;
result.processedPath.gross = result.processedPath.gross - prev + bonusOverride;
result.processedPath.net =
result.processedPath.gross -
result.processedPath.processingCost -
result.processedPath.transport;
result.addedValue = Math.max(0, result.processedPath.net - result.rawPath.net);
}
}
result.iqLayers = {
fabric: getFabricStatus().source,
foundry: foundryRule ? "live-agent" : foundryConfigured() ? "fallback-rules" : "local-rules",
};
if (notifyTeams !== false && getWorkIQStatus().active) {
result.workIQ = await notifyOptimizationComplete(result);
}
recordTrade({
crop,
qtyTons: Number(qtyTons),
isOrganic: !!isOrganic,
qualityMultiplier: Number(qualityMultiplier) || 1,
addedValue: result.addedValue,
pathBNet: result.processedPath?.net,
});
res.json(result);
});
app.get("/api/trade-history", (req, res) => {
const limit = Number(req.query.limit) || 20;
res.json({ trades: getTradeHistory(limit) });
});
app.post("/api/generate-contract", async (req, res) => {
const { crop, qtyTons, buyer, isOrganic, notifyTeams } = req.body;
if (!crop || !qtyTons) return res.status(400).json({ error: "Missing parameters" });
const contract = generateSupplyContract({ crop, qtyTons, buyer, isOrganic });
if (!contract) return res.status(404).json({ error: "Crop not found" });
let workIQ = null;
if (notifyTeams !== false && getWorkIQStatus().active) {
workIQ = await notifyContractGenerated({ crop, qtyTons, buyer });
}
res.json({ contract, workIQ });
});
app.post("/api/notify-teams", async (req, res) => {
const result = req.body;
if (!result?.crop) return res.status(400).json({ error: "Optimization result required" });
const workIQ = await notifyOptimizationComplete(result);
res.json(workIQ);
});
app.post("/api/fabric/sync", rateLimit(300000, 3), async (_req, res) => {
const sync = await syncFabricGraph(true);
res.json(sync);
});
async function bootstrap() {
await syncFabricGraph(true);
app.listen(PORT, () => {
console.log(`🛡️ AgriValue IQ server v3 — http://localhost:${PORT}`);
console.log(
` Fabric: ${getFabricStatus().source} | Foundry: ${foundryConfigured() ? "configured" : "local"} | Work IQ: ${getWorkIQStatus().active ? "active" : "off"}`
);
});
}
bootstrap();