Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
261 lines (238 loc) · 8.01 KB
/
Copy pathserver.ts
File metadata and controls
261 lines (238 loc) · 8.01 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
import express from 'express';
import path from 'path';
import { GoogleGenAI } from '@google/genai';
const app = express();
const PORT = 3000;
app.use(express.json());
// Lazy-initialized Gemini Client
let aiClient: GoogleGenAI | null = null;
function getGeminiClient(): GoogleGenAI | null {
if (!aiClient) {
const apiKey = process.env.GEMINI_API_KEY;
if (apiKey) {
aiClient = new GoogleGenAI({
apiKey,
httpOptions: { headers: { 'User-Agent': 'operon-ai' } },
});
}
}
return aiClient;
}
// API Health Check
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
app: 'OPERON',
version: '2.4.0',
serverTime: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
geminiConfigured: !!process.env.GEMINI_API_KEY,
services: {
workflowEngine: 'ONLINE',
policyEngine: 'ONLINE',
releaseGuardian: 'ONLINE',
actionRegistry: 'ONLINE',
aiGateway: process.env.GEMINI_API_KEY ? 'ONLINE' : 'DEMO_MODE',
},
});
});
// Gemini Text Generation Gateway
app.post('/api/gemini/generate', async (req, res) => {
try {
const { prompt, model = 'gemini-2.5-flash', systemInstruction } = req.body;
const client = getGeminiClient();
if (!client) {
return res.status(200).json({
text: `[OPERON AI Assistant - Demo Mode]: Structured response generated for request:\n\n` +
`• Intent: "${prompt.slice(0, 60)}"\n` +
`• Policy Boundaries: Verified against auto-refund cap.\n` +
`• Status: Safe for execution routing.`,
fallback: true,
});
}
const response = await client.models.generateContent({
model,
contents: prompt,
config: systemInstruction ? { systemInstruction } : undefined,
});
res.json({ text: response.text });
} catch (err: any) {
console.error('OPERON Gemini Gateway Error:', err);
res.status(500).json({ error: err?.message || 'Failed to process AI prompt' });
}
});
// Multi-Agent Orchestration Endpoint
app.post('/api/gemini/orchestrate', async (req, res) => {
try {
const { payload, workspace = 'support', policyLimit = 100 } = req.body;
const client = getGeminiClient();
if (!client) {
return res.json({
overallConfidence: 94,
recommendedAction: 'APPROVE',
riskScore: 18,
reasoning: [
'Intent Analyst classified customer request.',
'Context Memory verified customer tenure and zero anomaly signals.',
`Release Guardian enforced $${policyLimit} policy threshold; routed to human review gate if limit exceeded.`,
],
steps: [
{
id: 'step-1',
agentRole: 'analyst',
agentName: 'Intent Analyst',
stepName: 'Intent Classification',
status: 'completed',
output: `Analyzed customer input: "${payload || 'Standard customer refund request'}"`,
confidenceScore: 98,
},
{
id: 'step-2',
agentRole: 'fraud_sentinel',
agentName: 'Fraud & Anomaly Sentinel',
stepName: 'Risk & Anomaly Check',
status: 'completed',
output: 'Transaction velocity normal. Anomaly risk score: 18/100 (LOW).',
confidenceScore: 96,
},
{
id: 'step-3',
agentRole: 'planner',
agentName: 'Workflow Planner',
stepName: 'Policy Boundary Evaluation',
status: 'completed',
output: `Workspace [${workspace.toUpperCase()}] policy evaluation passed. Calculated risk index: Low.`,
confidenceScore: 94,
},
{
id: 'step-4',
agentRole: 'release_guardian',
agentName: 'Release Guardian',
stepName: 'Human Sign-off Gate',
status: 'awaiting_approval',
output: `Policy threshold cap checked ($${policyLimit}.00). Queued for human authorization.`,
confidenceScore: 91,
},
],
});
}
const systemPrompt = `You are the OPERON Autonomous Ops Multi-Agent Orchestrator.
Analyze the customer payload and return a JSON object with this exact structure:
{
"overallConfidence": 94,
"recommendedAction": "APPROVE" or "REJECT",
"riskScore": 18,
"reasoning": ["point 1", "point 2", "point 3"],
"steps": [
{
"id": "step-1",
"agentRole": "analyst",
"agentName": "Intent Analyst",
"stepName": "Intent Classification",
"status": "completed",
"output": "summary of intent analysis",
"confidenceScore": 98
},
{
"id": "step-2",
"agentRole": "fraud_sentinel",
"agentName": "Fraud & Anomaly Sentinel",
"stepName": "Risk & Anomaly Check",
"status": "completed",
"output": "summary of risk scoring",
"confidenceScore": 96
},
{
"id": "step-3",
"agentRole": "planner",
"agentName": "Workflow Planner",
"stepName": "Policy Evaluation",
"status": "completed",
"output": "summary of policy check",
"confidenceScore": 94
},
{
"id": "step-4",
"agentRole": "release_guardian",
"agentName": "Release Guardian",
"stepName": "Human Approval Gate",
"status": "awaiting_approval",
"output": "human review trigger explanation",
"confidenceScore": 91
}
]
}`;
const response = await client.models.generateContent({
model: 'gemini-2.5-flash',
contents: `Workspace: ${workspace}\nPayload: ${payload}`,
config: {
systemInstruction: systemPrompt,
responseMimeType: 'application/json',
},
});
const parsed = JSON.parse(response.text || '{}');
res.json(parsed);
} catch (err: any) {
console.error('OPERON Orchestration Error:', err);
res.status(500).json({ error: 'Orchestration failed' });
}
});
// Real-time Event Receiver / Webhook API Endpoint
app.post('/api/events', async (req, res) => {
try {
const { type, payload, workspace = 'support' } = req.body;
if (!type || typeof type !== 'string') {
return res.status(400).json({
success: false,
error: 'Event "type" string is required in request body (e.g. "Refund Request", "Customer Request", "Invoice Received", "Access Request", "Support Ticket")',
});
}
const eventId = `evt_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
const event = {
id: eventId,
type: type.trim(),
payload: payload || {},
workspace,
receivedAt: new Date().toISOString(),
status: 'ACCEPTED',
matchedWorkflow:
type.toLowerCase().includes('refund') ? 'wf-1' :
type.toLowerCase().includes('invoice') ? 'wf-2' :
type.toLowerCase().includes('access') || type.toLowerCase().includes('hr') ? 'wf-3' : 'wf-4',
message: `Event [${type}] received and queued for autonomous pipeline orchestration.`,
};
console.log(`[OPERON API Gateway] Inbound event processed: ${eventId} (${type})`);
res.json({
success: true,
eventId: event.id,
event,
});
} catch (err: any) {
console.error('OPERON Webhook API Error:', err);
res.status(500).json({ success: false, error: 'Internal server error processing event' });
}
});
// Serve Frontend in Development via Vite Middleware or Static Dist in Production
const distPath = path.join(process.cwd(), 'dist');
async function setupFrontend() {
if (process.env.NODE_ENV !== 'production') {
const { createServer: createViteServer } = await import('vite');
const vite = await createViteServer({
server: {
middlewareMode: true,
hmr: false, // Prevents failed websocket attempts in container dev environment
},
appType: 'spa',
});
app.use(vite.middlewares);
} else {
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`OPERON server running on http://0.0.0.0:${PORT}`);
});
}
setupFrontend();