everydaytok commited on
Commit
01043cc
·
verified ·
1 Parent(s): dd20980

Create app.js

Browse files
Files changed (1) hide show
  1. app.js +323 -0
app.js ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import cors from 'cors';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { createClient } from '@supabase/supabase-js';
6
+
7
+ const PORT = 7860;
8
+ const SUPABASE_URL = process.env.SUPABASE_URL;
9
+ const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
10
+ const REMOTE_SERVER_URL = process.env.REMOTE_AI_URL || "http://localhost:11434";
11
+ const FRONT_URL = process.env.FRONT_URL;
12
+ const CRON_REGISTRY_URL = process.env.CRON_REGISTRY_URL || "http://localhost:7861";
13
+ const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
14
+
15
+ const SMART_MODEL_ID = "claude";
16
+ const FAST_MODEL_ID = "gpt-5-mini";
17
+
18
+ // The Utility Server that handles the Email Dispatching
19
+ const UTILITY_SERVER_URL = process.env.UTILITY_SERVER_URL || "https://lu5zfciin5mk34fowavmhz7dt40pkhhg.lambda-url.us-east-1.on.aws";
20
+
21
+ if (!SUPABASE_URL || !SUPABASE_KEY) process.exit(1);
22
+
23
+ const app = express();
24
+ const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
25
+
26
+ app.use(express.json({ limit: '50mb' }));
27
+ app.use(cors());
28
+
29
+ let prompts = {};
30
+ try {
31
+ prompts = JSON.parse(fs.readFileSync(path.resolve('./prompts.json'), 'utf8'));
32
+ } catch (e) { process.exit(1); }
33
+
34
+ const activeProjects = new Map();
35
+
36
+ const StateManager = {
37
+ getHistory: async (projectId) => {
38
+ if (activeProjects.has(projectId)) return activeProjects.get(projectId).history;
39
+ const { data: chunks } = await supabase.from('message_chunks').select('*').eq('project_id', projectId).order('chunk_index', { ascending: false }).limit(10);
40
+ const fullHistory = (chunks || []).reverse().flatMap(c => c.payload ||[]);
41
+ activeProjects.set(projectId, { history: fullHistory, isFrozen: false });
42
+ return fullHistory;
43
+ },
44
+ addHistory: async (projectId, role, text) => {
45
+ const newMessage = { role, parts: [{ text }] };
46
+ if (activeProjects.has(projectId)) activeProjects.get(projectId).history.push(newMessage);
47
+ try {
48
+ const { data: latestChunk } = await supabase.from('message_chunks').select('id, chunk_index, payload').eq('project_id', projectId).order('chunk_index', { ascending: false }).limit(1).single();
49
+ const currentPayload = (latestChunk?.payload) ||[];
50
+ if (latestChunk && currentPayload.length < 20) {
51
+ await supabase.from('message_chunks').update({ payload: [...currentPayload, newMessage] }).eq('id', latestChunk.id);
52
+ } else {
53
+ await supabase.from('message_chunks').insert({ project_id: projectId, lead_id: projectId, chunk_index: (latestChunk?.chunk_index ?? -1) + 1, payload: [newMessage] });
54
+ }
55
+ } catch (e) {}
56
+ },
57
+ setFrozen: async (projectId, status) => {
58
+ if (activeProjects.has(projectId)) activeProjects.get(projectId).isFrozen = status;
59
+ await supabase.from('leads').update({ is_frozen: status }).eq('id', projectId);
60
+ },
61
+ isFrozen: async (projectId) => {
62
+ if (activeProjects.has(projectId)) return activeProjects.get(projectId).isFrozen;
63
+ const { data } = await supabase.from('leads').select('is_frozen').eq('id', projectId).single();
64
+ return data?.is_frozen || false;
65
+ }
66
+ };
67
+
68
+ const callAI = async (history, input, contextData, images, systemPrompt, projectContext, modelId) => {
69
+ let contextStr = "";
70
+ try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
71
+ const recentHistory = history.slice(-10).map(m => `${m.role === 'model' ? 'Assistant' : 'User'}: ${m.parts?.[0]?.text || ""}`).join('\n');
72
+ const fullPrompt = `System: ${systemPrompt}\n\n${projectContext}\n\n[HISTORY]:\n${recentHistory}\n\n[CONTEXT]: ${contextStr}\n\nUser: ${input}\nAssistant:`;
73
+
74
+ try {
75
+ const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
76
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
77
+ body: JSON.stringify({ model: modelId, prompt: fullPrompt, system_prompt: systemPrompt, images: images ||[] })
78
+ });
79
+ const result = await response.json();
80
+ return { text: result.data || result.text || "", usage: result.usage };
81
+ } catch (e) { return { text: "<notification>AI Unreachable</notification>", usage: {} }; }
82
+ };
83
+
84
+ function extractCommands(text) {
85
+ const commands =[];
86
+ const parse = (regex, type, isJson = true) => {
87
+ let match;
88
+ regex.lastIndex = 0;
89
+ while ((match = regex.exec(text)) !== null) {
90
+ let rawPayload = match[1].trim();
91
+ try {
92
+ commands.push({ type, payload: isJson ? JSON.parse(rawPayload) : rawPayload });
93
+ } catch (e) {
94
+ if (type === 'create_thrust') commands.push({ type, payload: { title: "System Thrust", markdown_content: rawPayload, tasks:[] } });
95
+ }
96
+ }
97
+ };
98
+
99
+ parse(/<thrust_create>([\s\S]*?)<\/thrust_create>/gi, 'create_thrust');
100
+ parse(/<timeline_log>([\s\S]*?)<\/timeline_log>/gi, 'log_timeline');
101
+ parse(/<notification>([\s\S]*?)<\/notification>/gi, 'notification', false);
102
+ parse(/<update_requirements>([\s\S]*?)<\/update_requirements>/gi, 'update_requirements', false);
103
+ parse(/<schedule_briefing>([\s\S]*?)<\/schedule_briefing>/gi, 'schedule_briefing');
104
+ parse(/<freeze_project>([\s\S]*?)<\/freeze_project>/gi, 'freeze_project', false);
105
+ parse(/<thrust_complete>([\s\S]*?)<\/thrust_complete>/gi, 'thrust_complete', false);
106
+ parse(/<complete_task>([\s\S]*?)<\/complete_task>/gi, 'complete_task', false);
107
+
108
+ // NEW: Extract AI queries sent to local MCPs
109
+ parse(/<mcp_query>([\s\S]*?)<\/mcp_query>/gi, 'mcp_query');
110
+
111
+ return commands;
112
+ }
113
+
114
+ // --- BULLETPROOF CRON MATH ---
115
+ async function registerMorningCron(projectId, offset) {
116
+ const now = new Date();
117
+ const target = new Date(now);
118
+
119
+ const targetUtcMinutes = (5 * 60) - (offset * 60);
120
+ target.setUTCHours(0, targetUtcMinutes, 0, 0);
121
+
122
+ if (target <= now) target.setDate(target.getDate() + 1);
123
+
124
+ const delayMs = target.getTime() - now.getTime();
125
+ console.log(`⏰ Briefing Scheduled for ${projectId}. Local 6AM occurs in ${(delayMs/1000/60/60).toFixed(2)} hours.`);
126
+
127
+ fetch(`${CRON_REGISTRY_URL}/register`, {
128
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
129
+ body: JSON.stringify({
130
+ secret: CRON_SECRET,
131
+ jobId: `briefing_${projectId}`,
132
+ intervalMs: 86400000,
133
+ initialDelay: delayMs,
134
+ webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`,
135
+ leadId: projectId,
136
+ payload: { projectId, timezoneOffset: offset }
137
+ })
138
+ }).catch(()=>{});
139
+ }
140
+
141
+ // --- EMAIL DISPATCHER HELPER ---
142
+ async function dispatchEmail(userId, projectId, projectName, briefingId, markdownContent) {
143
+ console.log(`📧 Dispatching email to Utility Server for Project: ${projectName}`);
144
+ fetch(`${UTILITY_SERVER_URL}/api/email/send-briefing`, {
145
+ method: 'POST',
146
+ headers: { 'Content-Type': 'application/json' },
147
+ body: JSON.stringify({ userId, projectId, projectName, briefingId, markdownContent })
148
+ }).catch(e => console.error("Email Dispatch Error:", e.message));
149
+ }
150
+
151
+ async function executeCommands(userId, projectId, commands) {
152
+ let flags = { shouldReload: false, thrustComplete: false, newThrustId: null, newThrustMarkdown: null };
153
+
154
+ for (const cmd of commands) {
155
+ try {
156
+ if (cmd.type === 'create_thrust') {
157
+ await supabase.from('thrusts').delete().eq('lead_id', projectId);
158
+
159
+ const { data: thrust } = await supabase.from('thrusts').insert({ lead_id: projectId, title: cmd.payload.title, markdown_content: cmd.payload.markdown_content, status: 'active' }).select().single();
160
+ if (thrust && cmd.payload.tasks && cmd.payload.tasks.length > 0) {
161
+ const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
162
+ await supabase.from('thrust_tasks').insert(tasks);
163
+ }
164
+
165
+ flags.shouldReload = true;
166
+
167
+ if (thrust) {
168
+ flags.newThrustId = thrust.id;
169
+ flags.newThrustMarkdown = cmd.payload.markdown_content;
170
+ }
171
+ }
172
+
173
+ if (cmd.type === 'log_timeline') {
174
+ await supabase.from('timeline_events').insert({ lead_id: projectId, title: cmd.payload.title, description: cmd.payload.description, type: (cmd.payload.type || 'system').toLowerCase() });
175
+ flags.shouldReload = true;
176
+ }
177
+
178
+ if (cmd.type === 'update_requirements') {
179
+ await supabase.from('leads').update({ requirements_doc: cmd.payload }).eq('id', projectId);
180
+ flags.shouldReload = true;
181
+ }
182
+
183
+ if (cmd.type === 'schedule_briefing') {
184
+ await registerMorningCron(projectId, cmd.payload.timezone_offset || 0);
185
+ }
186
+
187
+ if (cmd.type === 'complete_task') {
188
+ const { data: active } = await supabase.from('thrusts').select('id').eq('lead_id', projectId).eq('status', 'active').single();
189
+ if (active) {
190
+ await supabase.from('thrust_tasks').update({ status: 'done' }).eq('thrust_id', active.id).ilike('title', `%${cmd.payload}%`);
191
+ flags.shouldReload = true;
192
+ }
193
+ }
194
+
195
+ if (cmd.type === 'thrust_complete') {
196
+ const { data: active } = await supabase.from('thrusts').select('id').eq('lead_id', projectId).eq('status', 'active').single();
197
+ if (active) {
198
+ await supabase.from('thrusts').update({ status: 'completed' }).eq('id', active.id);
199
+ await supabase.from('thrust_tasks').delete().eq('thrust_id', active.id);
200
+ flags.thrustComplete = true;
201
+ }
202
+ }
203
+
204
+ if (cmd.type === 'freeze_project') {
205
+ const isFrozen = cmd.payload === 'true';
206
+ await StateManager.setFrozen(projectId, isFrozen);
207
+ }
208
+
209
+ if (cmd.type === 'notification' && FRONT_URL) {
210
+ fetch(`${FRONT_URL}/internal/notify`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userId, type: 'toast', message: cmd.payload }) }).catch(() => {});
211
+ }
212
+
213
+ // NEW: Forward AI MCP queries to the frontend gateway so it can push via websocket
214
+ if (cmd.type === 'mcp_query' && FRONT_URL) {
215
+ fetch(`${FRONT_URL}/internal/mcp_query`, {
216
+ method: 'POST',
217
+ headers: { 'Content-Type': 'application/json' },
218
+ body: JSON.stringify({ user_id: userId, lead_id: projectId, payload: cmd.payload })
219
+ }).catch(() => {});
220
+ }
221
+
222
+ } catch (e) {}
223
+ }
224
+ return flags;
225
+ }
226
+
227
+ app.post('/init-project', async (req, res) => {
228
+ const { userId, name, description, localPath, timezoneOffset = 0 } = req.body;
229
+ const { data: lead } = await supabase.from('leads').insert({ user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..." }).select().single();
230
+ res.json({ success: true, leadId: lead.id });
231
+
232
+ setImmediate(async () => {
233
+ try {
234
+ const initInput = `PROJECT: ${name}\nDESC: ${description}\nUSER TIMEZONE OFFSET: ${timezoneOffset}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
235
+ const aiResult = await callAI([], initInput, {},[], prompts.init_system_prompt, "", SMART_MODEL_ID);
236
+ aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
237
+ await StateManager.addHistory(lead.id, 'user', initInput);
238
+ await StateManager.addHistory(lead.id, 'model', aiResult.text);
239
+ const cmds = extractCommands(aiResult.text);
240
+ await executeCommands(userId, lead.id, cmds);
241
+ } catch (err) {}
242
+ });
243
+ });
244
+
245
+ app.post('/process', async (req, res) => {
246
+ const { userId, projectId, prompt, context, images, task_type = 'chat' } = req.body;
247
+ if (task_type === 'chat') await StateManager.setFrozen(projectId, false);
248
+
249
+ let selectedModel = (task_type === 'log_ingestion') ? FAST_MODEL_ID : SMART_MODEL_ID;
250
+ let sysPrompt = (task_type === 'log_ingestion') ? prompts.log_analyst_prompt : prompts.director_system_prompt;
251
+
252
+ try {
253
+ const { data: lead } = await supabase.from('leads').select('requirements_doc').eq('id', projectId).single();
254
+ const { data: activeThrust } = await supabase.from('thrusts').select('title, tasks:thrust_tasks(title, status)').eq('lead_id', projectId).eq('status', 'active').order('created_at', { ascending: false }).limit(1).single();
255
+ const { data: timeline } = await supabase.from('timeline_events').select('title, type, description, created_at').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(10);
256
+
257
+ const projectContext = `[PRD]: ${lead?.requirements_doc?.substring(0, 3000)}...\n[CURRENT THRUST]: ${activeThrust ? JSON.stringify(activeThrust) : "None"}\n[RECENT TIMELINE]: ${JSON.stringify(timeline ||[])}`;
258
+ const history = await StateManager.getHistory(projectId);
259
+
260
+ let aiResult = await callAI(history, prompt, context, images, sysPrompt, projectContext, selectedModel);
261
+ let cmds = extractCommands(aiResult.text);
262
+ let flags = await executeCommands(userId, projectId, cmds);
263
+
264
+ if (flags.thrustComplete && task_type === 'log_ingestion') {
265
+ const escalationPrompt = "The previous thrust is complete based on logs. Generate the next Thrust immediately to keep momentum.";
266
+ const smartResult = await callAI(history, escalationPrompt, context,[], prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
267
+ aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
268
+ const smartCmds = extractCommands(smartResult.text);
269
+ await executeCommands(userId, projectId, smartCmds);
270
+
271
+ await StateManager.addHistory(projectId, 'model', aiResult.text);
272
+ } else {
273
+ await StateManager.addHistory(projectId, 'model', aiResult.text);
274
+ }
275
+
276
+ const cleanText = aiResult.text.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, '').trim();
277
+ res.json({ text: cleanText, should_reload: flags.shouldReload });
278
+ } catch (e) { res.status(500).json({ error: "Processing Error" }); }
279
+ });
280
+
281
+ app.post('/automated-briefing', async (req, res) => {
282
+ const { projectId } = req.body;
283
+
284
+ try {
285
+ const isFrozen = await StateManager.isFrozen(projectId);
286
+ const { data: lastThrust } = await supabase.from('thrusts').select('created_at').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(1).single();
287
+
288
+ const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
289
+ const today = new Date();
290
+ const todayDate = today.getDate();
291
+
292
+ if (isFrozen) return res.json({ status: "skipped_frozen" });
293
+ if (lastThrustDate === todayDate) return res.json({ status: "skipped_exists" });
294
+
295
+ const currentDateString = today.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
296
+
297
+ const prompt = `[SYSTEM TIME: ${currentDateString} at 5:00 AM]\nIt is morning. Generate today's Morning Briefing (New Thrust). Look at the RECENT TIMELINE to see what was accomplished yesterday. Adopt a highly conversational, proactive tone in the markdown (e.g., 'Morning! You finished X yesterday. Today, the priority is Y.'). If the project has been idle for days, use <freeze_project>true</freeze_project>.`;
298
+
299
+ const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
300
+ const { data: timeline } = await supabase.from('timeline_events').select('*').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(5);
301
+
302
+ const projectContext = `[PRD]: ${lead.requirements_doc}\n[RECENT TIMELINE]: ${JSON.stringify(timeline)}`;
303
+ const history = await StateManager.getHistory(projectId);
304
+
305
+ const aiResult = await callAI(history, prompt, {}, [], prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
306
+
307
+ await StateManager.addHistory(projectId, 'model', aiResult.text);
308
+ const cmds = extractCommands(aiResult.text);
309
+ const flags = await executeCommands(lead.user_id, projectId, cmds);
310
+
311
+ // 👉 EMAIL IS DISPATCHED ONLY HERE
312
+ if (flags.newThrustId) {
313
+ await dispatchEmail(lead.user_id, projectId, lead.name, flags.newThrustId, flags.newThrustMarkdown);
314
+ }
315
+
316
+ await StateManager.setFrozen(projectId, true);
317
+ res.json({ success: true });
318
+
319
+ } catch (e) { res.status(500).json({ error: e.message }); }
320
+ });
321
+
322
+ app.get('/', async (req, res) => res.status(200).json({ status: "Alive" }));
323
+ app.listen(PORT, () => console.log(`✅ Core Online: ${PORT}`));