File size: 16,146 Bytes
c9f2107
 
 
 
 
b6fcea9
ef9fa39
 
 
a0a89c1
ef9fa39
 
a0a89c1
f8e692f
a0a89c1
ef9fa39
a0a89c1
be18b86
ef9fa39
 
 
 
a0a89c1
ef9fa39
 
 
 
9903c38
ab9b3de
b6fcea9
 
ef9fa39
b6fcea9
 
ab9b3de
f48f6ae
3456cb8
ef9fa39
b6fcea9
ef9fa39
 
b6fcea9
 
 
c9f2107
ab9b3de
8edba50
 
 
 
 
 
 
edd1266
8edba50
 
 
 
edd1266
a339571
edd1266
 
 
a339571
 
 
 
 
ef9fa39
 
182a272
ef9fa39
 
 
 
 
 
 
3443915
 
 
 
 
 
 
 
 
ef9fa39
 
 
 
 
 
 
182a272
ef9fa39
 
 
 
 
 
3443915
ef9fa39
182a272
3443915
 
182a272
 
 
3443915
 
 
 
 
 
 
182a272
 
 
 
 
3443915
ef9fa39
 
 
 
3443915
ef9fa39
 
 
aadc0a4
ef9fa39
3443915
ef9fa39
 
3443915
ef9fa39
3443915
 
 
 
 
 
 
 
ef9fa39
3443915
182a272
3443915
 
 
 
 
ef9fa39
 
 
 
 
 
 
182a272
ef9fa39
a339571
b6fcea9
ef9fa39
b6fcea9
 
c9f2107
 
b6fcea9
 
8edba50
b6fcea9
 
 
 
c9f2107
8edba50
 
b6fcea9
8edba50
b6fcea9
 
8edba50
b6fcea9
 
edd1266
 
b6fcea9
 
 
c9f2107
ef9fa39
b6fcea9
8edba50
 
 
 
 
b6fcea9
0787978
ef9fa39
a339571
 
ef9fa39
b6fcea9
 
ef9fa39
 
b6fcea9
 
 
 
ef9fa39
b6fcea9
712d3b7
edd1266
712d3b7
 
0787978
c9f2107
ef9fa39
0787978
8edba50
0787978
8edba50
b6fcea9
8edba50
b6fcea9
 
c9f2107
8edba50
 
b6fcea9
edd1266
0787978
c9f2107
ef9fa39
b6fcea9
8edba50
edd1266
8edba50
b6fcea9
 
 
 
 
 
 
 
 
ef9fa39
a339571
b6fcea9
 
0787978
 
ef9fa39
b6fcea9
8edba50
edd1266
8edba50
 
 
 
b6fcea9
0787978
edd1266
 
8edba50
 
b6fcea9
 
 
 
8edba50
edd1266
8edba50
b6fcea9
 
 
8edba50
ef9fa39
a339571
ef9fa39
edd1266
 
8edba50
edd1266
0787978
b6fcea9
 
 
edd1266
a339571
ef9fa39
8edba50
0787978
b6fcea9
0787978
ef9fa39
b6fcea9
edd1266
8edba50
edd1266
b6fcea9
ef9fa39
edd1266
 
 
ef9fa39
 
edd1266
 
ef9fa39
edd1266
 
 
ef9fa39
a339571
edd1266
a339571
edd1266
a339571
edd1266
 
 
 
 
 
 
 
b6fcea9
 
a339571
b6fcea9
 
 
a339571
b6fcea9
c9f2107
0787978
8edba50
0787978
 
c9f2107
b6fcea9
8edba50
ef9fa39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8edba50
b6fcea9
 
 
0787978
b6fcea9
f48f6ae
8edba50
edd1266
 
b6fcea9
c9f2107
edd1266
b6fcea9
 
c9f2107
b6fcea9
a339571
 
8edba50
 
c9f2107
ef9fa39
a339571
ef9fa39
a339571
 
ef9fa39
a339571
 
 
ef9fa39
a339571
 
