-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
327 lines (276 loc) · 9.29 KB
/
server.js
File metadata and controls
327 lines (276 loc) · 9.29 KB
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
const http = require('http');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const PORT = 4000;
const WORKSPACE = '/workspace';
// Store running tasks
const tasks = new Map();
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`);
// CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// Health check / ping - used by Cloudflare to check container is ready
if (url.pathname === '/health' || url.pathname === '/ping') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', workspace: WORKSPACE, tasks: tasks.size }));
return;
}
// Start a task (async - returns immediately with task ID)
if (url.pathname === '/run' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const { prompt, workdir, apiKey, agentId } = JSON.parse(body);
if (!prompt) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'prompt required' }));
return;
}
const taskId = agentId || `task-${Date.now()}`;
const cwd = workdir ? path.join(WORKSPACE, workdir) : WORKSPACE;
// Ensure directory exists
if (!fs.existsSync(cwd)) {
fs.mkdirSync(cwd, { recursive: true });
}
// Create task entry
tasks.set(taskId, {
status: 'running',
startTime: Date.now(),
stdout: '',
stderr: '',
exitCode: null,
cwd,
});
// Run Claude Code in background
const env = { ...process.env };
if (apiKey) env.ANTHROPIC_API_KEY = apiKey;
const claude = spawn('claude', [
'--dangerously-skip-permissions',
'--output-format', 'json',
'-p', prompt
], {
cwd,
env,
timeout: 600000 // 10 minute timeout
});
const task = tasks.get(taskId);
claude.stdout.on('data', data => {
task.stdout += data;
});
claude.stderr.on('data', data => {
task.stderr += data;
});
claude.on('close', code => {
task.status = code === 0 ? 'completed' : 'failed';
task.exitCode = code;
task.endTime = Date.now();
// Parse result
try {
task.result = JSON.parse(task.stdout);
} catch {
task.result = { raw: task.stdout };
}
});
claude.on('error', err => {
task.status = 'failed';
task.error = err.message;
task.endTime = Date.now();
});
// Return task ID immediately
res.writeHead(202, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
taskId,
status: 'running',
message: 'Task started. Poll /status/{taskId} for results.'
}));
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
// Check task status
const statusMatch = url.pathname.match(/^\/status\/(.+)$/);
if (statusMatch) {
const taskId = statusMatch[1];
const task = tasks.get(taskId);
if (!task) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Task not found' }));
return;
}
const response = {
taskId,
status: task.status,
startTime: task.startTime,
elapsed: Date.now() - task.startTime,
};
if (task.status === 'completed' || task.status === 'failed') {
response.endTime = task.endTime;
response.exitCode = task.exitCode;
response.result = task.result;
response.stderr = task.stderr || undefined;
response.error = task.error || undefined;
// Clean up after retrieval
tasks.delete(taskId);
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(response));
return;
}
// Run sync (for simple/quick tasks) - keeps old behavior
if (url.pathname === '/run-sync' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const { prompt, workdir, apiKey } = JSON.parse(body);
if (!prompt) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'prompt required' }));
return;
}
const cwd = workdir ? path.join(WORKSPACE, workdir) : WORKSPACE;
if (!fs.existsSync(cwd)) {
fs.mkdirSync(cwd, { recursive: true });
}
const env = { ...process.env };
if (apiKey) env.ANTHROPIC_API_KEY = apiKey;
const claude = spawn('claude', [
'--dangerously-skip-permissions',
'--output-format', 'json',
'-p', prompt
], {
cwd,
env,
timeout: 300000
});
let stdout = '';
let stderr = '';
claude.stdout.on('data', data => stdout += data);
claude.stderr.on('data', data => stderr += data);
claude.on('close', code => {
res.writeHead(200, { 'Content-Type': 'application/json' });
let result;
try {
result = JSON.parse(stdout);
} catch {
result = { raw: stdout };
}
res.end(JSON.stringify({
exitCode: code,
result,
stderr: stderr || undefined,
workdir: cwd
}));
});
claude.on('error', err => {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
});
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
// List workspace files
if (url.pathname === '/files') {
const dir = url.searchParams.get('dir') || '';
const targetDir = path.join(WORKSPACE, dir);
try {
const files = fs.readdirSync(targetDir, { withFileTypes: true });
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
path: targetDir,
files: files.map(f => ({
name: f.name,
type: f.isDirectory() ? 'directory' : 'file'
}))
}));
} catch (err) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
return;
}
// Read a file
if (url.pathname === '/read') {
const file = url.searchParams.get('file');
if (!file) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'file param required' }));
return;
}
const filePath = path.join(WORKSPACE, file);
try {
const content = fs.readFileSync(filePath, 'utf-8');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ path: filePath, content }));
} catch (err) {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
return;
}
// Clone a repo
if (url.pathname === '/clone' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
try {
const { repo, dir } = JSON.parse(body);
const targetDir = dir || repo.split('/').pop().replace('.git', '');
const fullPath = path.join(WORKSPACE, targetDir);
const git = spawn('git', ['clone', '--depth', '1', repo, fullPath]);
let stderr = '';
git.stderr.on('data', data => stderr += data);
git.on('close', code => {
res.writeHead(code === 0 ? 200 : 500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
success: code === 0,
path: fullPath,
error: code !== 0 ? stderr : undefined
}));
});
} catch (err) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: err.message }));
}
});
return;
}
// List all tasks
if (url.pathname === '/tasks') {
const taskList = [];
for (const [id, task] of tasks) {
taskList.push({
taskId: id,
status: task.status,
startTime: task.startTime,
elapsed: Date.now() - task.startTime,
});
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ tasks: taskList }));
return;
}
// 404
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'not found' }));
});
server.listen(PORT, () => {
console.log(`Claude Code container server running on port ${PORT}`);
console.log(`Workspace: ${WORKSPACE}`);
});