Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
933 lines (837 loc) · 27 KB
/
Copy pathserver.js
File metadata and controls
933 lines (837 loc) · 27 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
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import express from "express";
loadDotEnv(path.join(process.cwd(), ".env"));
const app = express();
const host = process.env.CODEX_REMOTE_HOST || "127.0.0.1";
const port = Number(process.env.CODEX_REMOTE_PORT || 8765);
const requiredAuthSecret = process.env.CODEX_REMOTE_TOKEN || "";
const adminAuthSecret = process.env.CODEX_REMOTE_ADMIN_TOKEN || "";
const codexHome = resolveCodexHome();
const sessionsDir = path.join(codexHome, "sessions");
const archivedDir = path.join(codexHome, "archived_sessions");
const runtimeDir = path.join(process.cwd(), "runtime");
const screenshotsDir = path.join(runtimeDir, "screenshots");
const desktopBridgeScript = path.join(process.cwd(), "scripts", "desktop-bridge.ps1");
const desktopBridgeAvailable = process.platform === "win32";
const jobs = new Map();
const terminalSessions = new Map();
app.disable("x-powered-by");
app.use(express.json({ limit: "256kb" }));
app.use(express.static(path.join(process.cwd(), "public"), {
extensions: ["html"],
maxAge: "5m"
}));
app.get("/api/health", (req, res) => {
if (adminAuthSecret && req.get("authorization") !== `Bearer ${adminAuthSecret}`) {
return res.status(401).json({ ok: false });
}
const body = { ok: true };
if (adminAuthSecret) {
body.codexHome = codexHome;
}
res.json(body);
});
app.post("/api/login", (req, res) => {
const authValue = String(req.body?.token || "");
if (!requiredAuthSecret) {
return res.status(503).json({ error: "CODEX_REMOTE_TOKEN is not configured" });
}
if (!constantTimeEquals(authValue, requiredAuthSecret)) {
return res.status(401).json({ error: "Invalid token" });
}
res.setHeader("Set-Cookie", buildAuthCookie(authValue));
res.json({ ok: true });
});
app.use("/api", requireAuth);
app.post("/api/logout", (_req, res) => {
res.setHeader("Set-Cookie", "codex_remote_token=; HttpOnly; SameSite=Strict; Path=/api; Max-Age=0");
res.json({ ok: true });
});
app.get("/api/status", async (_req, res) => {
res.json({
codexHome,
runner: process.env.CODEX_REMOTE_RUNNER || "mock",
terminal: getTerminalConfig().display,
sessionsReadable: await exists(sessionsDir),
archivedReadable: await exists(archivedDir),
desktopBridgeAvailable,
canWriteAppSessions: false,
note: "Desktop Codex sessions are treated as read-only because there is no stable public session-control API exposed here."
});
});
app.get("/api/desktop/codex/status", (_req, res) => {
res.json({
available: desktopBridgeAvailable,
platform: process.platform
});
});
app.post("/api/desktop/codex/focus", async (_req, res) => {
await respondWithDesktopAction(res, "focus");
});
app.post("/api/desktop/codex/screenshot", async (_req, res) => {
await respondWithDesktopAction(res, "screenshot");
});
app.post("/api/desktop/codex/paste", async (req, res) => {
const text = String(req.body?.text || "");
if (!text.trim()) {
return res.status(400).json({ error: "Text is required" });
}
if (text.length > 12000) {
return res.status(400).json({ error: "Text is too long" });
}
await respondWithDesktopAction(res, "paste", { text });
});
app.post("/api/desktop/codex/send-enter", async (_req, res) => {
await respondWithDesktopAction(res, "send-enter");
});
app.post("/api/desktop/codex/click", async (req, res) => {
const x = Number(req.body?.x);
const y = Number(req.body?.y);
if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || x > 1 || y < 0 || y > 1) {
return res.status(400).json({ error: "Click coordinates must be between 0 and 1" });
}
await respondWithDesktopAction(res, "click", { x, y });
});
app.get("/api/desktop/codex/screenshots/:name", (req, res) => {
const name = path.basename(req.params.name);
if (name !== req.params.name || !/^codex-\d{8}-\d{6}-\d{3}\.png$/.test(name)) {
return res.status(404).json({ error: "Screenshot not found" });
}
res.sendFile(path.join(screenshotsDir, name));
});
app.get("/api/sessions", async (req, res) => {
const includeArchived = req.query.archived === "1";
const limit = clampInt(req.query.limit, 1, 200, 50);
const records = await listSessionRecords(includeArchived);
records.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
res.json({ sessions: records.slice(0, limit) });
});
app.get("/api/sessions/:id", async (req, res) => {
const session = await findSessionById(req.params.id);
if (!session) {
return res.status(404).json({ error: "Session not found" });
}
const preview = await readSessionPreview(session.path);
res.json({ ...session, preview });
});
app.get("/api/jobs", (_req, res) => {
res.json({ jobs: Array.from(jobs.values()).sort((a, b) => b.createdAt.localeCompare(a.createdAt)) });
});
app.post("/api/jobs", async (req, res) => {
const prompt = String(req.body?.prompt || "").trim();
const workspace = String(req.body?.workspace || process.cwd()).trim();
if (!prompt) {
return res.status(400).json({ error: "Prompt is required" });
}
if (prompt.length > 12000) {
return res.status(400).json({ error: "Prompt is too long" });
}
const job = createJob(prompt, workspace);
jobs.set(job.id, job);
runJob(job);
res.status(202).json({ job });
});
app.get("/api/jobs/:id", (req, res) => {
const job = jobs.get(req.params.id);
if (!job) {
return res.status(404).json({ error: "Job not found" });
}
res.json({ job });
});
app.get("/api/jobs/:id/events", (req, res) => {
const job = jobs.get(req.params.id);
if (!job) {
return res.status(404).end();
}
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.flushHeaders?.();
sendEvent(res, "snapshot", job);
const listener = (changedJob) => {
if (changedJob.id === job.id) {
sendEvent(res, "snapshot", changedJob);
}
};
app.onJobUpdate(listener);
req.on("close", () => app.offJobUpdate(listener));
});
app.get("/api/terminal", (_req, res) => {
res.json({
config: getTerminalConfig(),
sessions: Array.from(terminalSessions.values()).map(publicTerminalSession).sort((a, b) => b.createdAt.localeCompare(a.createdAt))
});
});
app.post("/api/terminal/start", (req, res) => {
const runningSession = Array.from(terminalSessions.values()).find((session) => session.status === "running");
if (runningSession) {
return res.status(200).json({ session: publicTerminalSession(runningSession) });
}
const workspace = String(req.body?.workspace || process.cwd()).trim() || process.cwd();
const resolvedWorkspace = path.resolve(workspace);
if (!fs.existsSync(resolvedWorkspace) || !fs.statSync(resolvedWorkspace).isDirectory()) {
return res.status(400).json({ error: "Workspace must be an existing directory" });
}
const config = getTerminalConfig();
if (!config.enabled) {
return res.status(503).json({ error: "Terminal command is not configured" });
}
const session = createTerminalSession(resolvedWorkspace, config);
terminalSessions.set(session.id, session);
startTerminalProcess(session);
res.status(202).json({ session: publicTerminalSession(session) });
});
app.get("/api/terminal/:id", (req, res) => {
const session = terminalSessions.get(req.params.id);
if (!session) {
return res.status(404).json({ error: "Terminal session not found" });
}
res.json({ session: publicTerminalSession(session) });
});
app.get("/api/terminal/:id/events", (req, res) => {
const session = terminalSessions.get(req.params.id);
if (!session) {
return res.status(404).end();
}
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.flushHeaders?.();
sendEvent(res, "snapshot", publicTerminalSession(session));
const listener = (changedSession) => {
if (changedSession.id === session.id) {
sendEvent(res, "snapshot", publicTerminalSession(changedSession));
}
};
terminalListeners.add(listener);
req.on("close", () => terminalListeners.delete(listener));
});
app.post("/api/terminal/:id/input", (req, res) => {
const session = terminalSessions.get(req.params.id);
if (!session) {
return res.status(404).json({ error: "Terminal session not found" });
}
if (session.status !== "running" || !session.child || session.child.stdin.destroyed) {
return res.status(409).json({ error: "Terminal session is not running" });
}
const text = String(req.body?.text || "");
if (!text) {
return res.status(400).json({ error: "Input is required" });
}
if (text.length > 12000) {
return res.status(400).json({ error: "Input is too long" });
}
session.child.stdin.write(text);
appendTerminalLog(session, "stdin", text);
res.json({ session: publicTerminalSession(session) });
});
app.post("/api/terminal/:id/clear", (req, res) => {
const session = terminalSessions.get(req.params.id);
if (!session) {
return res.status(404).json({ error: "Terminal session not found" });
}
session.logs = [];
appendTerminalLog(session, "system", "Output cleared.");
res.json({ session: publicTerminalSession(session) });
});
app.post("/api/terminal/:id/stop", (req, res) => {
const session = terminalSessions.get(req.params.id);
if (!session) {
return res.status(404).json({ error: "Terminal session not found" });
}
stopTerminalSession(session);
res.json({ session: publicTerminalSession(session) });
});
const listeners = new Set();
const terminalListeners = new Set();
app.onJobUpdate = (listener) => listeners.add(listener);
app.offJobUpdate = (listener) => listeners.delete(listener);
app.listen(port, host, () => {
console.log(`Codex Remote listening on http://${host}:${port}`);
if (!requiredAuthSecret) {
console.warn("CODEX_REMOTE_TOKEN is not configured. Login will be disabled until you set it.");
}
});
function loadDotEnv(file) {
if (!fs.existsSync(file)) return;
const text = fs.readFileSync(file, "utf8");
for (const line of text.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(trimmed);
if (!match || process.env[match[1]] !== undefined) continue;
process.env[match[1]] = match[2].replace(/^"(.*)"$/, "$1");
}
}
function resolveCodexHome() {
if (process.env.CODEX_HOME) {
return path.resolve(process.env.CODEX_HOME);
}
return path.join(os.homedir(), ".codex");
}
function requireAuth(req, res, next) {
const header = req.get("authorization") || "";
const cookieAuthValue = parseCookies(req.get("cookie") || "").codex_remote_token || "";
const authValue = header.startsWith("Bearer ") ? header.slice(7) : cookieAuthValue;
if (!requiredAuthSecret) {
return res.status(503).json({ error: "CODEX_REMOTE_TOKEN is not configured" });
}
if (!constantTimeEquals(authValue, requiredAuthSecret)) {
return res.status(401).json({ error: "Unauthorized" });
}
next();
}
function buildAuthCookie(authValue) {
const parts = [
`codex_remote_token=${encodeURIComponent(authValue)}`,
"HttpOnly",
"SameSite=Strict",
"Path=/api",
"Max-Age=2592000"
];
if (process.env.CODEX_REMOTE_SECURE_COOKIE === "1") {
parts.push("Secure");
}
return parts.join("; ");
}
function parseCookies(header) {
const cookies = {};
for (const part of header.split(";")) {
const index = part.indexOf("=");
if (index === -1) continue;
const key = part.slice(0, index).trim();
const value = part.slice(index + 1).trim();
cookies[key] = decodeURIComponent(value);
}
return cookies;
}
function constantTimeEquals(a, b) {
const left = Buffer.from(String(a));
const right = Buffer.from(String(b));
if (left.length !== right.length) return false;
return crypto.timingSafeEqual(left, right);
}
function clampInt(value, min, max, fallback) {
const parsed = Number.parseInt(String(value ?? ""), 10);
if (Number.isNaN(parsed)) return fallback;
return Math.max(min, Math.min(max, parsed));
}
async function exists(target) {
try {
await fs.promises.access(target, fs.constants.R_OK);
return true;
} catch {
return false;
}
}
async function respondWithDesktopAction(res, action, options = {}) {
try {
const result = await runDesktopBridge(action, options);
res.json({ result });
} catch (error) {
res.status(error.status || 500).json({
error: error.message || "Desktop bridge failed",
details: error.details || undefined
});
}
}
async function runDesktopBridge(action, options = {}) {
if (!desktopBridgeAvailable) {
throw httpError(501, "Desktop bridge is only available on Windows.");
}
if (!await exists(desktopBridgeScript)) {
throw httpError(500, "Desktop bridge script is missing.");
}
let tempDir = "";
const args = ["-Action", action];
if (action === "screenshot") {
await fs.promises.mkdir(screenshotsDir, { recursive: true });
args.push("-OutDir", screenshotsDir);
}
if (action === "paste") {
tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "codex-remote-paste-"));
const textFile = path.join(tempDir, "prompt.txt");
await fs.promises.writeFile(textFile, options.text, "utf8");
args.push("-TextFile", textFile);
}
if (action === "click") {
args.push("-X", String(options.x), "-Y", String(options.y));
}
try {
const result = await spawnDesktopBridge(args);
delete result.path;
if (result.file) {
result.screenshotUrl = `/api/desktop/codex/screenshots/${encodeURIComponent(result.file)}`;
}
return result;
} finally {
if (tempDir) {
await fs.promises.rm(tempDir, { recursive: true, force: true });
}
}
}
function spawnDesktopBridge(args) {
return new Promise((resolve, reject) => {
const child = spawn("powershell.exe", [
"-NoLogo",
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-Sta",
"-File",
desktopBridgeScript,
...args
], {
cwd: process.cwd(),
windowsHide: true
});
let stdout = "";
let stderr = "";
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
child.kill();
reject(httpError(504, "Desktop bridge timed out."));
}, 15000);
child.stdout.on("data", (chunk) => {
stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk) => {
stderr += chunk.toString("utf8");
});
child.on("error", (error) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(httpError(500, error.message));
});
child.on("close", (code) => {
if (settled) return;
settled = true;
clearTimeout(timer);
if (code !== 0) {
reject(httpError(500, firstMeaningfulLine(stderr) || `Desktop bridge exited with code ${code}.`, firstMeaningfulLine(stdout)));
return;
}
try {
const line = stdout.split(/\r?\n/).filter(Boolean).at(-1);
resolve(JSON.parse(line));
} catch {
reject(httpError(500, "Desktop bridge returned invalid JSON.", stdout.slice(0, 500)));
}
});
});
}
function firstMeaningfulLine(text) {
return String(text || "").split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "";
}
function httpError(status, message, details = "") {
const error = new Error(message);
error.status = status;
error.details = details;
return error;
}
async function listSessionRecords(includeArchived) {
const records = [];
const activeFiles = await findJsonlFiles(sessionsDir);
for (const file of activeFiles) {
records.push(await sessionRecordFromFile(file, false));
}
if (includeArchived && await exists(archivedDir)) {
const archivedFiles = await findJsonlFiles(archivedDir);
for (const file of archivedFiles) {
records.push(await sessionRecordFromFile(file, true));
}
}
const indexed = await readSessionIndex();
return records.map((record) => ({
...record,
title: indexed.get(record.id)?.thread_name || record.title
}));
}
async function readSessionIndex() {
const indexPath = path.join(codexHome, "session_index.jsonl");
const index = new Map();
if (!await exists(indexPath)) return index;
const text = await fs.promises.readFile(indexPath, "utf8");
for (const line of text.split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const item = JSON.parse(line);
if (item.id) index.set(item.id, item);
} catch {
// Ignore malformed lines; the session files remain the source of truth.
}
}
return index;
}
async function findJsonlFiles(root) {
if (!await exists(root)) return [];
const result = [];
const pending = [root];
while (pending.length) {
const current = pending.pop();
const entries = await fs.promises.readdir(current, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) {
pending.push(full);
} else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
result.push(full);
}
}
}
return result;
}
async function sessionRecordFromFile(file, archived) {
const stat = await fs.promises.stat(file);
const basename = path.basename(file, ".jsonl");
const id = basename.match(/([0-9a-f]{4,}-[0-9a-f-]{8,})$/i)?.[1] || basename;
const preview = await readFirstMeaningfulText(file);
return {
id,
title: preview || id,
path: file,
archived,
size: stat.size,
updatedAt: stat.mtime.toISOString()
};
}
async function readFirstMeaningfulText(file) {
const lines = await readHeadLines(file, 150);
for (const line of lines) {
const text = extractDisplayText(line);
if (text && text.length > 8) return text.slice(0, 120);
}
return "";
}
async function findSessionById(id) {
const all = await listSessionRecords(true);
return all.find((session) => session.id === id);
}
async function readSessionPreview(file) {
const lines = await readTailLines(file, 120);
const messages = [];
for (const line of lines) {
const text = extractDisplayText(line);
if (text) {
messages.push(text);
}
}
return messages.slice(-30);
}
async function readHeadLines(file, maxLines) {
const text = await fs.promises.readFile(file, "utf8");
return text.split(/\r?\n/).slice(0, maxLines);
}
async function readTailLines(file, maxLines) {
const text = await fs.promises.readFile(file, "utf8");
const lines = text.split(/\r?\n/).filter(Boolean);
return lines.slice(-maxLines);
}
function extractDisplayText(line) {
try {
const item = JSON.parse(line);
const candidates = [
item.thread_name,
item.message,
item.text,
item.content,
item.payload?.message,
item.payload?.text,
item.payload?.content,
item.item?.content,
item.item?.message?.content
];
for (const candidate of candidates) {
const text = normalizeText(candidate);
if (text) return text;
}
} catch {
return "";
}
return "";
}
function normalizeText(value) {
if (!value) return "";
if (typeof value === "string") return value.replace(/\s+/g, " ").trim();
if (Array.isArray(value)) {
return value.map(normalizeText).filter(Boolean).join(" ").trim();
}
if (typeof value === "object") {
if (typeof value.text === "string") return normalizeText(value.text);
if (typeof value.content === "string") return normalizeText(value.content);
}
return "";
}
function createJob(prompt, workspace) {
const now = new Date().toISOString();
return {
id: crypto.randomUUID(),
prompt,
workspace,
status: "queued",
createdAt: now,
updatedAt: now,
logs: []
};
}
function runJob(job) {
const runner = process.env.CODEX_REMOTE_RUNNER || "mock";
appendLog(job, "system", `Runner: ${runner}`);
job.status = "running";
touchJob(job);
if (runner === "mock") {
appendLog(job, "stdout", "Dry run only. Configure CODEX_REMOTE_RUNNER=command after you have a trusted Codex/agent wrapper.");
appendLog(job, "stdout", `Prompt: ${job.prompt}`);
job.status = "completed";
touchJob(job);
return;
}
if (runner === "powershell-echo") {
spawnForJob(job, "powershell.exe", [
"-NoLogo",
"-NoProfile",
"-Command",
"Write-Output ('Received remote prompt: ' + $env:CODEX_REMOTE_PROMPT)"
], { CODEX_REMOTE_PROMPT: job.prompt });
return;
}
if (runner === "command") {
const command = process.env.CODEX_REMOTE_COMMAND;
if (!command) {
appendLog(job, "stderr", "CODEX_REMOTE_COMMAND is required when CODEX_REMOTE_RUNNER=command.");
job.status = "failed";
touchJob(job);
return;
}
const promptFile = writePromptFile(job);
spawnForJob(job, command, [], { CODEX_REMOTE_PROMPT_FILE: promptFile });
return;
}
appendLog(job, "stderr", `Unknown runner: ${runner}`);
job.status = "failed";
touchJob(job);
}
function writePromptFile(job) {
const dir = path.join(os.tmpdir(), "codex-remote-prompts");
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, `${job.id}.txt`);
fs.writeFileSync(file, job.prompt, "utf8");
return file;
}
function spawnForJob(job, command, args, extraEnv) {
appendLog(job, "system", `Starting process in ${job.workspace}`);
const child = spawn(command, args, {
cwd: job.workspace || process.cwd(),
env: { ...process.env, ...extraEnv },
shell: true,
windowsHide: true
});
child.stdout.on("data", (chunk) => appendLog(job, "stdout", chunk.toString("utf8")));
child.stderr.on("data", (chunk) => appendLog(job, "stderr", chunk.toString("utf8")));
child.on("error", (error) => {
appendLog(job, "stderr", error.message);
job.status = "failed";
touchJob(job);
});
child.on("close", (code) => {
appendLog(job, "system", `Process exited with code ${code}`);
job.status = code === 0 ? "completed" : "failed";
touchJob(job);
});
}
function getTerminalConfig() {
const command = process.env.CODEX_REMOTE_TERMINAL_COMMAND || process.env.CODEX_REMOTE_AGENT_COMMAND || defaultTerminalCommand();
const argsValue = process.env.CODEX_REMOTE_TERMINAL_ARGS || process.env.CODEX_REMOTE_AGENT_ARGS || "";
const args = argsValue ? splitCommandLine(argsValue) : defaultTerminalArgs(command);
return {
enabled: Boolean(command),
command,
args,
display: [command, ...args].filter(Boolean).join(" ")
};
}
function defaultTerminalCommand() {
if (process.platform === "win32") {
return "cmd.exe";
}
return process.env.SHELL || "";
}
function defaultTerminalArgs(command) {
if (process.platform === "win32" && path.basename(command).toLowerCase() === "cmd.exe") {
return ["/Q", "/K", "chcp 65001>nul"];
}
return [];
}
function splitCommandLine(value) {
const args = [];
let current = "";
let quote = "";
let escaped = false;
for (const char of String(value)) {
if (escaped) {
current += char;
escaped = false;
continue;
}
if (char === "\\") {
escaped = true;
continue;
}
if (quote) {
if (char === quote) {
quote = "";
} else {
current += char;
}
continue;
}
if (char === "\"" || char === "'") {
quote = char;
continue;
}
if (/\s/.test(char)) {
if (current) {
args.push(current);
current = "";
}
continue;
}
current += char;
}
if (escaped) {
current += "\\";
}
if (current) {
args.push(current);
}
return args;
}
function createTerminalSession(workspace, config) {
const now = new Date().toISOString();
return {
id: crypto.randomUUID(),
command: config.command,
args: config.args,
workspace,
status: "starting",
exitCode: null,
createdAt: now,
updatedAt: now,
logs: [],
child: null
};
}
function startTerminalProcess(session) {
appendTerminalLog(session, "system", `Starting terminal: ${[session.command, ...session.args].join(" ")}`);
appendTerminalLog(session, "system", `Workspace: ${session.workspace}`);
try {
const child = spawn(session.command, session.args, {
cwd: session.workspace,
env: { ...process.env, FORCE_COLOR: "0", NO_COLOR: "1" },
shell: false,
windowsHide: true
});
session.child = child;
session.status = "running";
touchTerminalSession(session);
child.stdout.on("data", (chunk) => appendTerminalLog(session, "stdout", chunk.toString("utf8")));
child.stderr.on("data", (chunk) => appendTerminalLog(session, "stderr", chunk.toString("utf8")));
child.on("error", (error) => {
appendTerminalLog(session, "stderr", error.message);
session.status = "failed";
touchTerminalSession(session);
});
child.on("close", (code) => {
appendTerminalLog(session, "system", `Terminal exited with code ${code}`);
session.exitCode = code;
if (session.status !== "stopped") {
session.status = code === 0 ? "completed" : "failed";
}
session.child = null;
touchTerminalSession(session);
});
} catch (error) {
appendTerminalLog(session, "stderr", error.message);
session.status = "failed";
touchTerminalSession(session);
}
}
function stopTerminalSession(session) {
if (session.status !== "running" || !session.child) {
session.status = session.status === "starting" ? "stopped" : session.status;
touchTerminalSession(session);
return;
}
appendTerminalLog(session, "system", "Stopping terminal.");
session.status = "stopped";
const pid = session.child.pid;
if (process.platform === "win32" && pid) {
const killer = spawn("taskkill.exe", ["/PID", String(pid), "/T", "/F"], {
windowsHide: true
});
killer.on("error", () => session.child?.kill());
} else {
session.child.kill("SIGTERM");
}
touchTerminalSession(session);
}
function appendTerminalLog(session, stream, text) {
const entry = {
time: new Date().toISOString(),
stream,
text: String(text).slice(0, 16000)
};
session.logs.push(entry);
if (session.logs.length > 1000) {
session.logs.splice(0, session.logs.length - 1000);
}
touchTerminalSession(session);
}
function touchTerminalSession(session) {
session.updatedAt = new Date().toISOString();
for (const listener of terminalListeners) {
listener(session);
}
}
function publicTerminalSession(session) {
return {
id: session.id,
command: session.command,
args: session.args,
workspace: session.workspace,
status: session.status,
exitCode: session.exitCode,
createdAt: session.createdAt,
updatedAt: session.updatedAt,
logs: session.logs
};
}
function appendLog(job, stream, text) {
const entry = {
time: new Date().toISOString(),
stream,
text: String(text).slice(0, 8000)
};
job.logs.push(entry);
if (job.logs.length > 500) {
job.logs.splice(0, job.logs.length - 500);
}
touchJob(job);
}
function touchJob(job) {
job.updatedAt = new Date().toISOString();
for (const listener of listeners) {
listener(job);
}
}
function sendEvent(res, event, data) {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}