ef9fa39
a339571
 
 
 
ef9fa39
a339571
 
 
8edba50
 
 
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
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import { StateManager } from './stateManager.js';
import { AIEngine } from './aiEngine.js';
import fs from 'fs';
import admin from 'firebase-admin';

// --- FIREBASE SETUP ---
// Using environment variable injection as requested
let db = null;
try {
    if (process.env.FIREBASE_SERVICE_ACCOUNT_JSON && process.env.FIREBASE_SERVICE_ACCOUNT_JSON !== "") {
        const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT_JSON);
        admin.initializeApp({
            credential: admin.credential.cert(serviceAccount),
            // Make sure to replace this URL or add it to env variables as well
            databaseURL: "https://shago-web-default-rtdb.firebaseio.com" 
        });
        db = admin.database();
        console.log("🔥 Firebase Connected");
    } else {
        console.warn("⚠️ No FIREBASE_SERVICE_ACCOUNT_JSON found. Running in Memory-Only mode.");
    }
} catch (e) {
    console.error("Firebase Init Error:", e);
}

const app = express();
const PORT = process.env.PORT || 7860;

// Load Prompts for Server-Side Logic Checks
const sysPrompts = JSON.parse(fs.readFileSync('./prompts.json', 'utf8'));

app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));

// --- HELPERS ---
const validateRequest = (req, res, next) => {
    if (req.path.includes('/onboarding')) return next();
    
    const { userId, projectId } = req.body;
    if (!userId || !projectId) return res.status(400).json({ error: "Missing ID" });
    next();
};

function extractWorkerPrompt(text) {
    const match = text.match(/WORKER_PROMPT:\s*(.*)/s);
    return match ? match[1].trim() : null;
}

function formatContext({ hierarchyContext, scriptContext, logContext }) {
    let out = "";
    if (scriptContext) out += `\n[TARGET SCRIPT]: ${scriptContext.targetName}\n[SOURCE PREVIEW]: ${scriptContext.scriptSource?.substring(0, 1000)}...`;
    if (logContext) out += `\n[LAST LOGS]: ${logContext.logs}`;
    return out;
}

function extractPMQuestion(text) {
    const match = text.match(/\[ASK_PM:\s*(.*?)\]/s); 
    return match ? match[1].trim() : null;
}

function extractImagePrompt(text) {
    const match = text.match(/\[GENERATE_IMAGE:\s*(.*?)\]/s);
    return match ? match[1].trim() : null;
}

// --- ONBOARDING ENDPOINTS ---
/**
 * 1. ANALYZE
 */
app.post('/onboarding/analyze', validateRequest, async (req, res) => {
    const { description } = req.body;
    if (!description) return res.status(400).json({ error: "Description required" });

    try {
        console.log(`[Onboarding] Analyzing idea...`);
        const result = await AIEngine.generateEntryQuestions(description);
        
        if (result.status === "REJECTED") {
            return res.json({ 
                rejected: true, 
                reason: result.reason || "Idea violates TOS or guidelines." 
            });
        }
        res.json({ questions: result.questions });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: "Analysis failed" });
    }
});

/**
 * 2. CREATE
 */
