Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
348 lines (334 loc) · 12.9 KB
/
Copy pathserver.js
File metadata and controls
348 lines (334 loc) · 12.9 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
const http = require("node:http");
const fs = require("node:fs");
const path = require("node:path");
const os = require("node:os");
const { CodexQuotaReader } = require("./quota-reader.cjs");
const root = __dirname;
const port = Number(process.env.TOKEN_MONITOR_PORT || 45731);
const configPath = path.join(root, "usage-config.json");
const defaultTimeZone = "Asia/Shanghai";
const officialTimeZone = defaultTimeZone;
function readConfig() {
try {
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
return {
paths: Array.isArray(config.paths) ? config.paths.filter(Boolean) : [],
timeZone: validTimeZone(config.timeZone) ? config.timeZone : defaultTimeZone,
};
} catch {
return { paths: [], timeZone: defaultTimeZone };
}
}
function validTimeZone(value) {
if (typeof value !== "string" || !value) return false;
try {
new Intl.DateTimeFormat("en-US", { timeZone: value }).format(new Date());
return true;
} catch {
return false;
}
}
function walkForUsage(dir, depth = 0, found = []) {
if (depth > 4 || !fs.existsSync(dir)) return found;
let entries;
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return found; }
for (const entry of entries) {
if (entry.name.startsWith(".")) continue;
const full = path.join(dir, entry.name);
if (entry.isFile() && /^codex-usage.*\.jsonl$/i.test(entry.name)) found.push(full);
if (entry.isDirectory() && !["node_modules", "cache", "sessions", "usage-test", "usage-test2"].includes(entry.name)) walkForUsage(full, depth + 1, found);
}
return found;
}
function candidatePaths() {
const configured = readConfig().paths.map((item) => path.resolve(root, item));
const roots = [
path.join(root, ".codex"),
process.env.CODEX_HOME,
path.join(os.homedir(), ".codex"),
].filter(Boolean).map((item) => path.resolve(item));
const discovered = roots.flatMap((item) => walkForUsage(item));
return [...new Set([...configured, ...discovered])].filter((item) => fs.existsSync(item));
}
function readRecords() {
const byTurn = new Map();
for (const file of candidatePaths()) {
let lines;
try { lines = fs.readFileSync(file, "utf8").split(/\r?\n/); } catch { continue; }
for (const line of lines) {
if (!line.trim()) continue;
try {
const record = JSON.parse(line);
if (!record.recorded_at || !record.turn_usage) continue;
const key = `${record.session_id || "unknown"}:${record.turn_id || record.recorded_at}`;
byTurn.set(key, { ...record, __file: file });
} catch {
// Ignore a partially written final JSONL line while a hook is appending.
}
}
}
return [...byTurn.values()].sort((a, b) => new Date(a.recorded_at) - new Date(b.recorded_at));
}
function number(value) { return Number.isFinite(Number(value)) ? Number(value) : 0; }
function usageOf(record) {
const usage = record.turn_usage || {};
return {
input: number(usage.input_tokens),
output: number(usage.output_tokens),
cached: number(usage.cached_input_tokens),
reasoning: number(usage.reasoning_output_tokens),
total: number(usage.total_tokens) || number(usage.input_tokens) + number(usage.output_tokens),
};
}
function add(a, b) {
return {
input: a.input + b.input,
output: a.output + b.output,
cached: a.cached + b.cached,
reasoning: a.reasoning + b.reasoning,
total: a.total + b.total,
};
}
function blank() { return { input: 0, output: 0, cached: 0, reasoning: 0, total: 0 }; }
function display(value) {
if (value >= 1000000) return `${(value / 1000000).toFixed(2).replace(/\.00$/, "")}M`;
if (value >= 1000) return `${(value / 1000).toFixed(1).replace(/\.0$/, "")}k`;
return String(Math.round(value));
}
function rangeItem(value, label) {
return {
label,
total: Math.round(value.total).toLocaleString("en-US"),
input: display(value.input),
output: display(value.output),
cached: display(value.cached),
reasoning: display(value.reasoning),
delta: "—",
raw: value,
};
}
function unavailableRange(label) {
return {
label,
total: "—",
input: "—",
output: "—",
cached: "—",
reasoning: "—",
delta: "—",
raw: { ...blank(), total: null },
unavailable: true,
};
}
function pendingRange(label) {
return {
...unavailableRange(label),
total: "待同步",
pending: true,
};
}
function totalRange(total, label) {
return total === null || total === undefined
? unavailableRange(label)
: rangeItem({ ...blank(), total: number(total) }, label);
}
const calendarFormatters = new Map();
function calendarParts(value, timeZone) {
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.valueOf())) return null;
let formatter = calendarFormatters.get(timeZone);
if (!formatter) {
formatter = new Intl.DateTimeFormat("en-US", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
});
calendarFormatters.set(timeZone, formatter);
}
const values = Object.fromEntries(
formatter.formatToParts(date)
.filter((item) => item.type !== "literal")
.map((item) => [item.type, Number(item.value)])
);
const year = values.year;
const month = values.month;
const day = values.day;
const ordinal = Date.UTC(year, month - 1, day);
return {
year,
month,
day,
ordinal,
key: `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`,
};
}
function buildPayload(now = new Date()) {
const records = readRecords();
const config = readConfig();
const timeZone = config.timeZone;
const currentDay = calendarParts(now, timeZone);
const todayOrdinal = currentDay.ordinal;
const weekStartOrdinal = todayOrdinal - 6 * 86400000;
const latest = records.at(-1);
const currentRequest = latest ? usageOf(latest) : blank();
let today = blank(); let week = blank(); let month = blank(); let lifetime = blank();
const dayBuckets = Array.from({ length: 7 }, (_, index) => {
const ordinal = weekStartOrdinal + index * 86400000;
const date = new Date(ordinal);
return {
ordinal,
date: date.toISOString().slice(0, 10),
label: index === 6 ? "今" : "日一二三四五六"[date.getUTCDay()],
total: 0,
today: index === 6,
};
});
for (const record of records) {
const value = usageOf(record);
lifetime = add(lifetime, value);
const recordDay = calendarParts(record.recorded_at, timeZone);
if (!recordDay) continue;
if (recordDay.ordinal === todayOrdinal) today = add(today, value);
if (recordDay.ordinal >= weekStartOrdinal && recordDay.ordinal <= todayOrdinal) {
week = add(week, value);
const bucket = dayBuckets[(recordDay.ordinal - weekStartOrdinal) / 86400000];
if (bucket) bucket.total += value.total;
}
if (recordDay.year === currentDay.year && recordDay.month === currentDay.month) month = add(month, value);
}
const lastResponse = latest?.last_response_usage || {};
const contextLimit = number(latest?.model_context_window) || 128000;
const contextUsed = number(lastResponse.total_tokens) || number(lastResponse.input_tokens) || number(latest?.turn_usage?.total_tokens);
const contextRemaining = Math.max(0, contextLimit - contextUsed);
const contextPercent = contextLimit ? Math.min(100, (contextUsed / contextLimit) * 100) : 0;
const contextRemainingPercent = contextLimit ? Math.min(100, (contextRemaining / contextLimit) * 100) : 0;
const sourceFiles = [...new Set(records.map((item) => item.__file))];
return {
ok: true,
records: records.length,
ranges: {
current: rangeItem(currentRequest, "本次请求总量"),
today: rangeItem(today, "今日本地总量"),
week: rangeItem(week, "近 7 天本地总量"),
month: rangeItem(month, "本月本地总量"),
lifetime: rangeItem(lifetime, "累计本地总量"),
},
request: rangeItem(currentRequest, "本次请求总量"),
current: rangeItem(currentRequest, "本次请求总量"),
context: {
used: contextUsed,
remaining: contextRemaining,
limit: contextLimit,
percent: contextPercent,
remainingPercent: contextRemainingPercent,
},
trend: dayBuckets,
timeZone,
timeZoneLabel: "北京时间",
updatedAt: latest?.recorded_at || null,
sourceLabel: sourceFiles.length ? "本地 Hook · 北京时间" : "等待本地 Hook 记录",
sourceFiles,
};
}
function buildOfficialPayload(snapshot, now = new Date(), timeZone = officialTimeZone) {
const currentDay = calendarParts(now, timeZone);
const todayOrdinal = currentDay.ordinal;
const weekStartOrdinal = todayOrdinal - 6 * 86400000;
const usage = snapshot?.data;
const hasUsage = Boolean(usage);
const byDate = new Map(
(Array.isArray(usage?.dailyUsageBuckets) ? usage.dailyUsageBuckets : [])
.map((item) => [item.startDate, number(item.tokens)])
);
const dayBuckets = Array.from({ length: 7 }, (_, index) => {
const ordinal = weekStartOrdinal + index * 86400000;
const date = new Date(ordinal);
const key = date.toISOString().slice(0, 10);
const pending = hasUsage && index === 6 && !byDate.has(key);
return {
ordinal,
date: key,
label: index === 6 ? "今" : "日一二三四五六"[date.getUTCDay()],
total: hasUsage ? pending ? null : number(byDate.get(key)) : null,
today: index === 6,
pending,
};
});
const todayKey = `${currentDay.year}-${String(currentDay.month).padStart(2, "0")}-${String(currentDay.day).padStart(2, "0")}`;
const monthPrefix = `${currentDay.year}-${String(currentDay.month).padStart(2, "0")}-`;
const todayPending = hasUsage && !byDate.has(todayKey);
const today = hasUsage && !todayPending ? number(byDate.get(todayKey)) : null;
const week = hasUsage ? dayBuckets.reduce((sum, item) => sum + number(item.total), 0) : null;
const month = hasUsage
? [...byDate.entries()].filter(([date]) => date.startsWith(monthPrefix)).reduce((sum, [, tokens]) => sum + tokens, 0)
: null;
const lifetime = hasUsage ? usage?.summary?.lifetimeTokens ?? null : null;
const status = snapshot?.status || "unavailable";
const reason = snapshot?.reason || null;
const sourceLabel = status === "stale"
? "Codex 官方统计 · 已缓存"
: status === "ready"
? "Codex 官方统计"
: status === "loading"
? "Codex 官方统计 · 读取中"
: reason === "codex_not_found"
? "未找到 Codex CLI"
: reason === "not_logged_in"
? "请先登录 Codex"
: reason === "unsupported_version"
? "请更新 Codex CLI"
: "Codex 官方统计 · 暂不可用";
return {
ok: hasUsage,
status,
reason,
records: usage?.dailyUsageBuckets?.length || 0,
ranges: {
today: todayPending ? pendingRange("今日官方总量") : totalRange(today, "今日官方总量"),
week: totalRange(week, "近 7 天官方总量"),
month: totalRange(month, "本月官方总量"),
lifetime: totalRange(lifetime, "累计官方总量"),
},
trend: dayBuckets,
timeZone,
timeZoneLabel: "北京时间",
updatedAt: snapshot?.updatedAt || null,
sourceLabel,
};
}
function buildMonitorPayload(account, now = new Date()) {
const local = buildPayload(now);
const official = buildOfficialPayload(account?.officialUsage, now);
return {
...local,
sources: { local, official },
quota: { status: account?.status, weekly: account?.weekly, updatedAt: account?.updatedAt },
};
}
const files = { "/": "index.html", "/index.html": "index.html", "/styles.css": "styles.css", "/app.js": "app.js" };
const contentTypes = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8" };
function startServer() {
const accountReader = new CodexQuotaReader();
accountReader.start();
const server = http.createServer((request, response) => {
const url = new URL(request.url, `http://${request.headers.host}`);
if (url.pathname === "/api/usage") {
const account = accountReader.getSnapshot();
const payload = buildMonitorPayload(account);
response.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
response.end(JSON.stringify(payload));
return;
}
const relative = files[url.pathname];
if (!relative) { response.writeHead(404); response.end("Not found"); return; }
const file = path.join(root, relative);
response.writeHead(200, { "Content-Type": contentTypes[path.extname(file)] || "application/octet-stream", "Cache-Control": "no-store" });
fs.createReadStream(file).on("error", () => response.end()).pipe(response);
});
server.listen(port, "127.0.0.1", () => console.log(`Token Monitor listening on http://127.0.0.1:${port}`));
server.on("close", () => accountReader.stop());
return server;
}
if (require.main === module) startServer();
module.exports = { buildMonitorPayload, buildOfficialPayload, buildPayload, calendarParts, startServer };