-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1434 lines (1328 loc) · 52.1 KB
/
Copy pathserver.js
File metadata and controls
1434 lines (1328 loc) · 52.1 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
import http from "node:http";
import { spawn, execFile } from "node:child_process";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { open, readFile, writeFile, mkdir, stat } from "node:fs/promises";
import { createReadStream } from "node:fs";
import path from "node:path";
import os from "node:os";
import { fileURLToPath } from "node:url";
import readline from "node:readline";
import QRCode from "qrcode";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number(process.env.PORT || 8787);
const HOST = process.env.HOST || "0.0.0.0";
const CODEX_HOME = process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
const DB = path.join(CODEX_HOME, "state_5.sqlite");
const LOGS_DB = path.join(CODEX_HOME, "logs_2.sqlite");
const APP_DIR = path.join(CODEX_HOME, "lan-companion");
const TOKEN_FILE = path.join(APP_DIR, "token");
const PINS_FILE = path.join(APP_DIR, "pins.json");
const ATTACHMENTS_DIR = path.join(APP_DIR, "attachments");
const GLOBAL_STATE_FILE = path.join(CODEX_HOME, ".codex-global-state.json");
const SESSION_INDEX_FILE = path.join(CODEX_HOME, "session_index.jsonl");
const PAIRING_QR_FILE = path.join(APP_DIR, "pairing-qr.png");
const SEND_MODE = process.env.CODEX_LAN_SEND_MODE || "desktop-ui";
const APP_SERVER_PORT = Number(process.env.CODEX_LAN_APP_SERVER_PORT || 18789);
const APP_SERVER_URL = process.env.CODEX_LAN_APP_SERVER_URL || `ws://127.0.0.1:${APP_SERVER_PORT}`;
const CODEX_BIN = process.env.CODEX_BIN || "/opt/homebrew/bin/codex";
const MAX_TRANSCRIPT_EVENTS = Number(process.env.CODEX_LAN_MAX_TRANSCRIPT_EVENTS || 2000);
const MAX_ROLLOUT_READ_BYTES = Number(process.env.CODEX_LAN_MAX_ROLLOUT_READ_BYTES || 64 * 1024 * 1024);
const mime = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".png": "image/png",
};
const runs = new Map();
const appServerActiveTurns = new Map();
let appServerClientPromise = null;
await mkdir(APP_DIR, { recursive: true });
await mkdir(ATTACHMENTS_DIR, { recursive: true });
const token = await loadOrCreateToken();
function sqlite(args, db = DB) {
return new Promise((resolve, reject) => {
execFile("sqlite3", ["-json", db, ...args], { maxBuffer: 20 * 1024 * 1024 }, (err, stdout, stderr) => {
if (err) {
reject(new Error(stderr || err.message));
return;
}
resolve(stdout.trim() ? JSON.parse(stdout) : []);
});
});
}
async function loadOrCreateToken() {
try {
const existing = (await readFile(TOKEN_FILE, "utf8")).trim();
if (existing) return existing;
} catch {}
const fresh = randomBytes(24).toString("base64url");
await writeFile(TOKEN_FILE, fresh, { mode: 0o600 });
return fresh;
}
async function readPins() {
const desktopPins = await readDesktopPins();
try {
const parsed = JSON.parse(await readFile(PINS_FILE, "utf8"));
const companionPins = new Set(Array.isArray(parsed.threadIds) ? parsed.threadIds : []);
const hiddenDesktopPins = new Set(Array.isArray(parsed.hiddenDesktopThreadIds) ? parsed.hiddenDesktopThreadIds : []);
return {
visible: new Set([...desktopPins, ...companionPins].filter((id) => !hiddenDesktopPins.has(id))),
desktop: desktopPins,
companion: companionPins,
hiddenDesktop: hiddenDesktopPins,
};
} catch {
return { visible: desktopPins, desktop: desktopPins, companion: new Set(), hiddenDesktop: new Set() };
}
}
async function readDesktopPins() {
try {
const parsed = JSON.parse(await readFile(GLOBAL_STATE_FILE, "utf8"));
const ids = parsed["pinned-thread-ids"];
return new Set(Array.isArray(ids) ? ids : []);
} catch {
return new Set();
}
}
async function readQueuedFollowUps() {
try {
const parsed = JSON.parse(await readFile(GLOBAL_STATE_FILE, "utf8"));
const raw = parsed["queued-follow-ups"];
if (!raw || typeof raw !== "object") return new Map();
const queued = new Map();
for (const [threadId, entries] of Object.entries(raw)) {
if (!Array.isArray(entries)) continue;
queued.set(
threadId,
entries
.filter((entry) => entry && typeof entry === "object")
.map((entry) => ({
id: String(entry.id || hash(JSON.stringify(entry))),
text: String(entry.text || entry.context?.prompt || ""),
imageAttachments: Array.isArray(entry.context?.imageAttachments) ? entry.context.imageAttachments : [],
createdAt: Number(entry.createdAt || 0),
}))
.filter((entry) => entry.text.trim()),
);
}
return queued;
} catch {
return new Map();
}
}
async function removeQueuedFollowUp(threadId, followUpId) {
const parsed = JSON.parse(await readFile(GLOBAL_STATE_FILE, "utf8"));
const raw = parsed["queued-follow-ups"];
if (!raw || !Array.isArray(raw[threadId])) return false;
const before = raw[threadId].length;
raw[threadId] = raw[threadId].filter((entry) => String(entry?.id || "") !== followUpId);
const removed = raw[threadId].length !== before;
if (raw[threadId].length === 0) delete raw[threadId];
await writeFile(GLOBAL_STATE_FILE, JSON.stringify(parsed));
return removed;
}
async function enqueueFollowUp(threadId, prompt, savedAttachments = []) {
const rows = await sqlite([`select id,cwd from threads where id = '${threadId.replaceAll("'", "''")}' limit 1`]);
if (!rows[0]) throw new Error("Thread not found");
let parsed = {};
try {
parsed = JSON.parse(await readFile(GLOBAL_STATE_FILE, "utf8"));
} catch {}
const queued = parsed["queued-follow-ups"] && typeof parsed["queued-follow-ups"] === "object" ? parsed["queued-follow-ups"] : {};
const cwd = rows[0].cwd || process.cwd();
queued[threadId] = Array.isArray(queued[threadId]) ? queued[threadId] : [];
queued[threadId].push({
id: randomUUID(),
text: prompt,
context: {
addedFiles: [],
prompt,
ideContext: null,
imageAttachments: savedAttachments.map((attachment) => ({
id: randomUUID(),
src: `data:${attachment.mimeType};base64,${attachment.dataBase64}`,
localPath: attachment.filePath,
filename: attachment.filename,
uploadStatus: "idle",
})),
nativeAppContexts: [],
fileAttachments: [],
inAppBrowserContext: null,
commentAttachments: [],
selectedTextAttachments: [],
pullRequestChecks: [],
workspaceRoots: [cwd],
},
cwd,
createdAt: Date.now(),
});
parsed["queued-follow-ups"] = queued;
await writeFile(GLOBAL_STATE_FILE, JSON.stringify(parsed));
}
async function readCustomThreadTitles() {
const titles = new Map();
try {
const parsed = JSON.parse(await readFile(GLOBAL_STATE_FILE, "utf8"));
const customTitles = parsed["thread-titles"]?.titles;
if (customTitles && typeof customTitles === "object") {
for (const [id, title] of Object.entries(customTitles)) {
if (typeof title === "string" && title.trim()) titles.set(id, title.trim());
}
}
} catch {}
try {
const raw = await readFile(SESSION_INDEX_FILE, "utf8");
for (const line of raw.split("\n")) {
if (!line.trim()) continue;
try {
const entry = JSON.parse(line);
if (entry.id && typeof entry.thread_name === "string" && entry.thread_name.trim()) {
titles.set(entry.id, entry.thread_name.trim());
}
} catch {}
}
} catch {}
return titles;
}
async function readLatestLimits() {
const transcriptLimits = await readLatestTranscriptLimits();
if (transcriptLimits) return transcriptLimits;
const rows = await sqlite(
[
`select id,ts,feedback_log_body
from logs
where feedback_log_body like '%websocket event:%codex.rate_limits%'
order by ts desc, ts_nanos desc, id desc
limit 50`,
],
LOGS_DB,
);
for (const row of rows) {
const event = parseCodexRateLimitEvent(row.feedback_log_body);
if (!event?.rate_limits) continue;
return {
updatedAt: new Date((Number(row.ts) || Date.now() / 1000) * 1000).toISOString(),
planType: event.plan_type || null,
limits: {
fiveHour: normalizeLimitWindow(event.rate_limits.primary),
weekly: normalizeLimitWindow(event.rate_limits.secondary),
},
};
}
return {
updatedAt: null,
planType: null,
limits: {
fiveHour: null,
weekly: null,
},
};
}
async function readLatestTranscriptLimits() {
const rows = await sqlite([`select rollout_path from threads where rollout_path is not null order by updated_at_ms desc, updated_at desc limit 20`]);
for (const row of rows) {
try {
const raw = await readFileTail(row.rollout_path, 2 * 1024 * 1024);
const lines = raw.split("\n").filter(Boolean).reverse();
for (const line of lines) {
let obj;
try {
obj = JSON.parse(line);
} catch {
continue;
}
const payload = obj.payload || {};
if (!payload.rate_limits) continue;
return {
updatedAt: obj.timestamp || new Date().toISOString(),
planType: payload.rate_limits.plan_type || null,
limits: {
fiveHour: normalizeLimitWindow(payload.rate_limits.primary),
weekly: normalizeLimitWindow(payload.rate_limits.secondary),
},
};
}
} catch {}
}
return null;
}
async function readFileTail(filePath, maxBytes) {
const handle = await open(filePath, "r");
try {
const { size } = await handle.stat();
const length = Math.min(size, maxBytes);
const buffer = Buffer.alloc(length);
await handle.read(buffer, 0, length, size - length);
return buffer.toString("utf8");
} finally {
await handle.close();
}
}
function parseCodexRateLimitEvent(message) {
const marker = "websocket event: ";
const start = message.indexOf(marker);
if (start < 0) return null;
try {
return JSON.parse(message.slice(start + marker.length));
} catch {
return null;
}
}
function normalizeLimitWindow(limit) {
if (!limit || typeof limit !== "object") return null;
const usedPercent = clampPercent(limit.used_percent);
const resetAtSeconds = Number(limit.reset_at || limit.resets_at || 0);
const resetAfterSeconds = Math.round(Number(limit.reset_after_seconds || Math.max(0, resetAtSeconds - Date.now() / 1000) || 0));
return {
usedPercent,
remainingPercent: Math.max(0, 100 - usedPercent),
windowMinutes: Number(limit.window_minutes || 0),
resetAt: resetAtSeconds ? new Date(resetAtSeconds * 1000).toISOString() : null,
resetAfterSeconds,
};
}
function clampPercent(value) {
const number = Number(value);
if (!Number.isFinite(number)) return 0;
return Math.max(0, Math.min(100, number));
}
async function writePins(pins) {
await writeFile(
PINS_FILE,
JSON.stringify(
{
threadIds: [...pins.companion],
hiddenDesktopThreadIds: [...pins.hiddenDesktop],
},
null,
2,
),
);
}
function normalizeIp(ip) {
if (!ip) return "";
if (ip.startsWith("::ffff:")) return ip.slice(7);
return ip;
}
function isPrivateNetwork(ip) {
ip = normalizeIp(ip);
if (ip === "::1" || ip === "127.0.0.1") return true;
if (ip.startsWith("10.")) return true;
if (ip.startsWith("192.168.")) return true;
const parts = ip.split(".").map(Number);
if (parts.length === 4 && parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
if (ip.startsWith("fe80:") || ip.startsWith("fd")) return true;
return false;
}
function sendJson(res, status, body) {
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
res.end(JSON.stringify(body));
}
function logRequest(req, message) {
console.log(`[${new Date().toISOString()}] ${normalizeIp(req.socket.remoteAddress)} ${message}`);
}
async function readBody(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 60 * 1024 * 1024) throw new Error("Body too large");
chunks.push(chunk);
}
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};
}
function authed(req) {
const provided = req.headers.authorization?.replace(/^Bearer\s+/i, "") || "";
const fromQuery = new URL(req.url, `http://${req.headers.host}`).searchParams.get("token") || "";
return provided === token || fromQuery === token;
}
function requireAccess(req, res) {
const ip = req.socket.remoteAddress;
if (!isPrivateNetwork(ip)) {
sendJson(res, 403, { error: "Only private local-network clients are allowed." });
return false;
}
if (req.url.startsWith("/api") && !authed(req)) {
sendJson(res, 401, { error: "Missing or invalid token." });
return false;
}
return true;
}
async function listThreads() {
const rows = await sqlite([
`select id,title,cwd,rollout_path,source,archived,created_at_ms,updated_at_ms,first_user_message,agent_nickname,agent_role,model,reasoning_effort
from threads
order by updated_at_ms desc, updated_at desc
limit 500`,
]);
const pins = await readPins();
const customTitles = await readCustomThreadTitles();
return rows.map((row) => ({
...row,
customTitle: customTitles.get(row.id) || null,
pinned: pins.visible.has(row.id),
project: row.cwd || "Unknown project",
}));
}
function eventText(payload) {
if (payload?.message) return payload.message;
if (Array.isArray(payload?.content)) {
return payload.content
.map((part) => part.text || part.input_text || part.output_text || "")
.filter(Boolean)
.join("\n");
}
return "";
}
async function readTranscript(threadId) {
const rows = await sqlite([`select * from threads where id = '${threadId.replaceAll("'", "''")}' limit 1`]);
if (!rows[0]) return null;
const pins = await readPins();
const customTitles = await readCustomThreadTitles();
const thread = {
...rows[0],
customTitle: customTitles.get(rows[0].id) || null,
pinned: pins.visible.has(rows[0].id),
project: rows[0].cwd || "Unknown project",
};
const events = [];
let pendingFileChanges = [];
for await (const line of readJsonlLines(thread.rollout_path)) {
if (!line.trim()) continue;
let obj;
try {
obj = JSON.parse(line);
} catch {
continue;
}
const payload = obj.payload || {};
if (obj.type === "response_item" && payload.type === "message") {
const text = eventText(payload);
if (text && payload.role !== "developer") {
const event = { id: hash(line), at: obj.timestamp, kind: "message", role: payload.role, text, phase: payload.phase || "" };
if (shouldAttachFileChanges(event) && pendingFileChanges.length) {
event.fileChanges = pendingFileChanges;
pendingFileChanges = [];
}
appendTranscriptEvent(events, event);
}
} else if (obj.type === "response_item" && ["function_call", "custom_tool_call"].includes(payload.type)) {
const text = summarizeToolCall(payload);
if (text) appendTranscriptEvent(events, { id: hash(line), at: obj.timestamp, kind: "event", role: "system", text, phase: "" });
} else if (obj.type === "event_msg") {
if (["agent_message", "user_message"].includes(payload.type)) {
const event = {
id: hash(line),
at: obj.timestamp,
kind: "message",
role: payload.type === "user_message" ? "user" : "assistant",
text: payload.message || "",
phase: payload.phase || "",
};
if (shouldAttachFileChanges(event) && pendingFileChanges.length) {
event.fileChanges = pendingFileChanges;
pendingFileChanges = [];
}
appendTranscriptEvent(events, event);
} else if (["exec_command_begin", "exec_command_end", "patch_apply_end", "task_started", "task_complete"].includes(payload.type)) {
const fileChanges = summarizeFileChanges(payload, thread.cwd);
if (fileChanges.length) pendingFileChanges = mergeFileChanges(pendingFileChanges, fileChanges);
appendTranscriptEvent(events, { id: hash(line), at: obj.timestamp, kind: "event", role: "system", text: summarizeEvent(payload), phase: "", fileChanges });
}
}
}
const queuedFollowUps = (await readQueuedFollowUps()).get(threadId) || [];
return { thread, events: compactDuplicateMessages(events), queuedFollowUps };
}
async function* readJsonlLines(filePath) {
const info = await stat(filePath);
if (info.size > MAX_ROLLOUT_READ_BYTES) {
const start = Math.max(0, info.size - MAX_ROLLOUT_READ_BYTES);
const size = info.size - start;
const handle = await open(filePath, "r");
try {
const buffer = Buffer.alloc(size);
await handle.read(buffer, 0, size, start);
const lines = buffer.toString("utf8").split("\n");
if (start > 0) lines.shift();
for (const line of lines) yield line;
} finally {
await handle.close();
}
return;
}
const stream = createReadStream(filePath, { encoding: "utf8" });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
for await (const line of rl) yield line;
}
function appendTranscriptEvent(events, event) {
events.push(event);
if (events.length > MAX_TRANSCRIPT_EVENTS) events.shift();
}
function compactDuplicateMessages(events) {
const out = [];
for (const event of events) {
const previous = out[out.length - 1];
if (event.kind === "message" && previous?.kind === "message" && previous.role === event.role && previous.text === event.text) {
if (!previous.phase && event.phase) previous.phase = event.phase;
if (!previous.fileChanges?.length && event.fileChanges?.length) previous.fileChanges = event.fileChanges;
continue;
}
out.push(event);
}
return out;
}
function shouldAttachFileChanges(event) {
return event.role === "assistant" && event.phase === "final_answer";
}
function summarizeFileChanges(payload, cwd) {
if (payload?.type !== "patch_apply_end" || payload.success === false || !payload.changes) return [];
return Object.entries(payload.changes).map(([filePath, change]) => {
const counts = countUnifiedDiff(change?.unified_diff || "");
return {
path: filePath,
displayPath: displayFilePath(filePath, cwd),
filename: path.basename(filePath),
status: change?.type || "update",
additions: counts.additions,
deletions: counts.deletions,
};
});
}
function countUnifiedDiff(diff) {
let additions = 0;
let deletions = 0;
for (const line of String(diff).split("\n")) {
if (line.startsWith("+++") || line.startsWith("---")) continue;
if (line.startsWith("+")) additions += 1;
else if (line.startsWith("-")) deletions += 1;
}
return { additions, deletions };
}
function displayFilePath(filePath, cwd) {
if (!cwd || !path.isAbsolute(filePath)) return filePath;
const relative = path.relative(cwd, filePath);
if (!relative.startsWith("..") && !path.isAbsolute(relative)) return relative || path.basename(filePath);
return filePath;
}
function mergeFileChanges(existing, incoming) {
const merged = new Map(existing.map((change) => [change.path, { ...change }]));
for (const change of incoming) {
const current = merged.get(change.path);
if (current) {
current.additions += change.additions;
current.deletions += change.deletions;
current.status = change.status;
} else {
merged.set(change.path, { ...change });
}
}
return Array.from(merged.values());
}
function summarizeEvent(payload) {
if (payload.type === "exec_command_begin") return `$ ${payload.cmd || "command"}`;
if (payload.type === "exec_command_end") return `command exited ${payload.exit_code ?? ""}`.trim();
if (payload.type === "patch_apply_end") return payload.success === false ? "patch failed" : "patch applied";
if (payload.type === "task_started") return "task started";
if (payload.type === "task_complete") return "task complete";
return payload.type || "event";
}
function summarizeToolCall(payload) {
if (payload.type === "custom_tool_call" && payload.name === "apply_patch") return "applying patch";
if (payload.type !== "function_call") return payload.name ? `using ${payload.name}` : "";
if (payload.name === "exec_command") {
const args = parseToolArguments(payload.arguments);
if (args?.cmd) return `$ ${oneLine(args.cmd, 140)}`;
return "running command";
}
if (payload.name === "write_stdin") return "reading command output";
if (payload.name === "apply_patch") return "applying patch";
return payload.name ? `using ${payload.name}` : "";
}
function parseToolArguments(argumentsText) {
if (!argumentsText || typeof argumentsText !== "string") return null;
try {
return JSON.parse(argumentsText);
} catch {
return null;
}
}
function oneLine(value, maxLength) {
const text = String(value).replace(/\s+/g, " ").trim();
return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
}
function hash(value) {
return createHash("sha1").update(value).digest("hex").slice(0, 16);
}
async function startRun(threadId, prompt, savedAttachments = []) {
if (SEND_MODE === "hybrid") {
const active = await isThreadActive(threadId);
const locked = await isMacScreenLocked();
const desktopAutomationReady = !isLaunchAgentBridge();
const desktopReady = !active && !locked && desktopAutomationReady;
console.log(
`[${new Date().toISOString()}] route thread=${threadId} active=${active} mode=hybrid locked=${locked} desktopAutomationReady=${desktopAutomationReady} desktopReady=${desktopReady}`,
);
if (active) return startQueuedFollowUpRun(threadId, prompt, savedAttachments);
if (desktopReady) return startDesktopUiRun(threadId, prompt, savedAttachments);
return startAppServerRun(threadId, prompt, savedAttachments);
}
if (SEND_MODE === "app-server") {
const appServerTurnId = appServerActiveTurns.get(threadId) || null;
const active = appServerTurnId ? true : await isThreadActive(threadId);
console.log(
`[${new Date().toISOString()}] route thread=${threadId} active=${active} mode=app-server appServerTurn=${appServerTurnId || "none"}`,
);
if (appServerTurnId) return startAppServerRun(threadId, prompt, savedAttachments, appServerTurnId);
if (active) return startQueuedFollowUpRun(threadId, prompt, savedAttachments);
return startAppServerRun(threadId, prompt, savedAttachments);
}
if (SEND_MODE === "desktop-ui") {
const active = await isThreadActive(threadId);
console.log(
`[${new Date().toISOString()}] route thread=${threadId} active=${active} mode=desktop-ui`,
);
// Keep mobile and Mac in one visible timeline: default app sends must never fork into a background CLI run.
if (active) return startQueuedFollowUpRun(threadId, prompt, savedAttachments);
return startDesktopUiRun(threadId, prompt, savedAttachments);
}
return startCliRun(threadId, prompt);
}
function isLaunchAgentBridge() {
return process.env.XPC_SERVICE_NAME === "com.matteodallombra.agentsidecar.bridge";
}
function isMacScreenLocked() {
return new Promise((resolve) => {
execFile("ioreg", ["-n", "Root", "-d1"], { timeout: 1500 }, (err, stdout) => {
if (err) {
resolve(true);
return;
}
resolve(/CGSSessionScreenIsLocked"\s*=\s*(Yes|1)/.test(stdout));
});
});
}
async function startAppServerRun(threadId, prompt, savedAttachments = [], expectedActiveTurnId = null) {
const rows = await sqlite([`select id,cwd from threads where id = '${threadId.replaceAll("'", "''")}' limit 1`]);
if (!rows[0]) throw new Error("Thread not found");
const id = randomBytes(10).toString("hex");
const run = {
id,
threadId,
status: "running",
mode: "app-server",
lines: [],
startedAt: Date.now(),
finishedAt: null,
exitCode: null,
appServerAgentMessage: "",
appServerReasoning: "",
};
runs.set(id, run);
console.log(`[${new Date().toISOString()}] run ${id} app-server submit thread=${threadId} chars=${prompt.length} attachments=${savedAttachments.length}`);
(async () => {
try {
const client = await getAppServerClient();
const resume = await client.request("thread/resume", {
threadId,
excludeTurns: true,
approvalPolicy: "never",
sandbox: "danger-full-access",
});
const activeTurnId = expectedActiveTurnId || (await findActiveTurnId(client, threadId));
const input = appServerInput(prompt, savedAttachments);
let response;
if (activeTurnId) {
run.appServerTurnId = activeTurnId;
response = await client.request("turn/steer", { threadId, expectedTurnId: activeTurnId, input });
run.lines.push({
at: new Date().toISOString(),
type: "stdout",
text: "Steered the active Codex app-server turn.",
parsed: null,
});
} else {
response = await client.request("turn/start", {
threadId,
input,
cwd: rows[0].cwd || resume.cwd || undefined,
approvalPolicy: "never",
sandboxPolicy: { type: "dangerFullAccess" },
});
run.appServerTurnId = response?.turn?.id || null;
if (run.appServerTurnId) appServerActiveTurns.set(threadId, run.appServerTurnId);
run.lines.push({
at: new Date().toISOString(),
type: "stdout",
text: "Started a Codex app-server turn.",
parsed: null,
});
}
if (response?.turn?.id) {
run.appServerTurnId = response.turn.id;
appServerActiveTurns.set(threadId, run.appServerTurnId);
}
await waitForAppServerTurn(client, run, threadId, run.appServerTurnId, 45 * 60 * 1000);
if (run.status === "running") {
run.status = "complete";
run.exitCode = 0;
}
} catch (error) {
console.log(`[${new Date().toISOString()}] run ${id} app-server failed: ${error.message}`);
run.status = "failed";
run.exitCode = 1;
run.lines.push({ at: new Date().toISOString(), type: "error", text: error.message });
appServerClientPromise = null;
} finally {
if (run.appServerTurnId && appServerActiveTurns.get(threadId) === run.appServerTurnId) {
appServerActiveTurns.delete(threadId);
}
run.finishedAt = Date.now();
}
})();
return run;
}
function appServerInput(prompt, savedAttachments) {
const input = [{ type: "text", text: prompt, text_elements: [] }];
for (const attachment of savedAttachments) {
input.push({ type: "localImage", path: attachment.filePath });
}
return input;
}
async function findActiveTurnId(client, threadId) {
try {
const turns = await client.request("thread/turns/list", { threadId, limit: 10, sortDirection: "desc" });
return turns?.data?.find((turn) => turn.status === "inProgress")?.id || null;
} catch {
return null;
}
}
async function waitForAppServerTurn(client, run, threadId, turnId, timeoutMs) {
if (!turnId) return;
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline && run.status === "running") {
const event = await client.nextNotification((message) => {
if (message.params?.threadId !== threadId) return false;
const eventTurnId = message.params?.turnId || message.params?.turn?.id;
return !eventTurnId || eventTurnId === turnId;
}, 30_000);
if (!event) continue;
handleAppServerNotification(run, event);
if (event.method === "turn/completed") return;
}
}
function handleAppServerNotification(run, message) {
const params = message.params || {};
if (message.method === "item/agentMessage/delta" && params.delta) {
run.appServerAgentMessage += params.delta;
} else if ((message.method === "item/reasoning/textDelta" || message.method === "item/reasoning/summaryTextDelta") && params.delta) {
run.appServerReasoning += params.delta;
} else if (message.method === "turn/completed") {
const turn = params.turn || {};
if (run.appServerReasoning) {
run.lines.push({
at: new Date().toISOString(),
type: "stdout",
text: JSON.stringify({ payload: { type: "reasoning", message: run.appServerReasoning } }),
parsed: { payload: { type: "reasoning", message: run.appServerReasoning } },
});
}
if (run.appServerAgentMessage) {
run.lines.push({
at: new Date().toISOString(),
type: "stdout",
text: JSON.stringify({ payload: { type: "agent_message", message: run.appServerAgentMessage } }),
parsed: { payload: { type: "agent_message", message: run.appServerAgentMessage } },
});
}
run.status = turn.status === "failed" ? "failed" : "complete";
run.exitCode = turn.status === "failed" ? 1 : 0;
if (turn.error?.message) {
run.lines.push({ at: new Date().toISOString(), type: "error", text: turn.error.message, parsed: null });
}
} else if (message.method === "thread/status/changed") {
run.lines.push({
at: new Date().toISOString(),
type: "stdout",
text: `Codex app-server status: ${JSON.stringify(params.status)}`,
parsed: null,
});
}
if (run.lines.length > 1000) run.lines.splice(0, run.lines.length - 1000);
}
async function getAppServerClient() {
if (!appServerClientPromise) appServerClientPromise = createAppServerClient();
return appServerClientPromise;
}
async function createAppServerClient() {
const started = await ensureAppServer();
const ws = new WebSocket(APP_SERVER_URL);
const pending = new Map();
const notifications = [];
const waiters = [];
let nextId = 1;
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("Timed out connecting to Codex app-server.")), 10_000);
ws.onopen = () => {
clearTimeout(timer);
resolve();
};
ws.onerror = () => reject(new Error("Could not connect to Codex app-server."));
});
ws.onmessage = (event) => {
let message;
try {
message = JSON.parse(event.data);
} catch {
return;
}
if (message.id != null && pending.has(message.id)) {
const { resolve, reject } = pending.get(message.id);
pending.delete(message.id);
if (message.error) reject(new Error(message.error.message || "Codex app-server request failed."));
else resolve(message.result);
return;
}
let delivered = false;
for (const waiter of waiters.splice(0)) {
if (waiter.filter(message)) {
clearTimeout(waiter.timer);
waiter.resolve(message);
delivered = true;
} else {
waiters.push(waiter);
}
}
if (!delivered) {
notifications.push(message);
if (notifications.length > 500) notifications.shift();
}
};
ws.onclose = () => {
appServerClientPromise = null;
for (const { reject } of pending.values()) reject(new Error("Codex app-server disconnected."));
pending.clear();
};
const client = {
started,
request(method, params) {
const id = nextId++;
ws.send(JSON.stringify({ id, method, params }));
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
setTimeout(() => {
if (!pending.has(id)) return;
pending.delete(id);
reject(new Error(`Timed out waiting for app-server ${method}.`));
}, 30_000);
});
},
notify(method, params) {
ws.send(JSON.stringify({ method, params }));
},
nextNotification(filter, timeoutMs) {
const existingIndex = notifications.findIndex(filter);
if (existingIndex >= 0) {
const [message] = notifications.splice(existingIndex, 1);
return Promise.resolve(message);
}
return new Promise((resolve) => {
const waiter = {
filter,
resolve,
timer: setTimeout(() => {
const index = waiters.indexOf(waiter);
if (index >= 0) waiters.splice(index, 1);
resolve(null);
}, timeoutMs),
};
waiters.push(waiter);
});
},
};
await client.request("initialize", {
clientInfo: { name: "agentsidecar", title: "AgentSidecar", version: "0.1.0" },
capabilities: { experimentalApi: true },
});
client.notify("initialized");
return client;
}
async function ensureAppServer() {
try {
const response = await fetch(APP_SERVER_URL.replace(/^ws/, "http").replace(/\/$/, "") + "/readyz");
if (response.ok) return false;
} catch {}
const url = new URL(APP_SERVER_URL);
if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost") {
throw new Error(`Codex app-server is not running at ${APP_SERVER_URL}.`);
}
const child = spawn(CODEX_BIN, ["app-server", "--listen", APP_SERVER_URL], {
stdio: ["ignore", "ignore", "pipe"],
env: { ...process.env, PATH: `/opt/homebrew/bin:${process.env.PATH || "/usr/bin:/bin:/usr/sbin:/sbin"}` },
});
child.on("error", (error) => {
console.log(`[codex app-server] failed to start ${CODEX_BIN}: ${error.message}`);
});
child.stderr.on("data", (chunk) => {
for (const line of chunk.toString("utf8").split("\n")) {
if (line.trim()) console.log(`[codex app-server] ${line}`);
}
});
child.unref();
const deadline = Date.now() + 10_000;
while (Date.now() < deadline) {
try {
const response = await fetch(APP_SERVER_URL.replace(/^ws/, "http").replace(/\/$/, "") + "/readyz");
if (response.ok) return true;
} catch {}
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("Timed out starting Codex app-server.");
}
async function isThreadActive(threadId) {
const rows = await sqlite([`select rollout_path from threads where id = '${threadId.replaceAll("'", "''")}' limit 1`]);
const rolloutPath = rows[0]?.rollout_path;
if (!rolloutPath) return false;
try {
let latestTaskEvent = null;
for await (const line of readJsonlLines(rolloutPath)) {
if (!line.trim()) continue;
let obj;
try {
obj = JSON.parse(line);
} catch {
continue;
}
if (obj.type !== "event_msg") continue;
const type = obj.payload?.type;
if (type === "task_started" || type === "task_complete") latestTaskEvent = type;
}
return latestTaskEvent === "task_started";
} catch {
return false;
}
}
async function buildPromptWithAttachments(threadId, prompt, attachments) {
const trimmed = typeof prompt === "string" ? prompt.trim() : "";
const saved = await saveAttachments(threadId, attachments);
if (!saved.length) return { prompt: trimmed, savedAttachments: [] };
const base = trimmed || "Please review the attached image(s).";
const lines = saved.flatMap((attachment, index) => [
`Image ${index + 1}: ${attachment.filename}`,
``,
]);
return { prompt: `${base}\n\nAttached images:\n${lines.join("\n")}`, savedAttachments: saved };
}
async function saveAttachments(threadId, attachments) {
if (!Array.isArray(attachments) || attachments.length === 0) return [];
if (attachments.length > 8) throw new Error("Attach up to 8 images at a time.");