tokenusage-cli 0.4.2 → 0.4.4

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.
@@ -375,8 +375,79 @@ function run(command, args) {
375
375
  execFileSync(command, args, { stdio: "pipe", windowsHide: true });
376
376
  }
377
377
 
378
- function errorText(error) {
379
- return String(error?.message || error).slice(0, 200);
378
+ // `stdio: "pipe"` keeps the child's own output on `error.stderr` / `stdout`,
379
+ // while `error.message` starts with a command echo ("Command failed: schtasks
380
+ // /Create /XML C:\Users\me\..."). Reading the message first buried the real
381
+ // reason — the non-elevated Windows rejection "ERROR: Access is denied."
382
+ // lands on the *second* line and was clipped away. Child output wins; the
383
+ // command echo is the last resort.
384
+ //
385
+ // Windows console tools also write their message in the console codepage, not
386
+ // UTF-8: a zh-CN "schtasks" prints "错误: 拒绝访问。" as GBK bytes, which decode
387
+ // to replacement characters and reached the user as mojibake. decodeStream()
388
+ // retries with the active codepage before giving up on the original text.
389
+ const CONSOLE_CODEPAGE_DECODERS = {
390
+ 932: "shift_jis",
391
+ 936: "gbk",
392
+ 949: "euc-kr",
393
+ 950: "big5",
394
+ };
395
+
396
+ // UTF-8 itself (65001) and the legacy single-byte pages need no decoder here.
397
+ function consoleEncoding(codepage) {
398
+ return CONSOLE_CODEPAGE_DECODERS[codepage] || null;
399
+ }
400
+
401
+ let cachedConsoleDecoder;
402
+
403
+ function consoleDecoder() {
404
+ if (cachedConsoleDecoder !== undefined) return cachedConsoleDecoder;
405
+ cachedConsoleDecoder = null;
406
+ if (process.platform !== "win32") return null;
407
+ try {
408
+ // "Active code page: 936" — digits survive any localisation.
409
+ const output = execFileSync("chcp.com", [], { stdio: "pipe", windowsHide: true })
410
+ .toString("latin1");
411
+ const codepage = Number((output.match(/\d{3,5}/) || [])[0]);
412
+ const encoding = consoleEncoding(codepage);
413
+ if (encoding) cachedConsoleDecoder = new TextDecoder(encoding);
414
+ } catch (_error) {
415
+ cachedConsoleDecoder = null;
416
+ }
417
+ return cachedConsoleDecoder;
418
+ }
419
+
420
+ function decodeStream(value, fallbackDecoder) {
421
+ if (value == null) return "";
422
+ if (typeof value === "string") return value;
423
+ const bytes = Buffer.isBuffer(value) ? value : Buffer.from(value);
424
+ const utf8 = bytes.toString("utf8");
425
+ if (!utf8.includes("\uFFFD")) return utf8;
426
+ const decoder = fallbackDecoder || consoleDecoder();
427
+ if (!decoder) return utf8;
428
+ const decoded = decoder.decode(bytes);
429
+ return decoded.includes("\uFFFD") ? utf8 : decoded;
430
+ }
431
+
432
+ function firstLine(value) {
433
+ return (
434
+ String(value ?? "")
435
+ .split(/\r?\n/)
436
+ .map((part) => part.trim())
437
+ .find(Boolean) ?? ""
438
+ );
439
+ }
440
+
441
+ function clipLine(line, max) {
442
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
443
+ }
444
+
445
+ function errorText(error, max = 200) {
446
+ for (const stream of [error?.stderr, error?.stdout]) {
447
+ const line = firstLine(decodeStream(stream));
448
+ if (line) return clipLine(line, max);
449
+ }
450
+ return clipLine(firstLine(decodeStream(error?.message)), max);
380
451
  }
381
452
 
382
453
  /**
@@ -644,12 +715,7 @@ function deleteAutoSyncSchedule({ home = os.homedir(), binDir, platform = proces
644
715
  // administrator" apart from a genuinely malformed definition. Clip it to one
645
716
  // short line so the summary table stays readable.
646
717
  function scheduleDetailLine(value, max = 100) {
647
- const line =
648
- String(value ?? "")
649
- .split(/\r?\n/)
650
- .map((part) => part.trim())
651
- .find(Boolean) ?? "";
652
- return line.length > max ? `${line.slice(0, max - 1)}…` : line;
718
+ return clipLine(firstLine(value), max);
653
719
  }
654
720
 
655
721
  function formatScheduleRegistration(outcome) {
@@ -725,4 +791,7 @@ module.exports = {
725
791
  formatScheduleRegistration,
726
792
  formatScheduleToggle,
727
793
  formatScheduleDelete,
794
+ consoleEncoding,
795
+ decodeStream,
796
+ errorText,
728
797
  };
@@ -408,9 +408,51 @@ function isWorktreeRef(ref) {
408
408
  return /[\\/](worktrees|subagents)[\\/]/.test(String(ref || ""));
409
409
  }
410
410
 
411
+ const SUBAGENT_DIR = "subagents";
412
+ const WORKTREE_DIR = "worktrees";
413
+ const UUID_SEGMENT = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
414
+
415
+ // Throwaway per-agent checkouts (`<repo>/.claude/worktrees/<id>`) and subagent
416
+ // transcripts (`<session-dir>/subagents/`) belong to the project that owns
417
+ // them, not to the temp name at the tail of the path. Both are artefacts of
418
+ // how a tool lays out its state, so the project key steps up to the real
419
+ // project directory instead of surfacing `agent-<hash>` / `subagents` as a
420
+ // project of its own. Normal cwds and anything without those markers keep the
421
+ // historical basename behavior.
411
422
  function projectKey(cwd, filePath) {
412
- const value = cwd || path.dirname(filePath || "");
413
- return path.basename(String(value).replace(/[\\/]+$/, "")) || "unknown";
423
+ const raw = String(cwd || path.dirname(filePath || "")).replace(/[\\/]+$/, "");
424
+ const segments = raw.split(/[\\/]+/).filter(Boolean);
425
+ if (segments.length === 0) return "unknown";
426
+ return projectSegment(segments) || "unknown";
427
+ }
428
+
429
+ function projectSegment(segments) {
430
+ const tail = segments[segments.length - 1];
431
+
432
+ const worktreeIndex = segments.lastIndexOf(WORKTREE_DIR);
433
+ if (worktreeIndex > 0 && worktreeIndex < segments.length - 1) {
434
+ const owner = segments[worktreeIndex - 1];
435
+ // Repo-local worktrees (`<repo>/.claude/worktrees/<id>`): the owner is the
436
+ // repo above the agent dot-directory.
437
+ if (owner === ".claude") {
438
+ const repo = segments[worktreeIndex - 2];
439
+ if (repo && !repo.startsWith(".")) return repo;
440
+ }
441
+ // `<project>/worktrees/<name>`: the project directly above the marker.
442
+ // A dot-directory there (e.g. `~/.codex/worktrees/<id>`) has no project
443
+ // above it, so keep the old tail behavior instead of guessing.
444
+ if (!owner.startsWith(".")) return owner;
445
+ }
446
+
447
+ if (tail === SUBAGENT_DIR) {
448
+ // `<project>/<session-id>/subagents`: skip the session container too.
449
+ let index = segments.length - 2;
450
+ while (index >= 0 && UUID_SEGMENT.test(segments[index])) index -= 1;
451
+ const project = index >= 0 ? segments[index] : null;
452
+ if (project && !project.startsWith(".")) return project;
453
+ }
454
+
455
+ return tail;
414
456
  }
415
457
 
416
458
  function extractClaudePrompt(obj) {
@@ -1996,6 +2038,12 @@ function scanQoderSessionFile(filePath, source) {
1996
2038
  if (typeof cwd === "string" && cwd.trim()) projectRef = cwd.trim();
1997
2039
  continue;
1998
2040
  }
2041
+ // Subagent transcripts under `<session>/subagents/` carry no workspace
2042
+ // record, but each record still names the workspace cwd — inherit it so the
2043
+ // project key stays the real project instead of the "subagents" directory.
2044
+ if (!projectRef && typeof record?.cwd === "string" && record.cwd.trim()) {
2045
+ projectRef = record.cwd.trim();
2046
+ }
1999
2047
  if (record?.type !== "assistant" || record?.message?.role !== "assistant") continue;
2000
2048
  const usage = record.message.usage;
2001
2049
  if (!usage || typeof usage !== "object") continue;
@@ -3128,6 +3176,8 @@ module.exports = {
3128
3176
  scanZcodeSessions,
3129
3177
  scanOpencodeSessions,
3130
3178
  scanKimiSessions,
3179
+ scanQoderSessionFile,
3180
+ projectKey,
3131
3181
  buildSessionAnalytics,
3132
3182
  summarizeSessions,
3133
3183
  listSessionsForBrowser,
@@ -56,7 +56,10 @@ function snapshotKey(bytes) {
56
56
  if (Object.hasOwn(row, "kind") || typeof row.hour_start !== "string" || !Number.isFinite(Date.parse(row.hour_start))) return null;
57
57
  const source = (typeof row.source === "string" ? row.source.trim().toLowerCase() : "") || "codex";
58
58
  const model = (typeof row.model === "string" ? row.model.trim() : "") || "unknown";
59
- return { key: JSON.stringify(["hourly", source, model, row.hour_start]), verifiedMs: null };
59
+ // contract v2 (2026-11-03): project_key joins the last-wins identity;
60
+ // rows without it collapse onto the unattributed ('') bucket as before.
61
+ const project = typeof row.project_key === "string" ? row.project_key.trim() : "";
62
+ return { key: JSON.stringify(["hourly", source, model, project, row.hour_start]), verifiedMs: null };
60
63
  }
61
64
 
62
65
  // Caller holds sync.lock. Only rewrite pending snapshots; uploaded history and