@aiusage/cli 1.7.14 → 1.8.1

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 +189 -110
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -4792,10 +4792,11 @@ function fmtDateShort(dateStr) {
4792
4792
  }
4793
4793
 
4794
4794
  // src/activity.ts
4795
- import { open, readdir as readdir7 } from "node:fs/promises";
4795
+ import { open, readdir as readdir7, stat as stat4 } from "node:fs/promises";
4796
4796
  import { createInterface as createInterface3 } from "node:readline";
4797
4797
  import { homedir as homedir16 } from "node:os";
4798
4798
  import { basename as basename12, join as join17 } from "node:path";
4799
+ import * as zlib from "node:zlib";
4799
4800
  var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
4800
4801
  async function buildActivityReport(range, options = {}) {
4801
4802
  let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
@@ -4807,7 +4808,8 @@ async function buildActivityReport(range, options = {}) {
4807
4808
  usageDate,
4808
4809
  exactCount: sumByConfidence(dayItems, "exact"),
4809
4810
  proxyCount: sumByConfidence(dayItems, "proxy"),
4810
- userMessageCount: sumUserMessages(dayItems)
4811
+ userMessageCount: sumKind(dayItems, "user_message"),
4812
+ userMessageChars: sumKind(dayItems, "user_message_chars")
4811
4813
  };
4812
4814
  }).filter((day) => requestedDates || day.exactCount > 0 || day.proxyCount > 0 || day.userMessageCount > 0);
4813
4815
  return {
@@ -4821,12 +4823,13 @@ async function buildActivityReport(range, options = {}) {
4821
4823
  exactCount: sumByConfidence(items, "exact"),
4822
4824
  proxyCount: sumByConfidence(items, "proxy"),
4823
4825
  userMessageCount: codex.stats.userMessages.size + claude.stats.userMessages.size,
4826
+ userMessageChars: sumKind(items, "user_message_chars"),
4824
4827
  filesScanned: codex.stats.filesScanned + claude.stats.filesScanned,
4825
4828
  sessionsScanned: (/* @__PURE__ */ new Set([...codex.stats.sessions, ...claude.stats.sessions])).size
4826
4829
  },
4827
4830
  daily,
4828
4831
  bySource: summarize(items, (item) => item.source, (item) => item.source),
4829
- byKind: summarize(items, (item) => item.kind, (item) => labelKind(item.kind)),
4832
+ byKind: summarize(items.filter((item) => item.kind !== "user_message_chars"), (item) => item.kind, (item) => labelKind(item.kind)),
4830
4833
  topTools: summarize(
4831
4834
  items.filter((item) => isToolLikeKind(item.kind)),
4832
4835
  (item) => `${item.source}|${item.name}`,
@@ -4849,13 +4852,14 @@ async function buildActivityReport(range, options = {}) {
4849
4852
  notes: [
4850
4853
  "Claude Code \u7684 Skill/Agent \u6765\u81EA\u7ED3\u6784\u5316 tool_use\uFF0C\u53E3\u5F84\u4E3A exact\u3002",
4851
4854
  "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",
4855
+ "\u7528\u6237\u6D88\u606F\u53EA\u8BA1\u4EBA\u5DE5\u8F93\u5165\uFF1A\u5254\u9664\u7CFB\u7EDF\u6CE8\u5165\u3001\u5B50\u4EE3\u7406\u3001\u81EA\u52A8\u5316\u4E0E\u5B9A\u65F6\u4EFB\u52A1\uFF1B\u5B57\u6570\u4E3A\u53BB\u7A7A\u767D\u5B57\u7B26\u6570\uFF0CClaude Code \u4E0D\u542B\u7C98\u8D34\u5757\u3002",
4852
4856
  "sync \u4F1A\u4E0A\u4F20\u6309\u65E5\u805A\u5408\u540E\u7684 activity \u6307\u6807\uFF0C\u4E0D\u4E0A\u4F20\u539F\u59CB\u6D88\u606F\u5185\u5BB9\u3002"
4853
4857
  ]
4854
4858
  };
4855
4859
  }
4856
4860
  function renderActivityReport(report, opts) {
4857
4861
  let lines = [], title = opts.emoji ? "\u{1F9ED} AIUsage Activity" : "AIUsage Activity";
4858
- 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)
4862
+ 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(`\u7528\u6237\u5B57\u6570 ${fmt(report.totals.userMessageChars)}`), lines.push(`Session ${fmt(report.totals.sessionsScanned)}`), lines.push(`\u6587\u4EF6 ${fmt(report.totals.filesScanned)}`), report.daysWithData === 0)
4859
4863
  return lines.push(""), lines.push("\u8BE5\u8303\u56F4\u65E0\u6D3B\u52A8\u6570\u636E\u3002"), lines.join(`
4860
4864
  `);
