@aiusage/cli 1.0.0 → 1.1.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/dist/cli.js +493 -259
- package/package.json +1 -1
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;
|
|
45
|
+
}
|
|
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);
|
|
20
49
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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";
|
|
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,7 +272,8 @@ 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;
|
|
@@ -157,8 +284,8 @@ async function scanCodexDates(targetDates, codexDir, projectAliases) {
|
|
|
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
|
-
|
|
287
|
+
if (globalSeenSigs.has(signature)) continue;
|
|
288
|
+
globalSeenSigs.add(signature);
|
|
162
289
|
let last = info.last_token_usage, grouped = groupedByDate.get(usageDate);
|
|
163
290
|
if (!grouped) continue;
|
|
164
291
|
let key = `${currentModel}|${currentProject}`, existing = grouped.get(key);
|
|
@@ -176,31 +303,30 @@ async function scanCodexDates(targetDates, codexDir, projectAliases) {
|
|
|
176
303
|
reasoningOutputTokens: last.reasoning_output_tokens ?? 0
|
|
177
304
|
});
|
|
178
305
|
}
|
|
306
|
+
} finally {
|
|
307
|
+
await fh.close();
|
|
179
308
|
}
|
|
180
|
-
return new Map(
|
|
181
|
-
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
182
|
-
);
|
|
183
309
|
}
|
|
184
310
|
async function collectSessionFiles(baseDir) {
|
|
185
|
-
let paths = [], archivedDir =
|
|
311
|
+
let paths = [], archivedDir = join3(baseDir, "archived_sessions");
|
|
186
312
|
try {
|
|
187
|
-
let files = await
|
|
313
|
+
let files = await readdir3(archivedDir);
|
|
188
314
|
for (let f of files)
|
|
189
|
-
f.endsWith(".jsonl") && paths.push(
|
|
315
|
+
f.endsWith(".jsonl") && paths.push(join3(archivedDir, f));
|
|
190
316
|
} catch {
|
|
191
317
|
}
|
|
192
|
-
let sessionsDir =
|
|
318
|
+
let sessionsDir = join3(baseDir, "sessions");
|
|
193
319
|
return await walkDir(sessionsDir, paths), paths;
|
|
194
320
|
}
|
|
195
321
|
async function walkDir(dir, result) {
|
|
196
322
|
let entries;
|
|
197
323
|
try {
|
|
198
|
-
entries = await
|
|
324
|
+
entries = await readdir3(dir, { withFileTypes: !0 });
|
|
199
325
|
} catch {
|
|
200
326
|
return;
|
|
201
327
|
}
|
|
202
328
|
for (let entry of entries) {
|
|
203
|
-
let fullPath =
|
|
329
|
+
let fullPath = join3(dir, entry.name);
|
|
204
330
|
entry.isDirectory() ? await walkDir(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
205
331
|
}
|
|
206
332
|
}
|
|
@@ -223,68 +349,9 @@ function extractProject(cwd, aliases) {
|
|
|
223
349
|
}
|
|
224
350
|
|
|
225
351
|
// src/scanners/copilot.ts
|
|
226
|
-
import { readFile
|
|
352
|
+
import { readFile } from "node:fs/promises";
|
|
227
353
|
import { join as join4 } from "node:path";
|
|
228
354
|
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
355
|
async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
289
356
|
let dates = new Set(targetDates), dir = baseDir ?? join4(homedir3(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
|
|
290
357
|
if (files.length === 0) return emptyResult(dates);
|
|
@@ -292,7 +359,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
292
359
|
for (let filePath of files) {
|
|
293
360
|
let content;
|
|
294
361
|
try {
|
|
295
|
-
content = await
|
|
362
|
+
content = await readFile(filePath, "utf-8");
|
|
296
363
|
} catch {
|
|
297
364
|
continue;
|
|
298
365
|
}
|
|
@@ -344,18 +411,176 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
344
411
|
return finalize(grouped);
|
|
345
412
|
}
|
|
346
413
|
|
|
414
|
+
// src/scanners/cursor.ts
|
|
415
|
+
import { existsSync } from "node:fs";
|
|
416
|
+
import { copyFile, mkdtemp, rm } from "node:fs/promises";
|
|
417
|
+
import { homedir as homedir4, tmpdir } from "node:os";
|
|
418
|
+
import { join as join5, resolve } from "node:path";
|
|
419
|
+
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";
|
|
420
|
+
function getDefaultDbPath() {
|
|
421
|
+
if (process.platform === "darwin")
|
|
422
|
+
return join5(homedir4(), "Library", "Application Support", "Cursor", CURSOR_STATE_DB_RELATIVE);
|
|
423
|
+
if (process.platform === "win32") {
|
|
424
|
+
let appData = process.env.APPDATA?.trim() || join5(homedir4(), "AppData", "Roaming");
|
|
425
|
+
return join5(appData, "Cursor", CURSOR_STATE_DB_RELATIVE);
|
|
426
|
+
}
|
|
427
|
+
let xdg = process.env.XDG_CONFIG_HOME?.trim() || join5(homedir4(), ".config");
|
|
428
|
+
return join5(xdg, "Cursor", CURSOR_STATE_DB_RELATIVE);
|
|
429
|
+
}
|
|
430
|
+
function findDbPath() {
|
|
431
|
+
let explicit = process.env[CURSOR_STATE_DB_PATH_ENV]?.trim();
|
|
432
|
+
if (explicit) {
|
|
433
|
+
let p = resolve(explicit);
|
|
434
|
+
return existsSync(p) ? p : null;
|
|
435
|
+
}
|
|
436
|
+
let dirs = process.env[CURSOR_CONFIG_DIR_ENV]?.trim(), candidates = dirs ? dirs.split(",").map((v) => {
|
|
437
|
+
let r = resolve(v.trim());
|
|
438
|
+
return r.endsWith(".vscdb") ? r : join5(r, CURSOR_STATE_DB_RELATIVE);
|
|
439
|
+
}) : [getDefaultDbPath()];
|
|
440
|
+
for (let c of candidates)
|
|
441
|
+
if (existsSync(c)) return c;
|
|
442
|
+
return null;
|
|
443
|
+
}
|
|
444
|
+
function readAuthFromDb(dbPath) {
|
|
445
|
+
let { DatabaseSync } = __require("node:sqlite"), db = new DatabaseSync(dbPath, { open: !0 });
|
|
446
|
+
try {
|
|
447
|
+
let raw = db.prepare("SELECT value FROM ItemTable WHERE key = ? LIMIT 1").get("cursorAuth/accessToken")?.value, token;
|
|
448
|
+
return typeof raw == "string" ? token = raw.trim() || void 0 : Buffer.isBuffer(raw) && (token = raw.toString("utf8").trim() || void 0), { accessToken: token };
|
|
449
|
+
} finally {
|
|
450
|
+
db.close();
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
async function withSnapshot(dbPath, cb) {
|
|
454
|
+
let dir = await mkdtemp(join5(tmpdir(), "aiusage-cursor-")), snap = join5(dir, "state.vscdb");
|
|
455
|
+
await copyFile(dbPath, snap);
|
|
456
|
+
for (let suffix of ["-shm", "-wal"])
|
|
457
|
+
existsSync(`${dbPath}${suffix}`) && await copyFile(`${dbPath}${suffix}`, `${snap}${suffix}`);
|
|
458
|
+
try {
|
|
459
|
+
return cb(snap);
|
|
460
|
+
} finally {
|
|
461
|
+
await rm(dir, { recursive: !0, force: !0 });
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
async function readAuth(dbPath) {
|
|
465
|
+
try {
|
|
466
|
+
return readAuthFromDb(dbPath);
|
|
467
|
+
} catch (err) {
|
|
468
|
+
if (err instanceof Error && /database is locked/i.test(err.message))
|
|
469
|
+
return withSnapshot(dbPath, (snap) => readAuthFromDb(snap));
|
|
470
|
+
throw err;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
function jwtSub(token) {
|
|
474
|
+
let part = token.split(".")[1];
|
|
475
|
+
if (!part) return;
|
|
476
|
+
let b64 = part.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(part.length / 4) * 4, "=");
|
|
477
|
+
try {
|
|
478
|
+
return JSON.parse(Buffer.from(b64, "base64").toString("utf8")).sub?.trim();
|
|
479
|
+
} catch {
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
function getWebBaseUrl() {
|
|
484
|
+
return (process.env[CURSOR_WEB_BASE_URL_ENV]?.trim() || "https://cursor.com").replace(/\/+$/, "");
|
|
485
|
+
}
|
|
486
|
+
async function fetchCsv(accessToken) {
|
|
487
|
+
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}` }];
|
|
488
|
+
for (let cv of cookieValues)
|
|
489
|
+
attempts.push({ Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` }), attempts.push({ Authorization: `Bearer ${accessToken}`, Cookie: `${CURSOR_SESSION_COOKIE}=${cv}` });
|
|
490
|
+
let failures = [];
|
|
491
|
+
for (let headers of attempts) {
|
|
492
|
+
let res = await fetch(url, { headers: { Accept: "text/csv,*/*;q=0.8", ...headers } });
|
|
493
|
+
if (res.ok) return res.text();
|
|
494
|
+
failures.push(`${res.status} ${res.statusText}`);
|
|
495
|
+
}
|
|
496
|
+
throw new Error(`Cursor API failed: ${failures.join(", ")}`);
|
|
497
|
+
}
|
|
498
|
+
function parseCsvLine(line) {
|
|
499
|
+
let vals = [], cur = "", inQ = !1;
|
|
500
|
+
for (let i = 0; i < line.length; i++) {
|
|
501
|
+
let c = line[i];
|
|
502
|
+
c === '"' ? inQ && line[i + 1] === '"' ? (cur += '"', i++) : inQ = !inQ : c === "," && !inQ ? (vals.push(cur), cur = "") : cur += c;
|
|
503
|
+
}
|
|
504
|
+
return vals.push(cur), vals;
|
|
505
|
+
}
|
|
506
|
+
function parseNum(v) {
|
|
507
|
+
let n = Number((v ?? "").replace(/,/g, "").trim());
|
|
508
|
+
return Number.isFinite(n) && n > 0 ? Math.round(n) : 0;
|
|
509
|
+
}
|
|
510
|
+
function parseDateStr(v) {
|
|
511
|
+
let s = v?.trim();
|
|
512
|
+
if (!s) return null;
|
|
513
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return s;
|
|
514
|
+
let d = new Date(s);
|
|
515
|
+
return isNaN(d.getTime()) ? null : dateKey(d);
|
|
516
|
+
}
|
|
517
|
+
async function scanCursorDates(targetDates) {
|
|
518
|
+
let dateSet = new Set(targetDates), empty = new Map(targetDates.map((d) => [d, []])), dbPath = findDbPath();
|
|
519
|
+
if (!dbPath) return empty;
|
|
520
|
+
let auth;
|
|
521
|
+
try {
|
|
522
|
+
auth = await readAuth(dbPath);
|
|
523
|
+
} catch {
|
|
524
|
+
return empty;
|
|
525
|
+
}
|
|
526
|
+
if (!auth.accessToken) return empty;
|
|
527
|
+
let csvText;
|
|
528
|
+
try {
|
|
529
|
+
csvText = await fetchCsv(auth.accessToken);
|
|
530
|
+
} catch {
|
|
531
|
+
return empty;
|
|
532
|
+
}
|
|
533
|
+
let grouped = /* @__PURE__ */ new Map();
|
|
534
|
+
for (let d of dateSet) grouped.set(d, /* @__PURE__ */ new Map());
|
|
535
|
+
let headers = null;
|
|
536
|
+
for (let rawLine of csvText.split(/\r?\n/)) {
|
|
537
|
+
let line = rawLine.trim();
|
|
538
|
+
if (!line) continue;
|
|
539
|
+
let values = parseCsvLine(line);
|
|
540
|
+
if (!headers) {
|
|
541
|
+
headers = values;
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
let row = {};
|
|
545
|
+
headers.forEach((h, i) => {
|
|
546
|
+
row[h] = values[i] ?? "";
|
|
547
|
+
});
|
|
548
|
+
let date = parseDateStr(row.Date);
|
|
549
|
+
if (!date || !dateSet.has(date)) continue;
|
|
550
|
+
let rawModel = row.Model?.trim();
|
|
551
|
+
if (!rawModel) continue;
|
|
552
|
+
let model = normalizeModelName(rawModel);
|
|
553
|
+
if (!(parseNum(row["Total Tokens"]) || parseNum(row.Tokens))) continue;
|
|
554
|
+
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);
|
|
555
|
+
existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.cachedInputTokens += cacheRead, existing.cacheWriteTokens += inputWithCache, existing.outputTokens += output) : dayMap.set(model, {
|
|
556
|
+
provider: "cursor",
|
|
557
|
+
product: "cursor",
|
|
558
|
+
channel: "ide",
|
|
559
|
+
model,
|
|
560
|
+
project: "unknown",
|
|
561
|
+
eventCount: 1,
|
|
562
|
+
inputTokens,
|
|
563
|
+
cachedInputTokens: cacheRead,
|
|
564
|
+
cacheWriteTokens: inputWithCache,
|
|
565
|
+
outputTokens: output,
|
|
566
|
+
reasoningOutputTokens: 0
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
return new Map([...grouped.entries()].map(([d, m]) => [d, [...m.values()]]));
|
|
570
|
+
}
|
|
571
|
+
|
|
347
572
|
// src/scanners/gemini.ts
|
|
348
|
-
import { readFile as
|
|
349
|
-
import { join as
|
|
350
|
-
import { homedir as
|
|
573
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
574
|
+
import { join as join6 } from "node:path";
|
|
575
|
+
import { homedir as homedir5 } from "node:os";
|
|
351
576
|
async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
352
|
-
let dates = new Set(targetDates), dir = baseDir ??
|
|
577
|
+
let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
|
|
353
578
|
if (files.length === 0) return emptyResult(dates);
|
|
354
579
|
let grouped = initDateMap(dates);
|
|
355
580
|
for (let filePath of files) {
|
|
356
581
|
let content;
|
|
357
582
|
try {
|
|
358
|
-
content = await
|
|
583
|
+
content = await readFile2(filePath, "utf-8");
|
|
359
584
|
} catch {
|
|
360
585
|
continue;
|
|
361
586
|
}
|
|
@@ -369,7 +594,7 @@ async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
|
369
594
|
for (let msg of messages) {
|
|
370
595
|
let tokens = extractTokens(msg);
|
|
371
596
|
if (!tokens) continue;
|
|
372
|
-
let model = msg.model ?? fallbackModel, ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
|
|
597
|
+
let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
|
|
373
598
|
if (!ts) continue;
|
|
374
599
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
375
600
|
dayMap && accumulate(
|
|
@@ -407,17 +632,17 @@ function extractTokens(msg) {
|
|
|
407
632
|
}
|
|
408
633
|
|
|
409
634
|
// src/scanners/qwen.ts
|
|
410
|
-
import { readFile as
|
|
411
|
-
import { join as
|
|
412
|
-
import { homedir as
|
|
635
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
636
|
+
import { join as join7, basename as basename2, dirname } from "node:path";
|
|
637
|
+
import { homedir as homedir6 } from "node:os";
|
|
413
638
|
async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
414
|
-
let dates = new Set(targetDates), dir = baseDir ??
|
|
639
|
+
let dates = new Set(targetDates), dir = baseDir ?? join7(homedir6(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
|
|
415
640
|
if (files.length === 0) return emptyResult(dates);
|
|
416
641
|
let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
417
642
|
for (let filePath of files) {
|
|
418
643
|
let chatsDir = dirname(filePath), projectDir = dirname(chatsDir), projectId = basename2(projectDir), content;
|
|
419
644
|
try {
|
|
420
|
-
content = await
|
|
645
|
+
content = await readFile3(filePath, "utf-8");
|
|
421
646
|
} catch {
|
|
422
647
|
continue;
|
|
423
648
|
}
|
|
@@ -465,17 +690,17 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
465
690
|
}
|
|
466
691
|
|
|
467
692
|
// src/scanners/kimi.ts
|
|
468
|
-
import { readFile as
|
|
469
|
-
import { join as
|
|
470
|
-
import { homedir as
|
|
693
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
694
|
+
import { join as join8, basename as basename3, dirname as dirname2 } from "node:path";
|
|
695
|
+
import { homedir as homedir7 } from "node:os";
|
|
471
696
|
async function scanKimiDates(targetDates, baseDir, projectAliases) {
|
|
472
|
-
let dates = new Set(targetDates), kimiHome = baseDir ??
|
|
697
|
+
let dates = new Set(targetDates), kimiHome = baseDir ?? join8(homedir7(), ".kimi"), sessionsDir = join8(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
|
|
473
698
|
if (files.length === 0) return emptyResult(dates);
|
|
474
699
|
let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
475
700
|
for (let filePath of files) {
|
|
476
701
|
let sessionDir = dirname2(filePath), hashDir = dirname2(sessionDir), workDirHash = basename3(hashDir), project = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
|
|
477
702
|
try {
|
|
478
|
-
content = await
|
|
703
|
+
content = await readFile4(filePath, "utf-8");
|
|
479
704
|
} catch {
|
|
480
705
|
continue;
|
|
481
706
|
}
|
|
@@ -530,7 +755,7 @@ function resolveKimiProject(hash, workspaceMap, aliases) {
|
|
|
530
755
|
async function loadWorkspaceMap(kimiHome) {
|
|
531
756
|
let map = /* @__PURE__ */ new Map();
|
|
532
757
|
try {
|
|
533
|
-
let raw = await
|
|
758
|
+
let raw = await readFile4(join8(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
|
|
534
759
|
if (config.workspaces)
|
|
535
760
|
for (let [hash, info] of Object.entries(config.workspaces))
|
|
536
761
|
info.path && map.set(hash, info.path);
|
|
@@ -540,15 +765,15 @@ async function loadWorkspaceMap(kimiHome) {
|
|
|
540
765
|
}
|
|
541
766
|
|
|
542
767
|
// src/scanners/amp.ts
|
|
543
|
-
import { readFile as
|
|
544
|
-
import { join as
|
|
545
|
-
import { homedir as
|
|
768
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
769
|
+
import { join as join9 } from "node:path";
|
|
770
|
+
import { homedir as homedir8 } from "node:os";
|
|
546
771
|
function resolveAmpDir(baseDir) {
|
|
547
772
|
if (baseDir) return baseDir;
|
|
548
773
|
let ampDataDir = process.env.AMP_DATA_DIR;
|
|
549
|
-
if (ampDataDir) return
|
|
774
|
+
if (ampDataDir) return join9(ampDataDir, "threads");
|
|
550
775
|
let xdgDataHome = process.env.XDG_DATA_HOME;
|
|
551
|
-
return xdgDataHome ?
|
|
776
|
+
return xdgDataHome ? join9(xdgDataHome, "amp", "threads") : join9(homedir8(), ".local", "share", "amp", "threads");
|
|
552
777
|
}
|
|
553
778
|
async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
554
779
|
let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
|
|
@@ -560,7 +785,7 @@ async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
|
560
785
|
for (let filePath of threadFiles) {
|
|
561
786
|
let raw;
|
|
562
787
|
try {
|
|
563
|
-
raw = await
|
|
788
|
+
raw = await readFile5(filePath, "utf-8");
|
|
564
789
|
} catch {
|
|
565
790
|
continue;
|
|
566
791
|
}
|
|
@@ -643,21 +868,21 @@ function processMessages(thread, dates, grouped) {
|
|
|
643
868
|
}
|
|
644
869
|
|
|
645
870
|
// src/scanners/droid.ts
|
|
646
|
-
import { readFile as
|
|
647
|
-
import { join as
|
|
648
|
-
import { homedir as
|
|
871
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
872
|
+
import { join as join10, dirname as dirname3, basename as basename4 } from "node:path";
|
|
873
|
+
import { homedir as homedir9 } from "node:os";
|
|
649
874
|
function extractProjectFromSlug(dirPath) {
|
|
650
875
|
let parts = basename4(dirPath).split("-").filter(Boolean);
|
|
651
876
|
return parts[parts.length - 1] || "unknown";
|
|
652
877
|
}
|
|
653
878
|
async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
654
|
-
let dates = new Set(targetDates), dir = baseDir ??
|
|
879
|
+
let dates = new Set(targetDates), dir = baseDir ?? join10(homedir9(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
|
|
655
880
|
if (files.length === 0) return emptyResult(dates);
|
|
656
881
|
let grouped = initDateMap(dates);
|
|
657
882
|
for (let jsonlPath of files) {
|
|
658
883
|
let content;
|
|
659
884
|
try {
|
|
660
|
-
content = await
|
|
885
|
+
content = await readFile6(jsonlPath, "utf-8");
|
|
661
886
|
} catch {
|
|
662
887
|
continue;
|
|
663
888
|
}
|
|
@@ -674,9 +899,9 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
674
899
|
if (!ts) continue;
|
|
675
900
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
676
901
|
if (!dayMap) continue;
|
|
677
|
-
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath =
|
|
902
|
+
let sessionDir = dirname3(jsonlPath), jsonlName = basename4(jsonlPath, ".jsonl"), settingsPath = join10(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
|
|
678
903
|
try {
|
|
679
|
-
settingsRaw = await
|
|
904
|
+
settingsRaw = await readFile6(settingsPath, "utf-8");
|
|
680
905
|
} catch {
|
|
681
906
|
continue;
|
|
682
907
|
}
|
|
@@ -711,16 +936,16 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
711
936
|
}
|
|
712
937
|
|
|
713
938
|
// src/scanners/opencode.ts
|
|
714
|
-
import { readFile as
|
|
715
|
-
import { homedir as
|
|
939
|
+
import { readFile as readFile7 } from "node:fs/promises";
|
|
940
|
+
import { homedir as homedir10 } from "node:os";
|
|
716
941
|
async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
717
|
-
let dates = new Set(targetDates), dir = baseDir ?? `${
|
|
942
|
+
let dates = new Set(targetDates), dir = baseDir ?? `${homedir10()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
|
|
718
943
|
if (files.length === 0) return emptyResult(dates);
|
|
719
944
|
let grouped = initDateMap(dates);
|
|
720
945
|
for (let filePath of files) {
|
|
721
946
|
let raw;
|
|
722
947
|
try {
|
|
723
|
-
raw = await
|
|
948
|
+
raw = await readFile7(filePath, "utf-8");
|
|
724
949
|
} catch {
|
|
725
950
|
continue;
|
|
726
951
|
}
|
|
@@ -761,9 +986,9 @@ async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
|
761
986
|
}
|
|
762
987
|
|
|
763
988
|
// src/scanners/pi.ts
|
|
764
|
-
import { readFile as
|
|
765
|
-
import { join as
|
|
766
|
-
import { homedir as
|
|
989
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
990
|
+
import { join as join11, basename as basename5, dirname as dirname4 } from "node:path";
|
|
991
|
+
import { homedir as homedir11 } from "node:os";
|
|
767
992
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
768
993
|
let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
|
|
769
994
|
if (files.length === 0) return emptyResult(dates);
|
|
@@ -771,7 +996,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
771
996
|
for (let filePath of files) {
|
|
772
997
|
let content;
|
|
773
998
|
try {
|
|
774
|
-
content = await
|
|
999
|
+
content = await readFile8(filePath, "utf-8");
|
|
775
1000
|
} catch {
|
|
776
1001
|
continue;
|
|
777
1002
|
}
|
|
@@ -826,7 +1051,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
826
1051
|
}
|
|
827
1052
|
function getSessionsDir() {
|
|
828
1053
|
let envDir = process.env.PI_CODING_AGENT_DIR;
|
|
829
|
-
return envDir ?
|
|
1054
|
+
return envDir ? join11(envDir, "sessions") : join11(homedir11(), ".pi", "agent", "sessions");
|
|
830
1055
|
}
|
|
831
1056
|
function extractProjectFromEncoded(encoded) {
|
|
832
1057
|
let parts = encoded.split("-").filter(Boolean);
|
|
@@ -849,6 +1074,7 @@ async function scanDates(targetDates, options = {}) {
|
|
|
849
1074
|
scanClaudeDates(uniqueDates, void 0, options.projectAliases),
|
|
850
1075
|
scanCodexDates(uniqueDates, void 0, options.projectAliases),
|
|
851
1076
|
scanCopilotDates(uniqueDates, void 0, options.projectAliases),
|
|
1077
|
+
scanCursorDates(uniqueDates),
|
|
852
1078
|
scanGeminiDates(uniqueDates, void 0, options.projectAliases),
|
|
853
1079
|
scanQwenDates(uniqueDates, void 0, options.projectAliases),
|
|
854
1080
|
scanKimiDates(uniqueDates, void 0, options.projectAliases),
|
|
@@ -884,9 +1110,9 @@ function createEmptyTotals() {
|
|
|
884
1110
|
}
|
|
885
1111
|
|
|
886
1112
|
// src/report.ts
|
|
887
|
-
import { readdir as readdir5, readFile as
|
|
888
|
-
import { homedir as
|
|
889
|
-
import { join as
|
|
1113
|
+
import { readdir as readdir5, readFile as readFile9 } from "node:fs/promises";
|
|
1114
|
+
import { homedir as homedir12 } from "node:os";
|
|
1115
|
+
import { join as join12 } from "node:path";
|
|
890
1116
|
async function buildLocalReport(range, options = {}) {
|
|
891
1117
|
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
1118
|
for (let result of results) {
|
|
@@ -947,18 +1173,18 @@ function buildPresetDates(range) {
|
|
|
947
1173
|
return result;
|
|
948
1174
|
}
|
|
949
1175
|
async function discoverAllDates() {
|
|
950
|
-
let dates = /* @__PURE__ */ new Set(), home =
|
|
1176
|
+
let dates = /* @__PURE__ */ new Set(), home = homedir12();
|
|
951
1177
|
return await Promise.all([
|
|
952
1178
|
discoverClaudeDates(dates),
|
|
953
1179
|
discoverCodexDates(dates),
|
|
954
1180
|
discoverGeminiDates(dates),
|
|
955
|
-
discoverGenericJsonlDates(
|
|
956
|
-
discoverGenericJsonlDates(
|
|
957
|
-
discoverGenericJsonlDates(
|
|
958
|
-
discoverGenericJsonDates(
|
|
959
|
-
discoverGenericJsonlDates(
|
|
960
|
-
discoverGenericJsonDates(
|
|
961
|
-
discoverGenericJsonlDates(
|
|
1181
|
+
discoverGenericJsonlDates(join12(home, ".copilot", "session-state"), dates),
|
|
1182
|
+
discoverGenericJsonlDates(join12(home, ".qwen", "tmp"), dates),
|
|
1183
|
+
discoverGenericJsonlDates(join12(home, ".kimi", "sessions"), dates),
|
|
1184
|
+
discoverGenericJsonDates(join12(home, ".local", "share", "amp", "threads"), dates),
|
|
1185
|
+
discoverGenericJsonlDates(join12(home, ".factory", "sessions"), dates),
|
|
1186
|
+
discoverGenericJsonDates(join12(home, ".local", "share", "opencode"), dates),
|
|
1187
|
+
discoverGenericJsonlDates(join12(home, ".pi", "agent", "sessions"), dates)
|
|
962
1188
|
]), [...dates].sort();
|
|
963
1189
|
}
|
|
964
1190
|
async function discoverGenericJsonlDates(baseDir, dates) {
|
|
@@ -1011,12 +1237,12 @@ async function walkForFiles(dir, ext, result) {
|
|
|
1011
1237
|
return;
|
|
1012
1238
|
}
|
|
1013
1239
|
for (let entry of entries) {
|
|
1014
|
-
let fullPath =
|
|
1240
|
+
let fullPath = join12(dir, entry.name);
|
|
1015
1241
|
entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
|
|
1016
1242
|
}
|
|
1017
1243
|
}
|
|
1018
1244
|
async function discoverGeminiDates(dates) {
|
|
1019
|
-
let baseDir =
|
|
1245
|
+
let baseDir = join12(homedir12(), ".gemini", "tmp"), files = [];
|
|
1020
1246
|
try {
|
|
1021
1247
|
await walkForGeminiJsonl(baseDir, files);
|
|
1022
1248
|
} catch {
|
|
@@ -1046,44 +1272,50 @@ async function walkForGeminiJsonl(dir, result) {
|
|
|
1046
1272
|
return;
|
|
1047
1273
|
}
|
|
1048
1274
|
for (let entry of entries) {
|
|
1049
|
-
let fullPath =
|
|
1275
|
+
let fullPath = join12(dir, entry.name);
|
|
1050
1276
|
entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
|
|
1051
1277
|
}
|
|
1052
1278
|
}
|
|
1053
1279
|
async function discoverClaudeDates(dates) {
|
|
1054
|
-
let
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
for (let projectDir of projectDirs) {
|
|
1061
|
-
let jsonlFiles = [];
|
|
1280
|
+
let home = homedir12(), baseDirs = [
|
|
1281
|
+
join12(home, ".config", "claude", "projects"),
|
|
1282
|
+
join12(home, ".claude", "projects")
|
|
1283
|
+
];
|
|
1284
|
+
for (let baseDir of baseDirs) {
|
|
1285
|
+
let projectDirs;
|
|
1062
1286
|
try {
|
|
1063
|
-
await
|
|
1287
|
+
projectDirs = await readdir5(baseDir);
|
|
1064
1288
|
} catch {
|
|
1065
1289
|
continue;
|
|
1066
1290
|
}
|
|
1067
|
-
for (let
|
|
1068
|
-
let
|
|
1069
|
-
|
|
1070
|
-
|
|
1291
|
+
for (let projectDir of projectDirs) {
|
|
1292
|
+
let jsonlFiles = [];
|
|
1293
|
+
try {
|
|
1294
|
+
await walkForClaudeJsonl(join12(baseDir, projectDir), jsonlFiles);
|
|
1295
|
+
} catch {
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
for (let filePath of jsonlFiles) {
|
|
1299
|
+
let content = await safeReadUtf8(filePath);
|
|
1300
|
+
if (content)
|
|
1301
|
+
for (let line of content.split(`
|
|
1071
1302
|
`)) {
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1303
|
+
if (!line.trim()) continue;
|
|
1304
|
+
let record;
|
|
1305
|
+
try {
|
|
1306
|
+
record = JSON.parse(line);
|
|
1307
|
+
} catch {
|
|
1308
|
+
continue;
|
|
1309
|
+
}
|
|
1310
|
+
let ts = parseTimestamp3(record.timestamp);
|
|
1311
|
+
ts && dates.add(toDateKey3(ts));
|
|
1078
1312
|
}
|
|
1079
|
-
|
|
1080
|
-
ts && dates.add(toDateKey3(ts));
|
|
1081
|
-
}
|
|
1313
|
+
}
|
|
1082
1314
|
}
|
|
1083
1315
|
}
|
|
1084
1316
|
}
|
|
1085
1317
|
async function discoverCodexDates(dates) {
|
|
1086
|
-
let baseDir =
|
|
1318
|
+
let baseDir = join12(homedir12(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
1087
1319
|
for (let filePath of files) {
|
|
1088
1320
|
let content = await safeReadUtf8(filePath);
|
|
1089
1321
|
if (content)
|
|
@@ -1105,17 +1337,17 @@ async function discoverCodexDates(dates) {
|
|
|
1105
1337
|
async function collectCodexSessionFiles(baseDir) {
|
|
1106
1338
|
let paths = [];
|
|
1107
1339
|
try {
|
|
1108
|
-
let archivedFiles = await readdir5(
|
|
1340
|
+
let archivedFiles = await readdir5(join12(baseDir, "archived_sessions"));
|
|
1109
1341
|
for (let file of archivedFiles)
|
|
1110
|
-
file.endsWith(".jsonl") && paths.push(
|
|
1342
|
+
file.endsWith(".jsonl") && paths.push(join12(baseDir, "archived_sessions", file));
|
|
1111
1343
|
} catch {
|
|
1112
1344
|
}
|
|
1113
|
-
return await walkForCodexJsonl(
|
|
1345
|
+
return await walkForCodexJsonl(join12(baseDir, "sessions"), paths), paths;
|
|
1114
1346
|
}
|
|
1115
1347
|
async function walkForClaudeJsonl(dir, result) {
|
|
1116
1348
|
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
1117
1349
|
for (let entry of entries) {
|
|
1118
|
-
let fullPath =
|
|
1350
|
+
let fullPath = join12(dir, entry.name);
|
|
1119
1351
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1120
1352
|
}
|
|
1121
1353
|
}
|
|
@@ -1127,13 +1359,13 @@ async function walkForCodexJsonl(dir, result) {
|
|
|
1127
1359
|
return;
|
|
1128
1360
|
}
|
|
1129
1361
|
for (let entry of entries) {
|
|
1130
|
-
let fullPath =
|
|
1362
|
+
let fullPath = join12(dir, entry.name);
|
|
1131
1363
|
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
1132
1364
|
}
|
|
1133
1365
|
}
|
|
1134
1366
|
async function safeReadUtf8(filePath) {
|
|
1135
1367
|
try {
|
|
1136
|
-
return await
|
|
1368
|
+
return await readFile9(filePath, "utf-8");
|
|
1137
1369
|
} catch {
|
|
1138
1370
|
return null;
|
|
1139
1371
|
}
|
|
@@ -1179,7 +1411,7 @@ function createEmptyTotals2() {
|
|
|
1179
1411
|
function mergeTotals(target, source) {
|
|
1180
1412
|
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
1413
|
}
|
|
1182
|
-
var CLAUDE_PRICING = {
|
|
1414
|
+
var FAST_MULTIPLIER = 6, CLAUDE_PRICING = {
|
|
1183
1415
|
"claude-opus-4-6": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1184
1416
|
"claude-opus-4-5": { input: 5, cache_write_5m: 6.25, cache_write_1h: 10, cache_read: 0.5, output: 25 },
|
|
1185
1417
|
"claude-opus-4-1": { input: 15, cache_write_5m: 18.75, cache_write_1h: 30, cache_read: 1.5, output: 75 },
|
|
@@ -1266,13 +1498,15 @@ function toBreakdownTotals(breakdown, warnings) {
|
|
|
1266
1498
|
};
|
|
1267
1499
|
}
|
|
1268
1500
|
function calculateBreakdownCost(breakdown, warnings) {
|
|
1501
|
+
if (breakdown.costUSD != null && breakdown.costUSD > 0)
|
|
1502
|
+
return breakdown.costUSD;
|
|
1269
1503
|
if (breakdown.provider === "anthropic" && breakdown.product === "claude-code") {
|
|
1270
|
-
let
|
|
1504
|
+
let isFast = breakdown.model.endsWith("-fast"), baseModel = isFast ? breakdown.model.replace(/-fast$/, "") : breakdown.model, resolved = resolveModel(baseModel, CLAUDE_PRICING);
|
|
1271
1505
|
if (!resolved)
|
|
1272
1506
|
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
1507
|
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
|
|
1508
|
+
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;
|
|
1509
|
+
return isFast ? baseCost * FAST_MULTIPLIER : baseCost;
|
|
1276
1510
|
}
|
|
1277
1511
|
if (breakdown.provider === "openai" && breakdown.product === "codex") {
|
|
1278
1512
|
let resolved = resolveModel(breakdown.model, OPENAI_PRICING);
|
|
@@ -1484,10 +1718,10 @@ function fmtDateShort(dateStr) {
|
|
|
1484
1718
|
}
|
|
1485
1719
|
|
|
1486
1720
|
// src/config.ts
|
|
1487
|
-
import { mkdir, readFile as
|
|
1488
|
-
import { homedir as
|
|
1489
|
-
import { basename as basename6, join as
|
|
1490
|
-
var CONFIG_DIR =
|
|
1721
|
+
import { mkdir, readFile as readFile10, writeFile } from "node:fs/promises";
|
|
1722
|
+
import { homedir as homedir13, hostname } from "node:os";
|
|
1723
|
+
import { basename as basename6, join as join13 } from "node:path";
|
|
1724
|
+
var CONFIG_DIR = join13(homedir13(), ".aiusage"), CONFIG_PATH = join13(CONFIG_DIR, "config.json");
|
|
1491
1725
|
function getConfigPath() {
|
|
1492
1726
|
return CONFIG_PATH;
|
|
1493
1727
|
}
|
|
@@ -1513,7 +1747,7 @@ function migrateConfig(config) {
|
|
|
1513
1747
|
}
|
|
1514
1748
|
async function readConfig() {
|
|
1515
1749
|
try {
|
|
1516
|
-
let raw = await
|
|
1750
|
+
let raw = await readFile10(CONFIG_PATH, "utf-8");
|
|
1517
1751
|
return migrateConfig(JSON.parse(raw));
|
|
1518
1752
|
} catch {
|
|
1519
1753
|
return {};
|
|
@@ -1600,13 +1834,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
1600
1834
|
|
|
1601
1835
|
// src/version.ts
|
|
1602
1836
|
import { readFileSync } from "node:fs";
|
|
1603
|
-
import { resolve, dirname as dirname5 } from "node:path";
|
|
1837
|
+
import { resolve as resolve2, dirname as dirname5 } from "node:path";
|
|
1604
1838
|
import { fileURLToPath } from "node:url";
|
|
1605
1839
|
var cached;
|
|
1606
1840
|
function getVersion() {
|
|
1607
1841
|
if (cached !== void 0) return cached;
|
|
1608
1842
|
try {
|
|
1609
|
-
let pkg =
|
|
1843
|
+
let pkg = resolve2(dirname5(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
1610
1844
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
1611
1845
|
} catch {
|
|
1612
1846
|
cached = "unknown";
|
|
@@ -1679,12 +1913,12 @@ async function requestJson(url, init) {
|
|
|
1679
1913
|
}
|
|
1680
1914
|
|
|
1681
1915
|
// src/schedule.ts
|
|
1682
|
-
import { mkdir as mkdir2, readFile as
|
|
1916
|
+
import { mkdir as mkdir2, readFile as readFile11, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
1683
1917
|
import { execFile } from "node:child_process";
|
|
1684
1918
|
import { promisify } from "node:util";
|
|
1685
|
-
import { homedir as
|
|
1686
|
-
import { join as
|
|
1687
|
-
var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH =
|
|
1919
|
+
import { homedir as homedir14, platform, tmpdir as tmpdir2 } from "node:os";
|
|
1920
|
+
import { join as join14, resolve as resolve3 } from "node:path";
|
|
1921
|
+
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
1922
|
function parseInterval(value) {
|
|
1689
1923
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
1690
1924
|
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
@@ -1719,7 +1953,7 @@ async function getScheduleStatus() {
|
|
|
1719
1953
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
1720
1954
|
}
|
|
1721
1955
|
function resolveCommandPaths() {
|
|
1722
|
-
let scriptPath =
|
|
1956
|
+
let scriptPath = resolve3(process.argv[1]);
|
|
1723
1957
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
1724
1958
|
throw new Error(
|
|
1725
1959
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -1729,7 +1963,7 @@ function resolveCommandPaths() {
|
|
|
1729
1963
|
}
|
|
1730
1964
|
async function enableLaunchd(intervalSeconds) {
|
|
1731
1965
|
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
1732
|
-
await mkdir2(
|
|
1966
|
+
await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
|
|
1733
1967
|
let plist = [
|
|
1734
1968
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
1735
1969
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
@@ -1783,7 +2017,7 @@ async function getLaunchdStatus() {
|
|
|
1783
2017
|
return { enabled: !1 };
|
|
1784
2018
|
}
|
|
1785
2019
|
try {
|
|
1786
|
-
let content = await
|
|
2020
|
+
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
2021
|
return {
|
|
1788
2022
|
enabled: !0,
|
|
1789
2023
|
interval,
|
|
@@ -1798,8 +2032,8 @@ async function getLaunchdStatus() {
|
|
|
1798
2032
|
}
|
|
1799
2033
|
}
|
|
1800
2034
|
async function enableCron(intervalSeconds) {
|
|
1801
|
-
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath =
|
|
1802
|
-
await mkdir2(
|
|
2035
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join14(homedir14(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
2036
|
+
await mkdir2(join14(homedir14(), ".aiusage"), { recursive: !0 });
|
|
1803
2037
|
let existing = "";
|
|
1804
2038
|
try {
|
|
1805
2039
|
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
@@ -1857,7 +2091,7 @@ async function getCronStatus() {
|
|
|
1857
2091
|
}
|
|
1858
2092
|
}
|
|
1859
2093
|
async function writeCrontab(content) {
|
|
1860
|
-
let tmpFile =
|
|
2094
|
+
let tmpFile = join14(tmpdir2(), `aiusage-cron-${Date.now()}`);
|
|
1861
2095
|
await writeFile2(tmpFile, content, "utf-8");
|
|
1862
2096
|
try {
|
|
1863
2097
|
await execFileAsync("crontab", [tmpFile]);
|
|
@@ -1889,8 +2123,8 @@ function escapeXml(value) {
|
|
|
1889
2123
|
|
|
1890
2124
|
// src/doctor.ts
|
|
1891
2125
|
import { readdir as readdir6, stat as stat2 } from "node:fs/promises";
|
|
1892
|
-
import { homedir as
|
|
1893
|
-
import { join as
|
|
2126
|
+
import { homedir as homedir15 } from "node:os";
|
|
2127
|
+
import { join as join15 } from "node:path";
|
|
1894
2128
|
var msgs = {
|
|
1895
2129
|
en: {
|
|
1896
2130
|
groupConfig: "Configuration",
|
|
@@ -1952,7 +2186,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
1952
2186
|
}
|
|
1953
2187
|
for (let e of entries) {
|
|
1954
2188
|
if (count >= cap) break;
|
|
1955
|
-
let full =
|
|
2189
|
+
let full = join15(current, e.name);
|
|
1956
2190
|
e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
|
|
1957
2191
|
}
|
|
1958
2192
|
}
|
|
@@ -1981,17 +2215,17 @@ async function runDoctor(lang = "zh") {
|
|
|
1981
2215
|
}
|
|
1982
2216
|
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
2217
|
}
|
|
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:
|
|
2218
|
+
let g3 = s.groupTools, home = homedir15(), tools = [
|
|
2219
|
+
{ dir: join15(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
|
|
2220
|
+
{ dir: join15(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
|
|
2221
|
+
{ dir: join15(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
|
|
2222
|
+
{ dir: join15(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
|
|
2223
|
+
{ dir: join15(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
|
|
2224
|
+
{ dir: join15(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
|
|
2225
|
+
{ dir: join15(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
|
|
2226
|
+
{ dir: join15(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
|
|
2227
|
+
{ dir: join15(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
|
|
2228
|
+
{ dir: join15(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
|
|
1995
2229
|
];
|
|
1996
2230
|
for (let tool of tools) {
|
|
1997
2231
|
try {
|
|
@@ -2130,10 +2364,10 @@ async function runEnroll(flags) {
|
|
|
2130
2364
|
}, null, 2));
|
|
2131
2365
|
}
|
|
2132
2366
|
function prompt(question) {
|
|
2133
|
-
let rl =
|
|
2134
|
-
return new Promise((
|
|
2367
|
+
let rl = createInterface3({ input: process.stdin, output: process.stdout });
|
|
2368
|
+
return new Promise((resolve4) => {
|
|
2135
2369
|
rl.question(question, (answer) => {
|
|
2136
|
-
rl.close(),
|
|
2370
|
+
rl.close(), resolve4(answer.trim());
|
|
2137
2371
|
});
|
|
2138
2372
|
});
|
|
2139
2373
|
}
|
|
@@ -2232,7 +2466,7 @@ async function runConfigSet(args) {
|
|
|
2232
2466
|
await writeConfig(next), console.log(JSON.stringify({ configPath: getConfigPath(), updated: keyPath }, null, 2));
|
|
2233
2467
|
}
|
|
2234
2468
|
function printHelp() {
|
|
2235
|
-
let initialized =
|
|
2469
|
+
let initialized = existsSync2(getConfigPath());
|
|
2236
2470
|
console.log(`aiusage v${getVersion()}
|
|
2237
2471
|
`), 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 config set <key> <value...>"), console.log(""), console.log(`\u914D\u7F6E\u6587\u4EF6: ${getConfigPath()}${initialized ? "" : " (\u5C1A\u672A\u521D\u59CB\u5316)"}`);
|
|
2238
2472
|
}
|