Spaces:
Running
Running
Update app.js
Browse files
app.js
CHANGED
|
@@ -15,7 +15,8 @@ const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
|
|
| 15 |
const SMART_MODEL_ID = "claude";
|
| 16 |
const FAST_MODEL_ID = "gpt-5-mini";
|
| 17 |
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
if (!SUPABASE_URL || !SUPABASE_KEY) process.exit(1);
|
| 21 |
|
|
@@ -64,7 +65,6 @@ const StateManager = {
|
|
| 64 |
}
|
| 65 |
};
|
| 66 |
|
| 67 |
-
// --- NEW: Support injected 'images' variable ---
|
| 68 |
const callAI = async (history, input, contextData, images, systemPrompt, projectContext, modelId) => {
|
| 69 |
let contextStr = "";
|
| 70 |
try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
|
|
@@ -113,16 +113,9 @@ async function registerMorningCron(projectId, offset) {
|
|
| 113 |
const now = new Date();
|
| 114 |
const target = new Date(now);
|
| 115 |
|
| 116 |
-
// We want exactly 6:00 AM local time.
|
| 117 |
-
// So we calculate the target UTC minutes needed.
|
| 118 |
-
// E.g., Local 6 AM in EST (-5) = 11 AM UTC (660 mins).
|
| 119 |
-
// E.g., Local 6 AM in IST (+5.5) = 12:30 AM UTC (30 mins).
|
| 120 |
const targetUtcMinutes = (6 * 60) - (offset * 60);
|
| 121 |
-
|
| 122 |
-
// setUTCHours natively handles fractional minutes and negative hour rollovers!
|
| 123 |
target.setUTCHours(0, targetUtcMinutes, 0, 0);
|
| 124 |
|
| 125 |
-
// If 6 AM today has already passed, schedule for tomorrow
|
| 126 |
if (target <= now) target.setDate(target.getDate() + 1);
|
| 127 |
|
| 128 |
const delayMs = target.getTime() - now.getTime();
|
|
@@ -133,7 +126,7 @@ async function registerMorningCron(projectId, offset) {
|
|
| 133 |
body: JSON.stringify({
|
| 134 |
secret: CRON_SECRET,
|
| 135 |
jobId: `briefing_${projectId}`,
|
| 136 |
-
intervalMs: 86400000,
|
| 137 |
initialDelay: delayMs,
|
| 138 |
webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`,
|
| 139 |
leadId: projectId,
|
|
@@ -142,6 +135,7 @@ async function registerMorningCron(projectId, offset) {
|
|
| 142 |
}).catch(()=>{});
|
| 143 |
}
|
| 144 |
|
|
|
|
| 145 |
async function dispatchEmail(userId, projectId, projectName, briefingId, markdownContent) {
|
| 146 |
console.log(`📧 Dispatching email to Utility Server for Project: ${projectName}`);
|
| 147 |
fetch(`${UTILITY_SERVER_URL}/api/email/send-briefing`, {
|
|
@@ -149,20 +143,31 @@ async function dispatchEmail(userId, projectId, projectName, briefingId, markdow
|
|
| 149 |
headers: { 'Content-Type': 'application/json' },
|
| 150 |
body: JSON.stringify({ userId, projectId, projectName, briefingId, markdownContent })
|
| 151 |
}).catch(e => console.error("Email Dispatch Error:", e.message));
|
| 152 |
-
}
|
| 153 |
|
| 154 |
async function executeCommands(userId, projectId, commands) {
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
for (const cmd of commands) {
|
| 158 |
try {
|
| 159 |
if (cmd.type === 'create_thrust') {
|
|
|
|
|
|
|
|
|
|
| 160 |
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();
|
| 161 |
if (thrust && cmd.payload.tasks && cmd.payload.tasks.length > 0) {
|
| 162 |
const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
|
| 163 |
await supabase.from('thrust_tasks').insert(tasks);
|
| 164 |
}
|
|
|
|
| 165 |
flags.shouldReload = true;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
}
|
| 167 |
|
| 168 |
if (cmd.type === 'log_timeline') {
|
|
@@ -208,58 +213,28 @@ async function executeCommands(userId, projectId, commands) {
|
|
| 208 |
} catch (e) {}
|
| 209 |
}
|
| 210 |
return flags;
|
| 211 |
-
}
|
| 212 |
|
| 213 |
app.post('/init-project', async (req, res) => {
|
| 214 |
-
//
|
| 215 |
const { userId, name, description, localPath, timezoneOffset = 0 } = req.body;
|
| 216 |
-
|
| 217 |
-
const { data: lead } = await supabase.from('leads').insert({
|
| 218 |
-
user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..."
|
| 219 |
-
}).select().single();
|
| 220 |
-
|
| 221 |
-
res.json({ success: true, leadId: lead.id });
|
| 222 |
-
|
| 223 |
-
setImmediate(async () => {
|
| 224 |
-
try {
|
| 225 |
-
// 2. Inject the explicit timezone offset into the initialization prompt
|
| 226 |
-
const initInput = `PROJECT: ${name}\nDESC: ${description}\nUSER TIMEZONE OFFSET: ${timezoneOffset}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
|
| 227 |
-
|
| 228 |
-
const aiResult = await callAI([], initInput, {}, [], prompts.init_system_prompt, "", SMART_MODEL_ID);
|
| 229 |
-
aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
|
| 230 |
-
|
| 231 |
-
await StateManager.addHistory(lead.id, 'user', initInput);
|
| 232 |
-
await StateManager.addHistory(lead.id, 'model', aiResult.text);
|
| 233 |
-
|
| 234 |
-
const cmds = extractCommands(aiResult.text);
|
| 235 |
-
const flags = await executeCommands(userId, lead.id, cmds);
|
| 236 |
-
|
| 237 |
-
if (flags.newThrustId) {
|
| 238 |
-
await dispatchEmail(userId, lead.id, lead.name, flags.newThrustId, flags.newThrustMarkdown);
|
| 239 |
-
}
|
| 240 |
-
} catch (err) {}
|
| 241 |
-
});
|
| 242 |
-
});
|
| 243 |
-
|
| 244 |
-
/*
|
| 245 |
-
app.post('/init-project', async (req, res) => {
|
| 246 |
-
const { userId, name, description, localPath } = req.body;
|
| 247 |
const { data: lead } = await supabase.from('leads').insert({ user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..." }).select().single();
|
| 248 |
res.json({ success: true, leadId: lead.id });
|
| 249 |
|
| 250 |
setImmediate(async () => {
|
| 251 |
try {
|
| 252 |
-
const initInput = `PROJECT: ${name}\nDESC: ${description}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
|
| 253 |
const aiResult = await callAI([], initInput, {}, [], prompts.init_system_prompt, "", SMART_MODEL_ID);
|
| 254 |
aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
|
| 255 |
await StateManager.addHistory(lead.id, 'user', initInput);
|
| 256 |
await StateManager.addHistory(lead.id, 'model', aiResult.text);
|
| 257 |
const cmds = extractCommands(aiResult.text);
|
| 258 |
await executeCommands(userId, lead.id, cmds);
|
|
|
|
|
|
|
| 259 |
} catch (err) {}
|
| 260 |
});
|
| 261 |
});
|
| 262 |
-
*/
|
| 263 |
|
| 264 |
app.post('/process', async (req, res) => {
|
| 265 |
const { userId, projectId, prompt, context, images, task_type = 'chat' } = req.body;
|
|
@@ -286,6 +261,9 @@ app.post('/process', async (req, res) => {
|
|
| 286 |
aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
|
| 287 |
const smartCmds = extractCommands(smartResult.text);
|
| 288 |
await executeCommands(userId, projectId, smartCmds);
|
|
|
|
|
|
|
|
|
|
| 289 |
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 290 |
} else {
|
| 291 |
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
|
@@ -304,12 +282,15 @@ app.post('/automated-briefing', async (req, res) => {
|
|
| 304 |
const { data: lastThrust } = await supabase.from('thrusts').select('created_at').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(1).single();
|
| 305 |
|
| 306 |
const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
|
| 307 |
-
const
|
|
|
|
| 308 |
|
| 309 |
if (isFrozen) return res.json({ status: "skipped_frozen" });
|
| 310 |
if (lastThrustDate === todayDate) return res.json({ status: "skipped_exists" });
|
| 311 |
|
| 312 |
-
const
|
|
|
|
|
|
|
| 313 |
|
| 314 |
const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
|
| 315 |
const { data: timeline } = await supabase.from('timeline_events').select('*').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(5);
|
|
@@ -321,299 +302,12 @@ app.post('/automated-briefing', async (req, res) => {
|
|
| 321 |
|
| 322 |
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 323 |
const cmds = extractCommands(aiResult.text);
|
| 324 |
-
await executeCommands(lead.user_id, projectId, cmds);
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
} catch (e) { res.status(500).json({ error: e.message }); }
|
| 330 |
-
});
|
| 331 |
-
|
| 332 |
-
app.get('/', async (req, res) => res.status(200).json({ status: "Alive" }));
|
| 333 |
-
app.listen(PORT, () => console.log(`✅ Core Online: ${PORT}`));
|
| 334 |
-
|
| 335 |
-
/* import express from 'express';
|
| 336 |
-
import cors from 'cors';
|
| 337 |
-
import fs from 'fs';
|
| 338 |
-
import path from 'path';
|
| 339 |
-
import { createClient } from '@supabase/supabase-js';
|
| 340 |
-
|
| 341 |
-
const PORT = 7860;
|
| 342 |
-
const SUPABASE_URL = process.env.SUPABASE_URL;
|
| 343 |
-
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_KEY;
|
| 344 |
-
const REMOTE_SERVER_URL = process.env.REMOTE_AI_URL || "http://localhost:11434";
|
| 345 |
-
const FRONT_URL = process.env.FRONT_URL;
|
| 346 |
-
const CRON_REGISTRY_URL = process.env.CRON_REGISTRY_URL || "http://localhost:7861";
|
| 347 |
-
const CRON_SECRET = process.env.CRON_SECRET || "default_secret";
|
| 348 |
-
|
| 349 |
-
const SMART_MODEL_ID = "claude";
|
| 350 |
-
const FAST_MODEL_ID = "gpt-5-mini";
|
| 351 |
-
|
| 352 |
-
if (!SUPABASE_URL || !SUPABASE_KEY) process.exit(1);
|
| 353 |
-
|
| 354 |
-
const app = express();
|
| 355 |
-
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
|
| 356 |
-
|
| 357 |
-
app.use(express.json({ limit: '50mb' }));
|
| 358 |
-
app.use(cors());
|
| 359 |
-
|
| 360 |
-
let prompts = {};
|
| 361 |
-
try {
|
| 362 |
-
prompts = JSON.parse(fs.readFileSync(path.resolve('./prompts.json'), 'utf8'));
|
| 363 |
-
} catch (e) { process.exit(1); }
|
| 364 |
-
|
| 365 |
-
const activeProjects = new Map();
|
| 366 |
-
|
| 367 |
-
const StateManager = {
|
| 368 |
-
getHistory: async (projectId) => {
|
| 369 |
-
if (activeProjects.has(projectId)) return activeProjects.get(projectId).history;
|
| 370 |
-
const { data: chunks } = await supabase.from('message_chunks').select('*').eq('project_id', projectId).order('chunk_index', { ascending: false }).limit(10);
|
| 371 |
-
const fullHistory = (chunks || []).reverse().flatMap(c => c.payload || []);
|
| 372 |
-
activeProjects.set(projectId, { history: fullHistory, isFrozen: false });
|
| 373 |
-
return fullHistory;
|
| 374 |
-
},
|
| 375 |
-
addHistory: async (projectId, role, text) => {
|
| 376 |
-
const newMessage = { role, parts: [{ text }] };
|
| 377 |
-
if (activeProjects.has(projectId)) activeProjects.get(projectId).history.push(newMessage);
|
| 378 |
-
try {
|
| 379 |
-
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();
|
| 380 |
-
const currentPayload = (latestChunk?.payload) || [];
|
| 381 |
-
if (latestChunk && currentPayload.length < 20) {
|
| 382 |
-
await supabase.from('message_chunks').update({ payload: [...currentPayload, newMessage] }).eq('id', latestChunk.id);
|
| 383 |
-
} else {
|
| 384 |
-
await supabase.from('message_chunks').insert({ project_id: projectId, lead_id: projectId, chunk_index: (latestChunk?.chunk_index ?? -1) + 1, payload: [newMessage] });
|
| 385 |
-
}
|
| 386 |
-
} catch (e) {}
|
| 387 |
-
},
|
| 388 |
-
setFrozen: async (projectId, status) => {
|
| 389 |
-
if (activeProjects.has(projectId)) activeProjects.get(projectId).isFrozen = status;
|
| 390 |
-
await supabase.from('leads').update({ is_frozen: status }).eq('id', projectId);
|
| 391 |
-
},
|
| 392 |
-
isFrozen: async (projectId) => {
|
| 393 |
-
if (activeProjects.has(projectId)) return activeProjects.get(projectId).isFrozen;
|
| 394 |
-
const { data } = await supabase.from('leads').select('is_frozen').eq('id', projectId).single();
|
| 395 |
-
return data?.is_frozen || false;
|
| 396 |
-
}
|
| 397 |
-
};
|
| 398 |
-
|
| 399 |
-
const callAI = async (history, input, contextData, systemPrompt, projectContext, modelId) => {
|
| 400 |
-
let contextStr = "";
|
| 401 |
-
try { contextStr = JSON.stringify(contextData, null, 2); } catch {}
|
| 402 |
-
const recentHistory = history.slice(-10).map(m => `${m.role === 'model' ? 'Assistant' : 'User'}: ${m.parts?.[0]?.text || ""}`).join('\n');
|
| 403 |
-
const fullPrompt = `System: ${systemPrompt}\n\n${projectContext}\n\n[HISTORY]:\n${recentHistory}\n\n[CONTEXT]: ${contextStr}\n\nUser: ${input}\nAssistant:`;
|
| 404 |
-
|
| 405 |
-
try {
|
| 406 |
-
const response = await fetch(`${REMOTE_SERVER_URL}/api/generate`, {
|
| 407 |
-
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 408 |
-
body: JSON.stringify({ model: modelId, prompt: fullPrompt, system_prompt: systemPrompt })
|
| 409 |
-
});
|
| 410 |
-
const result = await response.json();
|
| 411 |
-
return { text: result.data || result.text || "", usage: result.usage };
|
| 412 |
-
} catch (e) { return { text: "<notification>AI Unreachable</notification>", usage: {} }; }
|
| 413 |
-
};
|
| 414 |
-
|
| 415 |
-
// --- THRUST CLEANUP HELPER ---
|
| 416 |
-
async function clearPreviousThrusts(projectId) {
|
| 417 |
-
try {
|
| 418 |
-
// Deleting the thrust automatically deletes all its tasks
|
| 419 |
-
// because of the 'on delete cascade' rule in Supabase.
|
| 420 |
-
const { error } = await supabase
|
| 421 |
-
.from('thrusts')
|
| 422 |
-
.delete()
|
| 423 |
-
.eq('lead_id', projectId);
|
| 424 |
-
|
| 425 |
-
if (error) {
|
| 426 |
-
console.error(`[DB Error] Failed to clear old thrusts for ${projectId}:`, error.message);
|
| 427 |
-
} else {
|
| 428 |
-
console.log(`🧹 Cleared previous thrusts for project ${projectId}`);
|
| 429 |
-
}
|
| 430 |
-
} catch (e) {
|
| 431 |
-
console.error("Error in clearPreviousThrusts:", e.message);
|
| 432 |
-
}
|
| 433 |
-
}
|
| 434 |
-
|
| 435 |
-
function extractCommands(text) {
|
| 436 |
-
const commands = [];
|
| 437 |
-
const parse = (regex, type, isJson = true) => {
|
| 438 |
-
let match;
|
| 439 |
-
regex.lastIndex = 0;
|
| 440 |
-
while ((match = regex.exec(text)) !== null) {
|
| 441 |
-
let rawPayload = match[1].trim();
|
| 442 |
-
try {
|
| 443 |
-
commands.push({ type, payload: isJson ? JSON.parse(rawPayload) : rawPayload });
|
| 444 |
-
} catch (e) {
|
| 445 |
-
if (type === 'create_thrust') commands.push({ type, payload: { title: "System Thrust", markdown_content: rawPayload, tasks: [] } });
|
| 446 |
-
}
|
| 447 |
}
|
| 448 |
-
};
|
| 449 |
-
|
| 450 |
-
parse(/<thrust_create>([\s\S]*?)<\/thrust_create>/gi, 'create_thrust');
|
| 451 |
-
parse(/<timeline_log>([\s\S]*?)<\/timeline_log>/gi, 'log_timeline');
|
| 452 |
-
parse(/<notification>([\s\S]*?)<\/notification>/gi, 'notification', false);
|
| 453 |
-
parse(/<update_requirements>([\s\S]*?)<\/update_requirements>/gi, 'update_requirements', false);
|
| 454 |
-
parse(/<schedule_briefing>([\s\S]*?)<\/schedule_briefing>/gi, 'schedule_briefing');
|
| 455 |
-
parse(/<freeze_project>([\s\S]*?)<\/freeze_project>/gi, 'freeze_project', false);
|
| 456 |
-
parse(/<thrust_complete>([\s\S]*?)<\/thrust_complete>/gi, 'thrust_complete', false);
|
| 457 |
-
parse(/<complete_task>([\s\S]*?)<\/complete_task>/gi, 'complete_task', false);
|
| 458 |
-
|
| 459 |
-
return commands;
|
| 460 |
-
}
|
| 461 |
-
|
| 462 |
-
async function registerMorningCron(projectId, offset) {
|
| 463 |
-
const now = new Date();
|
| 464 |
-
const target = new Date(now);
|
| 465 |
-
target.setUTCHours(6 - offset, 0, 0, 0);
|
| 466 |
-
if (target <= now) target.setDate(target.getDate() + 1);
|
| 467 |
-
const delayMs = target.getTime() - now.getTime();
|
| 468 |
-
fetch(`${CRON_REGISTRY_URL}/register`, {
|
| 469 |
-
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
| 470 |
-
body: JSON.stringify({ secret: CRON_SECRET, jobId: `briefing_${projectId}`, intervalMs: 86400000, initialDelay: delayMs, webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`, leadId: projectId, payload: { projectId, timezoneOffset: offset } })
|
| 471 |
-
}).catch(()=>{});
|
| 472 |
-
}
|
| 473 |
-
|
| 474 |
-
async function executeCommands(userId, projectId, commands) {
|
| 475 |
-
let flags = { shouldReload: false, thrustComplete: false };
|
| 476 |
-
|
| 477 |
-
for (const cmd of commands) {
|
| 478 |
-
try {
|
| 479 |
-
if (cmd.type === 'create_thrust') {
|
| 480 |
-
// 👉 ADD THIS LINE: Wipe out the old thrust and tasks first
|
| 481 |
-
await clearPreviousThrusts(projectId);
|
| 482 |
-
|
| 483 |
-
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();
|
| 484 |
-
if (thrust && cmd.payload.tasks && cmd.payload.tasks.length > 0) {
|
| 485 |
-
const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
|
| 486 |
-
await supabase.from('thrust_tasks').insert(tasks);
|
| 487 |
-
}
|
| 488 |
-
flags.shouldReload = true;
|
| 489 |
-
}
|
| 490 |
-
|
| 491 |
-
if (cmd.type === 'log_timeline') {
|
| 492 |
-
await supabase.from('timeline_events').insert({ lead_id: projectId, title: cmd.payload.title, description: cmd.payload.description, type: (cmd.payload.type || 'system').toLowerCase() });
|
| 493 |
-
flags.shouldReload = true;
|
| 494 |
-
}
|
| 495 |
-
|
| 496 |
-
if (cmd.type === 'update_requirements') {
|
| 497 |
-
await supabase.from('leads').update({ requirements_doc: cmd.payload }).eq('id', projectId);
|
| 498 |
-
flags.shouldReload = true;
|
| 499 |
-
}
|
| 500 |
-
|
| 501 |
-
if (cmd.type === 'schedule_briefing') {
|
| 502 |
-
await registerMorningCron(projectId, cmd.payload.timezone_offset || 0);
|
| 503 |
-
}
|
| 504 |
-
|
| 505 |
-
if (cmd.type === 'complete_task') {
|
| 506 |
-
const { data: active } = await supabase.from('thrusts').select('id').eq('lead_id', projectId).eq('status', 'active').single();
|
| 507 |
-
if (active) {
|
| 508 |
-
await supabase.from('thrust_tasks').update({ status: 'done' }).eq('thrust_id', active.id).ilike('title', `%${cmd.payload}%`);
|
| 509 |
-
flags.shouldReload = true;
|
| 510 |
-
}
|
| 511 |
-
}
|
| 512 |
-
|
| 513 |
-
if (cmd.type === 'thrust_complete') {
|
| 514 |
-
const { data: active } = await supabase.from('thrusts').select('id').eq('lead_id', projectId).eq('status', 'active').single();
|
| 515 |
-
if (active) {
|
| 516 |
-
await supabase.from('thrusts').update({ status: 'completed' }).eq('id', active.id);
|
| 517 |
-
await supabase.from('thrust_tasks').delete().eq('thrust_id', active.id);
|
| 518 |
-
flags.thrustComplete = true;
|
| 519 |
-
}
|
| 520 |
-
}
|
| 521 |
-
|
| 522 |
-
if (cmd.type === 'freeze_project') {
|
| 523 |
-
const isFrozen = cmd.payload === 'true';
|
| 524 |
-
await StateManager.setFrozen(projectId, isFrozen);
|
| 525 |
-
}
|
| 526 |
-
|
| 527 |
-
if (cmd.type === 'notification' && FRONT_URL) {
|
| 528 |
-
fetch(`${FRONT_URL}/internal/notify`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user_id: userId, type: 'toast', message: cmd.payload }) }).catch(() => {});
|
| 529 |
-
}
|
| 530 |
-
|
| 531 |
-
} catch (e) {}
|
| 532 |
-
}
|
| 533 |
-
return flags;
|
| 534 |
-
}
|
| 535 |
-
|
| 536 |
-
app.post('/init-project', async (req, res) => {
|
| 537 |
-
const { userId, name, description, localPath } = req.body;
|
| 538 |
-
const { data: lead } = await supabase.from('leads').insert({ user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..." }).select().single();
|
| 539 |
-
res.json({ success: true, leadId: lead.id });
|
| 540 |
-
|
| 541 |
-
setImmediate(async () => {
|
| 542 |
-
try {
|
| 543 |
-
const initInput = `PROJECT: ${name}\nDESC: ${description}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
|
| 544 |
-
const aiResult = await callAI([], initInput, {}, prompts.init_system_prompt, "", SMART_MODEL_ID);
|
| 545 |
-
aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
|
| 546 |
-
await StateManager.addHistory(lead.id, 'user', initInput);
|
| 547 |
-
await StateManager.addHistory(lead.id, 'model', aiResult.text);
|
| 548 |
-
const cmds = extractCommands(aiResult.text);
|
| 549 |
-
await executeCommands(userId, lead.id, cmds);
|
| 550 |
-
} catch (err) {}
|
| 551 |
-
});
|
| 552 |
-
});
|
| 553 |
-
|
| 554 |
-
app.post('/process', async (req, res) => {
|
| 555 |
-
const { userId, projectId, prompt, context, task_type = 'chat' } = req.body;
|
| 556 |
-
if (task_type === 'chat') await StateManager.setFrozen(projectId, false);
|
| 557 |
-
|
| 558 |
-
let selectedModel = (task_type === 'log_ingestion') ? FAST_MODEL_ID : SMART_MODEL_ID;
|
| 559 |
-
let sysPrompt = (task_type === 'log_ingestion') ? prompts.log_analyst_prompt : prompts.director_system_prompt;
|
| 560 |
-
|
| 561 |
-
try {
|
| 562 |
-
const { data: lead } = await supabase.from('leads').select('requirements_doc').eq('id', projectId).single();
|
| 563 |
-
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();
|
| 564 |
-
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);
|
| 565 |
-
|
| 566 |
-
const projectContext = `[PRD]: ${lead?.requirements_doc?.substring(0, 3000)}...\n[CURRENT THRUST]: ${activeThrust ? JSON.stringify(activeThrust) : "None"}\n[RECENT TIMELINE]: ${JSON.stringify(timeline || [])}`;
|
| 567 |
-
const history = await StateManager.getHistory(projectId);
|
| 568 |
-
|
| 569 |
-
let aiResult = await callAI(history, prompt, context, sysPrompt, projectContext, selectedModel);
|
| 570 |
-
let cmds = extractCommands(aiResult.text);
|
| 571 |
-
let flags = await executeCommands(userId, projectId, cmds);
|
| 572 |
-
|
| 573 |
-
if (flags.thrustComplete && task_type === 'log_ingestion') {
|
| 574 |
-
const escalationPrompt = "The previous thrust is complete based on logs. Generate the next Thrust immediately to keep momentum.";
|
| 575 |
-
const smartResult = await callAI(history, escalationPrompt, context, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
|
| 576 |
-
aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
|
| 577 |
-
const smartCmds = extractCommands(smartResult.text);
|
| 578 |
-
await executeCommands(userId, projectId, smartCmds);
|
| 579 |
-
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 580 |
-
} else {
|
| 581 |
-
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 582 |
-
}
|
| 583 |
-
|
| 584 |
-
const cleanText = aiResult.text.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, '').trim();
|
| 585 |
-
res.json({ text: cleanText, should_reload: flags.shouldReload });
|
| 586 |
-
} catch (e) { res.status(500).json({ error: "Processing Error" }); }
|
| 587 |
-
});
|
| 588 |
-
|
| 589 |
-
// --- AUTOMATED MORNING BRIEFING ---
|
| 590 |
-
app.post('/automated-briefing', async (req, res) => {
|
| 591 |
-
const { projectId } = req.body;
|
| 592 |
-
|
| 593 |
-
try {
|
| 594 |
-
const isFrozen = await StateManager.isFrozen(projectId);
|
| 595 |
-
const { data: lastThrust } = await supabase.from('thrusts').select('created_at').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(1).single();
|
| 596 |
-
|
| 597 |
-
const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
|
| 598 |
-
const todayDate = new Date().getDate();
|
| 599 |
-
|
| 600 |
-
if (isFrozen) return res.json({ status: "skipped_frozen" });
|
| 601 |
-
if (lastThrustDate === todayDate) return res.json({ status: "skipped_exists" });
|
| 602 |
-
|
| 603 |
-
// TONE DIRECTIVE INJECTED INTO PROMPT
|
| 604 |
-
const prompt = "It 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>.";
|
| 605 |
-
|
| 606 |
-
const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
|
| 607 |
-
const { data: timeline } = await supabase.from('timeline_events').select('*').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(5);
|
| 608 |
-
|
| 609 |
-
const projectContext = `[PRD]: ${lead.requirements_doc}\n[RECENT TIMELINE]: ${JSON.stringify(timeline)}`;
|
| 610 |
-
const history = await StateManager.getHistory(projectId);
|
| 611 |
-
|
| 612 |
-
const aiResult = await callAI(history, prompt, {}, prompts.director_system_prompt, projectContext, SMART_MODEL_ID);
|
| 613 |
-
|
| 614 |
-
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 615 |
-
const cmds = extractCommands(aiResult.text);
|
| 616 |
-
await executeCommands(lead.user_id, projectId, cmds);
|
| 617 |
|
| 618 |
await StateManager.setFrozen(projectId, true);
|
| 619 |
res.json({ success: true });
|
|
@@ -622,5 +316,4 @@ app.post('/automated-briefing', async (req, res) => {
|
|
| 622 |
});
|
| 623 |
|
| 624 |
app.get('/', async (req, res) => res.status(200).json({ status: "Alive" }));
|
| 625 |
-
app.listen(PORT, () => console.log(`✅ Core Online: ${PORT}`));
|
| 626 |
-
*/
|
|
|
|
| 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 |
|
|
|
|
| 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 {}
|
|
|
|
| 113 |
const now = new Date();
|
| 114 |
const target = new Date(now);
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
const targetUtcMinutes = (6 * 60) - (offset * 60);
|
|
|
|
|
|
|
| 117 |
target.setUTCHours(0, targetUtcMinutes, 0, 0);
|
| 118 |
|
|
|
|
| 119 |
if (target <= now) target.setDate(target.getDate() + 1);
|
| 120 |
|
| 121 |
const delayMs = target.getTime() - now.getTime();
|
|
|
|
| 126 |
body: JSON.stringify({
|
| 127 |
secret: CRON_SECRET,
|
| 128 |
jobId: `briefing_${projectId}`,
|
| 129 |
+
intervalMs: 86400000,
|
| 130 |
initialDelay: delayMs,
|
| 131 |
webhookUrl: `https://everydaytok-thrust-core-server.hf.space/automated-briefing`,
|
| 132 |
leadId: projectId,
|
|
|
|
| 135 |
}).catch(()=>{});
|
| 136 |
}
|
| 137 |
|
| 138 |
+
// --- EMAIL DISPATCHER HELPER ---
|
| 139 |
async function dispatchEmail(userId, projectId, projectName, briefingId, markdownContent) {
|
| 140 |
console.log(`📧 Dispatching email to Utility Server for Project: ${projectName}`);
|
| 141 |
fetch(`${UTILITY_SERVER_URL}/api/email/send-briefing`, {
|
|
|
|
| 143 |
headers: { 'Content-Type': 'application/json' },
|
| 144 |
body: JSON.stringify({ userId, projectId, projectName, briefingId, markdownContent })
|
| 145 |
}).catch(e => console.error("Email Dispatch Error:", e.message));
|
| 146 |
+
}
|
| 147 |
|
| 148 |
async function executeCommands(userId, projectId, commands) {
|
| 149 |
+
// TRACK THE NEW THRUST SO WE CAN EMAIL IT LATER
|
| 150 |
+
let flags = { shouldReload: false, thrustComplete: false, newThrustId: null, newThrustMarkdown: null };
|
| 151 |
|
| 152 |
for (const cmd of commands) {
|
| 153 |
try {
|
| 154 |
if (cmd.type === 'create_thrust') {
|
| 155 |
+
// Wipe old thrust
|
| 156 |
+
await supabase.from('thrusts').delete().eq('lead_id', projectId);
|
| 157 |
+
|
| 158 |
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();
|
| 159 |
if (thrust && cmd.payload.tasks && cmd.payload.tasks.length > 0) {
|
| 160 |
const tasks = cmd.payload.tasks.map(t => ({ thrust_id: thrust.id, title: t }));
|
| 161 |
await supabase.from('thrust_tasks').insert(tasks);
|
| 162 |
}
|
| 163 |
+
|
| 164 |
flags.shouldReload = true;
|
| 165 |
+
|
| 166 |
+
// Capture data for email dispatch
|
| 167 |
+
if (thrust) {
|
| 168 |
+
flags.newThrustId = thrust.id;
|
| 169 |
+
flags.newThrustMarkdown = cmd.payload.markdown_content;
|
| 170 |
+
}
|
| 171 |
}
|
| 172 |
|
| 173 |
if (cmd.type === 'log_timeline') {
|
|
|
|
| 213 |
} catch (e) {}
|
| 214 |
}
|
| 215 |
return flags;
|
| 216 |
+
}
|
| 217 |
|
| 218 |
app.post('/init-project', async (req, res) => {
|
| 219 |
+
// Note: timezoneOffset added here to capture frontend's data
|
| 220 |
const { userId, name, description, localPath, timezoneOffset = 0 } = req.body;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
const { data: lead } = await supabase.from('leads').insert({ user_id: userId, name, description, local_path: localPath, status: 'active', requirements_doc: "Init..." }).select().single();
|
| 222 |
res.json({ success: true, leadId: lead.id });
|
| 223 |
|
| 224 |
setImmediate(async () => {
|
| 225 |
try {
|
| 226 |
+
const initInput = `PROJECT: ${name}\nDESC: ${description}\nUSER TIMEZONE OFFSET: ${timezoneOffset}\nTask: Init PRD, First Thrust, Schedule Morning Briefing.`;
|
| 227 |
const aiResult = await callAI([], initInput, {}, [], prompts.init_system_prompt, "", SMART_MODEL_ID);
|
| 228 |
aiResult.text += `\n<notification>Project '${name}' initialized successfully!</notification>`;
|
| 229 |
await StateManager.addHistory(lead.id, 'user', initInput);
|
| 230 |
await StateManager.addHistory(lead.id, 'model', aiResult.text);
|
| 231 |
const cmds = extractCommands(aiResult.text);
|
| 232 |
await executeCommands(userId, lead.id, cmds);
|
| 233 |
+
|
| 234 |
+
// NO EMAIL DISPATCH HERE - strictly for morning briefings!
|
| 235 |
} catch (err) {}
|
| 236 |
});
|
| 237 |
});
|
|
|
|
| 238 |
|
| 239 |
app.post('/process', async (req, res) => {
|
| 240 |
const { userId, projectId, prompt, context, images, task_type = 'chat' } = req.body;
|
|
|
|
| 261 |
aiResult.text += `\n\n[DIRECTOR INTERVENTION]:\n${smartResult.text}`;
|
| 262 |
const smartCmds = extractCommands(smartResult.text);
|
| 263 |
await executeCommands(userId, projectId, smartCmds);
|
| 264 |
+
|
| 265 |
+
// NO EMAIL DISPATCH HERE - strictly for morning briefings!
|
| 266 |
+
|
| 267 |
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 268 |
} else {
|
| 269 |
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
|
|
|
| 282 |
const { data: lastThrust } = await supabase.from('thrusts').select('created_at').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(1).single();
|
| 283 |
|
| 284 |
const lastThrustDate = lastThrust ? new Date(lastThrust.created_at).getDate() : 0;
|
| 285 |
+
const today = new Date();
|
| 286 |
+
const todayDate = today.getDate();
|
| 287 |
|
| 288 |
if (isFrozen) return res.json({ status: "skipped_frozen" });
|
| 289 |
if (lastThrustDate === todayDate) return res.json({ status: "skipped_exists" });
|
| 290 |
|
| 291 |
+
const currentDateString = today.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
|
| 292 |
+
|
| 293 |
+
const prompt = `[SYSTEM TIME: ${currentDateString} at 6: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>.`;
|
| 294 |
|
| 295 |
const { data: lead } = await supabase.from('leads').select('*').eq('id', projectId).single();
|
| 296 |
const { data: timeline } = await supabase.from('timeline_events').select('*').eq('lead_id', projectId).order('created_at', { ascending: false }).limit(5);
|
|
|
|
| 302 |
|
| 303 |
await StateManager.addHistory(projectId, 'model', aiResult.text);
|
| 304 |
const cmds = extractCommands(aiResult.text);
|
| 305 |
+
const flags = await executeCommands(lead.user_id, projectId, cmds);
|
| 306 |
|
| 307 |
+
// 👉 EMAIL IS DISPATCHED ONLY HERE
|
| 308 |
+
if (flags.newThrustId) {
|
| 309 |
+
await dispatchEmail(lead.user_id, projectId, lead.name, flags.newThrustId, flags.newThrustMarkdown);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
await StateManager.setFrozen(projectId, true);
|
| 313 |
res.json({ success: true });
|
|
|
|
| 316 |
});
|
| 317 |
|
| 318 |
app.get('/', async (req, res) => res.status(200).json({ status: "Alive" }));
|
| 319 |
+
app.listen(PORT, () => console.log(`✅ Core Online: ${PORT}`));
|
|
|