@aiusage/cli 1.6.4 → 1.7.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.
Files changed (2) hide show
  1. package/dist/cli.js +641 -64
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require < "u" ? require : typeof
7
7
  });
8
8
 
9
9
  // src/cli.ts
10
- import { createInterface as createInterface3 } from "node:readline";
10
+ import { createInterface as createInterface4 } from "node:readline";
11
11
  import { hostname as hostname3 } from "node:os";
12
12
 
13
13
  // src/scanners/antigravity.ts
@@ -3119,11 +3119,566 @@ function fmtDateShort(dateStr) {
3119
3119
  return (/* @__PURE__ */ new Date(dateStr + "T00:00:00")).toLocaleDateString("en-US", { month: "short", day: "numeric" });
3120
3120
  }
3121
3121
 
3122
+ // src/activity.ts
3123
+ import { open as open3, readdir as readdir7 } from "node:fs/promises";
3124
+ import { createInterface as createInterface3 } from "node:readline";
3125
+ import { homedir as homedir15 } from "node:os";
3126
+ import { basename as basename9, join as join15 } from "node:path";
3127
+ var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
3128
+ async function buildActivityReport(range, options = {}) {
3129
+ let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
3130
+ scanCodexActivity(targetDates, options),
3131
+ scanClaudeActivity(targetDates, options)
3132
+ ]), items = [...codex.items, ...claude.items].sort(sortActivityItems), requestedDates = options.dates?.slice().sort(), itemDates = [...new Set(items.map((item) => item.usageDate))].sort(), reportDates = requestedDates ?? itemDates, daily = reportDates.map((usageDate) => {
3133
+ let dayItems = items.filter((item) => item.usageDate === usageDate);
3134
+ return {
3135
+ usageDate,
3136
+ exactCount: sumByConfidence(dayItems, "exact"),
3137
+ proxyCount: sumByConfidence(dayItems, "proxy")
3138
+ };
3139
+ }).filter((day) => requestedDates || day.exactCount > 0 || day.proxyCount > 0);
3140
+ return {
3141
+ range,
3142
+ rangeLabel: getRangeLabel3(range),
3143
+ startDate: reportDates[0],
3144
+ endDate: reportDates[reportDates.length - 1],
3145
+ requestedDays: reportDates.length,
3146
+ daysWithData: daily.filter((day) => day.exactCount > 0 || day.proxyCount > 0).length,
3147
+ totals: {
3148
+ exactCount: sumByConfidence(items, "exact"),
3149
+ proxyCount: sumByConfidence(items, "proxy"),
3150
+ userMessageCount: codex.stats.userMessages.size + claude.stats.userMessages.size,
3151
+ filesScanned: codex.stats.filesScanned + claude.stats.filesScanned,
3152
+ sessionsScanned: (/* @__PURE__ */ new Set([...codex.stats.sessions, ...claude.stats.sessions])).size
3153
+ },
3154
+ daily,
3155
+ bySource: summarize(items, (item) => item.source, (item) => item.source),
3156
+ byKind: summarize(items, (item) => item.kind, (item) => labelKind(item.kind)),
3157
+ topTools: summarize(
3158
+ items.filter((item) => isToolLikeKind(item.kind)),
3159
+ (item) => `${item.source}|${item.name}`,
3160
+ (item) => `${item.name} (${item.source})`,
3161
+ 12
3162
+ ),
3163
+ topSkills: summarize(
3164
+ items.filter((item) => item.kind === "skill_call" || item.kind === "skill_proxy"),
3165
+ (item) => `${item.source}|${item.name}|${item.confidence}`,
3166
+ (item) => `${item.name} (${item.confidence === "proxy" ? "proxy" : item.source})`,
3167
+ 12
3168
+ ),
3169
+ topAgents: summarize(
3170
+ items.filter((item) => item.kind === "agent_call"),
3171
+ (item) => `${item.source}|${item.name}`,
3172
+ (item) => `${item.name} (${item.source})`,
3173
+ 12
3174
+ ),
3175
+ items,
3176
+ notes: [
3177
+ "Claude Code \u7684 Skill/Agent \u6765\u81EA\u7ED3\u6784\u5316 tool_use\uFF0C\u53E3\u5F84\u4E3A exact\u3002",
3178
+ "Codex \u7684 skill_proxy \u6765\u81EA\u547D\u4EE4\u4E2D\u8BFB\u53D6 SKILL.md \u7684\u75D5\u8FF9\uFF0C\u53EA\u80FD\u8868\u793A\u4EE3\u7406\u4FE1\u53F7\u3002",
3179
+ "\u8BE5\u62A5\u544A\u53EA\u8BFB\u53D6\u672C\u5730 Session\uFF0C\u4E0D\u53C2\u4E0E sync\uFF0C\u4E5F\u4E0D\u6539\u53D8\u670D\u52A1\u7AEF schema\u3002"
3180
+ ]
3181
+ };
3182
+ }
3183
+ function renderActivityReport(report, opts) {
3184
+ let lines = [], title = opts.emoji ? "\u{1F9ED} AIUsage Activity" : "AIUsage Activity";
3185
+ if (lines.push(title), lines.push("\u2500".repeat(stripAnsi(title).length)), lines.push(`\u5468\u671F ${report.rangeLabel} (${report.startDate ?? "-"} ~ ${report.endDate ?? "-"})`), lines.push(`\u786E\u5207\u4E8B\u4EF6 ${fmt(report.totals.exactCount)}`), lines.push(`\u4EE3\u7406\u4FE1\u53F7 ${fmt(report.totals.proxyCount)}`), lines.push(`\u7528\u6237\u6D88\u606F ${fmt(report.totals.userMessageCount)}`), lines.push(`Session ${fmt(report.totals.sessionsScanned)}`), lines.push(`\u6587\u4EF6 ${fmt(report.totals.filesScanned)}`), report.daysWithData === 0)
3186
+ return lines.push(""), lines.push("\u8BE5\u8303\u56F4\u65E0\u6D3B\u52A8\u6570\u636E\u3002"), lines.join(`
3187
+ `);
3188
+ lines.push(""), lines.push("\u6309\u6765\u6E90");
3189
+ for (let row of report.bySource)
3190
+ lines.push(` ${row.label}: ${formatSummaryCount(row)}`);
3191
+ lines.push(""), lines.push("\u6309\u7C7B\u578B");
3192
+ for (let row of report.byKind)
3193
+ lines.push(` ${row.label}: ${formatSummaryCount(row)}`);
3194
+ if (report.topTools.length > 0) {
3195
+ lines.push(""), lines.push("Top \u5DE5\u5177");
3196
+ for (let row of report.topTools)
3197
+ lines.push(` ${row.label}: ${fmt(row.count)}`);
3198
+ }
3199
+ if (report.topSkills.length > 0) {
3200
+ lines.push(""), lines.push("Top Skill");
3201
+ for (let row of report.topSkills)
3202
+ lines.push(` ${row.label}: ${formatSummaryCount(row)}`);
3203
+ }
3204
+ if (report.topAgents.length > 0) {
3205
+ lines.push(""), lines.push("Top Subagent");
3206
+ for (let row of report.topAgents)
3207
+ lines.push(` ${row.label}: ${fmt(row.count)}`);
3208
+ }
3209
+ if (opts.detail && report.daily.length > 0) {
3210
+ lines.push(""), lines.push("\u6BCF\u65E5");
3211
+ for (let day of report.daily)
3212
+ lines.push(` ${day.usageDate}: exact ${fmt(day.exactCount)} / proxy ${fmt(day.proxyCount)}`);
3213
+ }
3214
+ if (opts.detail) {
3215
+ lines.push(""), lines.push("\u53E3\u5F84");
3216
+ for (let note of report.notes) lines.push(` - ${note}`);
3217
+ }
3218
+ return lines.join(`
3219
+ `);
3220
+ }
3221
+ async function scanCodexActivity(targetDates, options) {
3222
+ let baseDir = options.codexDir ?? join15(homedir15(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
3223
+ return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
3224
+ await processCodexFile2(filePath, acc);
3225
+ }), finalizeActivity(acc);
3226
+ }
3227
+ async function processCodexFile2(filePath, acc) {
3228
+ let fh;
3229
+ try {
3230
+ fh = await open3(filePath, "r");
3231
+ } catch {
3232
+ return;
3233
+ }
3234
+ let sessionId = basename9(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
3235
+ try {
3236
+ let rl = createInterface3({
3237
+ input: fh.createReadStream({ encoding: "utf-8" }),
3238
+ crlfDelay: 1 / 0
3239
+ });
3240
+ for await (let line of rl) {
3241
+ if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES3) continue;
3242
+ let record;
3243
+ try {
3244
+ record = JSON.parse(line);
3245
+ } catch {
3246
+ continue;
3247
+ }
3248
+ if (record.type === "session_meta") {
3249
+ let id = stringValue(record.payload?.id);
3250
+ id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
3251
+ continue;
3252
+ }
3253
+ if (record.type === "turn_context") {
3254
+ let cwd = stringValue(record.payload?.cwd);
3255
+ cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
3256
+ continue;
3257
+ }
3258
+ let ts = parseTs(record.timestamp);
3259
+ if (!ts) continue;
3260
+ let usageDate = dateKey(ts);
3261
+ if (acceptsDate(acc, usageDate)) {
3262
+ if (record.type === "response_item") {
3263
+ handleCodexResponseItem(record.payload?.item ?? record.payload, usageDate, projectFields, sessionId, filePath, record.timestamp ?? "", acc);
3264
+ continue;
3265
+ }
3266
+ record.type === "event_msg" && handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc);
3267
+ }
3268
+ }
3269
+ } finally {
3270
+ await fh.close();
3271
+ }
3272
+ }
3273
+ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, filePath, timestamp, acc) {
3274
+ if (!item?.type) return;
3275
+ let callId = item.call_id, baseKey = callId ? `codex:${item.type}:${callId}` : `codex:${filePath}:${usageDate}:${item.type}:${item.name ?? ""}:${item.arguments ?? ""}`;
3276
+ if (item.type === "message") {
3277
+ item.role === "user" && hasCodexUserMessageContent(item.content) && addUserMessage(acc, {
3278
+ provider: "openai",
3279
+ product: "codex",
3280
+ sessionId,
3281
+ timestamp,
3282
+ content: extractCodexMessageText(item.content),
3283
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:${JSON.stringify(item.content ?? "")}`
3284
+ });
3285
+ return;
3286
+ }
3287
+ if (item.type === "function_call") {
3288
+ let name = item.name ?? "unknown", args = parseJsonObject(item.arguments), kind = name === "spawn_agent" ? "agent_call" : "function_call";
3289
+ addActivity(acc, {
3290
+ usageDate,
3291
+ provider: "openai",
3292
+ product: "codex",
3293
+ projectFields,
3294
+ sessionId,
3295
+ kind,
3296
+ name: kind === "agent_call" ? stringValue(args.agent_type) ?? name : name,
3297
+ confidence: "exact",
3298
+ dedupeKey: baseKey
3299
+ });
3300
+ for (let skillName of extractSkillProxyNames(item.arguments))
3301
+ addActivity(acc, {
3302
+ usageDate,
3303
+ provider: "openai",
3304
+ product: "codex",
3305
+ projectFields,
3306
+ sessionId,
3307
+ kind: "skill_proxy",
3308
+ name: skillName,
3309
+ confidence: "proxy",
3310
+ dedupeKey: `${baseKey}:skill:${skillName}`
3311
+ });
3312
+ return;
3313
+ }
3314
+ if (item.type === "custom_tool_call") {
3315
+ addActivity(acc, {
3316
+ usageDate,
3317
+ provider: "openai",
3318
+ product: "codex",
3319
+ projectFields,
3320
+ sessionId,
3321
+ kind: "custom_tool_call",
3322
+ name: item.name ?? "unknown",
3323
+ confidence: "exact",
3324
+ dedupeKey: baseKey
3325
+ });
3326
+ return;
3327
+ }
3328
+ (item.type === "web_search_call" || item.type === "tool_search_call" || item.type === "image_generation_call") && addActivity(acc, {
3329
+ usageDate,
3330
+ provider: "openai",
3331
+ product: "codex",
3332
+ projectFields,
3333
+ sessionId,
3334
+ kind: item.type === "web_search_call" ? "web_search" : item.type === "tool_search_call" ? "tool_search" : "image_generation",
3335
+ name: item.name ?? item.type,
3336
+ confidence: "exact",
3337
+ dedupeKey: baseKey
3338
+ });
3339
+ }
3340
+ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc) {
3341
+ let payloadType = record.payload?.type;
3342
+ if (payloadType === "user_message") {
3343
+ addUserMessage(acc, {
3344
+ provider: "openai",
3345
+ product: "codex",
3346
+ sessionId,
3347
+ timestamp: record.timestamp ?? "",
3348
+ content: stringValue(record.payload?.message),
3349
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
3350
+ });
3351
+ return;
3352
+ }
3353
+ let kind = payloadType === "task_started" || payloadType === "task_complete" ? "task" : payloadType === "context_compacted" ? "compaction" : payloadType === "thread_rolled_back" ? "rollback" : payloadType === "turn_aborted" ? "interruption" : payloadType === "mcp_tool_call_end" ? "mcp_tool_call" : void 0;
3354
+ if (!kind) return;
3355
+ let callId = stringValue(record.payload?.call_id);
3356
+ addActivity(acc, {
3357
+ usageDate,
3358
+ provider: "openai",
3359
+ product: "codex",
3360
+ projectFields,
3361
+ sessionId,
3362
+ kind,
3363
+ name: payloadType ?? kind,
3364
+ confidence: "exact",
3365
+ dedupeKey: callId ? `codex:event:${callId}:${payloadType}` : `codex:event:${filePath}:${usageDate}:${sessionId}:${payloadType}:${record.timestamp ?? ""}`
3366
+ });
3367
+ }
3368
+ async function scanClaudeActivity(targetDates, options) {
3369
+ let acc = createAccumulator(targetDates, options.projectAliases), fileJobs = [];
3370
+ for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
3371
+ let projectDirs;
3372
+ try {
3373
+ projectDirs = await readdir7(baseDir, { withFileTypes: !0 });
3374
+ } catch {
3375
+ continue;
3376
+ }
3377
+ for (let entry of projectDirs) {
3378
+ if (!entry.isDirectory()) continue;
3379
+ let projectPath = join15(baseDir, entry.name), jsonlFiles = [];
3380
+ await walkJsonl(projectPath, jsonlFiles);
3381
+ let fields = resolveClaudeProject(projectPath, acc.projectAliases);
3382
+ for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
3383
+ }
3384
+ }
3385
+ return acc.stats.filesScanned = fileJobs.length, await runWithConcurrency(fileJobs, FILE_CONCURRENCY3, async (job) => {
3386
+ await processClaudeFile(job.filePath, job.projectFields, acc);
3387
+ }), finalizeActivity(acc);
3388
+ }
3389
+ async function processClaudeFile(filePath, fallbackFields, acc) {
3390
+ let fh;
3391
+ try {
3392
+ fh = await open3(filePath, "r");
3393
+ } catch {
3394
+ return;
3395
+ }
3396
+ let fallbackSessionId = basename9(filePath).replace(/\.jsonl$/, "");
3397
+ try {
3398
+ let rl = createInterface3({
3399
+ input: fh.createReadStream({ encoding: "utf-8" }),
3400
+ crlfDelay: 1 / 0
3401
+ });
3402
+ for await (let line of rl) {
3403
+ if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES3) continue;
3404
+ let record;
3405
+ try {
3406
+ record = JSON.parse(line);
3407
+ } catch {
3408
+ continue;
3409
+ }
3410
+ let ts = parseTs(record.timestamp);
3411
+ if (!ts) continue;
3412
+ let usageDate = dateKey(ts);
3413
+ if (!acceptsDate(acc, usageDate)) continue;
3414
+ let sessionId = record.sessionId ?? fallbackSessionId;
3415
+ acc.stats.sessions.add(`claude:${sessionId}`);
3416
+ let projectFields = record.cwd ? resolveProjectFields(record.cwd, acc.projectAliases) : fallbackFields;
3417
+ isClaudeUserMessage(record) && addUserMessage(acc, {
3418
+ provider: "anthropic",
3419
+ product: "claude-code",
3420
+ sessionId,
3421
+ timestamp: record.timestamp ?? "",
3422
+ content: extractClaudeMessageText(record.message?.content),
3423
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:user:${record.timestamp ?? ""}`,
3424
+ id: record.uuid
3425
+ });
3426
+ let blocks = Array.isArray(record.message?.content) ? record.message.content : [];
3427
+ for (let block of blocks) {
3428
+ if (block?.type !== "tool_use") continue;
3429
+ let name = block.name ?? "unknown", kind = classifyClaudeTool(name), metricName = getClaudeMetricName(name, block.input), dedupeKey = block.id ? `claude:tool:${block.id}` : `claude:tool:${filePath}:${usageDate}:${sessionId}:${name}:${JSON.stringify(block.input ?? {})}`;
3430
+ addActivity(acc, {
3431
+ usageDate,
3432
+ provider: "anthropic",
3433
+ product: "claude-code",
3434
+ projectFields,
3435
+ sessionId,
3436
+ kind,
3437
+ name: metricName,
3438
+ confidence: "exact",
3439
+ dedupeKey
3440
+ });
3441
+ }
3442
+ }
3443
+ } finally {
3444
+ await fh.close();
3445
+ }
3446
+ }
3447
+ function createAccumulator(targetDates, projectAliases) {
3448
+ return {
3449
+ targetDates,
3450
+ projectAliases,
3451
+ items: /* @__PURE__ */ new Map(),
3452
+ seen: /* @__PURE__ */ new Set(),
3453
+ stats: {
3454
+ filesScanned: 0,
3455
+ sessions: /* @__PURE__ */ new Set(),
3456
+ userMessages: /* @__PURE__ */ new Set()
3457
+ }
3458
+ };
3459
+ }
3460
+ function finalizeActivity(acc) {
3461
+ return {
3462
+ items: [...acc.items.values()],
3463
+ stats: acc.stats
3464
+ };
3465
+ }
3466
+ function addActivity(acc, input) {
3467
+ if (acc.seen.has(input.dedupeKey)) return;
3468
+ acc.seen.add(input.dedupeKey);
3469
+ let source = `${input.provider}/${input.product}`, key = [
3470
+ input.usageDate,
3471
+ source,
3472
+ input.projectFields.project,
3473
+ input.kind,
3474
+ input.name,
3475
+ input.confidence
3476
+ ].join("|"), existing = acc.items.get(key);
3477
+ if (existing) {
3478
+ existing.count += 1;
3479
+ return;
3480
+ }
3481
+ acc.items.set(key, {
3482
+ usageDate: input.usageDate,
3483
+ provider: input.provider,
3484
+ product: input.product,
3485
+ source,
3486
+ project: input.projectFields.project,
3487
+ projectDisplay: input.projectFields.projectDisplay,
3488
+ projectAlias: input.projectFields.projectAlias,
3489
+ kind: input.kind,
3490
+ name: input.name,
3491
+ count: 1,
3492
+ confidence: input.confidence
3493
+ });
3494
+ }
3495
+ function addUserMessage(acc, input) {
3496
+ let source = `${input.provider}/${input.product}`, normalized = normalizeMessageText(input.content), key = input.id ? `${source}:user_message:${input.id}` : normalized ? `${source}:user_message:${input.sessionId}:${input.timestamp}:${normalized}` : `${source}:user_message:${input.fallbackKey}`;
3497
+ acc.stats.userMessages.add(key);
3498
+ }
3499
+ function acceptsDate(acc, usageDate) {
3500
+ return !acc.targetDates || acc.targetDates.has(usageDate);
3501
+ }
3502
+ async function collectCodexSessionFiles2(baseDir) {
3503
+ let paths = [];
3504
+ try {
3505
+ let files = await readdir7(join15(baseDir, "archived_sessions"));
3506
+ for (let file of files)
3507
+ file.endsWith(".jsonl") && paths.push(join15(baseDir, "archived_sessions", file));
3508
+ } catch {
3509
+ }
3510
+ return await walkJsonl(join15(baseDir, "sessions"), paths), paths;
3511
+ }
3512
+ function getClaudeProjectDirs2(configured) {
3513
+ if (configured?.length) return configured;
3514
+ let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
3515
+ if (envVar)
3516
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join15(p, "projects"));
3517
+ let home = homedir15();
3518
+ return [
3519
+ join15(home, ".config", "claude", "projects"),
3520
+ join15(home, ".claude", "projects")
3521
+ ];
3522
+ }
3523
+ async function walkJsonl(dir, result) {
3524
+ let entries;
3525
+ try {
3526
+ entries = await readdir7(dir, { withFileTypes: !0 });
3527
+ } catch {
3528
+ return;
3529
+ }
3530
+ for (let entry of entries) {
3531
+ let fullPath = join15(dir, entry.name);
3532
+ entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
3533
+ }
3534
+ }
3535
+ function resolveClaudeProject(projectPath, aliases2) {
3536
+ let rawName = basename9(projectPath), display = rawName.split("-").filter(Boolean).at(-1) || rawName || "unknown", alias = aliases2?.[projectPath] ?? aliases2?.[display];
3537
+ return {
3538
+ project: projectPath,
3539
+ projectDisplay: display,
3540
+ projectAlias: alias
3541
+ };
3542
+ }
3543
+ function classifyClaudeTool(name) {
3544
+ return name === "Skill" ? "skill_call" : name === "Agent" ? "agent_call" : name === "WebSearch" || name === "WebFetch" ? "web_search" : name === "ToolSearch" ? "tool_search" : name === "TaskCreate" || name === "TaskUpdate" || name === "TaskList" || name === "TaskStop" ? "task" : "tool_call";
3545
+ }
3546
+ function getClaudeMetricName(toolName, input) {
3547
+ return toolName === "Skill" ? stringValue(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue(input?.description) ?? stringValue(input?.subagent_type) ?? "unknown" : toolName;
3548
+ }
3549
+ function isClaudeUserMessage(record) {
3550
+ if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
3551
+ let content = record.message.content;
3552
+ return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" && stringValue(block.text));
3553
+ }
3554
+ function hasCodexUserMessageContent(content) {
3555
+ return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 ? !1 : content.some((block) => block?.type === "input_text" || block?.type === "text");
3556
+ }
3557
+ function extractCodexMessageText(content) {
3558
+ return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue(block.text)).filter(Boolean).join(`
3559
+ `) || void 0;
3560
+ }
3561
+ function extractClaudeMessageText(content) {
3562
+ return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue(block.text)).filter(Boolean).join(`
3563
+ `) || void 0;
3564
+ }
3565
+ function normalizeMessageText(value) {
3566
+ return value?.replace(/\s+/g, " ").trim() || void 0;
3567
+ }
3568
+ function extractSkillProxyNames(rawArguments) {
3569
+ if (!rawArguments) return [];
3570
+ let args = parseJsonObject(rawArguments), command2 = stringValue(args.cmd) ?? stringValue(args.command) ?? "";
3571
+ if (!command2.includes("SKILL.md")) return [];
3572
+ let names = /* @__PURE__ */ new Set();
3573
+ for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
3574
+ names.add(skillNameFromPath(match[1]));
3575
+ return [...names];
3576
+ }
3577
+ function parseJsonObject(raw) {
3578
+ if (!raw) return {};
3579
+ try {
3580
+ let parsed = JSON.parse(raw);
3581
+ return parsed && typeof parsed == "object" && !Array.isArray(parsed) ? parsed : {};
3582
+ } catch {
3583
+ return {};
3584
+ }
3585
+ }
3586
+ function skillNameFromPath(rawPath) {
3587
+ let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
3588
+ return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
3589
+ }
3590
+ function stringValue(value) {
3591
+ return typeof value == "string" && value.length > 0 ? value : void 0;
3592
+ }
3593
+ function summarize(items, keyFn, labelFn, limit) {
3594
+ let grouped = /* @__PURE__ */ new Map();
3595
+ for (let item of items) {
3596
+ let key = keyFn(item), existing = grouped.get(key);
3597
+ if (existing) {
3598
+ existing.count += item.count, item.confidence === "exact" ? existing.exactCount += item.count : existing.proxyCount += item.count;
3599
+ continue;
3600
+ }
3601
+ grouped.set(key, {
3602
+ key,
3603
+ label: labelFn(item),
3604
+ count: item.count,
3605
+ exactCount: item.confidence === "exact" ? item.count : 0,
3606
+ proxyCount: item.confidence === "proxy" ? item.count : 0
3607
+ });
3608
+ }
3609
+ let rows = [...grouped.values()].sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
3610
+ return limit ? rows.slice(0, limit) : rows;
3611
+ }
3612
+ function sumByConfidence(items, confidence) {
3613
+ return items.reduce((sum, item) => sum + (item.confidence === confidence ? item.count : 0), 0);
3614
+ }
3615
+ function isToolLikeKind(kind) {
3616
+ return kind === "function_call" || kind === "custom_tool_call" || kind === "tool_call" || kind === "web_search" || kind === "tool_search" || kind === "image_generation" || kind === "mcp_tool_call";
3617
+ }
3618
+ function labelKind(kind) {
3619
+ switch (kind) {
3620
+ case "function_call":
3621
+ return "Function Call";
3622
+ case "custom_tool_call":
3623
+ return "Custom Tool Call";
3624
+ case "tool_call":
3625
+ return "Tool Call";
3626
+ case "skill_call":
3627
+ return "Skill";
3628
+ case "skill_proxy":
3629
+ return "Skill Proxy";
3630
+ case "agent_call":
3631
+ return "Subagent";
3632
+ case "web_search":
3633
+ return "Web Search";
3634
+ case "tool_search":
3635
+ return "Tool Search";
3636
+ case "image_generation":
3637
+ return "Image Generation";
3638
+ case "task":
3639
+ return "Task";
3640
+ case "compaction":
3641
+ return "Context Compaction";
3642
+ case "rollback":
3643
+ return "Rollback";
3644
+ case "interruption":
3645
+ return "Interruption";
3646
+ case "mcp_tool_call":
3647
+ return "MCP Tool";
3648
+ }
3649
+ }
3650
+ function getRangeLabel3(range) {
3651
+ switch (range) {
3652
+ case "7d":
3653
+ return "\u6700\u8FD1 7 \u5929";
3654
+ case "1m":
3655
+ return "\u6700\u8FD1 30 \u5929";
3656
+ case "3m":
3657
+ return "\u6700\u8FD1 90 \u5929";
3658
+ case "all":
3659
+ return "\u5168\u90E8\u5386\u53F2";
3660
+ case "today":
3661
+ return "\u4ECA\u5929";
3662
+ }
3663
+ }
3664
+ function sortActivityItems(a, b) {
3665
+ return a.usageDate.localeCompare(b.usageDate) || a.source.localeCompare(b.source) || a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name);
3666
+ }
3667
+ function formatSummaryCount(row) {
3668
+ return row.proxyCount === 0 ? fmt(row.exactCount) : row.exactCount === 0 ? `${fmt(row.proxyCount)} proxy` : `${fmt(row.exactCount)} exact / ${fmt(row.proxyCount)} proxy`;
3669
+ }
3670
+ function fmt(n) {
3671
+ return n.toLocaleString("en-US");
3672
+ }
3673
+ function stripAnsi(s) {
3674
+ return s.replace(/\x1b\[[0-9;]*m/g, "");
3675
+ }
3676
+
3122
3677
  // src/config.ts
3123
3678
  import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
3124
- import { homedir as homedir15, hostname } from "node:os";
3125
- import { basename as basename9, join as join15 } from "node:path";
3126
- var CONFIG_DIR = join15(homedir15(), ".aiusage"), CONFIG_PATH = join15(CONFIG_DIR, "config.json");
3679
+ import { homedir as homedir16, hostname } from "node:os";
3680
+ import { basename as basename10, join as join16 } from "node:path";
3681
+ var CONFIG_DIR = join16(homedir16(), ".aiusage"), CONFIG_PATH = join16(CONFIG_DIR, "config.json");
3127
3682
  function getConfigPath() {
3128
3683
  return CONFIG_PATH;
3129
3684
  }
@@ -3340,9 +3895,9 @@ async function requestJson(url, init) {
3340
3895
  import { mkdir as mkdir2, readFile as readFile16, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
3341
3896
  import { execFile } from "node:child_process";
3342
3897
  import { promisify } from "node:util";
3343
- import { homedir as homedir16, platform, tmpdir as tmpdir2 } from "node:os";
3344
- import { join as join16, resolve as resolve3 } from "node:path";
3345
- var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join16(homedir16(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join16(homedir16(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
3898
+ import { homedir as homedir17, platform, tmpdir as tmpdir2 } from "node:os";
3899
+ import { join as join17, resolve as resolve3 } from "node:path";
3900
+ var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join17(homedir17(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join17(homedir17(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
3346
3901
  function parseInterval(value) {
3347
3902
  let match = value.match(/^(\d+)(m|h|d)$/);
3348
3903
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -3387,7 +3942,7 @@ function resolveCommandPaths() {
3387
3942
  }
3388
3943
  async function enableLaunchd(intervalSeconds) {
3389
3944
  let { nodePath, scriptPath } = resolveCommandPaths();
3390
- await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
3945
+ await mkdir2(join17(homedir17(), ".aiusage"), { recursive: !0 });
3391
3946
  let plist = [
3392
3947
  '<?xml version="1.0" encoding="UTF-8"?>',
3393
3948
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -3456,8 +4011,8 @@ async function getLaunchdStatus() {
3456
4011
  }
3457
4012
  }
3458
4013
  async function enableCron(intervalSeconds) {
3459
- let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join16(homedir16(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
3460
- await mkdir2(join16(homedir16(), ".aiusage"), { recursive: !0 });
4014
+ let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join17(homedir17(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
4015
+ await mkdir2(join17(homedir17(), ".aiusage"), { recursive: !0 });
3461
4016
  let existing = "";
3462
4017
  try {
3463
4018
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -3515,7 +4070,7 @@ async function getCronStatus() {
3515
4070
  }
3516
4071
  }
3517
4072
  async function writeCrontab(content) {
3518
- let tmpFile = join16(tmpdir2(), `aiusage-cron-${Date.now()}`);
4073
+ let tmpFile = join17(tmpdir2(), `aiusage-cron-${Date.now()}`);
3519
4074
  await writeFile2(tmpFile, content, "utf-8");
3520
4075
  try {
3521
4076
  await execFileAsync("crontab", [tmpFile]);
@@ -3546,9 +4101,9 @@ function escapeXml(value) {
3546
4101
  }
3547
4102
 
3548
4103
  // src/doctor.ts
3549
- import { readdir as readdir7, stat as stat2 } from "node:fs/promises";
3550
- import { homedir as homedir17 } from "node:os";
3551
- import { join as join17 } from "node:path";
4104
+ import { readdir as readdir8, stat as stat2 } from "node:fs/promises";
4105
+ import { homedir as homedir18 } from "node:os";
4106
+ import { join as join18 } from "node:path";
3552
4107
  var msgs = {
3553
4108
  en: {
3554
4109
  groupConfig: "Configuration",
@@ -3604,13 +4159,13 @@ async function countFiles(dir, exts, cap = 1e3) {
3604
4159
  for (; queue.length > 0 && count < cap; ) {
3605
4160
  let current = queue.pop(), entries;
3606
4161
  try {
3607
- entries = await readdir7(current, { withFileTypes: !0 });
4162
+ entries = await readdir8(current, { withFileTypes: !0 });
3608
4163
  } catch {
3609
4164
  continue;
3610
4165
  }
3611
4166
  for (let e of entries) {
3612
4167
  if (count >= cap) break;
3613
- let full = join17(current, e.name);
4168
+ let full = join18(current, e.name);
3614
4169
  e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
3615
4170
  }
3616
4171
  }
@@ -3639,20 +4194,20 @@ async function runDoctor(lang = "zh") {
3639
4194
  }
3640
4195
  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 });
3641
4196
  }
3642
- let g3 = s.groupTools, home = homedir17(), tools = [
3643
- { dir: join17(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
3644
- { dir: join17(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
3645
- { dir: join17(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
3646
- { dir: join17(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
3647
- { dir: join17(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
3648
- { dir: join17(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
3649
- { dir: join17(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
3650
- { dir: join17(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
3651
- { dir: join17(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
3652
- { dir: join17(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
3653
- { dir: join17(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
3654
- { dir: join17(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
3655
- { dir: join17(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
4197
+ let g3 = s.groupTools, home = homedir18(), tools = [
4198
+ { dir: join18(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
4199
+ { dir: join18(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
4200
+ { dir: join18(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
4201
+ { dir: join18(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
4202
+ { dir: join18(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
4203
+ { dir: join18(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
4204
+ { dir: join18(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
4205
+ { dir: join18(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
4206
+ { dir: join18(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
4207
+ { dir: join18(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
4208
+ { dir: join18(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
4209
+ { dir: join18(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
4210
+ { dir: join18(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
3656
4211
  ];
3657
4212
  for (let tool of tools) {
3658
4213
  try {
@@ -3674,9 +4229,9 @@ async function runDoctor(lang = "zh") {
3674
4229
  }
3675
4230
 
3676
4231
  // src/project.ts
3677
- import { open as open3, readdir as readdir8, readFile as readFile17 } from "node:fs/promises";
3678
- import { basename as basename10, join as join18 } from "node:path";
3679
- import { homedir as homedir18 } from "node:os";
4232
+ import { open as open4, readdir as readdir9, readFile as readFile17 } from "node:fs/promises";
4233
+ import { basename as basename11, join as join19 } from "node:path";
4234
+ import { homedir as homedir19 } from "node:os";
3680
4235
  async function discoverProjects(projectAliases) {
3681
4236
  let projectMap = /* @__PURE__ */ new Map();
3682
4237
  function add(name, source) {
@@ -3720,20 +4275,20 @@ async function discoverClaudeProjects() {
3720
4275
  for (let baseDir of getClaudeDirs()) {
3721
4276
  let entries;
3722
4277
  try {
3723
- entries = await readdir8(baseDir, { withFileTypes: !0 });
4278
+ entries = await readdir9(baseDir, { withFileTypes: !0 });
3724
4279
  } catch {
3725
4280
  continue;
3726
4281
  }
3727
4282
  for (let entry of entries) {
3728
4283
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
3729
- let projectDir = join18(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
4284
+ let projectDir = join19(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
3730
4285
  name && name !== "unknown" && names.push(name);
3731
4286
  }
3732
4287
  }
3733
4288
  return names;
3734
4289
  }
3735
4290
  async function discoverCodexProjects() {
3736
- let sessionsDir = join18(homedir18(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
4291
+ let sessionsDir = join19(homedir19(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
3737
4292
  for (let filePath of files) {
3738
4293
  let name = await extractCwdFromSessionMeta(filePath);
3739
4294
  name && name !== "unknown" && projects.add(name);
@@ -3743,7 +4298,7 @@ async function discoverCodexProjects() {
3743
4298
  async function extractCwdFromSessionMeta(filePath) {
3744
4299
  let fh;
3745
4300
  try {
3746
- fh = await open3(filePath, "r");
4301
+ fh = await open4(filePath, "r");
3747
4302
  let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
3748
4303
  if (bytesRead === 0) return;
3749
4304
  let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -3765,12 +4320,12 @@ async function walkFiles2(dir, ext) {
3765
4320
  async function walk2(d) {
3766
4321
  let entries;
3767
4322
  try {
3768
- entries = await readdir8(d, { withFileTypes: !0 });
4323
+ entries = await readdir9(d, { withFileTypes: !0 });
3769
4324
  } catch {
3770
4325
  return;
3771
4326
  }
3772
4327
  for (let entry of entries) {
3773
- let full = join18(d, entry.name);
4328
+ let full = join19(d, entry.name);
3774
4329
  entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
3775
4330
  }
3776
4331
  }
@@ -3781,7 +4336,7 @@ async function extractCwdFromFirstJsonl(dir) {
3781
4336
  if (!jsonlPath) return;
3782
4337
  let fh;
3783
4338
  try {
3784
- fh = await open3(jsonlPath, "r");
4339
+ fh = await open4(jsonlPath, "r");
3785
4340
  let buf = Buffer.alloc(32 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
3786
4341
  if (bytesRead === 0) return;
3787
4342
  let lines = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -3807,27 +4362,27 @@ async function extractCwdFromFirstJsonl(dir) {
3807
4362
  async function findFirstJsonl(dir) {
3808
4363
  let entries;
3809
4364
  try {
3810
- entries = await readdir8(dir, { withFileTypes: !0 });
4365
+ entries = await readdir9(dir, { withFileTypes: !0 });
3811
4366
  } catch {
3812
4367
  return;
3813
4368
  }
3814
4369
  let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
3815
- if (topJsonl) return join18(dir, topJsonl.name);
4370
+ if (topJsonl) return join19(dir, topJsonl.name);
3816
4371
  for (let entry of entries)
3817
4372
  if (!(!entry.isDirectory() || entry.name.startsWith(".")))
3818
4373
  try {
3819
- let sub = (await readdir8(join18(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
3820
- if (sub) return join18(dir, entry.name, sub);
4374
+ let sub = (await readdir9(join19(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
4375
+ if (sub) return join19(dir, entry.name, sub);
3821
4376
  } catch {
3822
4377
  continue;
3823
4378
  }
3824
4379
  }
3825
4380
  async function discoverCopilotProjects() {
3826
- let dir = join18(homedir18(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
4381
+ let dir = join19(homedir19(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
3827
4382
  for (let filePath of files) {
3828
4383
  let fh;
3829
4384
  try {
3830
- fh = await open3(filePath, "r");
4385
+ fh = await open4(filePath, "r");
3831
4386
  let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
3832
4387
  if (bytesRead === 0) continue;
3833
4388
  let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -3845,7 +4400,7 @@ async function discoverCopilotProjects() {
3845
4400
  return [...projects];
3846
4401
  }
3847
4402
  async function discoverGeminiProjects() {
3848
- let filePath = join18(homedir18(), ".gemini", "projects.json");
4403
+ let filePath = join19(homedir19(), ".gemini", "projects.json");
3849
4404
  try {
3850
4405
  let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
3851
4406
  if (!projects || typeof projects != "object") return [];
@@ -3860,7 +4415,7 @@ async function discoverGeminiProjects() {
3860
4415
  }
3861
4416
  }
3862
4417
  async function discoverCursorProjects() {
3863
- let storagePath = join18(homedir18(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
4418
+ let storagePath = join19(homedir19(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
3864
4419
  try {
3865
4420
  let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
3866
4421
  for (let uri of workspaceUris) {
@@ -3877,7 +4432,7 @@ async function discoverCursorProjects() {
3877
4432
  }
3878
4433
  }
3879
4434
  async function discoverCopilotVscodeProjects() {
3880
- let dir = join18(homedir18(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
4435
+ let dir = join19(homedir19(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
3881
4436
  for (let filePath of files) {
3882
4437
  let content;
3883
4438
  try {
@@ -3894,16 +4449,16 @@ async function discoverCopilotVscodeProjects() {
3894
4449
  return [...projects];
3895
4450
  }
3896
4451
  async function discoverAntigravityProjects() {
3897
- let dir = join18(homedir18(), ".gemini", "antigravity", "knowledge"), entries;
4452
+ let dir = join19(homedir19(), ".gemini", "antigravity", "knowledge"), entries;
3898
4453
  try {
3899
- entries = await readdir8(dir, { withFileTypes: !0 });
4454
+ entries = await readdir9(dir, { withFileTypes: !0 });
3900
4455
  } catch {
3901
4456
  return [];
3902
4457
  }
3903
4458
  let projects = /* @__PURE__ */ new Set();
3904
4459
  for (let entry of entries) {
3905
4460
  if (!entry.isDirectory()) continue;
3906
- let metadataPath = join18(dir, entry.name, "metadata.json");
4461
+ let metadataPath = join19(dir, entry.name, "metadata.json");
3907
4462
  try {
3908
4463
  let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
3909
4464
  name && name !== "unknown" && projects.add(name);
@@ -3916,7 +4471,7 @@ async function discoverAntigravityProjects() {
3916
4471
  function nameFromFileUri(raw) {
3917
4472
  let path = pathFromFileUri(raw);
3918
4473
  if (!path) return;
3919
- let name = basename10(path);
4474
+ let name = basename11(path);
3920
4475
  return name && name !== "unknown" ? name : void 0;
3921
4476
  }
3922
4477
  function pathFromFileUri(raw) {
@@ -3935,11 +4490,11 @@ function pathFromFileUri(raw) {
3935
4490
  function getClaudeDirs() {
3936
4491
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
3937
4492
  if (envVar)
3938
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join18(p, "projects"));
3939
- let home = homedir18();
4493
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join19(p, "projects"));
4494
+ let home = homedir19();
3940
4495
  return [
3941
- join18(home, ".config", "claude", "projects"),
3942
- join18(home, ".claude", "projects")
4496
+ join19(home, ".config", "claude", "projects"),
4497
+ join19(home, ".claude", "projects")
3943
4498
  ];
3944
4499
  }
3945
4500
 
@@ -3982,9 +4537,9 @@ function shortHash(p) {
3982
4537
 
3983
4538
  // src/pricing.ts
3984
4539
  import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
3985
- import { homedir as homedir19 } from "node:os";
3986
- import { join as join19 } from "node:path";
3987
- var CACHE_DIR = join19(homedir19(), ".aiusage"), CACHE_PATH = join19(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
4540
+ import { homedir as homedir20 } from "node:os";
4541
+ import { join as join20 } from "node:path";
4542
+ var CACHE_DIR = join20(homedir20(), ".aiusage"), CACHE_PATH = join20(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
3988
4543
  "https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
3989
4544
  "https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
3990
4545
  "https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
@@ -4094,6 +4649,10 @@ await (async () => {
4094
4649
  let parsed = parseArgs(argv.slice(1));
4095
4650
  if (parsed.flags.help) return helpForSubcommand("report");
4096
4651
  await runReport(parsed.flags, parsed.positionals);
4652
+ } else if (command === "activity") {
4653
+ let parsed = parseArgs(argv.slice(1));
4654
+ if (parsed.flags.help) return helpForSubcommand("activity");
4655
+ await runActivity(parsed.flags, parsed.positionals);
4097
4656
  } else if (command === "health") {
4098
4657
  let parsed = parseArgs(argv.slice(1));
4099
4658
  if (parsed.flags.help) return helpForSubcommand("health");
@@ -4212,10 +4771,10 @@ function printScanResult(result, zh2) {
4212
4771
  for (let [provider, breakdowns] of byProvider) {
4213
4772
  console.log(`\u2500\u2500 ${provider} \u2500\u2500`);
4214
4773
  for (let b of breakdowns.sort((a, c) => c.inputTokens - a.inputTokens))
4215
- console.log(` ${b.model} | ${b.projectAlias ?? b.projectDisplay ?? b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt(b.outputTokens)} \u63A8\u7406: ${fmt(b.reasoningOutputTokens)}`);
4774
+ console.log(` ${b.model} | ${b.projectAlias ?? b.projectDisplay ?? b.project}`), console.log(` \u4E8B\u4EF6: ${b.eventCount} \u8F93\u5165: ${fmt2(b.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt2(b.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt2(b.cacheWriteTokens)} \u8F93\u51FA: ${fmt2(b.outputTokens)} \u63A8\u7406: ${fmt2(b.reasoningOutputTokens)}`);
4216
4775
  console.log();
4217
4776
  }
4218
- console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt(result.totals.outputTokens)} \u63A8\u7406: ${fmt(result.totals.reasoningOutputTokens)}`), console.log();
4777
+ console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt2(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt2(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt2(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt2(result.totals.outputTokens)} \u63A8\u7406: ${fmt2(result.totals.reasoningOutputTokens)}`), console.log();
4219
4778
  }
4220
4779
  async function runReport(flags, positionals = []) {
4221
4780
  let config = await readConfig();
@@ -4236,7 +4795,21 @@ async function runReport(flags, positionals = []) {
4236
4795
  let lang = resolveGlobalLang(flags, config), emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
4237
4796
  console.log(renderReport(report, { lang, emoji, detail }));
4238
4797
  }
4239
- function fmt(n) {
4798
+ async function runActivity(flags, positionals = []) {
4799
+ let config = await readConfig();
4800
+ assertNoPositionals("activity", positionals, config.lang === "zh");
4801
+ let { dates, range } = resolveDateParams(flags, config), report = await buildActivityReport(range, {
4802
+ projectAliases: config.projectAliases,
4803
+ dates
4804
+ });
4805
+ if (flags.json) {
4806
+ console.log(JSON.stringify(report, null, 2));
4807
+ return;
4808
+ }
4809
+ let emoji = flags["no-emoji"] === !0 ? !1 : config.emoji ?? !0, detail = flags.detail === !0;
4810
+ console.log(renderActivityReport(report, { emoji, detail }));
4811
+ }
4812
+ function fmt2(n) {
4240
4813
  return n.toLocaleString("en-US");
4241
4814
  }
4242
4815
  async function runHealth(flags) {
@@ -4272,7 +4845,7 @@ async function runEnroll(flags) {
4272
4845
  }, null, 2));
4273
4846
  }
4274
4847
  function prompt(question) {
4275
- let rl = createInterface3({ input: process.stdin, output: process.stdout });
4848
+ let rl = createInterface4({ input: process.stdin, output: process.stdout });
4276
4849
  return new Promise((resolve4) => {
4277
4850
  rl.question(question, (answer) => {
4278
4851
  rl.close(), resolve4(answer.trim());
@@ -4505,6 +5078,7 @@ function printHelp(zh2 = !1) {
4505
5078
  let cmds = zh2 ? [
4506
5079
  ["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
4507
5080
  ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
5081
+ ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
4508
5082
  ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
4509
5083
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
4510
5084
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
@@ -4518,6 +5092,7 @@ function printHelp(zh2 = !1) {
4518
5092
  ] : [
4519
5093
  ["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "Scan usage breakdown"],
4520
5094
  ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
5095
+ ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
4521
5096
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
4522
5097
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
4523
5098
  ["project [list|alias]", "Project management & aliases"],
@@ -4540,6 +5115,7 @@ function printUsageHint(zh2 = !1) {
4540
5115
  let cmds = zh2 ? [
4541
5116
  ["scan [--date YYYY-MM-DD|--range 1m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
4542
5117
  ["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
5118
+ ["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
4543
5119
  ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
4544
5120
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
4545
5121
  ["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
@@ -4549,6 +5125,7 @@ function printUsageHint(zh2 = !1) {
4549
5125
  ] : [
4550
5126
  ["scan [--date YYYY-MM-DD|--range 1m]", "Scan usage breakdown"],
4551
5127
  ["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
5128
+ ["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
4552
5129
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
4553
5130
  ["project [list|alias]", "Project management & aliases"],
4554
5131
  ["pricing [status|update]", "Pricing catalog management"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiusage/cli",
3
- "version": "1.6.4",
3
+ "version": "1.7.0",
4
4
  "description": "Track and sync AI tool token usage across devices.",
5
5
  "license": "MIT",
6
6
  "private": false,