'use strict'; // ============================================================================ // 🤖 CODING AGENT (used ONLY by /api/agent-stream when the user picked "🤖 Agent") // // WRITE -> TEST -> FIX (edit only the broken lines) -> TEST again -> PRESENT // // It is the Node.js version of the Flask app.py agent: Gemini function-calling with // write_code / edit_code / read_file / execute_code / present_files // and it talks to the page with the SAME SSE events search.html already understands // (step / thought / plan / command / file_chunk / test / cmd_output / verdict / files / final / done). // // SAFETY // - every request gets its own temp workspace (deleted afterwards) // - code runs with a CLEAN environment (no API keys / secrets), no shell, no stdin, 15s limit // - file names are sanitised (no ../, no absolute paths) // - set AGENT_RUN_CODE=0 to disable execution (syntax checks only) // // ENV (all optional) // AGENT_RUN_CODE=0 only syntax-check, never execute // AGENT_RUN_TIMEOUT_SEC=30 time limit for one test run // AGENT_MAX_TURNS=18 max model turns per request // GEMINI_BASE_URL=... (tests only) point Gemini calls at a mock server // ============================================================================ const fs = require('fs'); const os = require('os'); const path = require('path'); const { spawn } = require('child_process'); const GEMINI_BASE = String(process.env.GEMINI_BASE_URL || 'https://generativelanguage.googleapis.com').replace(/\/+$/, ''); const IS_WIN = process.platform === 'win32'; const RUN_CODE = process.env.AGENT_RUN_CODE !== '0'; const RUN_LIMIT_MS = (parseInt(process.env.AGENT_RUN_TIMEOUT_SEC) || 30) * 1000; // a test run may take up to 30 seconds const MAX_TURNS = parseInt(process.env.AGENT_MAX_TURNS) || 35; // 🚀 Increased from 18 to 35 turns for deep 5-15 minute runs const MAX_WALL_MS = 15 * 60 * 1000; // 🚀 15 minutes limit (user requested 5-15 minutes instead of 1 minute) const MAX_FILE_BYTES = 400000; // a file the AI WRITES (new files) const MAX_SEED_BYTES = 3000000; // a file the USER uploaded (big pages like search.html are ~700 KB; used to be cut at 400 KB = "file is CUT OFF") const MAX_WS_BYTES = 24000000; const MAX_FILES = 80; const MAX_OUT = 100000; // show (almost) the FULL output of installs and runs const IDLE_MS = (parseFloat(process.env.AGENT_IDLE_SEC) || 15) * 1000; // 🚀 Fast failover watchdog: 15s instead of 90s to eliminate startup delay const HEARTBEAT_MS = (parseFloat(process.env.AGENT_HEARTBEAT_SEC) || 6) * 1000; // "still working..." message while the AI is silent const MAX_THOUGHT_CHARS = parseInt(process.env.AGENT_MAX_THOUGHT_CHARS) || 12000; // a thinking loop is cut after this much const FIRST_MAX_OUTPUT = 32768; // 🚀 Models pool: prioritize responsive, verified models first (gemini-2.5-flash, gemini-3.5-flash) to start in <1s const csv = (v, d) => String(v || d).split(',').map(x => x.trim()).filter(Boolean); const MODELS_STRONG = csv(process.env.AGENT_MODELS_STRONG, 'gemini-2.5-flash,gemini-3.5-flash,gemini-3.5-flash-lite,gemini-3.6-flash'); const MODELS_CHEAP = csv(process.env.AGENT_MODELS_CHEAP, 'gemini-2.5-flash,gemini-3.5-flash-lite,gemini-3.5-flash,gemini-3.6-flash'); const TRUNC_NOTE = '\n[output truncated]\n'; const PY_USER_BASE = path.join(os.tmpdir(), 'agent-pyuser'); const NPM_CACHE = path.join(os.tmpdir(), 'agent-npm-cache'); // ---------------------------------------------------------------------------- // Tools (same five as app.py) // ---------------------------------------------------------------------------- const TOOLS = [ { name: 'write_code', description: 'Creates a NEW file and writes the COMPLETE code to it. NEVER use this to modify an existing file (use edit_code).', parameters: { type: 'OBJECT', properties: { filename: { type: 'STRING', description: 'Relative path, e.g. app.py, games/snake.html, src/utils.js' }, content: { type: 'STRING', description: 'The complete, final source code of the file. No placeholders.' } }, required: ['filename', 'content'] } }, { name: 'edit_code', description: 'Edits an existing file by replacing one exact piece of text. Output ONLY the few lines that change, never the whole file.', parameters: { type: 'OBJECT', properties: { filename: { type: 'STRING' }, search_string: { type: 'STRING', description: 'Exact existing text to find (must match exactly ONE place; include enough surrounding lines).' }, replace_string: { type: 'STRING', description: 'The new text that replaces it.' } }, required: ['filename', 'search_string', 'replace_string'] } }, { name: 'read_file', description: 'Reads a file of this conversation (uploaded by the user or created by you): code, text, or the extracted text of a PDF/Word document. Use it before editing if you are not sure about the exact text. Optional start_line / end_line read only that range of a big file.', parameters: { type: 'OBJECT', properties: { filename: { type: 'STRING' }, start_line: { type: 'INTEGER', description: 'First line to read (1-based). Optional.' }, end_line: { type: 'INTEGER', description: 'Last line to read. Optional.' } }, required: ['filename'] } }, { name: 'execute_code', description: 'Runs the file to TEST it: python / node / java run the program (packages it imports are installed automatically first), html loads the page in a headless browser and reports JavaScript errors. If the program asks for keyboard input, pass the answers in `stdin`. You MUST call this after writing or editing code.', parameters: { type: 'OBJECT', properties: { language: { type: 'STRING', description: 'python, node, java or html' }, filename: { type: 'STRING', description: 'The main file to run / open' }, dependencies: { type: 'ARRAY', items: { type: 'STRING' }, description: 'Extra pip packages (python) or npm packages (node) to install first. Imports are detected and installed automatically, so this is only needed for packages that are not imported directly.' }, stdin: { type: 'STRING', description: 'Text typed into the program when it asks for input (input(), Scanner, readline). One line per prompt, lines separated by \\n, ending with the answer that makes the program exit (e.g. quit). Omit if the program needs no input.' } }, required: ['language', 'filename'] } }, { name: 'present_files', description: 'Call this ONLY after execute_code passed (or when the code truly cannot run on this server). Shows the final files to the user.', parameters: { type: 'OBJECT', properties: { filenames: { type: 'ARRAY', items: { type: 'STRING' }, description: 'All final files for the user.' } }, required: ['filenames'] } }, { name: 'web_search', description: 'Searches the web (Google, through Gemini 2.5 Flash) and returns a short factual answer with source links. Use it for things you are not sure about or that change: exact package names and versions, current API usage, error messages, library docs, anything the user asks you to look up. Do NOT use it for ordinary coding you already know. At most 6 searches per request.', parameters: { type: 'OBJECT', properties: { query: { type: 'STRING', description: 'A clear, specific search question, e.g. "yt-dlp download audio only mp3 python example 2026".' } }, required: ['query'] } }, { name: 'list_files', description: 'Lists the files of THIS conversation with their origin (uploaded by the user / created by you earlier / created in this run), size and line count. Use scope "user" to see only the files the user uploaded, "agent" for only the files you created, "all" for everything.', parameters: { type: 'OBJECT', properties: { scope: { type: 'STRING', description: 'all (default), user or agent' } } } }, { name: 'search_in_files', description: 'Searches text inside all files of this conversation (like grep) and returns file:line matches. Use it to find where a function, variable, import or link is used before you edit or rename something.', parameters: { type: 'OBJECT', properties: { pattern: { type: 'STRING', description: 'Text to find (or a regular expression when regex is true).' }, regex: { type: 'BOOLEAN', description: 'Treat pattern as a regular expression. Default false.' }, case_sensitive: { type: 'BOOLEAN', description: 'Default false.' }, scope: { type: 'STRING', description: 'all (default), user or agent' } }, required: ['pattern'] } }, { name: 'rename_file', description: 'Renames or moves a file (like mv). Afterwards update every reference to the old name (imports,