Repository navigation
Expand file tree
/
Copy pathcodeforge-remote-server.mjs
More file actions
1062 lines (944 loc) · 37.6 KB
/
Copy pathcodeforge-remote-server.mjs
File metadata and controls
1062 lines (944 loc) · 37.6 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { existsSync, statSync, createReadStream, mkdirSync } from 'node:fs';
import { randomUUID, randomInt, timingSafeEqual } from 'node:crypto';
import { networkInterfaces, hostname } from 'node:os';
import path, { extname, join } from 'node:path';
import dgram from 'node:dgram';
// "ws" (WebSocket sync) and "node-pty" (local shells) are optional at start: a fresh Linux
// server that only ran the setup script usually has plain Node.js and no npm packages yet.
// Missing pieces are reported instead of stopping the process, so the API, pairing mode and
// file/media routes keep working.
let webSocketModule = null;
try {
webSocketModule = await import('ws');
} catch {
console.warn('Hinweis: npm-Paket "ws" fehlt - WebSocket-Sync ist deaktiviert (npm install ws).');
}
let ptyModule = null;
async function loadPty() {
if (!ptyModule) {
try {
ptyModule = (await import('node-pty')).default;
} catch {
throw new Error('node-pty ist nicht installiert. Auf dem Server nachinstallieren: npm install node-pty');
}
}
return ptyModule;
}
let pairingMode = false;
let pairingCode = '';
let pairingBroadcastInterval = null;
let udpSocket = null;
let udpEaccesLogged = false;
const PAIRING_FAIL_LIMIT = 5;
const PAIRING_BLOCK_MS = 30_000;
const pairingFailures = new Map();
function getHostname() { return hostname(); }
const PORT = Number(process.env.PORT || process.env.CODEFORGE_PORT || 8787);
const HOST = process.env.HOST || process.env.CODEFORGE_HOST || '0.0.0.0';
const TOKEN = process.env.CODEFORGE_TOKEN || '';
const PROJECT_PATH = process.env.CODEFORGE_PROJECT_PATH || process.cwd();
const PAIRING_PORT = Number(process.env.CODEFORGE_PAIRING_PORT || 8789);
const PAIRING_AUTO_STOP_MINUTES = Number(process.env.CODEFORGE_PAIRING_TIMEOUT_MINUTES || 5);
const MAX_PROMPT_CHARS = Number(process.env.CODEFORGE_MAX_PROMPT_CHARS || 100_000);
const userHome = process.env.USERPROFILE || process.env.HOME || '';
const providers = {
antigravity: {
command: 'agy',
candidates: [
'agy',
join(userHome, 'AppData/Local/agy/bin/agy.exe').replace(/\\/g, '/'),
'/root/.local/bin/agy',
'/usr/local/bin/agy',
'/usr/bin/agy'
]
},
openai: {
command: 'codex',
candidates: [
'codex',
join(userHome, 'AppData/Local/Programs/OpenAI/Codex/bin/codex.exe').replace(/\\/g, '/'),
'/root/.local/bin/codex',
'/usr/local/bin/codex',
'/usr/bin/codex'
]
},
anthropic: {
command: 'claude',
candidates: [
'claude',
'/root/.local/bin/claude',
'/usr/local/bin/claude',
'/usr/bin/claude'
]
},
cursor: {
command: 'cursor-agent',
candidates: [
'cursor-agent',
'agent',
'/root/.local/bin/cursor-agent',
'/usr/local/bin/cursor-agent'
]
},
opencode: {
command: 'opencode',
candidates: [
'opencode',
'/root/.local/bin/opencode',
'/usr/local/bin/opencode',
'/usr/bin/opencode'
]
},
freebuff: {
command: 'freebuff',
candidates: [
'freebuff',
'/root/.local/bin/freebuff',
'/usr/local/bin/freebuff',
'/usr/bin/freebuff'
]
},
};
function resolveCommand(provider) {
for (const candidate of provider.candidates || [provider.command]) {
if (candidate.includes('/') && existsSync(candidate)) return candidate;
}
return provider.command;
}
function getLocalIp() {
return Object.values(networkInterfaces())
.flat()
.filter((iface) => iface && !iface.internal && iface.family === 'IPv4')
.map((iface) => iface.address)[0] || HOST;
}
function getEffectivePublicIp() {
return process.env.CODEFORGE_PUBLIC_IP || getLocalIp();
}
function json(res, status, payload) {
res.writeHead(status, {
'content-type': 'application/json; charset=utf-8',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'authorization, content-type',
'access-control-allow-methods': 'GET, POST, OPTIONS',
});
res.end(JSON.stringify(payload));
}
function bearerToken(req) {
const match = /^Bearer (.+)$/i.exec(req.headers.authorization || '');
return match ? match[1].trim() : '';
}
function equalsSecret(value, expected) {
if (typeof value !== 'string' || typeof expected !== 'string' || !expected) return false;
const actualBytes = Buffer.from(value);
const expectedBytes = Buffer.from(expected);
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
}
function tokenMatches(value) {
return equalsSecret(value, TOKEN);
}
function isAuthorized(req) {
return tokenMatches(bearerToken(req));
}
// Starting and stopping pairing changes who may connect, so only the owner (who has the API
// token) may do it. The setup scripts send the token; no loopback exception, so a local user
// without the token cannot mint themselves a session either.
function isTrustedRequest(req) {
return isAuthorized(req);
}
function requestIp(req) {
return req.socket.remoteAddress || 'unknown';
}
// The pairing code is shown to the local network only. On a server with a public address an
// anonymous visitor must not be able to read it out of /discover and take the session over.
function isPrivateAddress(address) {
const value = String(address || '').replace(/^::ffff:/, '');
if (!value) return false;
if (value === '::1' || /^(fe80|fc|fd)/i.test(value)) return true;
const parts = value.split('.').map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false;
return (
parts[0] === 10 ||
parts[0] === 127 ||
(parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
(parts[0] === 169 && parts[1] === 254)
);
}
function pairingBlockSeconds(req) {
const entry = pairingFailures.get(requestIp(req));
if (!entry || entry.blockedUntil <= Date.now()) return 0;
return Math.ceil((entry.blockedUntil - Date.now()) / 1000);
}
function registerPairingFailure(req) {
const ip = requestIp(req);
const entry = pairingFailures.get(ip) || { count: 0, blockedUntil: 0 };
entry.count += 1;
if (entry.count >= PAIRING_FAIL_LIMIT) {
entry.count = 0;
entry.blockedUntil = Date.now() + PAIRING_BLOCK_MS;
}
pairingFailures.set(ip, entry);
// Keep the map bounded, e.g. when many clients try a wrong code.
if (pairingFailures.size > 500) {
for (const [key, value] of pairingFailures) {
if (value.blockedUntil <= Date.now() && value.count === 0) pairingFailures.delete(key);
}
}
}
function clearPairingFailures(req) {
pairingFailures.delete(requestIp(req));
}
function unauthorized(res) {
return json(res, 401, { ok: false, error: 'Unauthorized.' });
}
function readBody(req) {
return new Promise((resolve, reject) => {
let body = '';
req.setEncoding('utf8');
req.on('data', (chunk) => {
body += chunk;
if (body.length > MAX_PROMPT_CHARS + 20_000) {
reject(new Error('Request body too large.'));
req.destroy();
}
});
req.on('end', () => resolve(body));
req.on('error', reject);
});
}
// ── Pairing mode ──────────────────────────────────────────────
function generatePairingCode() {
return String(randomInt(1000, 9999));
}
function startPairingBroadcast() {
if (pairingMode) return; // Already active
pairingMode = true;
pairingCode = generatePairingCode();
const localIp = getLocalIp();
const serverName = getHostname();
// Create UDP socket for broadcasting
udpSocket = dgram.createSocket('udp4');
udpSocket.bind(PAIRING_PORT, () => {
udpSocket.setBroadcast(true);
const easySetupUrl = `http://${getEffectivePublicIp()}:${PORT}/pair?code=${pairingCode}`;
console.log('');
console.log(' ╔══════════════════════════════════════════════════════════╗');
console.log(' ║ 📱 EASY SETUP – In die App einfügen: ║');
console.log(' ║ ║');
console.log(` ║ ${easySetupUrl} ║`);
console.log(' ║ ║');
console.log(' ║ FancyCode-App → Verbinden → Einfügen → FERTIG! ✨ ║');
console.log(' ╚══════════════════════════════════════════════════════════╝');
console.log('');
console.log(` 🔢 Kopplungscode: ${pairingCode} ⏱️ ${PAIRING_AUTO_STOP_MINUTES} Min gültig`);
console.log(` 📡 UDP-Broadcast auf Port ${PAIRING_PORT} (LAN-Discovery)`);
});
const broadcastMessage = () => {
if (!pairingMode || !udpSocket) return;
const payload = JSON.stringify({
type: 'codeforge-pairing',
service: 'codeforge-remote',
name: serverName,
ip: localIp,
port: PORT,
pairingCode,
tokenRequired: Boolean(TOKEN),
version: '2.4.3',
providers: Object.keys(providers),
timestamp: Date.now(),
});
const buffer = Buffer.from(payload, 'utf-8');
udpSocket.send(buffer, 0, buffer.length, PAIRING_PORT, '255.255.255.255', (err) => {
if (err) {
if (err.code === 'EACCES' && !udpEaccesLogged) {
udpEaccesLogged = true;
console.log(' ⚠️ UDP-Broadcast nicht möglich (keine root-Rechte). Kopplung funktioniert trotzdem via HTTP.');
}
}
});
};
// Send immediately, then every 2 seconds
broadcastMessage();
pairingBroadcastInterval = setInterval(broadcastMessage, 2000);
pairingBroadcastInterval.unref();
// Auto-stop after configured minutes (default 5)
const timeoutMs = (PAIRING_AUTO_STOP_MINUTES || 5) * 60 * 1000;
setTimeout(() => { if (pairingMode) stopPairingBroadcast(); }, timeoutMs).unref();
}
function stopPairingBroadcast() {
pairingMode = false;
pairingCode = '';
if (pairingBroadcastInterval) {
clearInterval(pairingBroadcastInterval);
pairingBroadcastInterval = null;
}
if (udpSocket) {
try { udpSocket.close(); } catch {}
udpSocket = null;
}
console.log('🔗 Kopplungsmodus beendet.');
}
// The code is only included while pairing is active; it is also broadcast over UDP on the LAN,
// which is how the app's "same Wi-Fi" wizard finds the server without an existing token.
function getPairingQRData(includeCode = true) {
const publicIp = getEffectivePublicIp();
const data = {
serverName: getHostname(),
serverIp: publicIp,
serverPort: PORT,
tokenRequired: Boolean(TOKEN),
};
if (!includeCode) return data;
const url = `http://${publicIp}:${PORT}/pair?code=${pairingCode}`;
return { ...data, url, qrContent: url, pairingCode };
}
// ── Pairing HTTP endpoint ─────────────────────────────────────
async function handlePairing(req, res) {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
// GET /pair?code=XXXX – discovery for the app; verifies a code when one is passed. The token is
// only handed out by POST /pair/verify, so a code cannot be turned into a session via a URL.
if (req.method === 'GET') {
const code = url.searchParams.get('code');
if (!pairingMode) {
return json(res, 200, { ...getPairingQRData(false), pairingActive: false });
}
if (code) {
const wait = pairingBlockSeconds(req);
if (wait) {
return json(res, 429, { ok: false, error: `Zu viele Fehlversuche. Bitte warte ${wait} Sekunden.` });
}
if (equalsSecret(code, pairingCode)) {
clearPairingFailures(req);
return json(res, 200, {
ok: true,
paired: true,
serverUrl: `http://${getEffectivePublicIp()}:${PORT}`,
providers: Object.keys(providers),
message: 'Code korrekt! Die App verbindet sich jetzt.',
});
}
registerPairingFailure(req);
const nowWait = pairingBlockSeconds(req);
if (nowWait) {
return json(res, 429, { ok: false, error: `Zu viele Fehlversuche. ${nowWait} Sekunden Sperre.` });
}
return json(res, 403, { ok: false, error: 'Falscher Kopplungscode.' });
}
return json(res, 200, { ...getPairingQRData(isPrivateAddress(req.socket.remoteAddress)), pairingActive: true });
}
// POST /pair/start – start pairing mode (owner or local setup script only)
if (req.method === 'POST' && url.pathname === '/pair/start') {
if (!isTrustedRequest(req)) return unauthorized(res);
if (pairingMode) stopPairingBroadcast();
startPairingBroadcast();
return json(res, 200, {
ok: true,
pairingCode,
...getPairingQRData(),
message: 'Kopplungsmodus gestartet. Der Server sendet nun UDP-Broadcasts.',
});
}
// POST /pair/stop – stop pairing mode (owner or local setup script only)
if (req.method === 'POST' && url.pathname === '/pair/stop') {
if (!isTrustedRequest(req)) return unauthorized(res);
stopPairingBroadcast();
return json(res, 200, { ok: true, message: 'Kopplungsmodus beendet.' });
}
// POST /pair/verify – verify code and return connection config (rate-limited)
if (req.method === 'POST' && url.pathname === '/pair/verify') {
const wait = pairingBlockSeconds(req);
if (wait) {
return json(res, 429, { ok: false, error: `Zu viele Fehlversuche. Bitte warte ${wait} Sekunden.` });
}
let body;
try { body = JSON.parse(await readBody(req)); } catch {
return json(res, 400, { ok: false, error: 'Invalid JSON.' });
}
if (!pairingMode) {
return json(res, 400, { ok: false, error: 'Kopplungsmodus ist nicht aktiv.' });
}
if (!equalsSecret(String(body.code || ''), pairingCode)) {
registerPairingFailure(req);
const nowWait = pairingBlockSeconds(req);
if (nowWait) {
return json(res, 429, { ok: false, error: `Zu viele Fehlversuche. ${nowWait} Sekunden Sperre.` });
}
return json(res, 403, { ok: false, error: 'Falscher Kopplungscode.' });
}
clearPairingFailures(req);
return json(res, 200, {
ok: true,
serverUrl: `http://${getEffectivePublicIp()}:${PORT}`,
token: TOKEN,
pairingCode,
serverName: getHostname(),
providers: Object.keys(providers),
});
}
return json(res, 404, { ok: false, error: 'Pairing endpoint not found.' });
}
// ── Existing handlers ─────────────────────────────────────────
function accessToCodexSandbox(access) {
if (access === 'read-only') return 'read-only';
if (access === 'full') return 'danger-full-access';
return 'workspace-write';
}
function normalizeReasoningEffort(value) {
return ['low', 'medium', 'high'].includes(value) ? value : 'medium';
}
function buildPrompt(systemPrompt, prompt, access, projectPath) {
const accessInstruction =
access === 'read-only'
? 'WICHTIG: Arbeite ausschliesslich lesend. Veraendere keine Dateien und fuehre keine destruktiven Befehle aus.'
: access === 'workspace-write'
? `WICHTIG: Veraendere nur Dateien innerhalb dieses Projektordners: ${projectPath}`
: 'Du darfst die fuer die Aufgabe erforderlichen Werkzeuge verwenden.';
const system = String(systemPrompt || '').trim();
return [accessInstruction, system ? `System-Prompt:\n${system}` : '', prompt].filter(Boolean).join('\n\n');
}
function accessToClaudeMode(access) {
if (access === 'read-only') return 'plan';
if (access === 'full') return 'bypassPermissions';
return 'auto';
}
function buildAgentCommand(providerId, model, prompt, access, projectPath, reasoningEffort) {
const args = [];
let stdin = '';
if (providerId === 'antigravity') {
args.push('-p', prompt, '--model', model, '--dangerously-skip-permissions');
} else if (providerId === 'openai') {
args.push(
'exec',
'-',
'--model',
model,
'--cd',
projectPath,
'--color',
'never',
'--skip-git-repo-check',
'--config',
`model_reasoning_effort="${normalizeReasoningEffort(reasoningEffort)}"`,
'--sandbox',
accessToCodexSandbox(access),
);
if (access === 'full') args.push('--dangerously-bypass-approvals-and-sandbox');
stdin = prompt;
} else if (providerId === 'anthropic') {
args.push('-p', '--model', model, '--output-format', 'text', '--permission-mode', accessToClaudeMode(access));
if (access === 'full') args.push('--dangerously-skip-permissions');
stdin = prompt;
} else if (providerId === 'cursor') {
args.push('-p', prompt, '--output-format', 'text');
if (model && model !== 'default') args.push('--model', model);
} else if (providerId === 'opencode') {
args.push('run', '--dir', projectPath);
if (model && model !== 'default') args.push('--model', model);
if (access === 'full') args.push('--dangerously-skip-permissions');
args.push(prompt);
} else if (providerId === 'freebuff') {
args.push('-p', prompt);
if (model && model !== 'default') args.push('--model', model);
}
return { args, stdin };
}
function runCapture(command, args, options = {}) {
return new Promise((resolve) => {
const isWin = process.platform === 'win32';
const child = spawn(command, args, {
cwd: options.cwd,
env: {
...(!isWin && {
HOME: process.env.HOME || '/root',
USER: process.env.USER || 'root',
}),
...process.env,
FORCE_COLOR: '0',
NO_COLOR: '1'
},
shell: isWin,
stdio: ['pipe', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
stdout += chunk;
options.onOutput?.(chunk, 'stdout');
});
child.stderr.on('data', (chunk) => {
stderr += chunk;
options.onOutput?.(chunk, 'stderr');
});
child.on('error', (error) => resolve({ ok: false, stdout, stderr, error: error.message, exitCode: -1 }));
child.on('close', (exitCode) => {
resolve({
ok: exitCode === 0,
stdout,
stderr,
error: exitCode === 0 ? '' : stderr.trim() || `Process exited with code ${exitCode}.`,
exitCode: exitCode ?? -1,
});
});
if (options.stdin) child.stdin.write(options.stdin);
child.stdin.end();
setTimeout(() => {
if (!child.killed) child.kill('SIGTERM');
}, options.timeoutMs || 10 * 60 * 1000).unref();
});
}
async function handleHealth(req, res) {
if (!isAuthorized(req)) return unauthorized(res);
json(res, 200, {
ok: true,
name: 'FancyCode Remote Server',
providers: Object.fromEntries(
Object.entries(providers).map(([id, provider]) => [id, { command: resolveCommand(provider) }]),
),
tokenConfigured: Boolean(TOKEN),
});
}
async function handleRun(req, res) {
if (!isAuthorized(req)) return unauthorized(res);
let input;
try {
input = JSON.parse(await readBody(req));
} catch (error) {
return json(res, 400, { ok: false, error: error.message || 'Invalid JSON.' });
}
const providerId = String(input.provider || 'openai');
const provider = providers[providerId];
const prompt = String(input.prompt || '').trim();
const projectPath = String(input.projectPath || '').trim();
const access = ['read-only', 'workspace-write', 'full'].includes(input.access) ? input.access : 'workspace-write';
const model = String(input.model || (providerId === 'openai' ? 'gpt-5.5' : 'default'));
const reasoningEffort = normalizeReasoningEffort(input.reasoningEffort);
const outputLimit = Math.max(1000, Math.min(50_000, Number(input.outputLimit || 12_000)));
const wantsStream = input.stream === true || /\bapplication\/x-ndjson\b/i.test(String(req.headers.accept || ''));
if (!provider) return json(res, 400, { ok: false, error: 'Unknown provider.' });
if (!prompt || prompt.length > MAX_PROMPT_CHARS) return json(res, 400, { ok: false, error: 'Prompt is empty or too large.' });
let effectiveProjectPath = projectPath;
if (!projectPath || !existsSync(effectiveProjectPath) || !statSync(effectiveProjectPath).isDirectory()) {
const isWin = process.platform === 'win32';
const userHome = process.env.USERPROFILE || process.env.HOME || '';
if (isWin) {
if (projectPath.startsWith('/root/') || projectPath === '/root/codeforge-project' || projectPath.startsWith('~/')) {
const docPath = path.join(userHome, 'OneDrive/Dokumente/FancyCode/Ohne Projekt');
const docPathAlt = path.join(userHome, 'Documents/FancyCode/Ohne Projekt');
if (existsSync(docPath)) {
effectiveProjectPath = docPath;
} else if (existsSync(docPathAlt)) {
effectiveProjectPath = docPathAlt;
} else {
try {
mkdirSync(docPath, { recursive: true });
effectiveProjectPath = docPath;
} catch (_) {
effectiveProjectPath = userHome || process.cwd();
}
}
} else {
try {
mkdirSync(projectPath, { recursive: true });
effectiveProjectPath = projectPath;
} catch (_) {
effectiveProjectPath = userHome || process.cwd();
}
}
} else {
try {
mkdirSync(projectPath, { recursive: true });
effectiveProjectPath = projectPath;
} catch (_) {
return json(res, 400, { ok: false, error: 'Project path does not exist on the server and could not be created.' });
}
}
}
const finalPrompt = buildPrompt(input.systemPrompt, prompt, access, effectiveProjectPath);
const { args, stdin } = buildAgentCommand(providerId, model, finalPrompt, access, effectiveProjectPath, reasoningEffort);
const startedAt = Date.now();
const runId = randomUUID();
if (wantsStream) {
const allowedOrigin = process.env.CODEFORGE_CORS_ORIGIN || '*';
res.writeHead(200, {
'content-type': 'application/x-ndjson; charset=utf-8',
'cache-control': 'no-cache',
'x-accel-buffering': 'no',
'access-control-allow-origin': allowedOrigin,
});
const writeEvent = (payload) => res.write(`${JSON.stringify(payload)}\n`);
writeEvent({ type: 'start', ok: true, runId, provider: providerId, startedAt });
const result = await runCapture(resolveCommand(provider), args, {
cwd: effectiveProjectPath,
stdin,
onOutput: (chunk, stream) => writeEvent({ type: 'output', runId, stream, chunk }),
});
const output = [result.stdout, result.stderr].filter(Boolean).join('\n').trim();
writeEvent({
type: 'done',
ok: result.ok,
runId,
exitCode: result.exitCode,
durationMs: Date.now() - startedAt,
output: output.slice(0, outputLimit),
truncated: output.length > outputLimit,
error: result.error,
});
res.end();
return;
}
const result = await runCapture(resolveCommand(provider), args, { cwd: effectiveProjectPath, stdin });
const output = [result.stdout, result.stderr].filter(Boolean).join('\n').trim();
json(res, result.ok ? 200 : 500, {
ok: result.ok,
runId,
exitCode: result.exitCode,
durationMs: Date.now() - startedAt,
output: output.slice(0, outputLimit),
truncated: output.length > outputLimit,
error: result.error,
});
}
async function handleUsage(req, res) {
if (!isAuthorized(req)) return unauthorized(res);
try {
const disk = await runCapture('df', ['-h', '/']);
const mem = await runCapture('free', ['-h']);
const cpu = await runCapture('uptime', []);
let agyOutput = 'Not available';
try {
const agyVersion = await runCapture('agy', ['--version']);
agyOutput = agyVersion.stdout.trim() || agyVersion.stderr.trim() || 'Not available';
} catch (_) {}
const usageOutput = [
`=== SYSTEM STATUS ===`,
cpu.stdout.trim(),
`\n=== MEMORY USAGE ===`,
mem.stdout.trim(),
`\n=== DISK SPACE ===`,
disk.stdout.trim(),
`\n=== ANTIGRAVITY VERSION ===`,
agyOutput
].join('\n');
json(res, 200, { ok: true, output: usageOutput });
} catch (error) {
json(res, 500, { ok: false, error: error.message });
}
}
const MEDIA_TYPES = {
'.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime', '.m4v': 'video/mp4',
'.ogg': 'video/ogg', '.ogv': 'video/ogg', '.avi': 'video/x-msvideo', '.mkv': 'video/x-matroska',
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif',
'.webp': 'image/webp', '.bmp': 'image/bmp', '.svg': 'image/svg+xml',
};
async function handleMedia(req, res) {
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
// <img>/<video> cannot send an Authorization header, so the token may also come as a query
// parameter. Without it this route would expose every readable file on the machine.
const token = bearerToken(req) || url.searchParams.get('token') || '';
if (!tokenMatches(token)) return unauthorized(res);
const filePath = url.searchParams.get('path');
if (!filePath) return json(res, 400, { ok: false, error: 'Missing path parameter.' });
const normalized = join('/', filePath.replace(/\\/g, '/').replace(/^~/, 'root'));
const resolved = join('/', normalized);
if (!existsSync(resolved) || !statSync(resolved).isFile()) {
return json(res, 404, { ok: false, error: 'File not found or not a file.' });
}
const ext = extname(resolved).toLowerCase();
const contentType = MEDIA_TYPES[ext];
if (!contentType) return json(res, 415, { ok: false, error: 'Unsupported media type.' });
res.writeHead(200, {
'content-type': contentType,
'cache-control': 'private, max-age=3600',
'content-length': statSync(resolved).size,
'x-content-type-options': 'nosniff',
'content-security-policy': "default-src 'none'; sandbox",
});
const stream = createReadStream(resolved);
stream.on('error', () => { if (!res.headersSent) { json(res, 500, { ok: false, error: 'Error reading file.' }); } else { res.destroy(); } });
stream.pipe(res);
}
const server = createServer((req, res) => {
if (req.method === 'OPTIONS') return json(res, 204, {});
const parsedUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const pathname = parsedUrl.pathname;
if (pathname.startsWith('/pair')) {
return handlePairing(req, res);
}
if (req.method === 'GET' && pathname === '/discover') {
return json(res, 200, {
ok: true,
service: 'codeforge-remote',
name: 'FancyCode Remote Server',
version: '2.5.0',
localIp: getLocalIp(),
port: PORT,
tokenRequired: Boolean(TOKEN),
providers: Object.keys(providers),
hostname: hostname(),
pairingActive: pairingMode,
...(pairingMode && isPrivateAddress(req.socket.remoteAddress) ? { pairingCode } : {}),
});
}
if (req.method === 'POST' && pathname === '/run') {
return handleRun(req, res);
}
if (req.method === 'GET' && pathname === '/media') {
return handleMedia(req, res);
}
if (req.method === 'GET' && pathname === '/usage') {
return handleUsage(req, res);
}
if (req.method === 'GET' && pathname === '/health') {
return handleHealth(req, res);
}
json(res, 404, { ok: false, error: 'Not found.' });
});
// -- WebSocket IPC Server (Sync Server) --
const wss = webSocketModule?.WebSocketServer ? new webSocketModule.WebSocketServer({ server }) : null;
const handlers = new Map();
const activeShells = new Map();
const activeTerminalProcesses = new Map();
function broadcast(msg, excludeWs = null, targetWs = null) {
if (!wss) return;
const data = JSON.stringify(msg);
for (const client of wss.clients) {
if (client !== excludeWs && client.readyState === 1 && (!targetWs || client === targetWs)) {
client.send(data);
}
}
}
wss?.on('connection', (ws, req) => {
const urlObj = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
const wsToken = urlObj.searchParams.get('token') || req.headers['authorization']?.replace(/^Bearer /i, '').trim() || '';
const isWsAuthorized = tokenMatches(wsToken);
if (!isWsAuthorized) {
console.log('WebSocket connection rejected (invalid token)');
ws.send(JSON.stringify({ type: 'error', error: 'Unauthorized' }));
ws.close(4001, 'Unauthorized');
return;
}
console.log('WebSocket connected');
ws.on('message', async (message) => {
try {
const msg = JSON.parse(message);
if (msg.type === 'ipc-call') {
const fn = handlers.get(msg.method);
if (fn) {
try {
const mockEvent = {
ws,
sender: {
send: (ch, data) => broadcast({ type: 'ipc-event', channel: ch, data }, null, ws)
}
};
const result = await fn(mockEvent, ...msg.args);
ws.send(JSON.stringify({ type: 'ipc-response', id: msg.id, result }));
} catch (err) {
ws.send(JSON.stringify({ type: 'ipc-response', id: msg.id, error: err.message }));
}
} else {
ws.send(JSON.stringify({ type: 'ipc-response', id: msg.id, error: `IPC handler not found for ${msg.method}` }));
}
}
} catch (err) {
console.error('WS Error:', err);
}
});
ws.on('close', () => {
if (ws.activeChatId && activeShells.has(ws.activeChatId)) {
const ptyProc = activeShells.get(ws.activeChatId);
try { ptyProc.kill(); } catch (e) {}
activeShells.delete(ws.activeChatId);
}
});
});
// IPC Handlers
handlers.set('system:status', async () => {
return Object.fromEntries(
Object.entries(providers).map(([id, provider]) => [id, { command: resolveCommand(provider) }])
);
});
handlers.set('shell:create', async (event, { chatId, cwd, shellType }) => {
if (event.ws) event.ws.activeChatId = chatId;
if (activeShells.has(chatId)) return;
const isWin = process.platform === 'win32';
const shell = isWin ? (shellType === 'powershell' ? 'powershell.exe' : (process.env.COMSPEC || 'cmd.exe')) : 'bash';
const args = isWin && shellType === 'powershell' ? ['-NoLogo'] : [];
let spawnCwd = PROJECT_PATH;
if (cwd && existsSync(cwd) && statSync(cwd).isDirectory()) spawnCwd = cwd;
const env = { ...process.env };
if (isWin) {
const agyPath = join(userHome, 'AppData/Local/agy/bin');
const pathKey = Object.keys(env).find(k => k.toUpperCase() === 'PATH') || 'PATH';
const paths = (env[pathKey] || '').split(';');
if (!paths.some(p => p.toLowerCase() === agyPath.toLowerCase())) {
paths.push(agyPath);
}
// Clean up case-variant duplicates of PATH on Windows to prevent node-pty launch errors
for (const k of Object.keys(env)) {
if (k.toUpperCase() === 'PATH') delete env[k];
}
env[pathKey] = paths.join(';');
}
try {
const pty = await loadPty();
const ptyProcess = pty.spawn(shell, args, {
name: 'xterm-color',
cols: 100,
rows: 30,
cwd: spawnCwd,
env: env,
useConpty: true
});
activeShells.set(chatId, ptyProcess);
ptyProcess.onData((data) => {
event.sender.send(`shell:output:${chatId}`, { type: 'stdout', text: data });
});
ptyProcess.onExit(({ exitCode }) => {
activeShells.delete(chatId);
event.sender.send(`shell:output:${chatId}`, { type: 'exit', code: exitCode });
});
} catch (err) {
event.sender.send(`shell:output:${chatId}`, { type: 'stderr', text: `PTY Spawn error: ${err.message}` });
}
});
handlers.set('shell:write', async (event, { chatId, text }) => {
const ptyProcess = activeShells.get(chatId);
if (ptyProcess) ptyProcess.write(text);
});
handlers.set('shell:resize', async (event, { chatId, cols, rows }) => {
const ptyProcess = activeShells.get(chatId);
if (ptyProcess) {
try { ptyProcess.resize(cols, rows); } catch (e) {}
}
});
handlers.set('shell:kill', async (event, chatId) => {
const ptyProcess = activeShells.get(chatId);
if (ptyProcess) {
ptyProcess.kill();
activeShells.delete(chatId);
}
});
handlers.set('terminal:run', async (event, { command, args, cwd }) => {
return new Promise((resolve) => {
const id = randomUUID();
let spawnCwd = PROJECT_PATH;
if (cwd && existsSync(cwd)) spawnCwd = cwd;
const child = spawn(command, args || [], {
cwd: spawnCwd,
env: process.env,
shell: true
});
activeTerminalProcesses.set(id, child);
child.stdout.on('data', (data) => event.sender.send(`terminal:output:${id}`, { type: 'stdout', text: data.toString() }));
child.stderr.on('data', (data) => event.sender.send(`terminal:output:${id}`, { type: 'stderr', text: data.toString() }));
child.on('close', (code) => {
activeTerminalProcesses.delete(id);
event.sender.send(`terminal:output:${id}`, { type: 'exit', code });
resolve({ exitCode: code });
});
child.on('error', (err) => {
activeTerminalProcesses.delete(id);
event.sender.send(`terminal:output:${id}`, { type: 'stderr', text: err.message });
resolve({ error: err.message });
});
});
});
handlers.set('terminal:cancel', async (event, id) => {
const child = activeTerminalProcesses.get(id);
if (child) {
child.kill();
activeTerminalProcesses.delete(id);
return true;
}
return false;
});
handlers.set('agent:run', async (event, request) => {
const providerId = request.provider || 'openai';
const provider = providers[providerId];
if (!provider) throw new Error('Unknown provider.');
const model = request.model || (providerId === 'openai' ? 'gpt-5.5' : 'default');
const prompt = request.prompt || '';
const access = ['read-only', 'workspace-write', 'full'].includes(request.access) ? request.access : 'workspace-write';
const accessInstruction = access === 'read-only' ? 'WICHTIG: Arbeite lesend.' : access === 'workspace-write' ? `WICHTIG: Ändere nur Dateien in: ${PROJECT_PATH}` : '';
const finalPrompt = [accessInstruction, request.systemPrompt ? `System:\n${request.systemPrompt}` : '', prompt].filter(Boolean).join('\n\n');
const args = [];
let stdin = '';
if (providerId === 'antigravity') {
args.push('-p', finalPrompt, '--model', model, '--dangerously-skip-permissions');
} else if (providerId === 'openai') {
args.push('exec', '-', '--model', model, '--cd', PROJECT_PATH, '--color', 'never', '--skip-git-repo-check', '--sandbox', access === 'full' ? 'danger-full-access' : (access === 'read-only' ? 'read-only' : 'workspace-write'));
if (access === 'full') args.push('--dangerously-bypass-approvals-and-sandbox');
stdin = finalPrompt;
} else if (providerId === 'anthropic') {
args.push('-p', '--model', model, '--output-format', 'text', '--permission-mode', access === 'full' ? 'bypassPermissions' : (access === 'read-only' ? 'plan' : 'auto'));
if (access === 'full') args.push('--dangerously-skip-permissions');
stdin = finalPrompt;
} else if (providerId === 'cursor') {
args.push('-p', finalPrompt, '--output-format', 'text');
if (model && model !== 'default') args.push('--model', model);
}
const isWin = process.platform === 'win32';
const child = spawn(resolveCommand(provider), args, {
cwd: PROJECT_PATH,
env: {
...process.env,
...(!isWin && {
HOME: process.env.HOME || '/root',
USER: process.env.USER || 'root',