Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
260 lines (223 loc) · 7.31 KB
/
Copy pathserver.js
File metadata and controls
260 lines (223 loc) · 7.31 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
import { pathToFileURL } from "node:url";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import express from "express";
import OpenAI from "openai";
import { FileConversationStore } from "./conversation-store.js";
import { runCodexExec } from "./codex-runner.js";
import { extractModelName, extractTokenCount } from "./token-usage.js";
const DEFAULT_MODEL = "gpt-5.5";
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
const PUBLIC_DIR = join(MODULE_DIR, "public");
const DATA_FILE = join(MODULE_DIR, "data", "conversations.json");
function isAuthorized(req, token) {
return (req.get("Authorization") ?? "") === `Bearer ${token}`;
}
function requireCodexToken(req, res, token) {
if (!token) {
res.status(503).json({ error: "CODEX_API_TOKEN is not configured" });
return false;
}
if (!isAuthorized(req, token)) {
res.status(401).json({ error: "Unauthorized" });
return false;
}
return true;
}
function pad2(value) {
return String(value).padStart(2, "0");
}
function getApiCallBucketTitle(now) {
const bucketMinute = now.getMinutes() < 30 ? 0 : 30;
return [
"API Calls",
`${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}`,
`${pad2(now.getHours())}:${pad2(bucketMinute)}`,
].join(" ");
}
function normalizeUser(user) {
if (typeof user !== "string") {
return "default";
}
const normalized = user.trim();
return normalized || "default";
}
async function getApiCallsConversation(store, now, user) {
const normalizedUser = normalizeUser(user);
const title = getApiCallBucketTitle(now);
const conversations = await store.list();
const existing = conversations.find(
(conversation) =>
conversation.title === title && conversation.user === normalizedUser,
);
if (existing) {
return store.get(existing.id);
}
return store.create(title, normalizedUser);
}
export function createApp(options = {}) {
const app = express();
app.use(express.json());
const apiKey = options.apiKey ?? process.env.OPENAI_API_KEY ?? "";
const client = options.client ?? (apiKey ? new OpenAI({ apiKey }) : null);
const codexApiToken = options.codexApiToken ?? process.env.CODEX_API_TOKEN ?? "";
const codexRunner = options.codexRunner ?? runCodexExec;
const conversationStore =
options.conversationStore ?? new FileConversationStore(DATA_FILE);
const now = options.now ?? (() => new Date());
app.use("/assets", express.static(PUBLIC_DIR));
app.get("/", (_req, res) => {
res.sendFile(join(PUBLIC_DIR, "index.html"));
});
app.get("/health", (_req, res) => {
res.json({ ok: true });
});
app.post("/chat", async (req, res) => {
if (!apiKey) {
res.status(503).json({ error: "OPENAI_API_KEY is not configured" });
return;
}
const message = req.body?.message;
if (typeof message !== "string" || !message.trim()) {
res.status(400).json({ error: "message is required" });
return;
}
try {
const response = await client.responses.create({
model: options.model ?? DEFAULT_MODEL,
input: message,
});
res.json({ text: response.output_text });
} catch (error) {
res.status(502).json({
error: "OpenAI request failed",
detail: error instanceof Error ? error.message : String(error),
});
}
});
app.post("/codex", async (req, res) => {
if (!requireCodexToken(req, res, codexApiToken)) {
return;
}
const prompt = req.body?.prompt;
if (typeof prompt !== "string" || !prompt.trim()) {
res.status(400).json({ error: "prompt is required" });
return;
}
const input = {
prompt,
model: req.body?.model,
sandbox: req.body?.sandbox,
cwd: req.body?.cwd,
timeoutMs: req.body?.timeoutMs,
};
for (const [key, value] of Object.entries(input)) {
if (value === undefined) {
delete input[key];
}
}
const result = await codexRunner(input);
const user = normalizeUser(req.body?.user);
const conversation = await getApiCallsConversation(conversationStore, now(), user);
await conversationStore.addMessage(conversation.id, {
role: "user",
content: prompt,
source: "api",
user,
});
await conversationStore.addMessage(conversation.id, {
role: "assistant",
content: result.stdout || result.stderr || "",
source: "api",
user,
model: extractModelName(result) || input.model || "default",
tokenCount: extractTokenCount(result),
meta: result,
});
const status = result.exitCode === 0 && !result.timedOut ? 200 : 502;
res.status(status).json(result);
});
app.get("/api/conversations", async (req, res) => {
if (!requireCodexToken(req, res, codexApiToken)) {
return;
}
res.json({ conversations: await conversationStore.list() });
});
app.post("/api/conversations", async (req, res) => {
if (!requireCodexToken(req, res, codexApiToken)) {
return;
}
const conversation = await conversationStore.create(req.body?.title);
res.status(201).json(conversation);
});
app.get("/api/conversations/:id", async (req, res) => {
if (!requireCodexToken(req, res, codexApiToken)) {
return;
}
const conversation = await conversationStore.get(req.params.id);
if (!conversation) {
res.status(404).json({ error: "Conversation not found" });
return;
}
res.json({ conversation });
});
app.delete("/api/conversations/:id", async (req, res) => {
if (!requireCodexToken(req, res, codexApiToken)) {
return;
}
const deleted = await conversationStore.delete(req.params.id);
if (!deleted) {
res.status(404).json({ error: "Conversation not found" });
return;
}
res.status(204).end();
});
app.post("/api/conversations/:id/messages", async (req, res) => {
if (!requireCodexToken(req, res, codexApiToken)) {
return;
}
const prompt = req.body?.prompt;
if (typeof prompt !== "string" || !prompt.trim()) {
res.status(400).json({ error: "prompt is required" });
return;
}
const userConversation = await conversationStore.addMessage(req.params.id, {
role: "user",
content: prompt,
});
if (!userConversation) {
res.status(404).json({ error: "Conversation not found" });
return;
}
const input = {
prompt,
model: req.body?.model,
sandbox: req.body?.sandbox,
cwd: req.body?.cwd,
timeoutMs: req.body?.timeoutMs,
};
for (const [key, value] of Object.entries(input)) {
if (value === undefined) {
delete input[key];
}
}
const result = await codexRunner(input);
const content = result.stdout || result.stderr || "";
const conversation = await conversationStore.addMessage(req.params.id, {
role: "assistant",
content,
model: extractModelName(result) || input.model || "default",
tokenCount: extractTokenCount(result),
meta: result,
});
const status = result.exitCode === 0 && !result.timedOut ? 200 : 502;
res.status(status).json({ conversation, result });
});
return app;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const port = Number(process.env.PORT ?? 3000);
createApp().listen(port, () => {
console.log(`API listening on http://localhost:${port}`);
});
}