File size: 4,826 Bytes
632108b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import fetch from "node-fetch";
import { exec } from "child_process";
import { promisify } from "util";
import fs from "fs";

const execPromise = promisify(exec);
dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

const CONFIG = {
  groq: {
    apiKey: process.env.GROQ_API_KEY || "",
    model: process.env.MODEL_ID || "openai/gpt-oss-120b"
  }
};

const OPENCLAW_SYSTEM_PROMPT = `
You are OpenClaw, a self-evolving autonomous agent with FULL SHELL ACCESS.
Your goal is to fulfill user requests by planning, installing necessary skills, and executing tasks INTERNALLY.

CAPABILITIES:
1. DYNAMIC SKILL INSTALLATION: Use 'execute_shell' to install any tool (ffmpeg, yt-dlp, npm packages, python libs).
2. INTERNAL EXECUTION: You are running in a persistent cloud container. You execute commands yourself.
3. CODE GENERATION: Write and execute Node.js, Python, or Shell scripts to perform complex operations.

OPERATIONAL GUIDELINES:
- You have permission to manage files and execute commands to fulfill the mission.
- If a tool is missing, INSTALL IT.
- For multi-step tasks, provide your full plan first, then execute step-by-step.
`;

const tools = [
  {
    name: "execute_shell",
    description: "Executes a shell command in the cloud environment.",
    parameters: {
      type: "object",
      properties: {
        command: { type: "string", description: "The bash/shell command to execute" }
      },
      required: ["command"]
    }
  },
  {
    name: "read_write_file",
    description: "Read or write content to a file in the workspace.",
    parameters: {
      type: "object",
      properties: {
        path: { type: "string", description: "File path" },
        content: { type: "string", description: "Content to write (if writing)" },
        action: { type: "string", enum: ["read", "write"] }
      },
      required: ["path", "action"]
    }
  }
];

// Self-Executing Agent Loop
app.post("/api/agent", async (req, res) => {
  const { message, history = [] } = req.body;
  let currentHistory = [...history];
  let currentMessage = message;
  let finalResponse = { content: "", actions: [] as any[] };

  try {
    // Run up to 10 iterations to prevent infinite loops
    for (let i = 0; i < 10; i++) {
      const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
        method: "POST",
        headers: {
          "Authorization": \`Bearer \${CONFIG.groq.apiKey}\`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          model: CONFIG.groq.model,
          messages: [
            { role: "system", content: OPENCLAW_SYSTEM_PROMPT },
            ...currentHistory,
            { role: "user", content: currentMessage }
          ],
          tools: tools.map(t => ({ type: "function", function: t })),
          tool_choice: "auto",
          temperature: 0.5
        })
      });

      const data: any = await response.json();
      if (!response.ok) throw new Error(data.error?.message || "Groq Error");

      const assistantMessage = data.choices[0].message;
      currentHistory.push(assistantMessage);

      if (assistantMessage.content) {
        finalResponse.content += assistantMessage.content + "\n";
      }

      if (!assistantMessage.tool_calls) {
        break; // Task finished
      }

      // EXECUTE TOOLS INTERNALLY
      for (const call of assistantMessage.tool_calls) {
        const { name, arguments: argsJson } = call.function;
        const args = JSON.parse(argsJson);
        let output = "";

        try {
          if (name === "execute_shell") {
            const { stdout, stderr } = await execPromise(args.command);
            output = stdout || stderr || "Success";
          } else if (name === "read_write_file") {
            if (args.action === "write") {
              fs.writeFileSync(args.path, args.content);
              output = \`Successfully wrote to \${args.path}\`;
            } else {
              output = fs.readFileSync(args.path, "utf8");
            }
          }
        } catch (err: any) {
          output = \`Error: \${err.message}\`;
        }

        currentHistory.push({
          tool_call_id: call.id,
          role: "tool",
          name: name,
          content: output
        });

        finalResponse.actions.push({ name, args, output });
      }

      currentMessage = "Continue based on the tool results.";
    }

    res.json(finalResponse);

  } catch (error: any) {
    res.status(500).json({ error: error.message });
  }
});

app.get("/", (req, res) => res.send("OpenClaw Autonomous Cloud Server is running."));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(\`Server running on port \${PORT}\`));