@aiusage/cli 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +138 -0
- package/dist/cli.js +1959 -0
- package/package.json +51 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1959 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { hostname as hostname3 } from "node:os";
|
|
6
|
+
|
|
7
|
+
// src/scanners/claude.ts
|
|
8
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
12
|
+
let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
|
|
13
|
+
for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
|
|
14
|
+
let baseDir = claudeDir ?? join(homedir(), ".claude", "projects"), projectDirs;
|
|
15
|
+
try {
|
|
16
|
+
projectDirs = await readdir(baseDir);
|
|
17
|
+
} catch {
|
|
18
|
+
return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
|
|
19
|
+
}
|
|
20
|
+
let deduped = /* @__PURE__ */ new Map();
|
|
21
|
+
for (let projDir of projectDirs) {
|
|
22
|
+
let projectPath = join(baseDir, projDir), project = resolveProject(projectPath, projectAliases), dirPath = join(baseDir, projDir), jsonlFiles = [];
|
|
23
|
+
try {
|
|
24
|
+
await walkForJsonl(dirPath, jsonlFiles);
|
|
25
|
+
} catch {
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
for (let filePath of jsonlFiles) {
|
|
29
|
+
let content;
|
|
30
|
+
try {
|
|
31
|
+
content = await readFile(filePath, "utf-8");
|
|
32
|
+
} catch {
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
for (let line of content.split(`
|
|
36
|
+
`)) {
|
|
37
|
+
if (!line.trim()) continue;
|
|
38
|
+
let record;
|
|
39
|
+
try {
|
|
40
|
+
record = JSON.parse(line);
|
|
41
|
+
} catch {
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
let ts = parseTimestamp(record.timestamp);
|
|
45
|
+
if (!ts) continue;
|
|
46
|
+
let usageDate = toDateKey(ts);
|
|
47
|
+
if (!targetDateSet.has(usageDate)) continue;
|
|
48
|
+
let message = record.message;
|
|
49
|
+
if (!message?.usage) continue;
|
|
50
|
+
let requestId = record.requestId ?? message.id ?? record.uuid;
|
|
51
|
+
if (!requestId) continue;
|
|
52
|
+
let usage = message.usage, model = message.model ?? "unknown", recordProject = record.cwd ? resolveProject(record.cwd, projectAliases) : project, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
|
|
53
|
+
cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
|
|
54
|
+
let dedupeKey = `${usageDate}|${requestId}`, existing = deduped.get(dedupeKey);
|
|
55
|
+
existing ? (existing.model = model, existing.inputTokens = Math.max(existing.inputTokens, usage.input_tokens ?? 0), existing.cacheWrite5mTokens = Math.max(existing.cacheWrite5mTokens, cache5m), existing.cacheWrite1hTokens = Math.max(existing.cacheWrite1hTokens, cache1h), existing.cachedInputTokens = Math.max(existing.cachedInputTokens, usage.cache_read_input_tokens ?? 0), existing.outputTokens = Math.max(existing.outputTokens, usage.output_tokens ?? 0)) : deduped.set(dedupeKey, {
|
|
56
|
+
model,
|
|
57
|
+
project: recordProject,
|
|
58
|
+
inputTokens: usage.input_tokens ?? 0,
|
|
59
|
+
cacheWrite5mTokens: cache5m,
|
|
60
|
+
cacheWrite1hTokens: cache1h,
|
|
61
|
+
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
|
|
62
|
+
outputTokens: usage.output_tokens ?? 0
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
for (let [dedupeKey, usage] of deduped.entries()) {
|
|
68
|
+
let [usageDate] = dedupeKey.split("|", 1), grouped = groupedByDate.get(usageDate);
|
|
69
|
+
if (!grouped) continue;
|
|
70
|
+
let cacheWriteTokens = usage.cacheWrite5mTokens + usage.cacheWrite1hTokens, key = `${usage.model}|${usage.project}`, existing = grouped.get(key);
|
|
71
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += usage.inputTokens, existing.cachedInputTokens += usage.cachedInputTokens, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + usage.cacheWrite5mTokens, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + usage.cacheWrite1hTokens, existing.outputTokens += usage.outputTokens) : grouped.set(key, {
|
|
72
|
+
provider: "anthropic",
|
|
73
|
+
product: "claude-code",
|
|
74
|
+
channel: "cli",
|
|
75
|
+
model: usage.model,
|
|
76
|
+
project: usage.project,
|
|
77
|
+
eventCount: 1,
|
|
78
|
+
inputTokens: usage.inputTokens,
|
|
79
|
+
cachedInputTokens: usage.cachedInputTokens,
|
|
80
|
+
cacheWriteTokens,
|
|
81
|
+
cacheWrite5mTokens: usage.cacheWrite5mTokens,
|
|
82
|
+
cacheWrite1hTokens: usage.cacheWrite1hTokens,
|
|
83
|
+
outputTokens: usage.outputTokens,
|
|
84
|
+
reasoningOutputTokens: 0
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return new Map(
|
|
88
|
+
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
function parseTimestamp(value) {
|
|
92
|
+
if (!value) return null;
|
|
93
|
+
try {
|
|
94
|
+
let d = new Date(value);
|
|
95
|
+
return isNaN(d.getTime()) ? null : d;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function toDateKey(date) {
|
|
101
|
+
let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
|
|
102
|
+
return `${year}-${month}-${day}`;
|
|
103
|
+
}
|
|
104
|
+
function extractProjectFromCwd(cwd) {
|
|
105
|
+
let parts = cwd.split("/").filter(Boolean);
|
|
106
|
+
return parts[parts.length - 1] || "unknown";
|
|
107
|
+
}
|
|
108
|
+
function resolveProject(rawPath, aliases) {
|
|
109
|
+
let project = extractProjectFromCwd(rawPath);
|
|
110
|
+
return aliases?.[rawPath] ?? aliases?.[project] ?? project;
|
|
111
|
+
}
|
|
112
|
+
async function walkForJsonl(dir, result) {
|
|
113
|
+
let entries = await readdir(dir, { withFileTypes: !0 });
|
|
114
|
+
for (let entry of entries) {
|
|
115
|
+
let fullPath = join(dir, entry.name);
|
|
116
|
+
entry.isDirectory() ? await walkForJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/scanners/codex.ts
|
|
121
|
+
import { readdir as readdir2, readFile as readFile2 } from "node:fs/promises";
|
|
122
|
+
import { join as join2 } from "node:path";
|
|
123
|
+
import { homedir as homedir2 } from "node:os";
|
|
124
|
+
async function scanCodexDates(targetDates, codexDir, projectAliases) {
|
|
125
|
+
let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
|
|
126
|
+
for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
|
|
127
|
+
let baseDir = codexDir ?? join2(homedir2(), ".codex"), sessionFiles = await collectSessionFiles(baseDir);
|
|
128
|
+
if (sessionFiles.length === 0)
|
|
129
|
+
return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
|
|
130
|
+
for (let filePath of sessionFiles) {
|
|
131
|
+
let content;
|
|
132
|
+
try {
|
|
133
|
+
content = await readFile2(filePath, "utf-8");
|
|
134
|
+
} catch {
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
let lines = content.split(`
|
|
138
|
+
`), currentModel = "unknown", currentProject = "unknown", lastTotalSignature = "";
|
|
139
|
+
for (let line of lines) {
|
|
140
|
+
if (!line.trim()) continue;
|
|
141
|
+
let record;
|
|
142
|
+
try {
|
|
143
|
+
record = JSON.parse(line);
|
|
144
|
+
} catch {
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (record.type === "turn_context") {
|
|
148
|
+
currentModel = record.payload?.model ?? currentModel, record.payload?.cwd && (currentProject = extractProject(record.payload.cwd, projectAliases));
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
|
|
152
|
+
let info = record.payload?.info;
|
|
153
|
+
if (!info?.last_token_usage || !info?.total_token_usage) continue;
|
|
154
|
+
let ts = parseTimestamp2(record.timestamp);
|
|
155
|
+
if (!ts) continue;
|
|
156
|
+
let usageDate = toDateKey2(ts);
|
|
157
|
+
if (!targetDateSet.has(usageDate)) continue;
|
|
158
|
+
let total = info.total_token_usage, signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
|
|
159
|
+
if (signature === lastTotalSignature) continue;
|
|
160
|
+
lastTotalSignature = signature;
|
|
161
|
+
let last = info.last_token_usage, grouped = groupedByDate.get(usageDate);
|
|
162
|
+
if (!grouped) continue;
|
|
163
|
+
let key = `${currentModel}|${currentProject}`, existing = grouped.get(key);
|
|
164
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += last.input_tokens ?? 0, existing.cachedInputTokens += last.cached_input_tokens ?? 0, existing.outputTokens += last.output_tokens ?? 0, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0) : grouped.set(key, {
|
|
165
|
+
provider: "openai",
|
|
166
|
+
product: "codex",
|
|
167
|
+
channel: "cli",
|
|
168
|
+
model: currentModel,
|
|
169
|
+
project: currentProject,
|
|
170
|
+
eventCount: 1,
|
|
171
|
+
inputTokens: last.input_tokens ?? 0,
|
|
172
|
+
cachedInputTokens: last.cached_input_tokens ?? 0,
|
|
173
|
+
cacheWriteTokens: 0,
|
|
174
|
+
outputTokens: last.output_tokens ?? 0,
|
|
175
|
+
reasoningOutputTokens: last.reasoning_output_tokens ?? 0
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return new Map(
|
|
180
|
+
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
async function collectSessionFiles(baseDir) {
|
|
184
|
+
let paths = [], archivedDir = join2(baseDir, "archived_sessions");
|
|
185
|
+
try {
|
|
186
|
+
let files = await readdir2(archivedDir);
|
|
187
|
+
for (let f of files)
|
|
188
|
+
f.endsWith(".jsonl") && paths.push(join2(archivedDir, f));
|
|
189
|
+
} catch {
|
|
190
|
+
}
|
|
191
|
+
let sessionsDir = join2(baseDir, "sessions");
|
|
192
|
+
return await walkDir(sessionsDir, paths), paths;
|
|
193
|
+
}
|
|
194
|
+
async function walkDir(dir, result) {
|
|
195
|
+
let entries;
|
|
196
|
+
try {
|
|
197
|
+
entries = await readdir2(dir, { withFileTypes: !0 });
|
|
198
|
+
} catch {
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
for (let entry of entries) {
|
|
202
|
+
let fullPath = join2(dir, entry.name);
|
|
203
|
+
entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function parseTimestamp2(value) {
|
|
207
|
+
if (!value) return null;
|
|
208
|
+
try {
|
|
209
|
+
let d = new Date(value);
|
|
210
|
+
return isNaN(d.getTime()) ? null : d;
|
|
211
|
+
} catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function toDateKey2(date) {
|
|
216
|
+
let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
|
|
217
|
+
return `${year}-${month}-${day}`;
|
|
218
|
+
}
|
|
219
|
+
function extractProject(cwd, aliases) {
|
|
220
|
+
let parts = cwd.split("/").filter(Boolean), project = parts[parts.length - 1] || "unknown";
|
|
221
|
+
return aliases?.[cwd] ?? aliases?.[project] ?? project;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// src/scanners/copilot.ts
|
|
225
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
226
|
+
import { join as join4 } from "node:path";
|
|
227
|
+
import { homedir as homedir3 } from "node:os";
|
|
228
|
+
|
|
229
|
+
// src/scanners/utils.ts
|
|
230
|
+
import { readdir as readdir3 } from "node:fs/promises";
|
|
231
|
+
import { join as join3 } from "node:path";
|
|
232
|
+
function parseTs(value) {
|
|
233
|
+
if (value == null) return null;
|
|
234
|
+
let d = new Date(value);
|
|
235
|
+
return isNaN(d.getTime()) ? null : d;
|
|
236
|
+
}
|
|
237
|
+
function dateKey(date) {
|
|
238
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
239
|
+
}
|
|
240
|
+
function projectFromPath(raw, aliases) {
|
|
241
|
+
let parts = raw.split("/").filter(Boolean), name = parts[parts.length - 1] || "unknown";
|
|
242
|
+
return aliases?.[raw] ?? aliases?.[name] ?? name;
|
|
243
|
+
}
|
|
244
|
+
async function walkFiles(dir, ext) {
|
|
245
|
+
let result = [];
|
|
246
|
+
return await walk(dir, ext, result), result;
|
|
247
|
+
}
|
|
248
|
+
async function walk(dir, ext, out) {
|
|
249
|
+
let entries;
|
|
250
|
+
try {
|
|
251
|
+
entries = await readdir3(dir, { withFileTypes: !0 });
|
|
252
|
+
} catch {
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
for (let e of entries) {
|
|
256
|
+
let full = join3(dir, e.name);
|
|
257
|
+
e.isDirectory() ? await walk(full, ext, out) : e.name.endsWith(ext) && out.push(full);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
function initDateMap(dates) {
|
|
261
|
+
let m = /* @__PURE__ */ new Map();
|
|
262
|
+
for (let d of dates) m.set(d, /* @__PURE__ */ new Map());
|
|
263
|
+
return m;
|
|
264
|
+
}
|
|
265
|
+
function accumulate(grouped, key, base, tokens) {
|
|
266
|
+
let existing = grouped.get(key);
|
|
267
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += tokens.input, existing.cachedInputTokens += tokens.cached, existing.cacheWriteTokens += tokens.cacheWrite, existing.outputTokens += tokens.output, existing.reasoningOutputTokens += tokens.reasoning) : grouped.set(key, {
|
|
268
|
+
...base,
|
|
269
|
+
eventCount: 1,
|
|
270
|
+
inputTokens: tokens.input,
|
|
271
|
+
cachedInputTokens: tokens.cached,
|
|
272
|
+
cacheWriteTokens: tokens.cacheWrite,
|
|
273
|
+
outputTokens: tokens.output,
|
|
274
|
+
reasoningOutputTokens: tokens.reasoning
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
function finalize(groupedByDate) {
|
|
278
|
+
return new Map(
|
|
279
|
+
[...groupedByDate.entries()].map(([d, m]) => [d, [...m.values()]])
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
function emptyResult(dates) {
|
|
283
|
+
return new Map([...dates].map((d) => [d, []]));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// src/scanners/copilot.ts
|
|
287
|
+
async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
288
|
+
let dates = new Set(targetDates), dir = baseDir ?? join4(homedir3(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
|
|
289
|
+
if (files.length === 0) return emptyResult(dates);
|
|
290
|
+
let grouped = initDateMap(dates);
|
|
291
|
+
for (let filePath of files) {
|
|
292
|
+
let content;
|
|
293
|
+
try {
|
|
294
|
+
content = await readFile3(filePath, "utf-8");
|
|
295
|
+
} catch {
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
let sessionProject = "unknown", lines = content.split(`
|
|
299
|
+
`);
|
|
300
|
+
for (let line of lines) {
|
|
301
|
+
if (!line.trim()) continue;
|
|
302
|
+
let obj;
|
|
303
|
+
try {
|
|
304
|
+
obj = JSON.parse(line);
|
|
305
|
+
} catch {
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (obj.type === "session.start" || obj.type === "session.resume") {
|
|
309
|
+
let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
|
|
310
|
+
raw && (sessionProject = projectFromPath(raw, projectAliases));
|
|
311
|
+
}
|
|
312
|
+
if (obj.type !== "session.shutdown") continue;
|
|
313
|
+
let ts = parseTs(obj.timestamp);
|
|
314
|
+
if (!ts) continue;
|
|
315
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
316
|
+
if (!dayMap) continue;
|
|
317
|
+
let metrics = obj.data?.modelMetrics;
|
|
318
|
+
if (metrics)
|
|
319
|
+
for (let [model, entry] of Object.entries(metrics)) {
|
|
320
|
+
let usage = entry.usage;
|
|
321
|
+
if (!usage) continue;
|
|
322
|
+
let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
|
|
323
|
+
accumulate(
|
|
324
|
+
dayMap,
|
|
325
|
+
`${model}|${sessionProject}`,
|
|
326
|
+
{
|
|
327
|
+
provider: "github",
|
|
328
|
+
product: "copilot-cli",
|
|
329
|
+
channel: "cli",
|
|
330
|
+
model,
|
|
331
|
+
project: sessionProject,
|
|
332
|
+
inputTokens: 0,
|
|
333
|
+
cachedInputTokens: 0,
|
|
334
|
+
cacheWriteTokens: 0,
|
|
335
|
+
outputTokens: 0,
|
|
336
|
+
reasoningOutputTokens: 0
|
|
337
|
+
},
|
|
338
|
+
{ input, cached: cacheRead, cacheWrite: 0, output, reasoning: 0 }
|
|
339
|
+
);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return finalize(grouped);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// src/scanners/gemini.ts
|
|
347
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
348
|
+
import { join as join5 } from "node:path";
|
|
349
|
+
import { homedir as homedir4 } from "node:os";
|
|
350
|
+
async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
351
|
+
let dates = new Set(targetDates), dir = baseDir ?? join5(homedir4(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
|
|
352
|
+
if (files.length === 0) return emptyResult(dates);
|
|
353
|
+
let grouped = initDateMap(dates);
|
|
354
|
+
for (let filePath of files) {
|
|
355
|
+
let content;
|
|
356
|
+
try {
|
|
357
|
+
content = await readFile4(filePath, "utf-8");
|
|
358
|
+
} catch {
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
let session;
|
|
362
|
+
try {
|
|
363
|
+
session = JSON.parse(content);
|
|
364
|
+
} catch {
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
let messages = session.data?.messages ?? session.data?.history ?? [], fallbackModel = session.data?.model ?? session.model ?? "unknown", fallbackTs = session.data?.createTime ?? session.createTime;
|
|
368
|
+
for (let msg of messages) {
|
|
369
|
+
let tokens = extractTokens(msg);
|
|
370
|
+
if (!tokens) continue;
|
|
371
|
+
let model = msg.model ?? fallbackModel, ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
|
|
372
|
+
if (!ts) continue;
|
|
373
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
374
|
+
dayMap && accumulate(
|
|
375
|
+
dayMap,
|
|
376
|
+
`${model}|unknown`,
|
|
377
|
+
{
|
|
378
|
+
provider: "google",
|
|
379
|
+
product: "gemini-cli",
|
|
380
|
+
channel: "cli",
|
|
381
|
+
model,
|
|
382
|
+
project: "unknown",
|
|
383
|
+
inputTokens: 0,
|
|
384
|
+
cachedInputTokens: 0,
|
|
385
|
+
cacheWriteTokens: 0,
|
|
386
|
+
outputTokens: 0,
|
|
387
|
+
reasoningOutputTokens: 0
|
|
388
|
+
},
|
|
389
|
+
tokens
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return finalize(grouped);
|
|
394
|
+
}
|
|
395
|
+
function extractTokens(msg) {
|
|
396
|
+
if (msg.tokens) {
|
|
397
|
+
let t = msg.tokens, cached2 = t.cached ?? 0, input = Math.max((t.input ?? 0) - cached2, 0), thoughts = t.thoughts ?? 0, output = Math.max((t.output ?? 0) - thoughts, 0);
|
|
398
|
+
return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
|
|
399
|
+
}
|
|
400
|
+
let u = msg.usage ?? msg.usageMetadata;
|
|
401
|
+
if (u) {
|
|
402
|
+
let cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
|
|
403
|
+
return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
|
|
404
|
+
}
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/scanners/qwen.ts
|
|
409
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
410
|
+
import { join as join6, basename as basename2, dirname } from "node:path";
|
|
411
|
+
import { homedir as homedir5 } from "node:os";
|
|
412
|
+
async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
413
|
+
let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
|
|
414
|
+
if (files.length === 0) return emptyResult(dates);
|
|
415
|
+
let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
416
|
+
for (let filePath of files) {
|
|
417
|
+
let chatsDir = dirname(filePath), projectDir = dirname(chatsDir), projectId = basename2(projectDir), content;
|
|
418
|
+
try {
|
|
419
|
+
content = await readFile5(filePath, "utf-8");
|
|
420
|
+
} catch {
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
for (let line of content.split(`
|
|
424
|
+
`)) {
|
|
425
|
+
if (!line.trim()) continue;
|
|
426
|
+
let obj;
|
|
427
|
+
try {
|
|
428
|
+
obj = JSON.parse(line);
|
|
429
|
+
} catch {
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
if (obj.type !== "assistant") continue;
|
|
433
|
+
let ts = parseTs(obj.timestamp);
|
|
434
|
+
if (!ts) continue;
|
|
435
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
436
|
+
if (!dayMap) continue;
|
|
437
|
+
if (obj.uuid) {
|
|
438
|
+
if (seen.has(obj.uuid)) continue;
|
|
439
|
+
seen.add(obj.uuid);
|
|
440
|
+
}
|
|
441
|
+
let u = obj.usageMetadata;
|
|
442
|
+
if (!u) continue;
|
|
443
|
+
let model = obj.model ?? "unknown", project = obj.cwd ? projectFromPath(obj.cwd, projectAliases) : projectFromPath(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
|
|
444
|
+
accumulate(
|
|
445
|
+
dayMap,
|
|
446
|
+
`${model}|${project}`,
|
|
447
|
+
{
|
|
448
|
+
provider: "alibaba",
|
|
449
|
+
product: "qwen-code",
|
|
450
|
+
channel: "cli",
|
|
451
|
+
model,
|
|
452
|
+
project,
|
|
453
|
+
inputTokens: 0,
|
|
454
|
+
cachedInputTokens: 0,
|
|
455
|
+
cacheWriteTokens: 0,
|
|
456
|
+
outputTokens: 0,
|
|
457
|
+
reasoningOutputTokens: 0
|
|
458
|
+
},
|
|
459
|
+
{ input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts }
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return finalize(grouped);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/scanners/kimi.ts
|
|
467
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
468
|
+
import { join as join7, basename as basename3, dirname as dirname2 } from "node:path";
|
|
469
|
+
import { homedir as homedir6 } from "node:os";
|
|
470
|
+
async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
471
|
+
let dates = new Set(targetDates), kimiHome = baseDir ?? join7(homedir6(), ".kimi"), sessionsDir = join7(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
|
|
472
|
+
if (files.length === 0) return emptyResult(dates);
|
|
473
|
+
let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
474
|
+
for (let filePath of files) {
|
|
475
|
+
let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), project = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
|
|
476
|
+
try {
|
|
477
|
+
content = await readFile6(filePath, "utf-8");
|
|
478
|
+
} catch {
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
let currentModel = "unknown";
|
|
482
|
+
for (let line of content.split(`
|
|
483
|
+
`)) {
|
|
484
|
+
if (!line.trim()) continue;
|
|
485
|
+
let obj;
|
|
486
|
+
try {
|
|
487
|
+
obj = JSON.parse(line);
|
|
488
|
+
} catch {
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
if (obj.payload?.model && (currentModel = obj.payload.model), obj.type !== "StatusUpdate") continue;
|
|
492
|
+
let usage = obj.payload?.token_usage;
|
|
493
|
+
if (!usage) continue;
|
|
494
|
+
let ts = parseTs(obj.timestamp);
|
|
495
|
+
if (!ts) continue;
|
|
496
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
497
|
+
if (!dayMap) continue;
|
|
498
|
+
let msgId = obj.payload?.message_id;
|
|
499
|
+
if (msgId) {
|
|
500
|
+
if (seen.has(msgId)) continue;
|
|
501
|
+
seen.add(msgId);
|
|
502
|
+
}
|
|
503
|
+
let input = usage.input_other ?? 0, cached2 = usage.input_cache_read ?? 0, output = usage.output ?? 0;
|
|
504
|
+
accumulate(
|
|
505
|
+
dayMap,
|
|
506
|
+
`${currentModel}|${project}`,
|
|
507
|
+
{
|
|
508
|
+
provider: "moonshot",
|
|
509
|
+
product: "kimi-code",
|
|
510
|
+
channel: "cli",
|
|
511
|
+
model: currentModel,
|
|
512
|
+
project,
|
|
513
|
+
inputTokens: 0,
|
|
514
|
+
cachedInputTokens: 0,
|
|
515
|
+
cacheWriteTokens: 0,
|
|
516
|
+
outputTokens: 0,
|
|
517
|
+
reasoningOutputTokens: 0
|
|
518
|
+
},
|
|
519
|
+
{ input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return finalize(grouped);
|
|
524
|
+
}
|
|
525
|
+
function resolveKimiProject(hash, workspaceMap, aliases) {
|
|
526
|
+
let wsPath = workspaceMap.get(hash);
|
|
527
|
+
return wsPath ? projectFromPath(wsPath, aliases) : projectFromPath(hash, aliases);
|
|
528
|
+
}
|
|
529
|
+
async function loadWorkspaceMap(kimiHome) {
|
|
530
|
+
let map = /* @__PURE__ */ new Map();
|
|
531
|
+
try {
|
|
532
|
+
let raw = await readFile6(join7(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
|
|
533
|
+
if (config.workspaces)
|
|
534
|
+
for (let [hash, info] of Object.entries(config.workspaces))
|
|
535
|
+
info.path && map.set(hash, info.path);
|
|
536
|
+
} catch {
|
|
537
|
+
}
|
|
538
|
+
return map;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// src/scanners/amp.ts
|
|
542
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
543
|
+
import { join as join8 } from "node:path";
|
|
544
|
+
import { homedir as homedir7 } from "node:os";
|
|
545
|
+
function resolveAmpDir(baseDir) {
|
|
546
|
+
if (baseDir) return baseDir;
|
|
547
|
+
let ampDataDir = process.env.AMP_DATA_DIR;
|
|
548
|
+
if (ampDataDir) return join8(ampDataDir, "threads");
|
|
549
|
+
let xdgDataHome = process.env.XDG_DATA_HOME;
|
|
550
|
+
return xdgDataHome ? join8(xdgDataHome, "amp", "threads") : join8(homedir7(), ".local", "share", "amp", "threads");
|
|
551
|
+
}
|
|
552
|
+
async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
553
|
+
let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
|
|
554
|
+
let name = f.split("/").pop() ?? "";
|
|
555
|
+
return name.startsWith("T-") && name.endsWith(".json");
|
|
556
|
+
});
|
|
557
|
+
if (threadFiles.length === 0) return emptyResult(dates);
|
|
558
|
+
let grouped = initDateMap(dates);
|
|
559
|
+
for (let filePath of threadFiles) {
|
|
560
|
+
let raw;
|
|
561
|
+
try {
|
|
562
|
+
raw = await readFile7(filePath, "utf-8");
|
|
563
|
+
} catch {
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
let thread;
|
|
567
|
+
try {
|
|
568
|
+
thread = JSON.parse(raw);
|
|
569
|
+
} catch {
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
let ledgerEvents = thread.usageLedger?.events;
|
|
573
|
+
Array.isArray(ledgerEvents) && ledgerEvents.length > 0 ? processLedger(thread, ledgerEvents, dates, grouped) : processMessages(thread, dates, grouped);
|
|
574
|
+
}
|
|
575
|
+
return finalize(grouped);
|
|
576
|
+
}
|
|
577
|
+
function getMessageByKey(messages, key) {
|
|
578
|
+
if (messages) {
|
|
579
|
+
if (Array.isArray(messages)) {
|
|
580
|
+
let idx = parseInt(key, 10);
|
|
581
|
+
return isNaN(idx) ? void 0 : messages[idx];
|
|
582
|
+
}
|
|
583
|
+
return messages[key];
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
function processLedger(thread, events, dates, grouped) {
|
|
587
|
+
for (let event of events) {
|
|
588
|
+
let ts = parseTs(event.timestamp);
|
|
589
|
+
if (!ts) continue;
|
|
590
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
591
|
+
if (!dayMap) continue;
|
|
592
|
+
let model = event.model ?? "unknown", input = event.tokens?.input ?? 0, output = event.tokens?.output ?? 0, cached2 = 0;
|
|
593
|
+
event.toMessageId && (cached2 = getMessageByKey(thread.messages, event.toMessageId)?.usage?.cacheReadInputTokens ?? 0), accumulate(
|
|
594
|
+
dayMap,
|
|
595
|
+
`${model}|unknown`,
|
|
596
|
+
{
|
|
597
|
+
provider: "sourcegraph",
|
|
598
|
+
product: "amp",
|
|
599
|
+
channel: "cli",
|
|
600
|
+
model,
|
|
601
|
+
project: "unknown",
|
|
602
|
+
inputTokens: 0,
|
|
603
|
+
cachedInputTokens: 0,
|
|
604
|
+
cacheWriteTokens: 0,
|
|
605
|
+
outputTokens: 0,
|
|
606
|
+
reasoningOutputTokens: 0
|
|
607
|
+
},
|
|
608
|
+
{ input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
function processMessages(thread, dates, grouped) {
|
|
613
|
+
let msgs = thread.messages;
|
|
614
|
+
if (!msgs) return;
|
|
615
|
+
let entries = Array.isArray(msgs) ? msgs : Object.values(msgs);
|
|
616
|
+
for (let msg of entries) {
|
|
617
|
+
let usage = msg.usage;
|
|
618
|
+
if (!usage) continue;
|
|
619
|
+
let ts = parseTs(msg.timestamp ?? thread.created);
|
|
620
|
+
if (!ts) continue;
|
|
621
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
622
|
+
if (!dayMap) continue;
|
|
623
|
+
let model = msg.model ?? "unknown", input = usage.inputTokens ?? 0, output = usage.outputTokens ?? 0, cached2 = usage.cacheReadInputTokens ?? 0;
|
|
624
|
+
accumulate(
|
|
625
|
+
dayMap,
|
|
626
|
+
`${model}|unknown`,
|
|
627
|
+
{
|
|
628
|
+
provider: "sourcegraph",
|
|
629
|
+
product: "amp",
|
|
630
|
+
channel: "cli",
|
|
631
|
+
model,
|
|
632
|
+
project: "unknown",
|
|
633
|
+
inputTokens: 0,
|
|
634
|
+
cachedInputTokens: 0,
|
|
635
|
+
cacheWriteTokens: 0,
|
|
636
|
+
outputTokens: 0,
|
|
637
|
+
reasoningOutputTokens: 0
|
|
638
|
+
},
|
|
639
|
+
{ input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
|
|
640
|
+
);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
// src/scanners/droid.ts
|
|
645
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
646
|
+
import { join as join9, dirname as dirname3, basename as basename4 } from "node:path";
|
|
647
|
+
import { homedir as homedir8 } from "node:os";
|
|
648
|
+
function extractProjectFromSlug(dirPath) {
|
|
649
|
+
let parts = basename4(dirPath).split("-").filter(Boolean);
|
|
650
|
+
return parts[parts.length - 1] || "unknown";
|
|
651
|
+
}
|
|
652
|
+
async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
653
|
+
let dates = new Set(targetDates), dir = baseDir ?? join9(homedir8(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
|
|
654
|
+
if (files.length === 0) return emptyResult(dates);
|
|
655
|
+
let grouped = initDateMap(dates);
|
|
656
|
+
for (let jsonlPath of files) {
|
|
657
|
+
let content;
|
|
658
|
+
try {
|
|
659
|
+
content = await readFile8(jsonlPath, "utf-8");
|
|
660
|
+
} catch {
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
let firstLine = content.split(`
|
|
664
|
+
`).find((l) => l.trim());
|
|
665
|
+
if (!firstLine) continue;
|
|
666
|
+
let firstObj;
|
|
667
|
+
try {
|
|
668
|
+
firstObj = JSON.parse(firstLine);
|
|
669
|
+
} catch {
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
let ts = parseTs(firstObj.timestamp);
|
|
673
|
+
if (!ts) continue;
|
|
674
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
675
|
+
if (!dayMap) continue;
|
|
676
|
+
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath = join9(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
|
|
677
|
+
try {
|
|
678
|
+
settingsRaw = await readFile8(settingsPath, "utf-8");
|
|
679
|
+
} catch {
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
let settings;
|
|
683
|
+
try {
|
|
684
|
+
settings = JSON.parse(settingsRaw);
|
|
685
|
+
} catch {
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
let usage = settings.tokenUsage;
|
|
689
|
+
if (!usage) continue;
|
|
690
|
+
let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), project = projectAliases?.[rawProject] ?? rawProject;
|
|
691
|
+
accumulate(
|
|
692
|
+
dayMap,
|
|
693
|
+
`${model}|${project}`,
|
|
694
|
+
{
|
|
695
|
+
provider: "droid",
|
|
696
|
+
product: "droid",
|
|
697
|
+
channel: "cli",
|
|
698
|
+
model,
|
|
699
|
+
project,
|
|
700
|
+
inputTokens: 0,
|
|
701
|
+
cachedInputTokens: 0,
|
|
702
|
+
cacheWriteTokens: 0,
|
|
703
|
+
outputTokens: 0,
|
|
704
|
+
reasoningOutputTokens: 0
|
|
705
|
+
},
|
|
706
|
+
{ input, cached: cacheRead, cacheWrite: 0, output, reasoning: thinking }
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
return finalize(grouped);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// src/scanners/opencode.ts
|
|
713
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
714
|
+
import { homedir as homedir9 } from "node:os";
|
|
715
|
+
async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
716
|
+
let dates = new Set(targetDates), dir = baseDir ?? `${homedir9()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
|
|
717
|
+
if (files.length === 0) return emptyResult(dates);
|
|
718
|
+
let grouped = initDateMap(dates);
|
|
719
|
+
for (let filePath of files) {
|
|
720
|
+
let raw;
|
|
721
|
+
try {
|
|
722
|
+
raw = await readFile9(filePath, "utf-8");
|
|
723
|
+
} catch {
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
let msg;
|
|
727
|
+
try {
|
|
728
|
+
msg = JSON.parse(raw);
|
|
729
|
+
} catch {
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
let tokens = msg.tokens;
|
|
733
|
+
if (!tokens) continue;
|
|
734
|
+
let input = tokens.input ?? 0, output = tokens.output ?? 0;
|
|
735
|
+
if (input === 0 && output === 0) continue;
|
|
736
|
+
let ts = parseTs(msg.time?.created);
|
|
737
|
+
if (!ts) continue;
|
|
738
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
739
|
+
if (!dayMap) continue;
|
|
740
|
+
let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, project = rootPath ? projectFromPath(rootPath, projectAliases) : "unknown";
|
|
741
|
+
accumulate(
|
|
742
|
+
dayMap,
|
|
743
|
+
`${model}|${project}`,
|
|
744
|
+
{
|
|
745
|
+
provider: "opencode",
|
|
746
|
+
product: "opencode",
|
|
747
|
+
channel: "cli",
|
|
748
|
+
model,
|
|
749
|
+
project,
|
|
750
|
+
inputTokens: 0,
|
|
751
|
+
cachedInputTokens: 0,
|
|
752
|
+
cacheWriteTokens: 0,
|
|
753
|
+
outputTokens: 0,
|
|
754
|
+
reasoningOutputTokens: 0
|
|
755
|
+
},
|
|
756
|
+
{ input, cached: cached2, cacheWrite: 0, output, reasoning }
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
return finalize(grouped);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// src/scanners/openclaw.ts
|
|
763
|
+
import { readFile as readFile10 } from "node:fs/promises";
|
|
764
|
+
import { basename as basename5, dirname as dirname4 } from "node:path";
|
|
765
|
+
import { homedir as homedir10 } from "node:os";
|
|
766
|
+
function resolveInput(u) {
|
|
767
|
+
return u.input ?? u.inputTokens ?? u.input_tokens ?? u.promptTokens ?? u.prompt_tokens ?? 0;
|
|
768
|
+
}
|
|
769
|
+
function resolveOutput(u) {
|
|
770
|
+
return u.output ?? u.outputTokens ?? u.output_tokens ?? u.completionTokens ?? u.completion_tokens ?? 0;
|
|
771
|
+
}
|
|
772
|
+
function resolveCached(u) {
|
|
773
|
+
return u.cacheRead ?? u.cache_read ?? u.cache_read_input_tokens ?? 0;
|
|
774
|
+
}
|
|
775
|
+
function agentNameFromPath(filePath) {
|
|
776
|
+
let sessionsDir = dirname4(filePath), agentDir = dirname4(sessionsDir);
|
|
777
|
+
return basename5(agentDir) || "unknown";
|
|
778
|
+
}
|
|
779
|
+
function collectBaseDirs(baseDir) {
|
|
780
|
+
if (baseDir) return [baseDir];
|
|
781
|
+
let home = homedir10();
|
|
782
|
+
return [
|
|
783
|
+
`${home}/.openclaw/agents`,
|
|
784
|
+
`${home}/.clawdbot`,
|
|
785
|
+
`${home}/.moltbot`,
|
|
786
|
+
`${home}/.moldbot`
|
|
787
|
+
];
|
|
788
|
+
}
|
|
789
|
+
async function scanOpenclawDates(targetDates, baseDir, projectAliases) {
|
|
790
|
+
let dates = new Set(targetDates), dirs = collectBaseDirs(baseDir), allFiles = [];
|
|
791
|
+
for (let d of dirs) {
|
|
792
|
+
let found = await walkFiles(d, ".jsonl");
|
|
793
|
+
allFiles = allFiles.concat(found);
|
|
794
|
+
}
|
|
795
|
+
if (allFiles.length === 0) return emptyResult(dates);
|
|
796
|
+
let grouped = initDateMap(dates);
|
|
797
|
+
for (let filePath of allFiles) {
|
|
798
|
+
let content;
|
|
799
|
+
try {
|
|
800
|
+
content = await readFile10(filePath, "utf-8");
|
|
801
|
+
} catch {
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
let agentName = agentNameFromPath(filePath), project = projectAliases?.[agentName] ?? agentName;
|
|
805
|
+
for (let line of content.split(`
|
|
806
|
+
`)) {
|
|
807
|
+
if (!line.trim()) continue;
|
|
808
|
+
let obj;
|
|
809
|
+
try {
|
|
810
|
+
obj = JSON.parse(line);
|
|
811
|
+
} catch {
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if (obj.type !== "message") continue;
|
|
815
|
+
let msg = obj.message;
|
|
816
|
+
if (!msg || msg.role !== "assistant") continue;
|
|
817
|
+
let usage = msg.usage;
|
|
818
|
+
if (!usage) continue;
|
|
819
|
+
let ts = parseTs(obj.timestamp ?? msg.timestamp);
|
|
820
|
+
if (!ts) continue;
|
|
821
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
822
|
+
if (!dayMap) continue;
|
|
823
|
+
let model = msg.model ?? obj.model ?? "unknown", input = resolveInput(usage), output = resolveOutput(usage), cached2 = resolveCached(usage);
|
|
824
|
+
accumulate(
|
|
825
|
+
dayMap,
|
|
826
|
+
`${model}|${project}`,
|
|
827
|
+
{
|
|
828
|
+
provider: "openclaw",
|
|
829
|
+
product: "openclaw",
|
|
830
|
+
channel: "cli",
|
|
831
|
+
model,
|
|
832
|
+
project,
|
|
833
|
+
inputTokens: 0,
|
|
834
|
+
cachedInputTokens: 0,
|
|
835
|
+
cacheWriteTokens: 0,
|
|
836
|
+
outputTokens: 0,
|
|
837
|
+
reasoningOutputTokens: 0
|
|
838
|
+
},
|
|
839
|
+
{ input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
return finalize(grouped);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// src/scan.ts
|
|
847
|
+
async function scanDate(targetDate, options = {}) {
|
|
848
|
+
let [result] = await scanDates([targetDate], options);
|
|
849
|
+
return result ?? {
|
|
850
|
+
usageDate: targetDate,
|
|
851
|
+
breakdowns: [],
|
|
852
|
+
totals: createEmptyTotals()
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
async function scanDates(targetDates, options = {}) {
|
|
856
|
+
let uniqueDates = [...new Set(targetDates)];
|
|
857
|
+
if (uniqueDates.length === 0) return [];
|
|
858
|
+
let scanners = [
|
|
859
|
+
scanClaudeDates(uniqueDates, void 0, options.projectAliases),
|
|
860
|
+
scanCodexDates(uniqueDates, void 0, options.projectAliases),
|
|
861
|
+
scanCopilotDates(uniqueDates, void 0, options.projectAliases),
|
|
862
|
+
scanGeminiDates(uniqueDates, void 0, options.projectAliases),
|
|
863
|
+
scanQwenDates(uniqueDates, void 0, options.projectAliases),
|
|
864
|
+
scanKimiDates(uniqueDates, void 0, options.projectAliases),
|
|
865
|
+
scanAmpDates(uniqueDates, void 0, options.projectAliases),
|
|
866
|
+
scanDroidDates(uniqueDates, void 0, options.projectAliases),
|
|
867
|
+
scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
|
|
868
|
+
scanOpenclawDates(uniqueDates, void 0, options.projectAliases)
|
|
869
|
+
], results = await Promise.all(scanners);
|
|
870
|
+
return uniqueDates.map((usageDate) => {
|
|
871
|
+
let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
|
|
872
|
+
(acc, b) => ({
|
|
873
|
+
eventCount: acc.eventCount + b.eventCount,
|
|
874
|
+
inputTokens: acc.inputTokens + b.inputTokens,
|
|
875
|
+
cachedInputTokens: acc.cachedInputTokens + b.cachedInputTokens,
|
|
876
|
+
cacheWriteTokens: acc.cacheWriteTokens + b.cacheWriteTokens,
|
|
877
|
+
outputTokens: acc.outputTokens + b.outputTokens,
|
|
878
|
+
reasoningOutputTokens: acc.reasoningOutputTokens + b.reasoningOutputTokens
|
|
879
|
+
}),
|
|
880
|
+
createEmptyTotals()
|
|
881
|
+
);
|
|
882
|
+
return { usageDate, breakdowns, totals };
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
function createEmptyTotals() {
|
|
886
|
+
return {
|
|
887
|
+
eventCount: 0,
|
|
888
|
+
inputTokens: 0,
|
|
889
|
+
cachedInputTokens: 0,
|
|
890
|
+
cacheWriteTokens: 0,
|
|
891
|
+
outputTokens: 0,
|
|
892
|
+
reasoningOutputTokens: 0
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// src/report.ts
|
|
897
|
+
import { readdir as readdir5, readFile as readFile11 } from "node:fs/promises";
|
|
898
|
+
import { homedir as homedir11 } from "node:os";
|
|
899
|
+
import { join as join10 } from "node:path";
|
|
900
|
+
async function buildLocalReport(range, options = {}) {
|
|
901
|
+
let requestedDates = range === "all" ? await discoverAllDates() : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
|
|
902
|
+
for (let result of results) {
|
|
903
|
+
let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = dayTotals.totalTokens > 0;
|
|
904
|
+
if (hasData) {
|
|
905
|
+
daysWithData += 1;
|
|
906
|
+
for (let breakdown of result.breakdowns) {
|
|
907
|
+
let breakdownTotals = toBreakdownTotals(breakdown, pricingWarnings);
|
|
908
|
+
dayTotals.estimatedCostUsd += breakdownTotals.estimatedCostUsd, mergeTotals(totals, breakdownTotals), mergeTotals(getOrCreate(bySource, `${breakdown.provider}/${breakdown.product}`), breakdownTotals), mergeTotals(
|
|
909
|
+
getOrCreate(byModel, `${breakdown.provider}/${breakdown.product}|${breakdown.model}`),
|
|
910
|
+
breakdownTotals
|
|
911
|
+
);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
(range !== "all" || hasData) && daily.push({ usageDate, ...dayTotals });
|
|
915
|
+
}
|
|
916
|
+
let sortedDates = requestedDates.slice().sort();
|
|
917
|
+
return {
|
|
918
|
+
range,
|
|
919
|
+
rangeLabel: getRangeLabel(range),
|
|
920
|
+
startDate: sortedDates[0],
|
|
921
|
+
endDate: sortedDates[sortedDates.length - 1],
|
|
922
|
+
requestedDays: requestedDates.length,
|
|
923
|
+
daysWithData,
|
|
924
|
+
totals,
|
|
925
|
+
daily,
|
|
926
|
+
bySource: [...bySource.entries()].map(([source, summary]) => ({ source, ...summary })).sort((a, b) => b.estimatedCostUsd - a.estimatedCostUsd || b.totalTokens - a.totalTokens),
|
|
927
|
+
byModel: [...byModel.entries()].map(([key, summary]) => {
|
|
928
|
+
let [source, model] = key.split("|");
|
|
929
|
+
return { source, model, ...summary };
|
|
930
|
+
}).sort((a, b) => b.estimatedCostUsd - a.estimatedCostUsd || b.totalTokens - a.totalTokens),
|
|
931
|
+
pricingWarnings: [...pricingWarnings].sort()
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
function renderLocalReport(report) {
|
|
935
|
+
let lines = [];
|
|
936
|
+
if (lines.push("\u{1F4CA} AIUsage \u672C\u5730\u7EDF\u8BA1"), lines.push(`\u8303\u56F4 ${report.rangeLabel}`), lines.push(`\u65F6\u95F4 ${report.startDate ?? "-"} ~ ${report.endDate ?? "-"}`), lines.push(`\u8BF7\u6C42\u5929\u6570 ${fmtInt(report.requestedDays)}`), lines.push(`\u6709\u6548\u5929\u6570 ${fmtInt(report.daysWithData)}`), lines.push(""), report.requestedDays === 0 || report.daysWithData === 0)
|
|
937
|
+
return lines.push("\u8BE5\u8303\u56F4\u6682\u65E0\u672C\u5730 token \u6570\u636E\u3002"), lines.join(`
|
|
938
|
+
`);
|
|
939
|
+
if (lines.push("Summary"), lines.push(renderTable(
|
|
940
|
+
["Metric", "Value"],
|
|
941
|
+
[
|
|
942
|
+
["Events", fmtInt(report.totals.eventCount)],
|
|
943
|
+
["Input", fmtToken(report.totals.inputTokens)],
|
|
944
|
+
["CacheRead", fmtToken(report.totals.cachedInputTokens)],
|
|
945
|
+
["CacheWrite", fmtToken(report.totals.cacheWriteTokens)],
|
|
946
|
+
["Output", fmtToken(report.totals.outputTokens)],
|
|
947
|
+
["Reasoning", fmtToken(report.totals.reasoningOutputTokens)],
|
|
948
|
+
["TotalTokens", fmtToken(report.totals.totalTokens)],
|
|
949
|
+
["CostUsd", fmtUsd(report.totals.estimatedCostUsd)]
|
|
950
|
+
],
|
|
951
|
+
["left", "right"]
|
|
952
|
+
)), lines.push(""), lines.push("By Source"), lines.push(renderTable(
|
|
953
|
+
["Source", "Events", "Input", "CacheRead", "CacheWrite", "Output", "Reasoning", "Total", "Cost"],
|
|
954
|
+
report.bySource.map((item) => [
|
|
955
|
+
item.source,
|
|
956
|
+
fmtInt(item.eventCount),
|
|
957
|
+
fmtToken(item.inputTokens),
|
|
958
|
+
fmtToken(item.cachedInputTokens),
|
|
959
|
+
fmtToken(item.cacheWriteTokens),
|
|
960
|
+
fmtToken(item.outputTokens),
|
|
961
|
+
fmtToken(item.reasoningOutputTokens),
|
|
962
|
+
fmtToken(item.totalTokens),
|
|
963
|
+
fmtUsd(item.estimatedCostUsd)
|
|
964
|
+
]),
|
|
965
|
+
["left", "right", "right", "right", "right", "right", "right", "right", "right"]
|
|
966
|
+
)), lines.push(""), lines.push("By Day"), lines.push(renderTable(
|
|
967
|
+
["Date", "Events", "Input", "CacheRead", "CacheWrite", "Output", "Reasoning", "Total", "Cost"],
|
|
968
|
+
report.daily.map((item) => [
|
|
969
|
+
item.usageDate,
|
|
970
|
+
fmtInt(item.eventCount),
|
|
971
|
+
fmtToken(item.inputTokens),
|
|
972
|
+
fmtToken(item.cachedInputTokens),
|
|
973
|
+
fmtToken(item.cacheWriteTokens),
|
|
974
|
+
fmtToken(item.outputTokens),
|
|
975
|
+
fmtToken(item.reasoningOutputTokens),
|
|
976
|
+
fmtToken(item.totalTokens),
|
|
977
|
+
fmtUsd(item.estimatedCostUsd)
|
|
978
|
+
]),
|
|
979
|
+
["left", "right", "right", "right", "right", "right", "right", "right", "right"]
|
|
980
|
+
)), lines.push(""), lines.push("Top Models"), lines.push(renderTable(
|
|
981
|
+
["Model", "Source", "Events", "Total", "Input", "Output", "Cost"],
|
|
982
|
+
report.byModel.slice(0, 12).map((item) => [
|
|
983
|
+
item.model,
|
|
984
|
+
item.source,
|
|
985
|
+
fmtInt(item.eventCount),
|
|
986
|
+
fmtToken(item.totalTokens),
|
|
987
|
+
fmtToken(item.inputTokens),
|
|
988
|
+
fmtToken(item.outputTokens),
|
|
989
|
+
fmtUsd(item.estimatedCostUsd)
|
|
990
|
+
]),
|
|
991
|
+
["left", "left", "right", "right", "right", "right", "right"]
|
|
992
|
+
)), report.pricingWarnings.length > 0) {
|
|
993
|
+
lines.push(""), lines.push("Pricing Notes");
|
|
994
|
+
for (let warning of report.pricingWarnings)
|
|
995
|
+
lines.push(`- ${warning}`);
|
|
996
|
+
}
|
|
997
|
+
return lines.join(`
|
|
998
|
+
`);
|
|
999
|
+
}
|
|
1000
|
+
function parseReportRange(value) {
|
|
1001
|
+
if (value === void 0 || value === !0) return "7d";
|
|
1002
|
+
if (value === "7d" || value === "1m" || value === "3m" || value === "all") return value;
|
|
1003
|
+
throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u3001all");
|
|
1004
|
+
}
|
|
1005
|
+
function getRangeLabel(range) {
|
|
1006
|
+
switch (range) {
|
|
1007
|
+
case "7d":
|
|
1008
|
+
return "\u6700\u8FD1 7 \u5929";
|
|
1009
|
+
case "1m":
|
|
1010
|
+
return "\u6700\u8FD1 30 \u5929";
|
|
1011
|
+
case "3m":
|
|
1012
|
+
return "\u6700\u8FD1 90 \u5929";
|
|
1013
|
+
case "all":
|
|
1014
|
+
return "\u5168\u90E8\u5386\u53F2";
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
function buildPresetDates(range) {
|
|
1018
|
+
let days = range === "7d" ? 7 : range === "1m" ? 30 : 90, today = getTodayLocalDate(), result = [];
|
|
1019
|
+
for (let offset = days - 1; offset >= 0; offset -= 1) {
|
|
1020
|
+
let day = new Date(today);
|
|
1021
|
+
day.setDate(today.getDate() - offset), result.push(toDateKey3(day));
|
|
1022
|
+
}
|
|
1023
|
+
return result;
|
|
1024
|
+
}
|
|
1025
|
+
async function discoverAllDates() {
|
|
1026
|
+
let dates = /* @__PURE__ */ new Set();
|
|
1027
|
+
return await Promise.all([discoverClaudeDates(dates), discoverCodexDates(dates)]), [...dates].sort();
|
|
1028
|
+
}
|
|
1029
|
+
async function discoverClaudeDates(dates) {
|
|
1030
|
+
let baseDir = join10(homedir11(), ".claude", "projects"), projectDirs;
|
|
1031
|
+
try {
|
|
1032
|
+
projectDirs = await readdir5(baseDir);
|
|
1033
|
+
} catch {
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
for (let projectDir of projectDirs) {
|
|
1037
|
+
let jsonlFiles = [];
|
|
1038
|
+
try {
|
|
1039
|
+
await walkForClaudeJsonl(join10(baseDir, projectDir), jsonlFiles);
|
|
1040
|
+
} catch {
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1043
|
+
for (let filePath of jsonlFiles) {
|
|
1044
|
+
let content = await safeReadUtf8(filePath);
|
|
1045
|
+
if (content)
|
|
1046
|
+
for (let line of content.split(`
|
|
1047
|
+
`)) {
|
|
1048
|
+
if (!line.trim()) continue;
|
|
1049
|
+
let record;
|
|
1050
|
+
try {
|
|
1051
|
+
record = JSON.parse(line);
|
|
1052
|
+
} catch {
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
let ts = parseTimestamp3(record.timestamp);
|
|
1056
|
+
ts && dates.add(toDateKey3(ts));
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
async function discoverCodexDates(dates) {
|
|
1062
|
+
let baseDir = join10(homedir11(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
1063
|
+
for (let filePath of files) {
|
|
1064
|
+
let content = await safeReadUtf8(filePath);
|
|
1065
|
+
if (content)
|
|
1066
|
+
for (let line of content.split(`
|
|
1067
|
+
`)) {
|
|
1068
|
+
if (!line.trim()) continue;
|
|
1069
|
+
let record;
|
|
1070
|
+
try {
|
|
1071
|
+
record = JSON.parse(line);
|
|
1072
|
+
} catch {
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
|
|
1076
|
+
let ts = parseTimestamp3(record.timestamp);
|
|
1077
|
+
ts && dates.add(toDateKey3(ts));
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
async function collectCodexSessionFiles(baseDir) {
|
|
1082
|
+
let paths = [];
|
|
1083
|
+
try {
|
|
1084
|
+
let archivedFiles = await readdir5(join10(baseDir, "archived_sessions"));
|
|
1085
|
+
for (let file of archivedFiles)
|
|
1086
|
+
file.endsWith(".jsonl") && paths.push(join10(baseDir, "archived_sessions", file));
|
|
1087
|
+
} catch {
|
|
1088
|
+
}
|
|
1089
|
+
return await walkForCodexJsonl(join10(baseDir, "sessions"), paths), paths;
|
|
1090
|
+
}
|
|
1091
|
+
async function walkForClaudeJsonl(dir, result) {
|
|
1092
|
+
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
1093
|
+
for (let entry of entries) {
|
|
1094
|
+
let fullPath = join10(dir, entry.name);
|
|
1095
|
+
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
async function walkForCodexJsonl(dir, result) {
|
|
1099
|
+
let entries;
|
|
1100
|
+
try {
|
|
1101
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
1102
|
+
} catch {
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
for (let entry of entries) {
|
|
1106
|
+
let fullPath = join10(dir, entry.name);
|
|
1107
|
+
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
async function safeReadUtf8(filePath) {
|
|
1111
|
+
try {
|
|
1112
|
+
return await readFile11(filePath, "utf-8");
|
|
1113
|
+
} catch {
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
function parseTimestamp3(value) {
|
|
1118
|
+
if (!value) return null;
|
|
1119
|
+
let date = new Date(value);
|
|
1120
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
1121
|
+
}
|
|
1122
|
+
function getTodayLocalDate() {
|
|
1123
|
+
let now = /* @__PURE__ */ new Date();
|
|
1124
|
+
return new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
|
1125
|
+
}
|
|
1126
|
+
function toDateKey3(date) {
|
|
1127
|
+
let year = date.getFullYear(), month = String(date.getMonth() + 1).padStart(2, "0"), day = String(date.getDate()).padStart(2, "0");
|
|
1128
|
+
return `${year}-${month}-${day}`;
|
|
1129
|
+
}
|
|
1130
|
+
function getOrCreate(map, key) {
|
|
1131
|
+
let existing = map.get(key);
|
|
1132
|
+
if (existing) return existing;
|
|
1133
|
+
let next = createEmptyTotals2();
|
|
1134
|
+
return map.set(key, next), next;
|
|
1135
|
+
}
|
|
1136
|
+
function withTotalTokens(totals) {
|
|
1137
|
+
return {
|
|
1138
|
+
...totals,
|
|
1139
|
+
totalTokens: totals.inputTokens + totals.cachedInputTokens + totals.cacheWriteTokens + totals.outputTokens + totals.reasoningOutputTokens,
|
|
1140
|
+
estimatedCostUsd: 0
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
function createEmptyTotals2() {
|
|
1144
|
+
return {
|
|
1145
|
+
eventCount: 0,
|
|
1146
|
+
inputTokens: 0,
|
|
1147
|
+
cachedInputTokens: 0,
|
|
1148
|
+
cacheWriteTokens: 0,
|
|
1149
|
+
outputTokens: 0,
|
|
1150
|
+
reasoningOutputTokens: 0,
|
|
1151
|
+
totalTokens: 0,
|
|
1152
|
+
estimatedCostUsd: 0
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
function mergeTotals(target, source) {
|
|
1156
|
+
return target.eventCount += source.eventCount, target.inputTokens += source.inputTokens, target.cachedInputTokens += source.cachedInputTokens, target.cacheWriteTokens += source.cacheWriteTokens, target.outputTokens += source.outputTokens, target.reasoningOutputTokens += source.reasoningOutputTokens, target.totalTokens += source.totalTokens, target.estimatedCostUsd += source.estimatedCostUsd, target;
|
|
1157
|
+
}
|
|
1158
|
+
function fmtInt(value) {
|
|
1159
|
+
return value.toLocaleString("en-US");
|
|
1160
|
+
}
|
|
1161
|
+
function fmtToken(value) {
|
|
1162
|
+
let abs = Math.abs(value);
|
|
1163
|
+
return abs < 1e3 ? fmtInt(value) : abs < 1e6 ? formatCompact(value / 1e3, "K") : abs < 1e9 ? formatCompact(value / 1e6, "M") : formatCompact(value / 1e9, "B");
|
|
1164
|
+
}
|
|
1165
|
+
function fmtUsd(value) {
|
|
1166
|
+
return `$${value.toFixed(4)}`;
|
|
1167
|
+
}
|
|
1168
|
+
function formatCompact(value, suffix) {
|
|
1169
|
+
let digits = Math.abs(value) >= 100 ? 1 : 2;
|
|
1170
|
+
return `${value.toFixed(digits).replace(/\.0+$/, "").replace(/(\.\d*[1-9])0+$/, "$1")}${suffix}`;
|
|
1171
|
+
}
|
|
1172
|
+
function renderTable(headers, rows, aligns) {
|
|
1173
|
+
if (rows.length === 0)
|
|
1174
|
+
return "(\u6682\u65E0\u6570\u636E)";
|
|
1175
|
+
let widths = headers.map(
|
|
1176
|
+
(header, index) => Math.max(
|
|
1177
|
+
header.length,
|
|
1178
|
+
...rows.map((row) => truncate(row[index] ?? "").length)
|
|
1179
|
+
)
|
|
1180
|
+
), formatRow = (row) => row.map((value, index) => {
|
|
1181
|
+
let cell = truncate(value ?? "", 42);
|
|
1182
|
+
return aligns[index] === "right" ? cell.padStart(widths[index], " ") : cell.padEnd(widths[index], " ");
|
|
1183
|
+
}).join(" "), divider = widths.map((width) => "-".repeat(width)).join(" ");
|
|
1184
|
+
return [formatRow(headers), divider, ...rows.map(formatRow)].join(`
|
|
1185
|
+
`);
|
|
1186
|
+
}
|
|
1187
|
+
function truncate(value, maxLength = 42) {
|
|
1188
|
+
return value.length <= maxLength ? value : `${value.slice(0, maxLength - 1)}\u2026`;
|
|
1189
|
+
}
|
|
1190
|
+
var CLAUDE_PRICING = {
|
|
1191
|
+
"claude-opus-4-6": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1192
|
+
"claude-opus-4-5": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1193
|
+
"claude-opus-4-1": { input: 15, cache_write_5m: 18.75, cache_write_1h: 30, cache_read: 1.5, output: 75 },
|
|
1194
|
+
"claude-opus-4": { input: 15, cache_write_5m: 18.75, cache_write_1h: 30, cache_read: 1.5, output: 75 },
|
|
1195
|
+
"claude-opus-3": { input: 15, cache_write_5m: 18.75, cache_write_1h: 30, cache_read: 1.5, output: 75 },
|
|
1196
|
+
"claude-sonnet-4-6": { input: 3, cache_write_5m: 3.75, cache_write_1h: 6, cache_read: 0.3, output: 15 },
|
|
1197
|
+
"claude-sonnet-4-5": { input: 3, cache_write_5m: 3.75, cache_write_1h: 6, cache_read: 0.3, output: 15 },
|
|
1198
|
+
"claude-sonnet-4": { input: 3, cache_write_5m: 3.75, cache_write_1h: 6, cache_read: 0.3, output: 15 },
|
|
1199
|
+
"claude-sonnet-3.7": { input: 3, cache_write_5m: 3.75, cache_write_1h: 6, cache_read: 0.3, output: 15 },
|
|
1200
|
+
"claude-haiku-4-5": { input: 1, cache_write_5m: 1.25, cache_write_1h: 2, cache_read: 0.1, output: 5 },
|
|
1201
|
+
"claude-haiku-3-5": { input: 0.8, cache_write_5m: 1, cache_write_1h: 1.6, cache_read: 0.08, output: 4 },
|
|
1202
|
+
"claude-haiku-3": { input: 0.25, cache_write_5m: 0.3, cache_write_1h: 0.5, cache_read: 0.03, output: 1.25 }
|
|
1203
|
+
}, OPENAI_PRICING = {
|
|
1204
|
+
"gpt-5.4-pro": { input: 30, cached_input: null, output: 180, estimated: !1 },
|
|
1205
|
+
"gpt-5.4": { input: 2.5, cached_input: 0.25, output: 15, estimated: !1 },
|
|
1206
|
+
"gpt-5.4-mini": { input: 0.75, cached_input: 0.075, output: 4.5, estimated: !1 },
|
|
1207
|
+
"gpt-5.4-nano": { input: 0.2, cached_input: 0.02, output: 1.25, estimated: !1 },
|
|
1208
|
+
"gpt-5.2-pro": { input: 21, cached_input: null, output: 168, estimated: !1 },
|
|
1209
|
+
"gpt-5.2": { input: 1.75, cached_input: 0.175, output: 14, estimated: !1 },
|
|
1210
|
+
"gpt-5.1": { input: 1.25, cached_input: 0.125, output: 10, estimated: !1 },
|
|
1211
|
+
"gpt-5": { input: 1.25, cached_input: 0.125, output: 10, estimated: !1 },
|
|
1212
|
+
"gpt-5-pro": { input: 15, cached_input: null, output: 120, estimated: !1 },
|
|
1213
|
+
"gpt-5-mini": { input: 0.25, cached_input: 0.025, output: 2, estimated: !1 },
|
|
1214
|
+
"gpt-5-nano": { input: 0.05, cached_input: 5e-3, output: 0.4, estimated: !1 },
|
|
1215
|
+
"gpt-5-codex": { input: 1.25, cached_input: 0.125, output: 10, estimated: !1 },
|
|
1216
|
+
"gpt-5.1-codex": { input: 1.25, cached_input: 0.125, output: 10, estimated: !1 },
|
|
1217
|
+
"gpt-5.1-codex-mini": { input: 0.25, cached_input: 0.025, output: 2, estimated: !1 },
|
|
1218
|
+
"gpt-5.1-codex-max": { input: 1.25, cached_input: 0.125, output: 10, estimated: !1 },
|
|
1219
|
+
"gpt-5.2-codex": { input: 1.75, cached_input: 0.175, output: 14, estimated: !1 },
|
|
1220
|
+
"gpt-5.3-codex": { input: 1.75, cached_input: 0.175, output: 14, estimated: !1 },
|
|
1221
|
+
"gpt-4.1": { input: 2, cached_input: 0.5, output: 8, estimated: !1 },
|
|
1222
|
+
"gpt-4.1-mini": { input: 0.4, cached_input: 0.1, output: 1.6, estimated: !1 },
|
|
1223
|
+
"gpt-4.1-nano": { input: 0.1, cached_input: 0.025, output: 0.4, estimated: !1 },
|
|
1224
|
+
"gpt-4o": { input: 2.5, cached_input: 1.25, output: 10, estimated: !1 },
|
|
1225
|
+
"gpt-4o-2024-05-13": { input: 5, cached_input: null, output: 15, estimated: !1 },
|
|
1226
|
+
"gpt-4o-mini": { input: 0.15, cached_input: 0.075, output: 0.6, estimated: !1 },
|
|
1227
|
+
o1: { input: 15, cached_input: 7.5, output: 60, estimated: !1 },
|
|
1228
|
+
"o1-pro": { input: 150, cached_input: null, output: 600, estimated: !1 },
|
|
1229
|
+
"o3-pro": { input: 20, cached_input: null, output: 80, estimated: !1 },
|
|
1230
|
+
o3: { input: 2, cached_input: 0.5, output: 8, estimated: !1 },
|
|
1231
|
+
"o4-mini": { input: 1.1, cached_input: 0.275, output: 4.4, estimated: !1 },
|
|
1232
|
+
"o3-mini": { input: 1.1, cached_input: 0.55, output: 4.4, estimated: !1 },
|
|
1233
|
+
"o1-mini": { input: 1.1, cached_input: 0.55, output: 4.4, estimated: !1 },
|
|
1234
|
+
"gpt-4-turbo-2024-04-09": { input: 10, cached_input: null, output: 30, estimated: !1 },
|
|
1235
|
+
"gpt-4-0125-preview": { input: 10, cached_input: null, output: 30, estimated: !1 },
|
|
1236
|
+
"gpt-4-1106-preview": { input: 10, cached_input: null, output: 30, estimated: !1 },
|
|
1237
|
+
"gpt-4-1106-vision-preview": { input: 10, cached_input: null, output: 30, estimated: !1 },
|
|
1238
|
+
"gpt-4-0613": { input: 30, cached_input: null, output: 60, estimated: !1 },
|
|
1239
|
+
"gpt-4-0314": { input: 30, cached_input: null, output: 60, estimated: !1 },
|
|
1240
|
+
"gpt-4-32k": { input: 60, cached_input: null, output: 120, estimated: !1 },
|
|
1241
|
+
"gpt-3.5-turbo": { input: 0.5, cached_input: null, output: 1.5, estimated: !1 },
|
|
1242
|
+
"gpt-3.5-turbo-0125": { input: 0.5, cached_input: null, output: 1.5, estimated: !1 },
|
|
1243
|
+
"gpt-3.5-turbo-1106": { input: 1, cached_input: null, output: 2, estimated: !1 },
|
|
1244
|
+
"gpt-3.5-turbo-0613": { input: 1.5, cached_input: null, output: 2, estimated: !1 },
|
|
1245
|
+
"gpt-3.5-0301": { input: 1.5, cached_input: null, output: 2, estimated: !1 },
|
|
1246
|
+
"gpt-3.5-turbo-instruct": { input: 1.5, cached_input: null, output: 2, estimated: !1 },
|
|
1247
|
+
"gpt-3.5-turbo-16k-0613": { input: 3, cached_input: null, output: 4, estimated: !1 },
|
|
1248
|
+
"davinci-002": { input: 2, cached_input: null, output: 2, estimated: !1 },
|
|
1249
|
+
"babbage-002": { input: 0.4, cached_input: null, output: 0.4, estimated: !1 },
|
|
1250
|
+
"o3-deep-research": { input: 10, cached_input: 2.5, output: 40, estimated: !1 },
|
|
1251
|
+
"o4-mini-deep-research": { input: 2, cached_input: 0.5, output: 8, estimated: !1 },
|
|
1252
|
+
"computer-use-preview": { input: 3, cached_input: null, output: 12, estimated: !1 },
|
|
1253
|
+
"text-embedding-3-small": { input: 0.02, cached_input: null, output: 0, estimated: !1 },
|
|
1254
|
+
"text-embedding-3-large": { input: 0.13, cached_input: null, output: 0, estimated: !1 },
|
|
1255
|
+
"text-embedding-ada-002": { input: 0.1, cached_input: null, output: 0, estimated: !1 },
|
|
1256
|
+
"codex-mini-latest": { input: 1.5, cached_input: 0.375, output: 6, estimated: !1 }
|
|
1257
|
+
};
|
|
1258
|
+
function toBreakdownTotals(breakdown, warnings) {
|
|
1259
|
+
let estimatedCostUsd = calculateBreakdownCost(breakdown, warnings);
|
|
1260
|
+
return {
|
|
1261
|
+
eventCount: breakdown.eventCount,
|
|
1262
|
+
inputTokens: breakdown.inputTokens,
|
|
1263
|
+
cachedInputTokens: breakdown.cachedInputTokens,
|
|
1264
|
+
cacheWriteTokens: breakdown.cacheWriteTokens,
|
|
1265
|
+
outputTokens: breakdown.outputTokens,
|
|
1266
|
+
reasoningOutputTokens: breakdown.reasoningOutputTokens,
|
|
1267
|
+
totalTokens: breakdown.inputTokens + breakdown.cachedInputTokens + breakdown.cacheWriteTokens + breakdown.outputTokens + breakdown.reasoningOutputTokens,
|
|
1268
|
+
estimatedCostUsd
|
|
1269
|
+
};
|
|
1270
|
+
}
|
|
1271
|
+
function calculateBreakdownCost(breakdown, warnings) {
|
|
1272
|
+
if (breakdown.provider === "anthropic" && breakdown.product === "claude-code") {
|
|
1273
|
+
let resolved = resolveModel(breakdown.model, CLAUDE_PRICING);
|
|
1274
|
+
if (!resolved)
|
|
1275
|
+
return warnings.add(`Claude \u6A21\u578B ${breakdown.model} \u672A\u914D\u7F6E\u516C\u5F00\u5355\u4EF7\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`), 0;
|
|
1276
|
+
resolved.normalized && warnings.add(`${breakdown.model} \u5DF2\u6309 ${resolved.model} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`);
|
|
1277
|
+
let pricing = CLAUDE_PRICING[resolved.model];
|
|
1278
|
+
return breakdown.inputTokens / 1e6 * pricing.input + ((breakdown.cacheWrite5mTokens ?? breakdown.cacheWriteTokens) || 0) / 1e6 * pricing.cache_write_5m + (breakdown.cacheWrite1hTokens ?? 0) / 1e6 * pricing.cache_write_1h + breakdown.cachedInputTokens / 1e6 * pricing.cache_read + breakdown.outputTokens / 1e6 * pricing.output;
|
|
1279
|
+
}
|
|
1280
|
+
if (breakdown.provider === "openai" && breakdown.product === "codex") {
|
|
1281
|
+
let resolved = resolveModel(breakdown.model, OPENAI_PRICING);
|
|
1282
|
+
if (!resolved)
|
|
1283
|
+
return warnings.add(`Codex/OpenAI \u6A21\u578B ${breakdown.model} \u672A\u914D\u7F6E\u516C\u5F00\u5355\u4EF7\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`), 0;
|
|
1284
|
+
let pricing = OPENAI_PRICING[resolved.model];
|
|
1285
|
+
return resolved.normalized ? warnings.add(`${breakdown.model} \u5DF2\u6309 ${resolved.model} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`) : pricing.estimated && warnings.add(`${breakdown.model} \u672A\u5728\u516C\u5F00\u4EF7\u76EE\u8868\u5355\u5217\uFF0C\u5F53\u524D\u6309 GPT-5 \u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`), breakdown.inputTokens / 1e6 * pricing.input + breakdown.cachedInputTokens / 1e6 * (pricing.cached_input ?? 0) + breakdown.outputTokens / 1e6 * pricing.output;
|
|
1286
|
+
}
|
|
1287
|
+
return warnings.add(`${breakdown.provider}/${breakdown.product} \u6682\u65E0\u672C\u5730\u5B9A\u4EF7\u7B56\u7565\uFF0C\u5DF2\u8DF3\u8FC7\u6210\u672C\u4F30\u7B97\u3002`), 0;
|
|
1288
|
+
}
|
|
1289
|
+
function resolveModel(model, pricingTable) {
|
|
1290
|
+
if (model in pricingTable)
|
|
1291
|
+
return { model, normalized: !1 };
|
|
1292
|
+
for (let known of Object.keys(pricingTable).sort((a, b) => b.length - a.length))
|
|
1293
|
+
if (model.startsWith(`${known}-`))
|
|
1294
|
+
return { model: known, normalized: !0 };
|
|
1295
|
+
return null;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
// src/config.ts
|
|
1299
|
+
import { mkdir, readFile as readFile12, writeFile } from "node:fs/promises";
|
|
1300
|
+
import { homedir as homedir12, hostname } from "node:os";
|
|
1301
|
+
import { basename as basename6, join as join11 } from "node:path";
|
|
1302
|
+
var CONFIG_DIR = join11(homedir12(), ".aiusage"), CONFIG_PATH = join11(CONFIG_DIR, "config.json");
|
|
1303
|
+
function getConfigPath() {
|
|
1304
|
+
return CONFIG_PATH;
|
|
1305
|
+
}
|
|
1306
|
+
async function readConfig() {
|
|
1307
|
+
try {
|
|
1308
|
+
let raw = await readFile12(CONFIG_PATH, "utf-8");
|
|
1309
|
+
return JSON.parse(raw);
|
|
1310
|
+
} catch {
|
|
1311
|
+
return {};
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
async function writeConfig(config) {
|
|
1315
|
+
await mkdir(CONFIG_DIR, { recursive: !0 }), await writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + `
|
|
1316
|
+
`, "utf-8");
|
|
1317
|
+
}
|
|
1318
|
+
function normalizeServerUrl(value) {
|
|
1319
|
+
return value.trim().replace(/\/+$/, "");
|
|
1320
|
+
}
|
|
1321
|
+
function detectDeviceId() {
|
|
1322
|
+
return hostname().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "unknown-device";
|
|
1323
|
+
}
|
|
1324
|
+
function getLocalTimezone() {
|
|
1325
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1326
|
+
}
|
|
1327
|
+
function setConfigValue(config, keyPath, values) {
|
|
1328
|
+
let next = structuredClone(config);
|
|
1329
|
+
if (keyPath === "server" || keyPath === "apiBaseUrl")
|
|
1330
|
+
return next.apiBaseUrl = normalizeServerUrl(requireSingleValue(keyPath, values)), next;
|
|
1331
|
+
if (keyPath === "siteId")
|
|
1332
|
+
return next.siteId = requireSingleValue(keyPath, values), next;
|
|
1333
|
+
if (keyPath === "device.id")
|
|
1334
|
+
return next.deviceId = requireSingleValue(keyPath, values), next;
|
|
1335
|
+
if (keyPath === "device.alias")
|
|
1336
|
+
return next.deviceAlias = requireSingleValue(keyPath, values), next;
|
|
1337
|
+
if (keyPath === "device.token")
|
|
1338
|
+
return next.deviceToken = requireSingleValue(keyPath, values), next;
|
|
1339
|
+
if (keyPath === "lookbackDays")
|
|
1340
|
+
return next.lookbackDays = parsePositiveInt(requireSingleValue(keyPath, values), keyPath), next;
|
|
1341
|
+
if (keyPath === "privacy.projectVisibility") {
|
|
1342
|
+
let value = requireSingleValue(keyPath, values);
|
|
1343
|
+
if (value !== "hidden" && value !== "masked" && value !== "plain")
|
|
1344
|
+
throw new Error("privacy.projectVisibility \u4EC5\u652F\u6301 hidden\u3001masked\u3001plain");
|
|
1345
|
+
return next.privacy = { ...next.privacy ?? {}, projectVisibility: value }, next;
|
|
1346
|
+
}
|
|
1347
|
+
if (keyPath === "project.alias") {
|
|
1348
|
+
if (values.length < 2)
|
|
1349
|
+
throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
|
|
1350
|
+
let [from, ...rest] = values, alias = rest.join(" ").trim();
|
|
1351
|
+
if (!alias) throw new Error("project.alias \u522B\u540D\u4E0D\u80FD\u4E3A\u7A7A");
|
|
1352
|
+
return next.projectAliases = { ...next.projectAliases ?? {}, [from]: alias }, next;
|
|
1353
|
+
}
|
|
1354
|
+
throw new Error(`\u4E0D\u652F\u6301\u7684\u914D\u7F6E\u9879: ${keyPath}`);
|
|
1355
|
+
}
|
|
1356
|
+
function requireSingleValue(keyPath, values) {
|
|
1357
|
+
let value = values.join(" ").trim();
|
|
1358
|
+
if (!value) throw new Error(`${keyPath} \u7F3A\u5C11\u503C`);
|
|
1359
|
+
return value;
|
|
1360
|
+
}
|
|
1361
|
+
function parsePositiveInt(value, keyPath) {
|
|
1362
|
+
let parsed = Number.parseInt(value, 10);
|
|
1363
|
+
if (!Number.isFinite(parsed) || parsed <= 0)
|
|
1364
|
+
throw new Error(`${keyPath} \u5FC5\u987B\u662F\u6B63\u6574\u6570`);
|
|
1365
|
+
return parsed;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
// src/api.ts
|
|
1369
|
+
import { hostname as hostname2 } from "node:os";
|
|
1370
|
+
|
|
1371
|
+
// src/version.ts
|
|
1372
|
+
import { readFileSync } from "node:fs";
|
|
1373
|
+
import { resolve, dirname as dirname5 } from "node:path";
|
|
1374
|
+
import { fileURLToPath } from "node:url";
|
|
1375
|
+
var cached;
|
|
1376
|
+
function getVersion() {
|
|
1377
|
+
if (cached !== void 0) return cached;
|
|
1378
|
+
try {
|
|
1379
|
+
let pkg = resolve(dirname5(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
1380
|
+
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
1381
|
+
} catch {
|
|
1382
|
+
cached = "unknown";
|
|
1383
|
+
}
|
|
1384
|
+
return cached;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// src/api.ts
|
|
1388
|
+
var SCHEMA_VERSION = "1.0", DEFAULT_LOOKBACK_DAYS = 7;
|
|
1389
|
+
async function fetchHealth(apiBaseUrl) {
|
|
1390
|
+
return requestJson(`${apiBaseUrl}/api/v1/health`);
|
|
1391
|
+
}
|
|
1392
|
+
async function enrollDevice(apiBaseUrl, params) {
|
|
1393
|
+
return requestJson(`${apiBaseUrl}/api/v1/enroll`, {
|
|
1394
|
+
method: "POST",
|
|
1395
|
+
headers: {
|
|
1396
|
+
Authorization: `Bearer ${params.enrollToken}`,
|
|
1397
|
+
"Content-Type": "application/json"
|
|
1398
|
+
},
|
|
1399
|
+
body: JSON.stringify({
|
|
1400
|
+
siteId: params.siteId,
|
|
1401
|
+
deviceId: params.deviceId,
|
|
1402
|
+
deviceAlias: params.deviceAlias,
|
|
1403
|
+
hostname: hostname2(),
|
|
1404
|
+
timezone: getLocalTimezone(),
|
|
1405
|
+
appVersion: getVersion()
|
|
1406
|
+
})
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
async function uploadDailyUsage(apiBaseUrl, config, days) {
|
|
1410
|
+
return requestJson(`${apiBaseUrl}/api/v1/ingest/daily`, {
|
|
1411
|
+
method: "POST",
|
|
1412
|
+
headers: {
|
|
1413
|
+
Authorization: `Bearer ${config.deviceToken}`,
|
|
1414
|
+
"Content-Type": "application/json"
|
|
1415
|
+
},
|
|
1416
|
+
body: JSON.stringify({
|
|
1417
|
+
siteId: config.siteId,
|
|
1418
|
+
schemaVersion: SCHEMA_VERSION,
|
|
1419
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1420
|
+
device: {
|
|
1421
|
+
deviceId: config.deviceId,
|
|
1422
|
+
deviceAlias: config.deviceAlias,
|
|
1423
|
+
hostname: hostname2(),
|
|
1424
|
+
timezone: getLocalTimezone(),
|
|
1425
|
+
appVersion: getVersion()
|
|
1426
|
+
},
|
|
1427
|
+
days
|
|
1428
|
+
})
|
|
1429
|
+
});
|
|
1430
|
+
}
|
|
1431
|
+
function defaultLookbackDays(config) {
|
|
1432
|
+
return config.lookbackDays ?? DEFAULT_LOOKBACK_DAYS;
|
|
1433
|
+
}
|
|
1434
|
+
async function requestJson(url, init) {
|
|
1435
|
+
let response = await fetch(url, init), text = await response.text(), data = null;
|
|
1436
|
+
if (text)
|
|
1437
|
+
try {
|
|
1438
|
+
data = JSON.parse(text);
|
|
1439
|
+
} catch {
|
|
1440
|
+
throw new Error(`\u670D\u52A1\u7AEF\u8FD4\u56DE\u4E86\u975E JSON \u54CD\u5E94 (${response.status})`);
|
|
1441
|
+
}
|
|
1442
|
+
if (!response.ok) {
|
|
1443
|
+
let error = data?.error;
|
|
1444
|
+
throw new Error(error?.message ?? `\u8BF7\u6C42\u5931\u8D25 (${response.status})`);
|
|
1445
|
+
}
|
|
1446
|
+
if (!data)
|
|
1447
|
+
throw new Error("\u670D\u52A1\u7AEF\u8FD4\u56DE\u4E86\u7A7A\u54CD\u5E94");
|
|
1448
|
+
return data;
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// src/schedule.ts
|
|
1452
|
+
import { mkdir as mkdir2, readFile as readFile13, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
1453
|
+
import { execFile } from "node:child_process";
|
|
1454
|
+
import { promisify } from "node:util";
|
|
1455
|
+
import { homedir as homedir13, platform, tmpdir } from "node:os";
|
|
1456
|
+
import { join as join12, resolve as resolve2 } from "node:path";
|
|
1457
|
+
var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join12(homedir13(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join12(homedir13(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
|
|
1458
|
+
function parseInterval(value) {
|
|
1459
|
+
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
1460
|
+
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
1461
|
+
let num = parseInt(match[1], 10), unit = match[2], seconds;
|
|
1462
|
+
switch (unit) {
|
|
1463
|
+
case "m":
|
|
1464
|
+
seconds = num * 60;
|
|
1465
|
+
break;
|
|
1466
|
+
case "h":
|
|
1467
|
+
seconds = num * 3600;
|
|
1468
|
+
break;
|
|
1469
|
+
case "d":
|
|
1470
|
+
seconds = num * 86400;
|
|
1471
|
+
break;
|
|
1472
|
+
default:
|
|
1473
|
+
throw new Error("\u4E0D\u652F\u6301\u7684\u65F6\u95F4\u5355\u4F4D");
|
|
1474
|
+
}
|
|
1475
|
+
if (seconds < 300) throw new Error("\u95F4\u9694\u4E0D\u80FD\u5C11\u4E8E 5 \u5206\u949F");
|
|
1476
|
+
if (seconds > 86400) throw new Error("\u95F4\u9694\u4E0D\u80FD\u8D85\u8FC7 1 \u5929");
|
|
1477
|
+
return { seconds, label: value };
|
|
1478
|
+
}
|
|
1479
|
+
function formatInterval(seconds) {
|
|
1480
|
+
return seconds >= 86400 && seconds % 86400 === 0 ? `${seconds / 86400}d` : seconds >= 3600 && seconds % 3600 === 0 ? `${seconds / 3600}h` : seconds % 60 === 0 ? `${seconds / 60}m` : `${seconds}s`;
|
|
1481
|
+
}
|
|
1482
|
+
async function enableSchedule(intervalSeconds) {
|
|
1483
|
+
return platform() === "darwin" ? enableLaunchd(intervalSeconds) : enableCron(intervalSeconds);
|
|
1484
|
+
}
|
|
1485
|
+
async function disableSchedule() {
|
|
1486
|
+
return platform() === "darwin" ? disableLaunchd() : disableCron();
|
|
1487
|
+
}
|
|
1488
|
+
async function getScheduleStatus() {
|
|
1489
|
+
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
1490
|
+
}
|
|
1491
|
+
function resolveCommandPaths() {
|
|
1492
|
+
let scriptPath = resolve2(process.argv[1]);
|
|
1493
|
+
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
1494
|
+
throw new Error(
|
|
1495
|
+
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
1496
|
+
\u8BF7\u5148\u6267\u884C: npm install -g @aiusage/cli`
|
|
1497
|
+
);
|
|
1498
|
+
return { nodePath: process.execPath, scriptPath };
|
|
1499
|
+
}
|
|
1500
|
+
async function enableLaunchd(intervalSeconds) {
|
|
1501
|
+
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
1502
|
+
await mkdir2(join12(homedir13(), ".aiusage"), { recursive: !0 });
|
|
1503
|
+
let plist = [
|
|
1504
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
1505
|
+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
1506
|
+
'<plist version="1.0">',
|
|
1507
|
+
"<dict>",
|
|
1508
|
+
" <key>Label</key>",
|
|
1509
|
+
` <string>${LABEL}</string>`,
|
|
1510
|
+
" <key>ProgramArguments</key>",
|
|
1511
|
+
" <array>",
|
|
1512
|
+
` <string>${escapeXml(nodePath)}</string>`,
|
|
1513
|
+
` <string>${escapeXml(scriptPath)}</string>`,
|
|
1514
|
+
" <string>sync</string>",
|
|
1515
|
+
" <string>--today</string>",
|
|
1516
|
+
" </array>",
|
|
1517
|
+
" <key>StartInterval</key>",
|
|
1518
|
+
` <integer>${intervalSeconds}</integer>`,
|
|
1519
|
+
" <key>StandardOutPath</key>",
|
|
1520
|
+
` <string>${escapeXml(LOG_PATH)}</string>`,
|
|
1521
|
+
" <key>StandardErrorPath</key>",
|
|
1522
|
+
` <string>${escapeXml(LOG_PATH)}</string>`,
|
|
1523
|
+
"</dict>",
|
|
1524
|
+
"</plist>",
|
|
1525
|
+
""
|
|
1526
|
+
].join(`
|
|
1527
|
+
`);
|
|
1528
|
+
try {
|
|
1529
|
+
await execFileAsync("launchctl", ["unload", PLIST_PATH]);
|
|
1530
|
+
} catch {
|
|
1531
|
+
}
|
|
1532
|
+
return await writeFile2(PLIST_PATH, plist, "utf-8"), await execFileAsync("launchctl", ["load", PLIST_PATH]), {
|
|
1533
|
+
enabled: !0,
|
|
1534
|
+
interval: intervalSeconds,
|
|
1535
|
+
intervalLabel: formatInterval(intervalSeconds),
|
|
1536
|
+
path: PLIST_PATH
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
async function disableLaunchd() {
|
|
1540
|
+
try {
|
|
1541
|
+
await execFileAsync("launchctl", ["unload", PLIST_PATH]);
|
|
1542
|
+
} catch {
|
|
1543
|
+
}
|
|
1544
|
+
try {
|
|
1545
|
+
await unlink(PLIST_PATH);
|
|
1546
|
+
} catch {
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
async function getLaunchdStatus() {
|
|
1550
|
+
try {
|
|
1551
|
+
await stat(PLIST_PATH);
|
|
1552
|
+
} catch {
|
|
1553
|
+
return { enabled: !1 };
|
|
1554
|
+
}
|
|
1555
|
+
try {
|
|
1556
|
+
let match = (await readFile13(PLIST_PATH, "utf-8")).match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0;
|
|
1557
|
+
return {
|
|
1558
|
+
enabled: !0,
|
|
1559
|
+
interval,
|
|
1560
|
+
intervalLabel: interval ? formatInterval(interval) : void 0,
|
|
1561
|
+
path: PLIST_PATH
|
|
1562
|
+
};
|
|
1563
|
+
} catch {
|
|
1564
|
+
return { enabled: !1 };
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
async function enableCron(intervalSeconds) {
|
|
1568
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join12(homedir13(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
1569
|
+
await mkdir2(join12(homedir13(), ".aiusage"), { recursive: !0 });
|
|
1570
|
+
let existing = "";
|
|
1571
|
+
try {
|
|
1572
|
+
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
1573
|
+
existing = stdout;
|
|
1574
|
+
} catch {
|
|
1575
|
+
}
|
|
1576
|
+
let filtered = existing.split(`
|
|
1577
|
+
`).filter((line) => !line.includes(CRON_MARKER)).join(`
|
|
1578
|
+
`).trimEnd(), newContent = filtered ? `${filtered}
|
|
1579
|
+
${cronLine}
|
|
1580
|
+
` : `${cronLine}
|
|
1581
|
+
`;
|
|
1582
|
+
return await writeCrontab(newContent), {
|
|
1583
|
+
enabled: !0,
|
|
1584
|
+
interval: intervalSeconds,
|
|
1585
|
+
intervalLabel: formatInterval(intervalSeconds)
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
async function disableCron() {
|
|
1589
|
+
let existing = "";
|
|
1590
|
+
try {
|
|
1591
|
+
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
1592
|
+
existing = stdout;
|
|
1593
|
+
} catch {
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
let filtered = existing.split(`
|
|
1597
|
+
`).filter((line) => !line.includes(CRON_MARKER)).join(`
|
|
1598
|
+
`).trimEnd();
|
|
1599
|
+
if (filtered)
|
|
1600
|
+
await writeCrontab(filtered + `
|
|
1601
|
+
`);
|
|
1602
|
+
else
|
|
1603
|
+
try {
|
|
1604
|
+
await execFileAsync("crontab", ["-r"]);
|
|
1605
|
+
} catch {
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
async function getCronStatus() {
|
|
1609
|
+
try {
|
|
1610
|
+
let { stdout } = await execFileAsync("crontab", ["-l"]), line = stdout.split(`
|
|
1611
|
+
`).find((l) => l.includes(CRON_MARKER));
|
|
1612
|
+
if (!line) return { enabled: !1 };
|
|
1613
|
+
let interval = cronToSeconds(line);
|
|
1614
|
+
return {
|
|
1615
|
+
enabled: !0,
|
|
1616
|
+
interval,
|
|
1617
|
+
intervalLabel: interval ? formatInterval(interval) : void 0
|
|
1618
|
+
};
|
|
1619
|
+
} catch {
|
|
1620
|
+
return { enabled: !1 };
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
async function writeCrontab(content) {
|
|
1624
|
+
let tmpFile = join12(tmpdir(), `aiusage-cron-${Date.now()}`);
|
|
1625
|
+
await writeFile2(tmpFile, content, "utf-8");
|
|
1626
|
+
try {
|
|
1627
|
+
await execFileAsync("crontab", [tmpFile]);
|
|
1628
|
+
} finally {
|
|
1629
|
+
try {
|
|
1630
|
+
await unlink(tmpFile);
|
|
1631
|
+
} catch {
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
function secondsToCron(seconds) {
|
|
1636
|
+
let minutes = Math.round(seconds / 60);
|
|
1637
|
+
if (minutes <= 60) return `*/${minutes} * * * *`;
|
|
1638
|
+
let hours = Math.round(seconds / 3600);
|
|
1639
|
+
return hours < 24 ? `0 */${hours} * * *` : "10 0 * * *";
|
|
1640
|
+
}
|
|
1641
|
+
function cronToSeconds(cronLine) {
|
|
1642
|
+
let parts = cronLine.trim().split(/\s+/);
|
|
1643
|
+
if (parts.length < 5) return;
|
|
1644
|
+
let [minute, hour] = parts, minMatch = minute.match(/^\*\/(\d+)$/);
|
|
1645
|
+
if (minMatch) return parseInt(minMatch[1], 10) * 60;
|
|
1646
|
+
let hourMatch = hour.match(/^\*\/(\d+)$/);
|
|
1647
|
+
if (hourMatch && minute === "0") return parseInt(hourMatch[1], 10) * 3600;
|
|
1648
|
+
if (minute === "10" && hour === "0") return 86400;
|
|
1649
|
+
}
|
|
1650
|
+
function escapeXml(value) {
|
|
1651
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// src/doctor.ts
|
|
1655
|
+
import { stat as stat2 } from "node:fs/promises";
|
|
1656
|
+
import { homedir as homedir14 } from "node:os";
|
|
1657
|
+
import { join as join13 } from "node:path";
|
|
1658
|
+
async function runDoctor() {
|
|
1659
|
+
let checks = [], config = await readConfig(), configPath = getConfigPath();
|
|
1660
|
+
try {
|
|
1661
|
+
await stat2(configPath), checks.push({ name: "\u914D\u7F6E\u6587\u4EF6", status: "ok", message: configPath });
|
|
1662
|
+
} catch {
|
|
1663
|
+
checks.push({ name: "\u914D\u7F6E\u6587\u4EF6", status: "fail", message: "\u672A\u627E\u5230\uFF0C\u8BF7\u5148\u6267\u884C aiusage init" });
|
|
1664
|
+
}
|
|
1665
|
+
let fields = [
|
|
1666
|
+
["apiBaseUrl", "\u670D\u52A1\u7AEF\u5730\u5740", "\u8BF7\u6267\u884C aiusage init --server <URL>"],
|
|
1667
|
+
["siteId", "\u7AD9\u70B9 ID", "\u8BF7\u6267\u884C aiusage init --site-id <ID>"],
|
|
1668
|
+
["deviceId", "\u8BBE\u5907 ID", "\u8BF7\u6267\u884C aiusage init"],
|
|
1669
|
+
["deviceToken", "\u8BBE\u5907\u4EE4\u724C", "\u8BF7\u6267\u884C aiusage enroll"]
|
|
1670
|
+
];
|
|
1671
|
+
for (let [key, label, hint] of fields) {
|
|
1672
|
+
let value = config[key];
|
|
1673
|
+
if (value) {
|
|
1674
|
+
let display = key === "deviceToken" ? `${String(value).slice(0, 12)}\u2026` : String(value);
|
|
1675
|
+
checks.push({ name: label, status: "ok", message: display });
|
|
1676
|
+
} else
|
|
1677
|
+
checks.push({
|
|
1678
|
+
name: label,
|
|
1679
|
+
status: key === "deviceToken" ? "fail" : "warn",
|
|
1680
|
+
message: `\u672A\u914D\u7F6E\uFF0C${hint}`
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
if (config.apiBaseUrl)
|
|
1684
|
+
try {
|
|
1685
|
+
let health = await fetchHealth(config.apiBaseUrl);
|
|
1686
|
+
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "ok", message: `${health.siteId} (v${health.version})` });
|
|
1687
|
+
} catch (err) {
|
|
1688
|
+
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "fail", message: err instanceof Error ? err.message : String(err) });
|
|
1689
|
+
}
|
|
1690
|
+
else
|
|
1691
|
+
checks.push({ name: "\u670D\u52A1\u7AEF\u8FDE\u901A", status: "warn", message: "\u8DF3\u8FC7\uFF08\u672A\u914D\u7F6E\u670D\u52A1\u7AEF\u5730\u5740\uFF09" });
|
|
1692
|
+
let scannerDirs = [
|
|
1693
|
+
[join13(homedir14(), ".claude", "projects"), "Claude \u65E5\u5FD7"],
|
|
1694
|
+
[join13(homedir14(), ".codex"), "Codex \u65E5\u5FD7"]
|
|
1695
|
+
];
|
|
1696
|
+
for (let [dir, label] of scannerDirs)
|
|
1697
|
+
try {
|
|
1698
|
+
await stat2(dir), checks.push({ name: label, status: "ok", message: dir });
|
|
1699
|
+
} catch {
|
|
1700
|
+
checks.push({ name: label, status: "warn", message: "\u76EE\u5F55\u4E0D\u5B58\u5728\uFF08\u672A\u4F7F\u7528\u53EF\u5FFD\u7565\uFF09" });
|
|
1701
|
+
}
|
|
1702
|
+
let schedule = await getScheduleStatus();
|
|
1703
|
+
return schedule.enabled ? checks.push({
|
|
1704
|
+
name: "\u5B9A\u65F6\u540C\u6B65",
|
|
1705
|
+
status: "ok",
|
|
1706
|
+
message: schedule.intervalLabel ? `\u6BCF ${schedule.intervalLabel}` : "\u5DF2\u542F\u7528"
|
|
1707
|
+
}) : checks.push({ name: "\u5B9A\u65F6\u540C\u6B65", status: "warn", message: "\u672A\u542F\u7528\uFF0C\u53EF\u6267\u884C aiusage schedule on" }), config.lastSuccessfulUploadAt ? checks.push({ name: "\u4E0A\u6B21\u540C\u6B65", status: "ok", message: config.lastSuccessfulUploadAt }) : checks.push({ name: "\u4E0A\u6B21\u540C\u6B65", status: "warn", message: "\u6682\u65E0\u8BB0\u5F55" }), checks;
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
// src/cli.ts
|
|
1711
|
+
var argv = process.argv.slice(2), command = argv[0];
|
|
1712
|
+
try {
|
|
1713
|
+
if (command === "--version" || command === "-v")
|
|
1714
|
+
console.log(getVersion());
|
|
1715
|
+
else if (command === "scan") {
|
|
1716
|
+
let parsed = parseArgs(argv.slice(1)), date = typeof parsed.flags.date == "string" ? parsed.flags.date : getYesterdayDate();
|
|
1717
|
+
await runScan(date, !!parsed.flags.json);
|
|
1718
|
+
} else if (command === "report") {
|
|
1719
|
+
let parsed = parseArgs(argv.slice(1));
|
|
1720
|
+
await runReport(parsed.flags);
|
|
1721
|
+
} else if (command === "health") {
|
|
1722
|
+
let parsed = parseArgs(argv.slice(1));
|
|
1723
|
+
await runHealth(parsed.flags.server);
|
|
1724
|
+
} else if (command === "enroll") {
|
|
1725
|
+
let parsed = parseArgs(argv.slice(1));
|
|
1726
|
+
await runEnroll(parsed.flags);
|
|
1727
|
+
} else if (command === "sync") {
|
|
1728
|
+
let parsed = parseArgs(argv.slice(1));
|
|
1729
|
+
await runSync(parsed.flags);
|
|
1730
|
+
} else if (command === "init") {
|
|
1731
|
+
let parsed = parseArgs(argv.slice(1));
|
|
1732
|
+
await runInit(parsed.flags);
|
|
1733
|
+
} else if (command === "schedule") {
|
|
1734
|
+
let sub = argv[1];
|
|
1735
|
+
if (sub === "off")
|
|
1736
|
+
await runSchedule("off", {});
|
|
1737
|
+
else if (sub === "status")
|
|
1738
|
+
await runSchedule("status", {});
|
|
1739
|
+
else if (sub === "on") {
|
|
1740
|
+
let parsed = parseArgs(argv.slice(2));
|
|
1741
|
+
await runSchedule("on", parsed.flags);
|
|
1742
|
+
} else {
|
|
1743
|
+
let parsed = parseArgs(argv.slice(1));
|
|
1744
|
+
await runSchedule("on", parsed.flags);
|
|
1745
|
+
}
|
|
1746
|
+
} else command === "doctor" ? await runDoctorCommand() : command === "config" && argv[1] === "set" ? await runConfigSet(argv.slice(2)) : command === "setup" ? (console.log(`To deploy the server, clone the repo and run the setup wizard:
|
|
1747
|
+
`), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
|
|
1748
|
+
`), console.log("See: https://github.com/ennann/aiusage#deploy-your-own-server")) : printHelp();
|
|
1749
|
+
} catch (error) {
|
|
1750
|
+
console.error(error instanceof Error ? error.message : String(error)), process.exitCode = 1;
|
|
1751
|
+
}
|
|
1752
|
+
async function runScan(date, isJson) {
|
|
1753
|
+
let config = await readConfig();
|
|
1754
|
+
isJson || console.log(`\u626B\u63CF\u65E5\u671F: ${date}
|
|
1755
|
+
`);
|
|
1756
|
+
let result = await scanDate(date, { projectAliases: config.projectAliases });
|
|
1757
|
+
if (isJson) {
|
|
1758
|
+
console.log(JSON.stringify(result, null, 2));
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
if (result.breakdowns.length === 0) {
|
|
1762
|
+
console.log("\u8BE5\u65E5\u65E0\u6570\u636E\u3002");
|
|
1763
|
+
return;
|
|
1764
|
+
}
|
|
1765
|
+
let byProvider = /* @__PURE__ */ new Map();
|
|
1766
|
+
for (let b of result.breakdowns) {
|
|
1767
|
+
let key = `${b.provider}/${b.product}`;
|
|
1768
|
+
byProvider.has(key) || byProvider.set(key, []), byProvider.get(key).push(b);
|
|
1769
|
+
}
|
|
1770
|
+
for (let [provider, breakdowns] of byProvider) {
|
|
1771
|
+
console.log(`\u2500\u2500 ${provider} \u2500\u2500`);
|
|
1772
|
+
for (let b of breakdowns.sort((a, c) => c.inputTokens - a.inputTokens))
|
|
1773
|
+
console.log(` ${b.model} | ${b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt(b.outputTokens)} \u63A8\u7406: ${fmt(b.reasoningOutputTokens)}`);
|
|
1774
|
+
console.log();
|
|
1775
|
+
}
|
|
1776
|
+
console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt(result.totals.outputTokens)} \u63A8\u7406: ${fmt(result.totals.reasoningOutputTokens)}`);
|
|
1777
|
+
}
|
|
1778
|
+
async function runReport(flags) {
|
|
1779
|
+
let config = await readConfig(), range = parseReportRange(flags.range), report = await buildLocalReport(range, { projectAliases: config.projectAliases });
|
|
1780
|
+
if (flags.json) {
|
|
1781
|
+
console.log(JSON.stringify(report, null, 2));
|
|
1782
|
+
return;
|
|
1783
|
+
}
|
|
1784
|
+
console.log(renderLocalReport(report));
|
|
1785
|
+
}
|
|
1786
|
+
function fmt(n) {
|
|
1787
|
+
return n.toLocaleString("en-US");
|
|
1788
|
+
}
|
|
1789
|
+
async function runHealth(serverFlag) {
|
|
1790
|
+
let config = await readConfig(), apiBaseUrl = resolveServer(serverFlag, config.apiBaseUrl), health = await fetchHealth(apiBaseUrl);
|
|
1791
|
+
console.log(JSON.stringify(health, null, 2));
|
|
1792
|
+
}
|
|
1793
|
+
async function runEnroll(flags) {
|
|
1794
|
+
let config = await readConfig(), apiBaseUrl = resolveServer(flags.server, config.apiBaseUrl), siteId = resolveRequiredString(flags["site-id"] ?? flags.siteId, config.siteId, "\u7F3A\u5C11 --site-id"), enrollToken = resolveRequiredString(flags["enroll-token"], void 0, "\u7F3A\u5C11 --enroll-token"), deviceId = resolveOptionalString(flags["device-id"], config.deviceId) ?? detectDeviceId(), deviceAlias = resolveOptionalString(flags["device-name"] ?? flags["device-alias"], config.deviceAlias), response = await enrollDevice(apiBaseUrl, { siteId, deviceId, deviceAlias, enrollToken });
|
|
1795
|
+
await writeConfig({
|
|
1796
|
+
...config,
|
|
1797
|
+
apiBaseUrl,
|
|
1798
|
+
siteId,
|
|
1799
|
+
deviceId,
|
|
1800
|
+
deviceAlias,
|
|
1801
|
+
deviceToken: response.deviceToken,
|
|
1802
|
+
lookbackDays: config.lookbackDays ?? 7
|
|
1803
|
+
}), console.log(JSON.stringify({
|
|
1804
|
+
siteId: response.siteId,
|
|
1805
|
+
deviceId: response.deviceId,
|
|
1806
|
+
issuedAt: response.issuedAt,
|
|
1807
|
+
configPath: getConfigPath()
|
|
1808
|
+
}, null, 2));
|
|
1809
|
+
}
|
|
1810
|
+
async function runSync(flags) {
|
|
1811
|
+
let config = await readConfig(), apiBaseUrl = resolveServer(flags.server, config.apiBaseUrl), siteId = resolveRequiredString(void 0, config.siteId, "\u7F3A\u5C11 siteId\uFF0C\u8BF7\u5148\u6267\u884C init \u6216 enroll"), deviceId = resolveRequiredString(void 0, config.deviceId, "\u7F3A\u5C11 deviceId\uFF0C\u8BF7\u5148\u6267\u884C init \u6216 enroll"), deviceToken = resolveRequiredString(void 0, config.deviceToken, "\u7F3A\u5C11 deviceToken\uFF0C\u8BF7\u5148\u6267\u884C enroll"), requestedDate = typeof flags.date == "string" ? flags.date : void 0, fromDate = typeof flags.from == "string" ? flags.from : void 0, toDate = typeof flags.to == "string" ? flags.to : void 0, includeToday = !!flags.today, targetDates;
|
|
1812
|
+
if (requestedDate)
|
|
1813
|
+
targetDates = [requestedDate];
|
|
1814
|
+
else if (fromDate)
|
|
1815
|
+
targetDates = buildDateRange(fromDate, toDate ?? getYesterdayDate());
|
|
1816
|
+
else {
|
|
1817
|
+
let lookbackDays = typeof flags.lookback == "string" ? parsePositiveInt2(flags.lookback, "--lookback") : defaultLookbackDays(config);
|
|
1818
|
+
targetDates = getClosedDates(lookbackDays), includeToday && targetDates.push(getTodayDate());
|
|
1819
|
+
}
|
|
1820
|
+
console.log(`\u626B\u63CF ${targetDates.length} \u5929 (${targetDates[0]} ~ ${targetDates[targetDates.length - 1]})${includeToday ? " [\u542B\u4ECA\u65E5]" : ""} ...`);
|
|
1821
|
+
let allDays = (await scanDates(targetDates, { projectAliases: config.projectAliases })).filter((r) => r.breakdowns.length > 0).map((r) => ({ usageDate: r.usageDate, breakdowns: r.breakdowns }));
|
|
1822
|
+
if (allDays.length === 0) {
|
|
1823
|
+
console.log("\u6CA1\u6709\u53EF\u4E0A\u4F20\u7684\u6570\u636E\u3002");
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
console.log(`\u53D1\u73B0 ${allDays.length} \u5929\u6709\u6570\u636E\uFF0C\u5F00\u59CB\u4E0A\u4F20 ...`);
|
|
1827
|
+
let BATCH_SIZE = 30, totalProcessed = 0, allCostSummary = {};
|
|
1828
|
+
for (let i = 0; i < allDays.length; i += BATCH_SIZE) {
|
|
1829
|
+
let batch = allDays.slice(i, i + BATCH_SIZE), batchNum = Math.floor(i / BATCH_SIZE) + 1, totalBatches = Math.ceil(allDays.length / BATCH_SIZE);
|
|
1830
|
+
totalBatches > 1 && console.log(` \u6279\u6B21 ${batchNum}/${totalBatches}: ${batch[0].usageDate} ~ ${batch[batch.length - 1].usageDate}`);
|
|
1831
|
+
let response = await uploadDailyUsage(
|
|
1832
|
+
apiBaseUrl,
|
|
1833
|
+
{ siteId, deviceId, deviceAlias: config.deviceAlias, deviceToken },
|
|
1834
|
+
batch
|
|
1835
|
+
);
|
|
1836
|
+
totalProcessed += response.daysProcessed, Object.assign(allCostSummary, response.costSummary);
|
|
1837
|
+
}
|
|
1838
|
+
await writeConfig({
|
|
1839
|
+
...config,
|
|
1840
|
+
apiBaseUrl,
|
|
1841
|
+
siteId,
|
|
1842
|
+
deviceId,
|
|
1843
|
+
deviceToken,
|
|
1844
|
+
lastSuccessfulUploadAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1845
|
+
}), console.log(JSON.stringify({
|
|
1846
|
+
uploadedDays: allDays.map((day) => day.usageDate),
|
|
1847
|
+
daysProcessed: totalProcessed,
|
|
1848
|
+
costSummary: allCostSummary
|
|
1849
|
+
}, null, 2));
|
|
1850
|
+
}
|
|
1851
|
+
async function runInit(flags) {
|
|
1852
|
+
let config = await readConfig(), next = {
|
|
1853
|
+
...config,
|
|
1854
|
+
apiBaseUrl: typeof flags.server == "string" ? normalizeServerUrl(flags.server) : config.apiBaseUrl,
|
|
1855
|
+
siteId: resolveOptionalString(flags["site-id"] ?? flags.siteId, config.siteId),
|
|
1856
|
+
deviceId: resolveOptionalString(flags["device-id"], config.deviceId) ?? detectDeviceId(),
|
|
1857
|
+
deviceAlias: resolveOptionalString(flags["device-name"] ?? flags["device-alias"], config.deviceAlias) ?? hostname3(),
|
|
1858
|
+
lookbackDays: typeof flags.lookback == "string" ? parsePositiveInt2(flags.lookback, "--lookback") : config.lookbackDays ?? 7
|
|
1859
|
+
};
|
|
1860
|
+
await writeConfig(next), console.log(JSON.stringify({ configPath: getConfigPath(), config: next }, null, 2));
|
|
1861
|
+
}
|
|
1862
|
+
async function runSchedule(sub, flags) {
|
|
1863
|
+
if (sub === "on") {
|
|
1864
|
+
let every = typeof flags.every == "string" ? flags.every : "5m", { seconds } = parseInterval(every), status = await enableSchedule(seconds);
|
|
1865
|
+
console.log(`\u5B9A\u65F6\u540C\u6B65\u5DF2\u542F\u7528\uFF0C\u6BCF ${status.intervalLabel} \u6267\u884C\u4E00\u6B21\uFF08\u542B\u4ECA\u65E5\u6570\u636E\uFF09\u3002`), status.path && console.log(`\u914D\u7F6E: ${status.path}`), console.log("\u65E5\u5FD7: ~/.aiusage/sync.log");
|
|
1866
|
+
} else if (sub === "off")
|
|
1867
|
+
await disableSchedule(), console.log("\u5B9A\u65F6\u540C\u6B65\u5DF2\u5173\u95ED\u3002");
|
|
1868
|
+
else {
|
|
1869
|
+
let status = await getScheduleStatus();
|
|
1870
|
+
status.enabled ? (console.log("\u72B6\u6001: \u5DF2\u542F\u7528"), status.intervalLabel && console.log(`\u95F4\u9694: \u6BCF ${status.intervalLabel}`), status.path && console.log(`\u914D\u7F6E: ${status.path}`)) : (console.log("\u72B6\u6001: \u672A\u542F\u7528"), console.log("\u542F\u7528: aiusage schedule [--every 5m]"));
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
async function runDoctorCommand() {
|
|
1874
|
+
let checks = await runDoctor();
|
|
1875
|
+
for (let check of checks) {
|
|
1876
|
+
let icon = check.status === "ok" ? "\u2713" : check.status === "warn" ? "\u26A0" : "\u2717";
|
|
1877
|
+
console.log(`${icon} ${check.name}: ${check.message}`);
|
|
1878
|
+
}
|
|
1879
|
+
checks.filter((c) => c.status === "fail").length > 0 && (process.exitCode = 1);
|
|
1880
|
+
}
|
|
1881
|
+
async function runConfigSet(args) {
|
|
1882
|
+
let [keyPath, ...values] = args;
|
|
1883
|
+
if (!keyPath) throw new Error("config set \u7F3A\u5C11\u914D\u7F6E\u9879");
|
|
1884
|
+
let config = await readConfig(), next = setConfigValue(config, keyPath, values);
|
|
1885
|
+
await writeConfig(next), console.log(JSON.stringify({ configPath: getConfigPath(), updated: keyPath }, null, 2));
|
|
1886
|
+
}
|
|
1887
|
+
function printHelp() {
|
|
1888
|
+
let initialized = existsSync(getConfigPath());
|
|
1889
|
+
console.log(`aiusage v${getVersion()}
|
|
1890
|
+
`), console.log("Usage: aiusage <command>"), console.log(""), console.log("Commands:"), console.log(" aiusage init [--server URL] [--site-id ID] [--device-id ID] [--device-name NAME] [--lookback N]"), console.log(" aiusage health [--server URL]"), console.log(" aiusage enroll --server URL --site-id ID --enroll-token TOKEN [--device-id ID] [--device-name NAME]"), console.log(" aiusage sync [--date YYYY-MM-DD] [--from YYYY-MM-DD [--to YYYY-MM-DD]] [--lookback N] [--today] [--server URL]"), console.log(" aiusage scan [--date YYYY-MM-DD] [--json]"), console.log(" aiusage report [--range 7d|1m|3m|all] [--json]"), console.log(" aiusage schedule [on|off|status] [--every 5m]"), console.log(" aiusage doctor"), console.log(" aiusage config set <key> <value...>"), console.log(""), console.log(`\u914D\u7F6E\u6587\u4EF6: ${getConfigPath()}${initialized ? "" : " (\u5C1A\u672A\u521D\u59CB\u5316)"}`);
|
|
1891
|
+
}
|
|
1892
|
+
function parseArgs(args) {
|
|
1893
|
+
let flags = {}, positionals = [];
|
|
1894
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
1895
|
+
let arg = args[index];
|
|
1896
|
+
if (!arg.startsWith("--")) {
|
|
1897
|
+
positionals.push(arg);
|
|
1898
|
+
continue;
|
|
1899
|
+
}
|
|
1900
|
+
let trimmed = arg.slice(2), eqIndex = trimmed.indexOf("=");
|
|
1901
|
+
if (eqIndex >= 0) {
|
|
1902
|
+
flags[trimmed.slice(0, eqIndex)] = trimmed.slice(eqIndex + 1);
|
|
1903
|
+
continue;
|
|
1904
|
+
}
|
|
1905
|
+
let next = args[index + 1];
|
|
1906
|
+
if (!next || next.startsWith("--")) {
|
|
1907
|
+
flags[trimmed] = !0;
|
|
1908
|
+
continue;
|
|
1909
|
+
}
|
|
1910
|
+
flags[trimmed] = next, index += 1;
|
|
1911
|
+
}
|
|
1912
|
+
return { flags, positionals };
|
|
1913
|
+
}
|
|
1914
|
+
function getYesterdayDate() {
|
|
1915
|
+
let yesterday = /* @__PURE__ */ new Date();
|
|
1916
|
+
return yesterday.setDate(yesterday.getDate() - 1), yesterday.toISOString().split("T")[0];
|
|
1917
|
+
}
|
|
1918
|
+
function getTodayDate() {
|
|
1919
|
+
return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1920
|
+
}
|
|
1921
|
+
function buildDateRange(from, to) {
|
|
1922
|
+
let start = /* @__PURE__ */ new Date(from + "T00:00:00"), end = /* @__PURE__ */ new Date(to + "T00:00:00");
|
|
1923
|
+
if (isNaN(start.getTime())) throw new Error(`--from \u65E5\u671F\u683C\u5F0F\u9519\u8BEF: ${from}`);
|
|
1924
|
+
if (isNaN(end.getTime())) throw new Error(`--to \u65E5\u671F\u683C\u5F0F\u9519\u8BEF: ${to}`);
|
|
1925
|
+
if (start > end) throw new Error("--from \u4E0D\u80FD\u665A\u4E8E --to");
|
|
1926
|
+
let dates = [], current = new Date(start);
|
|
1927
|
+
for (; current <= end; ) {
|
|
1928
|
+
let year = current.getFullYear(), month = String(current.getMonth() + 1).padStart(2, "0"), day = String(current.getDate()).padStart(2, "0");
|
|
1929
|
+
dates.push(`${year}-${month}-${day}`), current.setDate(current.getDate() + 1);
|
|
1930
|
+
}
|
|
1931
|
+
return dates;
|
|
1932
|
+
}
|
|
1933
|
+
function getClosedDates(lookbackDays) {
|
|
1934
|
+
let dates = [];
|
|
1935
|
+
for (let offset = lookbackDays; offset >= 1; offset -= 1) {
|
|
1936
|
+
let day = /* @__PURE__ */ new Date();
|
|
1937
|
+
day.setDate(day.getDate() - offset), dates.push(day.toISOString().split("T")[0]);
|
|
1938
|
+
}
|
|
1939
|
+
return dates;
|
|
1940
|
+
}
|
|
1941
|
+
function resolveServer(flagValue, configValue) {
|
|
1942
|
+
let value = resolveOptionalString(flagValue, configValue);
|
|
1943
|
+
if (!value) throw new Error("\u7F3A\u5C11\u670D\u52A1\u7AEF\u5730\u5740\uFF0C\u8BF7\u4F20 --server \u6216\u5148\u6267\u884C init");
|
|
1944
|
+
return normalizeServerUrl(value);
|
|
1945
|
+
}
|
|
1946
|
+
function resolveRequiredString(flagValue, configValue, message) {
|
|
1947
|
+
let value = resolveOptionalString(flagValue, configValue);
|
|
1948
|
+
if (!value) throw new Error(message);
|
|
1949
|
+
return value;
|
|
1950
|
+
}
|
|
1951
|
+
function resolveOptionalString(flagValue, fallback) {
|
|
1952
|
+
return typeof flagValue == "string" ? flagValue : fallback;
|
|
1953
|
+
}
|
|
1954
|
+
function parsePositiveInt2(value, label) {
|
|
1955
|
+
let parsed = Number.parseInt(value, 10);
|
|
1956
|
+
if (!Number.isFinite(parsed) || parsed <= 0)
|
|
1957
|
+
throw new Error(`${label} \u5FC5\u987B\u662F\u6B63\u6574\u6570`);
|
|
1958
|
+
return parsed;
|
|
1959
|
+
}
|