4861
4865
  lines.push(""), lines.push("\u6309\u6765\u6E90");
@@ -4882,7 +4886,7 @@ function renderActivityReport(report, opts) {
4882
4886
  if (opts.detail && report.daily.length > 0) {
4883
4887
  lines.push(""), lines.push("\u6BCF\u65E5");
4884
4888
  for (let day of report.daily)
4885
- lines.push(` ${day.usageDate}: exact ${fmt(day.exactCount)} / proxy ${fmt(day.proxyCount)} / user ${fmt(day.userMessageCount)}`);
4889
+ lines.push(` ${day.usageDate}: exact ${fmt(day.exactCount)} / proxy ${fmt(day.proxyCount)} / user ${fmt(day.userMessageCount)} (${fmt(day.userMessageChars)} \u5B57)`);
4886
4890
  }
4887
4891
  if (opts.detail) {
4888
4892
  lines.push(""), lines.push("\u53E3\u5F84");
@@ -4892,22 +4896,24 @@ function renderActivityReport(report, opts) {
4892
4896
  `);
4893
4897
  }
4894
4898
  async function scanCodexActivity(targetDates, options) {
4895
- let baseDir = options.codexDir ?? join17(homedir16(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
4899
+ let baseDir = options.codexDir ?? join17(homedir16(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await keepRecentFiles(await collectCodexSessionFiles2(baseDir), targetDates, (path) => path);
4896
4900
  return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
4897
4901
  await processCodexFile2(filePath, acc);
4898
4902
  }), finalizeActivity(acc);
4899
4903
  }
4900
4904
  async function processCodexFile2(filePath, acc) {
4905
+ let compressed = filePath.endsWith(".zst");
4906
+ if (compressed && typeof zlib.createZstdDecompress != "function") return;
4901
4907
  let fh;
4902
4908
  try {
4903
4909
  fh = await open(filePath, "r");
4904
4910
  } catch {
4905
4911
  return;
4906
4912
  }
4907
- let sessionId = basename12(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
4913
+ let sessionId = basename12(filePath).replace(/\.jsonl(\.zst)?$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" }, automated = !1, itemMessages = [], eventMessages = [];
4908
4914
  try {
4909
- let rl = createInterface3({
4910
- input: fh.createReadStream({ encoding: "utf-8" }),
4915
+ let stream = fh.createReadStream(), rl = createInterface3({
4916
+ input: compressed ? stream.pipe(zlib.createZstdDecompress()) : stream.setEncoding("utf-8"),
4911
4917
  crlfDelay: 1 / 0
4912
4918
  });
4913
4919
  for await (let line of rl) {
@@ -4920,7 +4926,7 @@ async function processCodexFile2(filePath, acc) {
4920
4926
  }
4921
4927
  if (record.type === "session_meta") {
4922
4928
  let id = stringValue3(record.payload?.id);
4923
- id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
4929
+ id && (sessionId = id), automated = isAutomatedCodexSession(record.payload), acc.stats.sessions.add(`codex:${sessionId}`);
4924
4930
  continue;
4925
4931
  }
4926
4932
  if (record.type === "turn_context") {
@@ -4936,98 +4942,119 @@ async function processCodexFile2(filePath, acc) {
4936
4942
  handleCodexResponseItem(record.payload?.item ?? record.payload, usageDate, projectFields, sessionId, filePath, record.timestamp ?? "", acc);
4937
4943
  continue;
4938
4944
  }
4939
- record.type === "event_msg" && handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc);
4945
+ if (record.type === "event_msg") {
4946
+ let message = codexUserMessage(record);
4947
+ if (message) {
4948
+ (record.payload?.type === "item_completed" ? itemMessages : eventMessages).push({ ...message, usageDate, projectFields });
4949
+ continue;
4950
+ }
4951
+ handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc);
4952
+ }
4940
4953
  }
4941
4954
  }
4955
+ } catch {
4942
4956
  } finally {
4943
4957
  await fh.close();
4944
4958
  }
4959
+ if (!automated)
4960
+ for (let message of itemMessages.length ? itemMessages : eventMessages) {
4961
+ let text = codexTypedText(message.text);
4962
+ text && addUserMessage(acc, {
4963
+ provider: "openai",
4964
+ product: "codex",
4965
+ usageDate: message.usageDate,
4966
+ projectFields: message.projectFields,
4967
+ sessionId,
4968
+ timestamp: message.timestamp,
4969
+ content: text,
4970
+ chars: countChars(text),
4971
+ fallbackKey: `${filePath}:${message.usageDate}:${sessionId}:user:${message.timestamp}`
4972
+ });
4973
+ }
4974
+ }
4975
+ function codexUserMessage(record) {
4976
+ let payload = record.payload;
4977
+ if (payload?.type === "user_message")
4978
+ return { timestamp: record.timestamp ?? "", text: stringValue3(payload.message) ?? "" };
4979
+ if (payload?.type === "item_completed" && payload.item?.type === "UserMessage")
4980
+ return { timestamp: record.timestamp ?? "", text: extractCodexMessageText(payload.item.content) ?? "" };
4981
+ }
4982
+ function isAutomatedCodexSession(payload) {
4983
+ if (payload?.originator === "codex_exec") return !0;
4984
+ let source = payload?.source;
4985
+ return typeof source == "object" && source !== null && "subagent" in source;
4986
+ }
4987
+ var CODEX_MY_REQUEST = /^## My request[^\n]*:[ \t]*$/gm, CODEX_BROWSER_COMMENT = /^Comment:\n([\s\S]*?)(?=\n\n## User Comment|\n\n#|\nThe next image|$(?![\s\S]))/gm;
4988
+ function codexTypedText(raw) {
4989
+ let text = raw, requests = [...raw.matchAll(CODEX_MY_REQUEST)];
4990
+ if (requests.length) {
4991
+ let last = requests[requests.length - 1];
4992
+ text = raw.slice(last.index + last[0].length);
4993
+ } else raw.trimStart().startsWith("# Browser comments") && (text = [...raw.matchAll(CODEX_BROWSER_COMMENT)].map((m) => m[1]).join(`
4994
+ `));
4995
+ if (!text.trimStart().startsWith("<"))
4996
+ return text.trim() ? text : void 0;
4945
4997
  }
4946
4998
  function handleCodexResponseItem(item, usageDate, projectFields, sessionId, filePath, timestamp, acc) {
4947
4999
  if (!item?.type) return;
4948
5000
  let callId = item.call_id, baseKey = callId ? `codex:${item.type}:${callId}` : `codex:${filePath}:${usageDate}:${item.type}:${item.name ?? ""}:${item.arguments ?? ""}`;
4949
- if (item.type === "message") {
4950
- item.role === "user" && hasCodexUserMessageContent(item.content) && addUserMessage(acc, {
4951
- provider: "openai",
4952
- product: "codex",
4953
- usageDate,
4954
- projectFields,
4955
- sessionId,
4956
- timestamp,
4957
- content: extractCodexMessageText(item.content),
4958
- fallbackKey: `${filePath}:${usageDate}:${sessionId}:${JSON.stringify(item.content ?? "")}`
4959
- });
4960
- return;
4961
- }
4962
- if (item.type === "function_call") {
4963
- let name = item.name ?? "unknown", args = parseJsonObject(item.arguments), kind = name === "spawn_agent" ? "agent_call" : "function_call";
4964
- addActivity(acc, {
4965
- usageDate,
4966
- provider: "openai",
4967
- product: "codex",
4968
- projectFields,
4969
- sessionId,
4970
- kind,
4971
- name: kind === "agent_call" ? stringValue3(args.agent_type) ?? name : name,
4972
- confidence: "exact",
4973
- dedupeKey: baseKey
4974
- });
4975
- for (let skillName of extractSkillProxyNames(item.arguments))
5001
+ if (item.type !== "message") {
5002
+ if (item.type === "function_call") {
5003
+ let name = item.name ?? "unknown", args = parseJsonObject(item.arguments), kind = name === "spawn_agent" ? "agent_call" : "function_call";
4976
5004
  addActivity(acc, {
4977
5005
  usageDate,
4978
5006
  provider: "openai",
4979
5007
  product: "codex",
4980
5008
  projectFields,
4981
5009
  sessionId,
4982
- kind: "skill_proxy",
4983
- name: skillName,
4984
- confidence: "proxy",
4985
- dedupeKey: `${baseKey}:skill:${skillName}`
5010
+ kind,
5011
+ name: kind === "agent_call" ? stringValue3(args.agent_type) ?? name : name,
5012
+ confidence: "exact",
5013
+ dedupeKey: baseKey
4986
5014
  });
4987
- return;
4988
- }
4989
- if (item.type === "custom_tool_call") {
4990
- addActivity(acc, {
5015
+ for (let skillName of extractSkillProxyNames(item.arguments))
5016
+ addActivity(acc, {
5017
+ usageDate,
5018
+ provider: "openai",
5019
+ product: "codex",
5020
+ projectFields,
5021
+ sessionId,
5022
+ kind: "skill_proxy",
5023
+ name: skillName,
5024
+ confidence: "proxy",
5025
+ dedupeKey: `${baseKey}:skill:${skillName}`
5026
+ });
5027
+ return;
5028
+ }
5029
+ if (item.type === "custom_tool_call") {
5030
+ addActivity(acc, {
5031
+ usageDate,
5032
+ provider: "openai",
5033
+ product: "codex",
5034
+ projectFields,
5035
+ sessionId,
5036
+ kind: "custom_tool_call",
5037
+ name: item.name ?? "unknown",
5038
+ confidence: "exact",
5039
+ dedupeKey: baseKey
5040
+ });
5041
+ return;
5042
+ }
5043
+ (item.type === "web_search_call" || item.type === "tool_search_call" || item.type === "image_generation_call") && addActivity(acc, {
4991
5044
  usageDate,
4992
5045
  provider: "openai",
4993
5046
  product: "codex",
4994
5047
  projectFields,
4995
5048
  sessionId,
4996
- kind: "custom_tool_call",
4997
- name: item.name ?? "unknown",
5049
+ kind: item.type === "web_search_call" ? "web_search" : item.type === "tool_search_call" ? "tool_search" : "image_generation",
5050
+ name: item.name ?? item.type,
4998
5051
  confidence: "exact",
4999
5052
  dedupeKey: baseKey
5000
5053
  });
5001
- return;
5002
5054
  }
5003
- (item.type === "web_search_call" || item.type === "tool_search_call" || item.type === "image_generation_call") && addActivity(acc, {
5004
- usageDate,
5005
- provider: "openai",
5006
- product: "codex",
5007
- projectFields,
5008
- sessionId,
5009
- kind: item.type === "web_search_call" ? "web_search" : item.type === "tool_search_call" ? "tool_search" : "image_generation",
5010
- name: item.name ?? item.type,
5011
- confidence: "exact",
5012
- dedupeKey: baseKey
5013
- });
5014
5055
  }
5015
5056
  function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath, acc) {
5016
- let payloadType = record.payload?.type;
5017
- if (payloadType === "user_message") {
5018
- addUserMessage(acc, {
5019
- provider: "openai",
5020
- product: "codex",
5021
- usageDate,
5022
- projectFields,
5023
- sessionId,
5024
- timestamp: record.timestamp ?? "",
5025
- content: stringValue3(record.payload?.message),
5026
- fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
5027
- });
5028
- return;
5029
- }
5030
- 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;
5057
+ let payloadType = record.payload?.type, 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;
5031
5058
  if (!kind) return;
5032
5059
  let callId = stringValue3(record.payload?.call_id);
5033
5060
  addActivity(acc, {
@@ -5059,7 +5086,8 @@ async function scanClaudeActivity(targetDates, options) {
5059
5086
  for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
5060
5087
  }
5061
5088
  }
5062
- return acc.stats.filesScanned = fileJobs.length, await runWithConcurrency(fileJobs, FILE_CONCURRENCY3, async (job) => {
5089
+ let recentJobs = await keepRecentFiles(fileJobs, targetDates, (job) => job.filePath);
5090
+ return acc.stats.filesScanned = recentJobs.length, await runWithConcurrency(recentJobs, FILE_CONCURRENCY3, async (job) => {
5063
5091
  await processClaudeFile(job.filePath, job.projectFields, acc);
5064
5092
  }), finalizeActivity(acc);
5065
5093
  }
@@ -5090,18 +5118,22 @@ async function processClaudeFile(filePath, fallbackFields, acc) {
5090
5118
  if (!acceptsDate(acc, usageDate)) continue;
5091
5119
  let sessionId = record.sessionId ?? fallbackSessionId;
5092
5120
  acc.stats.sessions.add(`claude:${sessionId}`);
5093
- let projectFields = record.cwd ? resolveProjectFields(record.cwd, acc.projectAliases) : fallbackFields;
5094
- isClaudeUserMessage(record) && addUserMessage(acc, {
5095
- provider: "anthropic",
5096
- product: "claude-code",
5097
- usageDate,
5098
- projectFields,
5099
- sessionId,
5100
- timestamp: record.timestamp ?? "",
5101
- content: extractClaudeMessageText(record.message?.content),
5102
- fallbackKey: `${filePath}:${usageDate}:${sessionId}:user:${record.timestamp ?? ""}`,
5103
- id: record.uuid
5104
- });
5121
+ let projectFields = record.cwd ? resolveProjectFields(record.cwd, acc.projectAliases) : fallbackFields, prompt2 = claudeHumanPrompt(record);
5122
+ if (prompt2) {
5123
+ let typed = claudeTypedText(prompt2.text);
5124
+ typed !== void 0 && addUserMessage(acc, {
5125
+ provider: "anthropic",
5126
+ product: "claude-code",
5127
+ usageDate,
5128
+ projectFields,
5129
+ sessionId,
5130
+ timestamp: record.timestamp ?? "",
5131
+ content: prompt2.text,
5132
+ chars: countChars(typed),
5133
+ fallbackKey: `${filePath}:${usageDate}:${sessionId}:user:${record.timestamp ?? ""}`,
5134
+ id: prompt2.id
5135
+ });
5136
+ }
5105
5137
  let blocks = Array.isArray(record.message?.content) ? record.message.content : [];
5106
5138
  for (let block of blocks) {
5107
5139
  if (block?.type !== "tool_use") continue;
@@ -5143,6 +5175,7 @@ function finalizeActivity(acc) {
5143
5175
  };
5144
5176
  }
5145
5177
  function addActivity(acc, input) {
5178
+ let amount = input.amount ?? 1;
5146
5179
  if (acc.seen.has(input.dedupeKey)) return;
5147
5180
  acc.seen.add(input.dedupeKey);
5148
5181
  let source = `${input.provider}/${input.product}`, key = [
@@ -5154,7 +5187,7 @@ function addActivity(acc, input) {
5154
5187
  input.confidence
5155
5188
  ].join("|"), existing = acc.items.get(key);
5156
5189
  if (existing) {
5157
- existing.count += 1;
5190
+ existing.count += amount;
5158
5191
  return;
5159
5192
  }
5160
5193
  acc.items.set(key, {
@@ -5167,7 +5200,7 @@ function addActivity(acc, input) {
5167
5200
  projectAlias: input.projectFields.projectAlias,
5168
5201
  kind: input.kind,
5169
5202
  name: input.name,
5170
- count: 1,
5203
+ count: amount,
5171
5204
  confidence: input.confidence
5172
5205
  });
5173
5206
  }
@@ -5183,8 +5216,30 @@ function addUserMessage(acc, input) {
5183
5216
  name: "user_message",
5184
5217
  confidence: "exact",
5185
5218
  dedupeKey: `activity:${key}`
5219
+ }), input.chars > 0 && addActivity(acc, {
5220
+ usageDate: input.usageDate,
5221
+ provider: input.provider,
5222
+ product: input.product,
5223
+ projectFields: input.projectFields,
5224
+ sessionId: input.sessionId,
5225
+ kind: "user_message_chars",
5226
+ name: "user_message_chars",
5227
+ confidence: "exact",
5228
+ dedupeKey: `activity:${key}:chars`,
5229
+ amount: input.chars
5186
5230
  }));
5187
5231
  }
5232
+ async function keepRecentFiles(items, targetDates, pathOf) {
5233
+ if (!targetDates?.size) return items;
5234
+ let earliest = [...targetDates].sort()[0], cutoff = Date.parse(`${earliest}T00:00:00Z`) - 1440 * 60 * 1e3, keep = await Promise.all(items.map(async (item) => {
5235
+ try {
5236
+ return (await stat4(pathOf(item))).mtimeMs >= cutoff;
5237
+ } catch {
5238
+ return !1;
5239
+ }
5240
+ }));
5241
+ return items.filter((_, i) => keep[i]);
5242
+ }
5188
5243
  function acceptsDate(acc, usageDate) {
5189
5244
  return !acc.targetDates || acc.targetDates.has(usageDate);
5190
5245
  }
@@ -5193,10 +5248,10 @@ async function collectCodexSessionFiles2(baseDir) {
5193
5248
  try {
5194
5249
  let files = await readdir7(join17(baseDir, "archived_sessions"));
5195
5250
  for (let file of files)
5196
- file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
5251
+ isCodexSessionFile(file) && paths.push(join17(baseDir, "archived_sessions", file));
5197
5252
  } catch {
5198
5253
  }
5199
- return await walkJsonl(join17(baseDir, "sessions"), paths), paths;
5254
+ return await walkJsonl(join17(baseDir, "sessions"), paths, isCodexSessionFile), paths;
5200
5255
  }
5201
5256
  function getClaudeProjectDirs(configured) {
5202
5257
  if (configured?.length) return configured;
@@ -5209,7 +5264,10 @@ function getClaudeProjectDirs(configured) {
5209
5264
  join17(home, ".claude", "projects")
5210
5265
  ];
5211
5266
  }
5212
- async function walkJsonl(dir, result) {
5267
+ function isCodexSessionFile(name) {
5268
+ return name.endsWith(".jsonl") || name.endsWith(".jsonl.zst");
5269
+ }
5270
+ async function walkJsonl(dir, result, accept = (name) => name.endsWith(".jsonl")) {
5213
5271
  let entries;
5214
5272
  try {
5215
5273
  entries = await readdir7(dir, { withFileTypes: !0 });
@@ -5218,7 +5276,7 @@ async function walkJsonl(dir, result) {
5218
5276
  }
5219
5277
  for (let entry of entries) {
5220
5278
  let fullPath = join17(dir, entry.name);
5221
- entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
5279
+ entry.isDirectory() ? await walkJsonl(fullPath, result, accept) : accept(entry.name) && result.push(fullPath);
5222
5280
  }
5223
5281
  }
5224
5282
  function resolveClaudeProject(projectPath, aliases2) {
@@ -5235,13 +5293,29 @@ function classifyClaudeTool(name) {
5235
5293
  function getClaudeMetricName(toolName, input) {
5236
5294
  return toolName === "Skill" ? stringValue3(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue3(input?.description) ?? stringValue3(input?.subagent_type) ?? "unknown" : toolName;
5237
5295
  }
5238
- function isClaudeUserMessage(record) {
5239
- if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
5296
+ function claudeHumanPrompt(record) {
5297
+ let attachment = record.attachment;
5298
+ if (attachment?.type === "queued_command")
5299
+ return attachment.origin?.kind !== "human" ? void 0 : { text: extractClaudeMessageText(attachment.prompt) ?? "", id: attachment.source_uuid };
5300
+ if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.isSidechain || record.isCompactSummary || record.isVisibleInTranscriptOnly) return;
5301
+ if (record.origin) {
5302
+ if (record.origin.kind !== "human") return;
5303
+ } else if (record.promptSource === "sdk" || record.promptSource === "system")
5304
+ return;
5305
+ if (record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return;
5240
5306
  let content = record.message.content;
5241
- 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" && stringValue3(block.text));
5307
+ if (Array.isArray(content) && content.some((block) => block?.type === "tool_result")) return;
5308
+ let text = extractClaudeMessageText(content);
5309
+ return text ? { text, id: record.uuid } : void 0;
5242
5310
  }
5243
- function hasCodexUserMessageContent(content) {
5244
- 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");
5311
+ var CLAUDE_REMINDER = /<system-reminder>[\s\S]*?<\/system-reminder>/g, CLAUDE_PASTE = /<pasted_content[^>]*>[\s\S]*?<\/pasted_content[^>]*>/g, CLAUDE_PLACEHOLDER = /\[(?:Pasted text #\d+(?: \+\d+ lines)?|Image #\d+)\]/g;
5312
+ function claudeTypedText(raw) {
5313
+ let text = raw.replace(CLAUDE_REMINDER, "").replace(CLAUDE_PASTE, ""), trimmed = text.trimStart();
5314
+ if (!(!trimmed || trimmed.startsWith("<") || trimmed.startsWith("Caveat:") || trimmed.startsWith("[Request interrupted")))
5315
+ return text.replace(CLAUDE_PLACEHOLDER, "");
5316
+ }
5317
+ function countChars(text) {
5318
+ return [...text.replace(/\s+/g, "")].length;
5245
5319
  }
5246
5320
  function extractCodexMessageText(content) {
5247
5321
  return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue3(block.text)).filter(Boolean).join(`
@@ -5299,10 +5373,13 @@ function summarize(items, keyFn, labelFn, limit) {
5299
5373
  return limit ? rows.slice(0, limit) : rows;
5300
5374
  }
5301
5375
  function sumByConfidence(items, confidence) {
5302
- return items.reduce((sum, item) => sum + (item.kind !== "user_message" && item.confidence === confidence ? item.count : 0), 0);
5376
+ return items.reduce((sum, item) => sum + (!isUserMessageKind(item.kind) && item.confidence === confidence ? item.count : 0), 0);
5377
+ }
5378
+ function sumKind(items, kind) {
5379
+ return items.reduce((sum, item) => sum + (item.kind === kind ? item.count : 0), 0);
5303
5380
  }
5304
- function sumUserMessages(items) {
5305
- return items.reduce((sum, item) => sum + (item.kind === "user_message" ? item.count : 0), 0);
5381
+ function isUserMessageKind(kind) {
5382
+ return kind === "user_message" || kind === "user_message_chars";
5306
5383
  }
5307
5384
  function isToolLikeKind(kind) {
5308
5385
  return kind === "function_call" || kind === "custom_tool_call" || kind === "tool_call" || kind === "web_search" || kind === "tool_search" || kind === "image_generation" || kind === "mcp_tool_call";
@@ -5311,6 +5388,8 @@ function labelKind(kind) {
5311
5388
  switch (kind) {
5312
5389
  case "user_message":
5313
5390
  return "User Message";
5391
+ case "user_message_chars":
5392
+ return "User Message Chars";
5314
5393
  case "function_call":
5315
5394
  return "Function Call";
5316
5395
  case "custom_tool_call":
@@ -5596,7 +5675,7 @@ async function requestJson(url, init) {
5596
5675
 
5597
5676
  // src/schedule.ts
5598
5677
  import { realpathSync } from "node:fs";
5599
- import { mkdir as mkdir2, readFile as readFile16, stat as stat4, unlink, writeFile as writeFile2 } from "node:fs/promises";
5678
+ import { mkdir as mkdir2, readFile as readFile16, stat as stat5, unlink, writeFile as writeFile2 } from "node:fs/promises";
5600
5679
  import { execFile as execFile2 } from "node:child_process";
5601
5680
  import { promisify } from "node:util";
5602
5681
  import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
@@ -5697,7 +5776,7 @@ async function disableLaunchd() {
5697
5776
  }
5698
5777
  async function getLaunchdStatus() {
5699
5778
  try {
5700
- await stat4(PLIST_PATH);
5779
+ await stat5(PLIST_PATH);
5701
5780
  } catch {
5702
5781
  return { enabled: !1 };
5703
5782
  }
@@ -5807,7 +5886,7 @@ function escapeXml(value) {
5807
5886
  }
5808
5887
 
5809
5888
  // src/doctor.ts
5810
- import { readdir as readdir8, stat as stat5 } from "node:fs/promises";
5889
+ import { readdir as readdir8, stat as stat6 } from "node:fs/promises";
5811
5890
  import { homedir as homedir19 } from "node:os";
5812
5891
  import { join as join20 } from "node:path";
5813
5892
  var msgs = {
@@ -5886,7 +5965,7 @@ async function countFiles(dir, exts, cap = 1e3) {
5886
5965
  async function runDoctor(lang = "zh") {
5887
5966
  let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
5888
5967
  try {
5889
- await stat5(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
5968
+ await stat6(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
5890
5969
  } catch {
5891
5970
  checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
5892
5971
  }
@@ -5933,7 +6012,7 @@ async function runDoctor(lang = "zh") {
5933
6012
  let installed = !1, installedDirs = 0, n = 0;
5934
6013
  for (let dir of tool.dirs)
5935
6014
  try {
5936
- await stat5(dir), installed = !0, installedDirs++, n += await countFiles(dir, tool.exts);
6015
+ await stat6(dir), installed = !0, installedDirs++, n += await countFiles(dir, tool.exts);
5937
6016
  } catch {
5938
6017
  }
5939
6018
  if (!installed) {
@@ -5952,7 +6031,7 @@ async function runDoctor(lang = "zh") {
5952
6031
  }), openCodeLegacyCount = await countFiles(openCodeSources.legacyDir, [".json"]), openCodeInstalled = openCodeSources.dbPaths.length > 0 || openCodeLegacyCount > 0;
5953
6032
  if (!openCodeInstalled)
5954
6033
  try {
5955
- await stat5(openCodeSources.dataDir), openCodeInstalled = !0;
6034
+ await stat6(openCodeSources.dataDir), openCodeInstalled = !0;
5956
6035
  } catch {
5957
6036
  }
5958
6037
  openCodeInstalled ? openCodeSources.dbPaths.length === 0 && openCodeLegacyCount === 0 ? checks.push({ group: g3, name: "OpenCode", status: "warn", message: s.installedNoData }) : openCodeSources.dbPaths.length > 0 && await detectOpenCodeSqliteRuntime() === "unavailable" ? checks.push({
@@ -6441,7 +6520,7 @@ function assertPricingCatalog(value) {
6441
6520
  import { execFile as execFile3 } from "node:child_process";
6442
6521
  import { createHash as createHash2 } from "node:crypto";
6443
6522
  import { existsSync as existsSync2 } from "node:fs";
6444
- import { mkdir as mkdir4, open as open3, readdir as readdir10, rename, stat as stat6, writeFile as writeFile4 } from "node:fs/promises";
6523
+ import { mkdir as mkdir4, open as open3, readdir as readdir10, rename, stat as stat7, writeFile as writeFile4 } from "node:fs/promises";
6445
6524
  import { createServer } from "node:net";
6446
6525
  import { homedir as homedir22 } from "node:os";
6447
6526
  import { join as join23 } from "node:path";
@@ -6762,7 +6841,7 @@ async function findCompletionLogs(dir) {
6762
6841
  if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
6763
6842
  else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
6764
6843
  try {
6765
- files.push({ path, mtimeMs: (await stat6(path)).mtimeMs });
6844
+ files.push({ path, mtimeMs: (await stat7(path)).mtimeMs });
6766
6845
  } catch {
6767
6846
  }
6768
6847
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiusage/cli",
3
- "version": "1.7.14",
3
+ "version": "1.8.1",
4
4
  "description": "Track and sync AI tool token usage across devices.",
5
5
  "license": "MIT",
6
6
  "private": false,