app.post('/onboarding/create', validateRequest, async (req, res) => {
    const { userId, description, answers } = req.body;
    const projectId = "proj_" + Date.now(); 

    try {
        console.log(`[Onboarding] Grading Project ${projectId}...`);

        // STEP 1: GRADE
        const grading = await AIEngine.gradeProject(description, answers);
        
        // STEP 2: CHECK FAIL CONDITIONS (Relaxed)
        // Only fail if Feasibility is extremely low (< 30) or Rating is F
        const isFailure = grading.feasibility < 30 || grading.rating === 'F';

        let thumbnailBase64 = null;

        if (isFailure) {
            console.log(`[Onboarding] ❌ Project Failed Grading (${grading.rating}). Skipping Image.`);
        } else {
            console.log(`[Onboarding] ✅ Passed. Generating Thumbnail...`);
            
            // --- CRITICAL FIX HERE ---
            // We MUST send the description so the AI knows what to draw.
            const imagePrompt = `Game Title: ${grading.title}. Core Concept: ${description}`;
            thumbnailBase64 = await AIEngine.generateImage(imagePrompt);
        }

        const projectData = {
            id: projectId,
            userId,
            title: grading.title || "Untitled Project",
            description,
            answers,
            stats: grading,
            thumbnail: thumbnailBase64, // ? `data:image/png;base64,${thumbnailBase64}` : null,
            createdAt: Date.now(),
            status: isFailure ? "rejected" : "initialized"
        };

        if (db) await db.ref(`projects/${projectId}`).set(projectData);
        
        if (!isFailure) {
            await StateManager.updateProject(projectId, {
                ...projectData,
                workerHistory: [],
                pmHistory: [],
                failureCount: 0
            });
        }

        res.json({ 
            success: !isFailure, 
            projectId, 
            stats: grading, 
            title: projectData.title,
            thumbnail: projectData.thumbnail 
        });

    } catch (err) {
        console.error("Create Error:", err);
        res.status(500).json({ error: "Creation failed" });
    }
});


// --- CORE WORKFLOW ENDPOINTS ---

/**
 * 3. INITIALIZE WORKSPACE (PM Generates GDD -> First Task)
 */
app.post('/new/project', validateRequest, async (req, res) => {
    const { userId, projectId, description } = req.body;

    try {
        const pmHistory = [];
        const gddPrompt = `Create a comprehensive GDD for: ${description}`;
        const gddResponse = await AIEngine.callPM(pmHistory, gddPrompt);
        
        pmHistory.push({ role: 'user', parts: [{ text: gddPrompt }] });
        pmHistory.push({ role: 'model', parts: [{ text: gddResponse }] });

        const taskPrompt = "Based on the GDD, generate the first technical milestone.\nOutput format:\nTASK_NAME: <Name>\nWORKER_PROMPT: <Specific, isolated instructions for the worker>";
        const taskResponse = await AIEngine.callPM(pmHistory, taskPrompt);

        pmHistory.push({ role: 'user', parts: [{ text: taskPrompt }] });
        pmHistory.push({ role: 'model', parts: [{ text: taskResponse }] });

        const initialWorkerInstruction = extractWorkerPrompt(taskResponse) || `Initialize structure for: ${description}`;

        const workerHistory = [];
        const initialWorkerPrompt = `CONTEXT: New Project. \nINSTRUCTION: ${initialWorkerInstruction}`;
        const workerResponse = await AIEngine.callWorker(workerHistory, initialWorkerPrompt, []);

        workerHistory.push({ role: 'user', parts: [{ text: initialWorkerPrompt }] });
        workerHistory.push({ role: 'model', parts: [{ text: workerResponse }] });

        // Update State
        await StateManager.updateProject(projectId, {
            userId,
            pmHistory,
            workerHistory,
            gdd: gddResponse,
            failureCount: 0
        });

        // Queue Actions
        await processAndQueueResponse(projectId, workerResponse);

        res.json({ success: true, message: "Workspace Initialized", gddPreview: gddResponse.substring(0, 200) });

    } catch (err) {
        console.error("Init Error:", err);
        res.status(500).json({ error: "Initialization Failed" });
    }
});

/**
 * 4. FEEDBACK LOOP (The "Brain")
 */
