-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcodex-bridge.ts
More file actions
2624 lines (2467 loc) · 75.4 KB
/
codex-bridge.ts
File metadata and controls
2624 lines (2467 loc) · 75.4 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
// @ts-nocheck
import { execFile as execFileCallback, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { join, normalize } from "node:path";
import { createInterface } from "node:readline";
import { promisify } from "node:util";
import { Codex } from "@openai/codex-sdk";
const execFile = promisify(execFileCallback);
const DEFAULT_STATUS = {
state: "idle",
serverUrl: null,
serverVersion: null,
error: null,
lastEventAt: null,
};
const CODEX_VALID_VARIANTS = ["none", "minimal", "low", "medium", "high", "xhigh"];
const DEFAULT_MODEL_ID = "gpt-5.4";
const DEFAULT_PROVIDER_ID = "openai";
const CODEX_APP_SERVER_TIMEOUT_MS = 8_000;
const CODEX_PROVIDER_CACHE_TTL_MS = 60_000;
const STATIC_CODEX_MODEL_SPECS = [
{
id: "gpt-5.5",
name: "GPT-5.5",
reasoning: true,
image: true,
releaseDate: "2026-04-29",
},
{
id: "gpt-5.4",
name: "GPT-5.4",
reasoning: true,
image: true,
releaseDate: "2026-04-01",
},
{
id: "gpt-5.4-mini",
name: "GPT-5.4 Mini",
reasoning: true,
image: true,
releaseDate: "2026-04-01",
},
{
id: "gpt-5.4-nano",
name: "GPT-5.4 Nano",
reasoning: false,
image: true,
releaseDate: "2026-04-01",
},
{
id: "gpt-5",
name: "GPT-5",
reasoning: true,
image: true,
},
{
id: "gpt-5-mini",
name: "GPT-5 Mini",
reasoning: true,
image: true,
},
{
id: "gpt-5-nano",
name: "GPT-5 Nano",
reasoning: false,
image: true,
},
{
id: "gpt-5-codex",
name: "GPT-5 Codex",
reasoning: true,
image: true,
status: "deprecated",
},
{
id: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
reasoning: true,
image: true,
releaseDate: "2026-03-01",
},
{
id: "gpt-5.2",
name: "GPT-5.2",
reasoning: true,
image: true,
},
{
id: "gpt-5.2-mini",
name: "GPT-5.2 Mini",
reasoning: true,
image: true,
},
{
id: "gpt-5.2-codex",
name: "GPT-5.2 Codex",
reasoning: true,
image: true,
status: "deprecated",
},
{
id: "codex-mini-latest",
name: "Codex Mini Latest",
reasoning: true,
image: true,
status: "deprecated",
},
];
const STATIC_CODEX_MODELS = Object.fromEntries(
STATIC_CODEX_MODEL_SPECS.map((spec) => [
spec.id,
makeModel(spec.id, spec.name, {
reasoning: spec.reasoning,
image: spec.image,
releaseDate: spec.releaseDate,
status: spec.status,
}),
]),
);
const STATIC_CODEX_PROVIDER = {
providers: [
{
id: DEFAULT_PROVIDER_ID,
name: "OpenAI",
source: "api",
env: ["CODEX_API_KEY", "OPENAI_API_KEY"],
options: {},
models: STATIC_CODEX_MODELS,
},
],
default: {
[DEFAULT_PROVIDER_ID]: DEFAULT_MODEL_ID,
},
};
let codexProviderCache = {
expiresAt: 0,
promise: null,
value: null,
};
function makeModel(
id,
name,
{ reasoning, image, releaseDate, status = "active", variants = null, context, output },
) {
return {
id,
providerID: DEFAULT_PROVIDER_ID,
api: {
id,
url: "https://api.openai.com",
npm: "@openai/codex-sdk",
},
name,
family: id,
capabilities: {
temperature: false,
reasoning,
attachment: image,
toolcall: true,
input: {
text: true,
audio: false,
image,
video: false,
pdf: false,
},
output: {
text: true,
audio: false,
image: false,
video: false,
pdf: false,
},
interleaved: false,
},
cost: {
input: 0,
output: 0,
cache: { read: 0, write: 0 },
},
limit: {
context: Number.isFinite(context) ? context : 200_000,
output: Number.isFinite(output) ? output : 8_192,
},
status,
options: {},
headers: {},
release_date: releaseDate,
variants: variants ?? undefined,
};
}
function titleCaseVariant(value) {
if (value === "xhigh") return "Extra High";
if (value === "none") return "None";
return value.charAt(0).toUpperCase() + value.slice(1);
}
function normalizeReasoningEfforts(value) {
if (!Array.isArray(value)) return [];
const efforts = [];
for (const entry of value) {
const effort =
typeof entry === "string"
? entry
: typeof entry?.reasoningEffort === "string"
? entry.reasoningEffort
: null;
if (!effort || efforts.includes(effort)) continue;
efforts.push(effort);
}
return efforts;
}
function humanizeModelId(id) {
return id
.replace(/^gpt/i, "GPT")
.replace(/-([a-z])/g, (_match, char) => ` ${char.toUpperCase()}`);
}
function buildVariantsFromReasoningEfforts(efforts, defaultEffort) {
if (!efforts.length) return {};
const ordered =
typeof defaultEffort === "string" && efforts.includes(defaultEffort)
? [defaultEffort, ...efforts.filter((effort) => effort !== defaultEffort)]
: efforts;
return Object.fromEntries(
ordered.map((effort) => [
effort,
{
label: titleCaseVariant(effort),
},
]),
);
}
function mapCodexAppServerModel(model) {
if (!model || typeof model !== "object") return null;
if (model.hidden === true) return null;
const id =
typeof model.model === "string" ? model.model : typeof model.id === "string" ? model.id : null;
if (!id) return null;
const fallback = STATIC_CODEX_MODELS[id];
const efforts = normalizeReasoningEfforts(model.supportedReasoningEfforts);
const variants = buildVariantsFromReasoningEfforts(efforts, model.defaultReasoningEffort);
const reasoning = efforts.length > 0 ? efforts.some((effort) => effort !== "none") : true;
const image = fallback?.capabilities?.input?.image ?? true;
const name =
typeof model.displayName === "string" && model.displayName.trim()
? model.displayName.trim()
: (fallback?.name ?? humanizeModelId(id));
return makeModel(id, name, {
reasoning,
image,
releaseDate: fallback?.release_date,
status:
typeof model.deprecationState === "string" && model.deprecationState !== "active"
? "deprecated"
: (fallback?.status ?? "active"),
variants,
context:
typeof model.contextWindow === "number"
? model.contextWindow
: typeof model.modelContextWindow === "number"
? model.modelContextWindow
: fallback?.limit?.context,
output:
typeof model.maxOutputTokens === "number" ? model.maxOutputTokens : fallback?.limit?.output,
});
}
function selectDefaultModelId(models) {
if (models["gpt-5.5"]) return "gpt-5.5";
if (models[DEFAULT_MODEL_ID]) return DEFAULT_MODEL_ID;
return Object.keys(models)[0] ?? DEFAULT_MODEL_ID;
}
function buildCodexProviderFromModels(models) {
const defaultModelId = selectDefaultModelId(models);
return {
providers: [
{
...STATIC_CODEX_PROVIDER.providers[0],
models,
},
],
default: {
[DEFAULT_PROVIDER_ID]: defaultModelId,
},
};
}
function getCodexExecutable() {
return process.env.CODEX_EXECUTABLE?.trim() || "codex";
}
function createCodexClient(options = {}) {
return new Codex({
...options,
codexPathOverride: getCodexExecutable(),
});
}
async function withCodexAppServer(requestWork) {
const env = pickCodexEnv(process.env);
const executable = getCodexExecutable();
return await new Promise((resolve, reject) => {
const child = spawn(executable, ["app-server"], {
env,
stdio: ["pipe", "pipe", "pipe"],
});
const rl = createInterface({
input: child.stdout,
crlfDelay: Infinity,
});
let settled = false;
let nextId = 1;
let stderr = "";
const pending = new Map();
const cleanup = () => {
for (const entry of pending.values()) {
clearTimeout(entry.timer);
}
pending.clear();
rl.close();
if (!child.killed) {
try {
child.kill();
} catch {}
}
};
const settleResolve = (value) => {
if (settled) return;
settled = true;
cleanup();
resolve(value);
};
const settleReject = (error) => {
if (settled) return;
settled = true;
cleanup();
reject(error);
};
const request = (method, params = {}) =>
new Promise((resolveRequest, rejectRequest) => {
const id = nextId++;
const timer = setTimeout(() => {
pending.delete(id);
rejectRequest(new Error(`Codex app-server request timed out: ${method}`));
}, CODEX_APP_SERVER_TIMEOUT_MS);
pending.set(id, { resolve: resolveRequest, reject: rejectRequest, timer });
child.stdin.write(`${JSON.stringify({ id, method, params })}\n`);
});
rl.on("line", (line) => {
if (!line.trim()) return;
let message;
try {
message = JSON.parse(line);
} catch {
return;
}
if (typeof message?.id !== "number") return;
const entry = pending.get(message.id);
if (!entry) return;
pending.delete(message.id);
clearTimeout(entry.timer);
if (message.error) {
entry.reject(new Error(message.error?.message || `Codex app-server error: ${message.id}`));
return;
}
entry.resolve(message.result);
});
child.stderr.on("data", (chunk) => {
stderr += String(chunk);
});
child.once("error", (error) => {
settleReject(error);
});
child.once("exit", (code, signal) => {
if (settled) return;
settleReject(
new Error(
`Codex app-server exited early (${signal ?? code ?? "unknown"}): ${stderr.trim() || "no stderr"}`,
),
);
});
void (async () => {
try {
await request("initialize", {
clientInfo: {
name: "opengui_desktop",
title: "OpenGUI",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
});
child.stdin.write(`${JSON.stringify({ method: "initialized", params: {} })}\n`);
const result = await requestWork({ request });
settleResolve(result);
} catch (error) {
settleReject(error);
}
})();
});
}
function codexTimestampToMs(value) {
if (!Number.isFinite(value)) return Date.now();
return value > 10_000_000_000 ? value : value * 1000;
}
function normalizeCodexAppServerThread(thread, workspaceId) {
const createdAt = codexTimestampToMs(thread?.createdAt);
const updatedAt = codexTimestampToMs(thread?.updatedAt ?? thread?.createdAt);
const directory = normalizeDir(thread?.cwd) || "";
const title = firstLine(thread?.name || thread?.preview || "").slice(0, 80) || "Untitled";
return {
id: thread.id,
slug: thread.id,
projectID: directory,
workspaceID: workspaceId,
directory,
title,
version: "codex",
time: {
created: createdAt,
updated: updatedAt,
},
};
}
function appServerUserText(item) {
const content = Array.isArray(item?.content) ? item.content : [];
return content
.map((entry) => {
if (typeof entry?.text === "string") return entry.text;
if (Array.isArray(entry?.text_elements)) {
return entry.text_elements.map((el) => el?.text || "").join("");
}
return "";
})
.filter(Boolean)
.join("\n\n")
.trim();
}
function appServerItemText(item) {
if (typeof item?.text === "string") return item.text;
if (typeof item?.message === "string") return item.message;
if (Array.isArray(item?.content)) return appServerUserText(item);
return "";
}
function appServerReasoningText(item) {
const chunks = [];
const collect = (value) => {
if (typeof value === "string" && value.trim()) chunks.push(value);
else if (Array.isArray(value)) {
for (const entry of value) collect(entry?.text ?? entry?.summary ?? entry?.content ?? entry);
} else if (value && typeof value === "object") {
collect(value.text ?? value.summary ?? value.content);
}
};
collect(item?.summary);
collect(item?.content);
return chunks.join("\n\n").trim();
}
function appServerStatusToCodexStatus(status) {
if (status === "inProgress") return "in_progress";
if (status === "declined") return "failed";
return status || "completed";
}
function normalizeAppServerItem(item, existing = {}) {
if (!item || typeof item !== "object") return null;
const id = item.id || existing.id || randomUUID();
if (item.type === "agentMessage" || item.type === "assistantMessage") {
return { id, type: "agent_message", text: appServerItemText(item) || existing.text || "" };
}
if (item.type === "reasoning") {
return { id, type: "reasoning", text: appServerReasoningText(item) || existing.text || "" };
}
if (item.type === "commandExecution") {
return {
id,
type: "command_execution",
command: item.command || existing.command || "",
aggregated_output: item.aggregatedOutput ?? existing.aggregated_output ?? "",
exit_code: item.exitCode ?? existing.exit_code ?? null,
status: appServerStatusToCodexStatus(item.status ?? existing.status),
};
}
if (item.type === "fileChange") {
return {
id,
type: "file_change",
changes: item.changes ?? existing.changes ?? [],
status: appServerStatusToCodexStatus(item.status ?? existing.status),
};
}
if (item.type === "mcpToolCall") {
return {
id,
type: "mcp_tool_call",
server: item.server ?? existing.server ?? "mcp",
tool: item.tool ?? existing.tool ?? "tool",
arguments: item.arguments ?? existing.arguments ?? {},
result: item.result ?? existing.result,
error: item.error ?? existing.error,
status: appServerStatusToCodexStatus(item.status ?? existing.status),
};
}
if (item.type === "webSearch") {
return {
id,
type: "web_search",
query: item.query ?? existing.query ?? item.action?.query ?? "",
status: appServerStatusToCodexStatus(item.status ?? existing.status),
};
}
if (item.type === "plan") {
return { id, type: "reasoning", text: item.text || existing.text || "" };
}
return { id, type: item.type || "item", text: appServerItemText(item) || existing.text || "" };
}
function buildMessagesFromCodexAppServerThread(thread) {
const sessionId = thread.id;
const directory = normalizeDir(thread.cwd) || "";
const modelId = thread.model || thread.modelId || DEFAULT_MODEL_ID;
const messages = [];
let seq = 0;
for (const turn of Array.isArray(thread.turns) ? thread.turns : []) {
const createdAt = codexTimestampToMs(turn.startedAt ?? thread.createdAt);
for (const item of Array.isArray(turn.items) ? turn.items : []) {
const type = item?.type;
if (type === "userMessage") {
const text = appServerUserText(item);
if (!text) continue;
const messageId = item.id || `${turn.id}:user:${seq++}`;
messages.push({
info: defaultUserInfo(sessionId, messageId, modelId, undefined, createdAt),
parts: [makeTextPart(sessionId, messageId, `${messageId}:text`, text, true)],
});
continue;
}
if (type === "agentMessage" || type === "assistantMessage" || type === "reasoning") {
const text = appServerItemText(item);
if (!text) continue;
const messageId = item.id || `${turn.id}:assistant:${seq++}`;
const info = defaultAssistantInfo(
sessionId,
messageId,
directory,
modelId,
undefined,
createdAt,
);
messages.push({
info,
parts:
type === "reasoning"
? [makeReasoningPart(sessionId, messageId, `${messageId}:reasoning`, text, createdAt)]
: [makeTextPart(sessionId, messageId, `${messageId}:text`, text, true)],
});
}
}
}
return messages;
}
async function listCodexAppServerSessions(target = {}) {
const workspaceId = target.workspaceId ?? "local";
if (target.workspaceId !== undefined && target.workspaceId !== "local") return [];
return await withCodexAppServer(async ({ request }) => {
const sessions = [];
let cursor = undefined;
do {
const response = await request("thread/list", {
limit: 100,
sortKey: "updated_at",
sortDirection: "desc",
...(cursor ? { cursor } : {}),
});
for (const thread of Array.isArray(response?.data) ? response.data : []) {
if (!thread?.id) continue;
const session = normalizeCodexAppServerThread(thread, workspaceId);
if (target.directory && normalizeDir(session.directory) !== normalizeDir(target.directory))
continue;
sessions.push(session);
}
cursor =
typeof response?.nextCursor === "string" && response.nextCursor
? response.nextCursor
: undefined;
} while (cursor);
return sessions;
});
}
async function readCodexAppServerMessages(sessionId) {
return await withCodexAppServer(async ({ request }) => {
const response = await request("thread/read", {
threadId: sessionId,
includeTurns: true,
});
return buildMessagesFromCodexAppServerThread(response?.thread ?? { id: sessionId, turns: [] });
});
}
async function fetchCodexProviderFromAppServer() {
return await withCodexAppServer(async ({ request }) => {
await request("account/read", {}).catch(() => null);
const models = {};
let cursor = undefined;
do {
const response = await request("model/list", cursor ? { cursor } : {});
for (const rawModel of Array.isArray(response?.data) ? response.data : []) {
const model = mapCodexAppServerModel(rawModel);
if (!model) continue;
models[model.id] = model;
}
cursor =
typeof response?.nextCursor === "string" && response.nextCursor
? response.nextCursor
: undefined;
} while (cursor);
return buildCodexProviderFromModels(
Object.keys(models).length > 0 ? models : STATIC_CODEX_MODELS,
);
});
}
async function getCodexProviderData() {
const now = Date.now();
if (codexProviderCache.value && codexProviderCache.expiresAt > now) {
return codexProviderCache.value;
}
if (codexProviderCache.promise) {
return codexProviderCache.promise;
}
codexProviderCache.promise = (async () => {
try {
const provider = await fetchCodexProviderFromAppServer();
codexProviderCache.value = provider;
codexProviderCache.expiresAt = Date.now() + CODEX_PROVIDER_CACHE_TTL_MS;
return provider;
} catch (error) {
console.warn("Failed to discover Codex models via app-server:", error);
codexProviderCache.value = STATIC_CODEX_PROVIDER;
codexProviderCache.expiresAt = Date.now() + CODEX_PROVIDER_CACHE_TTL_MS;
return STATIC_CODEX_PROVIDER;
} finally {
codexProviderCache.promise = null;
}
})();
return codexProviderCache.promise;
}
function getCodexModel(providerData, modelId) {
if (!providerData || !modelId) return null;
for (const provider of Array.isArray(providerData.providers) ? providerData.providers : []) {
const model = provider?.models?.[modelId];
if (model) return model;
}
return null;
}
async function resolveSupportedCodexVariant(model, variant) {
const normalized = resolveVariant(variant);
if (!normalized) return undefined;
const modelId = resolveSelectedModelId(model);
const providerData = await getCodexProviderData();
const codexModel = getCodexModel(providerData, modelId);
const variants = Object.keys(codexModel?.variants ?? {}).filter(
(key) => !codexModel?.variants?.[key]?.disabled,
);
if (variants.length === 0) return undefined;
return variants.includes(normalized) ? normalized : undefined;
}
function normalizeDir(directory) {
if (typeof directory !== "string") return "";
const trimmed = directory.trim();
if (!trimmed) return "";
return normalize(trimmed);
}
function makeProjectKey(workspaceId, directory) {
return `${workspaceId ?? "local"}:${normalizeDir(directory)}`;
}
function ok(data) {
return { success: true, data };
}
function fail(error, data) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
data,
};
}
function nowConnection(status = {}) {
return {
...DEFAULT_STATUS,
...status,
lastEventAt: Date.now(),
};
}
const MAX_CODEX_SESSION_INDEX_ENTRIES = 1000;
function sessionStatus(type) {
return { type };
}
function firstLine(text) {
return (
String(text ?? "")
.trim()
.split(/\r?\n/, 1)[0] ?? ""
);
}
function makeSessionTitle(text, title) {
const explicit = typeof title === "string" ? title.trim() : "";
if (explicit) return explicit;
const line = firstLine(text);
return line.slice(0, 80) || "Untitled";
}
function resolveSelectedModelId(selectedModel) {
if (selectedModel?.modelID && typeof selectedModel.modelID === "string") {
return selectedModel.modelID;
}
return DEFAULT_MODEL_ID;
}
function resolveVariant(variant) {
if (typeof variant !== "string") return undefined;
return CODEX_VALID_VARIANTS.includes(variant) ? variant : undefined;
}
function defaultUserInfo(sessionId, messageId, modelId, variant, createdAt = Date.now()) {
return {
id: messageId,
sessionID: sessionId,
role: "user",
time: { created: createdAt },
agent: "codex",
model: {
providerID: DEFAULT_PROVIDER_ID,
modelID: modelId,
...(variant ? { variant } : {}),
},
};
}
function defaultAssistantInfo(
sessionId,
messageId,
directory,
modelId,
variant,
createdAt = Date.now(),
) {
return {
id: messageId,
sessionID: sessionId,
role: "assistant",
time: { created: createdAt },
parentID: "",
modelID: modelId,
providerID: DEFAULT_PROVIDER_ID,
mode: "codex",
agent: "codex",
path: {
cwd: directory,
root: directory,
},
cost: 0,
tokens: {
input: 0,
output: 0,
reasoning: 0,
cache: { read: 0, write: 0 },
},
...(variant ? { variant } : {}),
};
}
function makeTextPart(sessionId, messageId, partId, text, synthetic = false) {
return {
id: partId,
sessionID: sessionId,
messageID: messageId,
type: "text",
text,
...(synthetic ? { synthetic: true } : {}),
};
}
function makeReasoningPart(sessionId, messageId, partId, text, start = Date.now()) {
return {
id: partId,
sessionID: sessionId,
messageID: messageId,
type: "reasoning",
text,
time: { start },
};
}
function parseDataUrl(dataUrl) {
if (typeof dataUrl !== "string") return null;
const match = dataUrl.match(/^data:([^;,]+)?;base64,(.+)$/);
if (!match) return null;
return {
mimeType: match[1] || "application/octet-stream",
data: match[2],
};
}
function mimeToExtension(mimeType) {
switch (mimeType) {
case "image/png":
return ".png";
case "image/jpeg":
case "image/jpg":
return ".jpg";
case "image/gif":
return ".gif";
case "image/webp":
return ".webp";
default:
return ".bin";
}
}
function createUserImageParts(sessionId, messageId, images) {
return (Array.isArray(images) ? images : [])
.map((image, index) => {
const parsed = parseDataUrl(image);
if (!parsed) return null;
return {
id: randomUUID(),
sessionID: sessionId,
messageID: messageId,
type: "file",
mime: parsed.mimeType,
filename: `image-${index + 1}${mimeToExtension(parsed.mimeType)}`,
url: image,
};
})
.filter(Boolean);
}
function stringifyUnknown(value) {
if (typeof value === "string") return value;
if (value == null) return "";
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
function mcpContentToText(result) {
if (!result || !Array.isArray(result.content))
return stringifyUnknown(result?.structured_content);
const parts = [];
for (const block of result.content) {
if (!block || typeof block !== "object") continue;
if (block.type === "text" && typeof block.text === "string") {
parts.push(block.text);
continue;
}
if (block.type === "image") {
parts.push("[image]");
continue;
}
parts.push(stringifyUnknown(block));
}
const joined = parts.join("\n\n").trim();
return joined || stringifyUnknown(result?.structured_content);
}
function cloneJSON(value) {
return JSON.parse(JSON.stringify(value));
}
function sanitizeFileName(id) {
return encodeURIComponent(id).replace(/%/g, "_");
}
function makeStoragePaths(userData = join(homedir(), ".config", "OpenGUI")) {
const root = join(userData, "codex");
return {
root,
indexFile: join(root, "sessions.json"),
transcriptsDir: join(root, "transcripts"),
};
}
function buildCodexPath(source) {
const pathValue = typeof source?.PATH === "string" ? source.PATH : "";
const home = source?.HOME || homedir();
const candidates = [
join(home, ".local", "share", "pnpm"),
join(home, ".bun", "bin"),
join(home, ".local", "bin"),
join(home, ".npm-global", "bin"),
"/usr/local/bin",
"/opt/homebrew/bin",
];
const parts = pathValue.split(":").filter(Boolean);
for (const candidate of candidates) {
if (!parts.includes(candidate)) parts.push(candidate);
}
return parts.join(":");
}
function pickCodexEnv(source) {
const env = {};
const allow = new Set([
"PATH",
"HOME",
"USERPROFILE",
"SHELL",
"TMPDIR",
"TMP",
"TEMP",
"SSL_CERT_FILE",
]);
const codexAllow = new Set([
"CODEX_API_KEY",
"CODEX_BASE_URL",
"CODEX_HOME",
"CODEX_CONFIG_DIR",
"CODEX_EXECUTABLE",
"CODEX_MANAGED_BY_NPM",
]);
for (const [key, value] of Object.entries(source ?? {})) {
if (typeof value !== "string") continue;
if (
allow.has(key) ||
codexAllow.has(key) ||
key.startsWith("OPENAI_") ||
key === "HTTP_PROXY" ||
key === "HTTPS_PROXY" ||
key === "NO_PROXY"
) {
env[key] = value;
}
}
env.PATH = buildCodexPath(source);
return env;
}
function getMessageText(bundle) {
if (!bundle || !Array.isArray(bundle.parts)) return "";
return bundle.parts
.filter((part) => part?.type === "text" && typeof part.text === "string")
.map((part) => part.text)
.join("\n\n")
.trim();
}
function getSessionPreview(messages) {
for (let i = messages.length - 1; i >= 0; i -= 1) {
const text = getMessageText(messages[i]);
if (text) return firstLine(text).slice(0, 160);
}
return "";
}