|
| 1 | +import { execSync } from "child_process"; |
| 2 | +import OpenAI from "openai"; |
| 3 | +import fs from "fs"; |
| 4 | + |
| 5 | +const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); |
| 6 | +const task = process.env.TASK || "Improve code quality"; |
| 7 | +const requester = process.env.REQUESTER || "unknown"; |
| 8 | + |
| 9 | +function sh(cmd) { |
| 10 | + return execSync(cmd, { encoding: "utf8", stdio: "pipe" }); |
| 11 | +} |
| 12 | + |
| 13 | +console.log(`[AGENT] Starting AI code agent for task: ${task}`); |
| 14 | +console.log(`[AGENT] Requested by: ${requester}`); |
| 15 | + |
| 16 | +// Get repo context |
| 17 | +const files = sh("git ls-files"); |
| 18 | +const recentCommits = sh("git log --oneline -10"); |
| 19 | + |
| 20 | +// Read cursor rules for context |
| 21 | +let cursorRules = ""; |
| 22 | +try { |
| 23 | + cursorRules = fs.readFileSync(".cursorrules", "utf8"); |
| 24 | +} catch (e) { |
| 25 | + console.log("[AGENT] No .cursorrules file found"); |
| 26 | +} |
| 27 | + |
| 28 | +// Build specialized prompt for SlackONOS |
| 29 | +const prompt = `You are an autonomous coding agent for SlackONOS, a democratic music bot for Discord and Slack that controls Sonos speakers. |
| 30 | +
|
| 31 | +CRITICAL SAFETY RULES: |
| 32 | +- Output ONLY a valid unified git diff (starting with "diff --git") |
| 33 | +- DO NOT modify authentication files (webauthn-handler.js, auth-handler.js) |
| 34 | +- DO NOT modify config handling (config/*) |
| 35 | +- DO NOT modify security-critical code |
| 36 | +- Small, focused changes only (max 300 lines changed) |
| 37 | +- Follow existing code style (CommonJS, async/await, logger for logging) |
| 38 | +- NEVER use console.log in production code, use logger instead |
| 39 | +- Test your changes mentally before outputting the diff |
| 40 | +
|
| 41 | +CODEBASE CONTEXT: |
| 42 | +
|
| 43 | +Project Rules and Conventions: |
| 44 | +${cursorRules} |
| 45 | +
|
| 46 | +Repository Files: |
| 47 | +${files} |
| 48 | +
|
| 49 | +Recent Commits: |
| 50 | +${recentCommits} |
| 51 | +
|
| 52 | +TASK FROM ADMIN (${requester}): |
| 53 | +${task} |
| 54 | +
|
| 55 | +Generate a safe, focused code change as a unified git diff. The diff will be applied with "git apply" so ensure it's properly formatted. |
| 56 | +
|
| 57 | +Remember: Output ONLY the git diff, no explanations, no markdown code blocks, just the raw diff.`; |
| 58 | + |
| 59 | +console.log("[AGENT] Calling OpenAI API..."); |
| 60 | +const res = await client.chat.completions.create({ |
| 61 | + model: "gpt-4o", |
| 62 | + temperature: 0.2, |
| 63 | + messages: [{ role: "user", content: prompt }], |
| 64 | +}); |
| 65 | + |
| 66 | +const output = res.choices[0].message.content; |
| 67 | + |
| 68 | +// Extract diff from potential markdown code blocks |
| 69 | +let diff = output; |
| 70 | +if (output.includes("```")) { |
| 71 | + // Extract content between code fences |
| 72 | + const match = output.match(/```(?:diff)?\n([\s\S]*?)```/); |
| 73 | + if (match) { |
| 74 | + diff = match[1]; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +// Validate diff format |
| 79 | +if (!diff.includes("diff --git")) { |
| 80 | + console.error("[AGENT] Model did not return a valid diff"); |
| 81 | + console.error("[AGENT] Output was:"); |
| 82 | + console.error(output); |
| 83 | + process.exit(1); |
| 84 | +} |
| 85 | + |
| 86 | +// Safety check: Ensure we're not touching forbidden files |
| 87 | +const forbiddenPatterns = [ |
| 88 | + /webauthn-handler\.js/, |
| 89 | + /auth-handler\.js/, |
| 90 | + /config\/config\.json$/, |
| 91 | + /config\/userActions\.json/, |
| 92 | + /config\/webauthn-credentials\.json/ |
| 93 | +]; |
| 94 | + |
| 95 | +for (const pattern of forbiddenPatterns) { |
| 96 | + if (pattern.test(diff)) { |
| 97 | + console.error(`[AGENT] SAFETY VIOLATION: Attempted to modify forbidden file matching ${pattern}`); |
| 98 | + process.exit(1); |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +// Count lines changed |
| 103 | +const linesChanged = (diff.match(/^[+-][^+-]/gm) || []).length; |
| 104 | +if (linesChanged > 300) { |
| 105 | + console.error(`[AGENT] SAFETY VIOLATION: Too many lines changed (${linesChanged} > 300)`); |
| 106 | + process.exit(1); |
| 107 | +} |
| 108 | + |
| 109 | +console.log(`[AGENT] Generated diff with ${linesChanged} lines changed`); |
| 110 | + |
| 111 | +// Apply patch |
| 112 | +fs.writeFileSync("/tmp/aicode.patch", diff); |
| 113 | +try { |
| 114 | + sh("git apply --check /tmp/aicode.patch"); |
| 115 | + sh("git apply /tmp/aicode.patch"); |
| 116 | + console.log("[AGENT] Patch applied successfully"); |
| 117 | +} catch (err) { |
| 118 | + console.error("[AGENT] Failed to apply patch:", err.message); |
| 119 | + console.error("[AGENT] Diff was:"); |
| 120 | + console.error(diff); |
| 121 | + process.exit(1); |
| 122 | +} |
| 123 | + |
| 124 | +// Show diff for logs |
| 125 | +console.log("\n[AGENT] Generated changes:"); |
| 126 | +console.log(sh("git diff")); |
| 127 | + |
| 128 | +// Stage changes |
| 129 | +sh("git add -A"); |
| 130 | +sh('git config user.name "AICODE Agent"'); |
| 131 | +sh('git config user.email "aicode@slackonos.bot"'); |
| 132 | +sh(`git commit -m "AI: ${task}"`); |
| 133 | + |
| 134 | +console.log("[AGENT] Changes committed, ready for testing"); |
| 135 | + |
0 commit comments