app.post('/project/feedback', async (req, res) => {
    const { projectId, prompt, hierarchyContext, scriptContext, logContext, taskComplete, images } = req.body;
    
    const project = await StateManager.getProject(projectId);
    if (!project) return res.status(404).json({ error: "Project not found." });

    // A. TASK COMPLETE -> SCOPE SWITCH
    if (taskComplete) {
        console.log(`[${projectId}] ✅ TASK COMPLETE.`);
        
        const summary = `Worker completed the previous task. Logs: ${logContext?.logs || "Clean"}. \nGenerate the NEXT task using 'WORKER_PROMPT:' format.`;
        const pmResponse = await AIEngine.callPM(project.pmHistory, summary);
        
        project.pmHistory.push({ role: 'user', parts: [{ text: summary }] });
        project.pmHistory.push({ role: 'model', parts: [{ text: pmResponse }] });

        const nextInstruction = extractWorkerPrompt(pmResponse);
        if (!nextInstruction) {
             await StateManager.updateProject(projectId, { pmHistory: project.pmHistory, status: "IDLE" });
             return res.json({ success: true, message: "No further tasks. Project Idle." });
        }

        console.log(`[${projectId}] 🧹 Nuking Worker for next task.`);
        const newWorkerHistory = [];
        const newPrompt = `New Objective: ${nextInstruction}`;
        const workerResponse = await AIEngine.callWorker(newWorkerHistory, newPrompt, []);

        newWorkerHistory.push({ role: 'user', parts: [{ text: newPrompt }] });
        newWorkerHistory.push({ role: 'model', parts: [{ text: workerResponse }] });

        await StateManager.updateProject(projectId, {
            pmHistory: project.pmHistory,
            workerHistory: newWorkerHistory,
            failureCount: 0
        });

        StateManager.queueCommand(projectId, { type: "EXECUTE", payload: "warn('Starting Next Task...')" });
        await processAndQueueResponse(projectId, workerResponse);

        return res.json({ success: true, message: "Next Task Assigned" });
    }

    // B. ERROR ESCALATION
    let isFailure = false;
    if (logContext?.logs) {
        const errs = ["Error", "Exception", "failed", "Stack Begin", "Infinite yield"];
        if (errs.some(k => logContext.logs.includes(k))) {
            isFailure = true;
            project.failureCount = (project.failureCount || 0) + 1;
        }
    }

    if (project.failureCount > 3) {
        console.log(`[${projectId}] 🚨 Escalating to PM...`);
        const pmPrompt = sysPrompts.pm_guidance_prompt.replace('{{LOGS}}', logContext?.logs);
        const pmVerdict = await AIEngine.callPM(project.pmHistory, pmPrompt);

        if (pmVerdict.includes("[TERMINATE]")) {
            const fixInstruction = pmVerdict.replace("[TERMINATE]", "").trim();
            const resetHistory = [];
            const resetPrompt = `[SYSTEM]: Previous worker terminated. \nNew Objective: ${fixInstruction}`;
            const workerResp = await AIEngine.callWorker(resetHistory, resetPrompt, []);
            
            resetHistory.push({ role: 'user', parts: [{ text: resetPrompt }] });
            resetHistory.push({ role: 'model', parts: [{ text: workerResp }] });

            await StateManager.updateProject(projectId, { workerHistory: resetHistory, failureCount: 0 });
            StateManager.queueCommand(projectId, { type: "EXECUTE", payload: "print('SYSTEM: Worker Reset')" });
            await processAndQueueResponse(projectId, workerResp);
            
            return res.json({ success: true, message: "Worker Terminated." });
        } else {
            const injection = `[PM GUIDANCE]: ${pmVerdict} \n\nApply this fix now.`;
            const workerResp = await AIEngine.callWorker(project.workerHistory, injection, []);
            
            project.workerHistory.push({ role: 'user', parts: [{ text: injection }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: workerResp }] });
            
            await StateManager.updateProject(projectId, { workerHistory: project.workerHistory, failureCount: 1 });
            await processAndQueueResponse(projectId, workerResp);
            
            return res.json({ success: true, message: "PM Guidance Applied." });
        }
    }

    // C. STANDARD LOOP + CONSULTATION
    try {
        const fullInput = `USER: ${prompt || "Automatic Feedback"}` + formatContext({ hierarchyContext, scriptContext, logContext });
        
        let response = await AIEngine.callWorker(project.workerHistory, fullInput, images || []);
        
        // CHECK: Consultant Question
        const pmQuestion = extractPMQuestion(response);
        if (pmQuestion) {
            console.log(`[${projectId}] 🙋 Worker asking PM: "${pmQuestion}"`);
            
            const pmConsultPrompt = `[WORKER CONSULTATION]: The Worker asks: "${pmQuestion}"\nProvide a technical answer to unblock them.`;
            const pmAnswer = await AIEngine.callPM(project.pmHistory, pmConsultPrompt);

            // Update PM Context
            project.pmHistory.push({ role: 'user', parts: [{ text: pmConsultPrompt }] });
            project.pmHistory.push({ role: 'model', parts: [{ text: pmAnswer }] });

            // Feed Answer Back
            const injectionMsg = `[PM RESPONSE]: ${pmAnswer}`;
            project.workerHistory.push({ role: 'user', parts: [{ text: fullInput }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: response }] });
            
            // Resume Worker
            response = await AIEngine.callWorker(project.workerHistory, injectionMsg, []);
            project.workerHistory.push({ role: 'user', parts: [{ text: injectionMsg }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: response }] });
        } else {
            project.workerHistory.push({ role: 'user', parts: [{ text: fullInput }] });
            project.workerHistory.push({ role: 'model', parts: [{ text: response }] });
        }

        await StateManager.updateProject(projectId, { 
            workerHistory: project.workerHistory,
            pmHistory: project.pmHistory, 
            failureCount: project.failureCount 
        });
        
        await processAndQueueResponse(projectId, response);
        res.json({ success: true });

    } catch (err) {
        console.error("AI Error:", err);
        res.status(500).json({ error: "AI Failed" });
    }
});

