-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
384 lines (343 loc) · 13.8 KB
/
Copy pathserver.ts
File metadata and controls
384 lines (343 loc) · 13.8 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
import express from "express";
import path from "path";
import { createServer as createViteServer } from "vite";
import { GoogleGenAI, Type } from "@google/genai";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// Gemini Initialization
const ai = new GoogleGenAI({
apiKey: process.env.GEMINI_API_KEY || "",
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
}
}
});
const MODELS = [
"gemini-3-flash",
"gemini-3.1-flash-lite",
"gemini-2.5-flash",
"gemini-2.5-flash-lite",
"gemini-2.0-flash",
"gemini-1.5-flash",
"gemini-1.5-flash-8b",
];
async function generateWithFallback(options: any) {
let lastError: any;
for (const model of MODELS) {
try {
console.log(`Neural Link: Attempting synthesis with ${model}...`);
const response = await ai.models.generateContent({
...options,
model: model,
});
return response;
} catch (error: any) {
lastError = error;
const errorMsg = (error.message || "").toLowerCase();
const statusCode = error.status || error.code || 0;
const isQuota = statusCode === 429 ||
errorMsg.includes('429') ||
errorMsg.includes('resource_exhausted') ||
errorMsg.includes('quota') ||
errorMsg.includes('limit reached');
const isNotFound = statusCode === 404 ||
errorMsg.includes('404') ||
errorMsg.includes('not_found') ||
errorMsg.includes('not supported') ||
errorMsg.includes('not found');
if (isQuota || isNotFound) {
console.warn(`Neural Link: ${model} ${isQuota ? 'rate limited' : 'unavailable'}. Re-routing to peer node...`);
continue;
}
throw error;
}
}
throw lastError;
}
/**
* AI Complex Decomposition Endpoint
*/
app.post("/api/ai/decompose", async (req, res) => {
try {
const { input, userProfile } = req.body;
if (!input) {
return res.status(400).json({ error: "input is required" });
}
const systemContext = userProfile ? `User Profile: Name: ${userProfile.name}, Bio: ${userProfile.bio}.` : "User Profile: Not provided.";
const response = await generateWithFallback({
contents: `${systemContext}
Act as the Orbita AI Neural Architect. You are analyzing a high-volume data stream.
STEP 1: CONTEXT INFERENCE
Analyze the input stream to infer the Industry, Project Type, and User's Role if not explicitly stated. Use this inferred context to tailor the task decomposition.
STEP 2: PROJECT MAPPING
Define a high-level "Sector" (Workspace) name that encapsulates this entire stream. If it's a meeting, name it after the project/topic discussed.
STEP 3: NODAL DECOMPOSITION
Extract a set of organized, actionable, and significant tasks (Nodes).
- Distinguish between "Action Items" (direct tasks) and "Strategic Goals".
- For meeting transcripts: Identify specific stakeholders (people) mentioned and assign them to tasks.
- Dependency Mapping: Identify if a task logically must follow another.
- Ensure tasks are significant. Merge minor, related points into cohesive work packages.
Input Stream: "${input}"
For each Node (Task) identified:
1. title: Imperative, clear title.
2. description: Detail the 'Why' and the 'Consensus' or 'Reasoning' behind the task.
3. subtasks: A comprehensive, step-by-step checklist for execution.
4. priority: Scale of urgency [Low, Medium, High, Critical].
5. complexity: Numeric value [1-5] representing operational difficulty.
6. estimatedTime: A human-readable estimate (e.g., "4h", "2d", "15m").
7. tags: 2-3 specific, relevant technical or functional tags.
8. stakeholders: Array of names identified as relevant to this task.
9. dependencies: Array of other task titles this depends on.
STEP 4: STRATEGIC SYNTHESIS
Provide a 'strategicBrief' which is a short (2-sentence max) executive summary of the workload's core objective.
Response Format: JSON object with 'suggestedWorkspaceName', 'strategicBrief', and an array of 'tasks'.`,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
suggestedWorkspaceName: { type: Type.STRING },
strategicBrief: { type: Type.STRING },
tasks: {
type: Type.ARRAY,
items: {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING },
description: { type: Type.STRING },
subtasks: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
priority: { type: Type.STRING, enum: ["Low", "Medium", "High", "Critical"] },
complexity: { type: Type.NUMBER },
estimatedTime: { type: Type.STRING },
tags: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
stakeholders: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
dependencies: {
type: Type.ARRAY,
items: { type: Type.STRING }
}
},
required: ["title", "description", "subtasks", "priority", "complexity", "estimatedTime", "tags"]
}
}
},
required: ["suggestedWorkspaceName", "strategicBrief", "tasks"]
}
}
});
const result = JSON.parse(response.text);
res.json(result);
} catch (error: any) {
console.error("AI Decomposition Error:", error);
const statusCode = error.status || error.code || 500;
if (statusCode === 429 || error.message?.includes('429')) {
return res.status(429).json({ error: "AI Neural Core is busy. Please wait 60 seconds." });
}
res.status(500).json({ error: "Failed to decompose input" });
}
});
/**
* AI Task Expansion Endpoint
*/
app.post("/api/ai/expand-task", async (req, res) => {
try {
const { taskTitle, userProfile } = req.body;
if (!taskTitle) {
return res.status(400).json({ error: "taskTitle is required" });
}
const systemContext = userProfile ? `User Context: ${userProfile.name}, bio: ${userProfile.bio}. Industry: ${userProfile.industry || 'General'}.` : "";
const response = await generateWithFallback({
contents: `${systemContext} Create a detailed execution plan for the following task: "${taskTitle}".
Break it down into actionable subtasks, provide a brief summary, suggest a priority (Low, Medium, High, Critical), estimate its complexity (1-5), and estimated duration.`,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
summary: { type: Type.STRING },
subtasks: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
priority: { type: Type.STRING, enum: ["Low", "Medium", "High", "Critical"] },
complexity: { type: Type.NUMBER },
estimatedTime: { type: Type.STRING }
},
required: ["summary", "subtasks", "priority", "complexity", "estimatedTime"]
}
}
});
const result = JSON.parse(response.text);
res.json(result);
} catch (error: any) {
console.error("AI Expansion Error:", error);
const statusCode = error.status || error.code || 500;
if (statusCode === 429 || error.message?.includes('429')) {
return res.status(429).json({ error: "AI Resources Exhausted. Please wait a moment." });
}
res.status(500).json({ error: "Failed to generate AI plan" });
}
});
async function chatWithFallback(options: { message: string; context?: any }) {
let lastError: any;
for (const model of MODELS) {
try {
console.log(`Neural Link: Chat uplink with ${model}...`);
const chat = ai.chats.create({
model: model,
config: {
systemInstruction: "You are the Orbita AI Neural Core, a high-end productivity AI assistant. You help users optimize their workflows, break down complex projects into actionable nodes, and maintain peak operational efficiency. You are professional, futuristic, and highly actionable. Context: " + JSON.stringify(options.context || {}),
},
});
const response = await chat.sendMessage({ message: options.message });
return response;
} catch (error: any) {
lastError = error;
const errorMsg = (error.message || "").toLowerCase();
const statusCode = error.status || error.code || 0;
const isQuota = statusCode === 429 ||
errorMsg.includes('429') ||
errorMsg.includes('resource_exhausted') ||
errorMsg.includes('quota') ||
errorMsg.includes('limit reached');
const isNotFound = statusCode === 404 ||
errorMsg.includes('404') ||
errorMsg.includes('not_found') ||
errorMsg.includes('not supported') ||
errorMsg.includes('not found');
if (isQuota || isNotFound) {
console.warn(`Neural Link: Chat node ${model} ${isQuota ? 'rate limited' : 'unavailable'}. Re-routing uplink...`);
continue;
}
throw error;
}
}
throw lastError;
}
/**
* AI Assistant Chat Endpoint
*/
app.post("/api/ai/chat", async (req, res) => {
try {
const { message, context } = req.body;
const response = await chatWithFallback({ message, context });
res.json({ response: response.text });
} catch (error: any) {
console.error("AI Chat Error:", error);
const statusCode = error.status || error.code || 500;
if (statusCode === 429 || error.message?.includes('429')) {
return res.status(429).json({ error: "Assistant busy (Quota Limit). Please retry shortly." });
}
res.status(500).json({ error: "AI Assistant unavailable" });
}
});
/**
* Productivity Insights Endpoint
*/
app.post("/api/ai/insights", async (req, res) => {
try {
const { taskHistory } = req.body;
const response = await generateWithFallback({
contents: "Analyze this task history and provide 3 smart productivity insights and a 'Focus Score' (1-100). Task History: " + JSON.stringify(taskHistory),
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
insights: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
focusScore: { type: Type.NUMBER },
recommendation: { type: Type.STRING }
},
required: ["insights", "focusScore", "recommendation"]
}
}
});
res.json(JSON.parse(response.text));
} catch (error: any) {
console.error("AI Insights Error:", error);
const statusCode = error.status || error.code || 500;
if (statusCode === 429 || error.message?.includes('429')) {
return res.status(429).json({ error: "Insights engine on cooldown (Quota). Try again later." });
}
res.status(500).json({ error: "Failed to generate insights" });
}
});
/**
* AI Neural Synthesis Endpoint
* Provides a high-level briefing of the current system state.
*/
app.post("/api/ai/synthesis", async (req, res) => {
try {
const { tasks, workspaces, userProfile } = req.body;
const response = await generateWithFallback({
contents: `User: ${userProfile?.name}. Bio: ${userProfile?.bio}.
Analyze the following system state and provide a concise 'Neural Briefing'.
- Identify bottlenecks or overdue priorities.
- Suggest the top 3 high-impact actions for today.
- Provide a motivational 'Operator Directive'.
State: Workspaces: ${JSON.stringify(workspaces)}, Tasks: ${JSON.stringify(tasks.filter((t: any) => !t.isDeleted))}`,
config: {
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
briefing: { type: Type.STRING },
topActions: {
type: Type.ARRAY,
items: { type: Type.STRING }
},
directive: { type: Type.STRING }
},
required: ["briefing", "topActions", "directive"]
}
}
});
res.json(JSON.parse(response.text));
} catch (error: any) {
console.error("AI Synthesis Error:", error);
const statusCode = error.status || error.code || 500;
if (statusCode === 429 || error.message?.includes('429')) {
return res.status(429).json({
error: "Neural Link Quota Exceeded",
message: "The AI Core is cooling down. Please retry in a few moments."
});
}
res.status(500).json({ error: "Synthesis engine offline" });
}
});
// Vite middleware for development
async function startServer() {
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
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(`Server running on http://localhost:${PORT}`);
});
}
startServer();