@aiusage/cli 1.0.0 → 1.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/README.md +19 -2
- package/dist/cli.js +748 -267
- package/package.json +4 -3
package/dist/cli.js
CHANGED
|
@@ -1,75 +1,138 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __require = /* @__PURE__ */ ((x) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(x, {
|
|
3
|
+
get: (a, b) => (typeof require < "u" ? require : a)[b]
|
|
4
|
+
}) : x)(function(x) {
|
|
5
|
+
if (typeof require < "u") return require.apply(this, arguments);
|
|
6
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
7
|
+
});
|
|
2
8
|
|
|
3
9
|
// src/cli.ts
|
|
4
|
-
import { existsSync } from "node:fs";
|
|
5
|
-
import { createInterface } from "node:readline";
|
|
10
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
11
|
+
import { createInterface as createInterface3 } from "node:readline";
|
|
6
12
|
import { hostname as hostname3 } from "node:os";
|
|
7
13
|
|
|
8
14
|
// src/scanners/claude.ts
|
|
9
|
-
import { readdir,
|
|
10
|
-
import { join } from "node:path";
|
|
15
|
+
import { readdir as readdir2, open } from "node:fs/promises";
|
|
16
|
+
import { join as join2 } from "node:path";
|
|
11
17
|
import { homedir } from "node:os";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
18
|
+
import { createInterface } from "node:readline";
|
|
19
|
+
|
|
20
|
+
// src/scanners/utils.ts
|
|
21
|
+
import { readdir } from "node:fs/promises";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
function parseTs(value) {
|
|
24
|
+
if (value == null) return null;
|
|
25
|
+
let d = new Date(value);
|
|
26
|
+
return isNaN(d.getTime()) ? null : d;
|
|
27
|
+
}
|
|
28
|
+
function dateKey(date) {
|
|
29
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
30
|
+
}
|
|
31
|
+
function projectFromPath(raw, aliases) {
|
|
32
|
+
let parts = raw.split("/").filter(Boolean), name = parts[parts.length - 1] || "unknown";
|
|
33
|
+
return aliases?.[raw] ?? aliases?.[name] ?? name;
|
|
34
|
+
}
|
|
35
|
+
async function walkFiles(dir, ext) {
|
|
36
|
+
let result = [];
|
|
37
|
+
return await walk(dir, ext, result), result;
|
|
38
|
+
}
|
|
39
|
+
async function walk(dir, ext, out) {
|
|
40
|
+
let entries;
|
|
16
41
|
try {
|
|
17
|
-
|
|
42
|
+
entries = await readdir(dir, { withFileTypes: !0 });
|
|
18
43
|
} catch {
|
|
19
|
-
return
|
|
44
|
+
return;
|
|
20
45
|
}
|
|
21
|
-
let
|
|
22
|
-
|
|
23
|
-
|
|
46
|
+
for (let e of entries) {
|
|
47
|
+
let full = join(dir, e.name);
|
|
48
|
+
e.isDirectory() ? await walk(full, ext, out) : e.name.endsWith(ext) && out.push(full);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function initDateMap(dates) {
|
|
52
|
+
let m = /* @__PURE__ */ new Map();
|
|
53
|
+
for (let d of dates) m.set(d, /* @__PURE__ */ new Map());
|
|
54
|
+
return m;
|
|
55
|
+
}
|
|
56
|
+
function accumulate(grouped, key, base, tokens) {
|
|
57
|
+
let existing = grouped.get(key);
|
|
58
|
+
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, {
|
|
59
|
+
...base,
|
|
60
|
+
eventCount: 1,
|
|
61
|
+
inputTokens: tokens.input,
|
|
62
|
+
cachedInputTokens: tokens.cached,
|
|
63
|
+
cacheWriteTokens: tokens.cacheWrite,
|
|
64
|
+
outputTokens: tokens.output,
|
|
65
|
+
reasoningOutputTokens: tokens.reasoning
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
function finalize(groupedByDate) {
|
|
69
|
+
return new Map(
|
|
70
|
+
[...groupedByDate.entries()].map(([d, m]) => [d, [...m.values()]])
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
function emptyResult(dates) {
|
|
74
|
+
return new Map([...dates].map((d) => [d, []]));
|
|
75
|
+
}
|
|
76
|
+
function normalizeModelName(name) {
|
|
77
|
+
return name.replace(/-\d{8}$/, "");
|
|
78
|
+
}
|
|
79
|
+
async function runWithConcurrency(items, concurrency, worker) {
|
|
80
|
+
if (items.length === 0) return;
|
|
81
|
+
let limit = Math.max(1, Math.min(concurrency, items.length)), nextIndex = 0;
|
|
82
|
+
await Promise.all(
|
|
83
|
+
Array.from({ length: limit }, async () => {
|
|
84
|
+
for (; ; ) {
|
|
85
|
+
let i = nextIndex++;
|
|
86
|
+
if (i >= items.length) return;
|
|
87
|
+
await worker(items[i], i);
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/scanners/claude.ts
|
|
94
|
+
var FILE_CONCURRENCY = 16, MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
95
|
+
function getClaudeProjectDirs(claudeDir) {
|
|
96
|
+
if (claudeDir) return [claudeDir];
|
|
97
|
+
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
98
|
+
if (envVar)
|
|
99
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join2(p, "projects"));
|
|
100
|
+
let home = homedir();
|
|
101
|
+
return [
|
|
102
|
+
join2(home, ".config", "claude", "projects"),
|
|
103
|
+
join2(home, ".claude", "projects")
|
|
104
|
+
];
|
|
105
|
+
}
|
|
106
|
+
async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
107
|
+
let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
|
|
108
|
+
for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
|
|
109
|
+
let baseDirs = getClaudeProjectDirs(claudeDir), deduped = /* @__PURE__ */ new Map(), fileJobs = [];
|
|
110
|
+
for (let baseDir of baseDirs) {
|
|
111
|
+
let projectDirs;
|
|
24
112
|
try {
|
|
25
|
-
await
|
|
113
|
+
projectDirs = await readdir2(baseDir);
|
|
26
114
|
} catch {
|
|
27
115
|
continue;
|
|
28
116
|
}
|
|
29
|
-
for (let
|
|
30
|
-
let
|
|
117
|
+
for (let projDir of projectDirs) {
|
|
118
|
+
let projectPath = join2(baseDir, projDir), project = resolveProject(projectPath, projectAliases), jsonlFiles = [];
|
|
31
119
|
try {
|
|
32
|
-
|
|
120
|
+
await walkForJsonl(projectPath, jsonlFiles);
|
|
33
121
|
} catch {
|
|
34
122
|
continue;
|
|
35
123
|
}
|
|
36
|
-
for (let
|
|
37
|
-
|
|
38
|
-
if (!line.trim()) continue;
|
|
39
|
-
let record;
|
|
40
|
-
try {
|
|
41
|
-
record = JSON.parse(line);
|
|
42
|
-
} catch {
|
|
43
|
-
continue;
|
|
44
|
-
}
|
|
45
|
-
let ts = parseTimestamp(record.timestamp);
|
|
46
|
-
if (!ts) continue;
|
|
47
|
-
let usageDate = toDateKey(ts);
|
|
48
|
-
if (!targetDateSet.has(usageDate)) continue;
|
|
49
|
-
let message = record.message;
|
|
50
|
-
if (!message?.usage) continue;
|
|
51
|
-
let requestId = record.requestId ?? message.id ?? record.uuid;
|
|
52
|
-
if (!requestId) continue;
|
|
53
|
-
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;
|
|
54
|
-
cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
|
|
55
|
-
let dedupeKey = `${usageDate}|${requestId}`, existing = deduped.get(dedupeKey);
|
|
56
|
-
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, {
|
|
57
|
-
model,
|
|
58
|
-
project: recordProject,
|
|
59
|
-
inputTokens: usage.input_tokens ?? 0,
|
|
60
|
-
cacheWrite5mTokens: cache5m,
|
|
61
|
-
cacheWrite1hTokens: cache1h,
|
|
62
|
-
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
|
|
63
|
-
outputTokens: usage.output_tokens ?? 0
|
|
64
|
-
});
|
|
65
|
-
}
|
|
124
|
+
for (let filePath of jsonlFiles)
|
|
125
|
+
fileJobs.push({ filePath, project });
|
|
66
126
|
}
|
|
67
127
|
}
|
|
128
|
+
await runWithConcurrency(fileJobs, FILE_CONCURRENCY, async (job) => {
|
|
129
|
+
await processJsonlFile(job.filePath, job.project, targetDateSet, projectAliases, deduped);
|
|
130
|
+
});
|
|
68
131
|
for (let [dedupeKey, usage] of deduped.entries()) {
|
|
69
132
|
let [usageDate] = dedupeKey.split("|", 1), grouped = groupedByDate.get(usageDate);
|
|
70
133
|
if (!grouped) continue;
|
|
71
134
|
let cacheWriteTokens = usage.cacheWrite5mTokens + usage.cacheWrite1hTokens, key = `${usage.model}|${usage.project}`, existing = grouped.get(key);
|
|
72
|
-
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, {
|
|
135
|
+
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, existing.costUSD = (existing.costUSD ?? 0) + usage.costUSD) : grouped.set(key, {
|
|
73
136
|
provider: "anthropic",
|
|
74
137
|
product: "claude-code",
|
|
75
138
|
channel: "cli",
|
|
@@ -82,13 +145,64 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
82
145
|
cacheWrite5mTokens: usage.cacheWrite5mTokens,
|
|
83
146
|
cacheWrite1hTokens: usage.cacheWrite1hTokens,
|
|
84
147
|
outputTokens: usage.outputTokens,
|
|
85
|
-
reasoningOutputTokens: 0
|
|
148
|
+
reasoningOutputTokens: 0,
|
|
149
|
+
costUSD: usage.costUSD
|
|
86
150
|
});
|
|
87
151
|
}
|
|
88
152
|
return new Map(
|
|
89
153
|
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
90
154
|
);
|
|
91
155
|
}
|
|
156
|
+
async function processJsonlFile(filePath, fallbackProject, targetDateSet, projectAliases, deduped) {
|
|
157
|
+
let fh;
|
|
158
|
+
try {
|
|
159
|
+
fh = await open(filePath, "r");
|
|
160
|
+
} catch {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
let rl = createInterface({
|
|
165
|
+
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
166
|
+
crlfDelay: 1 / 0
|
|
167
|
+
});
|
|
168
|
+
for await (let line of rl) {
|
|
169
|
+
if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES) continue;
|
|
170
|
+
let record;
|
|
171
|
+
try {
|
|
172
|
+
record = JSON.parse(line);
|
|
173
|
+
} catch {
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
let ts = parseTimestamp(record.timestamp);
|
|
177
|
+
if (!ts) continue;
|
|
178
|
+
let usageDate = toDateKey(ts);
|
|
179
|
+
if (!targetDateSet.has(usageDate)) continue;
|
|
180
|
+
let message = record.message;
|
|
181
|
+
if (!message?.usage) continue;
|
|
182
|
+
let rawModel = message.model ?? "unknown";
|
|
183
|
+
if (rawModel === "<synthetic>") continue;
|
|
184
|
+
let requestId = record.requestId ?? message.id ?? record.uuid;
|
|
185
|
+
if (!requestId) continue;
|
|
186
|
+
let usage = message.usage, model = normalizeModelName(rawModel);
|
|
187
|
+
usage.speed === "fast" && (model = `${model}-fast`);
|
|
188
|
+
let recordProject = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackProject, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
|
|
189
|
+
cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
|
|
190
|
+
let dedupeKey = `${usageDate}|${requestId}`, existing = deduped.get(dedupeKey);
|
|
191
|
+
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), existing.costUSD = Math.max(existing.costUSD, costUSD)) : deduped.set(dedupeKey, {
|
|
192
|
+
model,
|
|
193
|
+
project: recordProject,
|
|
194
|
+
inputTokens: usage.input_tokens ?? 0,
|
|
195
|
+
cacheWrite5mTokens: cache5m,
|
|
196
|
+
cacheWrite1hTokens: cache1h,
|
|
197
|
+
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
|
|
198
|
+
outputTokens: usage.output_tokens ?? 0,
|
|
199
|
+
costUSD
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
} finally {
|
|
203
|
+
await fh.close();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
92
206
|
function parseTimestamp(value) {
|
|
93
207
|
if (!value) return null;
|
|
94
208
|
try {
|
|
@@ -111,34 +225,46 @@ function resolveProject(rawPath, aliases) {
|
|
|
111
225
|
return aliases?.[rawPath] ?? aliases?.[project] ?? project;
|
|
112
226
|
}
|
|
113
227
|
async function walkForJsonl(dir, result) {
|
|
114
|
-
let entries = await
|
|
228
|
+
let entries = await readdir2(dir, { withFileTypes: !0 });
|
|
115
229
|
for (let entry of entries) {
|
|
116
|
-
let fullPath =
|
|
230
|
+
let fullPath = join2(dir, entry.name);
|
|
117
231
|
entry.isDirectory() ? await walkForJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
118
232
|
}
|
|
119
233
|
}
|
|
120
234
|
|
|
121
235
|
// src/scanners/codex.ts
|
|
122
|
-
import { readdir as
|
|
123
|
-
import { join as
|
|
236
|
+
import { readdir as readdir3, open as open2 } from "node:fs/promises";
|
|
237
|
+
import { join as join3 } from "node:path";
|
|
124
238
|
import { homedir as homedir2 } from "node:os";
|
|
239
|
+
import { createInterface as createInterface2 } from "node:readline";
|
|
240
|
+
var FILE_CONCURRENCY2 = 16, MAX_LINE_BYTES2 = 64 * 1024 * 1024;
|
|
125
241
|
async function scanCodexDates(targetDates, codexDir, projectAliases) {
|
|
126
242
|
let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
|
|
127
243
|
for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
|
|
128
|
-
let baseDir = codexDir ??
|
|
244
|
+
let baseDir = codexDir ?? join3(homedir2(), ".codex"), sessionFiles = await collectSessionFiles(baseDir);
|
|
129
245
|
if (sessionFiles.length === 0)
|
|
130
246
|
return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
247
|
+
let globalSeenSigs = /* @__PURE__ */ new Set();
|
|
248
|
+
return await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath) => {
|
|
249
|
+
await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs);
|
|
250
|
+
}), new Map(
|
|
251
|
+
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs) {
|
|
255
|
+
let fh;
|
|
256
|
+
try {
|
|
257
|
+
fh = await open2(filePath, "r");
|
|
258
|
+
} catch {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
let rl = createInterface2({
|
|
263
|
+
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
264
|
+
crlfDelay: 1 / 0
|
|
265
|
+
}), currentModel = "unknown", currentProject = "unknown", previousTotal = {};
|
|
266
|
+
for await (let line of rl) {
|
|
267
|
+
if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
|
|
142
268
|
let record;
|
|
143
269
|
try {
|
|
144
270
|
record = JSON.parse(line);
|
|
@@ -146,62 +272,69 @@ async function scanCodexDates(targetDates, codexDir, projectAliases) {
|
|
|
146
272
|
continue;
|
|
147
273
|
}
|
|
148
274
|
if (record.type === "turn_context") {
|
|
149
|
-
|
|
275
|
+
let rawModel = record.payload?.model ?? currentModel;
|
|
276
|
+
rawModel !== "<synthetic>" && (currentModel = normalizeModelName(rawModel)), record.payload?.cwd && (currentProject = extractProject(record.payload.cwd, projectAliases));
|
|
150
277
|
continue;
|
|
151
278
|
}
|
|
152
279
|
if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
|
|
153
280
|
let info = record.payload?.info;
|
|
154
|
-
if (!info?.
|
|
281
|
+
if (!info?.total_token_usage) continue;
|
|
155
282
|
let ts = parseTimestamp2(record.timestamp);
|
|
156
283
|
if (!ts) continue;
|
|
157
284
|
let usageDate = toDateKey2(ts);
|
|
158
285
|
if (!targetDateSet.has(usageDate)) continue;
|
|
159
286
|
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}`;
|
|
160
|
-
if (signature
|
|
161
|
-
|
|
162
|
-
let last = info.last_token_usage
|
|
287
|
+
if (globalSeenSigs.has(signature)) continue;
|
|
288
|
+
globalSeenSigs.add(signature);
|
|
289
|
+
let last = info.last_token_usage ?? {
|
|
290
|
+
input_tokens: Math.max(0, (total.input_tokens ?? 0) - (previousTotal.input_tokens ?? 0)),
|
|
291
|
+
cached_input_tokens: Math.max(0, (total.cached_input_tokens ?? 0) - (previousTotal.cached_input_tokens ?? 0)),
|
|
292
|
+
output_tokens: Math.max(0, (total.output_tokens ?? 0) - (previousTotal.output_tokens ?? 0)),
|
|
293
|
+
reasoning_output_tokens: Math.max(0, (total.reasoning_output_tokens ?? 0) - (previousTotal.reasoning_output_tokens ?? 0))
|
|
294
|
+
};
|
|
295
|
+
previousTotal = total;
|
|
296
|
+
let nonCachedInput = Math.max(0, (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)), grouped = groupedByDate.get(usageDate);
|
|
163
297
|
if (!grouped) continue;
|
|
164
298
|
let key = `${currentModel}|${currentProject}`, existing = grouped.get(key);
|
|
165
|
-
existing ? (existing.eventCount += 1, existing.inputTokens +=
|
|
299
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += nonCachedInput, existing.cachedInputTokens += last.cached_input_tokens ?? 0, existing.outputTokens += last.output_tokens ?? 0, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0) : grouped.set(key, {
|
|
166
300
|
provider: "openai",
|
|
167
301
|
product: "codex",
|
|
168
302
|
channel: "cli",
|
|
169
303
|
model: currentModel,
|
|
170
304
|
project: currentProject,
|
|
171
305
|
eventCount: 1,
|
|
172
|
-
inputTokens:
|
|
306
|
+
inputTokens: nonCachedInput,
|
|
173
307
|
cachedInputTokens: last.cached_input_tokens ?? 0,
|
|
174
308
|
cacheWriteTokens: 0,
|
|
175
309
|
outputTokens: last.output_tokens ?? 0,
|
|
176
310
|
reasoningOutputTokens: last.reasoning_output_tokens ?? 0
|
|
177
311
|
});
|
|
178
312
|
}
|
|
313
|
+
} finally {
|
|
314
|
+
await fh.close();
|
|
179
315
|
}
|
|
180
|
-
return new Map(
|
|
181
|
-
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
182
|
-
);
|
|
183
316
|
}
|
|
184
317
|
async function collectSessionFiles(baseDir) {
|
|
185
|
-
let paths = [], archivedDir =
|
|
318
|
+
let paths = [], archivedDir = join3(baseDir, "archived_sessions");
|
|
186
319
|
try {
|
|
187
|
-
let files = await
|
|
320
|
+
let files = await readdir3(archivedDir);
|
|
188
321
|
for (let f of files)
|
|
189
|
-
f.endsWith(".jsonl") && paths.push(
|
|
322
|
+
f.endsWith(".jsonl") && paths.push(join3(archivedDir, f));
|
|
190
323
|
} catch {
|
|
191
324
|
}
|
|
192
|
-
let sessionsDir =
|
|
325
|
+
let sessionsDir = join3(baseDir, "sessions");
|
|
193
326
|
return await walkDir(sessionsDir, paths), paths;
|
|
194
327
|
}
|
|
195
328
|
async function walkDir(dir, result) {
|
|
196
329
|
let entries;
|
|
197
330
|
try {
|
|
198
|
-
entries = await
|
|
331
|
+
entries = await readdir3(dir, { withFileTypes: !0 });
|
|
199
332
|
} catch {
|
|
200
333
|
return;
|
|
201
334
|
}
|
|
202
335
|
for (let entry of entries) {
|
|
203
|
-
let fullPath =
|
|
204
|
-
entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.
|
|
336
|
+
let fullPath = join3(dir, entry.name);
|
|
337
|
+
entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
205
338
|
}
|
|
206
339
|
}
|
|
207
340
|
function parseTimestamp2(value) {
|
|
@@ -223,68 +356,9 @@ function extractProject(cwd, aliases) {
|
|
|
223
356
|
}
|
|
224
357
|
|
|
225
358
|
// src/scanners/copilot.ts
|
|
226
|
-
import { readFile
|
|
359
|
+
import { readFile } from "node:fs/promises";
|
|
227
360
|
import { join as join4 } from "node:path";
|
|
228
361
|
import { homedir as homedir3 } from "node:os";
|
|
229
|
-
|
|
230
|
-
// src/scanners/utils.ts
|
|
231
|
-
import { readdir as readdir3 } from "node:fs/promises";
|
|
232
|
-
import { join as join3 } from "node:path";
|
|
233
|
-
function parseTs(value) {
|
|
234
|
-
if (value == null) return null;
|
|
235
|
-
let d = new Date(value);
|
|
236
|
-
return isNaN(d.getTime()) ? null : d;
|
|
237
|
-
}
|
|
238
|
-
function dateKey(date) {
|
|
239
|
-
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
240
|
-
}
|
|
241
|
-
function projectFromPath(raw, aliases) {
|
|
242
|
-
let parts = raw.split("/").filter(Boolean), name = parts[parts.length - 1] || "unknown";
|
|
243
|
-
return aliases?.[raw] ?? aliases?.[name] ?? name;
|
|
244
|
-
}
|
|
245
|
-
async function walkFiles(dir, ext) {
|
|
246
|
-
let result = [];
|
|
247
|
-
return await walk(dir, ext, result), result;
|
|
248
|
-
}
|
|
249
|
-
async function walk(dir, ext, out) {
|
|
250
|
-
let entries;
|
|
251
|
-
try {
|
|
252
|
-
entries = await readdir3(dir, { withFileTypes: !0 });
|
|
253
|
-
} catch {
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
for (let e of entries) {
|
|
257
|
-
let full = join3(dir, e.name);
|
|
258
|
-
e.isDirectory() ? await walk(full, ext, out) : e.name.endsWith(ext) && out.push(full);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
function initDateMap(dates) {
|
|
262
|
-
let m = /* @__PURE__ */ new Map();
|
|
263
|
-
for (let d of dates) m.set(d, /* @__PURE__ */ new Map());
|
|
264
|
-
return m;
|
|
265
|
-
}
|
|
266
|
-
function accumulate(grouped, key, base, tokens) {
|
|
267
|
-
let existing = grouped.get(key);
|
|
268
|
-
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, {
|
|
269
|
-
...base,
|
|
270
|
-
eventCount: 1,
|
|
271
|
-
inputTokens: tokens.input,
|
|
272
|
-
cachedInputTokens: tokens.cached,
|
|
273
|
-
cacheWriteTokens: tokens.cacheWrite,
|
|
274
|
-
outputTokens: tokens.output,
|
|
275
|
-
reasoningOutputTokens: tokens.reasoning
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
function finalize(groupedByDate) {
|
|
279
|
-
return new Map(
|
|
280
|
-
[...groupedByDate.entries()].map(([d, m]) => [d, [...m.values()]])
|
|
281
|
-
);
|
|
282
|
-
}
|
|
283
|
-
function emptyResult(dates) {
|
|
284
|
-
return new Map([...dates].map((d) => [d, []]));
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// src/scanners/copilot.ts
|
|
288
362
|
async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
289
363
|
let dates = new Set(targetDates), dir = baseDir ?? join4(homedir3(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
|
|
290
364
|
if (files.length === 0) return emptyResult(dates);
|
|
@@ -292,7 +366,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
292
366
|
for (let filePath of files) {
|
|
293
367
|
let content;
|
|
294
368
|
try {
|
|
295
|
-
content = await
|
|
369
|
+
content = await readFile(filePath, "utf-8");
|
|
296
370
|
} catch {
|
|
297
371
|
continue;
|
|
298
372
|
}
|
|
@@ -344,18 +418,176 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
344
418
|
return finalize(grouped);
|
|
345
419
|
}
|
|
346
420
|
|
|
421
|
+
// src/scanners/cursor.ts
|
|
422
|
+
import { existsSync } from "node:fs";
|
|
423
|
+
import { copyFile, mkdtemp, rm } from "node:fs/promises";
|
|
424
|
+
import { homedir as homedir4, tmpdir } from "node:os";
|
|
425
|
+
import { join as join5, resolve } from "node:path";
|
|
426
|
+
var CURSOR_CONFIG_DIR_ENV = "CURSOR_CONFIG_DIR", CURSOR_STATE_DB_PATH_ENV = "CURSOR_STATE_DB_PATH", CURSOR_WEB_BASE_URL_ENV = "CURSOR_WEB_BASE_URL", CURSOR_STATE_DB_RELATIVE = join5("User", "globalStorage", "state.vscdb"), CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
|
|
427
|
+
function getDefaultDbPath() {
|
|
428
|
+
if (process.platform === "darwin")
|
|
429
|
+
return join5(homedir4(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
|
|
430
|
+
if (process.platform === "win32") {
|
|
431
|
+
let appData = process.env.APPDATA?.trim() || join5(homedir4(), "AppData", "Roaming");
|
|
432
|
+
return join5(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
|
|
433
|
+
}
|
|
434
|
+
let xdg = process.env.XDG_CONFIG_HOME?.trim() || join5(homedir4(), ".config");
|
|
435
|
+
return join5(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
|
|
436
|
+
}
|
|
437
|
+
function findDbPath() {
|
|
438
|
+
let explicit = process.env[CURSOR_STATE_DB_PATH_ENV]?.trim();
|
|
439
|
+
if (explicit) {
|
|
440
|
+
let p = resolve(explicit);
|
|
441
|
+
return existsSync(p) ? p : null;
|
|
442
|
+
}
|
|
443
|
+
let dirs = process.env[CURSOR_CONFIG_DIR_ENV]?.trim(), candidates = dirs ? dirs.split(",").map((v) => {
|
|
444
|
+
let r = resolve(v.trim());
|
|
445
|
+
return r.endsWith(".vscdb") ? r : join5(r, CURSOR_STATE_DB_RELATIVE);
|
|
446
|
+
}) : [getDefaultDbPath()];
|
|
447
|
+
for (let c of candidates)
|
|
448
|
+
if (existsSync(c)) return c;
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
function readAuthFromDb(dbPath) {
|
|
452
|
+
let { DatabaseSync } = __require("node:sqlite"), db = new DatabaseSync(dbPath, { open: !0 });
|
|
453
|
+
try {
|
|
454
|
+
let raw = db.prepare("SELECT value FROM ItemTable WHERE key = ? LIMIT 1").get("cursorAuth/accessToken")?.value, token;
|
|
455
|
+
return typeof raw == "string" ? token = raw.trim() || void 0 : Buffer.isBuffer(raw) && (token = raw.toString("utf8").trim() || void 0), { accessToken: token };
|
|
456
|
+
} finally {
|
|
457
|
+
db.close();
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
async function withSnapshot(dbPath, cb) {
|
|
461
|
+
let dir = await mkdtemp(join5(tmpdir(), "aiusage-cursor-")), snap = join5(dir, "state.vscdb");
|
|
462
|
+
await copyFile(dbPath, snap);
|
|
463
|
+
for (let suffix of ["-shm", "-wal"])
|
|
464
|
+
existsSync(`${dbPath}${suffix}`) && await copyFile(`${dbPath}${suffix}`, `${snap}${suffix}`);
|
|
465
|
+
try {
|
|
466
|
+
return cb(snap);
|
|
467
|
+
} finally {
|
|
468
|
+
await rm(dir, { recursive: !0, force: !0 });
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
async function readAuth(dbPath) {
|
|
472
|
+
try {
|
|
473
|
+
return readAuthFromDb(dbPath);
|
|
474
|
+
} catch (err) {
|
|
475
|
+
if (err instanceof Error && /database is locked/i.test(err.message))
|
|
476
|
+
return withSnapshot(dbPath, (snap) => readAuthFromDb(snap));
|
|
477
|
+
throw err;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
function jwtSub(token) {
|
|
481
|
+
let part = token.split(".")[1];
|
|
482
|
+
if (!part) return;
|
|
483
|
+
let b64 = part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=");
|
|
484
|
+
try {
|
|
485
|
+
return JSON.parse(Buffer.from(b64, "base64").toString("utf8")).sub?.trim();
|
|
486
|
+
} catch {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function getWebBaseUrl() {
|
|
491
|
+
return (process.env[CURSOR_WEB_BASE_URL_ENV]?.trim() || "https://cursor.com").replace(/\/+$/, "");
|
|
492
|
+
}
|
|
493
|
+
async function fetchCsv(accessToken) {
|
|
494
|
+
let url = new URL("/api/dashboard/export-usage-events-csv?strategy=tokens", getWebBaseUrl()), sub = jwtSub(accessToken), cookieValues = [accessToken, ...sub ? [`${sub}::${accessToken}`] : []], attempts = [{ Authorization: `Bearer ${accessToken}` }];
|
|
495
|
+
for (let cv of cookieValues)
|
|
496
|
+
attempts.push({ Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` }), attempts.push({ Authorization: `Bearer ${accessToken}`, Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` });
|
|
497
|
+
let failures = [];
|
|
498
|
+
for (let headers of attempts) {
|
|
499
|
+
let res = await fetch(url, { headers: { Accept: "text/csv,*/*;q=0.8", ...headers } });
|
|
500
|
+
if (res.ok) return res.text();
|
|
501
|
+
failures.push(`${res.status} ${res.statusText}`);
|
|
502
|
+
}
|
|
503
|
+
throw new Error(`Cursor API failed: ${failures.join(", ")}`);
|
|
504
|
+
}
|
|
505
|
+
function parseCsvLine(line) {
|
|
506
|
+
let vals = [], cur = "", inQ = !1;
|
|
507
|
+
for (let i = 0; i < line.length; i++) {
|
|
508
|
+
let c = line[i];
|
|
509
|
+
c === '"' ? inQ && line[i + 1] === '"' ? (cur += '"', i++) : inQ = !inQ : c === "," && !inQ ? (vals.push(cur), cur = "") : cur += c;
|
|
510
|
+
}
|
|
511
|
+
return vals.push(cur), vals;
|
|
512
|
+
}
|
|
513
|
+
function parseNum(v) {
|
|
514
|
+
let n = Number((v ?? "").replace(/,/g, "").trim());
|
|
515
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
|
|
516
|
+
}
|
|
517
|
+
function parseDateStr(v) {
|
|
518
|
+
let s = v?.trim();
|
|
519
|
+
if (!s) return null;
|
|
520
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
|
|
521
|
+
let d = new Date(s);
|
|
522
|
+
return isNaN(d.getTime()) ? null : dateKey(d);
|
|
523
|
+
}
|
|
524
|
+
async function scanCursorDates(targetDates) {
|
|
525
|
+
let dateSet = new Set(targetDates), empty = new Map(targetDates.map((d) => [d, []])), dbPath = findDbPath();
|
|
526
|
+
if (!dbPath) return empty;
|
|
527
|
+
let auth;
|
|
528
|
+
try {
|
|
529
|
+
auth = await readAuth(dbPath);
|
|
530
|
+
} catch {
|
|
531
|
+
return empty;
|
|
532
|
+
}
|
|
533
|
+
if (!auth.accessToken) return empty;
|
|
534
|
+
let csvText;
|
|
535
|
+
try {
|
|
536
|
+
csvText = await fetchCsv(auth.accessToken);
|
|
537
|
+
} catch {
|
|
538
|
+
return empty;
|
|
539
|
+
}
|
|
540
|
+
let grouped = /* @__PURE__ */ new Map();
|
|
541
|
+
for (let d of dateSet) grouped.set(d, /* @__PURE__ */ new Map());
|
|
542
|
+
let headers = null;
|
|
543
|
+
for (let rawLine of csvText.split(/\r?\n/)) {
|
|
544
|
+
let line = rawLine.trim();
|
|
545
|
+
if (!line) continue;
|
|
546
|
+
let values = parseCsvLine(line);
|
|
547
|
+
if (!headers) {
|
|
548
|
+
headers = values;
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
let row = {};
|
|
552
|
+
headers.forEach((h, i) => {
|
|
553
|
+
row[h] = values[i] ?? "";
|
|
554
|
+
});
|
|
555
|
+
let date = parseDateStr(row.Date);
|
|
556
|
+
if (!date || !dateSet.has(date)) continue;
|
|
557
|
+
let rawModel = row.Model?.trim();
|
|
558
|
+
if (!rawModel) continue;
|
|
559
|
+
let model = normalizeModelName(rawModel);
|
|
560
|
+
if (!(parseNum(row["Total Tokens"]) || parseNum(row.Tokens))) continue;
|
|
561
|
+
let inputWithCache = parseNum(row["Input (w/ Cache Write)"]), inputWithout = parseNum(row["Input (w/o Cache Write)"]), cacheRead = parseNum(row["Cache Read"]), output = parseNum(row["Output Tokens"]), inputTokens = inputWithCache + inputWithout + cacheRead, dayMap = grouped.get(date), existing = dayMap.get(model);
|
|
562
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cacheRead, existing.cacheWriteTokens += inputWithCache, existing.outputTokens += output) : dayMap.set(model, {
|
|
563
|
+
provider: "cursor",
|
|
564
|
+
product: "cursor",
|
|
565
|
+
channel: "ide",
|
|
566
|
+
model,
|
|
567
|
+
project: "unknown",
|
|
568
|
+
eventCount: 1,
|
|
569
|
+
inputTokens,
|
|
570
|
+
cachedInputTokens: cacheRead,
|
|
571
|
+
cacheWriteTokens: inputWithCache,
|
|
572
|
+
outputTokens: output,
|
|
573
|
+
reasoningOutputTokens: 0
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
return new Map([...grouped.entries()].map(([d, m]) => [d, [...m.values()]]));
|
|
577
|
+
}
|
|
578
|
+
|
|
347
579
|
// src/scanners/gemini.ts
|
|
348
|
-
import { readFile as
|
|
349
|
-
import { join as
|
|
350
|
-
import { homedir as
|
|
580
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
581
|
+
import { join as join6 } from "node:path";
|
|
582
|
+
import { homedir as homedir5 } from "node:os";
|
|
351
583
|
async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
352
|
-
let dates = new Set(targetDates), dir = baseDir ??
|
|
584
|
+
let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
|
|
353
585
|
if (files.length === 0) return emptyResult(dates);
|
|
354
586
|
let grouped = initDateMap(dates);
|
|
355
587
|
for (let filePath of files) {
|
|
356
588
|
let content;
|
|
357
589
|
try {
|
|
358
|
-
content = await
|
|
590
|
+
content = await readFile2(filePath, "utf-8");
|
|
359
591
|
} catch {
|
|
360
592
|
continue;
|
|
361
593
|
}
|
|
@@ -369,7 +601,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
369
601
|
for (let msg of messages) {
|
|
370
602
|
let tokens = extractTokens(msg);
|
|
371
603
|
if (!tokens) continue;
|
|
372
|
-
let model = msg.model ?? fallbackModel, ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
|
|
604
|
+
let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
|
|
373
605
|
if (!ts) continue;
|
|
374
606
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
375
607
|
dayMap && accumulate(
|
|
@@ -407,17 +639,17 @@ function extractTokens(msg) {
|
|
|
407
639
|
}
|
|
408
640
|
|
|
409
641
|
// src/scanners/qwen.ts
|
|
410
|
-
import { readFile as
|
|
411
|
-
import { join as
|
|
412
|
-
import { homedir as
|
|
642
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
643
|
+
import { join as join7, basename as basename2, dirname } from "node:path";
|
|
644
|
+
import { homedir as homedir6 } from "node:os";
|
|
413
645
|
async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
414
|
-
let dates = new Set(targetDates), dir = baseDir ??
|
|
646
|
+
let dates = new Set(targetDates), dir = baseDir ?? join7(homedir6(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
|
|
415
647
|
if (files.length === 0) return emptyResult(dates);
|
|
416
648
|
let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
417
649
|
for (let filePath of files) {
|
|
418
650
|
let chatsDir = dirname(filePath), projectDir = dirname(chatsDir), projectId = basename2(projectDir), content;
|
|
419
651
|
try {
|
|
420
|
-
content = await
|
|
652
|
+
content = await readFile3(filePath, "utf-8");
|
|
421
653
|
} catch {
|
|
422
654
|
continue;
|
|
423
655
|
}
|
|
@@ -465,17 +697,17 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
465
697
|
}
|
|
466
698
|
|
|
467
699
|
// src/scanners/kimi.ts
|
|
468
|
-
import { readFile as
|
|
469
|
-
import { join as
|
|
470
|
-
import { homedir as
|
|
700
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
701
|
+
import { join as join8, basename as basename3, dirname as dirname2 } from "node:path";
|
|
702
|
+
import { homedir as homedir7 } from "node:os";
|
|
471
703
|
async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
472
|
-
let dates = new Set(targetDates), kimiHome = baseDir ??
|
|
704
|
+
let dates = new Set(targetDates), kimiHome = baseDir ?? join8(homedir7(), ".kimi"), sessionsDir = join8(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
|
|
473
705
|
if (files.length === 0) return emptyResult(dates);
|
|
474
706
|
let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
475
707
|
for (let filePath of files) {
|
|
476
708
|
let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), project = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
|
|
477
709
|
try {
|
|
478
|
-
content = await
|
|
710
|
+
content = await readFile4(filePath, "utf-8");
|
|
479
711
|
} catch {
|
|
480
712
|
continue;
|
|
481
713
|
}
|
|
@@ -530,7 +762,7 @@ function resolveKimiProject(hash, workspaceMap, aliases) {
|
|
|
530
762
|
async function loadWorkspaceMap(kimiHome) {
|
|
531
763
|
let map = /* @__PURE__ */ new Map();
|
|
532
764
|
try {
|
|
533
|
-
let raw = await
|
|
765
|
+
let raw = await readFile4(join8(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
|
|
534
766
|
if (config.workspaces)
|
|
535
767
|
for (let [hash, info] of Object.entries(config.workspaces))
|
|
536
768
|
info.path && map.set(hash, info.path);
|
|
@@ -540,15 +772,15 @@ async function loadWorkspaceMap(kimiHome) {
|
|
|
540
772
|
}
|
|
541
773
|
|
|
542
774
|
// src/scanners/amp.ts
|
|
543
|
-
import { readFile as
|
|
544
|
-
import { join as
|
|
545
|
-
import { homedir as
|
|
775
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
776
|
+
import { join as join9 } from "node:path";
|
|
777
|
+
import { homedir as homedir8 } from "node:os";
|
|
546
778
|
function resolveAmpDir(baseDir) {
|
|
547
779
|
if (baseDir) return baseDir;
|
|
548
780
|
let ampDataDir = process.env.AMP_DATA_DIR;
|
|
549
|
-
if (ampDataDir) return
|
|
781
|
+
if (ampDataDir) return join9(ampDataDir, "threads");
|
|
550
782
|
let xdgDataHome = process.env.XDG_DATA_HOME;
|
|
551
|
-
return xdgDataHome ?
|
|
783
|
+
return xdgDataHome ? join9(xdgDataHome, "amp", "threads") : join9(homedir8(), ".local", "share", "amp", "threads");
|
|
552
784
|
}
|
|
553
785
|
async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
554
786
|
let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
|
|
@@ -560,7 +792,7 @@ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
|
560
792
|
for (let filePath of threadFiles) {
|
|
561
793
|
let raw;
|
|
562
794
|
try {
|
|
563
|
-
raw = await
|
|
795
|
+
raw = await readFile5(filePath, "utf-8");
|
|
564
796
|
} catch {
|
|
565
797
|
continue;
|
|
566
798
|
}
|
|
@@ -643,21 +875,21 @@ function processMessages(thread, dates, grouped) {
|
|
|
643
875
|
}
|
|
644
876
|
|
|
645
877
|
// src/scanners/droid.ts
|
|
646
|
-
import { readFile as
|
|
647
|
-
import { join as
|
|
648
|
-
import { homedir as
|
|
878
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
879
|
+
import { join as join10, dirname as dirname3, basename as basename4 } from "node:path";
|
|
880
|
+
import { homedir as homedir9 } from "node:os";
|
|
649
881
|
function extractProjectFromSlug(dirPath) {
|
|
650
882
|
let parts = basename4(dirPath).split("-").filter(Boolean);
|
|
651
883
|
return parts[parts.length - 1] || "unknown";
|
|
652
884
|
}
|
|
653
885
|
async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
654
|
-
let dates = new Set(targetDates), dir = baseDir ??
|
|
886
|
+
let dates = new Set(targetDates), dir = baseDir ?? join10(homedir9(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
|
|
655
887
|
if (files.length === 0) return emptyResult(dates);
|
|
656
888
|
let grouped = initDateMap(dates);
|
|
657
889
|
for (let jsonlPath of files) {
|
|
658
890
|
let content;
|
|
659
891
|
try {
|
|
660
|
-
content = await
|
|
892
|
+
content = await readFile6(jsonlPath, "utf-8");
|
|
661
893
|
} catch {
|
|
662
894
|
continue;
|
|
663
895
|
}
|
|
@@ -674,9 +906,9 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
674
906
|
if (!ts) continue;
|
|
675
907
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
676
908
|
if (!dayMap) continue;
|
|
677
|
-
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath =
|
|
909
|
+
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath = join10(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
|
|
678
910
|
try {
|
|
679
|
-
settingsRaw = await
|
|
911
|
+
settingsRaw = await readFile6(settingsPath, "utf-8");
|
|
680
912
|
} catch {
|
|
681
913
|
continue;
|
|
682
914
|
}
|
|
@@ -711,16 +943,16 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
711
943
|
}
|
|
712
944
|
|
|
713
945
|
// src/scanners/opencode.ts
|
|
714
|
-
import { readFile as
|
|
715
|
-
import { homedir as
|
|
946
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
947
|
+
import { homedir as homedir10 } from "node:os";
|
|
716
948
|
async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
717
|
-
let dates = new Set(targetDates), dir = baseDir ?? `${
|
|
949
|
+
let dates = new Set(targetDates), dir = baseDir ?? `${homedir10()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
|
|
718
950
|
if (files.length === 0) return emptyResult(dates);
|
|
719
951
|
let grouped = initDateMap(dates);
|
|
720
952
|
for (let filePath of files) {
|
|
721
953
|
let raw;
|
|
722
954
|
try {
|
|
723
|
-
raw = await
|
|
955
|
+
raw = await readFile7(filePath, "utf-8");
|
|
724
956
|
} catch {
|
|
725
957
|
continue;
|
|
726
958
|
}
|
|
@@ -761,9 +993,9 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
761
993
|
}
|
|
762
994
|
|
|
763
995
|
// src/scanners/pi.ts
|
|
764
|
-
import { readFile as
|
|
765
|
-
import { join as
|
|
766
|
-
import { homedir as
|
|
996
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
997
|
+
import { join as join11, basename as basename5, dirname as dirname4 } from "node:path";
|
|
998
|
+
import { homedir as homedir11 } from "node:os";
|
|
767
999
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
768
1000
|
let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
|
|
769
1001
|
if (files.length === 0) return emptyResult(dates);
|
|
@@ -771,7 +1003,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
771
1003
|
for (let filePath of files) {
|
|
772
1004
|
let content;
|
|
773
1005
|
try {
|
|
774
|
-
content = await
|
|
1006
|
+
content = await readFile8(filePath, "utf-8");
|
|
775
1007
|
} catch {
|
|
776
1008
|
continue;
|
|
777
1009
|
}
|
|
@@ -826,7 +1058,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
826
1058
|
}
|
|
827
1059
|
function getSessionsDir() {
|
|
828
1060
|
let envDir = process.env.PI_CODING_AGENT_DIR;
|
|
829
|
-
return envDir ?
|
|
1061
|
+
return envDir ? join11(envDir, "sessions") : join11(homedir11(), ".pi", "agent", "sessions");
|
|
830
1062
|
}
|
|
831
1063
|
function extractProjectFromEncoded(encoded) {
|
|
832
1064
|
let parts = encoded.split("-").filter(Boolean);
|
|
@@ -849,6 +1081,7 @@ async function scanDates(targetDates, options = {}) {
|
|
|
849
1081
|
scanClaudeDates(uniqueDates, void 0, options.projectAliases),
|
|
850
1082
|
scanCodexDates(uniqueDates, void 0, options.projectAliases),
|
|
851
1083
|
scanCopilotDates(uniqueDates, void 0, options.projectAliases),
|
|
1084
|
+
scanCursorDates(uniqueDates),
|
|
852
1085
|
scanGeminiDates(uniqueDates, void 0, options.projectAliases),
|
|
853
1086
|
scanQwenDates(uniqueDates, void 0, options.projectAliases),
|
|
854
1087
|
scanKimiDates(uniqueDates, void 0, options.projectAliases),
|
|
@@ -884,9 +1117,9 @@ function createEmptyTotals() {
|
|
|
884
1117
|
}
|
|
885
1118
|
|
|
886
1119
|
// src/report.ts
|
|
887
|
-
import { readdir as readdir5, readFile as
|
|
888
|
-
import { homedir as
|
|
889
|
-
import { join as
|
|
1120
|
+
import { readdir as readdir5, readFile as readFile9 } from "node:fs/promises";
|
|
1121
|
+
import { homedir as homedir12 } from "node:os";
|
|
1122
|
+
import { join as join12 } from "node:path";
|
|
890
1123
|
async function buildLocalReport(range, options = {}) {
|
|
891
1124
|
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 });
|
|
892
1125
|
for (let result of results) {
|
|
@@ -947,18 +1180,18 @@ function buildPresetDates(range) {
|
|
|
947
1180
|
return result;
|
|
948
1181
|
}
|
|
949
1182
|
async function discoverAllDates() {
|
|
950
|
-
let dates = /* @__PURE__ */ new Set(), home =
|
|
1183
|
+
let dates = /* @__PURE__ */ new Set(), home = homedir12();
|
|
951
1184
|
return await Promise.all([
|
|
952
1185
|
discoverClaudeDates(dates),
|
|
953
1186
|
discoverCodexDates(dates),
|
|
954
1187
|
discoverGeminiDates(dates),
|
|
955
|
-
discoverGenericJsonlDates(
|
|
956
|
-
discoverGenericJsonlDates(
|
|
957
|
-
discoverGenericJsonlDates(
|
|
958
|
-
discoverGenericJsonDates(
|
|
959
|
-
discoverGenericJsonlDates(
|
|
960
|
-
discoverGenericJsonDates(
|
|
961
|
-
discoverGenericJsonlDates(
|
|
1188
|
+
discoverGenericJsonlDates(join12(home, ".copilot", "session-state"), dates),
|
|
1189
|
+
discoverGenericJsonlDates(join12(home, ".qwen", "tmp"), dates),
|
|
1190
|
+
discoverGenericJsonlDates(join12(home, ".kimi", "sessions"), dates),
|
|
1191
|
+
discoverGenericJsonDates(join12(home, ".local", "share", "amp", "threads"), dates),
|
|
1192
|
+
discoverGenericJsonlDates(join12(home, ".factory", "sessions"), dates),
|
|
1193
|
+
discoverGenericJsonDates(join12(home, ".local", "share", "opencode"), dates),
|
|
1194
|
+
discoverGenericJsonlDates(join12(home, ".pi", "agent", "sessions"), dates)
|
|
962
1195
|
]), [...dates].sort();
|
|
963
1196
|
}
|
|
964
1197
|
async function discoverGenericJsonlDates(baseDir, dates) {
|
|
@@ -1011,12 +1244,12 @@ async function walkForFiles(dir, ext, result) {
|
|
|
1011
1244
|
return;
|
|
1012
1245
|
}
|
|
1013
1246
|
for (let entry of entries) {
|
|
1014
|
-
let fullPath =
|
|
1247
|
+
let fullPath = join12(dir, entry.name);
|
|
1015
1248
|
entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
|
|
1016
1249
|
}
|
|
1017
1250
|
}
|
|
1018
1251
|
async function discoverGeminiDates(dates) {
|
|
1019
|
-
let baseDir =
|
|
1252
|
+
let baseDir = join12(homedir12(), ".gemini", "tmp"), files = [];
|
|
1020
1253
|
try {
|
|
1021
1254
|
await walkForGeminiJsonl(baseDir, files);
|
|
1022
1255
|
} catch {
|
|
@@ -1046,44 +1279,50 @@ async function walkForGeminiJsonl(dir, result) {
|
|
|
1046
1279
|
return;
|
|
1047
1280
|
}
|
|
1048
1281
|
for (let entry of entries) {
|
|
1049
|
-
let fullPath =
|
|
1282
|
+
let fullPath = join12(dir, entry.name);
|
|
1050
1283
|
entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
|
|
1051
1284
|
}
|
|
1052
1285
|
}
|
|
1053
1286
|
async function discoverClaudeDates(dates) {
|
|
1054
|
-
let
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
for (let projectDir of projectDirs) {
|
|
1061
|
-
let jsonlFiles = [];
|
|
1287
|
+
let home = homedir12(), baseDirs = [
|
|
1288
|
+
join12(home, ".config", "claude", "projects"),
|
|
1289
|
+
join12(home, ".claude", "projects")
|
|
1290
|
+
];
|
|
1291
|
+
for (let baseDir of baseDirs) {
|
|
1292
|
+
let projectDirs;
|
|
1062
1293
|
try {
|
|
1063
|
-
await
|
|
1294
|
+
projectDirs = await readdir5(baseDir);
|
|
1064
1295
|
} catch {
|
|
1065
1296
|
continue;
|
|
1066
1297
|
}
|
|
1067
|
-
for (let
|
|
1068
|
-
let
|
|
1069
|
-
|
|
1070
|
-
|
|
1298
|
+
for (let projectDir of projectDirs) {
|
|
1299
|
+
let jsonlFiles = [];
|
|
1300
|
+
try {
|
|
1301
|
+
await walkForClaudeJsonl(join12(baseDir, projectDir), jsonlFiles);
|
|
1302
|
+
} catch {
|
|
1303
|
+
continue;
|
|
1304
|
+
}
|
|
1305
|
+
for (let filePath of jsonlFiles) {
|
|
1306
|
+
let content = await safeReadUtf8(filePath);
|
|
1307
|
+
if (content)
|
|
1308
|
+
for (let line of content.split(`
|
|
1071
1309
|
`)) {
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1310
|
+
if (!line.trim()) continue;
|
|
1311
|
+
let record;
|
|
1312
|
+
try {
|
|
1313
|
+
record = JSON.parse(line);
|
|
1314
|
+
} catch {
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
let ts = parseTimestamp3(record.timestamp);
|
|
1318
|
+
ts && dates.add(toDateKey3(ts));
|
|
1078
1319
|
}
|
|
1079
|
-
|
|
1080
|
-
ts && dates.add(toDateKey3(ts));
|
|
1081
|
-
}
|
|
1320
|
+
}
|
|
1082
1321
|
}
|
|
1083
1322
|
}
|
|
1084
1323
|
}
|
|
1085
1324
|
async function discoverCodexDates(dates) {
|
|
1086
|
-
let baseDir =
|
|
1325
|
+
let baseDir = join12(homedir12(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
1087
1326
|
for (let filePath of files) {
|
|
1088
1327
|
let content = await safeReadUtf8(filePath);
|
|
1089
1328
|
if (content)
|
|
@@ -1105,17 +1344,17 @@ async function discoverCodexDates(dates) {
|
|
|
1105
1344
|
async function collectCodexSessionFiles(baseDir) {
|
|
1106
1345
|
let paths = [];
|
|
1107
1346
|
try {
|
|
1108
|
-
let archivedFiles = await readdir5(
|
|
1347
|
+
let archivedFiles = await readdir5(join12(baseDir, "archived_sessions"));
|
|
1109
1348
|
for (let file of archivedFiles)
|
|
1110
|
-
file.endsWith(".jsonl") && paths.push(
|
|
1349
|
+
file.endsWith(".jsonl") && paths.push(join12(baseDir, "archived_sessions", file));
|
|
1111
1350
|
} catch {
|
|
1112
1351
|
}
|
|
1113
|
-
return await walkForCodexJsonl(
|
|
1352
|
+
return await walkForCodexJsonl(join12(baseDir, "sessions"), paths), paths;
|
|
1114
1353
|
}
|
|
1115
1354
|
async function walkForClaudeJsonl(dir, result) {
|
|
1116
1355
|
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
1117
1356
|
for (let entry of entries) {
|
|
1118
|
-
let fullPath =
|
|
1357
|
+
let fullPath = join12(dir, entry.name);
|
|
1119
1358
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1120
1359
|
}
|
|
1121
1360
|
}
|
|
@@ -1127,13 +1366,13 @@ async function walkForCodexJsonl(dir, result) {
|
|
|
1127
1366
|
return;
|
|
1128
1367
|
}
|
|
1129
1368
|
for (let entry of entries) {
|
|
1130
|
-
let fullPath =
|
|
1369
|
+
let fullPath = join12(dir, entry.name);
|
|
1131
1370
|
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1132
1371
|
}
|
|
1133
1372
|
}
|
|
1134
1373
|
async function safeReadUtf8(filePath) {
|
|
1135
1374
|
try {
|
|
1136
|
-
return await
|
|
1375
|
+
return await readFile9(filePath, "utf-8");
|
|
1137
1376
|
} catch {
|
|
1138
1377
|
return null;
|
|
1139
1378
|
}
|
|
@@ -1179,7 +1418,7 @@ function createEmptyTotals2() {
|
|
|
1179
1418
|
function mergeTotals(target, source) {
|
|
1180
1419
|
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;
|
|
1181
1420
|
}
|
|
1182
|
-
var CLAUDE_PRICING = {
|
|
1421
|
+
var FAST_MULTIPLIER = 6, CLAUDE_PRICING = {
|
|
1183
1422
|
"claude-opus-4-6": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1184
1423
|
"claude-opus-4-5": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1185
1424
|
"claude-opus-4-1": { input: 15, cache_write_5m: 18.75, cache_write_1h: 30, cache_read: 1.5, output: 75 },
|
|
@@ -1266,13 +1505,15 @@ function toBreakdownTotals(breakdown, warnings) {
|
|
|
1266
1505
|
};
|
|
1267
1506
|
}
|
|
1268
1507
|
function calculateBreakdownCost(breakdown, warnings) {
|
|
1508
|
+
if (breakdown.costUSD != null && breakdown.costUSD > 0)
|
|
1509
|
+
return breakdown.costUSD;
|
|
1269
1510
|
if (breakdown.provider === "anthropic" && breakdown.product === "claude-code") {
|
|
1270
|
-
let
|
|
1511
|
+
let isFast = breakdown.model.endsWith("-fast"), baseModel = isFast ? breakdown.model.replace(/-fast$/, "") : breakdown.model, resolved = resolveModel(baseModel, CLAUDE_PRICING);
|
|
1271
1512
|
if (!resolved)
|
|
1272
1513
|
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;
|
|
1273
1514
|
resolved.normalized && warnings.add(`${breakdown.model} \u5DF2\u6309 ${resolved.model} \u7684\u516C\u5F00\u5355\u4EF7\u4F30\u7B97\u3002`);
|
|
1274
|
-
let pricing = CLAUDE_PRICING[resolved.model];
|
|
1275
|
-
return
|
|
1515
|
+
let pricing = CLAUDE_PRICING[resolved.model], baseCost = 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;
|
|
1516
|
+
return isFast ? baseCost * FAST_MULTIPLIER : baseCost;
|
|
1276
1517
|
}
|
|
1277
1518
|
if (breakdown.provider === "openai" && breakdown.product === "codex") {
|
|
1278
1519
|
let resolved = resolveModel(breakdown.model, OPENAI_PRICING);
|
|
@@ -1484,10 +1725,10 @@ function fmtDateShort(dateStr) {
|
|
|
1484
1725
|
}
|
|
1485
1726
|
|
|
1486
1727
|
// src/config.ts
|
|
1487
|
-
import { mkdir, readFile as
|
|
1488
|
-
import { homedir as
|
|
1489
|
-
import { basename as basename6, join as
|
|
1490
|
-
var CONFIG_DIR =
|
|
1728
|
+
import { mkdir, readFile as readFile10, writeFile } from "node:fs/promises";
|
|
1729
|
+
import { homedir as homedir13, hostname } from "node:os";
|
|
1730
|
+
import { basename as basename6, join as join13 } from "node:path";
|
|
1731
|
+
var CONFIG_DIR = join13(homedir13(), ".aiusage"), CONFIG_PATH = join13(CONFIG_DIR, "config.json");
|
|
1491
1732
|
function getConfigPath() {
|
|
1492
1733
|
return CONFIG_PATH;
|
|
1493
1734
|
}
|
|
@@ -1513,7 +1754,7 @@ function migrateConfig(config) {
|
|
|
1513
1754
|
}
|
|
1514
1755
|
async function readConfig() {
|
|
1515
1756
|
try {
|
|
1516
|
-
let raw = await
|
|
1757
|
+
let raw = await readFile10(CONFIG_PATH, "utf-8");
|
|
1517
1758
|
return migrateConfig(JSON.parse(raw));
|
|
1518
1759
|
} catch {
|
|
1519
1760
|
return {};
|
|
@@ -1600,13 +1841,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
1600
1841
|
|
|
1601
1842
|
// src/version.ts
|
|
1602
1843
|
import { readFileSync } from "node:fs";
|
|
1603
|
-
import { resolve, dirname as dirname5 } from "node:path";
|
|
1844
|
+
import { resolve as resolve2, dirname as dirname5 } from "node:path";
|
|
1604
1845
|
import { fileURLToPath } from "node:url";
|
|
1605
1846
|
var cached;
|
|
1606
1847
|
function getVersion() {
|
|
1607
1848
|
if (cached !== void 0) return cached;
|
|
1608
1849
|
try {
|
|
1609
|
-
let pkg =
|
|
1850
|
+
let pkg = resolve2(dirname5(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
1610
1851
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
1611
1852
|
} catch {
|
|
1612
1853
|
cached = "unknown";
|
|
@@ -1679,12 +1920,12 @@ async function requestJson(url, init) {
|
|
|
1679
1920
|
}
|
|
1680
1921
|
|
|
1681
1922
|
// src/schedule.ts
|
|
1682
|
-
import { mkdir as mkdir2, readFile as
|
|
1923
|
+
import { mkdir as mkdir2, readFile as readFile11, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
1683
1924
|
import { execFile } from "node:child_process";
|
|
1684
1925
|
import { promisify } from "node:util";
|
|
1685
|
-
import { homedir as
|
|
1686
|
-
import { join as
|
|
1687
|
-
var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH =
|
|
1926
|
+
import { homedir as homedir14, platform, tmpdir as tmpdir2 } from "node:os";
|
|
1927
|
+
import { join as join14, resolve as resolve3 } from "node:path";
|
|
1928
|
+
var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join14(homedir14(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join14(homedir14(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
|
|
1688
1929
|
function parseInterval(value) {
|
|
1689
1930
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
1690
1931
|
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
@@ -1719,7 +1960,7 @@ async function getScheduleStatus() {
|
|
|
1719
1960
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
1720
1961
|
}
|
|
1721
1962
|
function resolveCommandPaths() {
|
|
1722
|
-
let scriptPath =
|
|
1963
|
+
let scriptPath = resolve3(process.argv[1]);
|
|
1723
1964
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
1724
1965
|
throw new Error(
|
|
1725
1966
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -1729,7 +1970,7 @@ function resolveCommandPaths() {
|
|
|
1729
1970
|
}
|
|
1730
1971
|
async function enableLaunchd(intervalSeconds) {
|
|
1731
1972
|
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
1732
|
-
await mkdir2(
|
|
1973
|
+
await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
|
|
1733
1974
|
let plist = [
|
|
1734
1975
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
1735
1976
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
@@ -1783,7 +2024,7 @@ async function getLaunchdStatus() {
|
|
|
1783
2024
|
return { enabled: !1 };
|
|
1784
2025
|
}
|
|
1785
2026
|
try {
|
|
1786
|
-
let content = await
|
|
2027
|
+
let content = await readFile11(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
|
|
1787
2028
|
return {
|
|
1788
2029
|
enabled: !0,
|
|
1789
2030
|
interval,
|
|
@@ -1798,8 +2039,8 @@ async function getLaunchdStatus() {
|
|
|
1798
2039
|
}
|
|
1799
2040
|
}
|
|
1800
2041
|
async function enableCron(intervalSeconds) {
|
|
1801
|
-
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath =
|
|
1802
|
-
await mkdir2(
|
|
2042
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join14(homedir14(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
2043
|
+
await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
|
|
1803
2044
|
let existing = "";
|
|
1804
2045
|
try {
|
|
1805
2046
|
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
@@ -1857,7 +2098,7 @@ async function getCronStatus() {
|
|
|
1857
2098
|
}
|
|
1858
2099
|
}
|
|
1859
2100
|
async function writeCrontab(content) {
|
|
1860
|
-
let tmpFile =
|
|
2101
|
+
let tmpFile = join14(tmpdir2(), `aiusage-cron-${Date.now()}`);
|
|
1861
2102
|
await writeFile2(tmpFile, content, "utf-8");
|
|
1862
2103
|
try {
|
|
1863
2104
|
await execFileAsync("crontab", [tmpFile]);
|
|
@@ -1889,8 +2130,8 @@ function escapeXml(value) {
|
|
|
1889
2130
|
|
|
1890
2131
|
// src/doctor.ts
|
|
1891
2132
|
import { readdir as readdir6, stat as stat2 } from "node:fs/promises";
|
|
1892
|
-
import { homedir as
|
|
1893
|
-
import { join as
|
|
2133
|
+
import { homedir as homedir15 } from "node:os";
|
|
2134
|
+
import { join as join15 } from "node:path";
|
|
1894
2135
|
var msgs = {
|
|
1895
2136
|
en: {
|
|
1896
2137
|
groupConfig: "Configuration",
|
|
@@ -1952,7 +2193,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
1952
2193
|
}
|
|
1953
2194
|
for (let e of entries) {
|
|
1954
2195
|
if (count >= cap) break;
|
|
1955
|
-
let full =
|
|
2196
|
+
let full = join15(current, e.name);
|
|
1956
2197
|
e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
|
|
1957
2198
|
}
|
|
1958
2199
|
}
|
|
@@ -1981,17 +2222,17 @@ async function runDoctor(lang = "zh") {
|
|
|
1981
2222
|
}
|
|
1982
2223
|
target.lastSuccessfulUploadAt ? checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "ok", message: target.lastSuccessfulUploadAt }) : checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "warn", message: s.lastSyncNone });
|
|
1983
2224
|
}
|
|
1984
|
-
let g3 = s.groupTools, home =
|
|
1985
|
-
{ dir:
|
|
1986
|
-
{ dir:
|
|
1987
|
-
{ dir:
|
|
1988
|
-
{ dir:
|
|
1989
|
-
{ dir:
|
|
1990
|
-
{ dir:
|
|
1991
|
-
{ dir:
|
|
1992
|
-
{ dir:
|
|
1993
|
-
{ dir:
|
|
1994
|
-
{ dir:
|
|
2225
|
+
let g3 = s.groupTools, home = homedir15(), tools = [
|
|
2226
|
+
{ dir: join15(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
|
|
2227
|
+
{ dir: join15(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
|
|
2228
|
+
{ dir: join15(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
|
|
2229
|
+
{ dir: join15(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
|
|
2230
|
+
{ dir: join15(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
|
|
2231
|
+
{ dir: join15(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
|
|
2232
|
+
{ dir: join15(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
|
|
2233
|
+
{ dir: join15(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
|
|
2234
|
+
{ dir: join15(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
|
|
2235
|
+
{ dir: join15(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
|
|
1995
2236
|
];
|
|
1996
2237
|
for (let tool of tools) {
|
|
1997
2238
|
try {
|
|
@@ -2012,6 +2253,192 @@ async function runDoctor(lang = "zh") {
|
|
|
2012
2253
|
}) : checks.push({ group: g4, name: s.schedule, status: "warn", message: s.scheduleOff }), checks;
|
|
2013
2254
|
}
|
|
2014
2255
|
|
|
2256
|
+
// src/project.ts
|
|
2257
|
+
import { open as open3, readdir as readdir7, readFile as readFile12 } from "node:fs/promises";
|
|
2258
|
+
import { join as join16 } from "node:path";
|
|
2259
|
+
import { homedir as homedir16 } from "node:os";
|
|
2260
|
+
async function discoverProjects(projectAliases) {
|
|
2261
|
+
let projectMap = /* @__PURE__ */ new Map();
|
|
2262
|
+
function add(name, source) {
|
|
2263
|
+
!name || name === "unknown" || (projectMap.has(name) || projectMap.set(name, /* @__PURE__ */ new Set()), projectMap.get(name).add(source));
|
|
2264
|
+
}
|
|
2265
|
+
await Promise.all([
|
|
2266
|
+
// Claude: ~/.claude/projects/{encoded-path}/
|
|
2267
|
+
// 目录名是编码路径(- 替换 /),但项目名本身可能含 -,无法可靠还原。
|
|
2268
|
+
// 读取每个项目目录下第一个 jsonl 首行的 cwd 字段来获取真实项目名。
|
|
2269
|
+
discoverClaudeProjects().then((names) => names.forEach((n) => add(n, "claude"))),
|
|
2270
|
+
// Codex: ~/.codex/sessions/YYYY/MM/DD/*.jsonl
|
|
2271
|
+
// 每个 session 首行 session_meta 含 cwd 字段
|
|
2272
|
+
discoverCodexProjects().then((names) => names.forEach((n) => add(n, "codex"))),
|
|
2273
|
+
// Copilot CLI: ~/.copilot/session-state/{sessionId}/events.jsonl
|
|
2274
|
+
// 首行 session.start 含 data.context.gitRoot / cwd
|
|
2275
|
+
discoverCopilotProjects().then((names) => names.forEach((n) => add(n, "copilot"))),
|
|
2276
|
+
// Gemini CLI: ~/.gemini/projects.json 含 { projects: { path: name } }
|
|
2277
|
+
discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini")))
|
|
2278
|
+
]);
|
|
2279
|
+
let results = [];
|
|
2280
|
+
for (let [name, sources] of projectMap) {
|
|
2281
|
+
let alias = projectAliases?.[name];
|
|
2282
|
+
results.push({
|
|
2283
|
+
name,
|
|
2284
|
+
alias,
|
|
2285
|
+
sources: [...sources].sort()
|
|
2286
|
+
});
|
|
2287
|
+
}
|
|
2288
|
+
return results.sort((a, b) => a.name.localeCompare(b.name));
|
|
2289
|
+
}
|
|
2290
|
+
async function discoverClaudeProjects() {
|
|
2291
|
+
let names = [];
|
|
2292
|
+
for (let baseDir of getClaudeDirs()) {
|
|
2293
|
+
let entries;
|
|
2294
|
+
try {
|
|
2295
|
+
entries = await readdir7(baseDir, { withFileTypes: !0 });
|
|
2296
|
+
} catch {
|
|
2297
|
+
continue;
|
|
2298
|
+
}
|
|
2299
|
+
for (let entry of entries) {
|
|
2300
|
+
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
|
2301
|
+
let projectDir = join16(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
|
|
2302
|
+
name && name !== "unknown" && names.push(name);
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
return names;
|
|
2306
|
+
}
|
|
2307
|
+
async function discoverCodexProjects() {
|
|
2308
|
+
let sessionsDir = join16(homedir16(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
|
|
2309
|
+
for (let filePath of files) {
|
|
2310
|
+
let name = await extractCwdFromSessionMeta(filePath);
|
|
2311
|
+
name && name !== "unknown" && projects.add(name);
|
|
2312
|
+
}
|
|
2313
|
+
return [...projects];
|
|
2314
|
+
}
|
|
2315
|
+
async function extractCwdFromSessionMeta(filePath) {
|
|
2316
|
+
let fh;
|
|
2317
|
+
try {
|
|
2318
|
+
fh = await open3(filePath, "r");
|
|
2319
|
+
let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
2320
|
+
if (bytesRead === 0) return;
|
|
2321
|
+
let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
2322
|
+
`)[0], cwd = JSON.parse(line)?.payload?.cwd;
|
|
2323
|
+
if (!cwd) return;
|
|
2324
|
+
let parts = cwd.split("/").filter(Boolean);
|
|
2325
|
+
return parts[parts.length - 1] || void 0;
|
|
2326
|
+
} catch {
|
|
2327
|
+
return;
|
|
2328
|
+
} finally {
|
|
2329
|
+
await fh?.close();
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
async function walkJsonlFiles(dir) {
|
|
2333
|
+
let result = [];
|
|
2334
|
+
async function walk2(d) {
|
|
2335
|
+
let entries;
|
|
2336
|
+
try {
|
|
2337
|
+
entries = await readdir7(d, { withFileTypes: !0 });
|
|
2338
|
+
} catch {
|
|
2339
|
+
return;
|
|
2340
|
+
}
|
|
2341
|
+
for (let entry of entries) {
|
|
2342
|
+
let full = join16(d, entry.name);
|
|
2343
|
+
entry.isDirectory() ? await walk2(full) : entry.name.endsWith(".jsonl") && result.push(full);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
return await walk2(dir), result;
|
|
2347
|
+
}
|
|
2348
|
+
async function extractCwdFromFirstJsonl(dir) {
|
|
2349
|
+
let jsonlPath = await findFirstJsonl(dir);
|
|
2350
|
+
if (!jsonlPath) return;
|
|
2351
|
+
let fh;
|
|
2352
|
+
try {
|
|
2353
|
+
fh = await open3(jsonlPath, "r");
|
|
2354
|
+
let buf = Buffer.alloc(32 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
2355
|
+
if (bytesRead === 0) return;
|
|
2356
|
+
let lines = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
2357
|
+
`);
|
|
2358
|
+
for (let line of lines)
|
|
2359
|
+
if (line.trim())
|
|
2360
|
+
try {
|
|
2361
|
+
let record = JSON.parse(line);
|
|
2362
|
+
if (record?.cwd) {
|
|
2363
|
+
let parts = record.cwd.split("/").filter(Boolean), name = parts[parts.length - 1];
|
|
2364
|
+
if (name) return name;
|
|
2365
|
+
}
|
|
2366
|
+
} catch {
|
|
2367
|
+
continue;
|
|
2368
|
+
}
|
|
2369
|
+
return;
|
|
2370
|
+
} catch {
|
|
2371
|
+
return;
|
|
2372
|
+
} finally {
|
|
2373
|
+
await fh?.close();
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
async function findFirstJsonl(dir) {
|
|
2377
|
+
let entries;
|
|
2378
|
+
try {
|
|
2379
|
+
entries = await readdir7(dir, { withFileTypes: !0 });
|
|
2380
|
+
} catch {
|
|
2381
|
+
return;
|
|
2382
|
+
}
|
|
2383
|
+
let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
|
|
2384
|
+
if (topJsonl) return join16(dir, topJsonl.name);
|
|
2385
|
+
for (let entry of entries)
|
|
2386
|
+
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
2387
|
+
try {
|
|
2388
|
+
let sub = (await readdir7(join16(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
2389
|
+
if (sub) return join16(dir, entry.name, sub);
|
|
2390
|
+
} catch {
|
|
2391
|
+
continue;
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
async function discoverCopilotProjects() {
|
|
2395
|
+
let dir = join16(homedir16(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
|
|
2396
|
+
for (let filePath of files) {
|
|
2397
|
+
let fh;
|
|
2398
|
+
try {
|
|
2399
|
+
fh = await open3(filePath, "r");
|
|
2400
|
+
let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
2401
|
+
if (bytesRead === 0) continue;
|
|
2402
|
+
let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
2403
|
+
`)[0], record = JSON.parse(line), raw = record?.data?.context?.gitRoot ?? record?.data?.context?.cwd;
|
|
2404
|
+
if (raw) {
|
|
2405
|
+
let parts = raw.split("/").filter(Boolean), name = parts[parts.length - 1];
|
|
2406
|
+
name && name !== "unknown" && projects.add(name);
|
|
2407
|
+
}
|
|
2408
|
+
} catch {
|
|
2409
|
+
continue;
|
|
2410
|
+
} finally {
|
|
2411
|
+
await fh?.close();
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
return [...projects];
|
|
2415
|
+
}
|
|
2416
|
+
async function discoverGeminiProjects() {
|
|
2417
|
+
let filePath = join16(homedir16(), ".gemini", "projects.json");
|
|
2418
|
+
try {
|
|
2419
|
+
let raw = await readFile12(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
2420
|
+
if (!projects || typeof projects != "object") return [];
|
|
2421
|
+
let names = [];
|
|
2422
|
+
for (let [path, _name] of Object.entries(projects)) {
|
|
2423
|
+
let parts = path.split("/").filter(Boolean), name = parts[parts.length - 1];
|
|
2424
|
+
name && name !== "unknown" && names.push(name);
|
|
2425
|
+
}
|
|
2426
|
+
return names;
|
|
2427
|
+
} catch {
|
|
2428
|
+
return [];
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
function getClaudeDirs() {
|
|
2432
|
+
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
2433
|
+
if (envVar)
|
|
2434
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join16(p, "projects"));
|
|
2435
|
+
let home = homedir16();
|
|
2436
|
+
return [
|
|
2437
|
+
join16(home, ".config", "claude", "projects"),
|
|
2438
|
+
join16(home, ".claude", "projects")
|
|
2439
|
+
];
|
|
2440
|
+
}
|
|
2441
|
+
|
|
2015
2442
|
// src/cli.ts
|
|
2016
2443
|
var argv = process.argv.slice(2), command = argv[0];
|
|
2017
2444
|
try {
|
|
@@ -2051,9 +2478,15 @@ try {
|
|
|
2051
2478
|
} else if (command === "doctor") {
|
|
2052
2479
|
let parsed = parseArgs(argv.slice(1));
|
|
2053
2480
|
await runDoctorCommand(parsed.flags);
|
|
2054
|
-
} else command === "config" && argv[1] === "set"
|
|
2481
|
+
} else if (command === "config" && argv[1] === "set")
|
|
2482
|
+
await runConfigSet(argv.slice(2));
|
|
2483
|
+
else if (command === "project") {
|
|
2484
|
+
let sub = argv[1];
|
|
2485
|
+
sub === "list" || sub === void 0 ? await runProjectList() : sub === "alias" ? await runProjectAlias(argv.slice(2)) : (console.error(`\u672A\u77E5\u5B50\u547D\u4EE4: project ${sub}`), console.log("\u53EF\u7528: aiusage project list, aiusage project alias <\u9879\u76EE\u540D> <\u522B\u540D>"), process.exitCode = 1);
|
|
2486
|
+
} else command === "setup" ? (console.log(`To deploy the server, clone the repo and run the setup wizard:
|
|
2055
2487
|
`), console.log(" git clone https://github.com/ennann/aiusage.git"), console.log(" cd aiusage && pnpm install"), console.log(` pnpm setup
|
|
2056
|
-
`), console.log("See: https://github.com/ennann/aiusage#deploy-your-own-server")) : printHelp()
|
|
2488
|
+
`), console.log("See: https://github.com/ennann/aiusage#deploy-your-own-server")) : command === "--help" || command === "-h" || command === "help" ? printHelp() : (command && console.error(`\u672A\u77E5\u547D\u4EE4: "${command}"
|
|
2489
|
+
`), printUsageHint());
|
|
2057
2490
|
} catch (error) {
|
|
2058
2491
|
console.error(error instanceof Error ? error.message : String(error)), process.exitCode = 1;
|
|
2059
2492
|
}
|
|
@@ -2130,10 +2563,10 @@ async function runEnroll(flags) {
|
|
|
2130
2563
|
}, null, 2));
|
|
2131
2564
|
}
|
|
2132
2565
|
function prompt(question) {
|
|
2133
|
-
let rl =
|
|
2134
|
-
return new Promise((
|
|
2566
|
+
let rl = createInterface3({ input: process.stdin, output: process.stdout });
|
|
2567
|
+
return new Promise((resolve4) => {
|
|
2135
2568
|
rl.question(question, (answer) => {
|
|
2136
|
-
rl.close(),
|
|
2569
|
+
rl.close(), resolve4(answer.trim());
|
|
2137
2570
|
});
|
|
2138
2571
|
});
|
|
2139
2572
|
}
|
|
@@ -2231,10 +2664,58 @@ async function runConfigSet(args) {
|
|
|
2231
2664
|
let config = await readConfig(), next = setConfigValue(config, keyPath, values);
|
|
2232
2665
|
await writeConfig(next), console.log(JSON.stringify({ configPath: getConfigPath(), updated: keyPath }, null, 2));
|
|
2233
2666
|
}
|
|
2667
|
+
async function runProjectList() {
|
|
2668
|
+
let config = await readConfig(), projects = await discoverProjects(config.projectAliases);
|
|
2669
|
+
if (projects.length === 0) {
|
|
2670
|
+
console.log("\u672A\u53D1\u73B0\u4EFB\u4F55\u9879\u76EE\u3002");
|
|
2671
|
+
return;
|
|
2672
|
+
}
|
|
2673
|
+
let nameWidth = Math.max(6, ...projects.map((p) => p.name.length)), aliasWidth = Math.max(4, ...projects.map((p) => (p.alias ?? "-").length));
|
|
2674
|
+
console.log(
|
|
2675
|
+
"\u9879\u76EE".padEnd(nameWidth + 2) + "\u522B\u540D".padEnd(aliasWidth + 2) + "\u6765\u6E90"
|
|
2676
|
+
), console.log("-".repeat(nameWidth + aliasWidth + 20));
|
|
2677
|
+
for (let p of projects)
|
|
2678
|
+
console.log(
|
|
2679
|
+
p.name.padEnd(nameWidth + 2) + (p.alias ?? "-").padEnd(aliasWidth + 2) + p.sources.join(", ")
|
|
2680
|
+
);
|
|
2681
|
+
console.log(`
|
|
2682
|
+
\u5171 ${projects.length} \u4E2A\u9879\u76EE`);
|
|
2683
|
+
}
|
|
2684
|
+
async function runProjectAlias(args) {
|
|
2685
|
+
if (args.length === 0) {
|
|
2686
|
+
let aliases = (await readConfig()).projectAliases ?? {}, entries = Object.entries(aliases);
|
|
2687
|
+
if (entries.length === 0) {
|
|
2688
|
+
console.log("\u5C1A\u672A\u8BBE\u7F6E\u4EFB\u4F55\u9879\u76EE\u522B\u540D\u3002"), console.log("\u7528\u6CD5: aiusage project alias <\u9879\u76EE\u540D> <\u522B\u540D>");
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
for (let [from, to] of entries)
|
|
2692
|
+
console.log(` ${from} \u2192 ${to}`);
|
|
2693
|
+
return;
|
|
2694
|
+
}
|
|
2695
|
+
if (args[0] === "--remove") {
|
|
2696
|
+
let name2 = args.slice(1).join(" ").trim();
|
|
2697
|
+
if (!name2) throw new Error("\u8BF7\u6307\u5B9A\u8981\u79FB\u9664\u522B\u540D\u7684\u9879\u76EE\u540D");
|
|
2698
|
+
let config2 = await readConfig(), aliases = { ...config2.projectAliases ?? {} };
|
|
2699
|
+
if (!(name2 in aliases))
|
|
2700
|
+
throw new Error(`\u9879\u76EE "${name2}" \u672A\u8BBE\u7F6E\u522B\u540D`);
|
|
2701
|
+
delete aliases[name2], config2.projectAliases = Object.keys(aliases).length > 0 ? aliases : void 0, await writeConfig(config2), console.log(`\u5DF2\u79FB\u9664 "${name2}" \u7684\u522B\u540D\u3002`);
|
|
2702
|
+
return;
|
|
2703
|
+
}
|
|
2704
|
+
if (args.length < 2)
|
|
2705
|
+
throw new Error("\u7528\u6CD5: aiusage project alias <\u9879\u76EE\u540D> <\u522B\u540D>");
|
|
2706
|
+
let name = args[0], alias = args.slice(1).join(" ").trim();
|
|
2707
|
+
if (!alias) throw new Error("\u522B\u540D\u4E0D\u80FD\u4E3A\u7A7A");
|
|
2708
|
+
let config = await readConfig();
|
|
2709
|
+
config.projectAliases = { ...config.projectAliases ?? {}, [name]: alias }, await writeConfig(config), console.log(`\u5DF2\u8BBE\u7F6E: ${name} \u2192 ${alias}`);
|
|
2710
|
+
}
|
|
2234
2711
|
function printHelp() {
|
|
2235
|
-
let initialized =
|
|
2712
|
+
let initialized = existsSync2(getConfigPath());
|
|
2713
|
+
console.log(`aiusage v${getVersion()}
|
|
2714
|
+
`), console.log("Usage: aiusage <command>"), console.log(""), console.log("Commands:"), console.log(" aiusage init [--device-id ID] [--device-name NAME] [--lookback N]"), console.log(" aiusage enroll --server URL --site-id ID --enroll-token TOKEN [--target NAME]"), console.log(" aiusage sync [--target NAME] [--date YYYY-MM-DD] [--from YYYY-MM-DD [--to YYYY-MM-DD]] [--lookback N] [--today]"), console.log(" aiusage health [--target NAME] [--server URL]"), console.log(" aiusage scan [--date YYYY-MM-DD] [--json]"), console.log(" aiusage report [--range 7d|1m|3m|all] [--detail] [--lang en|zh] [--no-emoji] [--json]"), console.log(" aiusage schedule [on|off|status] [--every 5m]"), console.log(" aiusage doctor"), console.log(" aiusage project [list]"), console.log(" aiusage project alias [<\u9879\u76EE\u540D> <\u522B\u540D>] [--remove <\u9879\u76EE\u540D>]"), console.log(" aiusage config set <key> <value...>"), console.log(""), console.log(`\u914D\u7F6E\u6587\u4EF6: ${getConfigPath()}${initialized ? "" : " (\u5C1A\u672A\u521D\u59CB\u5316)"}`);
|
|
2715
|
+
}
|
|
2716
|
+
function printUsageHint() {
|
|
2236
2717
|
console.log(`aiusage v${getVersion()}
|
|
2237
|
-
`), console.log("
|
|
2718
|
+
`), console.log("\u5E38\u7528\u547D\u4EE4:"), console.log(" scan [--date YYYY-MM-DD] \u626B\u63CF\u67D0\u65E5\u7528\u91CF\u660E\u7EC6"), console.log(" report [--range 7d|1m|3m|all] \u672C\u5730\u7528\u91CF\u62A5\u544A"), console.log(" project [list] \u5217\u51FA\u672C\u673A\u6240\u6709\u9879\u76EE"), console.log(" project alias <\u540D\u79F0> <\u522B\u540D> \u8BBE\u7F6E\u9879\u76EE\u522B\u540D"), console.log(" sync \u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"), console.log(" schedule [on|off|status] \u5B9A\u65F6\u540C\u6B65"), console.log(" doctor \u8BCA\u65AD\u68C0\u67E5"), console.log(" config set <key> <value> \u4FEE\u6539\u914D\u7F6E"), console.log(""), console.log(`\u914D\u7F6E\u6587\u4EF6: ${getConfigPath()}`);
|
|
2238
2719
|
}
|
|
2239
2720
|
function parseArgs(args) {
|
|
2240
2721
|
let flags = {}, positionals = [];
|