/**
 * 5. PING (Plugin Polling)
 */
app.post('/project/ping', async (req, res) => {
    const { projectId } = req.body;
    const command = await StateManager.popCommand(projectId);
    
    if (command) {
        if (command.payload === "CLEAR_CONSOLE") {
             res.json({ action: "CLEAR_LOGS" });
        } else {
            res.json({ 
                action: command.type, 
                target: command.payload, 
                code: command.type === 'EXECUTE' ? command.payload : null 
            });
        }
    } else {
        res.json({ action: "IDLE" });
    }
});

/**
 * 6. MANUAL OVERRIDE
 */
app.post('/human/override', validateRequest, async (req, res) => {
    const { projectId, instruction, pruneHistory } = req.body;
    const project = await StateManager.getProject(projectId);
    
    const overrideMsg = `[SYSTEM OVERRIDE]: ${instruction}`;
    
    if (pruneHistory && project.workerHistory.length >= 2) {
        project.workerHistory.pop();
        project.workerHistory.pop();
    }

    const response = await AIEngine.callWorker(project.workerHistory, overrideMsg, []);
    project.workerHistory.push({ role: 'user', parts: [{ text: overrideMsg }] });
    project.workerHistory.push({ role: 'model', parts: [{ text: response }] });

    await StateManager.updateProject(projectId, { workerHistory: project.workerHistory });
    await processAndQueueResponse(projectId, response);
    res.json({ success: true });
});


// --- RESPONSE PROCESSOR ---
async function processAndQueueResponse(projectId, rawResponse) {
    // 1. Intercept Image Requests
    const imgPrompt = extractImagePrompt(rawResponse);
    if (imgPrompt) {
        console.log(`[${projectId}] 🎨 Generating Asset: ${imgPrompt}`);
        const base64Image = await AIEngine.generateImage(imgPrompt);
        
        if (base64Image) {
            // Queue asset creation for Plugin
            await StateManager.queueCommand(projectId, {
                type: "CREATE_ASSET", 
                payload: base64Image
            });
        }
    }

    // 2. Queue the Raw Response (StateManager parses code)
    await StateManager.queueCommand(projectId, rawResponse);
}

app.listen(PORT, () => {
    console.log(`AI Backend Running on ${PORT}`);
});