Update server.js
Browse files
server.js
CHANGED
|
@@ -1,20 +1,24 @@
|
|
| 1 |
import express from "express";
|
| 2 |
import { spawn } from "child_process";
|
| 3 |
import dotenv from "dotenv";
|
| 4 |
-
import { fileURLToPath } from 'url';
|
| 5 |
-
import { dirname, join } from 'path';
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
const app = express();
|
| 13 |
app.use(express.json());
|
| 14 |
|
| 15 |
/* ===============================
|
| 16 |
1. BASIC AUTH
|
| 17 |
-
|
| 18 |
|
| 19 |
const GATE_KEY = process.env.OPENCLAW_GATE_KEY;
|
| 20 |
|
|
@@ -28,7 +32,7 @@ app.use((req, res, next) => {
|
|
| 28 |
|
| 29 |
/* ===============================
|
| 30 |
2. RATE LIMITING (IP-based)
|
| 31 |
-
|
| 32 |
|
| 33 |
const RATE_LIMIT = 30; // requests
|
| 34 |
const WINDOW_MS = 60_000;
|
|
@@ -55,7 +59,7 @@ app.use((req, res, next) => {
|
|
| 55 |
|
| 56 |
/* ===============================
|
| 57 |
3. LOAD KEY POOLS
|
| 58 |
-
|
| 59 |
|
| 60 |
function loadPool(prefix) {
|
| 61 |
const keys = Object.keys(process.env)
|
|
@@ -81,7 +85,7 @@ function randomKey(pool) {
|
|
| 81 |
|
| 82 |
/* ===============================
|
| 83 |
4. TASK ROUTING
|
| 84 |
-
|
| 85 |
|
| 86 |
const TASKS = new Set([
|
| 87 |
"market_research",
|
|
@@ -91,7 +95,7 @@ const TASKS = new Set([
|
|
| 91 |
|
| 92 |
/* ===============================
|
| 93 |
5. RUN AGENT
|
| 94 |
-
|
| 95 |
app.use((req, res, next) => {
|
| 96 |
if (req.method === "POST" && !req.is("application/json")) {
|
| 97 |
return res.status(400).json({ error: "JSON body required" });
|
|
@@ -103,14 +107,79 @@ app.get("/", (req, res) => {
|
|
| 103 |
res.json({
|
| 104 |
status: "OpenClaw running on HF Space",
|
| 105 |
service: "market_research_agent",
|
| 106 |
-
endpoints:
|
|
|
|
|
|
|
|
|
|
| 107 |
timestamp: new Date().toISOString()
|
| 108 |
});
|
| 109 |
});
|
| 110 |
|
| 111 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
app.post("/api/market-research", async (req, res) => {
|
| 113 |
-
console.log('OpenClaw
|
| 114 |
keyword: req.body.keyword,
|
| 115 |
timestamp: new Date().toISOString()
|
| 116 |
});
|
|
@@ -131,7 +200,7 @@ app.post("/api/market-research", async (req, res) => {
|
|
| 131 |
apiKeys[provider] = [api_key];
|
| 132 |
providersToTry = [provider];
|
| 133 |
} else {
|
| 134 |
-
// Fallback to environment variables
|
| 135 |
console.log('OpenClaw: Using API keys from environment');
|
| 136 |
providersToTry = Object.keys(PROVIDERS);
|
| 137 |
apiKeys = PROVIDERS;
|
|
@@ -158,7 +227,7 @@ app.post("/api/market-research", async (req, res) => {
|
|
| 158 |
};
|
| 159 |
|
| 160 |
try {
|
| 161 |
-
console.log(`OpenClaw: Trying provider ${p}
|
| 162 |
const result = await runOpenClaw(env, { keyword });
|
| 163 |
console.log('OpenClaw: Success with provider', p);
|
| 164 |
return res.json(result);
|
|
@@ -179,20 +248,21 @@ app.post("/api/market-research", async (req, res) => {
|
|
| 179 |
});
|
| 180 |
|
| 181 |
/* ===============================
|
| 182 |
-
6. EXECUTION + JSON PARSE
|
| 183 |
-
|
| 184 |
|
| 185 |
function runOpenClaw(env, payload) {
|
| 186 |
return new Promise((resolve, reject) => {
|
| 187 |
-
//
|
| 188 |
const proc = spawn(process.execPath, ["src/index.js"], {
|
| 189 |
-
cwd:
|
| 190 |
env
|
| 191 |
});
|
| 192 |
|
| 193 |
let stdout = "";
|
| 194 |
let stderr = "";
|
| 195 |
|
|
|
|
| 196 |
proc.on("error", err => {
|
| 197 |
console.error('OpenClaw: Spawn error:', err);
|
| 198 |
reject(err);
|
|
@@ -227,12 +297,13 @@ function runOpenClaw(env, payload) {
|
|
| 227 |
}
|
| 228 |
});
|
| 229 |
|
| 230 |
-
//
|
| 231 |
proc.stdin.write(JSON.stringify(payload));
|
| 232 |
proc.stdin.end();
|
| 233 |
});
|
| 234 |
}
|
| 235 |
|
|
|
|
| 236 |
function isRateLimit(err) {
|
| 237 |
const msg = err.message?.toLowerCase() || "";
|
| 238 |
return (
|
|
@@ -243,13 +314,14 @@ function isRateLimit(err) {
|
|
| 243 |
);
|
| 244 |
}
|
| 245 |
|
|
|
|
| 246 |
/* ===============================
|
| 247 |
-
7. START
|
| 248 |
=============================== */
|
| 249 |
|
| 250 |
-
const PORT = process.env.PORT || 7860;
|
| 251 |
app.listen(PORT, "0.0.0.0", () => {
|
| 252 |
console.log(`π OpenClaw Agent Gateway running on port ${PORT}`);
|
| 253 |
console.log(`π‘ Endpoint: /api/market-research`);
|
| 254 |
-
console.log(`π
|
| 255 |
-
});
|
|
|
|
| 1 |
import express from "express";
|
| 2 |
import { spawn } from "child_process";
|
| 3 |
import dotenv from "dotenv";
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
console.log('OpenClaw: Starting server...');
|
| 6 |
+
console.log('OpenClaw: Node version:', process.version);
|
| 7 |
+
console.log('OpenClaw: Current directory:', process.cwd());
|
| 8 |
|
| 9 |
+
try {
|
| 10 |
+
dotenv.config();
|
| 11 |
+
console.log('OpenClaw: Environment loaded');
|
| 12 |
+
} catch (err) {
|
| 13 |
+
console.error('OpenClaw: Failed to load environment:', err.message);
|
| 14 |
+
}
|
| 15 |
|
| 16 |
const app = express();
|
| 17 |
app.use(express.json());
|
| 18 |
|
| 19 |
/* ===============================
|
| 20 |
1. BASIC AUTH
|
| 21 |
+
================================ */
|
| 22 |
|
| 23 |
const GATE_KEY = process.env.OPENCLAW_GATE_KEY;
|
| 24 |
|
|
|
|
| 32 |
|
| 33 |
/* ===============================
|
| 34 |
2. RATE LIMITING (IP-based)
|
| 35 |
+
================================ */
|
| 36 |
|
| 37 |
const RATE_LIMIT = 30; // requests
|
| 38 |
const WINDOW_MS = 60_000;
|
|
|
|
| 59 |
|
| 60 |
/* ===============================
|
| 61 |
3. LOAD KEY POOLS
|
| 62 |
+
================================ */
|
| 63 |
|
| 64 |
function loadPool(prefix) {
|
| 65 |
const keys = Object.keys(process.env)
|
|
|
|
| 85 |
|
| 86 |
/* ===============================
|
| 87 |
4. TASK ROUTING
|
| 88 |
+
================================ */
|
| 89 |
|
| 90 |
const TASKS = new Set([
|
| 91 |
"market_research",
|
|
|
|
| 95 |
|
| 96 |
/* ===============================
|
| 97 |
5. RUN AGENT
|
| 98 |
+
================================ */
|
| 99 |
app.use((req, res, next) => {
|
| 100 |
if (req.method === "POST" && !req.is("application/json")) {
|
| 101 |
return res.status(400).json({ error: "JSON body required" });
|
|
|
|
| 107 |
res.json({
|
| 108 |
status: "OpenClaw running on HF Space",
|
| 109 |
service: "market_research_agent",
|
| 110 |
+
endpoints: {
|
| 111 |
+
market_research: "POST /api/market-research",
|
| 112 |
+
health: "GET /health"
|
| 113 |
+
},
|
| 114 |
timestamp: new Date().toISOString()
|
| 115 |
});
|
| 116 |
});
|
| 117 |
|
| 118 |
+
// Simple health check endpoint
|
| 119 |
+
app.get("/health", (req, res) => {
|
| 120 |
+
res.json({
|
| 121 |
+
status: "healthy",
|
| 122 |
+
timestamp: new Date().toISOString(),
|
| 123 |
+
uptime: process.uptime()
|
| 124 |
+
});
|
| 125 |
+
});
|
| 126 |
+
|
| 127 |
+
app.post("/run", async (req, res) => {
|
| 128 |
+
console.log('OpenClaw: Received request:', {
|
| 129 |
+
task: req.body.task,
|
| 130 |
+
keyword: req.body.keyword,
|
| 131 |
+
timestamp: new Date().toISOString()
|
| 132 |
+
});
|
| 133 |
+
|
| 134 |
+
const { task = "market_research", provider, model, ...payload } = req.body;
|
| 135 |
+
|
| 136 |
+
if (!TASKS.has(task)) {
|
| 137 |
+
return res.status(400).json({ error: "Unknown task" });
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
const providersToTry = provider
|
| 141 |
+
? [provider, ...Object.keys(PROVIDERS).filter(p => p !== provider)]
|
| 142 |
+
: Object.keys(PROVIDERS);
|
| 143 |
+
|
| 144 |
+
let lastError;
|
| 145 |
+
|
| 146 |
+
for (const p of providersToTry) {
|
| 147 |
+
const pool = PROVIDERS[p];
|
| 148 |
+
if (!pool || pool.length === 0) continue;
|
| 149 |
+
|
| 150 |
+
for (let i = 0; i < pool.length; i++) {
|
| 151 |
+
const apiKey = randomKey(pool);
|
| 152 |
+
|
| 153 |
+
const env = {
|
| 154 |
+
...process.env,
|
| 155 |
+
OPENCLAW_PROVIDER: p,
|
| 156 |
+
OPENCLAW_MODEL: model || "",
|
| 157 |
+
OPENCLAW_API_KEY: apiKey,
|
| 158 |
+
OPENCLAW_TASK: task,
|
| 159 |
+
OPENCLAW_TIMEOUT: "180000"
|
| 160 |
+
};
|
| 161 |
+
|
| 162 |
+
try {
|
| 163 |
+
const result = await runOpenClaw(env, payload);
|
| 164 |
+
return res.json(result);
|
| 165 |
+
} catch (err) {
|
| 166 |
+
lastError = err;
|
| 167 |
+
if (!isRateLimit(err)) break;
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
res.status(500).json({
|
| 173 |
+
error: "All providers failed",
|
| 174 |
+
details: lastError?.message,
|
| 175 |
+
keyword: req.body.keyword,
|
| 176 |
+
timestamp: new Date().toISOString()
|
| 177 |
+
});
|
| 178 |
+
});
|
| 179 |
+
|
| 180 |
+
// Add specific market research endpoint for n8n compatibility
|
| 181 |
app.post("/api/market-research", async (req, res) => {
|
| 182 |
+
console.log('OpenClaw: Market research request:', {
|
| 183 |
keyword: req.body.keyword,
|
| 184 |
timestamp: new Date().toISOString()
|
| 185 |
});
|
|
|
|
| 200 |
apiKeys[provider] = [api_key];
|
| 201 |
providersToTry = [provider];
|
| 202 |
} else {
|
| 203 |
+
// Fallback to environment variables (for local testing)
|
| 204 |
console.log('OpenClaw: Using API keys from environment');
|
| 205 |
providersToTry = Object.keys(PROVIDERS);
|
| 206 |
apiKeys = PROVIDERS;
|
|
|
|
| 227 |
};
|
| 228 |
|
| 229 |
try {
|
| 230 |
+
console.log(`OpenClaw: Trying provider ${p} with key ${apiKey.substring(0, 10)}...`);
|
| 231 |
const result = await runOpenClaw(env, { keyword });
|
| 232 |
console.log('OpenClaw: Success with provider', p);
|
| 233 |
return res.json(result);
|
|
|
|
| 248 |
});
|
| 249 |
|
| 250 |
/* ===============================
|
| 251 |
+
6. EXECUTION + JSON PARSE
|
| 252 |
+
================================ */
|
| 253 |
|
| 254 |
function runOpenClaw(env, payload) {
|
| 255 |
return new Promise((resolve, reject) => {
|
| 256 |
+
// For HF Space, use current directory instead of /app
|
| 257 |
const proc = spawn(process.execPath, ["src/index.js"], {
|
| 258 |
+
cwd: process.cwd(), // Use current working directory
|
| 259 |
env
|
| 260 |
});
|
| 261 |
|
| 262 |
let stdout = "";
|
| 263 |
let stderr = "";
|
| 264 |
|
| 265 |
+
// CRITICAL: handle spawn errors
|
| 266 |
proc.on("error", err => {
|
| 267 |
console.error('OpenClaw: Spawn error:', err);
|
| 268 |
reject(err);
|
|
|
|
| 297 |
}
|
| 298 |
});
|
| 299 |
|
| 300 |
+
// SEND INPUT TO AGENT
|
| 301 |
proc.stdin.write(JSON.stringify(payload));
|
| 302 |
proc.stdin.end();
|
| 303 |
});
|
| 304 |
}
|
| 305 |
|
| 306 |
+
|
| 307 |
function isRateLimit(err) {
|
| 308 |
const msg = err.message?.toLowerCase() || "";
|
| 309 |
return (
|
|
|
|
| 314 |
);
|
| 315 |
}
|
| 316 |
|
| 317 |
+
|
| 318 |
/* ===============================
|
| 319 |
+
7. START (HF Space compatible)
|
| 320 |
=============================== */
|
| 321 |
|
| 322 |
+
const PORT = process.env.PORT || 7860; // HF Space uses 7860
|
| 323 |
app.listen(PORT, "0.0.0.0", () => {
|
| 324 |
console.log(`π OpenClaw Agent Gateway running on port ${PORT}`);
|
| 325 |
console.log(`π‘ Endpoint: /api/market-research`);
|
| 326 |
+
console.log(`π API keys from: ${Object.keys(PROVIDERS).filter(p => PROVIDERS[p].length > 0).join(', ') || 'requests only'}`);
|
| 327 |
+
});
|