-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1191 lines (1105 loc) · 35 KB
/
server.js
File metadata and controls
1191 lines (1105 loc) · 35 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 "dotenv/config";
import fs from "node:fs/promises";
import path from "node:path";
import crypto from "node:crypto";
import os from "node:os";
import express from "express";
import { fileURLToPath } from "node:url";
import { Codex } from "@openai/codex-sdk";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DEFAULT_MODEL = process.env.CODEX_MODEL ?? "gpt-5-codex";
const DEFAULT_REASONING =
process.env.CODEX_REASONING ??
process.env.CODEX_MODEL_REASONING ??
"medium";
const PORT = Number(process.env.PORT ?? 8080);
const STATE_FILE = path.join(__dirname, ".codex_threads.json");
const PUBLIC_DIR = path.join(__dirname, "public");
const DASHBOARD_HTML = path.join(PUBLIC_DIR, "dashboard.html");
let requestCounter = 0;
const SHOULD_SKIP_GIT =
process.env.CODEX_SKIP_GIT_CHECK === "false" ? false : true;
const API_KEY = process.env.CODEX_BRIDGE_API_KEY ?? "123321";
const SANDBOX_MODE = normalizeSandboxMode(
process.env.CODEX_SANDBOX_MODE ?? "danger-full-access",
);
const WORKING_DIRECTORY = resolveWorkingDirectory(process.env.CODEX_WORKDIR);
const NETWORK_ACCESS = readBooleanEnv(
process.env.CODEX_NETWORK_ACCESS,
false,
);
const WEB_SEARCH = readBooleanEnv(process.env.CODEX_WEB_SEARCH, false);
const APPROVAL_POLICY = normalizeApprovalPolicy(
process.env.CODEX_APPROVAL_POLICY ?? "never",
);
const LOG_REQUESTS = readBooleanEnv(process.env.CODEX_LOG_REQUESTS, false);
const REQUIRE_SESSION_ID = readBooleanEnv(
process.env.CODEX_REQUIRE_SESSION_ID,
false,
);
const JSON_LIMIT = process.env.CODEX_JSON_LIMIT ?? "10mb";
const APP_START = Date.now();
const DEFAULT_CODEX_DIR =
process.env.CODEX_STATE_DIR ?? path.join(os.homedir(), ".codex");
const CODEX_STATE_DIR =
process.env.CODEX_STATE_DIR ?? process.env.CODEX_DIR ?? DEFAULT_CODEX_DIR;
const CODEX_AUTH_FILE =
process.env.CODEX_AUTH_FILE ?? path.join(CODEX_STATE_DIR, "auth.json");
const APP_VERSION = process.env.npm_package_version ?? "dev";
const MODEL_PRESETS = [
{
id: "gpt-5-codex",
label: "GPT-5-Codex",
description: "面向复杂开发任务的旗舰 Codex,适合深度修改代码与调用多种工具。",
reasonings: [
{ level: "low", label: "Low", description: "响应最快,推理深度最低,适合简单改动。" },
{ level: "medium", label: "Medium", description: "推理深度与速度折中(默认)。" },
{ level: "high", label: "High", description: "推理深度最高,适合疑难杂症与大型重构。" },
],
defaultReasoning: "medium",
},
{
id: "gpt-5-codex-mini",
label: "GPT-5-Codex-Mini",
description: "轻量版 Codex,适合日常增删改查与脚本编辑,成本更低。",
reasonings: [
{ level: "low", label: "Low", description: "最快速的响应,适合简单编辑。" },
{ level: "medium", label: "Medium", description: "在速度与质量之间取得平衡(默认)。" },
],
defaultReasoning: "medium",
},
{
id: "gpt-5",
label: "GPT-5",
description: "通用型 GPT-5,覆盖广泛常识与自然语言任务,侧重综合推理。",
reasonings: [
{ level: "low", label: "Low", description: "高速度模式,适合问答/总结等轻负载任务。" },
{ level: "medium", label: "Medium", description: "标准推理深度(默认),适合大多数对话场景。" },
{ level: "high", label: "High", description: "最大化推理能力,适合复杂需求或长篇创作。" },
],
defaultReasoning: "medium",
},
];
const codex = new Codex();
const inMemoryThreads = new Map();
const persistedThreadIds = await loadState();
const saveQueue = createSaveQueue();
const app = express();
app.use(express.json({ limit: JSON_LIMIT }));
app.use((req, _res, next) => {
if (!req.path.startsWith("/public")) {
requestCounter += 1;
}
next();
});
if (await fileExists(DASHBOARD_HTML)) {
app.use("/public", express.static(PUBLIC_DIR));
app.get("/dashboard", (_req, res) => {
res.sendFile(DASHBOARD_HTML);
});
app.get("/api/dashboard", async (_req, res) => {
try {
const snapshot = await buildDashboardSnapshot();
res.json(snapshot);
} catch (error) {
console.error("Failed to build dashboard snapshot:", error);
res.status(500).json({
error: {
message: "Failed to load Codex dashboard data.",
},
});
}
});
}
app.use((req, res, next) => {
if (req.path === "/health") return next();
if (!API_KEY) return next();
const authHeader = req.get("authorization") ?? "";
let suppliedKey = null;
if (authHeader.toLowerCase().startsWith("bearer ")) {
suppliedKey = authHeader.slice(7).trim();
} else if (req.get("x-api-key")) {
suppliedKey = req.get("x-api-key");
}
if (suppliedKey !== API_KEY) {
return res.status(401).json({
error: {
message: "Invalid or missing API key.",
type: "unauthorized",
},
});
}
return next();
});
app.get("/health", (_req, res) => {
res.json({ status: "ok" });
});
app.get("/v1/models", (_req, res) => {
const flattened = MODEL_PRESETS.flatMap((model) =>
model.reasonings.map((reasoning) => ({
object: "model",
id: `${model.id}:${reasoning.level}`,
label: `${model.label} · ${reasoning.label}`,
description: `${model.description} (Reasoning: ${reasoning.label})`,
base_model: model.id,
reasoning: reasoning.level,
default_reasoning: model.defaultReasoning,
})),
);
res.json({
object: "list",
data: flattened,
defaults: {
model: `${DEFAULT_MODEL}:${DEFAULT_REASONING}`,
},
});
});
app.post("/v1/chat/completions", async (req, res) => {
const { messages, model, reasoning_effort, stream } = req.body ?? {};
if (LOG_REQUESTS) {
console.log(
"[Codex Bridge] incoming chat request:",
JSON.stringify(
{
session_id:
req.body?.session_id ??
req.body?.conversation_id ??
req.body?.thread_id ??
req.body?.user ??
null,
model,
reasoning_effort: reasoning_effort ?? req.body?.model_reasoning_effort,
stream: Boolean(stream),
message_count: Array.isArray(messages) ? messages.length : 0,
raw: req.body,
},
null,
2,
),
);
}
if (!Array.isArray(messages) || messages.length === 0) {
return res.status(400).json({
error: {
message: "Request body must include a non-empty messages array.",
type: "invalid_request_error",
},
});
}
let sessionId = resolveSessionId(req);
const sessionProvided = Boolean(sessionId);
if (!sessionProvided && REQUIRE_SESSION_ID) {
return res.status(400).json({
error: {
message:
"session_id (or conversation_id / thread_id / user) is required in this deployment.",
type: "missing_session_id",
},
});
}
if (!sessionProvided) {
sessionId = `ephemeral-${crypto.randomUUID()}`;
}
let normalizedMessages;
try {
normalizedMessages = await normalizeMessages(messages);
} catch (error) {
return res.status(400).json({
error: {
message: error?.message ?? "Invalid message attachments.",
type: "invalid_request_error",
},
});
}
let outputSchema = null;
try {
outputSchema = resolveOutputSchemaFromBody(req.body);
} catch (error) {
return res.status(400).json({
error: {
message: error?.message ?? "Invalid response_format schema.",
type: "invalid_request_error",
},
});
}
const latestUserPrompt = extractLatestUserContent(normalizedMessages);
const latestUserInputs = extractLatestUserInputs(normalizedMessages);
const conversationPrompt = buildConversationPrompt(normalizedMessages);
const conversationInputs = buildConversationInputs(normalizedMessages);
const systemPrompt = buildSystemPrompt(normalizedMessages);
const finalPrompt = sessionProvided
? mergePrompts(systemPrompt, latestUserPrompt)
: conversationPrompt;
const finalStructuredPrompt = sessionProvided
? mergeStructuredPrompts(systemPrompt, latestUserInputs)
: conversationInputs;
if (
!finalPrompt &&
(!finalStructuredPrompt || finalStructuredPrompt.length === 0)
) {
return res.status(400).json({
error: {
message: "Messages must include at least one user entry.",
type: "invalid_request_error",
},
});
}
const codexInput = finalStructuredPrompt ?? finalPrompt;
const turnOptions = {};
if (outputSchema) turnOptions.outputSchema = outputSchema;
const attachmentCleanups = collectAttachmentCleanups(normalizedMessages);
const { resolvedModel, resolvedReasoning } = resolveModelAndReasoning({
model: model ?? DEFAULT_MODEL,
reasoning: reasoning_effort ?? req.body?.model_reasoning_effort,
});
const threadOptions = {
skipGitRepoCheck: SHOULD_SKIP_GIT,
model: resolvedModel,
modelReasoningEffort: resolvedReasoning,
};
if (SANDBOX_MODE) threadOptions.sandboxMode = SANDBOX_MODE;
if (WORKING_DIRECTORY) threadOptions.workingDirectory = WORKING_DIRECTORY;
if (NETWORK_ACCESS !== null)
threadOptions.networkAccessEnabled = NETWORK_ACCESS;
if (WEB_SEARCH !== null) threadOptions.webSearchEnabled = WEB_SEARCH;
if (APPROVAL_POLICY) threadOptions.approvalPolicy = APPROVAL_POLICY;
const threadRecord = await getOrCreateThread(sessionId, threadOptions, {
ephemeral: !sessionProvided,
});
const { thread } = threadRecord;
if (stream) {
if (LOG_REQUESTS) {
console.log(
"[Codex Bridge] runStreamed payload:",
JSON.stringify(
{
session_id: sessionId,
model: threadOptions.model,
reasoning: threadOptions.modelReasoningEffort,
sandboxMode: threadOptions.sandboxMode,
workingDirectory: threadOptions.workingDirectory,
networkAccessEnabled: threadOptions.networkAccessEnabled,
webSearchEnabled: threadOptions.webSearchEnabled,
approvalPolicy: threadOptions.approvalPolicy,
prompt: codexInput,
response_format: outputSchema ? "json_schema" : "text",
output_schema: outputSchema,
ephemeral: !sessionProvided,
},
null,
2,
),
);
}
await handleStreamResponse({
res,
thread,
threadOptions,
sessionId,
prompt: codexInput,
shouldPersist: sessionProvided,
turnOptions,
cleanupTasks: attachmentCleanups,
});
return;
}
try {
if (LOG_REQUESTS) {
console.log(
"[Codex Bridge] run payload:",
JSON.stringify(
{
session_id: sessionId,
model: threadOptions.model,
reasoning: threadOptions.modelReasoningEffort,
sandboxMode: threadOptions.sandboxMode,
workingDirectory: threadOptions.workingDirectory,
networkAccessEnabled: threadOptions.networkAccessEnabled,
webSearchEnabled: threadOptions.webSearchEnabled,
approvalPolicy: threadOptions.approvalPolicy,
prompt: codexInput,
response_format: outputSchema ? "json_schema" : "text",
output_schema: outputSchema,
ephemeral: !sessionProvided,
},
null,
2,
),
);
}
const turn = await thread.run(codexInput, turnOptions);
if (sessionProvided) {
await persistThreadIdIfNeeded(sessionId, thread);
}
const usage = formatUsage(turn?.usage);
return res.json({
id: `chatcmpl-${thread.id ?? crypto.randomUUID()}`,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: threadOptions.model,
choices: [
{
index: 0,
message: {
role: "assistant",
content: extractAssistantResponse(turn),
},
finish_reason: "stop",
},
],
usage,
});
} catch (error) {
console.error("Codex run failed:", error);
return res.status(500).json({
error: {
message: error?.message ?? "Codex execution failed.",
type: "codex_execution_error",
},
});
} finally {
await cleanupAttachmentFiles(attachmentCleanups);
}
});
app.use((err, _req, res, _next) => {
console.error("Unhandled error:", err);
res.status(500).json({
error: {
message: err?.message ?? "Unexpected server error.",
type: "internal_server_error",
},
});
});
await new Promise((resolve) => {
app.listen(PORT, () => {
console.log(
`Codex OpenAI-compatible bridge listening on http://localhost:${PORT}`,
);
resolve();
});
});
function normalizeReasoning(value) {
if (!value) return null;
const lowered = String(value).toLowerCase();
if (["low", "medium", "high"].includes(lowered)) {
return lowered;
}
return null;
}
function buildConversationPrompt(messages) {
if (!Array.isArray(messages) || messages.length === 0) return null;
const lines = [];
for (const entry of messages) {
if (!entry?.role || !entry?.text) continue;
lines.push(`[${entry.role.toUpperCase()}]\n${entry.text}`.trim());
}
return lines.length ? lines.join("\n\n") : null;
}
function buildConversationInputs(messages) {
if (!Array.isArray(messages) || messages.length === 0) return null;
const inputs = [];
for (const entry of messages) {
if (!entry?.role) continue;
const label = `[${entry.role.toUpperCase()}]`;
let prefixed = false;
if (entry.text) {
inputs.push({
type: "text",
text: `${label}\n${entry.text}`.trim(),
});
prefixed = true;
}
if (Array.isArray(entry.attachments) && entry.attachments.length > 0) {
if (!prefixed) {
inputs.push({ type: "text", text: label });
prefixed = true;
}
for (const attachment of entry.attachments) {
if (attachment?.path) {
inputs.push({ type: "local_image", path: attachment.path });
}
}
}
}
return inputs.length ? inputs : null;
}
function extractLatestUserContent(messages) {
if (!Array.isArray(messages)) return null;
for (let i = messages.length - 1; i >= 0; i -= 1) {
const entry = messages[i];
if (entry?.role !== "user") continue;
if (entry?.text) return entry.text;
}
return null;
}
function extractLatestUserInputs(messages) {
if (!Array.isArray(messages)) return null;
for (let i = messages.length - 1; i >= 0; i -= 1) {
const entry = messages[i];
if (entry?.role !== "user") continue;
const inputs = [];
if (entry?.text) {
inputs.push({ type: "text", text: entry.text });
}
if (Array.isArray(entry?.attachments)) {
for (const attachment of entry.attachments) {
if (attachment?.path) {
inputs.push({ type: "local_image", path: attachment.path });
}
}
}
return inputs.length ? inputs : null;
}
return null;
}
function buildSystemPrompt(messages) {
if (!Array.isArray(messages)) return null;
const blocks = [];
for (const entry of messages) {
if (entry?.role !== "system" || !entry?.text) continue;
blocks.push(`[SYSTEM]\n${entry.text}`.trim());
}
return blocks.length ? blocks.join("\n\n") : null;
}
function mergePrompts(systemPrompt, userPrompt) {
if (!userPrompt) return null;
if (!systemPrompt) return userPrompt;
return `${systemPrompt}\n\n${userPrompt}`;
}
function mergeStructuredPrompts(systemPrompt, userInputs) {
const inputs = [];
if (systemPrompt) {
inputs.push({ type: "text", text: systemPrompt });
}
if (Array.isArray(userInputs) && userInputs.length > 0) {
inputs.push(...userInputs);
}
return inputs.length ? inputs : null;
}
function resolveSessionId(req) {
const body = req?.body ?? {};
const headers = req?.headers ?? {};
const readHeader = (key) => {
const value = headers[String(key).toLowerCase()];
if (value === undefined || value === null) return null;
const text = Array.isArray(value) ? value[0] : value;
return typeof text === "string" && text.trim() ? text.trim() : null;
};
return (
body?.session_id ??
body?.conversation_id ??
body?.thread_id ??
body?.user ??
readHeader("x-session-id") ??
readHeader("session-id") ??
readHeader("x-conversation-id") ??
readHeader("x-thread-id") ??
readHeader("x-user-id") ??
null
);
}
function getModelPreset(modelId) {
if (!modelId) return null;
const normalized = String(modelId).toLowerCase();
return MODEL_PRESETS.find((preset) => preset.id === normalized) ?? null;
}
function resolveModelAndReasoning({ model, reasoning }) {
if (!model) {
return {
resolvedModel: DEFAULT_MODEL,
resolvedReasoning: DEFAULT_REASONING,
};
}
const split = String(model).toLowerCase().split(":");
const modelId = split[0];
const appendedReasoning = split[1];
const modelPreset = getModelPreset(modelId) ?? getModelPreset(DEFAULT_MODEL);
const requestedReasoning = normalizeReasoning(reasoning ?? appendedReasoning);
const allowedReasoning =
requestedReasoning &&
modelPreset?.reasonings?.some((r) => r.level === requestedReasoning)
? requestedReasoning
: modelPreset?.defaultReasoning ?? DEFAULT_REASONING;
return {
resolvedModel: modelPreset?.id ?? DEFAULT_MODEL,
resolvedReasoning: allowedReasoning,
};
}
function readBooleanEnv(value, fallback = null) {
if (value === undefined || value === null) return fallback;
const normalized = String(value).trim().toLowerCase();
if (["1", "true", "yes", "y", "on"].includes(normalized)) return true;
if (["0", "false", "no", "n", "off"].includes(normalized)) return false;
return fallback;
}
function normalizeSandboxMode(value) {
if (!value) return null;
const normalized = String(value).toLowerCase();
const allowed = [
"read-only",
"workspace-write",
"danger-full-access",
];
return allowed.includes(normalized) ? normalized : null;
}
function normalizeApprovalPolicy(value) {
if (!value) return null;
const normalized = String(value).toLowerCase();
const allowed = ["never", "on-request", "on-failure", "untrusted"];
return allowed.includes(normalized) ? normalized : null;
}
function resolveWorkingDirectory(value) {
if (!value) return null;
if (path.isAbsolute(value)) return value;
return path.resolve(__dirname, value);
}
function resolveOutputSchemaFromBody(body) {
if (!body || typeof body !== "object") return null;
if (body.output_schema !== undefined) {
return ensureJsonSchemaObject(body.output_schema, "output_schema");
}
if (body.outputSchema !== undefined) {
return ensureJsonSchemaObject(body.outputSchema, "outputSchema");
}
const responseFormat = body.response_format ?? body.responseFormat;
if (responseFormat === undefined || responseFormat === null) return null;
if (typeof responseFormat === "string") {
const normalized = responseFormat.toLowerCase();
if (normalized === "json_schema") {
throw new Error(
"response_format \"json_schema\" requires an accompanying schema.",
);
}
if (normalized === "json_object") {
return { type: "object" };
}
return null;
}
if (!isPlainObject(responseFormat)) {
throw new Error("response_format must be an object when provided.");
}
const type =
typeof responseFormat.type === "string"
? responseFormat.type.toLowerCase()
: null;
if (type === "json_schema" || responseFormat.json_schema || responseFormat.schema) {
const schemaCandidate =
responseFormat?.json_schema?.schema ??
responseFormat?.schema ??
responseFormat?.json_schema;
if (!schemaCandidate) {
throw new Error(
"response_format.json_schema.schema must be provided for type=json_schema.",
);
}
return ensureJsonSchemaObject(
schemaCandidate,
"response_format.json_schema.schema",
);
}
if (type === "json_object") {
return { type: "object" };
}
if (type && type !== "text") {
throw new Error(`Unsupported response_format type "${responseFormat.type}".`);
}
if (responseFormat.schema) {
return ensureJsonSchemaObject(responseFormat.schema, "response_format.schema");
}
return null;
}
function ensureJsonSchemaObject(candidate, label = "output schema") {
if (!isPlainObject(candidate)) {
throw new Error(`${label} must be a JSON object.`);
}
return candidate;
}
function isPlainObject(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
async function normalizeMessages(messages) {
if (!Array.isArray(messages)) return [];
const normalized = [];
for (let i = 0; i < messages.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
normalized.push(await normalizeMessageEntry(messages[i], i));
}
return normalized;
}
async function normalizeMessageEntry(entry, index) {
if (!entry || typeof entry !== "object") {
return { role: null, text: null, attachments: [] };
}
const role =
typeof entry.role === "string" ? entry.role.trim().toLowerCase() : null;
const text = extractTextContent(entry);
const attachments = await extractImageAttachments(entry, index);
return { role, text, attachments };
}
function extractTextContent(entry) {
if (typeof entry?.content === "string") return entry.content;
if (!Array.isArray(entry?.content)) return null;
const textBlocks = entry.content
.filter((block) => block?.type === "text" && block?.text)
.map((block) => block.text);
if (textBlocks.length === 0) return null;
return textBlocks.join("\n");
}
async function extractImageAttachments(entry, index) {
if (!Array.isArray(entry?.content)) return [];
const attachments = [];
for (const block of entry.content) {
// eslint-disable-next-line no-await-in-loop
const resolved = await resolveImageBlock(block, index);
if (resolved) attachments.push(resolved);
}
return attachments;
}
async function resolveImageBlock(block, index) {
if (!block || typeof block !== "object") return null;
const type = block.type;
if (type === "local_image") {
const candidate =
typeof block.path === "string"
? block.path
: typeof block.image_path === "string"
? block.image_path
: null;
if (!candidate) {
throw new Error(`Message ${index + 1} local_image block is missing path.`);
}
return { path: resolveImagePath(candidate) };
}
if (type === "image_url" || type === "input_image") {
const candidate =
typeof block.image_url?.url === "string"
? block.image_url.url
: typeof block.url === "string"
? block.url
: null;
if (!candidate) {
throw new Error(`Message ${index + 1} image_url block is missing url.`);
}
return resolveImageUrlReference(candidate);
}
return null;
}
function resolveImagePath(value) {
if (typeof value !== "string") {
throw new Error("Image reference must be a string path or URL.");
}
const trimmed = value.trim();
if (!trimmed) {
throw new Error("Image reference cannot be empty.");
}
if (path.isAbsolute(trimmed)) {
return path.normalize(trimmed);
}
if (/^[a-z]+:\/\//i.test(trimmed)) {
const scheme = trimmed.split(":")[0].toLowerCase();
if (scheme !== "file") {
throw new Error(
"Only file:// URLs, HTTP(S) URLs, or local file paths are supported for images.",
);
}
try {
return fileURLToPath(trimmed);
} catch {
throw new Error("Invalid file:// URL provided for image attachment.");
}
}
if (/^[a-z]+:/i.test(trimmed)) {
throw new Error(
"Only file:// URLs, HTTP(S) URLs, or local file paths are supported for images.",
);
}
const baseDir = WORKING_DIRECTORY ?? process.cwd();
return path.resolve(baseDir, trimmed);
}
async function resolveImageUrlReference(value) {
if (typeof value !== "string") {
throw new Error("Image reference must be a string path or URL.");
}
const trimmed = value.trim();
if (!trimmed) {
throw new Error("Image reference cannot be empty.");
}
if (trimmed.startsWith("data:")) {
return createTempFileFromDataUrl(trimmed);
}
if (/^https?:\/\//i.test(trimmed)) {
return downloadImageToTempFile(trimmed);
}
return { path: resolveImagePath(trimmed) };
}
async function createTempFileFromDataUrl(dataUrl) {
const match = /^data:(?<mime>[^;]+);base64,(?<payload>.+)$/i.exec(dataUrl);
if (!match?.groups?.payload) {
throw new Error("Invalid data URL provided for image attachment.");
}
const mime = match.groups.mime;
const base64 = match.groups.payload.replace(/\s+/g, "");
const buffer = Buffer.from(base64, "base64");
return writeTempImageFile(buffer, inferExtensionFromMime(mime));
}
async function downloadImageToTempFile(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to download image from ${url} (status ${response.status}).`,
);
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
const contentType = response.headers.get("content-type");
return writeTempImageFile(buffer, inferExtensionFromMime(contentType));
}
async function writeTempImageFile(buffer, extension = ".png") {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "codex-bridge-image-"));
const safeExtension = extension.startsWith(".") ? extension : `.${extension}`;
const filePath = path.join(dir, `attachment${safeExtension}`);
await fs.writeFile(filePath, buffer);
const cleanup = async () => {
try {
await fs.rm(dir, { recursive: true, force: true });
} catch (error) {
console.warn("Failed to remove temporary image directory:", error);
}
};
return { path: filePath, cleanup };
}
function inferExtensionFromMime(mime) {
if (!mime) return ".png";
const normalized = mime.toLowerCase();
if (normalized.includes("png")) return ".png";
if (normalized.includes("jpeg") || normalized.includes("jpg")) return ".jpg";
if (normalized.includes("gif")) return ".gif";
if (normalized.includes("webp")) return ".webp";
if (normalized.includes("bmp")) return ".bmp";
return ".png";
}
function collectAttachmentCleanups(messages) {
const cleanups = [];
if (!Array.isArray(messages)) return cleanups;
for (const entry of messages) {
if (!Array.isArray(entry?.attachments)) continue;
for (const attachment of entry.attachments) {
if (typeof attachment?.cleanup === "function") {
cleanups.push(attachment.cleanup);
}
}
}
return cleanups;
}
async function cleanupAttachmentFiles(cleanups) {
if (!Array.isArray(cleanups) || cleanups.length === 0) return;
await Promise.all(
cleanups.map(async (cleanup) => {
try {
await cleanup();
} catch (error) {
console.warn("Failed to cleanup temporary attachment:", error);
}
}),
);
}
async function fileExists(targetPath) {
try {
await fs.access(targetPath);
return true;
} catch {
return false;
}
}
async function buildDashboardSnapshot() {
const account = await readAccountMetadata();
return {
generatedAt: new Date().toISOString(),
account,
stats: {
totalRequests: requestCounter,
activeSessions: persistedThreadIds.size,
uptimeSeconds: Math.floor((Date.now() - APP_START) / 1000),
sandboxMode: SANDBOX_MODE ?? "default",
approvalPolicy: APPROVAL_POLICY ?? "never",
networkAccess: Boolean(NETWORK_ACCESS),
webSearch: Boolean(WEB_SEARCH),
version: APP_VERSION,
},
tokens: Array.isArray(account?.tokens) ? account.tokens : [],
};
}
async function readAccountMetadata() {
const auth = await readJsonFile(CODEX_AUTH_FILE);
if (!auth) {
return {
status: "missing",
source: CODEX_AUTH_FILE,
};
}
const tokens = auth?.tokens ?? {};
const idToken =
tokens?.id_token ??
tokens?.idToken ??
auth?.id_token ??
auth?.idToken ??
null;
const accessToken =
tokens?.access_token ??
tokens?.accessToken ??
auth?.access_token ??
null;
const idPayload = idToken ? decodeJwtPayload(idToken) : null;
const accessPayload = accessToken ? decodeJwtPayload(accessToken) : null;
const issuedAt = unixToIso(accessPayload?.iat ?? idPayload?.iat);
const expiresAt = unixToIso(accessPayload?.exp ?? idPayload?.exp);
const status = deriveStatus(accessPayload?.exp ?? idPayload?.exp);
const tokenMeta = [];
if (accessToken) {
tokenMeta.push({
type: "Access Token",
email:
accessPayload?.["https://api.openai.com/profile"]?.email ??
accessPayload?.email ??
null,
issuer: accessPayload?.iss ?? null,
issuedAt: unixToIso(accessPayload?.iat),
expiresAt: unixToIso(accessPayload?.exp),
status: deriveStatus(accessPayload?.exp),
preview: formatTokenPreview(accessToken),
scopes: accessPayload?.scope ?? tokens?.scope ?? tokens?.scopes ?? null,
audience: Array.isArray(accessPayload?.aud)
? accessPayload.aud.join(", ")
: accessPayload?.aud ?? null,
});
}
return {
status,
email:
idPayload?.email ??
accessPayload?.["https://api.openai.com/profile"]?.email ??
auth?.email ??
null,
issuer: idPayload?.iss ?? accessPayload?.iss ?? null,
accountId: tokens?.account_id ?? auth?.account_id ?? null,
subject: idPayload?.sub ?? accessPayload?.sub ?? null,
issuedAt,
expiresAt,
device: auth?.device?.name ?? auth?.device_id ?? null,
source: CODEX_AUTH_FILE,
tokens: tokenMeta,
};
}
function decodeJwtPayload(token) {
try {
const parts = token.split(".");
if (parts.length !== 3) return null;
const payload = parts[1];
const normalized = payload.replace(/-/g, "+").replace(/_/g, "/");
const padded =
normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
const json = Buffer.from(padded, "base64").toString("utf8");
return JSON.parse(json);
} catch {
return null;
}
}
async function readJsonFile(targetPath) {
try {
const raw = await fs.readFile(targetPath, "utf8");
return JSON.parse(raw);
} catch {
return null;
}
}
function unixToIso(value) {
if (value === undefined || value === null) return null;
return new Date(value * 1000).toISOString();
}
function deriveStatus(exp) {
if (exp === undefined || exp === null) return "unknown";
return Date.now() > exp * 1000 ? "expired" : "active";
}
function formatTokenPreview(token) {
if (!token || token.length < 12) return token ?? null;
return `${token.slice(0, 12)}…${token.slice(-6)}`;
}
async function getOrCreateThread(sessionId, threadOptions) {
const cached = inMemoryThreads.get(sessionId);